text:
package org.springframework.boot.autoconfigure.web.servlet;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import jakarta.servlet.Filter;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;

import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.boot.autoconfigure.session.SessionAutoConfiguration;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.boot.testsupport.web.servlet.MockServletWebServer.RegisteredFilter;
import org.springframework.boot.web.server.WebServerFactoryCustomizerBeanPostProcessor;
import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext;
import org.springframework.boot.web.servlet.filter.OrderedCharacterEncodingFilter;
import org.springframework.boot.web.servlet.filter.OrderedRequestContextFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.session.MapSessionRepository;
import org.springframework.session.config.annotation.web.http.EnableSpringHttpSession;
import org.springframework.session.web.http.SessionRepositoryFilter;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;

/**
 * Integration tests that verify the ordering of various filters that are auto-configured.
 *
 * @author Andy Wilkinson
 * @author Eddú Meléndez
 */
class FilterOrderingIntegrationTests {

	private AnnotationConfigServletWebServerApplicationContext context;

	@AfterEach
	void cleanup() {
		if (this.context != null) {
			this.context.close();
		}
	}

	@Test
	void testFilterOrdering() {
		load();
		List<RegisteredFilter> registeredFilters = this.context.getBean(MockServletWebServerFactory.class)
				.getWebServer().getRegisteredFilters();
		List<Filter> filters = new ArrayList<>(registeredFilters.size());
		for (RegisteredFilter registeredFilter : registeredFilters) {
			filters.add(registeredFilter.getFilter());
		}
		Iterator<Filter> iterator = filters.iterator();
		assertThat(iterator.next()).isInstanceOf(OrderedCharacterEncodingFilter.class);
		assertThat(iterator.next()).isInstanceOf(SessionRepositoryFilter.class);
		assertThat(iterator.next()).isInstanceOf(Filter.class);
		assertThat(iterator.next()).isInstanceOf(Filter.class);
		assertThat(iterator.next()).isInstanceOf(OrderedRequestContextFilter.class);
		assertThat(iterator.next()).isInstanceOf(FilterChainProxy.class);
	}

	private void load() {
		this.context = new AnnotationConfigServletWebServerApplicationContext();
		this.context.register(MockWebServerConfiguration.class, TestSessionConfiguration.class,
				TestRedisConfiguration.class, WebMvcAutoConfiguration.class, SecurityAutoConfiguration.class,
				SessionAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class,
				PropertyPlaceholderAutoConfiguration.class, HttpEncodingAutoConfiguration.class);
		TestPropertyValues.of("spring.mvc.hiddenmethod.filter.enabled:true").applyTo(this.context);
		this.context.refresh();
	}

	@Configuration(proxyBeanMethods = false)
	static class MockWebServerConfiguration {

		@Bean
		MockServletWebServerFactory webServerFactory() {
			return new MockServletWebServerFactory();
		}

		@Bean
		WebServerFactoryCustomizerBeanPostProcessor ServletWebServerCustomizerBeanPostProcessor() {
			return new WebServerFactoryCustomizerBeanPostProcessor();
		}

	}

	@Configuration(proxyBeanMethods = false)
	@EnableSpringHttpSession
	static class TestSessionConfiguration {

		@Bean
		MapSessionRepository mapSessionRepository() {
			return new MapSessionRepository(new ConcurrentHashMap<>());
		}

	}

	@Configuration(proxyBeanMethods = false)
	static class TestRedisConfiguration {

		@Bean
		RedisConnectionFactory redisConnectionFactory() {
			RedisConnectionFactory connectionFactory = mock(RedisConnectionFactory.class);
			RedisConnection connection = mock(RedisConnection.class);
			given(connectionFactory.getConnection()).willReturn(connection);
			return connectionFactory;
		}

	}

}


text:
"""SVDF model with Mel spectrum and fully connected layers."""
from kws_streaming.layers import modes
from kws_streaming.layers import speech_features
from kws_streaming.layers import stream
from kws_streaming.layers import svdf
from kws_streaming.layers.compat import tf
import kws_streaming.models.model_utils as utils

def model_parameters(parser_nn):
  """SVDF model parameters."""

  parser_nn.add_argument(
      '--svdf_memory_size',
      type=str,
      default='4,10,10,10,10,10',
      help='Number of time steps to keep in memory (time dim) in svdf layers',
  )
  parser_nn.add_argument(
      '--svdf_units1',
      type=str,
      default='256,256,256,256,256,256',
      help='Number of units (feature dim) in the first part of svdf layers',
  )
  parser_nn.add_argument(
      '--svdf_act',
      type=str,
      default="'relu','relu','relu','relu','relu','relu'",
      help='Activation functions in svdf modules',
  )
  parser_nn.add_argument(
      '--svdf_units2',
      type=str,
      default='128,128,128,128,128,-1',
      help='Number of units (feature dim) in projection op of svdf layers',
  )
  parser_nn.add_argument(
      '--svdf_dropout',
      type=str,
      default='0.0,0.0,0.0,0.0,0.0,0.0',
      help='Percentage of data dropped in svdf layers',
  )
  parser_nn.add_argument(
      '--svdf_pad',
      type=int,
      default=0,
      help='If 1, causal pad svdf input data with zeros, else valid pad',
  )
  parser_nn.add_argument(
      '--dropout1',
      type=float,
      default=0.0,
      help='Percentage of data dropped after svdf layers',
  )
  parser_nn.add_argument(
      '--units2',
      type=str,
      default='',
      help='Number of units in the last set of hidden layers',
  )
  parser_nn.add_argument(
      '--act2',
      type=str,
      default='',
      help='Activation function of the last set of hidden layers',
  )

def model(flags):
  """SVDF model.

  This model is based on decomposition of a densely connected ops
  into low rank filters.
  It is based on paper
  END-TO-END STREAMING KEYWORD SPOTTING https://arxiv.org/pdf/1812.02802.pdf
  Args:
    flags: data/model parameters

  Returns:
    Keras model for training
  """

  input_audio = tf.keras.layers.Input(
      shape=modes.get_input_data_shape(flags, modes.Modes.TRAINING),
      batch_size=flags.batch_size)
  net = input_audio

  if flags.preprocess == 'raw':
    # it is a self contained model, user need to feed raw audio only
    net = speech_features.SpeechFeatures(
        speech_features.SpeechFeatures.get_params(flags))(
            net)

  # for streaming mode it is better to use causal padding
  padding = 'causal' if flags.svdf_pad else 'valid'

  for i, (units1, memory_size, units2, dropout, activation) in enumerate(
      zip(
          utils.parse(flags.svdf_units1), utils.parse(flags.svdf_memory_size),
          utils.parse(flags.svdf_units2), utils.parse(flags.svdf_dropout),
          utils.parse(flags.svdf_act))):
    net = svdf.Svdf(
        units1=units1,
        memory_size=memory_size,
        units2=units2,
        dropout=dropout,
        activation=activation,
        pad=padding,
        name='svdf_%d' % i)(
            net)

  net = stream.Stream(cell=tf.keras.layers.Flatten())(net)
  net = tf.keras.layers.Dropout(rate=flags.dropout1)(net)

  for units, activation in zip(
      utils.parse(flags.units2), utils.parse(flags.act2)):
    net = tf.keras.layers.Dense(units=units, activation=activation)(net)

  net = tf.keras.layers.Dense(units=flags.label_count)(net)
  if flags.return_softmax:
    net = tf.keras.layers.Activation('softmax')(net)
  return tf.keras.Model(input_audio, net)

redpajama_set_name: RedPajamaGithub


text:
package org.kie.workbench.common.dmn.client.editors.expressions.types.invocation;

import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.IntStream;

import com.ait.lienzo.client.core.shape.Viewport;
import com.ait.lienzo.client.core.types.Transform;
import com.ait.lienzo.test.LienzoMockitoTestRunner;
import com.google.gwt.user.client.ui.AbsolutePanel;
import org.jboss.errai.ui.client.local.spi.TranslationService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.dmn.api.definition.HasExpression;
import org.kie.workbench.common.dmn.api.definition.HasName;
import org.kie.workbench.common.dmn.api.definition.NOPDomainObject;
import org.kie.workbench.common.dmn.api.definition.model.Decision;
import org.kie.workbench.common.dmn.api.definition.model.Invocation;
import org.kie.workbench.common.dmn.api.definition.model.LiteralExpression;
import org.kie.workbench.common.dmn.api.property.dmn.Name;
import org.kie.workbench.common.dmn.api.property.dmn.QName;
import org.kie.workbench.common.dmn.api.property.dmn.types.BuiltInType;
import org.kie.workbench.common.dmn.client.commands.expressions.types.invocation.AddParameterBindingCommand;
import org.kie.workbench.common.dmn.client.commands.expressions.types.invocation.ClearExpressionTypeCommand;
import org.kie.workbench.common.dmn.client.commands.expressions.types.invocation.DeleteParameterBindingCommand;
import org.kie.workbench.common.dmn.client.commands.factory.DefaultCanvasCommandFactory;
import org.kie.workbench.common.dmn.client.commands.general.DeleteCellValueCommand;
import org.kie.workbench.common.dmn.client.commands.general.DeleteHasValueCommand;
import org.kie.workbench.common.dmn.client.commands.general.DeleteHeaderValueCommand;
import org.kie.workbench.common.dmn.client.commands.general.SetCellValueCommand;
import org.kie.workbench.common.dmn.client.commands.general.SetHasValueCommand;
import org.kie.workbench.common.dmn.client.commands.general.SetHeaderValueCommand;
import org.kie.workbench.common.dmn.client.commands.general.SetTypeRefCommand;
import org.kie.workbench.common.dmn.client.editors.expressions.types.ExpressionEditorDefinition;
import org.kie.workbench.common.dmn.client.editors.expressions.types.ExpressionEditorDefinitions;
import org.kie.workbench.common.dmn.client.editors.expressions.types.GridFactoryCommandUtils;
import org.kie.workbench.common.dmn.client.editors.expressions.types.context.ExpressionCellValue;
import org.kie.workbench.common.dmn.client.editors.expressions.types.context.ExpressionEditorColumn;
import org.kie.workbench.common.dmn.client.editors.expressions.types.context.InformationItemCell;
import org.kie.workbench.common.dmn.client.editors.expressions.types.undefined.UndefinedExpressionColumn;
import org.kie.workbench.common.dmn.client.editors.expressions.types.undefined.UndefinedExpressionEditorDefinition;
import org.kie.workbench.common.dmn.client.editors.expressions.types.undefined.UndefinedExpressionGrid;
import org.kie.workbench.common.dmn.client.editors.types.HasValueAndTypeRef;
import org.kie.workbench.common.dmn.client.editors.types.ValueAndDataTypePopoverView;
import org.kie.workbench.common.dmn.client.resources.i18n.DMNEditorConstants;
import org.kie.workbench.common.dmn.client.session.DMNSession;
import org.kie.workbench.common.dmn.client.widgets.grid.BaseExpressionGrid;
import org.kie.workbench.common.dmn.client.widgets.grid.columns.factory.TextAreaSingletonDOMElementFactory;
import org.kie.workbench.common.dmn.client.widgets.grid.columns.factory.TextBoxSingletonDOMElementFactory;
import org.kie.workbench.common.dmn.client.widgets.grid.controls.container.CellEditorControlsView;
import org.kie.workbench.common.dmn.client.widgets.grid.controls.list.HasListSelectorControl;
import org.kie.workbench.common.dmn.client.widgets.grid.controls.list.ListSelectorView;
import org.kie.workbench.common.dmn.client.widgets.grid.model.DMNGridColumn;
import org.kie.workbench.common.dmn.client.widgets.grid.model.ExpressionEditorChanged;
import org.kie.workbench.common.dmn.client.widgets.grid.model.GridCellTuple;
import org.kie.workbench.common.dmn.client.widgets.grid.model.GridCellValueTuple;
import org.kie.workbench.common.dmn.client.widgets.layer.DMNGridLayer;
import org.kie.workbench.common.dmn.client.widgets.panel.DMNGridPanel;
import org.kie.workbench.common.stunner.core.client.api.SessionManager;
import org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvasHandler;
import org.kie.workbench.common.stunner.core.client.canvas.command.UpdateElementPropertyCommand;
import org.kie.workbench.common.stunner.core.client.canvas.event.selection.DomainObjectSelectionEvent;
import org.kie.workbench.common.stunner.core.client.command.SessionCommandManager;
import org.kie.workbench.common.stunner.core.command.impl.CompositeCommand;
import org.kie.workbench.common.stunner.core.diagram.Diagram;
import org.kie.workbench.common.stunner.core.domainobject.DomainObject;
import org.kie.workbench.common.stunner.core.graph.Element;
import org.kie.workbench.common.stunner.core.graph.Graph;
import org.kie.workbench.common.stunner.core.graph.Node;
import org.kie.workbench.common.stunner.core.graph.command.GraphCommandExecutionContext;
import org.kie.workbench.common.stunner.core.graph.content.definition.Definition;
import org.kie.workbench.common.stunner.core.graph.processing.index.Index;
import org.kie.workbench.common.stunner.core.util.DefinitionUtils;
import org.kie.workbench.common.stunner.forms.client.event.RefreshFormPropertiesEvent;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.uberfire.ext.wires.core.grids.client.model.GridColumn;
import org.uberfire.ext.wires.core.grids.client.model.GridData;
import org.uberfire.ext.wires.core.grids.client.model.impl.BaseBounds;
import org.uberfire.ext.wires.core.grids.client.model.impl.BaseGridCellValue;
import org.uberfire.ext.wires.core.grids.client.model.impl.BaseGridData;
import org.uberfire.ext.wires.core.grids.client.model.impl.BaseGridRow;
import org.uberfire.ext.wires.core.grids.client.widget.dnd.GridWidgetDnDHandlersState;
import org.uberfire.ext.wires.core.grids.client.widget.grid.GridWidget;
import org.uberfire.ext.wires.core.grids.client.widget.grid.columns.RowNumberColumn;
import org.uberfire.ext.wires.core.grids.client.widget.layer.impl.GridLayerRedrawManager;
import org.uberfire.mocks.EventSourceMock;
import org.uberfire.mvp.Command;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(LienzoMockitoTestRunner.class)
public class InvocationGridTest {

