text:
package com.intellij.debugger.settings;

import com.intellij.debugger.DebuggerBundle;
import com.intellij.debugger.engine.DebuggerUtils;
import com.intellij.debugger.engine.JVMNameUtil;
import com.intellij.debugger.engine.evaluation.CodeFragmentKind;
import com.intellij.debugger.engine.evaluation.TextWithImports;
import com.intellij.debugger.engine.evaluation.TextWithImportsImpl;
import com.intellij.debugger.impl.DebuggerUtilsEx;
import com.intellij.debugger.impl.DebuggerUtilsImpl;
import com.intellij.debugger.ui.JavaDebuggerSupport;
import com.intellij.debugger.ui.tree.render.*;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.PsiTypeCodeFragmentImpl;
import com.intellij.ui.*;
import com.intellij.ui.components.JBCheckBox;
import com.intellij.ui.table.JBTable;
import com.intellij.util.ui.AbstractTableCellEditor;
import com.intellij.util.ui.JBUI;
import com.intellij.xdebugger.impl.breakpoints.XExpressionImpl;
import com.intellij.xdebugger.impl.ui.XDebuggerExpressionEditor;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.java.debugger.JavaDebuggerEditorsProvider;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;

class CompoundRendererConfigurable extends JPanel {
  private CompoundTypeRenderer myRenderer;
  private CompoundTypeRenderer myOriginalRenderer;
  private Project myProject;
  private final ClassNameEditorWithBrowseButton myClassNameField;
  private final JRadioButton myRbDefaultLabel;
  private final JRadioButton myRbExpressionLabel;
  private final JBCheckBox myShowTypeCheckBox;
  private final JBCheckBox myOnDemandCheckBox;
  private final JRadioButton myRbDefaultChildrenRenderer;
  private final JRadioButton myRbExpressionChildrenRenderer;
  private final JRadioButton myRbListChildrenRenderer;
  private final XDebuggerExpressionEditor myLabelEditor;
  private final XDebuggerExpressionEditor myChildrenEditor;
  private final XDebuggerExpressionEditor myChildrenExpandedEditor;
  private XDebuggerExpressionEditor myListChildrenEditor;
  private final JLabel myExpandedLabel;
  private JBTable myTable;
  private final JBCheckBox myAppendDefaultChildren;
  @NonNls private static final String EMPTY_PANEL_ID = "EMPTY";
  @NonNls private static final String DATA_PANEL_ID = "DATA";
  private static final int NAME_TABLE_COLUMN = 0;
  private static final int EXPRESSION_TABLE_COLUMN = 1;
  private static final int ONDEMAND_TABLE_COLUMN = 2;

