text:
package edu.utah.ece.async.sboldesigner.sbol.editor.dialog;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

import org.sbolstandard.core2.Collection;
import org.sbolstandard.core2.CombinatorialDerivation;
import org.sbolstandard.core2.ComponentDefinition;
import org.sbolstandard.core2.Identified;
import org.sbolstandard.core2.OperatorType;
import org.sbolstandard.core2.SBOLDocument;
import org.sbolstandard.core2.SBOLValidationException;
import org.sbolstandard.core2.StrategyType;
import org.sbolstandard.core2.TopLevel;
import org.sbolstandard.core2.VariableComponent;

import edu.utah.ece.async.sboldesigner.sbol.CharSequenceUtil;
import edu.utah.ece.async.sboldesigner.sbol.SBOLUtils;
import edu.utah.ece.async.sboldesigner.sbol.editor.Parts;
import edu.utah.ece.async.sboldesigner.swing.AbstractListTableModel;
import edu.utah.ece.async.sboldesigner.swing.FormBuilder;

public class VariantEditor extends JDialog implements ActionListener {
	private static final String TITLE = "Combinatorial Design Variants: ";

	private ComponentDefinition derivationCD;
	private ComponentDefinition variableCD;
	private SBOLDocument design;
	private Component parent;
	private final JComboBox<OperatorType> operatorSelection = new JComboBox<>(OperatorType.values());
	private final JComboBox<Strategy> strategySelection = new JComboBox<>(getStrategies());
	private final JButton addButton = new JButton("Add Variant");
	private final JButton removeButton = new JButton("Remove");
	private final JButton newButton = new JButton("Add new Combinatorial Derivation");
	private final JButton saveButton = new JButton("Save");
	private final JTextField displayId = new JTextField();
	private final JTextField name = new JTextField();
	private final JTextField description = new JTextField();
	private JTable table;
	private JLabel tableLabel;
	private JScrollPane scroller;

	private class Strategy {
		StrategyType type;

		public Strategy(StrategyType type) {
			this.type = type;
		}

		@Override
		public String toString() {
			if (type == null) {
				return "None";
			}

			return type.toString();
		}
	}

	private Strategy[] getStrategies() {
		StrategyType[] values = StrategyType.values();

		Strategy[] a = new Strategy[values.length + 1];
		a[0] = new Strategy(null);

		for (int i = 0; i < values.length; i++) {
			a[i + 1] = new Strategy(values[i]);
		}

		return a;
	}

	private static String title(Identified comp) {
		String title = comp.getDisplayId();
		if (title == null) {
			title = comp.getName();
		}
		if (title == null) {
			URI uri = comp.getIdentity();
			title = (uri == null) ? null : uri.toString();
		}

		return (title == null) ? "" : CharSequenceUtil.shorten(title, 20).toString();
	}