    private final static int HEADER = 0;

    private final static int INSERT_PARAMETER = 1;

    private final static int INSERT_PARAMETER_ABOVE = 1;

    private final static int INSERT_PARAMETER_BELOW = 2;

    private final static int DELETE_PARAMETER = 3;

    private final static int DIVIDER = 4;

    private final static int CLEAR_EXPRESSION_TYPE = 5;

    private static final String NODE_UUID = "uuid";

    private static final String NAME = "name";

    private static final String NAME_NEW = "name-new";

    private static final String EXPRESSION_TEXT_NEW = "invocation-expression-new";

    private GridCellTuple tupleWithoutValue;

    private GridCellValueTuple tupleWithValue;

    @Mock
    private Viewport viewport;

    @Mock
    private Transform transform;

    @Mock
    private DMNGridPanel gridPanel;

    @Mock
    private DMNGridLayer gridLayer;

    @Mock
    private AbsolutePanel gridLayerDomElementContainer;

    @Mock
    private GridWidget gridWidget;

    @Mock
    private DefinitionUtils definitionUtils;

    @Mock
    private SessionManager sessionManager;

    @Mock
    private DMNSession session;

    @Mock
    private AbstractCanvasHandler canvasHandler;

    @Mock
    private Diagram diagram;

    @Mock
    private Graph graph;

    @Mock
    private Node node;

    @Mock
    private Index index;

    @Mock
    private Element element;

    @Mock
    private GraphCommandExecutionContext graphContext;

    @Mock
    private SessionCommandManager<AbstractCanvasHandler> sessionCommandManager;

    @Mock
    private DefaultCanvasCommandFactory canvasCommandFactory;

    @Mock
    private CellEditorControlsView.Presenter cellEditorControls;

    @Mock
    private ListSelectorView.Presenter listSelector;

    @Mock
    private TranslationService translationService;

    @Mock
    private Supplier<ExpressionEditorDefinitions> expressionEditorDefinitionsSupplier;

    @Mock
    private ValueAndDataTypePopoverView.Presenter headerEditor;

    @Mock
    private GridWidget parentGridWidget;

    @Mock
    private GridData parentGridData;

    @Mock
    private GridColumn parentGridColumn;

    @Mock
    private GridCellTuple parent;

    @Mock
    private ExpressionEditorDefinition literalExpressionEditorDefinition;

    @Mock
    private BaseExpressionGrid literalExpressionEditor;

    @Mock
    private UndefinedExpressionEditorDefinition undefinedExpressionEditorDefinition;

    @Mock
    private UndefinedExpressionGrid undefinedExpressionEditor;

    @Mock
    private GridWidgetDnDHandlersState dndHandlersState;

    @Mock
    private EventSourceMock<ExpressionEditorChanged> editorSelectedEvent;

    @Mock
    private EventSourceMock<RefreshFormPropertiesEvent> refreshFormPropertiesEvent;

    @Mock
    private EventSourceMock<DomainObjectSelectionEvent> domainObjectSelectionEvent;

    @Captor
    private ArgumentCaptor<AddParameterBindingCommand> addParameterBindingCommandCaptor;

    @Captor
    private ArgumentCaptor<DeleteParameterBindingCommand> deleteParameterBindingCommandCaptor;

    @Captor
    private ArgumentCaptor<ClearExpressionTypeCommand> clearExpressionTypeCommandCaptor;

    @Captor
    private ArgumentCaptor<GridLayerRedrawManager.PrioritizedCommand> redrawCommandCaptor;

    @Captor
    private ArgumentCaptor<CompositeCommand> compositeCommandCaptor;

    @Captor
    private ArgumentCaptor<DomainObjectSelectionEvent> domainObjectSelectionEventCaptor;

    private Decision hasExpression = new Decision();

    private LiteralExpression literalExpression = new LiteralExpression();

    private Optional<Invocation> expression = Optional.empty();

    private Optional<HasName> hasName = Optional.empty();

    private InvocationEditorDefinition definition;

    private InvocationGrid grid;

    @Before
    @SuppressWarnings("unchecked")
    public void setup() {
        when(parent.getGridWidget()).thenReturn(parentGridWidget);
        when(parentGridWidget.getModel()).thenReturn(parentGridData);
        when(parentGridData.getColumns()).thenReturn(Collections.singletonList(parentGridColumn));

        when(sessionManager.getCurrentSession()).thenReturn(session);
        when(session.getGridPanel()).thenReturn(gridPanel);
        when(session.getGridLayer()).thenReturn(gridLayer);
        when(session.getCellEditorControls()).thenReturn(cellEditorControls);

        tupleWithoutValue = new GridCellTuple(0, 1, gridWidget);
        tupleWithValue = new GridCellValueTuple<>(0, 1, gridWidget, new BaseGridCellValue<>("value"));

        definition = new InvocationEditorDefinition(definitionUtils,
                                                    sessionManager,
                                                    sessionCommandManager,
                                                    canvasCommandFactory,
                                                    editorSelectedEvent,
                                                    refreshFormPropertiesEvent,
                                                    domainObjectSelectionEvent,
                                                    listSelector,
                                                    translationService,
                                                    expressionEditorDefinitionsSupplier,
                                                    headerEditor);

        expression = definition.getModelClass();
        definition.enrich(Optional.empty(), hasExpression, expression);
        expression.ifPresent(invocation -> ((LiteralExpression) invocation.getExpression()).getText().setValue("invocation-expression"));
        final ExpressionEditorDefinitions expressionEditorDefinitions = new ExpressionEditorDefinitions();
        expressionEditorDefinitions.add((ExpressionEditorDefinition) definition);
        expressionEditorDefinitions.add(literalExpressionEditorDefinition);
        expressionEditorDefinitions.add(undefinedExpressionEditorDefinition);

        when(expressionEditorDefinitionsSupplier.get()).thenReturn(expressionEditorDefinitions);
        when(literalExpressionEditorDefinition.getModelClass()).thenReturn(Optional.of(literalExpression));
        when(literalExpressionEditorDefinition.getEditor(any(GridCellTuple.class),
                                                         any(Optional.class),
                                                         any(HasExpression.class),
                                                         any(Optional.class),
                                                         anyBoolean(),
                                                         anyInt())).thenReturn(Optional.of(literalExpressionEditor));

        when(undefinedExpressionEditor.getParentInformation()).thenReturn(parent);
        when(undefinedExpressionEditorDefinition.getModelClass()).thenReturn(Optional.empty());
        when(undefinedExpressionEditorDefinition.getEditor(any(GridCellTuple.class),
                                                           any(Optional.class),
                                                           any(HasExpression.class),
                                                           any(Optional.class),
                                                           anyBoolean(),
                                                           anyInt())).thenReturn(Optional.of(undefinedExpressionEditor));

        when(sessionManager.getCurrentSession()).thenReturn(session);
        when(session.getCanvasHandler()).thenReturn(canvasHandler);
        when(canvasHandler.getGraphExecutionContext()).thenReturn(graphContext);

        final Decision decision = new Decision();
        decision.setName(new Name("name"));
        hasName = Optional.of(decision);

        when(gridWidget.getModel()).thenReturn(new BaseGridData(false));
        when(gridLayer.getDomElementContainer()).thenReturn(gridLayerDomElementContainer);
        when(gridLayerDomElementContainer.iterator()).thenReturn(mock(Iterator.class));
        when(gridLayer.getVisibleBounds()).thenReturn(new BaseBounds(0, 0, 100, 200));
        when(gridLayer.getViewport()).thenReturn(viewport);
        when(viewport.getTransform()).thenReturn(transform);

        when(canvasHandler.getDiagram()).thenReturn(diagram);
        when(diagram.getGraph()).thenReturn(graph);
        when(graph.nodes()).thenReturn(Collections.singletonList(node));

        when(canvasHandler.getGraphIndex()).thenReturn(index);
        when(index.get(anyString())).thenReturn(element);
        when(element.getContent()).thenReturn(mock(Definition.class));
        when(definitionUtils.getNameIdentifier(any())).thenReturn("name");
        when(canvasCommandFactory.updatePropertyValue(any(Element.class),
                                                      anyString(),
                                                      any())).thenReturn(mock(UpdateElementPropertyCommand.class));

        doAnswer((i) -> i.getArguments()[0].toString()).when(translationService).format(anyString());
        doAnswer((i) -> i.getArguments()[0].toString()).when(translationService).getTranslation(anyString());
    }

    private void setupGrid(final int nesting) {
        this.hasExpression.setExpression(expression.get());
        this.grid = spy((InvocationGrid) definition.getEditor(parent,
                                                              nesting == 0 ? Optional.of(NODE_UUID) : Optional.empty(),
                                                              hasExpression,
                                                              hasName,
                                                              false,
                                                              nesting).get());

        when(parent.getGridWidget()).thenReturn(gridWidget);
        when(parent.getRowIndex()).thenReturn(0);
        when(parent.getColumnIndex()).thenReturn(2);
    }