  CompoundRendererConfigurable(@NotNull Disposable parentDisposable) {
    super(new CardLayout());

    if (myProject == null) {
      myProject = JavaDebuggerSupport.getContextProjectForEditorFieldsInDebuggerConfigurables();
    }

    myRbDefaultLabel = new JRadioButton(DebuggerBundle.message("label.compound.renderer.configurable.use.default.renderer"));
    myRbExpressionLabel = new JRadioButton(DebuggerBundle.message("label.compound.renderer.configurable.use.expression"));
    final ButtonGroup labelButtonsGroup = new ButtonGroup();
    labelButtonsGroup.add(myRbDefaultLabel);
    labelButtonsGroup.add(myRbExpressionLabel);

    myShowTypeCheckBox = new JBCheckBox(DebuggerBundle.message("label.compound.renderer.configurable.show.type"));
    myOnDemandCheckBox = new JBCheckBox(DebuggerBundle.message("label.compound.renderer.configurable.ondemand"));

    myRbDefaultChildrenRenderer = new JRadioButton(DebuggerBundle.message("label.compound.renderer.configurable.use.default.renderer"));
    myRbExpressionChildrenRenderer = new JRadioButton(DebuggerBundle.message("label.compound.renderer.configurable.use.expression"));
    myRbListChildrenRenderer = new JRadioButton(DebuggerBundle.message("label.compound.renderer.configurable.use.expression.list"));
    final ButtonGroup childrenButtonGroup = new ButtonGroup();
    childrenButtonGroup.add(myRbDefaultChildrenRenderer);
    childrenButtonGroup.add(myRbExpressionChildrenRenderer);
    childrenButtonGroup.add(myRbListChildrenRenderer);

    JavaDebuggerEditorsProvider editorsProvider = new JavaDebuggerEditorsProvider();

    myLabelEditor = new XDebuggerExpressionEditor(myProject, editorsProvider, "ClassLabelExpression", null, XExpressionImpl.EMPTY_EXPRESSION, false, false, true);
    myChildrenEditor = new XDebuggerExpressionEditor(myProject, editorsProvider, "ClassChildrenExpression", null, XExpressionImpl.EMPTY_EXPRESSION, false, false, true);
    myChildrenExpandedEditor = new XDebuggerExpressionEditor(myProject, editorsProvider, "ClassChildrenExpression", null, XExpressionImpl.EMPTY_EXPRESSION, false, false, true);
    JComponent myChildrenListEditor = createChildrenListEditor(editorsProvider);

    final ItemListener updateListener = new ItemListener() {
      @Override
      public void itemStateChanged(@NotNull ItemEvent e) {
        updateEnabledState();
      }
    };
    myRbExpressionLabel.addItemListener(updateListener);
    myRbListChildrenRenderer.addItemListener(updateListener);
    myRbExpressionChildrenRenderer.addItemListener(updateListener);

    myClassNameField = new ClassNameEditorWithBrowseButton(new ActionListener() {
      @Override
      public void actionPerformed(@NotNull ActionEvent e) {
        PsiClass psiClass = DebuggerUtils.getInstance()
          .chooseClassDialog(DebuggerBundle.message("title.compound.renderer.configurable.choose.renderer.reference.type"), myProject);
        if (psiClass != null) {
          String qName = JVMNameUtil.getNonAnonymousClassName(psiClass);
          myClassNameField.setText(qName);
          updateContext(qName);
        }
      }
    }, myProject);
    myClassNameField.getEditorTextField().addFocusListener(new FocusAdapter() {
      @Override
      public void focusLost(@NotNull FocusEvent e) {
        updateContext(myClassNameField.getText());
      }
    });

    myAppendDefaultChildren = new JBCheckBox(DebuggerBundle.message("label.compound.renderer.configurable.append.default.children"));

    JPanel panel = new JPanel(new GridBagLayout());
    panel.add(new JLabel(DebuggerBundle.message("label.compound.renderer.configurable.apply.to")),
              new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE,
                                     JBUI.emptyInsets(), 0, 0));
    panel.add(myClassNameField, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST,
                                                       GridBagConstraints.HORIZONTAL, JBUI.insetsTop(4), 0, 0));

    panel.add(new JLabel(DebuggerBundle.message("label.compound.renderer.configurable.when.rendering")),
              new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE,
                                     JBUI.insetsTop(20), 0, 0));
    panel.add(myShowTypeCheckBox,
              new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE,
                                     JBUI.insetsLeft(7), 0, 0));
    panel.add(myRbDefaultLabel,
              new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE,
                                     JBUI.insetsLeft(10), 0, 0));
    panel.add(myRbExpressionLabel,
              new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE,
                                     JBUI.insetsLeft(10), 0, 0));
    panel.add(myLabelEditor.getComponent(), new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST,
                                                                   GridBagConstraints.HORIZONTAL, JBUI.insetsLeft(30), 0, 0));
    panel.add(myOnDemandCheckBox, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST,
                                                         GridBagConstraints.HORIZONTAL, JBUI.insetsLeft(30), 0, 0));

    panel.add(new JLabel(DebuggerBundle.message("label.compound.renderer.configurable.when.expanding")),
              new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE,
                                     JBUI.insetsTop(20), 0, 0));
    panel.add(myRbDefaultChildrenRenderer,
              new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE,
                                     JBUI.insetsLeft(10), 0, 0));
    panel.add(myRbExpressionChildrenRenderer,
              new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE,
                                     JBUI.insetsLeft(10), 0, 0));
    panel.add(myChildrenEditor.getComponent(), new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST,
                                                                      GridBagConstraints.HORIZONTAL, JBUI.insetsLeft(30), 0, 0));
    myExpandedLabel = new JLabel(DebuggerBundle.message("label.compound.renderer.configurable.test.can.expand"));
    panel.add(myExpandedLabel,
              new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE,
                                     JBUI.insets(4, 30, 0, 0), 0, 0));
    panel.add(myChildrenExpandedEditor.getComponent(), new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST,
                                                                              GridBagConstraints.HORIZONTAL, JBUI.insetsLeft(30), 0, 0));
    panel.add(myRbListChildrenRenderer, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST,
                                                               GridBagConstraints.HORIZONTAL, JBUI.insetsLeft(10), 0, 0));
    panel.add(myChildrenListEditor,
              new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH,
                                     JBUI.insets(4, 30, 0, 0), 0, 0));
    panel.add(myAppendDefaultChildren,
              new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE,
                                     JBUI.insetsLeft(25), 0, 0));
    add(new JPanel(), EMPTY_PANEL_ID);
    add(panel, DATA_PANEL_ID);
  }

  public void setRenderer(NodeRenderer renderer) {
    if (renderer instanceof CompoundTypeRenderer) {
      myRenderer = (CompoundTypeRenderer)renderer;
      myOriginalRenderer = (CompoundTypeRenderer)renderer.clone();
    }
    else {
      myRenderer = myOriginalRenderer = null;
    }
    reset();
  }

  public CompoundTypeRenderer getRenderer() {
    return myRenderer;
  }

  private void updateContext(final String qName) {
    ApplicationManager.getApplication().runReadAction(() -> {
      Project project = myProject;
      if (project != null) {
        Pair<PsiElement, PsiType>pair = DebuggerUtilsImpl.getPsiClassAndType(qName, project);
        PsiElement context = pair.first;
        if (context != null) {
          myLabelEditor.setContext(context);
          myChildrenEditor.setContext(context);
          myChildrenExpandedEditor.setContext(context);
          myListChildrenEditor.setContext(context);
        }
      }
    });
  }

  private void updateEnabledState() {
    boolean isLabelRenderer = myRbExpressionLabel.isSelected();
    myLabelEditor.setEnabled(isLabelRenderer);
    myOnDemandCheckBox.setEnabled(isLabelRenderer);

    final boolean isChildrenExpression = myRbExpressionChildrenRenderer.isSelected();
    myChildrenExpandedEditor.setEnabled(isChildrenExpression);
    myExpandedLabel.setEnabled(isChildrenExpression);
    myChildrenEditor.setEnabled(isChildrenExpression);

    boolean isListChildren = myRbListChildrenRenderer.isSelected();
    myTable.setEnabled(isListChildren);
    myAppendDefaultChildren.setEnabled(isListChildren);
  }

  private JComponent createChildrenListEditor(JavaDebuggerEditorsProvider editorsProvider) {
    final MyTableModel tableModel = new MyTableModel();
    myTable = new JBTable(tableModel);
    myListChildrenEditor = new XDebuggerExpressionEditor(myProject, editorsProvider, "NamedChildrenConfigurable", null, XExpressionImpl.EMPTY_EXPRESSION, false, false, false);
    JComponent editorComponent = myListChildrenEditor.getComponent();

    AbstractTableCellEditor editor = new AbstractTableCellEditor() {
      @Override
      public Object getCellEditorValue() {
        return TextWithImportsImpl.fromXExpression(myListChildrenEditor.getExpression());
      }

      @Override
      public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        myListChildrenEditor.setExpression(TextWithImportsImpl.toXExpression((TextWithImports)value));
        return editorComponent;
      }
    };
    editorComponent.registerKeyboardAction(e -> editor.stopCellEditing(), KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0),
                           JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    editorComponent.registerKeyboardAction(e -> editor.cancelCellEditing(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
                           JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);

    TableColumn exprColumn = myTable.getColumnModel().getColumn(EXPRESSION_TABLE_COLUMN);
    exprColumn.setCellEditor(editor);
    exprColumn.setCellRenderer(new DefaultTableCellRenderer() {
      @NotNull
      @Override
      public Component getTableCellRendererComponent(@NotNull JTable table,
                                                     Object value,
                                                     boolean isSelected,
                                                     boolean hasFocus,
                                                     int row,
                                                     int column) {
        final TextWithImports textWithImports = (TextWithImports)value;
        final String text = (textWithImports != null) ? textWithImports.getText() : "";
        return super.getTableCellRendererComponent(table, text, isSelected, hasFocus, row, column);
      }
    });

    return ToolbarDecorator.createDecorator(myTable)
      .setAddAction(new AnActionButtonRunnable() {
        @Override
        public void run(AnActionButton button) {
          tableModel.addRow("", DebuggerUtils.getInstance().createExpressionWithImports(""));
        }
      }).setRemoveAction(new AnActionButtonRunnable() {
        @Override
        public void run(AnActionButton button) {
          int selectedRow = myTable.getSelectedRow();
          if (selectedRow >= 0 && selectedRow < myTable.getRowCount()) {
            getTableModel().removeRow(selectedRow);
          }
        }
      }).setMoveUpAction(new AnActionButtonRunnable() {
        @Override
        public void run(AnActionButton button) {
          TableUtil.moveSelectedItemsUp(myTable);
        }
      }).setMoveDownAction(new AnActionButtonRunnable() {
        @Override
        public void run(AnActionButton button) {
          TableUtil.moveSelectedItemsDown(myTable);
        }
      }).createPanel();
  }

  public boolean isModified() {
    if (myRenderer == null) {
      return false;
    }
    final CompoundTypeRenderer cloned = (CompoundTypeRenderer)myRenderer.clone();
    flushDataTo(cloned);
    return !DebuggerUtilsEx.externalizableEqual(cloned, myOriginalRenderer);
  }

  public void apply() {
    if (myRenderer == null) {
      return;
    }
    flushDataTo(myRenderer);
    // update the renderer to compare with in order to find out whether we've been modified since last apply
    myOriginalRenderer = (CompoundTypeRenderer)myRenderer.clone();
  }

  private void flushDataTo(final CompoundTypeRenderer renderer) { // label
    LabelRenderer labelRenderer = null;
    renderer.setShowType(myShowTypeCheckBox.isSelected());
    if (myRbExpressionLabel.isSelected()) {
      labelRenderer = new LabelRenderer();
      labelRenderer.setLabelExpression(TextWithImportsImpl.fromXExpression(myLabelEditor.getExpression()));
      labelRenderer.setOnDemand(myOnDemandCheckBox.isSelected());
    }
    renderer.setLabelRenderer(labelRenderer);
    // children
    ChildrenRenderer childrenRenderer = null;
    if (myRbExpressionChildrenRenderer.isSelected()) {
      childrenRenderer = new ExpressionChildrenRenderer();
      ((ExpressionChildrenRenderer)childrenRenderer).setChildrenExpression(TextWithImportsImpl.fromXExpression(myChildrenEditor.getExpression()));
      ((ExpressionChildrenRenderer)childrenRenderer).setChildrenExpandable(TextWithImportsImpl.fromXExpression(myChildrenExpandedEditor.getExpression()));
    }
    else if (myRbListChildrenRenderer.isSelected()) {
      EnumerationChildrenRenderer enumerationChildrenRenderer = new EnumerationChildrenRenderer(getTableModel().getExpressions());
      enumerationChildrenRenderer.setAppendDefaultChildren(myAppendDefaultChildren.isSelected());
      childrenRenderer = enumerationChildrenRenderer;
    }
    renderer.setChildrenRenderer(childrenRenderer);
    // classname
    renderer.setClassName(myClassNameField.getText());
  }

  public void reset() {
    final TextWithImports emptyExpressionFragment = new TextWithImportsImpl(CodeFragmentKind.EXPRESSION, "");
    ((CardLayout)getLayout()).show(this, myRenderer == null ? EMPTY_PANEL_ID : DATA_PANEL_ID);
    if (myRenderer == null) {
      return;
    }
    final String className = myRenderer.getClassName();
    myClassNameField.setText(className);

    updateContext(className);

    final ValueLabelRenderer labelRenderer = myRenderer.getLabelRenderer();
    final ChildrenRenderer childrenRenderer = myRenderer.getChildrenRenderer();

    myShowTypeCheckBox.setSelected(myRenderer.isShowType());

    if (myRenderer.isBaseRenderer(labelRenderer)) {
      myLabelEditor.setExpression(TextWithImportsImpl.toXExpression(emptyExpressionFragment));
      myRbDefaultLabel.setSelected(true);
      myOnDemandCheckBox.setSelected(false);
    }
    else {
      myRbExpressionLabel.setSelected(true);
      LabelRenderer lr = (LabelRenderer)labelRenderer;
      myLabelEditor.setExpression(TextWithImportsImpl.toXExpression(lr.getLabelExpression()));
      myOnDemandCheckBox.setSelected(lr.isOnDemand());
    }

    getTableModel().clear();
    myAppendDefaultChildren.setSelected(false);

    if (myRenderer.isBaseRenderer(childrenRenderer)) {
      myRbDefaultChildrenRenderer.setSelected(true);
      myChildrenEditor.setExpression(TextWithImportsImpl.toXExpression(emptyExpressionFragment));
      myChildrenExpandedEditor.setExpression(TextWithImportsImpl.toXExpression(emptyExpressionFragment));
    }
    else if (childrenRenderer instanceof ExpressionChildrenRenderer) {
      myRbExpressionChildrenRenderer.setSelected(true);
      final ExpressionChildrenRenderer exprRenderer = (ExpressionChildrenRenderer)childrenRenderer;
      myChildrenEditor.setExpression(TextWithImportsImpl.toXExpression(exprRenderer.getChildrenExpression()));
      myChildrenExpandedEditor.setExpression(TextWithImportsImpl.toXExpression(exprRenderer.getChildrenExpandable()));
    }
    else {
      myRbListChildrenRenderer.setSelected(true);
      myChildrenEditor.setExpression(TextWithImportsImpl.toXExpression(emptyExpressionFragment));
      myChildrenExpandedEditor.setExpression(TextWithImportsImpl.toXExpression(emptyExpressionFragment));
      if (childrenRenderer instanceof EnumerationChildrenRenderer) {
        EnumerationChildrenRenderer enumerationRenderer = (EnumerationChildrenRenderer)childrenRenderer;
        getTableModel().init(enumerationRenderer.getChildren());
        myAppendDefaultChildren.setSelected(enumerationRenderer.isAppendDefaultChildren());
      }
    }

    updateEnabledState();
  }

  private MyTableModel getTableModel() {
    return (MyTableModel)myTable.getModel();
  }

  private static final class MyTableModel extends AbstractTableModel {
    private final List<EnumerationChildrenRenderer.ChildInfo> myData = new ArrayList<>();

    MyTableModel() {
    }

    public void init(List<EnumerationChildrenRenderer.ChildInfo> data) {
      myData.clear();
      for (EnumerationChildrenRenderer.ChildInfo childInfo : data) {
        myData.add(new EnumerationChildrenRenderer.ChildInfo(childInfo.myName, childInfo.myExpression, childInfo.myOnDemand));
      }
      fireTableDataChanged();
    }

    @Override
    public int getColumnCount() {
      return 3;
    }

    @Override
    public int getRowCount() {
      return myData.size();
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
      return true;
    }

    @NotNull
    @Override
    public Class getColumnClass(int columnIndex) {
      switch (columnIndex) {
        case NAME_TABLE_COLUMN:
          return String.class;
        case EXPRESSION_TABLE_COLUMN:
          return TextWithImports.class;
        case ONDEMAND_TABLE_COLUMN:
          return Boolean.class;
        default:
          return super.getColumnClass(columnIndex);
      }
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
      if (rowIndex >= getRowCount()) {
        return null;
      }
      final EnumerationChildrenRenderer.ChildInfo row = myData.get(rowIndex);
      switch (columnIndex) {
        case NAME_TABLE_COLUMN:
          return row.myName;
        case EXPRESSION_TABLE_COLUMN:
          return row.myExpression;
        case ONDEMAND_TABLE_COLUMN:
          return row.myOnDemand;
        default:
          return null;
      }
    }

    @Override
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
      if (rowIndex >= getRowCount()) {
        return;
      }
      final EnumerationChildrenRenderer.ChildInfo row = myData.get(rowIndex);
      switch (columnIndex) {
        case NAME_TABLE_COLUMN:
          row.myName = (String)aValue;
          break;
        case EXPRESSION_TABLE_COLUMN:
          row.myExpression = (TextWithImports)aValue;
          break;
        case ONDEMAND_TABLE_COLUMN:
          row.myOnDemand = (Boolean)aValue;
          break;
      }
    }

    @NotNull
    @Override
    public String getColumnName(int columnIndex) {
      switch (columnIndex) {
        case NAME_TABLE_COLUMN:
          return DebuggerBundle.message("label.compound.renderer.configurable.table.header.name");
        case EXPRESSION_TABLE_COLUMN:
          return DebuggerBundle.message("label.compound.renderer.configurable.table.header.expression");
        case ONDEMAND_TABLE_COLUMN:
          return DebuggerBundle.message("label.compound.renderer.configurable.table.header.ondemand");
        default:
          return "";
      }
    }

    public void addRow(final String name, final TextWithImports expressionWithImports) {
      myData.add(new EnumerationChildrenRenderer.ChildInfo(name, expressionWithImports, false));
      final int lastRow = myData.size() - 1;
      fireTableRowsInserted(lastRow, lastRow);
    }

    public void removeRow(final int row) {
      if (row >= 0 && row < myData.size()) {
        myData.remove(row);
        fireTableRowsDeleted(row, row);
      }
    }

    public void clear() {
      myData.clear();
      fireTableDataChanged();
    }

    public List<EnumerationChildrenRenderer.ChildInfo> getExpressions() {
      return myData;
    }

    private static final class Row {
      public String name;
      public TextWithImports value;

      Row(final String name, final TextWithImports value) {
        this.name = name;
        this.value = value;
      }
    }
  }

  private static class ClassNameEditorWithBrowseButton extends ReferenceEditorWithBrowseButton {
    private ClassNameEditorWithBrowseButton(ActionListener browseActionListener, final Project project) {
      super(browseActionListener, project,
            s -> {
              JavaCodeFragment fragment = new PsiTypeCodeFragmentImpl(project, true, "fragment.java", s, 0, null) {
                @Override
                public boolean importClass(@NotNull PsiClass aClass) {
                  return false;
                }
              };
              fragment.setVisibilityChecker(JavaCodeFragment.VisibilityChecker.EVERYTHING_VISIBLE);
              return PsiDocumentManager.getInstance(project).getDocument(fragment);
            }, "");
    }
  }
}


text:
.. _metadata_ddl_toplevel:
.. _metadata_ddl:
.. module:: sqlalchemy.schema

Customizing DDL
===============