	public VariantEditor(Component parent, ComponentDefinition derivationCD, ComponentDefinition variableCD,
			SBOLDocument design) {
		super(JOptionPane.getFrameForComponent(parent), TITLE + title(variableCD), true);
		this.derivationCD = derivationCD;
		this.variableCD = variableCD;
		this.parent = parent;
		this.design = design;

		try {
			CombinatorialDerivation derivation = getCombinatorialDerivation(derivationCD);
			if (derivation == null) {
				setVisible(false);
				return;
			}

			operatorSelection.setSelectedItem(getOperator());
			operatorSelection.addActionListener(this);

			strategySelection
					.setSelectedIndex(getStrategy() == null ? 0 : getStrategy() == StrategyType.ENUMERATE ? 1 : 2);
			strategySelection.addActionListener(this);

			displayId.setText(derivation.getDisplayId());
			name.setText(derivation.getName());
			description.setText(derivation.getDescription());
			displayId.setEditable(false);

			FormBuilder builder = new FormBuilder();
			builder.add("Variant operator", operatorSelection);
			builder.add("Derivation strategy", strategySelection);
			builder.add("Derivation display ID", displayId);
			builder.add("Derivation name", name);
			builder.add("Derivation description", description);
			JPanel optionPane = builder.build();

			addButton.addActionListener(this);
			addButton.setEnabled(true);
			removeButton.addActionListener(this);
			removeButton.setEnabled(false);
			newButton.addActionListener(this);
			newButton.setEnabled(true);
			saveButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
					JComponent.WHEN_IN_FOCUSED_WINDOW);
			saveButton.addActionListener(this);
			getRootPane().setDefaultButton(saveButton);

			JPanel buttonPane = new JPanel();
			buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
			buttonPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
			buttonPane.add(addButton);
			buttonPane.add(removeButton);
			buttonPane.add(newButton);
			buttonPane.add(Box.createHorizontalStrut(100));
			buttonPane.add(Box.createHorizontalGlue());
			buttonPane.add(saveButton);

			JPanel tablePane = initMainPanel();

			Container contentPane = getContentPane();
			contentPane.add(optionPane, BorderLayout.PAGE_START);
			contentPane.add(tablePane, BorderLayout.CENTER);
			contentPane.add(buttonPane, BorderLayout.PAGE_END);
			((JComponent) contentPane).setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

			pack();
			setLocationRelativeTo(parent);
			this.setVisible(true);
		} catch (SBOLValidationException e) {
			e.printStackTrace();
		}
	}

	private StrategyType getStrategy() throws SBOLValidationException {
		CombinatorialDerivation derivation = getCombinatorialDerivation(derivationCD);
		if (derivation == null || !derivation.isSetStrategy()) {
			return null;
		}

		return derivation.getStrategy();
	}

	private OperatorType getOperator() throws SBOLValidationException {
		VariableComponent variable = getVariableComponent();
		if (variable == null) {
			return OperatorType.ONE;
		}

		return variable.getOperator();
	}

	protected JPanel initMainPanel() throws SBOLValidationException {
		//ComponentDefinitionTableModel tableModel = new ComponentDefinitionTableModel(getVariants());
		TopLevelTableModel tableModel = new TopLevelTableModel(getVariantsCollectionsAndDerivations());
		JPanel panel = createTablePanel(tableModel, "Variant count (" + tableModel.getRowCount() + ")");

		table = (JTable) panel.getClientProperty("table");
		tableLabel = (JLabel) panel.getClientProperty("label");
		scroller = (JScrollPane) panel.getClientProperty("scroller");

		return panel;
	}

	protected JPanel createTablePanel(AbstractListTableModel<?> tableModel, String title) {
		final JTable table = new JTable(tableModel);
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
			@Override
			public void valueChanged(ListSelectionEvent event) {
				removeButton.setEnabled(table.getSelectedRow() >= 0);
			}
		});

		setWidthAsPercentages(table, tableModel.getWidths());

		TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(tableModel);
		table.setRowSorter(sorter);

		table.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				handleTableClick(e);
			}
		});

		JScrollPane tableScroller = new JScrollPane(table);
		tableScroller.setPreferredSize(new Dimension(850, 200));
		tableScroller.setAlignmentX(LEFT_ALIGNMENT);

		JLabel tableLabel = new JLabel(title);
		tableLabel.setLabelFor(table);

		JPanel tablePane = new JPanel();
		tablePane.setLayout(new BoxLayout(tablePane, BoxLayout.PAGE_AXIS));
		tablePane.add(tableLabel);
		tablePane.add(Box.createRigidArea(new Dimension(0, 5)));
		tablePane.add(tableScroller);

		tablePane.putClientProperty("table", table);
		tablePane.putClientProperty("scroller", tableScroller);
		tablePane.putClientProperty("label", tableLabel);

		return tablePane;
	}

	protected static void setWidthAsPercentages(JTable table, double... percentages) {
		final double factor = 10000;

		TableColumnModel model = table.getColumnModel();
		for (int columnIndex = 0; columnIndex < percentages.length; columnIndex++) {
			TableColumn column = model.getColumn(columnIndex);
			column.setPreferredWidth((int) (percentages[columnIndex] * factor));
		}
	}

	private void handleTableClick(MouseEvent e) {
		if (e.getClickCount() == 2 && table.getSelectedRow() >= 0) {
			int row = table.convertRowIndexToModel(table.getSelectedRow());
			ComponentDefinition variant = ((ComponentDefinitionTableModel) table.getModel()).getElement(row);

			try {
				Desktop.getDesktop().browse(variant.getIdentity());
			} catch (IOException e1) {
				MessageDialog.showMessage(parent, "The URI could not be opened: ", e1.getMessage());
			}
		}
	}

	private CombinatorialDerivation chosenDerivation = null;

	private CombinatorialDerivation getCombinatorialDerivation(ComponentDefinition derivationCD)
			throws SBOLValidationException {
		if (chosenDerivation == null) {
			chosenDerivation = CombinatorialDerivationInputDialog.pickCombinatorialDerivation(parent, design, derivationCD);
			//chosenDerivation = new ComboDerivDesign();
			if (chosenDerivation == null) {
				String id = JOptionPane.showInputDialog("What would you like to call this combinatorial derivation?",
						derivationCD.isSetDisplayId() ? derivationCD.getDisplayId() + "_CombinatorialDerivation" : "");
				if (id == null) {
					return null;
				}
				chosenDerivation = createCombinatorialDerivation(derivationCD, id);
			}
		}

		return chosenDerivation;
	}

	private VariableComponent getVariableComponent(OperatorType operator) throws Exception {
		CombinatorialDerivation derivation = getCombinatorialDerivation(derivationCD);
		if (derivation == null) {
			return null;
		}

		org.sbolstandard.core2.Component link = getComponentLink(derivationCD, variableCD);
		if (link == null) {
			throw new Exception("derivationCD does not have a component to variableCD");
		}

		VariableComponent variable = getVariableComponent(derivation, link);
		if (variable == null) {
			variable = createVariableComponent(derivation, operator, link);
		}

		return variable;
	}

	private VariableComponent getVariableComponent() throws SBOLValidationException {
		CombinatorialDerivation derivation = getCombinatorialDerivation(derivationCD);
		if (derivation == null) {
			return null;
		}

		org.sbolstandard.core2.Component link = getComponentLink(derivationCD, variableCD);
		if (link == null) {
			return null;
		}

		VariableComponent variable = getVariableComponent(derivation, link);
		if (variable == null) {
			return null;
		}

		return variable;
	}

	private VariableComponent getVariableComponent(CombinatorialDerivation derivation,
			org.sbolstandard.core2.Component link) {
		for (VariableComponent variable : derivation.getVariableComponents()) {
			if (variable.getVariable().equals(link)) {
				return variable;
			}
		}

		return null;
	}

	private org.sbolstandard.core2.Component getComponentLink(ComponentDefinition derivationCD,
			ComponentDefinition variableCD) {
		for (org.sbolstandard.core2.Component link : derivationCD.getComponents()) {
			if (link.getDefinitionURI().equals(variableCD.getIdentity())) {
				return link;
			}
		}

		return null;
	}

	private List<TopLevel> getVariantsCollectionsAndDerivations() throws SBOLValidationException {
		ArrayList<TopLevel> variants = new ArrayList<>();

		VariableComponent variable = getVariableComponent();
		if (variable == null) {
			return variants;
		}

		//Get variants
		for (URI cd : variable.getVariantURIs()) {
			variants.add(design.getComponentDefinition(cd));
		}

		//Get variantCollections
		for (URI col : variable.getVariantCollectionURIs()) {
			variants.add(design.getCollection(col));
		}

		//Get combinatoralDerivations
		for (URI der : variable.getVariantDerivationURIs()) {
			variants.add(design.getCombinatorialDerivation(der));
		}

		return variants;
	}

	private void addVariant(ComponentDefinition variant) throws Exception {
		VariableComponent variable = getVariableComponent((OperatorType) operatorSelection.getSelectedItem());
		variable.addVariant(variant.getIdentity());
	}

	private void addCollection(Collection collection) throws Exception {
		VariableComponent variable = getVariableComponent((OperatorType) operatorSelection.getSelectedItem());
		variable.addVariantCollection(collection.getIdentity());
	}

	private void addDerivation(CombinatorialDerivation derivation) throws Exception {
		VariableComponent variable = getVariableComponent((OperatorType) operatorSelection.getSelectedItem());
		variable.addVariantDerivation(derivation.getIdentity());
	}

	private VariableComponent createVariableComponent(CombinatorialDerivation derivation, OperatorType operator,
			org.sbolstandard.core2.Component link) throws SBOLValidationException {
		String uniqueId = SBOLUtils.getUniqueDisplayId(null, derivation, link.getDisplayId() + "_VariableComponent",
				null, "VariableComponent", design);
		return derivation.createVariableComponent(uniqueId, operator, link.getIdentity());
	}

	private CombinatorialDerivation createCombinatorialDerivation(ComponentDefinition derivationCD, String displayId)
			throws SBOLValidationException {
		String uniqueId = SBOLUtils.getUniqueDisplayId(null, null, displayId, derivationCD.getVersion(),
				"CombinatorialDerivation", design);
		CombinatorialDerivation derivation = design.createCombinatorialDerivation(uniqueId, "1",
				derivationCD.getIdentity());

		StrategyType strategy = ((Strategy) strategySelection.getSelectedItem()).type;
		if (strategy != null) {
			derivation.setStrategy(strategy);
		}

		addAsNestedDerivation(derivationCD, derivation);
		addNestedDerivations(variableCD);

		this.displayId.setText(displayId);

		chosenDerivation = derivation;

		return derivation;
	}

	private void addAsNestedDerivation(ComponentDefinition derivationCD, CombinatorialDerivation derivation)
			throws SBOLValidationException {
		for (ComponentDefinition parentCD : design.getComponentDefinitions()) {
			for (org.sbolstandard.core2.Component link : parentCD.getComponents()) {
				if (link.getDefinition().equals(derivationCD)) {
					CombinatorialDerivation parentDerivation = getCombinatorialDerivation(parentCD);

					if (parentDerivation != null) {
						VariableComponent variable = getVariableComponent(parentDerivation, link);

						if (variable == null) {
							variable = createVariableComponent(parentDerivation, OperatorType.ONE, link);
						}

						if (!variable.getVariantDerivations().contains(derivation)) {
							variable.addVariantDerivation(derivation.getIdentity());
						}
					}
				}
			}
		}
	}

	private void addNestedDerivations(ComponentDefinition variableCD) throws SBOLValidationException {
		VariableComponent variable = getVariableComponent();
		if (variable == null) {
			return;
		}

		for (CombinatorialDerivation childDerivation : design.getCombinatorialDerivations()) {
			if (childDerivation.getTemplate().equals(variableCD)
					&& !variable.getVariantDerivations().contains(childDerivation)) {
				variable.addVariantDerivation(childDerivation.getIdentity());
			}
		}
	}

	private void removeVariant(TopLevel top) throws Exception {
		VariableComponent variable = getVariableComponent();
		if (variable == null) {
			return;
		}
		if(top instanceof ComponentDefinition)
		{
			ComponentDefinition variant = (ComponentDefinition) top;
			variable.removeVariant(variant);

			// TODO: pull into a function and call on all three types of removes
			if (variable.getVariants().isEmpty()) { // TODO: should check variantCollections / variantDerivations
				// TODO: this call should not create when it cannot find
				// also need to see why it cannot find it
				CombinatorialDerivation derivation = getCombinatorialDerivation(derivationCD);
				if (derivation == null) {
					return;
				}

				derivation.removeVariableComponent(variable);

//				if (derivation.getVariableComponents().isEmpty()) {
//					design.removeCombinatorialDerivation(derivation);
//					chosenDerivation = null;
//				}
			}
		}else if (top instanceof CombinatorialDerivation)
		{
			variable.removeVariantDerivation((CombinatorialDerivation)top);
			// TODO: remove variableComponent if last variant
		}else if(top instanceof Collection)
		{
			variable.removeVariantCollection((Collection) top);
			// TODO: remove variableComponent if last variant
		}

	}

	@Override
	public void actionPerformed(ActionEvent e) {
		try {
			if (e.getSource() == operatorSelection) {
				setOperator((OperatorType) operatorSelection.getSelectedItem());
				return;
			}

			if (e.getSource() == strategySelection) {
				setStrategy(((Strategy) strategySelection.getSelectedItem()).type);
				return;
			}

			if (e.getSource() == saveButton) {
				if (chosenDerivation != null) {
					if (!name.getText().equals("")) {
						chosenDerivation.setName(name.getText());
					}
					if (!description.getText().equals("")) {
						chosenDerivation.setDescription(description.getText());
					}
				}

				setVisible(false);
				return;
			}

			if (e.getSource() == addButton) {
				ComponentDefinitionBox root = new ComponentDefinitionBox();
				RegistryInputDialog dialog = new RegistryInputDialog(parent, root, Parts.forIdentified(variableCD),
						SBOLUtils.Types.DNA, null, null);
				dialog.allowCollectionSelection();
				dialog.setObjectType("Variant");
				SBOLDocument selection = dialog.getInput();
				if (selection == null) {
					return;
				}
				URI selectedURI = dialog.getSelectedURI();

				TopLevel selectedTopLevel = selection.getTopLevel(selectedURI);
				SBOLUtils.insertTopLevels(selection, design);
				Collection col;
				if(selectedTopLevel instanceof Collection)
				{
					col = selection.getCollections().iterator().next();
					boolean cont = true;
					while(cont)
					{
						cont = false;
						for(Collection c : selection.getCollections())
						{
							if(col != c)
							{
								if(c.containsMember(col.getIdentity()))
								{
									col = c;
									cont = true;
								}
							}
						}
					}
					addCollection(col);
				} else if(selectedTopLevel instanceof CombinatorialDerivation) {
					addDerivation(selection.getCombinatorialDerivations().iterator().next());
				} else if(selectedTopLevel instanceof ComponentDefinition) {
					addVariant(root.cd);
				} else {
					System.err.println("ERROR: Variant is not a valid type (" + selectedTopLevel.getClass() + ")");
				}

				updateTable();
				return;
			}

			if (e.getSource() == removeButton) {
				int row = table.convertRowIndexToModel(table.getSelectedRow());
				TopLevelTableModel model = (TopLevelTableModel) table.getModel();
				TopLevel top = model.getElement(row);
				removeVariant(top);
				updateTable();
				return;
			}

			if (e.getSource() == newButton) {
				addCombinatorialDerivation();
				return;
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	}

	private void setStrategy(StrategyType strategy) {
		try {
			CombinatorialDerivation derivation = getCombinatorialDerivation(derivationCD);
			if (derivation == null) {
				return;
			}

			if (strategy == null) {
				derivation.unsetStrategy();
			} else {
				derivation.setStrategy(strategy);
			}
		} catch (SBOLValidationException e) {
			JOptionPane.showMessageDialog(parent, "Strategy cannot be enumerate when operators are *orMore");
			e.printStackTrace();
			setVisible(false);
		}
	}

	private void setOperator(OperatorType operator) {
		try {
			VariableComponent variable = getVariableComponent(operator);
			variable.setOperator(operator);
		} catch (Exception e) {
			JOptionPane.showMessageDialog(parent, "Operator cannot be *orMore when strategy is enumerate");
			e.printStackTrace();
			setVisible(false);
		}
	}

	private void addCombinatorialDerivation() throws SBOLValidationException {
		String displayId = JOptionPane.showInputDialog("What would you like the Display ID to be?");
		if (displayId == null) {
			return;
		}

		CombinatorialDerivation newDerivation = createCombinatorialDerivation(derivationCD, displayId);

		JOptionPane.showMessageDialog(parent,
				"A new CombinatorialDerivation was created: " + newDerivation.getDisplayId());

		setVisible(false);
	}

	private void updateTable() throws SBOLValidationException {
		TopLevelTableModel tableModel = new TopLevelTableModel(getVariantsCollectionsAndDerivations());
		table.setModel(tableModel);
		setWidthAsPercentages(table, tableModel.getWidths());
		TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(tableModel);
		table.setRowSorter(sorter);
	}

}


text:
package payloads_test

import (
	"testing"

	. "github.com/01org/ciao/payloads"
	"github.com/01org/ciao/testutil"
	"gopkg.in/yaml.v2"
)

func TestRestartFailureUnmarshal(t *testing.T) {
	var error ErrorRestartFailure
	err := yaml.Unmarshal([]byte(testutil.RestartFailureYaml), &error)
	if err != nil {
		t.Error(err)
	}

	if error.InstanceUUID != testutil.InstanceUUID {
		t.Error("Wrong UUID field")
	}

	if error.Reason != RestartAlreadyRunning {
		t.Error("Wrong Error field")
	}
}

func TestRestartFailureMarshal(t *testing.T) {
	error := ErrorRestartFailure{
		InstanceUUID: testutil.InstanceUUID,
		Reason:       RestartAlreadyRunning,
	}

	y, err := yaml.Marshal(&error)
	if err != nil {
		t.Error(err)
	}

	if string(y) != testutil.RestartFailureYaml {
		t.Errorf("RestartFailure marshalling failed\n[%s]\n vs\n[%s]", string(y), testutil.RestartFailureYaml)
	}
}

func TestRestartFailureString(t *testing.T) {
	var stringTests = []struct {
		r        RestartFailureReason
		expected string
	}{
		{RestartNoInstance, "Instance does not exist"},
		{RestartInvalidPayload, "YAML payload is corrupt"},
		{RestartInvalidData, "Command section of YAML payload is corrupt or missing required information"},
		{RestartAlreadyRunning, "Instance is already running"},
		{RestartInstanceCorrupt, "Instance is corrupt"},
		{RestartLaunchFailure, "Failed to launch instance"},
		{RestartNetworkFailure, "Failed to locate VNIC for instance"},
	}
	error := ErrorRestartFailure{
		InstanceUUID: testutil.InstanceUUID,
	}
	for _, test := range stringTests {
		error.Reason = test.r
		s := error.Reason.String()
		if s != test.expected {
			t.Errorf("expected \"%s\", got \"%s\"", test.expected, s)
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
An experimental project for blocking all search engines/all bot useragents in robots.txt. No idea why.

If you have useragents that are not on the list, open an issue with the useragent and I will add it as soon as I verify its an actual bot ;)

Not accepting donations currently.


text:
package org.jboss.shrinkwrap.api;

import java.io.OutputStream;
import java.util.Collection;
import java.util.Map;

import org.jboss.shrinkwrap.api.asset.Asset;
import org.jboss.shrinkwrap.api.asset.NamedAsset;
import org.jboss.shrinkwrap.api.exporter.StreamExporter;
import org.jboss.shrinkwrap.api.formatter.Formatter;
import org.jboss.shrinkwrap.api.formatter.Formatters;

/**
 * Represents a collection of resources which may be constructed programmatically. In effect this represents a virtual
 * filesystem.
 *
 *

 *

 * All {@link Archive} types support the addition of {@link Node}s under a designated {@link ArchivePath} (context). The
 * contents of a {@link Node} are either a directory or {@link Asset}.
 *
 *

 *

 * {@link Archive}s are generally created via an {@link ArchiveFactory} or via the default configuration shortcut
 * {@link ShrinkWrap} utility class.
 *
 *

 *

 * Because {@link Archive}s are {@link Assignable}, they may be wrapped in another user "view" used to perform
 * operations like adding JavaEE Spec-specific resources or exporting in ZIP format.
 *
 * @author ALR
 * @version $Revision: $
 */
public interface Archive<T extends Archive<T>> extends Assignable {
    // -------------------------------------------------------------------------------------||
    // Contracts --------------------------------------------------------------------------||
    // -------------------------------------------------------------------------------------||

    /**
     * Obtains the name of this archive (ie. myLibrary.jar)
     */
    String getName();

    /**
     * Obtains a globally-unique identifier for this {@link Archive}
     *
     * @return
     */
    String getId();

    /**
     * Adds the specified asset under the specified path into the target context
     *
     * @param target
     *            The context under which to add the assets
     * @param asset
     * @return
     * @throws IllegalArgumentException
     *             If no target or assets were specified
     * @throws IllegalArchivePathException
     *             If the target is invalid.
     */
    T add(Asset asset, ArchivePath target) throws IllegalArgumentException;

    /**
     * Adds the specified asset under the specified target (directory) using the specified name. The resultant path will
     * be treating the specified path as a prefix namespace, then appending the name.
     *
     * @param target
     *            The context directory under which to add the asset
     * @param name
     *            The name to assign the assent under the target namespace
     * @param asset
     * @return
     * @throws IllegalArgumentException
     *             If the target, name, or asset was not specified
     * @throws IllegalArchivePathException
     *             If the target is invalid.
     */
    T add(Asset asset, ArchivePath target, String name) throws IllegalArgumentException;

    /**
     * Adds the specified asset under the specified target (directory) using the specified name. The resultant path will
     * be treating the specified path as a prefix namespace, then appending the name.
     *
     * @param target
     *            The context directory under which to add the asset
     * @param name
     *            The name to assign the assent under the target namespace
     * @param asset
     * @return
     * @throws IllegalArgumentException
     *             If the target, name, or asset was not specified
     * @throws IllegalArchivePathException
     *             If the target is invalid.
     */
    T add(Asset asset, String target, String name) throws IllegalArgumentException;

    /**
     * Adds the asset encapsulated within the specified {@link NamedAsset} under the encapsulated name and target
     * (directory)
     *
     * @param namedAsset
     * @return
     * @throws IllegalArgumentException
     *             If either the target or asset is not specified
     * @throws IllegalArchivePathException
     *             If the target is invalid.
     */
    T add(NamedAsset namedAsset) throws IllegalArgumentException;

    /**
     * Adds the specified resource under the context denoted by the specified target
     *
     * @param target
     * @param asset
     * @return
     * @throws IllegalArgumentException
     *             If either the target or asset is not specified
     * @throws IllegalArchivePathException
     *             If the target is invalid.
     */
    T add(Asset asset, String target) throws IllegalArgumentException;

    /**
     * Adds the specified directory.
     *
     * @param path
     *            The path to add
     * @return This archive
     * @throws IllegalArgumentException
     *             If no path was specified
     * @throws IllegalArchivePathException
     *             If the path is invalid.
     */
    T addAsDirectory(String path) throws IllegalArgumentException;

    /**
     * Adds the specified directories.
     *
     * @param paths
     *            The paths to add
     * @return This archive
     * @throws IllegalArgumentException
     *             If no paths were specified
     * @throws IllegalArchivePathException
     *             If at least one path is invalid.
     */
    T addAsDirectories(String... paths) throws IllegalArgumentException;

    /**
     * Adds the specified directory.
     *
     * @param path
     *            The path to add
     * @return This archive
     * @throws IllegalArgumentException
     *             If no path was specified
     * @throws IllegalArchivePathException
     *             If the path is invalid.
     */
    T addAsDirectory(ArchivePath path) throws IllegalArgumentException;

    /**
     * Adds the specified directories.
     *
     * @param paths
     *            The paths to add
     * @return This archive
     * @throws IllegalArgumentException
     *             If no paths were specified
     * @throws IllegalArchivePathException
     *             If at least one path is invalid.
     */
    T addAsDirectories(ArchivePath... paths) throws IllegalArgumentException;

    /**
     * Add an array of listeners for call back based.
     *
     * @param listener
     *            CallBack on add
     * @return This archive
     */
    T addHandlers(ArchiveEventHandler... handlers);

    /**
     * Obtains the {@link Node} located at the specified path
     *
     * @param path
     * @return The {@link Node}, or null if nothing is found at the specified path
     * @throws IllegalArgumentException
     *             If the path is not specified
     */
    Node get(ArchivePath path) throws IllegalArgumentException;

    /**
     * Obtains the {@link Node} located at the specified path
     *
     * @param path
     * @return The {@link Node}, or null if nothing is found at the Path
     * @throws IllegalArgumentException
     *             If the path is not specified
     */
    Node get(String path) throws IllegalArgumentException;

    /**
     * Get a nested {@link Archive} as a specific type.

     *

     *
     * The found Archives must have been added as a Archive, no import is performed.
     *
     * @param <X>
     * @param type
     *            The Type to return the Archive as
     * @param path
     *            The location of the Archive
     * @return The found Archive as given type or null if none found at given path
     * @throws IllegalArgumentException
     *             if found {@link Asset} is not pointing to a {@link Archive}
     * @see Archive#getAsType(Class, ArchivePath)
     * @see Archive#add(Archive, ArchivePath, Class)
     * @see Archive#add(Archive, String, Class)
     */
    <X extends Archive<X>> X getAsType(Class<X> type, String path);

    /**
     * Get a nested {@link Archive} as a specific type.

     *

     *
     * The found Archives must have been added as a Archive, no import is performed.
     *
     * @param <X>
     * @param type
     *            The Type to return the Archive as
     * @param path
     *            The location of the Archive
     * @return The found Archive as given type or null if none found at given {@link ArchivePath}
     * @throws IllegalArgumentException
     *             if found {@link Asset} is not pointing to a {@link Archive}
     * @see Archive#add(Archive, ArchivePath, Class)
     * @see Archive#add(Archive, String, Class)
     */
    <X extends Archive<X>> X getAsType(Class<X> type, ArchivePath path);

    /**
     * Get all nested {@link Archive} matching the filter as a specific type.

     *

     *
     * The found Archives must have been added as a Archive, no import is performed.
     *
     * @param <X>
     * @param type
     *            The Type to return the Archive as
     * @param filter
     *            Filter to match result
     * @return A {@link Collection} of found Archives matching given filter or empty {@link Collection} if non found.
     * @throws IllegalArgumentException
     *             if found {@link Asset} is not pointing to a {@link Archive}
     * @see Archive#getAsType(Class, ArchivePath)
     * @see Archive#add(Archive, ArchivePath, Class)
     * @see Archive#add(Archive, String, Class)
     */
    <X extends Archive<X>> Collection<X> getAsType(Class<X> type, Filter<ArchivePath> filter);

    /**
     * Get a nested {@link Archive} as a specific type using the specify {@code ArchiveFormat}
     *
     * @param type
     *            The Type to return the Archive as
     * @param path
     *            The location of the Archive
     * @param archiveFormat
     *            The archive format
     * @return The found Archive as given type or null if none found at the given path
     * @see Archive#add(Archive, ArchivePath, Class)
     * @see Archive#add(Archive, String, Class)
     */
    <X extends Archive<X>> X getAsType(Class<X> type, String path, ArchiveFormat archiveFormat);

    /**
     * Get a nested {@link Archive} located in a {@code ArchivePath} as a specific type using the specify
     * {@code ArchiveFormat}
     *
     * @param type
     *            The Type to return the Archive as
     * @param path
     *            The location of the Archive
     * @param archiveFormat
     *            The archive format
     * @return The found Archive as given type or null if none found at given {@link ArchivePath}
     * @see Archive#add(Archive, ArchivePath, Class)
     * @see Archive#add(Archive, String, Class)
     */
    <X extends Archive<X>> X getAsType(Class<X> type, ArchivePath path, ArchiveFormat archiveFormat);

    /**
     * Get all nested {@link Archive} matching the filter as a specific type using the specify {@code ArchiveFormat}.
     *
     * @param <X>
     * @param type
     *            The Type to return the Archive as
     * @param filter
     *            Filter to match result
     * @param archiveFormat
     *            The archive format
     * @return A {@link Collection} of found Archives matching given filter or empty {@link Collection} if non found.
     * @see Archive#getAsType(Class, ArchivePath, ArchiveFormat)
     * @see Archive#add(Archive, ArchivePath, Class)
     * @see Archive#add(Archive, String, Class)
     */
    <X extends Archive<X>> Collection<X> getAsType(Class<X> type, Filter<ArchivePath> filter,
        ArchiveFormat archiveFormat);

    /**
     * Denotes whether this archive contains a resource at the specified path
     *
     * @param path
     * @return
     * @throws IllegalArgumentException
     *             If the path is not specified
     */
    boolean contains(ArchivePath path) throws IllegalArgumentException;

    /**
     * Denotes whether this archive contains a resource at the specified path
     *
     * @param path
     * @return
     * @throws IllegalArgumentException
     *             If the path is not specified
     */
    boolean contains(String path) throws IllegalArgumentException;

    /**
     * Removes the {@link Node} in the {@link Archive} at the specified {@link ArchivePath}. If the path is a directory,
     * recursively removes all contents. If the path does not exist, return null.
     *
     * @param path
     * @return The Node removed
     */
    Node delete(ArchivePath path) throws IllegalArgumentException;

    /**
     * Removes the {@link Node} in the {@link Archive} at the {@link ArchivePath} indicated by the specified String
     * archivePath. If the path is a directory, recursively removes all contents. If the path does not exist, return
     * null.
     *
     * @param archivePath
     * @return The Node removed
     * @see #delete(ArchivePath)
     */
    Node delete(String archivePath) throws IllegalArgumentException;

    /**
     * Obtains all assets in this archive, along with their respective paths. The returned Map will be an immutable
     * view.
     *
     * @return
     */
    Map<ArchivePath, Node> getContent();

    /**
     * Obtains all assets matching given filter in this archive, along with its respective Path. The returned Map will
     * be an immutable view.
     *
     * @return
     */
    Map<ArchivePath, Node> getContent(Filter<ArchivePath> filter);

    /**
     * Obtains all assets matching given filter in this archive as a new Archive.

     *

     * This is an alias for shallowCopy(Filter).
     *
     * @see org.jboss.shrinkwrap.api.Archive#shallowCopy(Filter)
     * @param filter
     * @return
     */
    T filter(Filter<ArchivePath> filter);

    /**
     * Add an archive under a specific context and maintain the archive name as context path.
     *
     * @param path
     *            to use
     * @param archive
     *            to add
     * @param exporter
     *            Exporter type to use in fulfilling the {@link Asset#openStream()} contract for the added (nested)
     *            archive.
     * @return
     * @throws IllegalArgumentException
     *             If any argument is not specified
     */
    T add(Archive<?> archive, ArchivePath path, Class<? extends StreamExporter> exporter)
        throws IllegalArgumentException;

    /**
     * Add an archive under a specific context and maintain the archive name as context path.
     *
     * @param path
     *            to use
     * @param archive
     *            to add
     * @param exporter
     *            Exporter type to use in fulfilling the {@link Asset#openStream()} contract for the added (nested)
     *            archive.
     * @return
     * @throws IllegalArgumentException
     *             If the path or archive are not specified
     */
    T add(Archive<?> archive, String path, Class<? extends StreamExporter> exporter) throws IllegalArgumentException;

    /**
     * Merge the contents from an existing archive without maintaining the archive name in the context path.
     *
     * @param source
     *            Archive to add contents from
     * @return
     * @throws IllegalArgumentException
     *             If the existing archive is not specified
     */
    T merge(Archive<?> source) throws IllegalArgumentException;

    /**
     * Merge the contents from an existing archive without maintaining the archive name in the context path.
     *
     * The filter control which {@link ArchivePath}s to include form the source {@link Archive}.
     *
     * @param source
     *            Archive to add contents from
     * @return
     * @throws IllegalArgumentException
     *             If the existing archive is not specified
     */
    T merge(Archive<?> source, Filter<ArchivePath> filter) throws IllegalArgumentException;

    /**
     * Merge the contents from an existing archive in a specific path without maintaining the archive name in the
     * context path.
     *
     * @param source
     *            Archive to add contents from
     * @param path
     *            Path to add contents to
     * @return
     * @throws IllegalArgumentException
     *             If the path or existing archive is not specified
     */
    T merge(Archive<?> source, ArchivePath path) throws IllegalArgumentException;

    /**
     * Merge the contents from an existing archive in a specific path without maintaining the archive name in the
     * context path.
     *
     * @param source
     *            Archive to add contents from
     * @param path
     *            Path to add contents to
     * @return
     * @throws IllegalArgumentException
     *             If the path or existing archive is not specified
     */
    T merge(Archive<?> source, String path) throws IllegalArgumentException;

    /**
     * Merge the contents from an existing archive in a specific path without maintaining the archive name in the
     * context path. The filter control which {@link ArchivePath}s to include form the source {@link Archive}.
     *
     * @param source
     *            Archive to add contents from
     * @param path
     *            Path to add contents to
     * @param filter
     *            Filter to use for including {@link Asset}s in the merge.
     * @return
     * @throws IllegalArgumentException
     *             If the path or existing archive is not specified
     */
    T merge(Archive<?> source, ArchivePath path, Filter<ArchivePath> filter) throws IllegalArgumentException;

    /**
     * Merge the contents from an existing archive in a specific path without maintaining the archive name in the
     * context path. The filter control which {@link ArchivePath}s to include form the source {@link Archive}.
     *
     * @param source
     *            Archive to add contents from
     * @param path
     *            Path to add contents to
     * @param filter
     *            Filter to use for including {@link Asset}s in the merge.
     * @return
     * @throws IllegalArgumentException
     *             If the path or existing archive is not specified
     */
    T merge(Archive<?> source, String path, Filter<ArchivePath> filter) throws IllegalArgumentException;

    /**
     * Moves the asset under the source path to the target path.
     *
     * @param source
     *            The context under which to remove the assets
     * @param target
     *            The context under which to add the moved assets
     * @return the resulting archive with the moved assets
     * @throws IllegalArgumentException
     *             If any of the paths is not specified
     * @throws IllegalArchivePathException
     *             If the source path is invalid.
     */
    T move(ArchivePath source, ArchivePath target) throws IllegalArgumentException, IllegalArchivePathException;

    /**
     * Moves the asset under the source path to the target path.
     *
     * @param source
     *            The context under which to remove the assets
     * @param target
     *            The context under which to add the moved assets
     * @return the resulting archive with the moved assets
     * @throws IllegalArgumentException
     *             If any of the paths is not specified
     * @throws IllegalArchivePathException
     *             If the source path is invalid.
     */
    T move(String source, String target) throws IllegalArgumentException, IllegalArchivePathException;

    /**
     * Acts as a shorthand for {@link Archive#toString(Formatter)} where the {@link Formatters#SIMPLE} is leveraged.
     *
     * @return
     */
    @Override
    String toString();

    /**
     * If "true" is specified, acts as a shorthand for {@link Archive#toString(Formatter)} where the
     * {@link Formatters#VERBOSE} is leveraged. Otherwise the {@link Formatters#SIMPLE} will be used (equivalent to
     * {@link Archive#toString()}).
     *
     * @return
     */
    String toString(boolean verbose);

    /**
     * Returns a view of this {@link Archive} as returned from the specified {@link Formatter}. Common options may be to
     * use the predefined formatters located in {@link Formatters}
     *
     * @param formatter
     * @return
     * @throws IllegalArgumentException
     *             If the formatter is not specified
     */
    String toString(Formatter formatter) throws IllegalArgumentException;

    /**
     * Prints the content of this {@link Archive} to the specified {@link OutputStream} on the format defined by the
     * specified {@link Formatter}. The caller is responsible for opening, flushing and eventually closing the stream.
     *
     * @param outputStream
     *            the stream to print the archive contents to
     * @param formatter
     *            the output format
     * @throws IllegalArgumentException
     *             if an exceptions occur when writing the archive contents.
     */
    void writeTo(OutputStream outputStream, Formatter formatter) throws IllegalArgumentException;

    /**
     * Creates a shallow copy of this {@link Archive}. Assets from this archive are made available under the same paths.
     * However, removing old assets or adding new assets on this archive affects does not affect the new archive.
     *
     * @return a new archive with a copy of the pointers to the assets
     */
    Archive<T> shallowCopy();

    /**
     * Creates a shallow copy of this {@link Archive} based on given filter.
     * Assets from this archive are made available
     * under the same paths. However, removing old assets or
     * adding new assets on this archive affects does not affect
     * the new archive. This allows for filtering of both directory-based
     * and {@link Asset}-based paths.
     *
     * @return a new archive with a copy of the pointers to the assets
     */
    Archive<T> shallowCopy(Filter<ArchivePath> filter);
}


text:
package com.strucr.grizzly1679;

import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.Response;
import com.ning.http.client.providers.grizzly.GrizzlyAsyncHttpProvider;

import java.util.concurrent.Future;

/**
 * Run a request
 */
public class Main {
    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("\n== Usage Error ==\nPlease pass URL to call");
            System.exit(1);
        }
        String url = args[0];

        AsyncHttpClientConfig config = new AsyncHttpClientConfig.Builder()
            .setCompressionEnabled(true)
            .setFollowRedirects(false)
            .setUserAgent("Grizzly 1679 Test Case")
            .setConnectionTimeoutInMs(15000)
            .setRequestTimeoutInMs(15000)
            .setAllowPoolingConnection(false)
            .setUseRawUrl(true)
            .setIOThreadMultiplier(2) // 2 is default
            .build();

        AsyncHttpClient client = new AsyncHttpClient(new GrizzlyAsyncHttpProvider(config), config);

        try {
            Future<Response> f = client.prepareGet(url).execute();
            Response r = f.get();
            System.out.println("\n== OK ==\nGot Respone " + r.getStatusText());
            System.exit(0);
        } catch (Exception e) {
            System.out.println("\n== Bug Hit! ==\nCaught Exception " + e.toString());
            System.exit(2);
        }
    }
}


text:
2016-01-20: Version 2.8.7

	- Added iOS 9 and iPad Pro support.
	- iPhone 6 Plus and iPhone 6S Plus @3x graphics.
	- Sticky paging on iPod/iPhone workaround fix.

2015-03-24: Version 2.8.6

	- Added French and Spanish Localizable.strings
	- iOS 8 UIScrollView bug revisited - again...

2014-12-07: Version 2.8.5

	- iPhone 6 and 6 Plus support - launch images and thumbnails.
	- iOS 8 UIScrollView bug revisited - possibly fixed in 8.1.1?

2014-10-18: Version 2.8.4

	- Fixed a rather daft design decision in ReaderDocument.

2014-09-20: Version 2.8.3

	- Workaround for bug in 32-bit iOS UIScrollView when UIUserInterfaceIdiomPhone.

2014-09-17: Version 2.8.2

	- Tweaked the flat toolbar look.

2014-09-16: Version 2.8.1

	- Replaced READER_ENABLE_MAIL with a canEmail document property.
	- Replaced READER_ENABLE_EXPORT with a canExport document property.
	- Replaced READER_ENABLE_PRINT with a canPrint document property.
	- Compile time READER_FLAT_UI option now flattens the toolbars.

2014-09-14: Version 2.8.0

	- Double-tap to zoom now centers the zoom on the location of the double-tap.
	- The toolbar Done button now adjusts its width based on the width of its localized text.
	- Reworked handling of views in the ReaderViewController paging UIScrollView. You can now page as fast as the device can go.
	- Added a READER_ENABLE_EXPORT compile time option. Uses UIDocumentInteractionController to export the current PDF to other applications.
	- Added a READER_FLAT_UI compile time option that (for now only) disables button borders.
	- Fixed crash under iOS 8 - please see the note in the ReaderDocument class file.
	- Cleaned up 64-bit compiler warnings for various format strings.

2013-11-19: Version 2.7.3

	- Retina and zoom levels bug fixes.
	- PDF annotation URI handling bug fix.

2013-10-24: Version 2.7.2

	- iOS 7 status bar handling bug fixes.

2013-10-12: Version 2.7.1

	- Changed 'unsafe_unretained' to 'weak'.

2013-10-03: Version 2.7.0

	- iOS 7 and Xcode 5.0 support.

2013-06-04: Version 2.6.2

	- Touch two UIButton, exclusiveTouch = NO. Not good. Fixed.

2012-10-05: Version 2.6.1

	- Greatly improved thumb operation cancel handling.
	- iOS 4 support and various other miscellaneous fixes.

2012-09-24: Version 2.6.0

	- Refactored to use ARC memory management.
	- General code cleanup and modernization.
	- Added ReaderDocumentOutline class.

2012-04-16: Version 2.5.6

	- Now loads and decodes thumbnails on a background thread.
	- Added READER_DISABLE_RETINA #define performance option.

2012-04-10: Version 2.5.5

	- Handles PDF web links without http:// as the prefix.
	- Bug fix to PDF link handling with crop-boxed PDF files.
	- Some performance improvements on iPad 3rd generation.

2012-01-14: Version 2.5.4

	- Bug fix to PDF link handling in older format PDFs.
	- Changed from CC BY 3.0 License to MIT License.

2011-11-08: Version 2.5.3

	- Various refinements and minor bug fixes.

2011-10-15: Version 2.5.2

	- One (crashing) bug fix and one minor UI tweak.

2011-10-06: Version 2.5.1

	- Fixed content view centering under iOS 5.

2011-10-05: Version 2.5.0

	- Critical bug fixes and various assorted tweaks.

2011-09-20: Version 2.4.0

	- Replaced UIToolbars with custom UIView-based toolbars.

2011-09-14: Version 2.3.0

	- Added page thumbnail document navigation.
	- Added support for page bookmarks.

2011-09-10: Version 2.2.1

	- Added password handling to ReaderDocument plist unarchive.

2011-09-09: Version 2.2.0

	- A medium resolution page preview image is now shown first.
	- The page bar now uses small page thumbs instead of a slider.

2011-08-27: Version 2.1.1

	- Fixed rotation handling when in a UITabBarController.

2011-08-25: Version 2.1.0

	- Added PDF link (URI and document page) support.
	- Assorted code cleanup, optimizations and bug fixes.

2011-07-29: Version 2.0.0

	- Released v2.0 into the wild for general use.


text:
package org.apache.deltaspike.example.echo;

/**
 * Interface for the different kinds of echo-services
 */
public interface EchoService
{
    /**
     * Returns the given text again - the format might change
     *
     * @param message given message
     * @return message text
     */
    String echo(String message);
}


text:
<?php

namespace cms;

use think\facade\Url;
use think\facade\View;
use think\facade\Config;
use think\facade\Request;
use cms\facade\Response;
use cms\core\objects\ReturnObject;
use cms\core\constant\CodeConstant;

class Controller
{

    /**
     * @var \think\View
     */
    protected $view;

    /**
     * @var \think\Request
     */
    protected $request;

    /**
     * Controller constructor.
     */
    public function __construct()
    {
        $this->view = View::init(Config::pull('template'));
        $this->request = Request::instance();

        // 初始化
        $this->_initialize();
    }

    /**
     * 初始化
     */
    protected function _initialize()
    {
    }

    /**
     * 视图渲染前
     */
    protected function beforeViewRender()
    {
    }

    /**
     * 成功返回
     *
     * @param string $msg
     * @param string $url
     * @param string $data
     * @param int $wait
     * @param array $header
     */
    protected function success($msg = '', $url = '', $data = '', $wait = 3, $header = [])
    {
        $this->jump(CodeConstant::CODE_SUCCESS, $msg, $url, $data, $wait, $header);
    }

    /**
     * 失败返回
     *
     * @param string $msg
     * @param string $url
     * @param string $data
     * @param int $wait
     * @param array $header
     */
    protected function error($msg = '', $url = '', $data = '', $wait = 3, $header = [])
    {
        $this->jump(CodeConstant::CODE_ERROR, $msg, $url, $data, $wait, $header);
    }

    /**
     * 结果返回
     *
     * @param int $code
     * @param string $msg
     * @param string $url
     * @param string $data
     * @param int $wait
     * @param array $header
     */
    protected function jump($code = CodeConstant::CODE_SUCCESS, $msg = '', $url = '', $data = '', $wait = 3, $header = [])
    {
        $result = [
            'code' => $code,
            'msg' => $msg,
            'url' => $this->buildUrl($url),
            'data' => $data,
            'wait' => $wait
        ];
        if ($this->request->isAjax()) {
            Response::json($result, $header);
        } else {
            $template = $this->getJumpTemplate($code);
            $content = $this->fetch($template, $result);
            Response::data($content, 'html', 200, $header);
        }
    }

    /**
     * 返回结果
     *
     * @param ReturnObject $return
     * @param string $url
     * @param int $wait
     * @param array $header
     */
    protected function response($return, $url = '', $wait = 3, $header = [])
    {
        if ($return->isSuccess()) {
            $this->success($return->getMsg(), $url, $return->getData(), $wait, $header);
        } else {
            $this->error($return->getMsg(), $url, $return->getData(), $wait, $header);
        }
    }

    /**
     * 模板变量赋值
     *
     * @param string $name
     * @param string $value
     * @return \think\View
     */
    protected function assign($name, $value = '')
    {
        return $this->view->assign($name, $value);
    }

    /**
     * 解析和获取模板内容
     *
     * @param  string $template
     * @param  array $vars
     * @param  array $config
     * @param  bool $renderContent
     * @return string
     */
    protected function fetch($template = '', $vars = [], $config = [], $renderContent = false)
    {
        $this->beforeViewRender();

        return $this->view->fetch($template, $vars, $config, $renderContent);
    }

    /**
     * 渲染内容输出
     *
     * @param  string $content
     * @param  array $vars
     * @param  array $config
     * @return string
     */
    protected function display($content, $vars = [], $config = [])
    {
        $this->beforeViewRender();

        return $this->view->fetch($content, $vars, $config, true);
    }

    /**
     * 构造Url
     *
     * @param string $url
     * @return string
     */
    protected function buildUrl($url)
    {
        if (strpos($url, '://') || 0 === strpos($url, '/')) {
            return $url;
        } elseif ($url === '') {
            return $url;
        } else {
            return Url::build($url);
        }
    }

    /**
     * 获取跳转模板
     *
     * @param int $code
     * @return mixed
     */
    protected function getJumpTemplate($code)
    {
        if ($code == CodeConstant::CODE_SUCCESS) {
            return Config::get('dispatch_success_tmpl');
        } else {
            return Config::get('dispatch_error_tmpl');
        }
    }

}


text:
require 'poise'

class Chef
  class Provider::FirewallIptables < Provider
    include Poise
    include Chef::Mixin::ShellOut

    def action_enable
      converge_by('install package iptables and default DROP if no rules exist') do
        package 'iptables' do
          action :install
        end

        # prints all the firewall rules
        # pp new_resource.subresources
        log_current_iptables
        if active?
          Chef::Log.info("#{new_resource} already enabled.")
        else
          Chef::Log.debug("#{new_resource} is about to be enabled")
          shell_out!('iptables -P INPUT DROP')
          shell_out!('iptables -P OUTPUT DROP')
          shell_out!('iptables -P FORWARD DROP')

          shell_out!('ip6tables -P INPUT DROP')
          shell_out!('ip6tables -P OUTPUT DROP')
          shell_out!('ip6tables -P FORWARD DROP')
          Chef::Log.info("#{new_resource} enabled.")
          new_resource.updated_by_last_action(true)
        end
      end
    end

    def action_disable
      if active?
        shell_out!('iptables -P INPUT ACCEPT')
        shell_out!('iptables -P OUTPUT ACCEPT')
        shell_out!('iptables -P FORWARD ACCEPT')
        shell_out!('iptables -F')

        shell_out!('ip6tables -P INPUT ACCEPT')
        shell_out!('ip6tables -P OUTPUT ACCEPT')
        shell_out!('ip6tables -P FORWARD ACCEPT')
        shell_out!('ip6tables -F')
        Chef::Log.info("#{new_resource} disabled")
        new_resource.updated_by_last_action(true)
      else
        Chef::Log.debug("#{new_resource} already disabled.")
      end
    end

    def action_flush
      shell_out!('iptables -F')
      shell_out!('ip6tables -F')
      Chef::Log.info("#{new_resource} flushed.")
    end

    def action_save
      shell_out!('service iptables save')
      shell_out!('service ip6tables save')
      Chef::Log.info("#{new_resource} saved.")
    end

    private

    def active?
      @active ||= begin
        cmd = shell_out!('iptables-save')
        cmd.stdout =~ /INPUT ACCEPT/
      end
      @active_v6 ||= begin
        cmd = shell_out!('ip6tables-save')
        cmd.stdout =~ /INPUT ACCEPT/
      end
      @active && @active_v6
    end

    def log_current_iptables
      cmdstr = 'iptables -L'
      Chef::Log.info("#{new_resource} log_current_iptables (#{cmdstr}):")
      cmd = shell_out!(cmdstr)
      Chef::Log.info(cmd.inspect)
      cmdstr = 'ip6tables -L'
      Chef::Log.info("#{new_resource} log_current_iptables (#{cmdstr}):")
      cmd = shell_out!(cmdstr)
      Chef::Log.info(cmd.inspect)
    rescue
      Chef::Log.info("#{new_resource} log_current_iptables failed!")
    end
  end
end


text:
<!DOCTYPE html>

    <meta charset='utf-8'>
    <title>Crosswalk_Cordova_WebApp_Project_Build</title>
    <link rel="author" title="Intel" href="http://www.intel.com">

      Test steps:

Use command: 'sudo gedit ./helloworld/assets/www/index.html' to edit index.html file

Add '&lta href="http://www.intel.com">Intel&lt/a>' in body area and save index.html file

Use command:'./helloworld/cordova/build' build helloworld project

      Expected Output:

The index.html could be opened

The link could be added successfully

The helloworld projet could be builded successful and could be seen 'BUILD SUCCESSFUL' on console


text:
@(categories: Seq[models.Category], products: Seq[models.Product])(implicit flash: play.api.mvc.Flash, messages: Messages)

@main {

    @flash.get("success").map { message =>

            Done! @message

    }

Add a category

Add a product

Home

            @categories.map { category =>

 @category.name

                    @products.filter(product=> product.categoryId == category._id.stringify).map { product =>

 @product.name
                    }

            }

}


text:
#include <QTreeWidgetItem>
#include <QInputDialog>
#include <QRadioButton>
#include <QTreeWidget>
#include <QHeaderView>
#include <QMessageBox>
#include <QPushButton>
#include <QComboBox>
#include <QLineEdit>
#include <QSpinBox>
#include <QLabel>

#include "qlcinputprofile.h"
#include "qlcinputchannel.h"
#include "qlccapability.h"
#include "qlcchannel.h"

#include "vcsliderproperties.h"
#include "selectinputchannel.h"
#include "functionselection.h"
#include "mastertimer.h"
#include "inputpatch.h"
#include "vcslider.h"
#include "fixture.h"
#include "doc.h"

#define KColumnName  0
#define KColumnType  1
#define KColumnRange 2
#define KColumnID    3

VCSliderProperties::VCSliderProperties(VCSlider* slider, Doc* doc)
    : QDialog(slider)
    , m_doc(doc)
{
    Q_ASSERT(doc != NULL);
    Q_ASSERT(slider != NULL);
    m_slider = slider;

    setupUi(this);

    QAction* action = new QAction(this);
    action->setShortcut(QKeySequence(QKeySequence::Close));
    connect(action, SIGNAL(triggered(bool)), this, SLOT(reject()));
    addAction(action);

    /* Level page connections */
    connect(m_levelLowLimitSpin, SIGNAL(valueChanged(int)),
            this, SLOT(slotLevelLowSpinChanged(int)));
    connect(m_levelHighLimitSpin, SIGNAL(valueChanged(int)),
            this, SLOT(slotLevelHighSpinChanged(int)));
    connect(m_levelCapabilityButton, SIGNAL(clicked()),
            this, SLOT(slotLevelCapabilityClicked()));
    connect(m_levelList, SIGNAL(itemClicked(QTreeWidgetItem*,int)),
            this, SLOT(slotLevelListClicked(QTreeWidgetItem*)));
    connect(m_levelAllButton, SIGNAL(clicked()),
            this, SLOT(slotLevelAllClicked()));
    connect(m_levelNoneButton, SIGNAL(clicked()),
            this, SLOT(slotLevelNoneClicked()));
    connect(m_levelInvertButton, SIGNAL(clicked()),
            this, SLOT(slotLevelInvertClicked()));
    connect(m_levelByGroupButton, SIGNAL(clicked()),
            this, SLOT(slotLevelByGroupClicked()));
    connect(m_switchToLevelModeButton, SIGNAL(clicked()),
            this, SLOT(slotModeLevelClicked()));

    /* Playback page connections */
    connect(m_switchToPlaybackModeButton, SIGNAL(clicked()),
            this, SLOT(slotModePlaybackClicked()));
    connect(m_attachPlaybackFunctionButton, SIGNAL(clicked()),
            this, SLOT(slotAttachPlaybackFunctionClicked()));
    connect(m_detachPlaybackFunctionButton, SIGNAL(clicked()),
            this, SLOT(slotDetachPlaybackFunctionClicked()));

    /* Submaster page connections */
    connect(m_switchToSubmasterModeButton, SIGNAL(clicked()),
            this, SLOT(slotModeSubmasterClicked()));

    /*********************************************************************
     * General page
     *********************************************************************/

    /* Name */
    m_nameEdit->setText(m_slider->caption());

    /* Widget appearance */
    if (m_slider->widgetStyle() == VCSlider::WKnob)
        m_widgetKnobRadio->setChecked(true);
    else
        m_widgetSliderRadio->setChecked(true);

    /* Slider mode */
    m_sliderMode = m_slider->sliderMode();
    switch (m_sliderMode)
    {
    default:
    case VCSlider::Level:
        slotModeLevelClicked();
        break;
    case VCSlider::Playback:
        slotModePlaybackClicked();
        break;
    case VCSlider::Submaster:
        slotModeSubmasterClicked();
        break;
    }

    /* Slider movement (Qt understands inverted appearance vice versa) */
    if (m_slider->invertedAppearance() == true)
        m_sliderMovementInvertedRadio->setChecked(true);
    else
        m_sliderMovementNormalRadio->setChecked(true);

    /* Value display style */
    switch (m_slider->valueDisplayStyle())
    {
    default:
    case VCSlider::ExactValue:
        m_valueExactRadio->setChecked(true);
        break;
    case VCSlider::PercentageValue:
        m_valuePercentageRadio->setChecked(true);
        break;
    }

    /********************************************************************
     * External input
     ********************************************************************/
    m_inputSource = m_slider->inputSource();
    updateInputSource();

    connect(m_autoDetectInputButton, SIGNAL(toggled(bool)),
            this, SLOT(slotAutoDetectInputToggled(bool)));
    connect(m_chooseInputButton, SIGNAL(clicked()),
            this, SLOT(slotChooseInputClicked()));

    /*********************************************************************
     * Level page
     *********************************************************************/

    /* Level limit spins */
    m_levelLowLimitSpin->setValue(m_slider->levelLowLimit());
    m_levelHighLimitSpin->setValue(m_slider->levelHighLimit());

    /* Tree widget contents */
    levelUpdateFixtures();
    levelUpdateChannelSelections();

    connect(m_levelList, SIGNAL(expanded(QModelIndex)),
            this, SLOT(slotItemExpanded()));
    connect(m_levelList, SIGNAL(collapsed(QModelIndex)),
            this, SLOT(slotItemExpanded()));

    m_monitorValuesCheck->setChecked(m_slider->channelsMonitorEnabled());

    /*********************************************************************
     * Playback page
     *********************************************************************/

    /* Function */
    m_playbackFunctionId = m_slider->playbackFunction();
    updatePlaybackFunctionName();

}

VCSliderProperties::~VCSliderProperties()
{
}

/*****************************************************************************
 * General page
 *****************************************************************************/

void VCSliderProperties::slotModeLevelClicked()
{
    m_sliderMode = VCSlider::Level;

    m_nameEdit->setEnabled(true);

    setLevelPageVisibility(true);
    setPlaybackPageVisibility(false);
    setSubmasterPageVisibility(false);

    int cngType = m_slider->clickAndGoType();
    switch(cngType)
    {
        case ClickAndGoWidget::Red:
        case ClickAndGoWidget::Green:
        case ClickAndGoWidget::Blue:
        case ClickAndGoWidget::Cyan:
        case ClickAndGoWidget::Magenta:
        case ClickAndGoWidget::Yellow:
        case ClickAndGoWidget::Amber:
        case ClickAndGoWidget::White:
        case ClickAndGoWidget::UV:
            m_cngColorCheck->setChecked(true);
        break;
        case ClickAndGoWidget::RGB:
            m_cngRGBCheck->setChecked(true);
        break;
        case ClickAndGoWidget::CMY:
            m_cngCMYCheck->setChecked(true);
        break;
        case ClickAndGoWidget::Preset:
            m_cngPresetCheck->setChecked(true);
        break;
        default:
        case ClickAndGoWidget::None:
            m_cngNoneCheck->setChecked(true);
        break;

    }
}

void VCSliderProperties::slotModePlaybackClicked()
{
    m_sliderMode = VCSlider::Playback;

    m_nameEdit->setEnabled(true);

    setLevelPageVisibility(false);
    setPlaybackPageVisibility(true);
    setSubmasterPageVisibility(false);
}

void VCSliderProperties::slotModeSubmasterClicked()
{
    m_sliderMode = VCSlider::Submaster;

    setLevelPageVisibility(false);
    setPlaybackPageVisibility(false);
    setSubmasterPageVisibility(true);
}

void VCSliderProperties::slotAutoDetectInputToggled(bool checked)
{
    if (checked == true)
    {
        connect(m_doc->inputOutputMap(), SIGNAL(inputValueChanged(quint32,quint32,uchar)),
                this, SLOT(slotInputValueChanged(quint32,quint32)));
    }
    else
    {
        disconnect(m_doc->inputOutputMap(), SIGNAL(inputValueChanged(quint32,quint32,uchar)),
                   this, SLOT(slotInputValueChanged(quint32,quint32)));
    }
}

void VCSliderProperties::slotInputValueChanged(quint32 universe, quint32 channel)
{
    m_inputSource = QSharedPointer<QLCInputSource>(new QLCInputSource(universe, (m_slider->page() << 16) | channel));
    updateInputSource();
}

void VCSliderProperties::slotChooseInputClicked()
{
    SelectInputChannel sic(this, m_doc->inputOutputMap());
    if (sic.exec() == QDialog::Accepted)
    {
        m_inputSource = QSharedPointer<QLCInputSource>(new QLCInputSource(sic.universe(), sic.channel()));
        updateInputSource();
    }
}

void VCSliderProperties::updateInputSource()
{
    QString uniName;
    QString chName;

    if (m_doc->inputOutputMap()->inputSourceNames(m_inputSource, uniName, chName) == false)
    {
        uniName = KInputNone;
        chName = KInputNone;
    }

    m_inputUniverseEdit->setText(uniName);
    m_inputChannelEdit->setText(chName);
}

void VCSliderProperties::setLevelPageVisibility(bool visible)
{
    m_levelValueRangeGroup->setVisible(visible);
    m_levelList->setVisible(visible);
    m_levelAllButton->setVisible(visible);
    m_levelNoneButton->setVisible(visible);
    m_levelInvertButton->setVisible(visible);
    m_levelByGroupButton->setVisible(visible);
    m_clickngoGroup->setVisible(visible);
    m_monitorValuesCheck->setVisible(visible);

    if (visible == true)
    {
        m_switchToLevelModeButton->hide();
        m_levelSpacer->changeSize(0, 0, QSizePolicy::Fixed, QSizePolicy::Expanding);
    }
    else
    {
        m_switchToLevelModeButton->show();
        m_levelSpacer->changeSize(0, 0, QSizePolicy::Fixed, QSizePolicy::Fixed);
    }
}

void VCSliderProperties::setPlaybackPageVisibility(bool visible)
{
    m_playbackFunctionGroup->setVisible(visible);

    if (visible == true)
    {
        m_switchToPlaybackModeButton->hide();
        m_playbackSpacer->changeSize(0, 0, QSizePolicy::Fixed, QSizePolicy::Expanding);
    }
    else
    {
        m_switchToPlaybackModeButton->show();
        m_playbackSpacer->changeSize(0, 0, QSizePolicy::Fixed, QSizePolicy::Fixed);
    }
}

void VCSliderProperties::setSubmasterPageVisibility(bool visible)
{
    m_submasterInfo->setVisible(visible);

    if (visible == true)
    {
        m_switchToSubmasterModeButton->hide();
        m_submasterSpacer->changeSize(0, 0, QSizePolicy::Fixed, QSizePolicy::Expanding);
    }
    else
    {
        m_switchToSubmasterModeButton->show();
        m_submasterSpacer->changeSize(0, 0, QSizePolicy::Fixed, QSizePolicy::Fixed);
    }
}

/*****************************************************************************
 * Level page
 *****************************************************************************/

void VCSliderProperties::levelUpdateFixtures()
{
    foreach(Fixture* fixture, m_doc->fixtures())
    {
        Q_ASSERT(fixture != NULL);
        levelUpdateFixtureNode(fixture->id());
    }
    m_levelList->resizeColumnToContents(KColumnName);
    m_levelList->resizeColumnToContents(KColumnType);
}

void VCSliderProperties::levelUpdateFixtureNode(quint32 id)
{
    QTreeWidgetItem* item;
    Fixture* fxi;
    QString str;

    fxi = m_doc->fixture(id);
    Q_ASSERT(fxi != NULL);

    item = levelFixtureNode(id);
    if (item == NULL)
    {
        item = new QTreeWidgetItem(m_levelList);
        item->setText(KColumnID, str.setNum(id));
        item->setFlags(item->flags() | Qt::ItemIsUserCheckable
                       | Qt::ItemIsTristate);
    }

    item->setText(KColumnName, fxi->name());
    item->setIcon(KColumnName, fxi->getIconFromType(fxi->type()));
    item->setText(KColumnType, fxi->type());

    levelUpdateChannels(item, fxi);

}

QTreeWidgetItem* VCSliderProperties::levelFixtureNode(quint32 id)
{
    QTreeWidgetItem* item;
    int i;

    for (i = 0; i < m_levelList->topLevelItemCount(); i++)
    {
        item = m_levelList->topLevelItem(i);
        if (item->text(KColumnID).toUInt() == id)
            return item;
    }

    return NULL;
}

void VCSliderProperties::levelUpdateChannels(QTreeWidgetItem* parent,
                                             Fixture* fxi)
{
    quint32 channels = 0;
    quint32 ch = 0;

    Q_ASSERT(parent != NULL);
    Q_ASSERT(fxi != NULL);

    channels = fxi->channels();
    for (ch = 0; ch < channels; ch++)
        levelUpdateChannelNode(parent, fxi, ch);
}

void VCSliderProperties::levelUpdateChannelNode(QTreeWidgetItem* parent,
                                                Fixture* fxi, quint32 ch)
{
    Q_ASSERT(parent != NULL);

    if (fxi == NULL)
        return;

    const QLCChannel* channel = fxi->channel(ch);
    if (channel == NULL)
        return;

    QTreeWidgetItem* item = levelChannelNode(parent, ch);
    if (item == NULL)
    {
        item = new QTreeWidgetItem(parent);
        item->setText(KColumnID, QString::number(ch));
        item->setFlags(item->flags() | Qt::ItemIsUserCheckable);
        item->setCheckState(KColumnName, Qt::Unchecked);
    }

    item->setText(KColumnName, QString("%1:%2").arg(ch + 1)
                  .arg(channel->name()));
    item->setIcon(KColumnName, channel->getIcon());
    if (channel->group() == QLCChannel::Intensity &&
        channel->colour() != QLCChannel::NoColour)
        item->setText(KColumnType, QLCChannel::colourToString(channel->colour()));
    else
        item->setText(KColumnType, QLCChannel::groupToString(channel->group()));

    levelUpdateCapabilities(item, channel);
}

QTreeWidgetItem* VCSliderProperties::levelChannelNode(QTreeWidgetItem* parent,
                                                      quint32 ch)
{
    Q_ASSERT(parent != NULL);

    for (int i = 0; i < parent->childCount(); i++)
    {
        QTreeWidgetItem* item = parent->child(i);
        if (item->text(KColumnID).toUInt() == ch)
            return item;
    }

    return NULL;
}

void VCSliderProperties::levelUpdateCapabilities(QTreeWidgetItem* parent,
                                                 const QLCChannel* channel)
{
    Q_ASSERT(parent != NULL);
    Q_ASSERT(channel != NULL);

    QListIterator <QLCCapability*> it(channel->capabilities());
    while (it.hasNext() == true)
        levelUpdateCapabilityNode(parent, it.next());
}

void VCSliderProperties::levelUpdateCapabilityNode(QTreeWidgetItem* parent,
        QLCCapability* cap)
{
    QTreeWidgetItem* item;
    QString str;

    Q_ASSERT(parent != NULL);
    Q_ASSERT(cap != NULL);

    item = new QTreeWidgetItem(parent);
    item->setText(KColumnName, cap->name());
    item->setText(KColumnRange, str.sprintf("%.3d - %.3d",
                                            cap->min(), cap->max()));
    item->setFlags(item->flags() & (~Qt::ItemIsUserCheckable));
}

void VCSliderProperties::levelUpdateChannelSelections()
{
    /* Check all items that are present in the slider's list of
       controlled channels. We don't need to set other items off,
       because this function is run only during init when everything
       is off. */
    QListIterator <VCSlider::LevelChannel> it(m_slider->m_levelChannels);
    while (it.hasNext() == true)
    {
        VCSlider::LevelChannel lch(it.next());

        QTreeWidgetItem* fxiNode = levelFixtureNode(lch.fixture);
        if (fxiNode == NULL)
            continue;

        QTreeWidgetItem* chNode = levelChannelNode(fxiNode, lch.channel);
        if (chNode == NULL)
            continue;

        chNode->setCheckState(KColumnName, Qt::Checked);
    }
}

void VCSliderProperties::levelSelectChannelsByGroup(QString group)
{
    QTreeWidgetItem* fxi_item;
    QTreeWidgetItem* ch_item;
    int i;
    int j;

    /* Go thru only channel items. Fixture items get (partially) selected
       according to their children's state */
    for (i = 0; i < m_levelList->topLevelItemCount(); i++)
    {
        fxi_item = m_levelList->topLevelItem(i);
        Q_ASSERT(fxi_item != NULL);

        for (j = 0; j < fxi_item->childCount(); j++)
        {
            ch_item = fxi_item->child(j);
            Q_ASSERT(ch_item != NULL);

            if (ch_item->text(KColumnType) == group)
                ch_item->setCheckState(KColumnName, Qt::Checked);
        }
    }
}

void VCSliderProperties::slotLevelLowSpinChanged(int value)
{
    if (value >= m_levelHighLimitSpin->value())
        m_levelHighLimitSpin->setValue(value + 1);
}

void VCSliderProperties::slotLevelHighSpinChanged(int value)
{
    if (value <= m_levelLowLimitSpin->value())
        m_levelLowLimitSpin->setValue(value - 1);
}

void VCSliderProperties::slotLevelCapabilityClicked()
{
    QTreeWidgetItem* item;
    QStringList list;

    item = m_levelList->currentItem();
    if (item == NULL || item->parent() == NULL ||
            item->parent()->parent() == NULL)
        return;

    list = item->text(KColumnRange).split("-");
    Q_ASSERT(list.size() == 2);

    m_levelLowLimitSpin->setValue(list[0].toInt());
    m_levelHighLimitSpin->setValue(list[1].toInt());
}

void VCSliderProperties::slotLevelListClicked(QTreeWidgetItem* item)
{
    /* Enable the capability button if a capability has been selected */
    if (item != NULL && item->parent() != NULL &&
            item->parent()->parent() != NULL)
    {
        m_levelCapabilityButton->setEnabled(true);
    }
    else
    {
        m_levelCapabilityButton->setEnabled(false);
    }
}

void VCSliderProperties::slotLevelAllClicked()
{
    QTreeWidgetItem* fxi_item;
    int i;

    /* Set all fixture items selected, their children should get selected
       as well because the fixture items are Controller items. */
    for (i = 0; i < m_levelList->topLevelItemCount(); i++)
    {
        fxi_item = m_levelList->topLevelItem(i);
        Q_ASSERT(fxi_item != NULL);

        fxi_item->setCheckState(KColumnName, Qt::Checked);
    }
}

void VCSliderProperties::slotLevelNoneClicked()
{
    QTreeWidgetItem* fxi_item;
    int i;

    /* Set all fixture items unselected, their children should get unselected
       as well because the fixture items are Controller items. */
    for (i = 0; i < m_levelList->topLevelItemCount(); i++)
    {
        fxi_item = m_levelList->topLevelItem(i);
        Q_ASSERT(fxi_item != NULL);

        fxi_item->setCheckState(KColumnName, Qt::Unchecked);
    }
}

void VCSliderProperties::slotLevelInvertClicked()
{
    QTreeWidgetItem* fxi_item;
    QTreeWidgetItem* ch_item;
    int i;
    int j;

    /* Go thru only channel items. Fixture items get (partially) selected
       according to their children's state */
    for (i = 0; i < m_levelList->topLevelItemCount(); i++)
    {
        fxi_item = m_levelList->topLevelItem(i);
        Q_ASSERT(fxi_item != NULL);

        for (j = 0; j < fxi_item->childCount(); j++)
        {
            ch_item = fxi_item->child(j);
            Q_ASSERT(ch_item != NULL);

            if (ch_item->checkState(KColumnName) == Qt::Checked)
                ch_item->setCheckState(KColumnName,
                                       Qt::Unchecked);
            else
                ch_item->setCheckState(KColumnName,
                                       Qt::Checked);
        }
    }
}

void VCSliderProperties::slotLevelByGroupClicked()
{
    bool ok = false;
    QString group;
    QStringList groups;

    foreach(Fixture* fixture, m_doc->fixtures())
    {
        Q_ASSERT(fixture != NULL);

        for(quint32 i = 0; i < fixture->channels(); i++)
        {
            QLCChannel channel = fixture->channel(i);

            QString property = QLCChannel::groupToString(channel.group());

            if (channel.group() == QLCChannel::Intensity &&
                channel.colour() != QLCChannel::NoColour)
            {
                property = QLCChannel::colourToString(channel.colour());
            }

            if (groups.contains(property) == false)
                groups.append(property);
        }
    }

    group = QInputDialog::getItem(this,
                                  tr("Select channels by group"),
                                  tr("Select a channel group"),
                                  groups, 0,
                                  false, &ok);

    if (ok == true)
        levelSelectChannelsByGroup(group);
}

void VCSliderProperties::slotItemExpanded()
{
    m_levelList->resizeColumnToContents(KColumnName);
    m_levelList->resizeColumnToContents(KColumnType);
}

/*****************************************************************************
 * Playback page
 *****************************************************************************/

void VCSliderProperties::slotAttachPlaybackFunctionClicked()
{
    FunctionSelection fs(this, m_doc);
    fs.setMultiSelection(false);
    fs.setFilter(Function::Scene | Function::Chaser | Function::EFX | Function::Audio | Function::RGBMatrix
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
                 | Function::Video
#endif
                 , true);

    if (fs.exec() != QDialog::Accepted)
        return;

    if (fs.selection().size() == 0)
        return;

    m_playbackFunctionId = fs.selection().first();
    updatePlaybackFunctionName();
}

void VCSliderProperties::slotDetachPlaybackFunctionClicked()
{
    m_playbackFunctionId = Function::invalidId();
    updatePlaybackFunctionName();
}

void VCSliderProperties::updatePlaybackFunctionName()
{
    Function* function = m_doc->function(m_playbackFunctionId);
    if (function != NULL)
    {
        m_playbackFunctionEdit->setText(function->name());
        if (m_nameEdit->text().simplified().isEmpty() == true)
            m_nameEdit->setText(function->name());
    }
    else
    {
        m_playbackFunctionId = Function::invalidId(); // Ensure
        m_playbackFunctionEdit->setText(tr("No function"));
    }
}

/*****************************************************************************
 * OK & Cancel
 *****************************************************************************/

void VCSliderProperties::checkMajorColor(int *comp, int *max, int type)
{
    if (*comp > *max)
    {
        *max = *comp;
        m_slider->setClickAndGoType((ClickAndGoWidget::ClickAndGo)type);
    }
}

void VCSliderProperties::storeLevelChannels()
{
    int red = 0, green = 0, blue = 0;
    int cyan = 0, magenta = 0, yellow = 0, amber = 0, white = 0, uv = 0;
    int majorColor = 0;
    /* Clear all channels from the slider first */
    m_slider->clearLevelChannels();

    /* Go thru all fixtures and their channels, add checked channels */
    for (int i = 0; i < m_levelList->topLevelItemCount(); i++)
    {
        QTreeWidgetItem* fxi_item = m_levelList->topLevelItem(i);
        Q_ASSERT(fxi_item != NULL);

        quint32 fxi_id = fxi_item->text(KColumnID).toUInt();
        Fixture *fxi = m_doc->fixture(fxi_id);

        for (int j = 0; j < fxi_item->childCount(); j++)
        {
            QTreeWidgetItem* ch_item = fxi_item->child(j);
            Q_ASSERT(ch_item != NULL);

            if (ch_item->checkState(KColumnName) == Qt::Checked)
            {
                quint32 ch_num = ch_item->text(KColumnID).toUInt();
                if (fxi != NULL)
                {
                    const QLCChannel *ch = fxi->channel(ch_num);
                    if (ch->group() == QLCChannel::Intensity &&
                        m_cngColorCheck->isChecked())
                    {
                        if (ch->colour() == QLCChannel::Red)
                        {
                            red++;
                            checkMajorColor(&red, &majorColor, ClickAndGoWidget::Red);
                        }
                        else if (ch->colour() == QLCChannel::Green)
                        {
                            green++;
                            checkMajorColor(&green, &majorColor, ClickAndGoWidget::Green);
                        }
                        else if (ch->colour() == QLCChannel::Blue)
                        {
                            blue++;
                            checkMajorColor(&blue, &majorColor, ClickAndGoWidget::Blue);
                        }
                        else if (ch->colour() == QLCChannel::Cyan)
                        {
                            cyan++;
                            checkMajorColor(&cyan, &majorColor, ClickAndGoWidget::Cyan);
                        }
                        else if (ch->colour() == QLCChannel::Magenta)
                        {
                            magenta++;
                            checkMajorColor(&magenta, &majorColor, ClickAndGoWidget::Magenta);
                        }
                        else if (ch->colour() == QLCChannel::Yellow)
                        {
                            yellow++;
                            checkMajorColor(&yellow, &majorColor, ClickAndGoWidget::Yellow);
                        }
                        else if (ch->colour() == QLCChannel::Amber)
                        {
                            amber++;
                            checkMajorColor(&amber, &majorColor, ClickAndGoWidget::Amber);
                        }
                        else if (ch->colour() == QLCChannel::White)
                        {
                            white++;
                            checkMajorColor(&white, &majorColor, ClickAndGoWidget::White);
                        }
                        else if (ch->colour() == QLCChannel::UV)
                        {
                            uv++;
                            checkMajorColor(&uv, &majorColor, ClickAndGoWidget::UV);
                        }
                    }
                }
                m_slider->addLevelChannel(fxi_id, ch_num);
            }
        }
    }
}

void VCSliderProperties::accept()
{
    /* Widget appearance */
    if (m_widgetKnobRadio->isChecked())
        m_slider->setWidgetStyle(VCSlider::WKnob);
    else
        m_slider->setWidgetStyle(VCSlider::WSlider);

    /* Level page */
    bool limitDiff =
        (m_slider->levelLowLimit() != m_levelLowLimitSpin->value()) ||
        (m_slider->levelHighLimit() != m_levelLowLimitSpin->value());
    m_slider->setLevelLowLimit(m_levelLowLimitSpin->value());
    m_slider->setLevelHighLimit(m_levelHighLimitSpin->value());
    storeLevelChannels();

    /* Click & Go group */
    /* Color doesn't have a case cause it is calculated
     * in storeLevelChannels */
    if (m_cngNoneCheck->isChecked())
        m_slider->setClickAndGoType(ClickAndGoWidget::None);
    else if (m_cngRGBCheck->isChecked())
        m_slider->setClickAndGoType(ClickAndGoWidget::RGB);
    else if (m_cngCMYCheck->isChecked())
        m_slider->setClickAndGoType(ClickAndGoWidget::CMY);
    else if (m_cngPresetCheck->isChecked())
        m_slider->setClickAndGoType(ClickAndGoWidget::Preset);

    /* Playback page */
    m_slider->setPlaybackFunction(m_playbackFunctionId);

    /* Slider mode */
    if (m_slider->sliderMode() != m_sliderMode)
    {
        m_slider->setSliderMode(VCSlider::SliderMode(m_sliderMode));
        if (m_slider->sliderMode() == VCSlider::Submaster)
        {
            m_slider->setLevelValue(UCHAR_MAX);
            m_slider->setSliderValue(UCHAR_MAX);
        }
    }
    else if (limitDiff && m_slider->sliderMode() == VCSlider::Level)
    {
        // Force the refresh of the slider range
        m_slider->setSliderMode(VCSlider::Level);
    }

    if (m_slider->sliderMode() == VCSlider::Level)
        m_slider->setChannelsMonitorEnabled(m_monitorValuesCheck->isChecked());

    m_slider->setCaption(m_nameEdit->text());

    /* Value style */
    if (m_valueExactRadio->isChecked() == true)
        m_slider->setValueDisplayStyle(VCSlider::ExactValue);
    else
        m_slider->setValueDisplayStyle(VCSlider::PercentageValue);

    /* Slider movement */
    if (m_sliderMovementNormalRadio->isChecked() == true)
        m_slider->setInvertedAppearance(false);
    else
        m_slider->setInvertedAppearance(true);

    /* External input */
    m_slider->setInputSource(m_inputSource);

    /* Close dialog */
    QDialog::accept();
}


text:
define(['jquery', 'main/extension', 'main/config'], function ($, ext, cf) {
    'use strict';
    var identifier;
    var config = cf.init();

    var init = function (wrapper, util, params, callback) {
        identifier = params.identifier;
        window.dnn.initThemes = function () {
            return {
                utility: util,
                params: params,
                moduleName: "Themes"
            };
        };

        util.loadBundleScript('modules/dnn.themes/scripts/bundles/themes-bundle.js');

        if (typeof callback === 'function') {
            callback();
        }
    };

    var load = function (params, callback) {
        if (typeof callback === 'function') {
            callback();
        }
    };

    return {
        init: init,
        load: load
    };
});


text:
<?php

namespace Innmind\AppBundle\DependencyInjection\Security\Factory;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\DefinitionDecorator;
use Symfony\Component\Config\Definition\Builder\NodeDefinition;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\SecurityFactoryInterface;

class ServerFactory implements SecurityFactoryInterface
{
    public function create(ContainerBuilder $container, $id, $config, $userProvider, $defaultEntryPoint)
    {
        $providerId = 'security.authentication.provider.server.'.$id;
        $container
            ->setDefinition(
                $providerId,
                new DefinitionDecorator('server.security.authentication.provider')
            )
            ->replaceArgument(0, new Reference($userProvider));

        $listenerId = 'security.authentication.listener.server.'.$id;
        $container->setDefinition(
            $listenerId,
            new DefinitionDecorator('server.security.authentication.listener')
        );

        return array($providerId, $listenerId, $defaultEntryPoint);
    }

    public function getPosition()
    {
        return 'pre_auth';
    }

    public function getKey()
    {
        return 'server';
    }

    public function addConfiguration(NodeDefinition $node)
    {
    }
}


text:
import YAML
config = YAML.load(open("config.yaml"))

# Points at which to create images
parameters = readdlm("parameters.dat")

parnames = config["emulator"]["parameters"]

npoints = size(parameters, 1)

using DiskJockey.constants
using DiskJockey.model
using DiskJockey.visibilities
using DiskJockey.image
using HDF5

import PyPlot.plt
using LaTeXStrings

cmap = plt[:get_cmap]("plasma")

grd = config["grid"]
grid = Grid(grd)

# Load the parameters file from the configuration setting, and make this an object.
pars = convert_dict(config["parameters"], config["model"])
vel = pars.vel # [km/s]
npix = config["npix"] # number of pixels
species = config["species"]
transition = config["transition"]
lam0 = lam0s[species*transition]
model = config["model"]

# Figure out how many plots we'll have.
ncols = 8
nrows = ceil(Int, npoints/ncols)

xx = 1.5 * 9
dx = 1.5
yy = (nrows + 1) * 1.5
dy = 1.5

fig, ax = plt[:subplots](nrows=nrows, ncols=ncols, figsize=(xx, yy))

for row=1:nrows
    for col=1:ncols
        iframe = col + (row - 1) * ncols

        if iframe > npoints
          # ax[row, col][:imshow](zeros((im_ny, im_nx)), cmap=cmap, vmin=0, vmax=20, extent=ext, origin="lower")
          continue
        else

          image = @sprintf("image_%3.3i.out", iframe)

          println(row, " ", col, " ", iframe)

          nu, incl = parameters[iframe,:]

          # Load image into SkyImage
          img = imread("images/" * image)
          pars.incl = incl
          skim = imToSky(img, pars.dpc)

          vvmax = maxabs(img.data)
          norm = PyPlot.matplotlib[:colors][:Normalize](0, vvmax)

          # Image needs to be flipped along RA dimension
          ext = (skim.ra[end], skim.ra[1], skim.dec[1], skim.dec[end])

          if col != 1 || row != nrows
              ax[row, col][:xaxis][:set_ticklabels]([])
              ax[row, col][:yaxis][:set_ticklabels]([])
          else
              ax[row, col][:set_xlabel](L"$\Delta \alpha$ ('')")
              ax[row, col][:set_ylabel](L"$\Delta \delta$ ('')")
          end

          #Flip the frame for Sky convention
          frame = flipdim(img.data[:,:,1], 2)

          ax[row, col][:imshow](frame, extent=ext, interpolation="none", origin="lower", cmap=cmap, norm=norm)
        end

    end
end

fig[:subplots_adjust](hspace=0.00, wspace=0.00, top=(yy - 0.5 * dy)/yy, bottom=(0.5 * dy)/yy, left=(0.5 * dx)/xx, right=(xx - 0.5 * dy)/xx)
plt[:savefig]("chmaps_all_params.png", dpi=600)


text:
const sf::Texture	&MyTexture::getGameSelectCurs(void)const
{
  return (this->_game_select_curs);
}

const sf::Texture	&MyTexture::getGameAttackCurs(void)const
{
  return (this->_game_attack_curs);
}

const sf::Texture	&MyTexture::getGameMoveFog(void)const
{
  return (this->_game_move_fog);
}

const sf::Texture	&MyTexture::getGameAttackFog(void)const
{
  return (this->_game_select_attack_fog);
}

const sf::Texture	&MyTexture::getGameVisuFog(void)const
{
  return (this->_game_visu_fog);
}

const sf::Texture	&MyTexture::getGameRedBack(void)const
{
  return (this->_game_red_back);
}

const sf::Texture	&MyTexture::getGameBlueBack(void)const
{
  return (this->_game_blue_back);
}

const sf::Texture	&MyTexture::getGameRightBack(void)const
{
  return (this->_game_right_back);
}

const sf::Texture	&MyTexture::getGameLeftBack(void)const
{
  return (this->_game_left_back);
}