    @Test
    public void testInitialSetupFromDefinition() {
        setupGrid(0);

        final GridData uiModel = grid.getModel();
        assertTrue(uiModel instanceof InvocationGridData);

        assertEquals(3,
                     uiModel.getColumnCount());
        assertTrue(uiModel.getColumns().get(0) instanceof RowNumberColumn);
        assertTrue(uiModel.getColumns().get(1) instanceof InvocationParameterColumn);
        assertTrue(uiModel.getColumns().get(2) instanceof ExpressionEditorColumn);

        assertEquals(1,
                     uiModel.getRowCount());

        assertEquals(1,
                     uiModel.getCell(0, 0).getValue().getValue());
        assertEquals(InvocationDefaultValueUtilities.PREFIX + "1",
                     ((InformationItemCell.HasNameAndDataTypeCell) uiModel.getCell(0, 1).getValue().getValue()).getName().getValue());
        assertTrue(uiModel.getCell(0, 2).getValue() instanceof ExpressionCellValue);
        final ExpressionCellValue dcv0 = (ExpressionCellValue) uiModel.getCell(0, 2).getValue();
        assertEquals(undefinedExpressionEditor,
                     dcv0.getValue().get());
    }

    @Test
    public void testInitialColumnWidthsFromDefinition() {
        setupGrid(0);

        assertComponentWidths(50.0,
                              DMNGridColumn.DEFAULT_WIDTH,
                              UndefinedExpressionColumn.DEFAULT_WIDTH);
    }

    @Test
    public void testInitialColumnWidthsFromExpression() {
        final List<Double> componentWidths = expression.get().getComponentWidths();
        componentWidths.set(0, 100.0);
        componentWidths.set(1, 200.0);
        componentWidths.set(2, 300.0);

        setupGrid(0);

        assertComponentWidths(100.0,
                              200.0,
                              300.0);
    }

    private void assertComponentWidths(final double... widths) {
        final GridData uiModel = grid.getModel();
        IntStream.range(0, widths.length).forEach(i -> assertEquals(widths[i], uiModel.getColumns().get(i).getWidth(), 0.0));
    }

    @Test
    public void testCacheable() {
        setupGrid(0);

        assertTrue(grid.isCacheable());
    }

    @Test
    public void testNameColumnMetaData() {
        setupGrid(0);

        final GridColumn<?> column = grid.getModel().getColumns().get(InvocationUIModelMapper.BINDING_PARAMETER_COLUMN_INDEX);
        final List<GridColumn.HeaderMetaData> header = column.getHeaderMetaData();

        assertEquals(2,
                     header.size());
        assertTrue(header.get(0) instanceof InvocationColumnHeaderMetaData);
        assertTrue(header.get(1) instanceof InvocationColumnExpressionHeaderMetaData);

        final InvocationColumnHeaderMetaData md1 = (InvocationColumnHeaderMetaData) header.get(0);
        final InvocationColumnExpressionHeaderMetaData md2 = (InvocationColumnExpressionHeaderMetaData) header.get(1);

        assertEquals("name",
                     md1.getTitle());
        assertEquals("invocation-expression",
                     md2.getTitle());
    }

    @Test
    public void testNameColumnMetaDataWhenNested() {
        setupGrid(1);

        final GridColumn<?> column = grid.getModel().getColumns().get(InvocationUIModelMapper.BINDING_PARAMETER_COLUMN_INDEX);
        final List<GridColumn.HeaderMetaData> header = column.getHeaderMetaData();

        assertEquals(1,
                     header.size());
        assertTrue(header.get(0) instanceof InvocationColumnExpressionHeaderMetaData);

        final InvocationColumnExpressionHeaderMetaData md1 = (InvocationColumnExpressionHeaderMetaData) header.get(0);

        assertEquals("invocation-expression",
                     md1.getTitle());
    }

    @Test
    public void testExpressionColumnMetaData() {
        setupGrid(0);

        final GridColumn<?> column = grid.getModel().getColumns().get(InvocationUIModelMapper.BINDING_EXPRESSION_COLUMN_INDEX);
        final List<GridColumn.HeaderMetaData> header = column.getHeaderMetaData();

        assertEquals(2,
                     header.size());
        assertTrue(header.get(0) instanceof InvocationColumnHeaderMetaData);
        assertTrue(header.get(1) instanceof InvocationColumnExpressionHeaderMetaData);

        final InvocationColumnHeaderMetaData md1 = (InvocationColumnHeaderMetaData) header.get(0);
        final InvocationColumnExpressionHeaderMetaData md2 = (InvocationColumnExpressionHeaderMetaData) header.get(1);

        assertEquals("name",
                     md1.getTitle());
        assertEquals("invocation-expression",
                     md2.getTitle());
    }

    @Test
    public void testExpressionColumnMetaDataWhenNested() {
        setupGrid(1);

        final GridColumn<?> column = grid.getModel().getColumns().get(InvocationUIModelMapper.BINDING_EXPRESSION_COLUMN_INDEX);
        final List<GridColumn.HeaderMetaData> header = column.getHeaderMetaData();

        assertEquals(1,
                     header.size());
        assertTrue(header.get(0) instanceof InvocationColumnExpressionHeaderMetaData);

        final InvocationColumnExpressionHeaderMetaData md1 = (InvocationColumnExpressionHeaderMetaData) header.get(0);

        assertEquals("invocation-expression",
                     md1.getTitle());
    }

    @Test
    public void testExpressionColumnMetaDataSetExpressionText() {
        setupGrid(0);

        final GridColumn<?> column = grid.getModel().getColumns().get(InvocationUIModelMapper.BINDING_EXPRESSION_COLUMN_INDEX);
        final List<GridColumn.HeaderMetaData> header = column.getHeaderMetaData();
        final InvocationColumnExpressionHeaderMetaData md2 = (InvocationColumnExpressionHeaderMetaData) header.get(1);

        md2.setTitle(EXPRESSION_TEXT_NEW);

        assertEquals(EXPRESSION_TEXT_NEW,
                     ((LiteralExpression) expression.get().getExpression()).getText().getValue());
    }

    @Test
    public void testGetItemsRowNumberColumn() {
        setupGrid(0);

        assertDefaultListItems(grid.getItems(0, 0), true);
    }

    @Test
    public void testOnItemSelectedNameColumn() {
        setupGrid(0);

        assertDefaultListItems(grid.getItems(0, 1), true);
    }

    @Test
    public void testOnItemSelectedExpressionColumnUndefinedExpressionType() {
        setupGrid(0);

        //The default model from ContextEditorDefinition has an undefined expression at (0, 2)
        assertDefaultListItems(grid.getItems(0, 2), true);
    }

    @Test
    public void testOnItemSelectedExpressionColumnDefinedExpressionType() {
        setupGrid(0);

        //Set an editor for expression at (0, 2)
        final BaseExpressionGrid editor = mock(BaseExpressionGrid.class);
        grid.getModel().setCellValue(0, 2, new ExpressionCellValue(Optional.of(editor)));

        final List<HasListSelectorControl.ListSelectorItem> items = grid.getItems(0, 2);

        assertThat(items.size()).isEqualTo(6);
        assertDefaultListItems(items.subList(0, 4), true);

        assertThat(items.get(DIVIDER)).isInstanceOf(HasListSelectorControl.ListSelectorDividerItem.class);
        assertListSelectorTextItem(items.get(CLEAR_EXPRESSION_TYPE),
                                   DMNEditorConstants.ExpressionEditor_Clear,
                                   true);

        ((HasListSelectorControl.ListSelectorTextItem) items.get(CLEAR_EXPRESSION_TYPE)).getCommand().execute();
        verify(cellEditorControls).hide();
        verify(sessionCommandManager).execute(eq(canvasHandler),
                                              any(ClearExpressionTypeCommand.class));
    }

    @Test
    public void testGetItemsWithCellSelectionsCoveringMultipleRows() {
        setupGrid(0);

        addParameterBinding(0);
        grid.getModel().selectCell(0, 0);
        grid.getModel().selectCell(1, 0);

        assertDefaultListItems(grid.getItems(0, 0), false);
    }

    @Test
    public void testOnItemSelectedExpressionColumnDefinedExpressionTypeWithCellSelectionsCoveringMultipleRows() {
        setupGrid(0);

        addParameterBinding(0);
        grid.getModel().selectCell(0, 0);
        grid.getModel().selectCell(1, 0);

        //Set an editor for expression at (0, 2)
        final BaseExpressionGrid editor = mock(BaseExpressionGrid.class);
        grid.getModel().setCellValue(0, 2, new ExpressionCellValue(Optional.of(editor)));

        final List<HasListSelectorControl.ListSelectorItem> items = grid.getItems(0, 2);

        assertThat(items.size()).isEqualTo(6);
        assertDefaultListItems(items.subList(0, 4), false);

        assertThat(items.get(DIVIDER)).isInstanceOf(HasListSelectorControl.ListSelectorDividerItem.class);
        assertListSelectorTextItem(items.get(CLEAR_EXPRESSION_TYPE),
                                   DMNEditorConstants.ExpressionEditor_Clear,
                                   false);
    }

    @Test
    public void testGetHeaderItemsRowNumberColumn() {
        setupGrid(0);

        assertDefaultHeaderListItems(grid.getHeaderItems(0, 0));
    }

    @Test
    public void testGetHeaderItemsNameColumn() {
        setupGrid(0);

        assertDefaultHeaderListItems(grid.getHeaderItems(0, 1));
    }

    @Test
    public void testGetHeaderItemsExpressionColumn() {
        setupGrid(0);

        assertDefaultHeaderListItems(grid.getHeaderItems(0, 2));
    }

    private void assertDefaultListItems(final List<HasListSelectorControl.ListSelectorItem> items,
                                        final boolean enabled) {
        assertThat(items.size()).isEqualTo(4);
        assertListSelectorHeaderItem(items.get(HEADER),
                                     DMNEditorConstants.InvocationEditor_Header);
        assertListSelectorTextItem(items.get(INSERT_PARAMETER_ABOVE),
                                   DMNEditorConstants.InvocationEditor_InsertParameterAbove,
                                   enabled);
        assertListSelectorTextItem(items.get(INSERT_PARAMETER_BELOW),
                                   DMNEditorConstants.InvocationEditor_InsertParameterBelow,
                                   enabled);
        assertListSelectorTextItem(items.get(DELETE_PARAMETER),
                                   DMNEditorConstants.InvocationEditor_DeleteParameter,
                                   enabled && grid.getModel().getRowCount() > 1);
    }

    private void assertListSelectorHeaderItem(final HasListSelectorControl.ListSelectorItem item,
                                              final String text) {
        assertThat(item).isInstanceOf(HasListSelectorControl.ListSelectorHeaderItem.class);
        final HasListSelectorControl.ListSelectorHeaderItem hi = (HasListSelectorControl.ListSelectorHeaderItem) item;
        assertThat(hi.getText()).isEqualTo(text);
    }

    private void assertListSelectorTextItem(final HasListSelectorControl.ListSelectorItem item,
                                            final String text,
                                            final boolean enabled) {
        assertThat(item).isInstanceOf(HasListSelectorControl.ListSelectorTextItem.class);
        final HasListSelectorControl.ListSelectorTextItem ti = (HasListSelectorControl.ListSelectorTextItem) item;
        assertThat(ti.getText()).isEqualTo(text);
        assertThat(ti.isEnabled()).isEqualTo(enabled);
    }

    private void assertDefaultHeaderListItems(final List<HasListSelectorControl.ListSelectorItem> items) {
        assertThat(items.size()).isEqualTo(2);
        assertListSelectorHeaderItem(items.get(HEADER),
                                     DMNEditorConstants.InvocationEditor_Header);
        assertListSelectorTextItem(items.get(INSERT_PARAMETER),
                                   DMNEditorConstants.InvocationEditor_InsertParameter,
                                   true);
    }