In the preceding sections we've discussed a variety of schema constructs
including :class:`~sqlalchemy.schema.Table`,
:class:`~sqlalchemy.schema.ForeignKeyConstraint`,
:class:`~sqlalchemy.schema.CheckConstraint`, and
:class:`~sqlalchemy.schema.Sequence`. Throughout, we've relied upon the
``create()`` and :func:`~sqlalchemy.schema.MetaData.create_all` methods of
:class:`~sqlalchemy.schema.Table` and :class:`~sqlalchemy.schema.MetaData` in
order to issue data definition language (DDL) for all constructs. When issued,
a pre-determined order of operations is invoked, and DDL to create each table
is created unconditionally including all constraints and other objects
associated with it. For more complex scenarios where database-specific DDL is
required, SQLAlchemy offers two techniques which can be used to add any DDL
based on any condition, either accompanying the standard generation of tables
or by itself.

Custom DDL
----------

Custom DDL phrases are most easily achieved using the
:class:`~sqlalchemy.schema.DDL` construct. This construct works like all the
other DDL elements except it accepts a string which is the text to be emitted:

.. sourcecode:: python+sql

    event.listen(
        metadata,
        "after_create",
        DDL("ALTER TABLE users ADD CONSTRAINT "
            "cst_user_name_length "
            " CHECK (length(user_name) >= 8)")
    )

A more comprehensive method of creating libraries of DDL constructs is to use
custom compilation - see :ref:`sqlalchemy.ext.compiler_toplevel` for
details.

.. _schema_ddl_sequences:

Controlling DDL Sequences
-------------------------

The :class:`~.schema.DDL` construct introduced previously also has the
ability to be invoked conditionally based on inspection of the
database.  This feature is available using the :meth:`.DDLElement.execute_if`
method.  For example, if we wanted to create a trigger but only on
the PostgreSQL backend, we could invoke this as::

    mytable = Table(
        'mytable', metadata,
        Column('id', Integer, primary_key=True),
        Column('data', String(50))
    )

    trigger = DDL(
        "CREATE TRIGGER dt_ins BEFORE INSERT ON mytable "
        "FOR EACH ROW BEGIN SET NEW.data='ins'; END"
    )

    event.listen(
        mytable,
        'after_create',
        trigger.execute_if(dialect='postgresql')
    )

The :paramref:`.DDLElement.execute_if.dialect` keyword also accepts a tuple
of string dialect names::

    event.listen(
        mytable,
        "after_create",
        trigger.execute_if(dialect=('postgresql', 'mysql'))
    )
    event.listen(
        mytable,
        "before_drop",
        trigger.execute_if(dialect=('postgresql', 'mysql'))
    )

The :meth:`.DDLElement.execute_if` method can also work against a callable
function that will receive the database connection in use.  In the
example below, we use this to conditionally create a CHECK constraint,
first looking within the PostgreSQL catalogs to see if it exists:

.. sourcecode:: python+sql

    def should_create(ddl, target, connection, **kw):
        row = connection.execute(
            "select conname from pg_constraint where conname='%s'" %
            ddl.element.name).scalar()
        return not bool(row)

    def should_drop(ddl, target, connection, **kw):
        return not should_create(ddl, target, connection, **kw)

    event.listen(
        users,
        "after_create",
        DDL(
            "ALTER TABLE users ADD CONSTRAINT "
            "cst_user_name_length CHECK (length(user_name) >= 8)"
        ).execute_if(callable_=should_create)
    )
    event.listen(
        users,
        "before_drop",
        DDL(
            "ALTER TABLE users DROP CONSTRAINT cst_user_name_length"
        ).execute_if(callable_=should_drop)
    )

    {sql}users.create(engine)
    CREATE TABLE users (
        user_id SERIAL NOT NULL,
        user_name VARCHAR(40) NOT NULL,
        PRIMARY KEY (user_id)
    )

    select conname from pg_constraint where conname='cst_user_name_length'
    ALTER TABLE users ADD CONSTRAINT cst_user_name_length  CHECK (length(user_name) >= 8){stop}

    {sql}users.drop(engine)
    select conname from pg_constraint where conname='cst_user_name_length'
    ALTER TABLE users DROP CONSTRAINT cst_user_name_length
    DROP TABLE users{stop}

Using the built-in DDLElement Classes
--------------------------------------

The ``sqlalchemy.schema`` package contains SQL expression constructs that
provide DDL expressions. For example, to produce a ``CREATE TABLE`` statement:

.. sourcecode:: python+sql

    from sqlalchemy.schema import CreateTable
    {sql}engine.execute(CreateTable(mytable))
    CREATE TABLE mytable (
        col1 INTEGER,
        col2 INTEGER,
        col3 INTEGER,
        col4 INTEGER,
        col5 INTEGER,
        col6 INTEGER
    ){stop}

Above, the :class:`~sqlalchemy.schema.CreateTable` construct works like any
other expression construct (such as ``select()``, ``table.insert()``, etc.).
All of SQLAlchemy's DDL oriented constructs are subclasses of
the :class:`.DDLElement` base class; this is the base of all the
objects corresponding to CREATE and DROP as well as ALTER,
not only in SQLAlchemy but in Alembic Migrations as well.
A full reference of available constructs is in :ref:`schema_api_ddl`.

User-defined DDL constructs may also be created as subclasses of
:class:`.DDLElement` itself.   The documentation in
:ref:`sqlalchemy.ext.compiler_toplevel` has several examples of this.

The event-driven DDL system described in the previous section
:ref:`schema_ddl_sequences` is available with other :class:`.DDLElement`
objects as well.  However, when dealing with the built-in constructs
such as :class:`.CreateIndex`, :class:`.CreateSequence`, etc, the event
system is of **limited** use, as methods like :meth:`.Table.create` and
:meth:`.MetaData.create_all` will invoke these constructs unconditionally.
In a future SQLAlchemy release, the DDL event system including conditional
execution will taken into account for built-in constructs that currently
invoke in all cases.

We can illustrate an event-driven
example with the :class:`.AddConstraint` and :class:`.DropConstraint`
constructs, as the event-driven system will work for CHECK and UNIQUE
constraints, using these as we did in our previous example of
:meth:`.DDLElement.execute_if`:

.. sourcecode:: python+sql

    def should_create(ddl, target, connection, **kw):
        row = connection.execute(
            "select conname from pg_constraint where conname='%s'" %
            ddl.element.name).scalar()
        return not bool(row)

    def should_drop(ddl, target, connection, **kw):
        return not should_create(ddl, target, connection, **kw)

    event.listen(
        users,
        "after_create",
        AddConstraint(constraint).execute_if(callable_=should_create)
    )
    event.listen(
        users,
        "before_drop",
        DropConstraint(constraint).execute_if(callable_=should_drop)
    )

    {sql}users.create(engine)
    CREATE TABLE users (
        user_id SERIAL NOT NULL,
        user_name VARCHAR(40) NOT NULL,
        PRIMARY KEY (user_id)
    )

    select conname from pg_constraint where conname='cst_user_name_length'
    ALTER TABLE users ADD CONSTRAINT cst_user_name_length  CHECK (length(user_name) >= 8){stop}

    {sql}users.drop(engine)
    select conname from pg_constraint where conname='cst_user_name_length'
    ALTER TABLE users DROP CONSTRAINT cst_user_name_length
    DROP TABLE users{stop}

While the above example is against the built-in :class:`.AddConstraint`
and :class:`.DropConstraint` objects, the main usefulness of DDL events
for now remains focused on the use of the :class:`.DDL` construct itself,
as well as with user-defined subclasses of :class:`.DDLElement` that aren't
already part of the :meth:`.MetaData.create_all`, :meth:`.Table.create`,
and corresponding "drop" processes.

.. _schema_api_ddl:

DDL Expression Constructs API
-----------------------------

.. autofunction:: sort_tables

.. autofunction:: sort_tables_and_constraints

.. autoclass:: DDLElement
    :members:
    :undoc-members:

.. autoclass:: DDL
    :members:
    :undoc-members:

.. autoclass:: _CreateDropBase

.. autoclass:: CreateTable
    :members:
    :undoc-members:

.. autoclass:: DropTable
    :members:
    :undoc-members:

.. autoclass:: CreateColumn
    :members:
    :undoc-members:

.. autoclass:: CreateSequence
    :members:
    :undoc-members:

.. autoclass:: DropSequence
    :members:
    :undoc-members:

.. autoclass:: CreateIndex
    :members:
    :undoc-members:

.. autoclass:: DropIndex
    :members:
    :undoc-members:

.. autoclass:: AddConstraint
    :members:
    :undoc-members:

.. autoclass:: DropConstraint
    :members:
    :undoc-members:

.. autoclass:: CreateSchema
    :members:
    :undoc-members:

.. autoclass:: DropSchema
    :members:
    :undoc-members:

redpajama_set_name: RedPajamaGithub


text:
@echo off
pushd %~dp0
"%VS120COMNTOOLS%..\IDE\mstest" /test:Microsoft.Protocols.TestSuites.MS_OXWSCORE.S03_ManageDistributionListsItems.MSOXWSCORE_S03_TC11_GetDistributionListsItemWithConvertHtmlCodePageToUTF8 /testcontainer:..\..\MS-OXWSCORE\TestSuite\bin\Debug\MS-OXWSCORE_TestSuite.dll /runconfig:..\..\MS-OXWSCORE\MS-OXWSCORE.testsettings /unique
pause


text:
'use strict';

var HelloSignResource = require('../HelloSignResource');
var hellosignMethod = HelloSignResource.method;

module.exports = HelloSignResource.extend({
    path: 'unclaimed_draft',

    create: hellosignMethod({
        path: '/create',
        method: 'POST'
    }),
    createEmbedded: hellosignMethod({
        path: '/create_embedded',
        method: 'POST',
        appRequest: true
    }),
    createEmbeddedWithTemplate: hellosignMethod({
        path: '/create_embedded_with_template',
        method: 'POST',
        appRequest: true
    }),
    editAndResend: hellosignMethod({
        path: '/edit_and_resend/{signatureRequestId}',
        method: 'POST',
        appRequest: true,
        urlParams: ['signatureRequestId']
    })

});


text:
<?php

namespace SabreForRainLoop\DAV;

class TemporaryFileFilterPlugin extends ServerPlugin {

    /**
     * This is the list of patterns we intercept.
     * If new patterns are added, they must be valid patterns for preg_match.
     *
     * @var array
     */
    public $temporaryFilePatterns = array(
        '/^\._(.*)$/',     // OS/X resource forks
        '/^.DS_Store$/',   // OS/X custom folder settings
        '/^desktop.ini$/', // Windows custom folder settings
        '/^Thumbs.db$/',   // Windows thumbnail cache
        '/^.(.*).swp$/',   // ViM temporary files
        '/^\.dat(.*)$/',   // Smultron seems to create these
        '/^~lock.(.*)#$/', // Windows 7 lockfiles
    );

    /**
     * A reference to the main Server class
     *
     * @var SabreForRainLoop\DAV\Server
     */
    protected $server;

    /**
     * This is the directory where this plugin
     * will store it's files.
     *
     * @var string
     */
    private $dataDir;

    /**
     * Creates the plugin.
     *
     * Make sure you specify a directory for your files. If you don't, we
     * will use PHP's directory for session-storage instead, and you might
     * not want that.
     *
     * @param string|null $dataDir
     */
    public function __construct($dataDir = null) {

        if (!$dataDir) $dataDir = ini_get('session.save_path').'/sabredav/';
        if (!is_dir($dataDir)) mkdir($dataDir);
        $this->dataDir = $dataDir;

    }

    /**
     * Initialize the plugin
     *
     * This is called automatically be the Server class after this plugin is
     * added with SabreForRainLoop\DAV\Server::addPlugin()
     *
     * @param Server $server
     * @return void
     */
    public function initialize(Server $server) {

        $this->server = $server;
        $server->subscribeEvent('beforeMethod',array($this,'beforeMethod'));
        $server->subscribeEvent('beforeCreateFile',array($this,'beforeCreateFile'));

    }

    /**
     * This method is called before any HTTP method handler
     *
     * This method intercepts any GET, DELETE, PUT and PROPFIND calls to
     * filenames that are known to match the 'temporary file' regex.
     *
     * @param string $method
     * @param string $uri
     * @return bool
     */
    public function beforeMethod($method, $uri) {

        if (!$tempLocation = $this->isTempFile($uri))
            return true;

        switch($method) {
            case 'GET' :
                return $this->httpGet($tempLocation);
            case 'PUT' :
                return $this->httpPut($tempLocation);
            case 'PROPFIND' :
                return $this->httpPropfind($tempLocation, $uri);
            case 'DELETE' :
                return $this->httpDelete($tempLocation);
         }
         return true;

    }

    /**
     * This method is invoked if some subsystem creates a new file.
     *
     * This is used to deal with HTTP LOCK requests which create a new
     * file.
     *
     * @param string $uri
     * @param resource $data
     * @return bool
     */
    public function beforeCreateFile($uri,$data) {

        if ($tempPath = $this->isTempFile($uri)) {

            $hR = $this->server->httpResponse;
            $hR->setHeader('X-Sabre-Temp','true');
            file_put_contents($tempPath,$data);
            return false;
        }
        return true;

    }

    /**
     * This method will check if the url matches the temporary file pattern
     * if it does, it will return an path based on $this->dataDir for the
     * temporary file storage.
     *
     * @param string $path
     * @return boolean|string
     */
    protected function isTempFile($path) {

        // We're only interested in the basename.
        list(, $tempPath) = URLUtil::splitPath($path);

        foreach($this->temporaryFilePatterns as $tempFile) {

            if (preg_match($tempFile,$tempPath)) {
                return $this->getDataDir() . '/sabredav_' . md5($path) . '.tempfile';
            }

        }

        return false;

    }

    /**
     * This method handles the GET method for temporary files.
     * If the file doesn't exist, it will return false which will kick in
     * the regular system for the GET method.
     *
     * @param string $tempLocation
     * @return bool
     */
    public function httpGet($tempLocation) {

        if (!file_exists($tempLocation)) return true;

        $hR = $this->server->httpResponse;
        $hR->setHeader('Content-Type','application/octet-stream');
        $hR->setHeader('Content-Length',filesize($tempLocation));
        $hR->setHeader('X-Sabre-Temp','true');
        $hR->sendStatus(200);
        $hR->sendBody(fopen($tempLocation,'r'));
        return false;

    }

    /**
     * This method handles the PUT method.
     *
     * @param string $tempLocation
     * @return bool
     */
    public function httpPut($tempLocation) {

        $hR = $this->server->httpResponse;
        $hR->setHeader('X-Sabre-Temp','true');

        $newFile = !file_exists($tempLocation);

        if (!$newFile && ($this->server->httpRequest->getHeader('If-None-Match'))) {
             throw new Exception\PreconditionFailed('The resource already exists, and an If-None-Match header was supplied');
        }

        file_put_contents($tempLocation,$this->server->httpRequest->getBody());
        $hR->sendStatus($newFile?201:200);
        return false;

    }

    /**
     * This method handles the DELETE method.
     *
     * If the file didn't exist, it will return false, which will make the
     * standard HTTP DELETE handler kick in.
     *
     * @param string $tempLocation
     * @return bool
     */
    public function httpDelete($tempLocation) {

        if (!file_exists($tempLocation)) return true;

        unlink($tempLocation);
        $hR = $this->server->httpResponse;
        $hR->setHeader('X-Sabre-Temp','true');
        $hR->sendStatus(204);
        return false;

    }

    /**
     * This method handles the PROPFIND method.
     *
     * It's a very lazy method, it won't bother checking the request body
     * for which properties were requested, and just sends back a default
     * set of properties.
     *
     * @param string $tempLocation
     * @param string $uri
     * @return bool
     */
    public function httpPropfind($tempLocation, $uri) {

        if (!file_exists($tempLocation)) return true;

        $hR = $this->server->httpResponse;
        $hR->setHeader('X-Sabre-Temp','true');
        $hR->sendStatus(207);
        $hR->setHeader('Content-Type','application/xml; charset=utf-8');

        $this->server->parsePropFindRequest($this->server->httpRequest->getBody(true));

        $properties = array(
            'href' => $uri,
            200 => array(
                '{DAV:}getlastmodified' => new Property\GetLastModified(filemtime($tempLocation)),
                '{DAV:}getcontentlength' => filesize($tempLocation),
                '{DAV:}resourcetype' => new Property\ResourceType(null),
                '{'.Server::NS_SABREDAV.'}tempFile' => true,

            ),
         );

        $data = $this->server->generateMultiStatus(array($properties));
        $hR->sendBody($data);
        return false;

    }

    /**
     * This method returns the directory where the temporary files should be stored.
     *
     * @return string
     */
    protected function getDataDir()
    {
        return $this->dataDir;
    }
}


text:
<include file="Public:head"/>
<include file="School:class"/>

您的位置: 分类管理 > 学期分类管理
  刷新

      <form class="form" method="post" action="" target="_top" enctype="multipart/form-data">

    名称
    排序
    操作

     <input type="hidden" name="add[sid][]" readonly="readonly" disabled="disabled" value="" style="width:20px;">

            <input type="text" name="add[sname][]" value="" placeholder="请填写选项标题" class="px" style="width:120px;">

            <input type="text" name="add[ssort][]" value="" style="width:20px;" class="px">

        删除
          添加

     <input type="hidden" name="add[sid][]" readonly="readonly" disabled="disabled" value="" style="width:20px;">

            <input type="text" name="add[sname][]" value="" placeholder="请填写选项标题" class="px" style="width:120px;">

            <input type="text" name="add[ssort][]" value="" style="width:20px;" class="px">

        删除
          添加

      <input type="hidden" name="add[sid][]" readonly="readonly" disabled="disabled" value="" style="width:50px;">

            <input type="text" name="add[sname][]" value="" placeholder="请填写选项标题" class="px" style="width:120px;">

            <input type="text" name="add[ssort][]" value="" style="width:20px;" class="px">

        删除
          添加

      <input type="hidden" name="add[sid][]" readonly="readonly" disabled="disabled" value="" style="width:50px;">

            <input type="text" name="add[sname][]" placeholder="请填写选项标题" value="" class="px" style="width:120px;">

            <input type="text" name="add[ssort][]" value="" style="width:20px;" class="px">

        删除
          添加

     <input type="hidden" name="add[sid][]" readonly="readonly" disabled="disabled" value="" style="width:50px;">

            <input type="text" name="add[sname][]" value="" placeholder="请填写选项标题" class="px" style="width:120px;">

            <input type="text" name="add[ssort][]" value="" style="width:20px;" class="px">

        删除
          添加

     <input type="hidden" name="add[sid][]" readonly="readonly" disabled="disabled" value="" style="width:50px;">

            <input type="text" name="add[sname][]" value="" placeholder="请填写选项标题" class="px" style="width:120px;">

            <input type="text" name="add[ssort][]" value="" style="width:20px;" class="px">

        删除
          添加

     <input type="hidden" name="add[sid][]" readonly="readonly" disabled="disabled" value="" style="width:50px;">

            <input type="text" name="add[sname][]" value="" placeholder="请填写选项标题" class="px" style="width:120px;">

            <input type="text" name="add[ssort][]" value="" style="width:20px;" class="px">

         删除
          添加

     <input type="hidden" name="add[sid][]" readonly="readonly" disabled="disabled" value="" style="width:50px;">

            <input type="text" name="add[sname][]" value="" placeholder="请填写选项标题" class="px" style="width:120px;">

            <input type="text" name="add[ssort][]" value="" style="width:20px;" class="px">

         删除
          添加

     <input type="hidden" name="add[sid][]" readonly="readonly" disabled="disabled" value="" style="width:50px;">

            <input type="text" name="add[sname][]" value="" placeholder="请填写选项标题" class="px" style="width:120px;">

            <input type="text" name="add[ssort][]" value="" style="width:20px;" class="px">

         删除
          添加

     <input type="hidden" name="add[sid][]" readonly="readonly" disabled="disabled" value="" style="width:50px;">

            <input type="text" name="add[sname][]" value="" placeholder="请填写选项标题" class="px" style="width:120px;">

            <input type="text" name="add[ssort][]" value="" style="width:20px;" class="px">

          删除

                添加顶级分类

    </form>

<include file="Public:footer"/>


text:
<?php

namespace wfcreations\metronic\bundles\pages\styles;

use yii\web\AssetBundle;

class InvoiceAsset extends AssetBundle {

    public $sourcePath = '@wfcreations/metronic/assets/admin/pages/';
    public $css = [
        'css/invoice.css',
    ];

}


text:
package org.nd4j.linalg.api.ops.impl.scalar;

import org.nd4j.autodiff.samediff.SDVariable;
import org.nd4j.autodiff.samediff.SameDiff;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.BaseScalarOp;

import java.util.Arrays;
import java.util.List;

/**
 * Scalar addition
 *
 * @author Adam Gibson
 */
public class ScalarAdd extends BaseScalarOp {

    public ScalarAdd() {}

    public ScalarAdd(INDArray x, INDArray y, INDArray z, long n, Number num) {
        super(x, y, z, n, num);
    }

    public ScalarAdd(INDArray x, Number num) {
        super(x, num);
    }

    public ScalarAdd(INDArray arr) {
        this(arr, 0);
    }

    public ScalarAdd(SameDiff sameDiff, SDVariable i_v, Number scalar, boolean inPlace) {
        super(sameDiff, i_v, scalar, inPlace);

    }

    public ScalarAdd(SameDiff sameDiff, SDVariable i_v, Number scalar, boolean inPlace, Object[] extraArgs) {
        super(sameDiff, i_v, scalar, inPlace, extraArgs);
    }

    public ScalarAdd(SameDiff sameDiff, SDVariable i_v, Number scalar, Object[] extraArgs) {
        super(sameDiff, i_v, scalar, extraArgs);
    }

    @Override
    public int opNum() {
        return 0;
    }

    @Override
    public String opName() {
        return "add_scalar";
    }

    @Override
    public String onnxName() {
        return "Add";
    }

    @Override
    public String tensorflowName() {
        return "RealAdd";
    }

    @Override
    public List<SDVariable> doDiff(List<SDVariable> i_v1) {
        SDVariable g = i_v1.get(0);
        return Arrays.asList(g);
    }
}


text:
module.exports = function(fn) {
  return function(a, b, c) {
    return fn.apply(null, arguments);
  };
};


text:
<!doctype html>

	<title>Live input effects</title>
    <ascript src="http://cwilso.github.io/AudioContext-MonkeyPatch/AudioContextMonkeyPatch.js"></ascript>