    @Test
    public void testOnItemSelected() {
        setupGrid(0);

        final Command command = mock(Command.class);
        final HasListSelectorControl.ListSelectorTextItem listSelectorItem = mock(HasListSelectorControl.ListSelectorTextItem.class);
        when(listSelectorItem.getCommand()).thenReturn(command);

        grid.onItemSelected(listSelectorItem);

        verify(command).execute();
    }

    @Test
    public void testOnItemSelectedInsertParameterAbove() {
        setupGrid(0);

        final List<HasListSelectorControl.ListSelectorItem> items = grid.getItems(0, 0);
        final HasListSelectorControl.ListSelectorTextItem ti = (HasListSelectorControl.ListSelectorTextItem) items.get(INSERT_PARAMETER_ABOVE);

        grid.onItemSelected(ti);

        verify(cellEditorControls).hide();
        verify(grid).addParameterBinding(eq(0));
    }

    @Test
    public void testOnItemSelectedInsertParameterBelow() {
        setupGrid(0);

        final List<HasListSelectorControl.ListSelectorItem> items = grid.getItems(0, 0);
        final HasListSelectorControl.ListSelectorTextItem ti = (HasListSelectorControl.ListSelectorTextItem) items.get(INSERT_PARAMETER_BELOW);

        grid.onItemSelected(ti);

        verify(cellEditorControls).hide();
        verify(grid).addParameterBinding(eq(1));
    }

    @Test
    public void testOnItemSelectedDeleteParameter() {
        setupGrid(0);

        final List<HasListSelectorControl.ListSelectorItem> items = grid.getItems(0, 0);
        final HasListSelectorControl.ListSelectorTextItem ti = (HasListSelectorControl.ListSelectorTextItem) items.get(DELETE_PARAMETER);

        grid.onItemSelected(ti);

        verify(cellEditorControls).hide();
        verify(grid).deleteParameterBinding(eq(0));
    }

    @Test
    public void testOnItemSelectedDeleteParameterEnabled() {
        setupGrid(0);

        //Grid has one row from Invocation model. It cannot be deleted.
        assertDeleteParameterEnabled(0, false);

        //Grid has two rows. Rows 1 and 2 can be deleted.
        grid.getModel().appendRow(new BaseGridRow());
        assertDeleteParameterEnabled(0, true);
        assertDeleteParameterEnabled(1, true);
    }

    @Test
    public void testOnHeaderItemSelectedInsertParameter() {
        setupGrid(0);

        final List<HasListSelectorControl.ListSelectorItem> items = grid.getHeaderItems(0, 1);
        final HasListSelectorControl.ListSelectorTextItem ti = (HasListSelectorControl.ListSelectorTextItem) items.get(INSERT_PARAMETER);

        grid.onItemSelected(ti);

        verify(cellEditorControls).hide();
        verify(grid).addParameterBinding(eq(1));
    }

    private void assertDeleteParameterEnabled(final int uiRowIndex, final boolean enabled) {
        final List<HasListSelectorControl.ListSelectorItem> items = grid.getItems(uiRowIndex, 0);
        final HasListSelectorControl.ListSelectorTextItem ti = (HasListSelectorControl.ListSelectorTextItem) items.get(DELETE_PARAMETER);
        assertThat(ti.isEnabled()).isEqualTo(enabled);
    }

    @Test
    public void testAddParameterBinding() {
        setupGrid(0);

        addParameterBinding(0);

        verify(parent).proposeContainingColumnWidth(eq(grid.getWidth() + grid.getPadding() * 2),
                                                    eq(BaseExpressionGrid.RESIZE_EXISTING));

        verify(gridLayer).batch(redrawCommandCaptor.capture());
        verify(gridPanel).refreshScrollPosition();
        verify(gridPanel).updatePanelSize();

        final GridLayerRedrawManager.PrioritizedCommand redrawCommand = redrawCommandCaptor.getValue();

        redrawCommand.execute();

        verify(gridLayer).draw();

        verify(headerEditor).bind(any(HasValueAndTypeRef.class),
                                  eq(0),
                                  eq(1));
        verify(cellEditorControls).show(eq(headerEditor),
                                        anyInt(),
                                        anyInt());
    }

    private void addParameterBinding(final int index) {
        grid.addParameterBinding(index);

        verify(sessionCommandManager).execute(eq(canvasHandler), addParameterBindingCommandCaptor.capture());

        final AddParameterBindingCommand addParameterBindingCommand = addParameterBindingCommandCaptor.getValue();
        addParameterBindingCommand.execute(canvasHandler);
    }

    @Test
    public void testDeleteParameterBinding() {
        setupGrid(0);

        grid.deleteParameterBinding(0);

        verify(sessionCommandManager).execute(eq(canvasHandler),
                                              deleteParameterBindingCommandCaptor.capture());

        final DeleteParameterBindingCommand deleteParameterBindingCommand = deleteParameterBindingCommandCaptor.getValue();
        deleteParameterBindingCommand.execute(canvasHandler);

        verify(parent).onResize();
        verify(gridPanel).refreshScrollPosition();
        verify(gridPanel).updatePanelSize();
        verify(gridLayer).batch(redrawCommandCaptor.capture());

        final GridLayerRedrawManager.PrioritizedCommand redrawCommand = redrawCommandCaptor.getValue();
        redrawCommand.execute();

        verify(gridLayer).draw();
    }

    @Test
    public void testClearExpressionType() {
        setupGrid(0);

        grid.clearExpressionType(0);

        verify(sessionCommandManager).execute(eq(canvasHandler),
                                              clearExpressionTypeCommandCaptor.capture());

        final ClearExpressionTypeCommand clearExpressionTypeCommand = clearExpressionTypeCommandCaptor.getValue();
        clearExpressionTypeCommand.execute(canvasHandler);

        verify(grid).resize(BaseExpressionGrid.RESIZE_EXISTING_MINIMUM);
        verify(gridLayer).select(undefinedExpressionEditor);
        verify(undefinedExpressionEditor).selectFirstCell();
        verify(gridLayer).batch(redrawCommandCaptor.capture());
        redrawCommandCaptor.getValue().execute();
        verify(gridLayer).draw();

        //Check undo operation
        reset(grid, gridLayer);
        clearExpressionTypeCommand.undo(canvasHandler);

        //Verify Expression has been restored and UndefinedExpressionEditor resized
        assertThat(grid.getModel().getColumns().get(2).getWidth()).isEqualTo(UndefinedExpressionColumn.DEFAULT_WIDTH);
        verify(grid).resize(BaseExpressionGrid.RESIZE_EXISTING_MINIMUM);

        verify(grid).selectExpressionEditorFirstCell(eq(0), eq(InvocationUIModelMapper.BINDING_EXPRESSION_COLUMN_INDEX));
        verify(gridLayer).select(undefinedExpressionEditor);
        verify(undefinedExpressionEditor, times(2)).selectFirstCell();

        verify(gridLayer).batch(redrawCommandCaptor.capture());
        assertThat(redrawCommandCaptor.getAllValues()).hasSize(2);
        redrawCommandCaptor.getAllValues().get(1).execute();
        verify(gridLayer).draw();
    }

    @Test
    public void testHeaderFactoryWhenNested() {
        setupGrid(1);

        final TextBoxSingletonDOMElementFactory factory = grid.getHeaderTextBoxFactory();
        assertThat(factory.getHasNoValueCommand().apply(tupleWithoutValue)).isInstanceOf(DeleteHeaderValueCommand.class);
        assertThat(factory.getHasValueCommand().apply(tupleWithValue)).isInstanceOf(SetHeaderValueCommand.class);
    }

    @Test
    public void testHeaderFactoryWhenNotNested() {
        setupGrid(0);

        final TextBoxSingletonDOMElementFactory factory = grid.getHeaderTextBoxFactory();
        assertThat(factory.getHasNoValueCommand().apply(tupleWithoutValue)).isInstanceOf(DeleteHeaderValueCommand.class);
        assertThat(factory.getHasValueCommand().apply(tupleWithValue)).isInstanceOf(SetHeaderValueCommand.class);
    }

    @Test
    public void testBodyFactoryWhenNested() {
        setupGrid(1);

        final TextAreaSingletonDOMElementFactory factory = grid.getBodyTextAreaFactory();
        assertThat(factory.getHasNoValueCommand().apply(tupleWithoutValue)).isInstanceOf(DeleteCellValueCommand.class);
        assertThat(factory.getHasValueCommand().apply(tupleWithValue)).isInstanceOf(SetCellValueCommand.class);
    }

    @Test
    public void testBodyFactoryWhenNotNested() {
        setupGrid(0);

        final TextAreaSingletonDOMElementFactory factory = grid.getBodyTextAreaFactory();
        assertThat(factory.getHasNoValueCommand().apply(tupleWithoutValue)).isInstanceOf(DeleteCellValueCommand.class);
        assertThat(factory.getHasValueCommand().apply(tupleWithValue)).isInstanceOf(SetCellValueCommand.class);
    }

    @Test
    public void testGetDisplayName() {
        setupGrid(0);

        assertThat(extractHeaderMetaData().getValue().getValue()).isEqualTo(NAME);
    }

    private InvocationColumnHeaderMetaData extractHeaderMetaData() {
        final InvocationParameterColumn column = (InvocationParameterColumn) grid.getModel().getColumns().get(1);
        return (InvocationColumnHeaderMetaData) column.getHeaderMetaData().get(0);
    }

    @Test
    @SuppressWarnings("unchecked")
    public void testSetDisplayNameWithNoChange() {
        setupGrid(0);

        extractHeaderMetaData().setValue(new Name(NAME));

        verify(sessionCommandManager, never()).execute(any(AbstractCanvasHandler.class),
                                                       any(org.kie.workbench.common.stunner.core.command.Command.class));
    }

    @Test
    @SuppressWarnings("unchecked")
    public void testSetDisplayNameWithEmptyValue() {
        setupGrid(0);

        extractHeaderMetaData().setValue(new Name());

        verify(sessionCommandManager).execute(eq(canvasHandler),
                                              compositeCommandCaptor.capture());

        GridFactoryCommandUtils.assertCommands(compositeCommandCaptor.getValue(),
                                               DeleteHasValueCommand.class,
                                               UpdateElementPropertyCommand.class);
    }

    @Test
    @SuppressWarnings("unchecked")
    public void testSetDisplayNameWithNullValue() {
        setupGrid(0);

        extractHeaderMetaData().setValue(null);

        verify(sessionCommandManager).execute(eq(canvasHandler),
                                              compositeCommandCaptor.capture());

        GridFactoryCommandUtils.assertCommands(compositeCommandCaptor.getValue(),
                                               DeleteHasValueCommand.class,
                                               UpdateElementPropertyCommand.class);
    }

    @Test
    @SuppressWarnings("unchecked")
    public void testSetDisplayNameWithNonEmptyValue() {
        setupGrid(0);

        extractHeaderMetaData().setValue(new Name(NAME_NEW));

        verify(sessionCommandManager).execute(eq(canvasHandler),
                                              compositeCommandCaptor.capture());

        GridFactoryCommandUtils.assertCommands(compositeCommandCaptor.getValue(),
                                               SetHasValueCommand.class,
                                               UpdateElementPropertyCommand.class);
    }

    @Test
    public void testGetTypeRef() {
        setupGrid(0);

        assertThat(extractHeaderMetaData().getTypeRef()).isNotNull();
    }

    @Test
    public void testSetTypeRef() {
        setupGrid(0);

        extractHeaderMetaData().setTypeRef(new QName(QName.NULL_NS_URI,
                                                     BuiltInType.DATE.getName()));

        verify(sessionCommandManager).execute(eq(canvasHandler),
                                              any(SetTypeRefCommand.class));
    }