Input:
		<select id="audioinput" onchange="changeInput(this.selectedIndex);">
			<option>default (selection not supported)</option>
		</select>

	<canvas id="view1" width="750" height="200"></canvas>

	<canvas id="view2" width="750" height="200"></canvas>

		<input type="radio" name="radioSet" value="data"
		onmousedown="analyserView1.setAnalysisType(ANALYSISTYPE_FREQUENCY); analyserView2.setAnalysisType(ANALYSISTYPE_FREQUENCY);">Frequency
		<input type="radio" name="radioSet" value="data"
		onmousedown="analyserView1.setAnalysisType(ANALYSISTYPE_SONOGRAM); analyserView2.setAnalysisType(ANALYSISTYPE_SONOGRAM);">Sonogram
		<input type="radio" name="radioSet" value="data" checked="checked"
		onmousedown="analyserView1.setAnalysisType(ANALYSISTYPE_3D_SONOGRAM); analyserView2.setAnalysisType(ANALYSISTYPE_3D_SONOGRAM);">3D Sonogram
		<input type="radio" name="radioSet" value="data"
		onmousedown="analyserView1.setAnalysisType(ANALYSISTYPE_WAVEFORM); analyserView2.setAnalysisType(ANALYSISTYPE_WAVEFORM);">Waveform

Effect: <select id="effect">
		<option>Delay </option>
		<option>Reverb </option>
		<option>Distortion </option>
		<option>Telephone </option>
		<option>Gain LFO </option>
		<option>Chorus </option>
		<option>Flange </option>
		<option>Ring mod </option>
		<option>Stereo Chorus </option>
		<option>Stereo Flange </option>
		<option>Pitch Shifter </option>
		<option>Mod Delay </option>
		<option>Ping-pong delay</option>
		<option>LFO Filter</option>
		<option>Envelope Follower (testing only)</option>
		<option>Autowah</option>
		<option>Noise Gate</option>
		<option>Wah Bass</option>
		<option>Distorted Wah Chorus</option>
		<option>Vibrato</option>
		<option>BitCrusher</option>
		<option>Apollo Quindar Tones</option>
</select>
  Effect Mix: <input type="range" min="0.0" max="1.0" step="0.01" value="1.0" style="height: 20px; width: 200px;"
onInput="crossfade( event.target.value );">
  Mono input: <input type="checkbox" checked onchange="toggleMono()">

A basic digital delay.

		Delay time: <input id="dtime" type="range" min="0.01" max="3" step="0.01" value="0.15" style="height: 20px; width: 200px" onInput="if (dtime) dtime.delayTime.value = event.target.value;">

		Regen: <input id="dregen" type="range" min="0.0" max="1.0" step="0.01" value="0.75" style="height: 20px; width: 200px;"
		onInput="if (dregen) dregen.gain.value = event.target.value;">

A convolution-based "hall" reverb, using a generated impulse file.

A waveshaper, used to do distortion.  Note this will become more high-quality in the future, as we improve the antialiasing in waveshapers.

		Drive: <input type="range" min="0.01" max="20" step="0.01" value="5" style="height: 20px; width: 200px;"
		onInput="if (waveshaper) waveshaper.setDrive(event.target.value);">

This effect pairs a low-pass and a high-pass filter to "telephonize" a sound - removing
		the high and low frequencies.

This effect chops up the sound by using a low-frequency oscillator (LFO) to control the
		gain.

		LFO type:
		<select id="lfotype" onchange="if (lfotype) lfotype.type = parseInt(event.target.value);">
			<option selected="selected" value="0">SIN</option>
			<option value="1">SQUARE</option>
			<option value="2">SAWTOOTH</option>
			<option value="3">TRIANGLE</option>
		</select>

		LFO speed: <input id="lfo" type="range" min="0.25" max="20" step="0.25" value="3" style="height: 20px; width: 200px;" onInput="if (lfo) lfo.frequency.value = event.target.value;">

		LFO depth: <input id="lfodepth" type="range" min="0.0" max="1.0" step="0.1" value="1.0" style="height: 20px; width: 200px;" onInput="if (lfodepth) lfodepth.gain.value = event.target.value;">

A basic (monophonic) chorus effect.

		Chorus speed: <input id="cspeed" type="range" min="0.5" max="15" step="0.25" value="3.5" style="height: 20px; width: 200px;" onInput="if (cspeed) cspeed.frequency.value = event.target.value;">

		Chorus delay: <input id="cdelay" type="range" min="0.005" max="0.055" step="0.005" value="0.03" style="height: 20px; width: 200px;" onInput="if (cdelay) cdelay.delayTime.value = event.target.value;">

		Chorus depth: <input id="cdepth" type="range" min="0.0005" max="0.004" step="0.0005" value="0.002" style="height: 20px; width: 200px;" onInput="if (cdepth) cdepth.gain.value = event.target.value;">

A basic (monophonic) flanging effect.

		Flanger speed: <input id="flspeed" type="range" min="0.05" max="5" step="0.05" value="0.25" style="height: 20px; width: 200px;" onInput="if (flspeed) flspeed.frequency.value = event.target.value;">

		Flanger delay: <input id="fldelay" type="range" min="0.001" max="0.02" step="0.001" value="0.005" style="height: 20px; width: 200px;" onInput="if (fldelay) fldelay.delayTime.value = event.target.value;">

		Flanger depth: <input id="fldepth" type="range" min="0.0005" max="0.005" step="0.00025" value="0.002" style="height: 20px; width: 200px;" onInput="if (fldepth) fldepth.gain.value = event.target.value;">

		Flanger feedback: <input id="flfb" type="range" min="0" max="1" step="0.01" value="0.5" style="height: 20px; width: 200px;" onInput="if (flfb) flfb.gain.value = event.target.value;">

A ring modulator.

		Ringmod freq: <input id="rmfreq" type="range" min="9" max="13" step="0.01" value="11" style="height: 20px; width: 200px;" onInput="if (rmod) rmod.frequency.value = Math.pow(2, event.target.value);">

A stereo chorus effect.

		Chorus speed: <input id="scspeed" type="range" min="0.5" max="15" step="0.25" value="3.5" style="height: 20px; width: 200px;" onInput="if (scspeed) scspeed.frequency.value = event.target.value;">

		Chorus delay: <input id="scdelay" type="range" min="0.005" max="0.055" step="0.005" value="0.03" style="height: 20px; width: 200px;" onInput="if (scldelay) scldelay.delayTime.value = event.target.value;if (scrdelay) scrdelay.delayTime.value = event.target.value;">

		Chorus depth: <input id="scdepth" type="range" min="0.0005" max="0.004" step="0.0005" value="0.002" style="height: 20px; width: 200px;" onInput="if (scldepth) scldepth.gain.value = event.target.value; if (scrdepth) scrdepth.gain.value = -1.0 * event.target.value;">

A stereo flanging effect.

		Flanger speed: <input id="sflspeed" type="range" min="0.05" max="2" step="0.05" value="0.15" style="height: 20px; width: 200px;" onInput="if (sflspeed) sflspeed.frequency.value = event.target.value;">

		Flanger delay: <input id="sfldelay" type="range" min="0.001" max="0.02" step="0.001" value="0.003" style="height: 20px; width: 200px;" onInput="if (sflldelay) sflldelay.delayTime.value = event.target.value; if (sflrdelay) sflrdelay.delayTime.value = event.target.value;">

		Flanger depth: <input id="sfldepth" type="range" min="0.0005" max="0.02" step="0.00025" value="0.005" style="height: 20px; width: 200px;" onInput="if (sflldepth) sflldepth.gain.value = event.target.value; if (sflrdepth) sflrdepth.gain.value = -1.0 * event.target.value;">

		Flanger feedback: <input id="sflfb" type="range" min="0" max="1" step="0.01" value="0.9" style="height: 20px; width: 200px;" onInput="if (sfllfb) sfllfb.gain.value = event.target.value; if (sflrfb) sflrfb.gain.value = event.target.value;">

A pitch-shifting effect, using sample-accurate delay ramping.  Defaults to one octave down.

		Pitch-shift: <input id="octpitch" type="range" min="-1" max="1" step="0.05" value="-1" style="height: 20px; width: 200px;" onInput="if (effect.setPitchOffset) effect.setPitchOffset(event.target.value);">

A delay with a basic chorus effect.

		Delay time: <input id="mdtime" type="range" min="0.01" max="3" step="0.01" value="0.15" style="height: 20px; width: 200px" onInput="if (mdtime) mdtime.delayTime.value = event.target.value;">

		Regen: <input id="mdfeedback" type="range" min="0.0" max="1.0" step="0.01" value="0.5" style="height: 20px; width: 200px;"
		onInput="if (mdfeedback) mdfeedback.gain.value = event.target.value;">

		Chorus speed: <input id="mdspeed" type="range" min="0.5" max="15" step="0.25" value="3.5" style="height: 20px; width: 200px;" onInput="if (mdspeed) mdspeed.frequency.value = event.target.value;">

		Chorus delay: <input id="mddelay" type="range" min="0.005" max="0.055" step="0.005" value="0.03" style="height: 20px; width: 200px;" onInput="if (mddelay) mddelay.delayTime.value = event.target.value;">

		Chorus depth: <input id="mddepth" type="range" min="0.0005" max="0.004" step="0.0005" value="0.002" style="height: 20px; width: 200px;" onInput="if (mddepth) mddepth.gain.value = event.target.value;">

A ping-pong delay - bounces stereo channels.  Most noticeable with mono signal.

An LFO-controlled low-pass filter.

		LFO type:
		<select id="lplfotype" onchange="if (lplfo) lplfo.type = parseInt(event.target.value);">
			<option selected="selected" value="0">SIN</option>
			<option value="1">SQUARE</option>
			<option value="2">SAWTOOTH</option>
			<option value="3">TRIANGLE</option>
		</select>

		LFO speed: <input id="lplfo" type="range" min="0.25" max="20" step="0.25" value="3" style="height: 20px; width: 200px;" onInput="if (lplfo) lplfo.frequency.value = event.target.value;">

		LFO depth: <input id="lplfodepth" type="range" min="0.0" max="1.0" step="0.1" value="1.0" style="height: 20px; width: 200px;" onInput="if (lplfodepth) lplfodepth.gain.value = 2500 * event.target.value;">
		Filter Q: <input id="lplfoq" type="range" min="0.0" max="20.0" step="0.5" value="3.0" style="height: 20px; width: 200px;" onInput="if (lplfofilter) lplfofilter.Q.value = event.target.value;">

An envelope follower.  Just for testing.

An autowah effect.

		Envelope follower filter frequency: <input id="awEF" type="range" min="0.25" max="20" step="0.25" value="10" style="height: 20px; width: 200px;" onInput="if (awFollower) awFollower.frequency.value = event.target.value;">

		Filter depth (log): <input id="lfo" type="range" min="0" max="4" step="0.1" value="3.5" style="height: 20px; width: 200px;" onInput="if (awDepth) awDepth.gain.value = Math.pow(2,10+parseFloat(event.target.value));">

		Filter Q: <input id="awQ" type="range" min="0.0" max="20.0" step="0.1" value="5.0" style="height: 20px; width: 200px;" onInput="if (awFilter) awFilter.Q.value = event.target.value;">

A cheaply-implemented noise gate.  Due to how it's implemented, it WILL have chattering problems.

		Envelope follower filter frequency: <input id="ngEF" type="range" min="0.25" max="20" step="0.25" value="10" style="height: 20px; width: 200px;" onInput="if (ngFollower) ngFollower.frequency.value = event.target.value;">

		Floor: <input id="ngFloor" type="range" min="0.0" max="0.1" step="0.001" value="0.01" style="height: 20px; width: 200px;" onInput="if (ngGate)    ngGate.curve = generateNoiseFloorCurve(event.target.value);">

Octave-down + wah + ping-pong.

Wah + distortion + stereo chorus.