    @Test
    public void testSetTypeRefWithoutChange() {
        setupGrid(0);

        extractHeaderMetaData().setTypeRef(new QName());

        verify(sessionCommandManager, never()).execute(any(AbstractCanvasHandler.class),
                                                       any(SetTypeRefCommand.class));
    }

    @Test
    public void testSelectRow() {
        setupGrid(0);

        grid.selectCell(0, InvocationUIModelMapper.ROW_NUMBER_COLUMN_INDEX, false, false);

        assertNOPDomainObjectSelection();
    }

    @Test
    public void testSelectParameterBinding() {
        setupGrid(0);

        grid.selectCell(0, InvocationUIModelMapper.BINDING_PARAMETER_COLUMN_INDEX, false, false);

        assertDomainObjectSelection(expression.get().getBinding().get(0).getVariable());
    }

    @Test
    @SuppressWarnings("unchecked")
    public void testSelectMultipleParameterBindings() {
        setupGrid(0);

        addParameterBinding(0);

        //Reset DomainObjectSelectionEvent fired when the new row is added.
        reset(domainObjectSelectionEvent);

        grid.selectCell(0, InvocationUIModelMapper.BINDING_PARAMETER_COLUMN_INDEX, false, false);

        assertDomainObjectSelection(expression.get().getBinding().get(0).getVariable());

        //Reset DomainObjectSelectionEvent tested above.
        reset(domainObjectSelectionEvent);

        grid.selectCell(1, InvocationUIModelMapper.BINDING_PARAMETER_COLUMN_INDEX, false, true);

        assertNOPDomainObjectSelection();
    }

    @Test
    @SuppressWarnings("unchecked")
    public void testSelectSingleParameterBindingWithHeaderSelected() {
        setupGrid(0);

        grid.selectHeaderCell(0, InvocationUIModelMapper.BINDING_PARAMETER_COLUMN_INDEX, false, false);

        assertDomainObjectSelection(hasExpression);

        //Reset DomainObjectSelectionEvent tested above.
        reset(domainObjectSelectionEvent);

        grid.selectCell(0, InvocationUIModelMapper.BINDING_PARAMETER_COLUMN_INDEX, false, true);

        assertDomainObjectSelection(expression.get().getBinding().get(0).getVariable());
    }

    @Test
    public void testSelectHeaderRowColumn() {
        setupGrid(0);

        grid.selectHeaderCell(0, InvocationUIModelMapper.ROW_NUMBER_COLUMN_INDEX, false, false);

        assertNOPDomainObjectSelection();
    }

    @Test
    public void testSelectHeaderNameColumnNameRow() {
        setupGrid(0);

        grid.selectHeaderCell(0, InvocationUIModelMapper.BINDING_PARAMETER_COLUMN_INDEX, false, false);

        assertDomainObjectSelection(hasExpression);
    }

    @Test
    public void testSelectHeaderExpressionColumnNameRow() {
        setupGrid(0);

        grid.selectHeaderCell(0, InvocationUIModelMapper.BINDING_EXPRESSION_COLUMN_INDEX, false, false);

        assertDomainObjectSelection(hasExpression);
    }

    @Test
    public void testSelectHeaderNameColumnParametersRow() {
        setupGrid(0);

        grid.selectHeaderCell(1, InvocationUIModelMapper.BINDING_PARAMETER_COLUMN_INDEX, false, false);

        assertNOPDomainObjectSelection();
    }

    @Test
    public void testSelectHeaderExpressionColumnParametersRow() {
        setupGrid(0);

        grid.selectHeaderCell(1, InvocationUIModelMapper.BINDING_EXPRESSION_COLUMN_INDEX, false, false);

        assertNOPDomainObjectSelection();
    }

    @Test
    public void testSelectHeaderNameColumnParametersRowWhenNested() {
        setupGrid(1);

        grid.selectHeaderCell(0, InvocationUIModelMapper.BINDING_PARAMETER_COLUMN_INDEX, false, false);

        assertNOPDomainObjectSelection();
    }

    @Test
    public void testSelectHeaderExpressionColumnParametersRowWhenNested() {
        setupGrid(1);

        grid.selectHeaderCell(0, InvocationUIModelMapper.BINDING_EXPRESSION_COLUMN_INDEX, false, false);

        assertNOPDomainObjectSelection();
    }

    private void assertDomainObjectSelection(final DomainObject domainObject) {
        verify(domainObjectSelectionEvent).fire(domainObjectSelectionEventCaptor.capture());

        final DomainObjectSelectionEvent domainObjectSelectionEvent = domainObjectSelectionEventCaptor.getValue();
        assertThat(domainObjectSelectionEvent.getDomainObject()).isEqualTo(domainObject);
    }

    private void assertNOPDomainObjectSelection() {
        verify(domainObjectSelectionEvent).fire(domainObjectSelectionEventCaptor.capture());

        final DomainObjectSelectionEvent domainObjectSelectionEvent = domainObjectSelectionEventCaptor.getValue();
        assertThat(domainObjectSelectionEvent.getDomainObject()).isInstanceOf(NOPDomainObject.class);
    }

    @Test
    public void testAsDMNModelInstrumentedBase() {
        setupGrid(0);

        assertThat(extractHeaderMetaData().asDMNModelInstrumentedBase()).isInstanceOf(hasExpression.getVariable().getClass());
    }
}


text:
Levenshtein - basic
--FILE--
<?php
// input misspelled word
$input = 'carrrot';

// array of words to check against
$words  = array('apple','pineapple','banana','orange',
                'radish','carrot','pea','bean','potato');

// no shortest distance found, yet
$shortest = -1;

// loop through words to find the closest
foreach ($words as $word) {

    // calculate the distance between the input word,
    // and the current word
    $lev = levenshtein($input, $word);

    // check for an exact match
    if ($lev == 0) {

        // closest word is this one (exact match)
        $closest = $word;
        $shortest = 0;

        // break out of the loop; we've found an exact match
        break;
    }

    // if this distance is less than the next found shortest
    // distance, OR if a next shortest word has not yet been found
    if ($lev <= $shortest || $shortest < 0) {
        // set the closest match, and shortest distance
        $closest  = $word;
        $shortest = $lev;
    }
}

echo "Input word: $input\n";
if ($shortest == 0) {
    echo "Exact match found: $closest\n";
} else {
    echo "Did you mean: $closest?\n";
}

--EXPECT--
Input word: carrrot
Did you mean: carrot?


text:
using System;
using System.Runtime.Serialization;

namespace StatusPageIo.Api.Models.Incidents
{
    [DataContract]
    public class IncidentUpdate
    {
        [DataMember(Name = "body")]
        public string Body { get; set; }

        [DataMember(Name = "created_at")]
        public DateTime CreatedAt { get; set; }

        [DataMember(Name = "display_at")]
        public DateTime DisplayAt { get; set; }

        [DataMember(Name = "id")]
        public string Id { get; set; }

        [DataMember(Name = "incident_id")]
        public string IncidentId { get; set; }

        [DataMember(Name = "status")]
        public string Status { get; set; }

        [DataMember(Name = "twitter_updated_at")]
        public DateTime? TwitterUpdatedAt { get; set; }

        [DataMember(Name = "updated_at")]
        public DateTime? UpdatedAt { get; set; }

        [DataMember(Name = "wants_twitter_update")]
        public bool WantsTwitterUpdate { get; set; }
    }
}


text: Meteo bluetooth android client for Arduino


text:
cask "boinc" do
  version "7.20.2"
  sha256 "34bbcfca18915294e5da18110a0e8c302effa1dbe1ae0eca9dd5e40d3a8b3a98"

  url "https://boinc.berkeley.edu/dl/boinc_#{version}_macOSX_universal.zip"
  name "Berkeley Open Infrastructure for Network Computing"
  name "BOINC"
  desc "Downloads scientific computing jobs and runs them invisibly in the background"
  homepage "https://boinc.berkeley.edu/"

  livecheck do
    url "https://boinc.berkeley.edu/download.php"
    regex(%r{href=.*?/dl/boinc[._-]v?(\d+(?:\.\d+)+)_macOSX_universal\.zip}i)
  end

  pkg "boinc_#{version}_macOSX_universal/BOINC Installer.app/Contents/Resources/BOINC.pkg"

  uninstall pkgutil:   "edu.berkeley.boinc",
            launchctl: "edu.berkeley.boinc-sshelper"

  zap trash: [
    "~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/edu.berkeley.boinc.sfl*",
    "~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/edu.berkeley.boinc.*.sfl*",
    "~/Library/Application Support/BOINC",
    "~/Library/Caches/edu.berkeley.boinc",
    "~/Library/Preferences/BOINC Manager Preferences",
    "~/Library/Preferences/edu.berkeley.boinc.plist",
    "/Library/Screen Savers/BOINCSaver.saver",
  ]
end


text:
describe('[Regression](GH-3724)', () => {
    it('Should correctly type text in an editable iframe', () => runTests('testcafe-fixtures/index.js'));
});


text:
const $A = window.$A;
const aura = window.Aura;

var cmp;
var rootElem = document.getElementById("main");

const cmpName = "aura:unescapedHtml";
const cmpParams = {"value": "
unescapedHTML Perf Test
"};

describe(cmpName, () => {

    benchmark('create_component', () => {
        run(() => {
            $A.createComponent(cmpName, cmpParams, (res) => {
                cmp = res;
            });
        });
    });

    benchmark('render_component', () => {
        run(() => {
            $A.renderingService.render(cmp, rootElem);
        });
    });

    benchmark('unrender_component', () => {
        run(() => {
            $A.renderingService.unrender(cmp, rootElem);
        });
    });

    benchmark('destroy_component', () => {
        before(() => {
            $A.createComponent(cmpName, cmpParams, (res) => {
                cmp = res;
                $A.renderingService.render(cmp, rootElem);
            });
        });

        run(() => {
            cmp.destroy();
        });
    });
});


text:
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Input.Bindings;
using osu.Framework.IO.Stores;
using osu.Game.Beatmaps;
using osu.Game.Overlays.Settings;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Replays.Types;
using osu.Game.Rulesets.UI;
using osu.Game.Beatmaps.Legacy;
using osu.Game.Configuration;
using osu.Game.Rulesets.Configuration;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Scoring;
using osu.Game.Scoring;
using osu.Game.Skinning;
using osu.Game.Users;
using JetBrains.Annotations;
using osu.Framework.Extensions;
using osu.Framework.Extensions.EnumExtensions;
using osu.Framework.Testing;
using osu.Game.Extensions;
using osu.Game.Rulesets.Filter;
using osu.Game.Screens.Edit.Setup;
using osu.Game.Screens.Ranking.Statistics;

namespace osu.Game.Rulesets
{
    [ExcludeFromDynamicCompile]
    public abstract class Ruleset
    {
        public RulesetInfo RulesetInfo { get; internal set; }

        private static readonly ConcurrentDictionary<int, IMod[]> mod_reference_cache = new ConcurrentDictionary<int, IMod[]>();

        /// <summary>
        /// A queryable source containing all available mods.
        /// Call <see cref="IMod.CreateInstance"/> for consumption purposes.
        /// </summary>
        public IEnumerable<IMod> AllMods
        {
            get
            {
                if (!(RulesetInfo.ID is int id))
                    return CreateAllMods();

                if (!mod_reference_cache.TryGetValue(id, out var mods))
                    mod_reference_cache[id] = mods = CreateAllMods().Cast<IMod>().ToArray();

                return mods;
            }
        }

        /// <summary>
        /// Returns fresh instances of all mods.
        /// </summary>
        /// <remarks>
        /// This comes with considerable allocation overhead. If only accessing for reference purposes (ie. not changing bindables / settings)
        /// use <see cref="AllMods"/> instead.
        /// </remarks>
        public IEnumerable<Mod> CreateAllMods() => Enum.GetValues(typeof(ModType)).Cast<ModType>()
                                                       // Confine all mods of each mod type into a single IEnumerable<Mod>
                                                       .SelectMany(GetModsFor)
                                                       // Filter out all null mods
                                                       .Where(mod => mod != null)
                                                       // Resolve MultiMods as their .Mods property
                                                       .SelectMany(mod => (mod as MultiMod)?.Mods ?? new[] { mod });

        /// <summary>
        /// Returns a fresh instance of the mod matching the specified acronym.
        /// </summary>
        /// <param name="acronym">The acronym to query for .</param>
        public Mod CreateModFromAcronym(string acronym)
        {
            return AllMods.FirstOrDefault(m => m.Acronym == acronym)?.CreateInstance();
        }

        /// <summary>
        /// Returns a fresh instance of the mod matching the specified type.
        /// </summary>
        public T CreateMod<T>()
            where T : Mod
        {
            return AllMods.FirstOrDefault(m => m is T)?.CreateInstance() as T;
        }

        public abstract IEnumerable<Mod> GetModsFor(ModType type);

        /// <summary>
        /// Converts mods from legacy enum values. Do not override if you're not a legacy ruleset.
        /// </summary>
        /// <param name="mods">The legacy enum which will be converted.</param>
        /// <returns>An enumerable of constructed <see cref="Mod"/>s.</returns>
        public virtual IEnumerable<Mod> ConvertFromLegacyMods(LegacyMods mods) => Array.Empty<Mod>();

        /// <summary>
        /// Converts mods to legacy enum values. Do not override if you're not a legacy ruleset.
        /// </summary>
        /// <param name="mods">The mods which will be converted.</param>
        /// <returns>A single bitwise enumerable value representing (to the best of our ability) the mods.</returns>
        public virtual LegacyMods ConvertToLegacyMods(Mod[] mods)
        {
            var value = LegacyMods.None;

            foreach (var mod in mods)
            {
                switch (mod)
                {
                    case ModNoFail _:
                        value |= LegacyMods.NoFail;
                        break;

                    case ModEasy _:
                        value |= LegacyMods.Easy;
                        break;

                    case ModHidden _:
                        value |= LegacyMods.Hidden;
                        break;

                    case ModHardRock _:
                        value |= LegacyMods.HardRock;
                        break;

                    case ModPerfect _:
                        value |= LegacyMods.Perfect;
                        break;

                    case ModSuddenDeath _:
                        value |= LegacyMods.SuddenDeath;
                        break;

                    case ModNightcore _:
                        value |= LegacyMods.Nightcore;
                        break;

                    case ModDoubleTime _:
                        value |= LegacyMods.DoubleTime;
                        break;

                    case ModRelax _:
                        value |= LegacyMods.Relax;
                        break;

                    case ModHalfTime _:
                        value |= LegacyMods.HalfTime;
                        break;

                    case ModFlashlight _:
                        value |= LegacyMods.Flashlight;
                        break;

                    case ModCinema _:
                        value |= LegacyMods.Cinema;
                        break;

                    case ModAutoplay _:
                        value |= LegacyMods.Autoplay;
                        break;
                }
            }

            return value;
        }

        [CanBeNull]
        public ModAutoplay GetAutoplayMod() => CreateMod<ModAutoplay>();

        public virtual ISkin CreateLegacySkinProvider([NotNull] ISkin skin, IBeatmap beatmap) => null;

        protected Ruleset()
        {
            RulesetInfo = new RulesetInfo
            {
                Name = Description,
                ShortName = ShortName,
                ID = (this as ILegacyRuleset)?.LegacyID,
                InstantiationInfo = GetType().GetInvariantInstantiationInfo(),
                Available = true,
            };
        }

        /// <summary>
        /// Attempt to create a hit renderer for a beatmap
        /// </summary>
        /// <param name="beatmap">The beatmap to create the hit renderer for.</param>
        /// <param name="mods">The <see cref="Mod"/>s to apply.</param>
        /// <exception cref="BeatmapInvalidForRulesetException">Unable to successfully load the beatmap to be usable with this ruleset.</exception>
        public abstract DrawableRuleset CreateDrawableRulesetWith(IBeatmap beatmap, IReadOnlyList<Mod> mods = null);

        /// <summary>
        /// Creates a <see cref="ScoreProcessor"/> for this <see cref="Ruleset"/>.
        /// </summary>
        /// <returns>The score processor.</returns>
        public virtual ScoreProcessor CreateScoreProcessor() => new ScoreProcessor();

        /// <summary>
        /// Creates a <see cref="HealthProcessor"/> for this <see cref="Ruleset"/>.
        /// </summary>
        /// <returns>The health processor.</returns>
        public virtual HealthProcessor CreateHealthProcessor(double drainStartTime) => new DrainingHealthProcessor(drainStartTime);

        /// <summary>
        /// Creates a <see cref="IBeatmapConverter"/> to convert a <see cref="IBeatmap"/> to one that is applicable for this <see cref="Ruleset"/>.
        /// </summary>
        /// <param name="beatmap">The <see cref="IBeatmap"/> to be converted.</param>
        /// <returns>The <see cref="IBeatmapConverter"/>.</returns>
        public abstract IBeatmapConverter CreateBeatmapConverter(IBeatmap beatmap);

        /// <summary>
        /// Optionally creates a <see cref="IBeatmapProcessor"/> to alter a <see cref="IBeatmap"/> after it has been converted.
        /// </summary>
        /// <param name="beatmap">The <see cref="IBeatmap"/> to be processed.</param>
        /// <returns>The <see cref="IBeatmapProcessor"/>.</returns>
        public virtual IBeatmapProcessor CreateBeatmapProcessor(IBeatmap beatmap) => null;

        public abstract DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap);

        /// <summary>
        /// Optionally creates a <see cref="PerformanceCalculator"/> to generate performance data from the provided score.
        /// </summary>
        /// <param name="attributes">Difficulty attributes for the beatmap related to the provided score.</param>
        /// <param name="score">The score to be processed.</param>
        /// <returns>A performance calculator instance for the provided score.</returns>
        [CanBeNull]
        public virtual PerformanceCalculator CreatePerformanceCalculator(DifficultyAttributes attributes, ScoreInfo score) => null;

        /// <summary>
        /// Optionally creates a <see cref="PerformanceCalculator"/> to generate performance data from the provided score.
        /// </summary>
        /// <param name="beatmap">The beatmap to use as a source for generating <see cref="DifficultyAttributes"/>.</param>
        /// <param name="score">The score to be processed.</param>
        /// <returns>A performance calculator instance for the provided score.</returns>
        [CanBeNull]
        public PerformanceCalculator CreatePerformanceCalculator(WorkingBeatmap beatmap, ScoreInfo score)
        {
            var difficultyCalculator = CreateDifficultyCalculator(beatmap);
            var difficultyAttributes = difficultyCalculator.Calculate(score.Mods);
            return CreatePerformanceCalculator(difficultyAttributes, score);
        }

        public virtual HitObjectComposer CreateHitObjectComposer() => null;

        public virtual IBeatmapVerifier CreateBeatmapVerifier() => null;

        public virtual Drawable CreateIcon() => new SpriteIcon { Icon = FontAwesome.Solid.QuestionCircle };

        public virtual IResourceStore<byte[]> CreateResourceStore() => new NamespacedResourceStore<byte[]>(new DllResourceStore(GetType().Assembly), @"Resources");

        public abstract string Description { get; }

        public virtual RulesetSettingsSubsection CreateSettings() => null;

        /// <summary>
        /// Creates the <see cref="IRulesetConfigManager"/> for this <see cref="Ruleset"/>.
        /// </summary>
        /// <param name="settings">The <see cref="SettingsStore"/> to store the settings.</param>
        public virtual IRulesetConfigManager CreateConfig(SettingsStore settings) => null;

        /// <summary>
        /// A unique short name to reference this ruleset in online requests.
        /// </summary>
        public abstract string ShortName { get; }

        /// <summary>
        /// The playing verb to be shown in the <see cref="UserActivity.InGame"/> activities.
        /// </summary>
        public virtual string PlayingVerb => "Playing";

        /// <summary>
        /// A list of available variant ids.
        /// </summary>
        public virtual IEnumerable<int> AvailableVariants => new[] { 0 };

        /// <summary>
        /// Get a list of default keys for the specified variant.
        /// </summary>
        /// <param name="variant">A variant.</param>
        /// <returns>A list of valid <see cref="KeyBinding"/>s.</returns>
        public virtual IEnumerable<KeyBinding> GetDefaultKeyBindings(int variant = 0) => Array.Empty<KeyBinding>();

        /// <summary>
        /// Gets the name for a key binding variant. This is used for display in the settings overlay.
        /// </summary>
        /// <param name="variant">The variant.</param>
        /// <returns>A descriptive name of the variant.</returns>
        public virtual string GetVariantName(int variant) => string.Empty;

        /// <summary>
        /// For rulesets which support legacy (osu-stable) replay conversion, this method will create an empty replay frame
        /// for conversion use.
        /// </summary>
        /// <returns>An empty frame for the current ruleset, or null if unsupported.</returns>
        public virtual IConvertibleReplayFrame CreateConvertibleReplayFrame() => null;

        /// <summary>
        /// Creates the statistics for a <see cref="ScoreInfo"/> to be displayed in the results screen.
        /// </summary>
        /// <param name="score">The <see cref="ScoreInfo"/> to create the statistics for. The score is guaranteed to have <see cref="ScoreInfo.HitEvents"/> populated.</param>
        /// <param name="playableBeatmap">The <see cref="IBeatmap"/>, converted for this <see cref="Ruleset"/> with all relevant <see cref="Mod"/>s applied.</param>
        /// <returns>The <see cref="StatisticRow"/>s to display. Each <see cref="StatisticRow"/> may contain 0 or more <see cref="StatisticItem"/>.</returns>
        [NotNull]
        public virtual StatisticRow[] CreateStatisticsForScore(ScoreInfo score, IBeatmap playableBeatmap) => Array.Empty<StatisticRow>();

        /// <summary>
        /// Get all valid <see cref="HitResult"/>s for this ruleset.
        /// Generally used for results display purposes, where it can't be determined if zero-count means the user has not achieved any or the type is not used by this ruleset.
        /// </summary>
        /// <returns>
        /// All valid <see cref="HitResult"/>s along with a display-friendly name.
        /// </returns>
        public IEnumerable<(HitResult result, string displayName)> GetHitResults()
        {
            var validResults = GetValidHitResults();

            // enumerate over ordered list to guarantee return order is stable.
            foreach (var result in EnumExtensions.GetValuesInOrder<HitResult>())
            {
                switch (result)
                {
                    // hard blocked types, should never be displayed even if the ruleset tells us to.
                    case HitResult.None:
                    case HitResult.IgnoreHit:
                    case HitResult.IgnoreMiss:
                    // display is handled as a completion count with corresponding "hit" type.
                    case HitResult.LargeTickMiss:
                    case HitResult.SmallTickMiss:
                        continue;
                }

                if (result == HitResult.Miss || validResults.Contains(result))
                    yield return (result, GetDisplayNameForHitResult(result));
            }
        }

        /// <summary>
        /// Get all valid <see cref="HitResult"/>s for this ruleset.
        /// Generally used for results display purposes, where it can't be determined if zero-count means the user has not achieved any or the type is not used by this ruleset.
        /// </summary>
        /// <remarks>
        /// <see cref="HitResult.Miss"/> is implicitly included. Special types like <see cref="HitResult.IgnoreHit"/> are ignored even when specified.
        /// </remarks>
        protected virtual IEnumerable<HitResult> GetValidHitResults() => EnumExtensions.GetValuesInOrder<HitResult>();

        /// <summary>
        /// Get a display friendly name for the specified result type.
        /// </summary>
        /// <param name="result">The result type to get the name for.</param>
        /// <returns>The display name.</returns>
        public virtual string GetDisplayNameForHitResult(HitResult result) => result.GetDescription();

        /// <summary>
        /// Creates ruleset-specific beatmap filter criteria to be used on the song select screen.
        /// </summary>
        [CanBeNull]
        public virtual IRulesetFilterCriteria CreateRulesetFilterCriteria() => null;

        /// <summary>
        /// Can be overridden to add a ruleset-specific section to the editor beatmap setup screen.
        /// </summary>
        [CanBeNull]
        public virtual RulesetSetupSection CreateEditorSetupSection() => null;
    }
}