Vibrato.

		Vibrato speed: <input id="vspeed" type="range" min="0.5" max="15" step="0.25" value="3.5" style="height: 20px; width: 200px;" onInput="if (cspeed) cspeed.frequency.value = event.target.value;">

		Vibrato delay: <input id="vdelay" type="range" min="0.005" max="0.055" step="0.005" value="0.03" style="height: 20px; width: 200px;" onInput="if (cdelay) cdelay.delayTime.value = event.target.value;">

		Vibrato depth: <input id="vdepth" type="range" min="0.0005" max="0.004" step="0.0005" value="0.002" style="height: 20px; width: 200px;" onInput="if (cdepth) cdepth.gain.value = event.target.value;">

Bitcrusher effect.

		Bit depth: <input id="bitdepth" type="range" min="1" max="16" step="0.25" value="8" style="height: 20px; width: 200px;" onInput="btcrBits = parseInt(event.target.value);">

		Frequency stepping: <input id="btcrFreq" type="range" min="0" max="1" step="0.01" value="1" style="height: 20px; width: 200px;" onInput="btcrNormFreq = parseFloat(event.target.value);">

Apollo Quindar tone effect.

		Noise floor: <input id="apolloFloor" type="range" min="0.0" max="0.2" step="0.001" value="0.01" style="height: 20px; width: 200px;" onInput="if (apolloGate)    apolloGate.curve = generateNoiseFloorCurve(event.target.value);">


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Gibraltar.Data;
using Gibraltar.Data.Internal;
using Gibraltar.Monitor;
using Loupe.Extensibility.Data;

namespace Gibraltar.Server.Client
{
    /// <summary>
    /// A web channel request to upload a session file or full session stream
    /// </summary>
    internal class SessionUploadRequest : WebChannelRequestBase, IDisposable
    {

        private const string SessionTempFolder = "Session_Upload";

        private const int SinglePassCutoffBytes = 3000000; //about 3MB.
        private const int DefaultSegmentSizeBytes = 1000000; //about 1MB.

        private bool m_Initialized;
        private bool m_PerformCleanup;
        private int m_BytesWritten;
        private string m_TempSessionProgressFileNamePath; //the transfer tracking file.
        private Stream m_SessionFileStream; //the actual file stream to be transfered.
        private string m_SessionFileHash;

        private InterprocessLock m_SessionTransportLock;
        private bool m_DeleteTemporaryFilesOnDispose;

        /// <summary>
        /// Create a new session upload request.
        /// </summary>
        /// <param name="clientId"></param>
        /// <param name="repository"></param>
        /// <param name="sessionId"></param>
        /// <param name="fileId"></param>
        /// <param name="purgeSessionOnSuccess">Indicates if the session should be purged from the repository once it has been sent successfully.</param>
        public SessionUploadRequest(Guid clientId, LocalRepository repository, Guid sessionId, Guid? fileId, bool purgeSessionOnSuccess)
            :base(true, false)
        {
            ClientId = clientId;
            Repository = repository;
            SessionId = sessionId;
            FileId = fileId;
            PurgeSessionOnSuccess = purgeSessionOnSuccess;
            m_Initialized = false;
        }

        /// <summary>
        /// Initialize the upload request and underlying session data for transport.
        /// </summary>
        /// <returns>True if the session has been initialized and this is the only upload request trying to process this data.</returns>
        /// <remarks>If the session isn't already being transported to this endpoint then a lock will be set for transport.
        /// This request must be disposed to ensure this lock is released in a timely manner.</remarks>
        public bool PrepareSession()
        {
            Initialize();

            return (m_SessionTransportLock != null);
        }

        /// <summary>
        /// The repository the session upload request is coming from
        /// </summary>
        public LocalRepository Repository { get; private set; }

        /// <summary>
        /// The unique id to use for the client sending the session
        /// </summary>
        public Guid ClientId { get; private set; }

        /// <summary>
        /// The unique id of the session being sent.
        /// </summary>
        public Guid SessionId { get; private set; }

        /// <summary>
        /// Optional.  The unique id of the file within the session being sent.
        /// </summary>
        public Guid? FileId { get; set; }

        /// <summary>
        /// Indicates if the session should be purged from the repository once it has been sent successfully.
        /// </summary>
        public bool PurgeSessionOnSuccess { get; private set; }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        /// <filterpriority>2</filterpriority>
        public void Dispose()
        {
            Dispose(true);

            GC.SuppressFinalize(this);
        }

        #region Protected Properties and Methods

        /// <summary>
        /// Dispose managed resources
        /// </summary>
        /// <param name="releaseManaged"></param>
        protected virtual void Dispose(bool releaseManaged)
        {
            if (releaseManaged)
            {
                //we have to get rid of the lock if we have it.
                m_SessionTransportLock.SafeDispose();
                m_SessionTransportLock = null;

                m_SessionFileStream.SafeDispose();
                m_SessionFileStream = null;

                //and flush any temporary files we have if they aren't in a persistent repository.
                if (m_DeleteTemporaryFilesOnDispose)
                {
                    SafeDeleteTemporaryData();
                }
            }
        }

        private void PerformCleanup(IWebChannelConnection connection)
        {
            try
            {
                //we're going to upload zero bytes as a delete to the right URL.
                connection.UploadData(GenerateResourceUri(), HttpMethod.Delete, BinaryContentType, new byte[] { });
            }
            catch (Exception ex)
            {
                GC.KeepAlive(ex);
#if DEBUG
                    Log.RecordException(0, ex, null, RepositoryPublishClient.LogCategory, true);
#endif
            }
        }

        /// <summary>
        /// Implemented by inheritors to perform the request on the provided web client.
        /// </summary>
        /// <param name="connection"></param>
        protected override async Task OnProcessRequest(IWebChannelConnection connection)
        {
            if (m_Initialized == false)
            {
                Initialize();
            }

            if (m_SessionTransportLock == null)
            {
                throw new InvalidOperationException("The session is currently being transported by another process.");
            }

            //if we might have left a file fragment on the server we need to send a delete call to remove any partial file
            if (m_PerformCleanup)
            {
                m_PerformCleanup = false; //even if we fail, don't try again.
                PerformCleanup(connection);
            }

            var resourceUri = GenerateResourceUri();
            var additionalHeaders = new List<NameValuePair<string>>();
            if (string.IsNullOrEmpty(m_SessionFileHash) == false)
            {
                additionalHeaders.Add(new NameValuePair<string>(HubConnection.SHA1HashHeader, m_SessionFileHash));
            }

            //if it's SMALL we just put the whole thing up as a single action.
            if (m_SessionFileStream.Length < SinglePassCutoffBytes)
            {
                var sessionData = new byte[m_SessionFileStream.Length ];
                await m_SessionFileStream.ReadAsync(sessionData, 0, sessionData.Length).ConfigureAwait(false);
                await connection.UploadData(resourceUri, HttpMethod.Put, BinaryContentType, sessionData, additionalHeaders).ConfigureAwait(false);
            }
            else
            {
                //we need to do a segmented post operation.  Note that we may be restarting a request after an error, so don't reset
                //our bytes written.
                m_SessionFileStream.Position = m_BytesWritten;
                var restartCount = 0;
                var sessionData = new byte[DefaultSegmentSizeBytes];
                while (m_BytesWritten < m_SessionFileStream.Length)
                {
                    //Read the next segment which is either our segment size or the last fragment of the file, exactly sized.
                    if ((m_SessionFileStream.Length - m_SessionFileStream.Position) < sessionData.Length)
                    {
                        //we're at the last block - resize our buffer down.
                        sessionData = new byte[(m_SessionFileStream.Length - m_SessionFileStream.Position)];
                    }

                    await m_SessionFileStream.ReadAsync(sessionData, 0, sessionData.Length).ConfigureAwait(false);

                    var isComplete = (m_SessionFileStream.Position == m_SessionFileStream.Length);
                    var requestUrl =
                        $"{resourceUri}?Start={m_BytesWritten}&Complete={isComplete}&FileSize={m_SessionFileStream.Length}";

                    try
                    {
                        await connection.UploadData(requestUrl, HttpMethod.Post, BinaryContentType, sessionData, additionalHeaders).ConfigureAwait(false);

                        //and now that we've written the bytes and not gotten an exception we can mark these bytes as done!
                        m_BytesWritten = (int)m_SessionFileStream.Position;
                        UpdateProgressTrackingFile();
                    }
                    catch (WebChannelBadRequestException ex)
                    {
                        if (!Log.SilentMode)
                            Log.Write(LogMessageSeverity.Error, LogWriteMode.Queued, ex, RepositoryPublishClient.LogCategory, "Server exchange error, we will assume client and server are out of sync.",
                                "The server returned a Bad Request Error (400) which generally means there is either a session-specific transfer problem that may be resolved by restarting the transfer from zero or an internal server problem.\r\nException: {0}", ex);

                        if (restartCount < 4)
                        {
                            //if we experience this type of Server-level transport error, assume there's some out of sync condition and start again.
                            restartCount++;
                            PerformCleanup(connection);
                            m_SessionFileStream.Position = 0;
                            m_BytesWritten = 0;
                            UpdateProgressTrackingFile();
                        }
                        else
                        {
                            //we didn't find a reason to restart the transfer, we need to let the exception fly.
                            throw;
                        }
                    }
                }
            }

            //and since we're now good & done...  clean up our temp stuff.
            SafeDeleteTemporaryData();

            //finally, if we are supposed to purge a session once we sent we need to give that a shot.
            if (PurgeSessionOnSuccess)
            {
                SafePurgeSession();
            }
        }

        #endregion

        #region Private Properties and Methods

        private int LoadProgressTrackingFile()
        {
            using (var sessionTrackingFileStream = new FileStream(m_TempSessionProgressFileNamePath, FileMode.Open, FileAccess.Read, FileShare.None))
            {
                using (var reader = new BinaryReader(sessionTrackingFileStream, Encoding.UTF8))
                {
                    return reader.ReadInt32();
                }
            }
        }