text:
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//

// AI Navigation areas
// Author: Michael S. Booth (mike@turtlerockstudios.com), January 2003

#include "cbase.h"

#include "nav_mesh.h"
#include "nav_node.h"
#include "nav_pathfind.h"
#include "nav_colors.h"

// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"

extern ConVar nav_area_bgcolor;

LINK_ENTITY_TO_CLASS( info_ladder, CInfoLadder );

unsigned int CNavLadder::m_nextID = 1;

//--------------------------------------------------------------------------------------------------------------
bool CInfoLadder::KeyValue( const char *szKeyName, const char *szValue )
{
	if ( FStrEq( szKeyName, "mins.x" ) )
	{
		mins.x = atof( szValue );
		SetCollisionBounds( mins, maxs );
	}
	else if ( FStrEq( szKeyName, "mins.y" ) )
	{
		mins.y = atof( szValue );
		SetCollisionBounds( mins, maxs );
	}
	else if ( FStrEq( szKeyName, "mins.z" ) )
	{
		mins.z = atof( szValue );
		SetCollisionBounds( mins, maxs );
	}
	else if ( FStrEq( szKeyName, "maxs.x" ) )
	{
		maxs.x = atof( szValue );
		SetCollisionBounds( mins, maxs );
	}
	else if ( FStrEq( szKeyName, "maxs.y" ) )
	{
		maxs.y = atof( szValue );
		SetCollisionBounds( mins, maxs );
	}
	else if ( FStrEq( szKeyName, "maxs.z" ) )
	{
		maxs.z = atof( szValue );
		SetCollisionBounds( mins, maxs );
	}

	return BaseClass::KeyValue( szKeyName, szValue );
}

//--------------------------------------------------------------------------------------------------------------
void CNavLadder::CompressIDs( void )
{
	m_nextID = 1;

	if ( TheNavMesh )
	{
		FOR_EACH_LL( TheNavMesh->GetLadders(), id )
		{
			CNavLadder *ladder = TheNavMesh->GetLadders()[id];
			ladder->m_id = m_nextID++;
		}
	}
}

//--------------------------------------------------------------------------------------------------------------
CNavArea ** CNavLadder::GetConnection( LadderConnectionType dir )
{
	switch ( dir )
	{
	case LADDER_TOP_FORWARD:
		return &m_topForwardArea;
	case LADDER_TOP_LEFT:
		return &m_topLeftArea;
	case LADDER_TOP_RIGHT:
		return &m_topRightArea;
	case LADDER_TOP_BEHIND:
		return &m_topBehindArea;
	case LADDER_BOTTOM:
		return &m_bottomArea;
	}

	return NULL;
}

//--------------------------------------------------------------------------------------------------------------
void CNavLadder::OnSplit( CNavArea *original, CNavArea *alpha, CNavArea *beta )
{
	for ( int con=0; con<NUM_LADDER_CONNECTIONS; ++con )
	{
		CNavArea ** areaConnection = GetConnection( (LadderConnectionType)con );

		if ( areaConnection && *areaConnection == original )
		{
			float alphaDistance = alpha->GetDistanceSquaredToPoint( m_top );
			float betaDistance = beta->GetDistanceSquaredToPoint( m_top );

			if ( alphaDistance < betaDistance )
			{
				*areaConnection = alpha;
			}
			else
			{
				*areaConnection = beta;
			}
		}
	}
}

//--------------------------------------------------------------------------------------------------------------
/**
 * Connect this ladder to given area
 */
void CNavLadder::ConnectTo( CNavArea *area )
{
	float center = (m_top.z + m_bottom.z) * 0.5f;

	if (area->GetCenter().z > center)
	{
		// connect to top
		NavDirType dir;

		Vector dirVector = area->GetCenter() - m_top;
		if ( fabs( dirVector.x ) > fabs( dirVector.y ) )
		{
			if ( dirVector.x > 0.0f ) // east
			{
				dir = EAST;
			}
			else // west
			{
				dir = WEST;
			}
		}
		else
		{
			if ( dirVector.y > 0.0f ) // south
			{
				dir = SOUTH;
			}
			else // north
			{
				dir = NORTH;
			}
		}

		if ( m_dir == dir )
		{
			m_topBehindArea = area;
		}
		else if ( OppositeDirection( m_dir ) == dir )
		{
			m_topForwardArea = area;
		}
		else if ( DirectionLeft( m_dir ) == dir )
		{
			m_topLeftArea = area;
		}
		else
		{
			m_topRightArea = area;
		}
	}
	else
	{
		// connect to bottom
		m_bottomArea = area;
	}
}

//--------------------------------------------------------------------------------------------------------------
/**
 * Destructor
 */
CNavLadder::~CNavLadder()
{
	// tell the other areas we are going away
	FOR_EACH_LL( TheNavAreaList, it )
	{
		CNavArea *area = TheNavAreaList[ it ];

		area->OnDestroyNotify( this );
	}
}

//--------------------------------------------------------------------------------------------------------------
/**
 * invoked when given area is going away
 */
void CNavLadder::OnDestroyNotify( CNavArea *dead )
{
	Disconnect( dead );
}

//--------------------------------------------------------------------------------------------------------------
/**
 * Disconnect this ladder from given area
 */
void CNavLadder::Disconnect( CNavArea *area )
{
	if ( m_topForwardArea == area )
	{
		m_topForwardArea = NULL;
	}
	else if ( m_topLeftArea == area )
	{
		m_topLeftArea = NULL;
	}
	else if ( m_topRightArea == area )
	{
		m_topRightArea = NULL;
	}
	else if ( m_topBehindArea == area )
	{
		m_topBehindArea = NULL;
	}
	else if ( m_bottomArea == area )
	{
		m_bottomArea = NULL;
	}
}

//--------------------------------------------------------------------------------------------------------------
/**
 * returns true if given area is connected in given direction
 */
bool CNavLadder::IsConnected( const CNavArea *area, LadderDirectionType dir ) const
{
	if ( dir == LADDER_DOWN )
	{
		return area == m_bottomArea;
	}
	else if ( dir == LADDER_UP )
	{
		return ( area == m_topForwardArea ||
			area == m_topLeftArea ||
			area == m_topRightArea ||
			area == m_topBehindArea );
	}
	else
	{
		return ( area == m_bottomArea ||
			area == m_topForwardArea ||
			area == m_topLeftArea ||
			area == m_topRightArea ||
			area == m_topBehindArea );
	}
}

//--------------------------------------------------------------------------------------------------------------
void CNavLadder::SetDir( NavDirType dir )
{
	m_dir = dir;

	m_normal.Init();
	AddDirectionVector( &m_normal, m_dir, 1.0f );	// worst-case, we have the NavDirType as a normal

	Vector from = (m_top + m_bottom) * 0.5f + m_normal * 5.0f;
	Vector to = from - m_normal * 32.0f;

	trace_t result;
	UTIL_TraceLine( from, to, MASK_PLAYERSOLID_BRUSHONLY, NULL, COLLISION_GROUP_NONE, &result );

	if (result.fraction != 1.0f)
	{
		bool climbableSurface = physprops->GetSurfaceData( result.surface.surfaceProps )->game.climbable != 0;
		if ( !climbableSurface )
		{
			climbableSurface = (result.contents & CONTENTS_LADDER) != 0;
		}
		if ( climbableSurface )
		{
			m_normal = result.plane.normal;
		}
	}
}

//--------------------------------------------------------------------------------------------------------------
void CNavLadder::DrawLadder( void ) const
{
	CBasePlayer *player = UTIL_GetListenServerHost();
	if (player == NULL)
		return;

	Vector dir;
	const Vector &eye = player->EyePosition();
	AngleVectors( player->EyeAngles() + player->GetPunchAngle(), &dir );

	float dx = eye.x - m_bottom.x;
	float dy = eye.y - m_bottom.y;

	Vector2D eyeDir( dx, dy );
	eyeDir.NormalizeInPlace();
	bool isSelected = ( this == TheNavMesh->GetSelectedLadder() );
	bool isMarked = ( this == TheNavMesh->GetMarkedLadder() );
	bool isFront = DotProduct2D( eyeDir, GetNormal().AsVector2D() ) > 0;

	if ( TheNavMesh->IsPlaceMode() )
	{
		isSelected = isMarked = false;
		isFront = true;
	}

	// Draw 'ladder' lines ----------------------------------------------------
	NavEditColor ladderColor = NavNormalColor;
	if ( isFront )
	{
		if ( isMarked )
		{
			ladderColor = NavMarkedColor;
		}
		else if ( isSelected )
		{
			ladderColor = NavSelectedColor;
		}
		else
		{
			ladderColor = NavSamePlaceColor;
		}
	}
	else if ( isMarked )
	{
		ladderColor = NavMarkedColor;
	}
	else if ( isSelected )
	{
		ladderColor = NavSelectedColor;
	}

	Vector right(0, 0, 0), up( 0, 0, 0 );
	VectorVectors( GetNormal(), right, up );
	right *= m_width * 0.5f;

	Vector bottomLeft = m_bottom - right;
	Vector bottomRight = m_bottom + right;
	Vector topLeft = m_top - right;
	Vector topRight = m_top + right;

	int bgcolor[4];
	if ( 4 == sscanf( nav_area_bgcolor.GetString(), "%d %d %d %d", &(bgcolor[0]), &(bgcolor[1]), &(bgcolor[2]), &(bgcolor[3]) ) )
	{
		for ( int i=0; i<4; ++i )
			bgcolor[i] = clamp( bgcolor[i], 0, 255 );

		if ( bgcolor[3] > 0 )
		{
			Vector offset( 0, 0, 0 );
			AddDirectionVector( &offset, OppositeDirection( m_dir ), 1 );
			NDebugOverlay::Triangle( topLeft+offset, topRight+offset, bottomRight+offset, bgcolor[0], bgcolor[1], bgcolor[2], bgcolor[3], true, 0.15f );
			NDebugOverlay::Triangle( bottomRight+offset, bottomLeft+offset, topLeft+offset, bgcolor[0], bgcolor[1], bgcolor[2], bgcolor[3], true, 0.15f );
		}
	}

	NavDrawLine( topLeft, bottomLeft, ladderColor );
	NavDrawLine( topRight, bottomRight, ladderColor );

	while ( bottomRight.z < topRight.z )
	{
		NavDrawLine( bottomRight, bottomLeft, ladderColor );
		bottomRight += up * (GenerationStepSize/2);
		bottomLeft += up * (GenerationStepSize/2);
	}

	// Draw connector lines ---------------------------------------------------
	if ( !TheNavMesh->IsPlaceMode() )
	{
		Vector bottom = m_bottom;
		Vector top = m_top;

		NavDrawLine( top, bottom, NavConnectedTwoWaysColor );

		if (m_bottomArea)
		{
			float offset = GenerationStepSize;
			const Vector& areaBottom = m_bottomArea->GetCenter();

			 // don't draw the bottom connection too high if the ladder is very short
			if ( top.z - bottom.z < GenerationStepSize * 1.5f )
				offset = 0.0f;

			 // don't draw the bottom connection too high if the ladder is high above the area
			if ( bottom.z - areaBottom.z > GenerationStepSize * 1.5f )
				offset = 0.0f;

			NavDrawLine( bottom + Vector( 0, 0, offset ), areaBottom, ((m_bottomArea->IsConnected( this, LADDER_UP ))?NavConnectedTwoWaysColor:NavConnectedOneWayColor) );
		}

		if (m_topForwardArea)
			NavDrawLine( top, m_topForwardArea->GetCenter(), ((m_topForwardArea->IsConnected( this, LADDER_DOWN ))?NavConnectedTwoWaysColor:NavConnectedOneWayColor) );

		if (m_topLeftArea)
			NavDrawLine( top, m_topLeftArea->GetCenter(), ((m_topLeftArea->IsConnected( this, LADDER_DOWN ))?NavConnectedTwoWaysColor:NavConnectedOneWayColor) );

		if (m_topRightArea)
			NavDrawLine( top, m_topRightArea->GetCenter(), ((m_topRightArea->IsConnected( this, LADDER_DOWN ))?NavConnectedTwoWaysColor:NavConnectedOneWayColor) );

		if (m_topBehindArea)
			NavDrawLine( top, m_topBehindArea->GetCenter(), ((m_topBehindArea->IsConnected( this, LADDER_DOWN ))?NavConnectedTwoWaysColor:NavConnectedOneWayColor) );
	}
}