        private void UpdateProgressTrackingFile()
        {
            using (var sessionTrackingFileStream = new FileStream(m_TempSessionProgressFileNamePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
            {
                using (var writer = new BinaryWriter(sessionTrackingFileStream, Encoding.UTF8))
                {
                    writer.Write(m_BytesWritten);
                    writer.Flush();
                    sessionTrackingFileStream.SetLength(sessionTrackingFileStream.Position);
                }
            }
        }

        private void SafePurgeSession()
        {
            try
            {
                if (FileId.HasValue)
                    Repository.Remove(SessionId, FileId.Value); //this will just remove the one file, not the whole session.
                else
                    Repository.Remove(SessionId);
            }
            catch (Exception ex)
            {
                GC.KeepAlive(ex);

#if DEBUG
                Log.RecordException(0, ex, null, RepositoryPublishClient.LogCategory, true);
#endif
            }
        }

        /// <summary>
        /// Removes all of the temporary data used to transfer the session without allowing exceptions to propagate on failure.
        /// </summary>
        private void SafeDeleteTemporaryData()
        {
            SafeDeleteFile(m_TempSessionProgressFileNamePath);
            m_DeleteTemporaryFilesOnDispose = false; //because we already did.
        }

        private static void SafeDeleteFile(string fileNamePath)
        {
            if (string.IsNullOrEmpty(fileNamePath))
                return;

            try
            {
                File.Delete(fileNamePath);
            }
            catch (Exception ex)
            {
                GC.KeepAlive(ex);

#if DEBUG
                Log.RecordException(0, ex, null, RepositoryPublishClient.LogCategory, true);
#endif
            }
        }

        private string GenerateResourceUri()
        {
            return FileId.HasValue ? $"/Hub/Hosts/{ClientId}/Sessions/{SessionId}/Files/{FileId}.zip"
                : $"/Hub/Hosts/{ClientId}/Sessions/{SessionId}/session.glf";
        }

        /// <summary>
        /// The temporary path to put all of the transfer information for this session.
        /// </summary>
        /// <returns></returns>
        private string GenerateTemporarySessionPath()
        {
            //find the right temporary directory for us...
            //if this is a real repository, we'll use a persistent path.
            //otherwise we'll use something truly temporary and have to clean up after ourselves.
            string tempDirectory;
            if (Repository != null)
            {
                tempDirectory = Path.Combine(Repository.TempPath, SessionTempFolder);
            }
            else
            {
                tempDirectory = FileSystemTools.GetTempFileName();
                File.Delete(tempDirectory); //we just want it as a directory, not a file.
                m_DeleteTemporaryFilesOnDispose = true;
            }

            //make damn sure it exists.
            Directory.CreateDirectory(tempDirectory);

            return tempDirectory;
        }

        /// <summary>
        /// The file name (without extension) for this session
        /// </summary>
        /// <returns></returns>
        private string GenerateTemporarySessionFileName()
        {
            //the path needs to be generated reliably, but uniquely.
            return FileId.HasValue ? $"{SessionId}_{ClientId}_{FileId}" : $"{SessionId}_{ClientId}";
        }

        /// <summary>
        /// The full file name and path (without extension) for the transfer information for this session
        /// </summary>
        /// <returns></returns>
        internal string GenerateTemporarySessionFileNamePath()
        {
            return Path.Combine(GenerateTemporarySessionPath(), GenerateTemporarySessionFileName() + ".txt");
        }

        private void Initialize()
        {
            if (m_Initialized)
                return;

            //we need to grab a lock on this session to prevent it from being transported to the same endpoint at the same time.
            var sessionWorkingFileNamePath = GenerateTemporarySessionFileNamePath();

            //we aren't going to do Using - we keep the lock!
            if (m_SessionTransportLock == null) //if we are retrying to initialize after a failure we may already have it.
            {
                m_SessionTransportLock = InterprocessLockManager.Lock(this, GenerateTemporarySessionPath(), GenerateTemporarySessionFileName(), 0, true);
            }

            //we aren't waiting to see if we can get the lock - if anyone else has it they must be transferring the session.
            if (m_SessionTransportLock != null)
            {
                //grab a lock on the actual data file - if it's not there, no point in continuing.
                m_SessionFileStream = Repository.LoadSessionFileStream(SessionId, FileId.Value);

                //calculate our SHA1 Hash...
                try
                {
                    using (var csp = SHA1.Create())
                    {
                        m_SessionFileHash = BitConverter.ToString(csp.ComputeHash(m_SessionFileStream));
                    }

                    //now back up the stream to the beginning so we can send the actual data.
                    m_SessionFileStream.Position = 0;
                }
                catch (Exception ex)
                {
                    if (!Log.SilentMode)
                        Log.Write(LogMessageSeverity.Error, LogWriteMode.Queued, ex, RepositoryPublishClient.LogCategory, "Unable to calculate hash for session file due to " + ex.GetType() + " exception.", "The upload will proceed but without the hash to check the accuracy of the upload.\r\nException: {0}\r\n{1}\r\n", ex.GetType(), ex.Message);
                }

                //Lets figure out if we're restarting a previous send or starting a new one.
                m_TempSessionProgressFileNamePath = sessionWorkingFileNamePath;

                m_BytesWritten = 0;
                if (File.Exists(m_TempSessionProgressFileNamePath))
                {
                    //load up the existing transfer state.
                    try
                    {
                        m_BytesWritten = LoadProgressTrackingFile();
                    }
                    catch
                    {
                        //oh well, assume no progress.
                        m_PerformCleanup = true;

                        SafeDeleteFile(m_TempSessionProgressFileNamePath);
                    }
                }
                else
                {
                    //make sure we didn't get started, but not finish, writing our temp file.
                    SafeDeleteFile(m_TempSessionProgressFileNamePath);
                }

                m_Initialized = true;
            }
        }

        #endregion
    }
}


text:
//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// constraints_tests_util.h
//
// Identification: tests/catalog/constraints_tests_util.h
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#pragma once

#include <vector>
#include <memory>

#include "backend/common/types.h"

namespace peloton {

//===--------------------------------------------------------------------===//
// Utils
//===--------------------------------------------------------------------===//

class VarlenPool;

namespace catalog {
class Column;
class Manager;
}

namespace concurrency {
class Transaction;
}

namespace executor {
class AbstractExecutor;
class LogicalTile;
}

namespace storage {
class Backend;
class TileGroup;
class DataTable;
class Tuple;
}

namespace planner {
class ProjectInfo;
}

#define TESTS_TUPLES_PER_TILEGROUP 5
#define DEFAULT_TILEGROUP_COUNT 3

namespace test {

class ConstraintsTestsUtil {
 public:
  /** @brief Creates a basic table with allocated but not populated tuples */
  static storage::DataTable *CreateTable(
      int tuples_per_tilegroup_count = TESTS_TUPLES_PER_TILEGROUP,
      bool indexes = true);

  /** @brief Insert a tupl with 4 columns' value specified */
  static bool ExecuteInsert(concurrency::Transaction *transaction,
                            storage::DataTable *table, const Value &col1,
                            const Value &col2, const Value &col3,
                            const Value &col4);

  /** @brief Creates a basic table with allocated and populated tuples */
  static storage::DataTable *CreateAndPopulateTable();

  static void PopulateTable(concurrency::Transaction *transaction,
                            storage::DataTable *table, int num_rows);

  static catalog::Column GetColumnInfo(int index);