//--------------------------------------------------------------------------------------------------------------
void CNavLadder::DrawConnectedAreas( void )
{
	CUtlVector< CNavArea * > areas;
	if ( m_topForwardArea )
		areas.AddToTail( m_topForwardArea );
	if ( m_topLeftArea )
		areas.AddToTail( m_topLeftArea );
	if ( m_topRightArea )
		areas.AddToTail( m_topRightArea );
	if ( m_topBehindArea )
		areas.AddToTail( m_topBehindArea );
	if ( m_bottomArea )
		areas.AddToTail( m_bottomArea );

	for ( int i=0; i<areas.Count(); ++i )
	{
		CNavArea *adj = areas[i];

		adj->Draw();

		if ( ! TheNavMesh->IsPlaceMode() )
		{
			adj->DrawHidingSpots();
		}
	}
}

//--------------------------------------------------------------------------------------------------------------
/**
 * Save a navigation ladder to the opened binary stream
 */
void CNavLadder::Save( FileHandle_t file, unsigned int version ) const
{
	// save ID
	filesystem->Write( &m_id, sizeof(unsigned int), file );

	// save extent of ladder
	filesystem->Write( &m_width, sizeof(float), file );

	// save top endpoint of ladder
	filesystem->Write( &m_top, 3*sizeof(float), file );

	// save bottom endpoint of ladder
	filesystem->Write( &m_bottom, 3*sizeof(float), file );

	// save ladder length
	filesystem->Write( &m_length, sizeof(float), file );

	// save direction
	filesystem->Write( &m_dir, sizeof(m_dir), file );

	// save IDs of connecting areas
	unsigned int id;
	id = ( m_topForwardArea ) ? m_topForwardArea->GetID() : 0;
	filesystem->Write( &id, sizeof(id), file );

	id = ( m_topLeftArea ) ? m_topLeftArea->GetID() : 0;
	filesystem->Write( &id, sizeof(id), file );

	id = ( m_topRightArea ) ? m_topRightArea->GetID() : 0;
	filesystem->Write( &id, sizeof(id), file );

	id = ( m_topBehindArea ) ? m_topBehindArea->GetID() : 0;
	filesystem->Write( &id, sizeof(id), file );

	id = ( m_bottomArea ) ? m_bottomArea->GetID() : 0;
	filesystem->Write( &id, sizeof(id), file );
}

//--------------------------------------------------------------------------------------------------------------
/**
 * Load a navigation ladder from the opened binary stream
 */
void CNavLadder::Load( FileHandle_t file, unsigned int version )
{
	// load ID
	filesystem->Read( &m_id, sizeof(unsigned int), file );

	// update nextID to avoid collisions
	if (m_id >= m_nextID)
		m_nextID = m_id+1;

	// load extent of ladder
	filesystem->Read( &m_width, sizeof(float), file );

	// load top endpoint of ladder
	filesystem->Read( &m_top, 3*sizeof(float), file );

	// load bottom endpoint of ladder
	filesystem->Read( &m_bottom, 3*sizeof(float), file );

	// load ladder length
	filesystem->Read( &m_length, sizeof(float), file );

	// load direction
	filesystem->Read( &m_dir, sizeof(m_dir), file );
	SetDir( m_dir ); // regenerate the surface normal

	// load dangling status
	if ( version == 6 )
	{
		bool m_isDangling;
		filesystem->Read( &m_isDangling, sizeof(m_isDangling), file );
	}

	// load IDs of connecting areas
	unsigned int id;
	filesystem->Read( &id, sizeof(id), file );
	m_topForwardArea = TheNavMesh->GetNavAreaByID( id );

	filesystem->Read( &id, sizeof(id), file );
	m_topLeftArea = TheNavMesh->GetNavAreaByID( id );

	filesystem->Read( &id, sizeof(id), file );
	m_topRightArea = TheNavMesh->GetNavAreaByID( id );

	filesystem->Read( &id, sizeof(id), file );
	m_topBehindArea = TheNavMesh->GetNavAreaByID( id );

	filesystem->Read( &id, sizeof(id), file );
	m_bottomArea = TheNavMesh->GetNavAreaByID( id );
	if ( !m_bottomArea )
	{
		DevMsg( "ERROR: Unconnected ladder #%d bottom at ( %g, %g, %g )\n", m_id, m_bottom.x, m_bottom.y, m_bottom.z );
	}

	// can't include behind area, since it is not used when going up a ladder
	if (!m_topForwardArea && !m_topLeftArea && !m_topRightArea)
		DevMsg( "ERROR: Unconnected ladder #%d top at ( %g, %g, %g )\n", m_id, m_top.x, m_top.y, m_top.z );
}

//--------------------------------------------------------------------------------------------------------------
/**
 * Functor returns true if ladder is free, or false if someone is on the ladder
 */
class IsLadderFreeFunctor
{
public:
	IsLadderFreeFunctor( const CNavLadder *ladder, const CBasePlayer *ignore )
	{
		m_ladder = ladder;
		m_ignore = ignore;
	}

	bool operator() ( CBasePlayer *player )
	{
		if (player == m_ignore)
			return true;

		if (!player->IsOnLadder())
			return true;

		// player is on a ladder - is it this one?
		const Vector &feet = player->GetAbsOrigin();

		if (feet.z > m_ladder->m_top.z + HalfHumanHeight)
			return true;

		if (feet.z + HumanHeight < m_ladder->m_bottom.z - HalfHumanHeight)
			return true;

		Vector2D away( m_ladder->m_bottom.x - feet.x, m_ladder->m_bottom.y - feet.y );
		const float onLadderRange = 50.0f;
		return away.IsLengthGreaterThan( onLadderRange );
	}

	const CNavLadder *m_ladder;
	const CBasePlayer *m_ignore;
};

//--------------------------------------------------------------------------------------------------------------
/**
 * Return true if someone is on this ladder
 */
bool CNavLadder::IsInUse( const CBasePlayer *ignore ) const
{
	IsLadderFreeFunctor	isLadderFree( this, ignore );
	return !ForEachPlayer( isLadderFree );
}

//--------------------------------------------------------------------------------------------------------------
Vector CNavLadder::GetPosAtHeight( float height ) const
{
	if ( height < m_bottom.z )
	{
		return m_bottom;
	}

	if ( height > m_top.z )
	{
		return m_top;
	}

	if ( m_top.z == m_bottom.z )
	{
		return m_top;
	}

	float percent = ( height - m_bottom.z ) / ( m_top.z - m_bottom.z );

	return m_top * percent + m_bottom * ( 1.0f - percent );
}

//--------------------------------------------------------------------------------------------------------------


text:
[Exploratoria]( http://exploratoria.github.io ) » [Exhibits]( http://exploratoria.github.io/exhibits/ ) »

Astronomy & Solar System Read Me
====

<span style="display: none"> [You are now in GitHub source code view - Click here to view Read Me file as a web page]( http://exploratoria.github.io/exhibits/astronomy/index.html 'View file as a web page' ) </span>
<input type=button value="You are now in GitHub web page view - Click here to view Read Me file as source code" onclick="window.location.href='https://github.com/exploratoria/exploratoria.github.io/tree/master/exhibits/astronomy/'" />

## Gravitating System

[Gravitating System - Web Page]( http://exploratoria.github.io/exhibits/astronomy/gravitating-system/index.html )
[Gravitating System - Source Code]( https://github.com/exploratoria/exploratoria.github.io/tree/master/exhibits/astronomy/gravitating-system/ )

## Gravitating System WebXR

[Gravitating System WebXR - Web Page]( http://exploratoria.github.io/exhibits/astronomy/gravitating-system-webxr/index.html )
[Gravitating System WebXR - Source Code]( https://github.com/exploratoria/exploratoria.github.io/tree/master/exhibits/astronomy/gravitating-system-webxr/ )

## Star Spotter

[Star Spotter - Web Page]( http://exploratoria.github.io/exhibits/astronomy/star-spotter/index.html )
[Star Spotter - Source Code]( https://github.com/exploratoria/exploratoria.github.io/tree/master/exhibits/astronomy/star-spotter/ )


text:
using System.Runtime.InteropServices;
using static VCSFramework.Registers;

namespace Samples.CSharpFeatures
{
    // Not a proper VCS program.
    static class StructSample
    {
        private static MultiByteStruct _MultiByteStruct;
        private static CompositeStruct _CompositeStruct;
        private static SingleByteStruct _SingleByteStruct;

        public static void Main()
        {
            //var qq = new SequentialStruct(0x48); // @TODO
            _CompositeStruct = new CompositeStruct
            {
                Value = 0x12,
                StructA = new SequentialStruct
                {
                    ValueA = 0x1,
                    ValueB = 0x56,
                    ValueC = 0x78
                },
                StructB = new AutoStruct
                {
                    Value = 0x9A
                }
            };
            while (true)
            {
                _MultiByteStruct.ValueB = (byte)(_SingleByteStruct.Value + _CompositeStruct.StructA.ValueA);
                _CompositeStruct.StructA.ValueC = _MultiByteStruct.ValueB;
                ColuBk = _CompositeStruct.StructA.ValueC;
                _SingleByteStruct.Value = _MultiByteStruct.ValueB;
            }
        }

        // Doesn't matter if this is declared inside or outside of StructSample.
        [StructLayout(LayoutKind.Explicit)]
        struct SingleByteStruct
        {
            // Note static values already work out of the box.
            [FieldOffset(0)]
            public byte Value;
        }

        [StructLayout(LayoutKind.Explicit)]
        struct MultiByteStruct
        {
            [FieldOffset(0)]
            public byte ValueA;
            [FieldOffset(1)]
            public byte ValueB;
            [FieldOffset(2)]
            public byte ValueC;
        }

        [StructLayout(LayoutKind.Explicit)]
        struct CompositeStruct
        {
            [FieldOffset(0)]
            public byte Value;
            [FieldOffset(1)]
            public SequentialStruct StructA;
            [FieldOffset(9)]
            public AutoStruct StructB;
        }

        [StructLayout(LayoutKind.Sequential, Pack = 0)]
        struct SequentialStruct
        {
            public byte ValueA;
            public byte ValueB;
            public byte ValueC;

            public SequentialStruct(byte value)
            {
                ValueA = ValueB = ValueC = value;
            }
        }

        [StructLayout(LayoutKind.Auto)]
        struct AutoStruct
        {
            public byte Value;
        }
    }
}