  /**
   * @brief Returns the value populated at the specified field.
   * @param tuple_id Row of the specified field.
   * @param column_id Column of the specified field.
   *
   * This method defines the values that are populated by PopulateTiles().
   *
   * @return Populated value.
   */
  inline static int PopulatedValue(const oid_t tuple_id,
                                   const oid_t column_id) {
    return 10 * tuple_id + column_id;
  }
};

}  // namespace test
}  // namespace peloton


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package shopcar.pojo;

import java.io.Serializable;
import java.util.Objects;
import javax.persistence.Entity;

/**
 *
 * @author Mandy Grimm
 */
@Entity
public class Carro extends VeiculoPassageiro implements Serializable
{
    private static final Long serialVersionUID = 1L;
}


text:
import * as ts from 'typescript';

import {absoluteFrom, getFileSystem, relativeFrom} from '../../../src/ngtsc/file_system';
import {runInEachFileSystem} from '../../../src/ngtsc/file_system/testing';
import {loadTestFiles} from '../../../test/helpers';
import {createDependencyInfo} from '../../src/dependencies/dependency_host';
import {DtsDependencyHost} from '../../src/dependencies/dts_dependency_host';

runInEachFileSystem(() => {

  describe('DtsDependencyHost', () => {
    let _: typeof absoluteFrom;
    let host: DtsDependencyHost;
    beforeEach(() => {
      _ = absoluteFrom;
      setupMockFileSystem();
      const fs = getFileSystem();
      host = new DtsDependencyHost(fs);
    });

    describe('collectDependencies()', () => {
      it('should not generate a TS AST if the source does not contain any imports or re-exports',
         () => {
           spyOn(ts, 'createSourceFile');
           host.collectDependencies(
               _('/no/imports/or/re-exports/index.d.ts'), createDependencyInfo());
           expect(ts.createSourceFile).not.toHaveBeenCalled();
         });

      it('should resolve all the external imports of the source file', () => {
        const {dependencies, missing, deepImports} = createDependencyInfo();
        host.collectDependencies(
            _('/external/imports/index.d.ts'), {dependencies, missing, deepImports});
        expect(dependencies.size).toBe(2);
        expect(missing.size).toBe(0);
        expect(deepImports.size).toBe(0);
        expect(dependencies.has(_('/node_modules/lib-1'))).toBe(true);
        expect(dependencies.has(_('/node_modules/lib-1/sub-1'))).toBe(true);
      });

      it('should resolve all the external re-exports of the source file', () => {
        const {dependencies, missing, deepImports} = createDependencyInfo();
        host.collectDependencies(
            _('/external/re-exports/index.d.ts'), {dependencies, missing, deepImports});
        expect(dependencies.size).toBe(2);
        expect(missing.size).toBe(0);
        expect(deepImports.size).toBe(0);
        expect(dependencies.has(_('/node_modules/lib-1'))).toBe(true);
        expect(dependencies.has(_('/node_modules/lib-1/sub-1'))).toBe(true);
      });

      it('should capture missing external imports', () => {
        const {dependencies, missing, deepImports} = createDependencyInfo();
        host.collectDependencies(
            _('/external/imports-missing/index.d.ts'), {dependencies, missing, deepImports});

        expect(dependencies.size).toBe(1);
        expect(dependencies.has(_('/node_modules/lib-1'))).toBe(true);
        expect(missing.size).toBe(1);
        expect(missing.has(relativeFrom('missing'))).toBe(true);
        expect(deepImports.size).toBe(0);
      });

      it('should not register deep imports as missing', () => {
        // This scenario verifies the behavior of the dependency analysis when an external import
        // is found that does not map to an entry-point but still exists on disk, i.e. a deep
        // import. Such deep imports are captured for diagnostics purposes.
        // Note that in the DTS version, the deep import may not map to a .d.ts file, but instead
        // a .js file. This test exercises this particular scenario.
        const {dependencies, missing, deepImports} = createDependencyInfo();
        host.collectDependencies(
            _('/external/deep-import/index.d.ts'), {dependencies, missing, deepImports});

        expect(dependencies.size).toBe(0);
        expect(missing.size).toBe(0);
        expect(deepImports.size).toBe(1);
        expect(deepImports.has(_('/node_modules/lib-1/deep/import'))).toBe(true);
      });

      it('should not register deep imports as missing, if available in `@types/...`', () => {
        // This scenario verifies the behavior of the dependency analysis when an external import
        // is found that does not map to an entry-point but still exists in an `@types/...` package,
        // i.e. a type-only deep import. Such deep imports are captured for diagnostics purposes.
        const {dependencies, missing, deepImports} = createDependencyInfo();
        host.collectDependencies(
            _('/external/deep-import-2/index.d.ts'), {dependencies, missing, deepImports});

        expect(dependencies.size).toBe(0);
        expect(missing.size).toBe(0);
        expect(deepImports.size).toBe(1);
        expect(deepImports.has(_('/node_modules/@types/type-only/deep/import'))).toBe(true);
      });

      it('should recurse into internal dependencies', () => {
        const {dependencies, missing, deepImports} = createDependencyInfo();
        host.collectDependencies(
            _('/internal/outer/index.d.ts'), {dependencies, missing, deepImports});

        expect(dependencies.size).toBe(1);
        expect(dependencies.has(_('/node_modules/lib-1/sub-1'))).toBe(true);
        expect(missing.size).toBe(0);
        expect(deepImports.size).toBe(0);
      });

      it('should handle circular internal dependencies', () => {
        const {dependencies, missing, deepImports} = createDependencyInfo();
        host.collectDependencies(
            _('/internal/circular-a/index.d.ts'), {dependencies, missing, deepImports});
        expect(dependencies.size).toBe(2);
        expect(dependencies.has(_('/node_modules/lib-1'))).toBe(true);
        expect(dependencies.has(_('/node_modules/lib-1/sub-1'))).toBe(true);
        expect(missing.size).toBe(0);
        expect(deepImports.size).toBe(0);
      });

      it('should support `paths` alias mappings when resolving modules', () => {
        const fs = getFileSystem();
        host = new DtsDependencyHost(fs, {
          baseUrl: '/dist',
          paths: {
            '@app/*': ['*'],
            '@lib/*/test': ['lib/*/test'],
          }
        });
        const {dependencies, missing, deepImports} = createDependencyInfo();
        host.collectDependencies(_('/path-alias/index.d.ts'), {dependencies, missing, deepImports});
        expect(dependencies.size).toBe(4);
        expect(dependencies.has(_('/dist/components'))).toBe(true);
        expect(dependencies.has(_('/dist/shared'))).toBe(true);
        expect(dependencies.has(_('/dist/lib/shared/test'))).toBe(true);
        expect(dependencies.has(_('/node_modules/lib-1'))).toBe(true);
        expect(missing.size).toBe(0);
        expect(deepImports.size).toBe(0);
      });

      it('should handle entry-point paths with no extension', () => {
        const {dependencies, missing, deepImports} = createDependencyInfo();
        host.collectDependencies(
            _('/external/imports/index'), {dependencies, missing, deepImports});
        expect(dependencies.size).toBe(2);
        expect(missing.size).toBe(0);
        expect(deepImports.size).toBe(0);
        expect(dependencies.has(_('/node_modules/lib-1'))).toBe(true);
        expect(dependencies.has(_('/node_modules/lib-1/sub-1'))).toBe(true);
      });
    });

    function setupMockFileSystem(): void {
      loadTestFiles([
        {
          name: _('/no/imports/or/re-exports/index.d.ts'),
          contents: '// some text but no import-like statements'
        },
        {name: _('/no/imports/or/re-exports/package.json'), contents: '{"esm2015": "./index.js"}'},
        {name: _('/no/imports/or/re-exports/index.metadata.json'), contents: 'MOCK METADATA'},
        {
          name: _('/external/imports/index.d.ts'),
          contents: `import {X} from 'lib-1';\nimport {Y} from 'lib-1/sub-1';`
        },
        {name: _('/external/imports/package.json'), contents: '{"esm2015": "./index.js"}'},
        {name: _('/external/imports/index.metadata.json'), contents: 'MOCK METADATA'},
        {
          name: _('/external/re-exports/index.d.ts'),
          contents: `export {X} from 'lib-1';\nexport {Y} from 'lib-1/sub-1';`
        },
        {name: _('/external/re-exports/package.json'), contents: '{"esm2015": "./index.js"}'},
        {name: _('/external/re-exports/index.metadata.json'), contents: 'MOCK METADATA'},
        {
          name: _('/external/imports-missing/index.d.ts'),
          contents: `import {X} from 'lib-1';\nimport {Y} from 'missing';`
        },
        {name: _('/external/imports-missing/package.json'), contents: '{"esm2015": "./index.js"}'},
        {name: _('/external/imports-missing/index.metadata.json'), contents: 'MOCK METADATA'},
        {
          name: _('/external/deep-import/index.d.ts'),
          contents: `import {Y} from 'lib-1/deep/import';`
        },
        {name: _('/external/deep-import/package.json'), contents: '{"esm2015": "./index.js"}'},
        {name: _('/external/deep-import/index.metadata.json'), contents: 'MOCK METADATA'},
        {
          name: _('/external/deep-import-2/index.d.ts'),
          contents: `import {Y} from 'type-only/deep/import';`
        },
        {
          name: _('/node_modules/@types/type-only/deep/import/index.d.ts'),
          contents: `export declare class Y {}`
        },
        {name: _('/internal/outer/index.d.ts'), contents: `import {X} from '../inner';`},
        {name: _('/internal/outer/package.json'), contents: '{"esm2015": "./index.js"}'},
        {name: _('/internal/outer/index.metadata.json'), contents: 'MOCK METADATA'},
        {
          name: _('/internal/inner/index.d.ts'),
          contents: `import {Y} from 'lib-1/sub-1'; export declare class X {}`
        },
        {
          name: _('/internal/circular-a/index.d.ts'),
          contents:
              `import {B} from '../circular-b'; import {X} from '../circular-b'; export {Y} from 'lib-1/sub-1';`
        },
        {
          name: _('/internal/circular-b/index.d.ts'),
          contents:
              `import {A} from '../circular-a'; import {Y} from '../circular-a'; export {X} from 'lib-1';`
        },
        {name: _('/internal/circular-a/package.json'), contents: '{"esm2015": "./index.js"}'},
        {name: _('/internal/circular-a/index.metadata.json'), contents: 'MOCK METADATA'},
        {
          name: _('/path-alias/index.d.ts'),
          contents:
              `import {TestHelper} from '@app/components';\nimport {Service} from '@app/shared';\nimport {TestHelper} from '@lib/shared/test';\nimport {X} from 'lib-1';`
        },
        {name: _('/path-alias/package.json'), contents: '{"esm2015": "./index.js"}'},
        {name: _('/path-alias/index.metadata.json'), contents: 'MOCK METADATA'},
        {name: _('/node_modules/lib-1/index.d.ts'), contents: 'export declare class X {}'},
        {name: _('/node_modules/lib-1/package.json'), contents: '{"esm2015": "./index.js"}'},
        {name: _('/node_modules/lib-1/index.metadata.json'), contents: 'MOCK METADATA'},
        {
          name: _('/node_modules/lib-1/deep/import/index.js'),
          contents: 'export class DeepImport {}'
        },
        {name: _('/node_modules/lib-1/sub-1/index.d.ts'), contents: 'export declare class Y {}'},
        {name: _('/node_modules/lib-1/sub-1/package.json'), contents: '{"esm2015": "./index.js"}'},
        {name: _('/node_modules/lib-1/sub-1/index.metadata.json'), contents: 'MOCK METADATA'},
        {name: _('/node_modules/lib-1/sub-2.d.ts'), contents: `export * from './sub-2/sub-2';`},
        {name: _('/node_modules/lib-1/sub-2/sub-2.d.ts'), contents: `export declare class Z {}';`},
        {name: _('/node_modules/lib-1/sub-2/package.json'), contents: '{"esm2015": "./sub-2.js"}'},
        {name: _('/node_modules/lib-1/sub-2/sub-2.metadata.json'), contents: 'MOCK METADATA'},
        {name: _('/dist/components/index.d.ts'), contents: `class MyComponent {};`},
        {name: _('/dist/components/package.json'), contents: '{"esm2015": "./index.js"}'},
        {name: _('/dist/components/index.metadata.json'), contents: 'MOCK METADATA'},
        {
          name: _('/dist/shared/index.d.ts'),
          contents: `import {X} from 'lib-1';\nexport declare class Service {}`
        },
        {name: _('/dist/shared/package.json'), contents: '{"esm2015": "./index.js"}'},
        {name: _('/dist/shared/index.metadata.json'), contents: 'MOCK METADATA'},
        {
          name: _('/dist/lib/shared/test/index.d.ts'),
          contents: `export declare class TestHelper {}`
        },
        {name: _('/dist/lib/shared/test/package.json'), contents: '{"esm2015": "./index.js"}'},
        {name: _('/dist/lib/shared/test/index.metadata.json'), contents: 'MOCK METADATA'},
      ]);
    }
  });
});


text:
class ETC_Decoder
{
public:
	enum InputType
	{
		ETC_R_SIGNED,
		ETC_R_UNSIGNED,
		ETC_RG_SIGNED,
		ETC_RG_UNSIGNED,
		ETC_RGB,
		ETC_RGB_PUNCHTHROUGH_ALPHA,
		ETC_RGBA
	};

	/// ETC_Decoder::Decode - Decodes 1 to 4 channel images to 8 bit output
	/// @param src            Pointer to ETC2 encoded image
	/// @param dst            Pointer to BGRA, 8 bit output
	/// @param w              src image width
	/// @param h              src image height
	/// @param dstW           dst image width
	/// @param dstH           dst image height
	/// @param dstPitch       dst image pitch (bytes per row)
	/// @param dstBpp         dst image bytes per pixel
	/// @param inputType      src's format
	/// @return               true if the decoding was performed
	static bool Decode(const unsigned char* src, unsigned char *dst, int w, int h, int dstW, int dstH, int dstPitch, int dstBpp, InputType inputType);
};


text:
const ethSigUtil = require('eth-sig-util');
const Wallet = require('ethereumjs-wallet').default;
const { EIP712Domain } = require('../helpers/eip712');

const { expectEvent } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');

const ERC2771ContextMock = artifacts.require('ERC2771ContextMock');
const MinimalForwarder = artifacts.require('MinimalForwarder');
const ContextMockCaller = artifacts.require('ContextMockCaller');

const { shouldBehaveLikeRegularContext } = require('../utils/Context.behavior');

const name = 'MinimalForwarder';
const version = '0.0.1';

contract('ERC2771Context', function (accounts) {
  beforeEach(async function () {
    this.forwarder = await MinimalForwarder.new();
    this.recipient = await ERC2771ContextMock.new(this.forwarder.address);

    this.domain = {
      name,
      version,
      chainId: await web3.eth.getChainId(),
      verifyingContract: this.forwarder.address,
    };
    this.types = {
      EIP712Domain,
      ForwardRequest: [
        { name: 'from', type: 'address' },
        { name: 'to', type: 'address' },
        { name: 'value', type: 'uint256' },
        { name: 'gas', type: 'uint256' },
        { name: 'nonce', type: 'uint256' },
        { name: 'data', type: 'bytes' },
      ],
    };
  });

  it('recognize trusted forwarder', async function () {
    expect(await this.recipient.isTrustedForwarder(this.forwarder.address));
  });

  context('when called directly', function () {
    beforeEach(async function () {
      this.context = this.recipient; // The Context behavior expects the contract in this.context
      this.caller = await ContextMockCaller.new();
    });

    shouldBehaveLikeRegularContext(...accounts);
  });

  context('when receiving a relayed call', function () {
    beforeEach(async function () {
      this.wallet = Wallet.generate();
      this.sender = web3.utils.toChecksumAddress(this.wallet.getAddressString());
      this.data = {
        types: this.types,
        domain: this.domain,
        primaryType: 'ForwardRequest',
      };
    });

    describe('msgSender', function () {
      it('returns the relayed transaction original sender', async function () {
        const data = this.recipient.contract.methods.msgSender().encodeABI();

        const req = {
          from: this.sender,
          to: this.recipient.address,
          value: '0',
          gas: '100000',
          nonce: (await this.forwarder.getNonce(this.sender)).toString(),
          data,
        };

        const sign = ethSigUtil.signTypedMessage(this.wallet.getPrivateKey(), { data: { ...this.data, message: req } });
        expect(await this.forwarder.verify(req, sign)).to.equal(true);

        const { tx } = await this.forwarder.execute(req, sign);
        await expectEvent.inTransaction(tx, ERC2771ContextMock, 'Sender', { sender: this.sender });
      });
    });

    describe('msgData', function () {
      it('returns the relayed transaction original data', async function () {
        const integerValue = '42';
        const stringValue = 'OpenZeppelin';
        const data = this.recipient.contract.methods.msgData(integerValue, stringValue).encodeABI();

        const req = {
          from: this.sender,
          to: this.recipient.address,
          value: '0',
          gas: '100000',
          nonce: (await this.forwarder.getNonce(this.sender)).toString(),
          data,
        };

        const sign = ethSigUtil.signTypedMessage(this.wallet.getPrivateKey(), { data: { ...this.data, message: req } });
        expect(await this.forwarder.verify(req, sign)).to.equal(true);

        const { tx } = await this.forwarder.execute(req, sign);
        await expectEvent.inTransaction(tx, ERC2771ContextMock, 'Data', { data, integerValue, stringValue });
      });
    });
  });
});