text:
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.structuralsearch.plugin.ui;

import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
import com.intellij.codeInsight.template.TemplateBuilder;
import com.intellij.codeInsight.template.impl.TemplateEditorUtil;
import com.intellij.find.FindBundle;
import com.intellij.find.FindInProjectSettings;
import com.intellij.find.FindSettings;
import com.intellij.icons.AllIcons;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.lang.Language;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.SelectionModel;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.event.DocumentListener;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.ide.CopyPasteManager;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.project.*;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.util.DimensionService;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.GlobalSearchScopesCore;
import com.intellij.psi.search.SearchScope;
import com.intellij.structuralsearch.*;
import com.intellij.structuralsearch.impl.matcher.CompiledPattern;
import com.intellij.structuralsearch.impl.matcher.compiler.PatternCompiler;
import com.intellij.structuralsearch.plugin.StructuralSearchPlugin;
import com.intellij.structuralsearch.plugin.replace.ReplaceOptions;
import com.intellij.structuralsearch.plugin.replace.impl.Replacer;
import com.intellij.structuralsearch.plugin.replace.ui.ReplaceCommand;
import com.intellij.structuralsearch.plugin.replace.ui.ReplaceConfiguration;
import com.intellij.structuralsearch.plugin.ui.filters.FilterPanel;
import com.intellij.ui.ColoredListCellRenderer;
import com.intellij.ui.EditorTextField;
import com.intellij.ui.OnePixelSplitter;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.util.Alarm;
import com.intellij.util.textCompletion.TextCompletionUtil;
import com.intellij.util.ui.EdtInvocationManager;
import com.intellij.util.ui.TextTransferable;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

import static com.intellij.openapi.util.text.StringUtil.*;

/**
 * @author Bas Leijdekkers
 */
public class StructuralSearchDialog extends DialogWrapper {
  @NonNls private static final String SEARCH_DIMENSION_SERVICE_KEY = "#com.intellij.structuralsearch.plugin.ui.StructuralSearchDialog";
  @NonNls private static final String REPLACE_DIMENSION_SERVICE_KEY = "#com.intellij.structuralsearch.plugin.ui.StructuralReplaceDialog";

  @NonNls private static final String RECURSIVE_STATE = "structural.search.recursive";
  @NonNls private static final String MATCH_CASE_STATE = "structural.search.match.case";
  @NonNls private static final String SHORTEN_FQN_STATE = "structural.search.shorten.fqn";
  @NonNls private static final String REFORMAT_STATE = "structural.search.reformat";
  @NonNls private static final String USE_STATIC_IMPORT_STATE = "structural.search.use.static.import";

  public static final Key<StructuralSearchDialog> STRUCTURAL_SEARCH = Key.create("STRUCTURAL_SEARCH_AREA");
  public static final String USER_DEFINED = SSRBundle.message("new.template.defaultname");

  private final SearchContext mySearchContext;
  boolean myReplace;
  Configuration myConfiguration;
  @NonNls FileType myFileType = StructuralSearchUtil.getDefaultFileType();
  Language myDialect = null;
  String myContext = null;

  // ui management
  private final Alarm myAlarm;
  private boolean myUseLastConfiguration;
  private final boolean myEditConfigOnly;
  private boolean myDoingOkAction;
  boolean myFilterButtonEnabled = false;

  // components
  JCheckBox myRecursive;
  private JCheckBox myMatchCase;
  private JCheckBox myShortenFQN; // replace
  private JCheckBox myReformat; // replace
  private JCheckBox myUseStaticImport; // replace
  FileTypeSelector myFileTypesComboBox;
  ActionToolbarImpl myOptionsToolbar;
  EditorTextField mySearchCriteriaEdit;
  EditorTextField myReplaceCriteriaEdit;
  OnePixelSplitter mySearchEditorPanel;
  private OnePixelSplitter myReplaceEditorPanel;

  FilterPanel myFilterPanel;
  private LinkComboBox myTargetComboBox;
  private ScopePanel myScopePanel;
  private JCheckBox myOpenInNewTab;

  JComponent myReplacePanel;

  public StructuralSearchDialog(SearchContext searchContext, boolean replace) {
    this(searchContext, replace, false);
  }

  public StructuralSearchDialog(SearchContext searchContext, boolean replace, boolean editConfigOnly) {
    super(searchContext.getProject(), true);

    if (!editConfigOnly) {
      setModal(false);
      setOKButtonText(FindBundle.message("find.dialog.find.button"));
    }
    myReplace = replace;
    myEditConfigOnly = editConfigOnly;
    mySearchContext = searchContext;
    myConfiguration = createConfiguration(null);
    setTitle(getDefaultTitle());

    init();
    myAlarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, myDisposable);
    ProjectManager.getInstance().addProjectManagerListener(searchContext.getProject(), new ProjectManagerListener() {
      @Override
      public void projectClosing(@NotNull Project project) {
        close(CANCEL_EXIT_CODE);
      }
    });
  }

  public void setUseLastConfiguration(boolean useLastConfiguration) {
    myUseLastConfiguration = useLastConfiguration;
  }

  private EditorTextField createEditor(String text) {
    final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByFileType(myFileType);
    assert profile != null;
    final Document document = profile.createDocument(getProject(), myFileType, myDialect, text);

    final EditorTextField textField = new EditorTextField(document, getProject(), myFileType, false, false) {
      @Override
      protected EditorEx createEditor() {
        final EditorEx editor = super.createEditor();
        editor.setHorizontalScrollbarVisible(true);
        editor.setVerticalScrollbarVisible(true);
        final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByFileType(myFileType);
        assert profile != null;
        TemplateEditorUtil.setHighlighter(editor, profile.getTemplateContextType());
        SubstitutionShortInfoHandler.install(editor, variableName -> {
          myFilterPanel.initFilters(UIUtil.getOrAddVariableConstraint(variableName, myConfiguration));
          if (isFilterPanelEnabled()) {
            myConfiguration.setCurrentVariableName(variableName);
          }
        });
        editor.putUserData(SubstitutionShortInfoHandler.CURRENT_CONFIGURATION_KEY, myConfiguration);
        final Project project = getProject();
        final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(getDocument());
        if (file != null) {
          DaemonCodeAnalyzer.getInstance(project).setHighlightingEnabled(file, false);
        }
        TextCompletionUtil.installCompletionHint(editor);
        editor.putUserData(STRUCTURAL_SEARCH, StructuralSearchDialog.this);
        editor.setEmbeddedIntoDialogWrapper(true);
        return editor;
      }

      @Override
      protected void updateBorder(@NotNull EditorEx editor) {
        setupBorder(editor);
      }
    };
    textField.setPreferredSize(new Dimension(850, 150));
    textField.setMinimumSize(new Dimension(200, 50));
    textField.addDocumentListener(new DocumentListener() {
      @Override
      public void documentChanged(@NotNull final DocumentEvent event) {
        initiateValidation();
      }
    });
    return textField;
  }

  void initiateValidation() {
    if (myAlarm.isDisposed()) return;
    myAlarm.cancelAllRequests();
    myAlarm.addRequest(() -> {
      try {
        final boolean valid = isValid();
        final boolean compiled = isCompiled();
        ApplicationManager.getApplication().invokeLater(() -> {
          myFilterButtonEnabled = compiled;
          setSearchTargets(myConfiguration.getMatchOptions());
          getOKAction().setEnabled(valid);
        }, ModalityState.stateForComponent(getRootPane()));
      }
      catch (ProcessCanceledException e) {
        throw e;
      }
      catch (RuntimeException e) {
        Logger.getInstance(StructuralSearchDialog.class).error(e);
      }
    }, 250);
  }

  private boolean isCompiled() {
    try {
      final CompiledPattern compiledPattern = PatternCompiler.compilePattern(getProject(), myConfiguration.getMatchOptions(), false);
      if (compiledPattern != null) {
        myFilterPanel.setCompiledPattern(compiledPattern);
        if (!myFilterPanel.isInitialized()) {
          myFilterPanel.initFilters(UIUtil.getOrAddVariableConstraint(Configuration.CONTEXT_VAR_NAME, myConfiguration));
        }
      }
      return compiledPattern != null;
    } catch (MalformedPatternException e) {
      return false;
    }
  }

  private void detectFileType() {
    PsiElement context = mySearchContext.getFile();

    final Editor editor = mySearchContext.getEditor();
    if (editor != null && context != null) {
      context = context.findElementAt(editor.getCaretModel().getOffset());
      if (context != null) {
        context = context.getParent();
      }
    }
    if (context != null) {
      final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByPsiElement(context);
      if (profile != null) {
        final FileType fileType = profile.detectFileType(context);
        if (fileType != null) {
          myFileType = fileType;
          return;
        }
      }
    }

    myFileType = StructuralSearchUtil.getDefaultFileType();
  }

  private Configuration createConfiguration(Configuration template) {
    if (myReplace) {
      return (template == null) ? new ReplaceConfiguration(USER_DEFINED, USER_DEFINED) : new ReplaceConfiguration(template);
    }
    else {
      return (template == null) ? new SearchConfiguration(USER_DEFINED, USER_DEFINED) : new SearchConfiguration(template);
    }
  }

  private void setTextFromContext() {
    final Editor editor = mySearchContext.getEditor();
    if (editor != null) {
      final SelectionModel selectionModel = editor.getSelectionModel();
      final String selectedText = selectionModel.getSelectedText();
      if (selectedText != null) {
        if (loadConfiguration(selectedText)) {
          return;
        }
        final String text = selectedText.trim();
        setTextForEditor(text.trim(), mySearchCriteriaEdit);
        if (myReplace) {
          setTextForEditor(text, myReplaceCriteriaEdit);
        }
        myScopePanel.setScope(null);
        ApplicationManager.getApplication().invokeLater(() -> startTemplate());
        return;
      }
    }

    final Configuration configuration = ConfigurationManager.getInstance(getProject()).getMostRecentConfiguration();
    if (configuration != null) {
      loadConfiguration(configuration);
    }
  }

  private void setTextForEditor(String text, EditorTextField editor) {
    editor.setText(text);
    editor.selectAll();
    final Project project = getProject();
    final Document document = editor.getDocument();
    final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
    documentManager.commitDocument(document);
    final PsiFile file = documentManager.getPsiFile(document);
    if (file == null) return;

    WriteCommandAction.writeCommandAction(project, file).run(
      () -> CodeStyleManager.getInstance(project).adjustLineIndent(file, new TextRange(0, document.getTextLength())));
  }

  private void startSearching() {
    if (myReplace) {
      new ReplaceCommand(myConfiguration, mySearchContext).startSearching();
    }
    else {
      new SearchCommand(myConfiguration, mySearchContext).startSearching();
    }
  }

  @NotNull
  String getDefaultTitle() {
    return myReplace ? SSRBundle.message("structural.replace.title") : SSRBundle.message("structural.search.title");
  }

  @Override
  protected JComponent createCenterPanel() {
    mySearchEditorPanel = new OnePixelSplitter(false, 1.0f);
    myReplaceEditorPanel = new OnePixelSplitter(false, 1.0f);
    mySearchEditorPanel.setLackOfSpaceStrategy(Splitter.LackOfSpaceStrategy.HONOR_THE_SECOND_MIN_SIZE);
    mySearchEditorPanel.getDivider().setOpaque(false);
    mySearchCriteriaEdit = createEditor("");
    mySearchEditorPanel.setFirstComponent(mySearchCriteriaEdit);
    mySearchEditorPanel.add(BorderLayout.CENTER, mySearchCriteriaEdit);

    myReplacePanel = createReplacePanel();
    myReplacePanel.setVisible(myReplace);

    myScopePanel = new ScopePanel(getProject());
    if (!myEditConfigOnly) {
      myScopePanel.setRecentDirectories(FindInProjectSettings.getInstance(getProject()).getRecentDirectories());
      myScopePanel.setScopeConsumer(scope -> initiateValidation());
    }
    else {
      myScopePanel.setVisible(false);
    }

    myFilterPanel = new FilterPanel(getProject(), StructuralSearchUtil.getProfileByFileType(myFileType), getDisposable());
    myFilterPanel.setConstraintChangedCallback(() -> initiateValidation());
    myFilterPanel.getComponent().setMinimumSize(new Dimension(300, 50));

    final JLabel searchTargetLabel = new JLabel(SSRBundle.message("search.target.label"));
    myTargetComboBox = new LinkComboBox(SSRBundle.message("complete.match.variable.name"));
    myTargetComboBox.setItemConsumer(item -> {
      final MatchOptions matchOptions = myConfiguration.getMatchOptions();
      for (String name : matchOptions.getVariableConstraintNames()) {
        matchOptions.getVariableConstraint(name).setPartOfSearchResults(name.equals(item));
      }
    });

    final JPanel centerPanel = new JPanel(null);
    final GroupLayout layout = new GroupLayout(centerPanel);
    centerPanel.setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup()
        .addComponent(mySearchEditorPanel)
        .addComponent(myReplacePanel)
        .addComponent(myScopePanel)
        .addGroup(layout.createSequentialGroup()
                    .addComponent(searchTargetLabel)
                    .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 5, 5)
                    .addComponent(myTargetComboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        )
    );
    layout.setVerticalGroup(
      layout.createSequentialGroup()
        .addComponent(mySearchEditorPanel)
        .addGap(2)
        .addComponent(myReplacePanel)
        .addComponent(myScopePanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        .addGap(16)
        .addGroup(layout.createParallelGroup()
                    .addComponent(searchTargetLabel)
                    .addComponent(myTargetComboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        )
    );

    return centerPanel;
  }

  private JComponent createReplacePanel() {
    final JLabel label = new JLabel(SSRBundle.message("replacement.template.label"));
    myShortenFQN = new JCheckBox(SSRBundle.message("shorten.fully.qualified.names.checkbox"));
    myReformat = new JCheckBox(SSRBundle.message("reformat.checkbox"));
    myUseStaticImport = new JCheckBox(SSRBundle.message("use.static.import.checkbox"));
    myReplaceCriteriaEdit = createEditor("");
    myReplaceEditorPanel.setFirstComponent(myReplaceCriteriaEdit);

    final JPanel replacePanel = new JPanel(null);
    final GroupLayout layout = new GroupLayout(replacePanel);
    replacePanel.setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup()
        .addGroup(
          layout.createSequentialGroup()
            .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED, 28, 28)
            .addComponent(label)
            .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED, 20, Integer.MAX_VALUE)
            .addComponent(myShortenFQN)
            .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED, 15, 15)
            .addComponent(myReformat)
            .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED, 15, 15)
            .addComponent(myUseStaticImport)
        )
        .addComponent(myReplaceEditorPanel)
    );
    layout.setVerticalGroup(
      layout.createSequentialGroup().
        addGroup(
          layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
            .addComponent(label)
            .addComponent(myShortenFQN)
            .addComponent(myReformat)
            .addComponent(myUseStaticImport)
        )
        .addComponent(myReplaceEditorPanel)
    );

    return replacePanel;
  }

  @Nullable
  @Override
  protected JComponent createNorthPanel() {
    final DefaultActionGroup historyActionGroup = new DefaultActionGroup(new DumbAwareAction("History", null, getShowHistoryIcon()) {
      @Override
      public void actionPerformed(@NotNull AnActionEvent e) {
        final Object source = e.getInputEvent().getSource();
        if (!(source instanceof Component)) return;
        JBPopupFactory.getInstance()
                      .createPopupChooserBuilder(ConfigurationManager.getInstance(getProject()).getHistoryConfigurations())
                      .setRenderer(new ColoredListCellRenderer<Configuration>() {
                        @Override
                        protected void customizeCellRenderer(@NotNull JList<? extends Configuration> list,
                                                             Configuration value,
                                                             int index,
                                                             boolean selected,
                                                             boolean hasFocus) {
                          if (value instanceof ReplaceConfiguration) {
                            setIcon(AllIcons.Actions.Replace);
                            append(shortenTextWithEllipsis(collapseWhiteSpace(value.getMatchOptions().getSearchPattern()), 49, 0, true)
                                   + " ⇒ "
                                   + shortenTextWithEllipsis(collapseWhiteSpace(value.getReplaceOptions().getReplacement()), 49, 0, true));
                          }
                          else {
                            setIcon(AllIcons.Actions.Find);
                            append(shortenTextWithEllipsis(collapseWhiteSpace(value.getMatchOptions().getSearchPattern()), 100, 0, true));
                          }
                        }
                      })
                      .setItemChosenCallback(c -> loadConfiguration(c))
                      .setSelectionMode(ListSelectionModel.SINGLE_SELECTION)
                      .createPopup()
                      .showUnderneathOf((Component)source);
      }
    });
    final ActionManager actionManager = ActionManager.getInstance();
    final ActionToolbarImpl historyToolbar =
      (ActionToolbarImpl)actionManager.createActionToolbar(ActionPlaces.EDITOR_TOOLBAR, historyActionGroup, true);
    historyToolbar.setLayoutPolicy(ActionToolbar.NOWRAP_LAYOUT_POLICY);
    final JLabel label = new JLabel(SSRBundle.message("search.template"));
    UIUtil.installCompleteMatchInfo(label, () -> myConfiguration, link -> showFilterPanel(link));

    myRecursive = new JCheckBox(SSRBundle.message("recursive.matching.checkbox"), true);
    myRecursive.setVisible(!myReplace);
    myMatchCase = new JCheckBox(FindBundle.message("find.popup.case.sensitive"), true);
    final List<FileType> types = new ArrayList<>();
    for (FileType fileType : StructuralSearchUtil.getSuitableFileTypes()) {
      if (StructuralSearchUtil.getProfileByFileType(fileType) != null) {
        types.add(fileType);
      }
    }
    Collections.sort(types, (o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName()));
    detectFileType();
    myFileTypesComboBox = new FileTypeSelector(types);
    myFileTypesComboBox.setMinimumAndPreferredWidth(200);
    myFileTypesComboBox.setSelectedItem(myFileType, myDialect, myContext);
    myFileTypesComboBox.addItemListener(new ItemListener() {
      @Override
      public void itemStateChanged(ItemEvent e) {
        if (e.getStateChange() == ItemEvent.SELECTED) {
          final FileTypeInfo item = myFileTypesComboBox.getSelectedItem();
          if (item == null) return;
          myFileType = item.getFileType();
          myDialect = item.getDialect();
          myContext = item.getContext();
          final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByFileType(myFileType);
          assert profile != null;
          final Document searchDocument = profile.createDocument(getProject(), myFileType, myDialect, mySearchCriteriaEdit.getText());
          mySearchCriteriaEdit.setNewDocumentAndFileType(myFileType, searchDocument);
          final Document replaceDocument = profile.createDocument(getProject(), myFileType, myDialect, myReplaceCriteriaEdit.getText());
          myReplaceCriteriaEdit.setNewDocumentAndFileType(myFileType, replaceDocument);
          myFilterPanel.setProfile(profile);
          initiateValidation();
        }
      }
    });
    final JLabel fileTypeLabel = new JLabel(SSRBundle.message("search.dialog.file.type.label"));
    fileTypeLabel.setLabelFor(myFileTypesComboBox);
    final DefaultActionGroup templateActionGroup = new DefaultActionGroup(
      new DumbAwareAction(SSRBundle.message("save.template.text.button")) {

        @Override
        public void actionPerformed(@NotNull AnActionEvent e) {
          ConfigurationManager.getInstance(getProject()).showSaveTemplateAsDialog(getConfiguration());
        }
      },
      new CopyConfigurationAction(),
      new PasteConfigurationAction(),
      new DumbAwareAction(SSRBundle.message("copy.existing.template.button")) {
        @Override
        public void actionPerformed(@NotNull AnActionEvent e) {
          final SelectTemplateDialog dialog = new SelectTemplateDialog(getProject(), false, myReplace);
          if (!dialog.showAndGet()) {
            return;
          }
          final Configuration[] configurations = dialog.getSelectedConfigurations();
          if (configurations.length == 1) {
            loadConfiguration(configurations[0]);
          }
        }
      },
      Separator.getInstance(),
      new SwitchAction()
    );
    templateActionGroup.setPopup(true);
    templateActionGroup.getTemplatePresentation().setIcon(AllIcons.General.GearPlain);

    final AnAction filterAction = new DumbAwareToggleAction(null, "View variable filters", AllIcons.General.Filter) {

      @Override
      public boolean isSelected(@NotNull AnActionEvent e) {
        return isFilterPanelEnabled();
      }

      @Override
      public void setSelected(@NotNull AnActionEvent e, boolean state) {
        setFilterPanelEnabled(state);
      }

      @Override
      public void update(@NotNull AnActionEvent e) {
        e.getPresentation().setEnabled(myFilterButtonEnabled);
        super.update(e);
      }
    };
    final DefaultActionGroup optionsActionGroup = new DefaultActionGroup(filterAction, templateActionGroup);
    myOptionsToolbar = (ActionToolbarImpl)actionManager.createActionToolbar(ActionPlaces.EDITOR_TOOLBAR, optionsActionGroup, true);
    myOptionsToolbar.setLayoutPolicy(ActionToolbar.NOWRAP_LAYOUT_POLICY);
    myOptionsToolbar.setForceMinimumSize(true);

    final JPanel northPanel = new JPanel(null);
    final GroupLayout layout = new GroupLayout(northPanel);
    northPanel.setLayout(layout);
    layout.setHonorsVisibility(true);
    layout.setHorizontalGroup(
      layout.createSequentialGroup()
            .addComponent(historyToolbar, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
            .addComponent(label)
            .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED, 20, Integer.MAX_VALUE)
            .addComponent(myRecursive)
            .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED, 15, 15)
            .addComponent(myMatchCase)
            .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED, 15, 15)
            .addComponent(fileTypeLabel)
            .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 5, 5)
            .addComponent(myFileTypesComboBox, 125, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
            .addComponent(myOptionsToolbar, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
            .addComponent(historyToolbar)
            .addComponent(label)
            .addComponent(myRecursive)
            .addComponent(myMatchCase)
            .addComponent(fileTypeLabel)
            .addComponent(myFileTypesComboBox)
            .addComponent(myOptionsToolbar)
    );

    return northPanel;
  }

  @Nullable
  @Override
  protected JPanel createSouthAdditionalPanel() {
    if (myEditConfigOnly) return null;
    final JPanel panel = new JPanel(new BorderLayout());
    panel.setBorder(BorderFactory.createEmptyBorder(0, 6, 0, 0));
    myOpenInNewTab = new JCheckBox(SSRBundle.message("open.in.new.tab.checkbox"));
    myOpenInNewTab.setSelected(FindSettings.getInstance().isShowResultsInSeparateView());
    panel.add(myOpenInNewTab, BorderLayout.EAST);
    return panel;
  }

  Project getProject() {
    return mySearchContext.getProject();
  }

  @Override
  public void show() {
    StructuralSearchPlugin.getInstance(getProject()).setDialogVisible(true);
    if (!myUseLastConfiguration) {
      setTextFromContext();
    }
    super.show();

    // handle dimension service manually to store dimensions correctly when switching between search/replace in the same dialog
    final DimensionService dimensionService = DimensionService.getInstance();
    final Point location = dimensionService.getLocation(SEARCH_DIMENSION_SERVICE_KEY, getProject());
    if (location != null) {
      setLocation(location);
    }
    final Dimension size = dimensionService.getSize(myReplace ? REPLACE_DIMENSION_SERVICE_KEY : SEARCH_DIMENSION_SERVICE_KEY, getProject());
    if (size != null) {
      setSize(size.width, size.height);
    }
    else {
      pack();
      // set width from replace if search not available and vice versa
      final Dimension otherSize =
        dimensionService.getSize(myReplace ? SEARCH_DIMENSION_SERVICE_KEY : REPLACE_DIMENSION_SERVICE_KEY, getProject());
      if (otherSize != null) {
        setSize(otherSize.width, getSize().height);
      }
    }
  }

  private void startTemplate() {
    if (!Registry.is("ssr.template.from.selection.builder")) {
      return;
    }
    Document document = mySearchCriteriaEdit.getDocument();
    PsiFile psiFile = PsiDocumentManager.getInstance(getProject()).getPsiFile(document);
    assert psiFile != null;
    TemplateBuilder builder = new StructuralSearchTemplateBuilder(psiFile).buildTemplate();
    WriteCommandAction
      .runWriteCommandAction(getProject(), () -> builder.run(Objects.requireNonNull(mySearchCriteriaEdit.getEditor()), true));
  }

  @Override
  public JComponent getPreferredFocusedComponent() {
    return mySearchCriteriaEdit;
  }

  @Override
  protected void doOKAction() {
    myDoingOkAction = true;
    final boolean result = isValid();
    myDoingOkAction = false;
    if (!result) return;

    myAlarm.cancelAllRequests();
    myConfiguration.removeUnusedVariables();
    final SearchScope scope = myScopePanel.getScope();
    if (scope == null) return;
    super.doOKAction();
    if (myEditConfigOnly) return;

    if (scope instanceof GlobalSearchScopesCore.DirectoryScope) {
      final GlobalSearchScopesCore.DirectoryScope directoryScope = (GlobalSearchScopesCore.DirectoryScope)scope;
      FindInProjectSettings.getInstance(getProject()).addDirectory(directoryScope.getDirectory().getPresentableUrl());
    }

    final FindSettings findSettings = FindSettings.getInstance();
    findSettings.setDefaultScopeName(scope.getDisplayName());
    findSettings.setShowResultsInSeparateView(myOpenInNewTab.isSelected());

    try {
      ConfigurationManager.getInstance(getProject()).addHistoryConfiguration(myConfiguration);
      startSearching();
    }
    catch (MalformedPatternException ex) {
      reportMessage(SSRBundle.message("this.pattern.is.malformed.message", ex.getMessage()), true, mySearchCriteriaEdit);
    }
  }

  public Configuration getConfiguration() {
    saveConfiguration();
    return myConfiguration;
  }

  private boolean isValid() {
    final MatchOptions matchOptions = getConfiguration().getMatchOptions();
    try {
      Matcher.validate(getProject(), matchOptions);
    }
    catch (MalformedPatternException e) {
      final String message = isEmpty(matchOptions.getSearchPattern())
                             ? null
                             : SSRBundle.message("this.pattern.is.malformed.message", (e.getMessage() != null) ? e.getMessage() : "");
      reportMessage(message, true, mySearchCriteriaEdit);
      return false;
    }
    catch (UnsupportedPatternException e) {
      reportMessage(SSRBundle.message("this.pattern.is.unsupported.message", e.getMessage()), true, mySearchCriteriaEdit);
      return false;
    }
    catch (NoMatchFoundException e) {
      reportMessage(e.getMessage(), false, myScopePanel);
      return false;
    }
    reportMessage(null, false, mySearchCriteriaEdit);
    if (myReplace) {
      try {
        Replacer.checkSupportedReplacementPattern(getProject(), myConfiguration.getReplaceOptions());
      }
      catch (UnsupportedPatternException ex) {
        reportMessage(SSRBundle.message("unsupported.replacement.pattern.message", ex.getMessage()), true, myReplaceCriteriaEdit);
        return false;
      }
      catch (MalformedPatternException ex) {
        reportMessage(SSRBundle.message("malformed.replacement.pattern.message", ex.getMessage()), true, myReplaceCriteriaEdit);
        return false;
      }
    }
    reportMessage(null, false, myReplaceCriteriaEdit);
    return myEditConfigOnly || myScopePanel.getScope() != null;
  }

  void reportMessage(String message, boolean error, JComponent component) {
    com.intellij.util.ui.UIUtil.invokeLaterIfNeeded(() -> {
      component.putClientProperty("JComponent.outline", (!error || message == null) ? null : "error");
      component.repaint();

      if (message == null) return;
      final Balloon balloon = JBPopupFactory.getInstance()
        .createHtmlTextBalloonBuilder(message, error ? MessageType.ERROR : MessageType.WARNING, null)
        .setHideOnFrameResize(false)
        .createBalloon();
      if (component != myScopePanel) {
        balloon.show(new RelativePoint(component, new Point(component.getWidth() / 2, component.getHeight())), Balloon.Position.below);
      }
      else {
        balloon.show(new RelativePoint(component, new Point(component.getWidth() / 2, 0)), Balloon.Position.above);
      }
      balloon.showInCenterOf(component);
      Disposer.register(myDisposable, balloon);
    });
  }

  void securityCheck() {
    final MatchOptions matchOptions = myConfiguration.getMatchOptions();
    for (String name : matchOptions.getVariableConstraintNames()) {
      final MatchVariableConstraint constraint = matchOptions.getVariableConstraint(name);
      if (showSecurityMessage(constraint)) return;
    }
    final ReplaceOptions replaceOptions = myConfiguration.getReplaceOptions();
    if (replaceOptions != null) {
      for (ReplacementVariableDefinition variableDefinition : replaceOptions.getVariableDefinitions()) {
        if (showSecurityMessage(variableDefinition)) return;
      }
    }
  }

  private boolean showSecurityMessage(NamedScriptableDefinition constraint) {
    if (constraint.getScriptCodeConstraint().length() <= 2) {
      return false;
    }
    EdtInvocationManager.getInstance().invokeLater(
      () -> reportMessage(SSRBundle.message("import.template.script.warning", ApplicationNamesInfo.getInstance().getFullProductName()),
                          false, myOptionsToolbar));
    return true;
  }

  public void showFilterPanel(String variableName) {
    if (myFilterButtonEnabled) {
      myFilterPanel.initFilters(UIUtil.getOrAddVariableConstraint(variableName, myConfiguration));
      setFilterPanelEnabled(true);
      myConfiguration.setCurrentVariableName(variableName);
    }
  }

  void setFilterPanelEnabled(boolean enabled) {
    if (enabled) {
      if (!isFilterPanelEnabled()) {
        mySearchEditorPanel.setSecondComponent(myFilterPanel.getComponent());
      }
    }
    else {
      if (isFilterPanelEnabled()) {
        mySearchEditorPanel.setSecondComponent(null);
        myConfiguration.setCurrentVariableName(null);
      }
    }
  }

  boolean isFilterPanelEnabled() {
    return mySearchEditorPanel.getSecondComponent() != null;
  }

  private void setSearchTargets(MatchOptions matchOptions) {
    final List<String> names = new ArrayList<>(matchOptions.getVariableConstraintNames());
    names.remove(Configuration.CONTEXT_VAR_NAME);
    names.add(SSRBundle.message("complete.match.variable.name"));
    myTargetComboBox.setItems(names);
    if (names.size() > 1) {
      myTargetComboBox.setEnabled(true);
      for (String name : names) {
        final MatchVariableConstraint constraint = matchOptions.getVariableConstraint(name);
        if (constraint != null && constraint.isPartOfSearchResults()) {
          myTargetComboBox.setSelectedItem(name);
          break;
        }
      }
    }
    else {
      myTargetComboBox.setEnabled(false);
    }
  }

  boolean loadConfiguration(String text) {
    if (text == null) {
      return false;
    }
    final Configuration configuration = ConfigurationUtil.fromXml(text);
    if (configuration == null) {
      return false;
    }
    loadConfiguration(configuration);
    securityCheck();
    return true;
  }

  public void loadConfiguration(Configuration configuration) {
    myConfiguration = createConfiguration(configuration);
    final MatchOptions matchOptions = myConfiguration.getMatchOptions();
    setSearchTargets(matchOptions);
    final SearchScope scope = matchOptions.getScope();
    if (scope != null) {
      myScopePanel.setScope(scope);
    }

    UIUtil.setContent(mySearchCriteriaEdit, matchOptions.getSearchPattern());

    myMatchCase.setSelected(matchOptions.isCaseSensitiveMatch());
    myFileTypesComboBox.setSelectedItem(matchOptions.getFileType(), matchOptions.getDialect(), matchOptions.getPatternContext());
    final Editor searchEditor = mySearchCriteriaEdit.getEditor();
    if (searchEditor != null) {
      searchEditor.putUserData(SubstitutionShortInfoHandler.CURRENT_CONFIGURATION_KEY, myConfiguration);
    }

    final PropertiesComponent properties = PropertiesComponent.getInstance();
    if (myReplace) {
      if (configuration instanceof ReplaceConfiguration) {
        final ReplaceOptions replaceOptions = configuration.getReplaceOptions();

        UIUtil.setContent(myReplaceCriteriaEdit, replaceOptions.getReplacement());

        myShortenFQN.setSelected(replaceOptions.isToShortenFQN());
        myReformat.setSelected(replaceOptions.isToReformatAccordingToStyle());
        myUseStaticImport.setSelected(replaceOptions.isToUseStaticImport());
      }
      else {
        UIUtil.setContent(myReplaceCriteriaEdit, matchOptions.getSearchPattern());

        myShortenFQN.setSelected(properties.getBoolean(SHORTEN_FQN_STATE));
        myReformat.setSelected(properties.getBoolean(REFORMAT_STATE));
        myUseStaticImport.setSelected(properties.getBoolean(USE_STATIC_IMPORT_STATE));
      }
      final Editor replaceEditor = myReplaceCriteriaEdit.getEditor();
      if (replaceEditor != null) {
        replaceEditor.putUserData(SubstitutionShortInfoHandler.CURRENT_CONFIGURATION_KEY, myConfiguration);
      }
      myRecursive.setSelected(false);
    }
    else {
      if (configuration instanceof ReplaceConfiguration) {
        myRecursive.setSelected(properties.getBoolean(RECURSIVE_STATE));
      }
    }
  }

  private void saveConfiguration() {
    final MatchOptions matchOptions = myConfiguration.getMatchOptions();

    if (!myEditConfigOnly) {
      final SearchScope scope = myScopePanel.getScope();
      if (scope != null) {
        final boolean searchWithinHierarchy = IdeBundle.message("scope.class.hierarchy").equals(scope.getDisplayName());
        // We need to reset search within hierarchy scope during online validation since the scope works with user participation
        matchOptions.setScope(searchWithinHierarchy && !myDoingOkAction ? GlobalSearchScope.projectScope(getProject()) : scope);
      }
    }
    matchOptions.setFileType(myFileType);
    matchOptions.setDialect(myDialect);
    matchOptions.setPatternContext(myContext);
    matchOptions.setSearchPattern(mySearchCriteriaEdit.getDocument().getText());
    matchOptions.setCaseSensitiveMatch(myMatchCase.isSelected());

    if (myReplace) {
      final ReplaceOptions replaceOptions = myConfiguration.getReplaceOptions();

      replaceOptions.setReplacement(myReplaceCriteriaEdit.getDocument().getText());
      replaceOptions.setToShortenFQN(myShortenFQN.isSelected());
      replaceOptions.setToReformatAccordingToStyle(myReformat.isSelected());
      replaceOptions.setToUseStaticImport(myUseStaticImport.isSelected());
    }
    else {
      matchOptions.setRecursiveSearch(myRecursive.isSelected());
    }

    final PropertiesComponent properties = PropertiesComponent.getInstance();
    if (myReplace) {
      properties.setValue(SHORTEN_FQN_STATE, myShortenFQN.isSelected());
      properties.setValue(REFORMAT_STATE, myReformat.isSelected());
      properties.setValue(USE_STATIC_IMPORT_STATE, myUseStaticImport.isSelected());
    }
    else {
      properties.setValue(RECURSIVE_STATE, myRecursive.isSelected());
      properties.setValue(MATCH_CASE_STATE, myMatchCase.isSelected());
    }
  }

  @Nullable
  @Override
  protected final String getDimensionServiceKey() {
    return null;
  }

  @Override
  public void dispose() {
    if (myReplace) storeDimensions(REPLACE_DIMENSION_SERVICE_KEY, SEARCH_DIMENSION_SERVICE_KEY);
    else storeDimensions(SEARCH_DIMENSION_SERVICE_KEY, REPLACE_DIMENSION_SERVICE_KEY);

    StructuralSearchPlugin.getInstance(getProject()).setDialogVisible(false);
    myAlarm.cancelAllRequests();
    mySearchCriteriaEdit.removeNotify();
    myReplaceCriteriaEdit.removeNotify();
    super.dispose();
  }

  private void storeDimensions(String key1, String key2) {
    // handle own dimension service to store dimensions correctly when switching between search/replace in the same dialog
    final Dimension size = getSize();
    final DimensionService dimensionService = DimensionService.getInstance();
    dimensionService.setLocation(SEARCH_DIMENSION_SERVICE_KEY, getLocation(), getProject());
    dimensionService.setSize(key1, size, getProject());
    final Dimension otherSize = dimensionService.getSize(key2);
    if (otherSize != null && otherSize.width != size.width) {
      otherSize.width = size.width;
      dimensionService.setSize(key2, otherSize, getProject());
    }
  }

  @Override
  protected String getHelpId() {
    return "find.structuredSearch";
  }

  private static Icon getShowHistoryIcon() {
    return AllIcons.Actions.SearchWithHistory;
  }

  private class SwitchAction extends AnAction implements DumbAware {

    SwitchAction() {
      init();
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
      myReplace = !myReplace;
      setTitle(getDefaultTitle());
      myReplacePanel.setVisible(myReplace);
      myRecursive.setVisible(!myReplace);
      loadConfiguration(myConfiguration);
      final Dimension size =
        DimensionService.getInstance().getSize(myReplace ? REPLACE_DIMENSION_SERVICE_KEY : SEARCH_DIMENSION_SERVICE_KEY);
      if (size != null) {
        setSize(getSize().width, size.height);
      }
      else {
        pack();
      }
      init();
    }

    private void init() {
      getTemplatePresentation().setText(SSRBundle.message(myReplace ? "switch.to.search.action" : "switch.to.replace.action"));
      final ActionManager actionManager = ActionManager.getInstance();
      final ShortcutSet searchShortcutSet = actionManager.getAction("StructuralSearchPlugin.StructuralSearchAction").getShortcutSet();
      final ShortcutSet replaceShortcutSet = actionManager.getAction("StructuralSearchPlugin.StructuralReplaceAction").getShortcutSet();
      final ShortcutSet shortcutSet = myReplace
                                      ? new CompositeShortcutSet(searchShortcutSet, replaceShortcutSet)
                                      : new CompositeShortcutSet(replaceShortcutSet, searchShortcutSet);
      registerCustomShortcutSet(shortcutSet, getRootPane());
    }
  }

  private class CopyConfigurationAction extends AnAction implements DumbAware {

    CopyConfigurationAction() {
      super(SSRBundle.message("export.template.action"));
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
      CopyPasteManager.getInstance().setContents(new TextTransferable(ConfigurationUtil.toXml(myConfiguration)));
    }
  }

  private class PasteConfigurationAction extends AnAction implements DumbAware {

    PasteConfigurationAction() {
      super(SSRBundle.message("import.template.action"));
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
      final String contents = CopyPasteManager.getInstance().getContents(DataFlavor.stringFlavor);
      if (!loadConfiguration(contents)) {
        reportMessage(SSRBundle.message("no.template.found.warning"), false, myOptionsToolbar);
      }
    }
  }
}


text:
package lcf

import (
	"bytes"
	"io"
	"os"

	"github.com/sirupsen/logrus"
)

// WithCapSys temporarily redirects stdout/stderr pipes to capture the output while the function runs. Returns them as
// strings.
func WithCapSys(function func()) (string, string, error) {
	var writeStdout *os.File
	var writeStderr *os.File
	chanStdout := make(chan string)
	chanStderr := make(chan string)

	// Prepare new streams.
	if read, write, err := os.Pipe(); err == nil {
		writeStdout = write
		go func() { var buf bytes.Buffer; io.Copy(&buf, read); chanStdout <- buf.String() }()
		if read, write, err := os.Pipe(); err == nil {
			writeStderr = write
			go func() { var buf bytes.Buffer; io.Copy(&buf, read); chanStderr <- buf.String() }()
		} else {
			return "", "", err
		}
	} else {
		return "", "", err
	}

	// Patch streams.
	oldStdout := os.Stdout
	oldStderr := os.Stderr
	defer func() { os.Stdout = oldStdout; os.Stderr = oldStderr }()
	os.Stdout = writeStdout
	os.Stderr = writeStderr

	// Run.
	function()

	// Collect and return.
	writeStdout.Close()
	writeStderr.Close()
	stdout := <-chanStdout
	stderr := <-chanStderr
	return stdout, stderr, nil
}

// ResetLogger re-initializes the global logrus logger so stdout/stderr changes are applied to it.
// Otherwise after patching the streams logrus still points to the original file descriptor.
func ResetLogger() {
	*logrus.StandardLogger() = *logrus.New()
}

// Log sample messages to logrus.
func LogMsgs() {
	logrus.Debug("Sample debug 1.")
	logrus.WithFields(logrus.Fields{"name": CallerName(1), "a": "b", "c": 10}).Debug("Sample debug 2.")
	logrus.Info("Sample info 1.")
	logrus.WithFields(logrus.Fields{"name": CallerName(1), "a": "b", "c": 10}).Info("Sample info 2.")
	logrus.Warn("Sample warn 1.")
	logrus.WithFields(logrus.Fields{"name": CallerName(1), "a": "b", "c": 10}).Warn("Sample warn 2.")
	logrus.Error("Sample error 1.")
	logrus.WithFields(logrus.Fields{"name": CallerName(1), "a": "b", "c": 10}).Error("Sample error 2.")
}

redpajama_set_name: RedPajamaGithub


text:
package com.github.redsolo.vcm.commands;

import static com.github.redsolo.vcm.Matchers.hasItemWithValue;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

import java.io.File;
import java.util.Arrays;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import com.github.redsolo.vcm.Model;
import com.github.redsolo.vcm.ModelResource;
import com.github.redsolo.vcm.commands.MainConfiguration;
import com.github.redsolo.vcm.commands.ReplaceTextInResourceCommand;
import com.github.redsolo.vcm.commands.ResourceDataParser;
import com.github.redsolo.vcm.util.TestUtil;

public class ReplaceTextInResourceCommandTest {

	@Rule
	public TemporaryFolder folder = new TemporaryFolder();

	@Test
	public void assertPropertiesAreUpdated() throws Throwable {
		File file = TestUtil.getResourceFile(folder.getRoot());
		ReplaceTextInResourceCommand command = new ReplaceTextInResourceCommand();
		command.setReplacementtext(Arrays.asList(new String[]{"ACME::PLATFORM=ACME::PlatformS"}));
		command.setComponentRootPath(file.getParentFile().getCanonicalPath());
		command.execute(new MainConfiguration());

		Model model = new Model(file);
		ModelResource variables = ResourceDataParser.getVariables(model.getResourceData());
        assertThat(variables.getResources(), hasItemWithValue("ACME::PlatformS", "Y12"));
        assertThat(model.getComponentData().getRevision(), is(49l));
	}
}


text:
import React, {Component} from 'react';
import { View,
         Text,
         TextInput,
         ActivityIndicator,
         StyleSheet} from 'react-native';

export default class SearchBar extends Component {
  constructor(props) {
    super(props)
    this.state = {
      text: ''
    }
  }

  //-----------------------------------
  // RENDERING
  //-----------------------------------

  render() {
    return (
      <View style={styles.searchBar}>
        <TextInput
            style={styles.searchBarInput}
            onKeyPress={this._handleKeyPress}
            onSubmitEditing={this.props.onSearchChange}
            placeholder=" Search for a user..."
            autoCapitalize="words"
            auotCorrect="false"
        />
        <ActivityIndicator
          animating={this.props.isLoading}
          style={styles.spinner}
        />
      </View>
    );
  }

  //-----------------------------------
  // PRIVATE METHODS
  //-----------------------------------

  _handleKeyPress(event) {
    // if (event.nativeEvent.key === 'Enter') {
      // this._update(this.state.text)
    // }
  }

  _update(text) {
    this.props.onUpdate(text)
  }
}

const styles = StyleSheet.create({
  searchBar: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 20,
    paddingVertical: 10,
  },
  searchBarInput: {
    height: 40,
    borderColor: 'gray',
    borderWidth: 1,
    flex: 1,
  },
  spinner: {
    width: 30,
  },
});


text:
export default [function(){
    return {
        generateArraysOfNodesAndLinks: (allNodes) => {
            let nonRootNodeIds = [];
            let allNodeIds = [];
            let arrayOfLinksForChart = [];
            let nodeIdToChartNodeIdMapping = {};
            let chartNodeIdToIndexMapping = {};
            let nodeRef = {};
            let nodeIdCounter = 1;
            let arrayOfNodesForChart = [
                {
                    id: nodeIdCounter,
                    unifiedJobTemplate: {
                        name: "START"
                    }
                }
            ];
            nodeIdCounter++;
            // Assign each node an ID - 0 is reserved for the start node.  We need to
            // make sure that we have an ID on every node including new nodes so the
            // ID returned by the api won't do
            allNodes.forEach((node) => {
                node.workflowMakerNodeId = nodeIdCounter;
                nodeRef[nodeIdCounter] = {
                    originalNodeObject: node
                };

                const nodeObj = {
                    index: nodeIdCounter-1,
                    id: nodeIdCounter
                };

                if(node.summary_fields.job) {
                    nodeObj.job = node.summary_fields.job;
                }
                if(node.summary_fields.unified_job_template) {
                    nodeRef[nodeIdCounter].unifiedJobTemplate = nodeObj.unifiedJobTemplate = node.summary_fields.unified_job_template;
                }

                arrayOfNodesForChart.push(nodeObj);
                allNodeIds.push(node.id);
                nodeIdToChartNodeIdMapping[node.id] = node.workflowMakerNodeId;
                chartNodeIdToIndexMapping[nodeIdCounter] = nodeIdCounter-1;
                nodeIdCounter++;
            });

            allNodes.forEach((node) => {
                const sourceIndex = chartNodeIdToIndexMapping[node.workflowMakerNodeId];
                node.success_nodes.forEach((nodeId) => {
                    const targetIndex = chartNodeIdToIndexMapping[nodeIdToChartNodeIdMapping[nodeId]];
                    arrayOfLinksForChart.push({
                        source: arrayOfNodesForChart[sourceIndex],
                        target: arrayOfNodesForChart[targetIndex],
                        edgeType: "success"
                    });
                    nonRootNodeIds.push(nodeId);
                });
                node.failure_nodes.forEach((nodeId) => {
                    const targetIndex = chartNodeIdToIndexMapping[nodeIdToChartNodeIdMapping[nodeId]];
                    arrayOfLinksForChart.push({
                        source: arrayOfNodesForChart[sourceIndex],
                        target: arrayOfNodesForChart[targetIndex],
                        edgeType: "failure"
                    });
                    nonRootNodeIds.push(nodeId);
                });
                node.always_nodes.forEach((nodeId) => {
                    const targetIndex = chartNodeIdToIndexMapping[nodeIdToChartNodeIdMapping[nodeId]];
                    arrayOfLinksForChart.push({
                        source: arrayOfNodesForChart[sourceIndex],
                        target: arrayOfNodesForChart[targetIndex],
                        edgeType: "always"
                    });
                    nonRootNodeIds.push(nodeId);
                });
            });

            let uniqueNonRootNodeIds = Array.from(new Set(nonRootNodeIds));

            let rootNodes = _.difference(allNodeIds, uniqueNonRootNodeIds);

            rootNodes.forEach((rootNodeId) => {
                const targetIndex = chartNodeIdToIndexMapping[nodeIdToChartNodeIdMapping[rootNodeId]];
                arrayOfLinksForChart.push({
                    source: arrayOfNodesForChart[0],
                    target: arrayOfNodesForChart[targetIndex],
                    edgeType: "always"
                });
            });

            return {
                arrayOfNodesForChart,
                arrayOfLinksForChart,
                nodeIdToChartNodeIdMapping,
                nodeRef,
                workflowMakerNodeIdCounter: nodeIdCounter
            };
        }
    };
}];


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

import wvlet.airframe.control.Retry.RetryContext
import wvlet.airframe.http.HttpMessage.{Request, Response}
import wvlet.airframe.http.{HttpClient, HttpClientConfig, ServerAddress}

/**
  */
trait HttpClientBackend {
  def defaultRequestRetryer: RetryContext = HttpClient.defaultHttpClientRetry[Request, Response]

  def newHttpChannel(serverAddress: ServerAddress, config: HttpClientConfig): HttpChannel

  def newSyncClient(serverAddress: ServerAddress, config: HttpClientConfig): SyncClient = {
    new SyncClientImpl(newHttpChannel(serverAddress, config), config)
  }

  def newAsyncClient(
      serverAddress: ServerAddress,
      config: HttpClientConfig
  ): AsyncClient = {
    new AsyncClientImpl(newHttpChannel(serverAddress, config), config)
  }
}


text:
const argString = process.argv[2];

let tplString = `Hello, ${argString}!
Your name lowercased is "${argString.toLowerCase()}".`;

console.log(tplString);


text:
export SPARK_HOME=/spark-2.2.1-bin-hadoop2.7
export PYTHONPATH=$SPARK_HOME/python:$SPARK_HOME/python/lib/py4j-0.10.4-src.zip
export PYSPARK_PYTHON=/usr/bin/python3.5
export PYSPARK_DRIVER_PYTHON=/usr/local/bin/jupyter
export PYSPARK_DRIVER_PYTHON_OPTS="notebook --allow-root --NotebookApp.open_browser=False --NotebookApp.ip='0.0.0.0' --NotebookApp.port=8888"


text:
package org.osgi.impl.service.upnp.cd;

import java.net.InetAddress;
import java.net.UnknownHostException;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.impl.service.upnp.cd.control.ControlImpl;
import org.osgi.impl.service.upnp.cd.event.EventRegistry;
import org.osgi.impl.service.upnp.cd.event.GenaServer;
import org.osgi.impl.service.upnp.cd.event.SubscriptionAlive;
import org.osgi.impl.service.upnp.cd.ssdp.SSDPComponent;

public class UPnPController implements BundleActivator {
	private String				devexp;
	private SSDPComponent		ssdpcomp;
	private ControlImpl			control;
	private GenaServer			server;
	private SubscriptionAlive	sa;
	@SuppressWarnings("unused")
	private BundleContext		bc;

	// This method starts the CD bundle
	@Override
	public void start(@SuppressWarnings("hiding") BundleContext bc)
			throws Exception {
		//System.out.println("UPnP : starting CD exporter");
		this.bc = bc;
		devexp = "2100";
		String IP = bc.getProperty("org.osgi.service.http.hostname");
		try {
			if (IP == null) {
				IP = InetAddress.getLocalHost().getHostAddress();
			}
			else {
				IP = InetAddress.getByName(IP).getHostAddress();
			}
		}
		catch (UnknownHostException e) {
			IP = "127.0.0.1";
		}
		//Control starting
		control = new ControlImpl();
		//Eventing starting
		EventRegistry eventregistry = new EventRegistry(IP);
		sa = new SubscriptionAlive();
		sa.start();
		try {
			server = new GenaServer(8180, control, bc, eventregistry);
			server.start();
		}
		catch (Exception e) {
			System.out.println(e.getMessage());
		}
		//SSDDP starting
		try {
			ssdpcomp = new SSDPComponent(devexp, bc, server.getServerIP(),
					eventregistry);
			ssdpcomp.startSSDPFunctionality();
			//System.out.println("Discovery started");
		}
		catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}

	// This method stops the bundle
	@Override
	public void stop(@SuppressWarnings("hiding") BundleContext bc)
			throws Exception {
		try {
			if (ssdpcomp != null) {
				ssdpcomp.killSSDP();
			}
			if (server != null) {
				server.shutdown();
			}
			if (sa != null) {
				sa.surrender(false);
			}
		}
		catch (Exception e) {
			System.out.println(e.getMessage());
			throw e;
		}
	}
}


text:
var app = angular.module('frontendApp', ['ngAnimate', 'ngSanitize', 'ui.bootstrap', 'ui.bootstrap.modal', 'ui.bootstrap.datepicker', 'ui.bootstrap.timepicker', 'ui.sortable', 'ui.select', 'ajoslin.promise-tracker', 'directoryService', 'vocabularyService', 'metadataService', 'frontendService', 'bagService', 'jobService', 'Url', 'uiGmapgoogle-maps', 'pascalprecht.translate', 'pasvaz.bindonce']);

app.config(function(uiGmapGoogleMapApiProvider) {
    uiGmapGoogleMapApiProvider.configure({
  //      key: <%= $config->{google_maps_api_key} %>,
        key:'AIzaSyBWE_bAtgkm1RuWkrW7jBrYV1JBiPUZDAs',
        v: '3.17',
        libraries: 'weather,geometry,visualization'
    });
});

app.config(['$translateProvider', function($translateProvider){

  // [prefix][langKey][suffix]
  $translateProvider.useStaticFilesLoader({
    prefix: 'i18n/',
    suffix: '.json'
  });

  // Tell the module what language to use by default
  $translateProvider.preferredLanguage('en_US');
}]);

app.controller('FrontendCtrl', function($scope, $window, $modal, $log, $translate, DirectoryService, MetadataService, FrontendService, promiseTracker) {

  // we will use this to track running ajax requests to show spinner
  $scope.loadingTracker = promiseTracker.register('loadingTrackerFrontend');

    $scope.alerts = [];
    $scope.query = '';

  $scope.initdata = '';
  $scope.current_user = '';

  $scope.uwmfields = {
      user: [],
      project: []
  };

  $scope.default_template = {
      user: '',
      project: ''
  };

  $scope.settings = {
    user: {},
    project: {}
  };

  $scope.projectclasses = [];

  $scope.init = function (initdata) {

    $scope.initdata = angular.fromJson(initdata);

    $scope.current_user = $scope.initdata.current_user;
    $scope.baseurl = $('head base').attr('href');
    };

    $scope.initSettings = function (initdata_settings) {
      $scope.baseurl = $('head base').attr('href');
      var d = angular.fromJson(initdata_settings);
      $scope.initdata = d;
      $scope.current_user = d.current_user;
      $scope.loadSettings();
    };

    $scope.loadSettings = function() {
      var promise = FrontendService.loadSettings();
    $scope.loadingTracker.addPromise(promise);
    promise.then(
        function(response) {
          $scope.alerts = response.data.alerts;
          console.log('loadSettings:',response.data);
          $scope.settings = response.data.settings;

          delete $scope.settings.members;
          console.log('xxxxxxx', $scope.settings);
          if($scope.settings.project['included_classifications']){
            var included_classifications = {};
            for (var i = 0; i < $scope.settings.project.included_classifications.length; ++i) {
              included_classifications[$scope.settings.project.included_classifications[i]] = true;
            }
            $scope.settings.project['included_classifications'] = included_classifications;
          }
          $scope.settings.templates.push({title:'None',_id:''});
          if($scope.settings.user == null){
              $scope.settings.user = {};
          }
          console.log('int settings:', $scope.settings);
          $scope.getProjectClasses();
          $scope.getUwmfields();
          $scope.form_disabled = false;
        }
        ,function(response) {
          $scope.alerts = response.data.alerts;
          $scope.alerts.unshift({type: 'danger', msg: "Error code "+response.status});
           $scope.form_disabled = false;
         }
    );
    }

    $scope.getUwmfields = function () {
      var promise = MetadataService.getUwmetadataTree();
    $scope.loadingTracker.addPromise(promise);
    promise.then(
        function(response) {
          $scope.alerts = response.data.alerts;
          $scope.uwmfields.user = response.data.tree;
          angular.copy(response.data.tree, $scope.uwmfields.project);
          console.log('uwmfields:',$scope.uwmfields);
          $scope.applyVisibleFieldsSettings();
          $scope.form_disabled = false;
        }
        ,function(response) {
          $scope.alerts = response.data.alerts;
          $scope.alerts.unshift({type: 'danger', msg: "Error code "+response.status});
           $scope.form_disabled = false;
         }
    );
  };

  $scope.applyVisibleFieldsSettings = function(){
    if($scope.settings['user'].visible_uwmfields){
      $scope.applyVisibleFieldsSettingsRec($scope.uwmfields['user'], $scope.settings['user'].visible_uwmfields);
    }
    if($scope.settings['project'].visible_uwmfields){
      $scope.applyVisibleFieldsSettingsRec($scope.uwmfields['project'], $scope.settings['project'].visible_uwmfields);
    }
  }

  $scope.saveSettings = function(type){

    console.log('saveSettings type',type);

    console.log('aaaaa2',$scope.settings.project.members);
    //default_assignee
    if(type == 'members'){

         //$scope.settings[type] =  $scope.settings.project.members;
         //$scope.settings[type].visible_uwmfields = [];
         //console.log('uwmfields111:',$scope.uwmfields[type]);

         //$scope.saveVisibleFieldsSettingsRec($scope.uwmfields[type], type);

         console.log('aaaaa11',$scope.settings.project.members);
         $scope.form_disabled = true;
         var promise = FrontendService.saveSettings(type, $scope.settings.project.members);
         $scope.loadingTracker.addPromise(promise);
         promise.then(
           function(response) {
             $scope.form_disabled = false;
             $scope.alerts = response.data.alerts;
           }
          ,function(response) {
             $scope.form_disabled = false;
             $scope.alerts = response.data.alerts;
           }
         );

    }else{

         console.log('default_template before save1',$scope.settings.project.default_template);
         console.log('default_template before save2',$scope.settings.user.default_template);

         $scope.settings[type].visible_uwmfields = [];
         $scope.saveVisibleFieldsSettingsRec($scope.uwmfields[type], type);

         if($scope.settings.project.members){
                 if($scope.settings.project.members.selected){
                           $scope.settings[type].default_assignee = $scope.settings.project.members.selected.username;
                 }
         }
         console.log('settings before save',$scope.settings);
         $scope.form_disabled = true;
         var promise = FrontendService.saveSettings(type, $scope.settings[type]);
         $scope.loadingTracker.addPromise(promise);
         promise.then(
           function(response) {
             $scope.form_disabled = false;
             $scope.alerts = response.data.alerts;
           }
           ,function(response) {
             $scope.form_disabled = false;
             $scope.alerts = response.data.alerts;
             }
         );

    }
  };

  $scope.addClassToConfig = function(uri){
    if(typeof $scope.settings.project.classifications == 'undefined'){
            $scope.settings.project['classifications'] = [];
    }
    $scope.settings.project.classifications.push(uri);
    $scope.saveSettings('project');
    $scope.getProjectClasses();
  }

  $scope.removeClassFromConfig = function(index){
    if(typeof $scope.settings.project.classifications == 'undefined'){
          $scope.settings.project['classifications'] = [];
    }else{
          $scope.settings['project'].classifications.splice(index, 1);
    }
    $scope.saveSettings('project');
    $scope.getProjectClasses();
  }

  $scope.removeMemberFromConfig = function(index){

    if(typeof $scope.settings.project.members == 'undefined'){
         $scope.settings.project.members = [];
    }else{
         $scope.settings.project.members.splice(index, 1);
    }
    $scope.saveSettings('members');

  }

  $scope.editMemberConfig = function(index, member_data){

       var modalInstance = $modal.open({
            templateUrl: $('head base').attr('href')+'views/modals/edit_project_member.html',
            controller: EditMemberModalCtrl,
            scope: $scope,
            resolve: {
                            username: function(){
                                   return member_data.username;
                                  },
                            role: function(){
                                   return member_data.role;
                                  },
                            displayname: function(){
                                   return member_data.displayname;
                                  }
                    }
      });
  }

   $scope.addMemberConfig = function(){

        console.log('addMemberConfig:');
       var modalInstance = $modal.open({
            templateUrl: $('head base').attr('href')+'views/modals/add_project_member.html',
            controller: AddMemberModalCtrl,
            scope: $scope
      });
   }

  $scope.getProjectClasses = function(index){
    $scope.form_disabled = true;
    var promise = FrontendService.getClassifications();
    $scope.loadingTracker.addPromise(promise);
    promise.then(
      function(response) {
        $scope.form_disabled = false;
        $scope.projectclasses = [];
        for (var i = 0; i < response.data.classifications.length; ++i) {
            if(response.data.classifications[i].type == 'project'){
              $scope.projectclasses.push(response.data.classifications[i]);
            }
        }
        $scope.alerts = response.data.alerts;
      }
      ,function(response) {
        $scope.form_disabled = false;
        $scope.alerts = response.data.alerts;
        }
    );
  }

  $scope.saveVisibleFieldsSettingsRec = function(children, type){
    for (var i = 0; i < children.length; ++i) {
      if(children[i].include){
        var uri;
        if(children[i].help_id == "helpmeta_37"){
          uri = children[i].xmlns+'/rights#'+children[i].xmlname;
        }else{
          uri = children[i].xmlns+'#'+children[i].xmlname;
        }
      $scope.settings[type].visible_uwmfields.push(uri);
      }
      if(children[i].children){
        $scope.saveVisibleFieldsSettingsRec(children[i].children, type);
      }
    }
  };

  $scope.applyVisibleFieldsSettingsRec = function(children, visible){
    for (var i = 0; i < children.length; ++i) {
      var uri;
      if(children[i].help_id == "helpmeta_37"){
        uri = children[i].xmlns+'/rights#'+children[i].xmlname;
      }else{
        uri = children[i].xmlns+'#'+children[i].xmlname;
      }

      for(var j = 0; j < visible.length; ++j) {
        if(visible[j] == uri){
          children[i].include = true;
        }
      }

      if(children[i].children){
        $scope.applyVisibleFieldsSettingsRec(children[i].children, visible);
      }
    }
  }

  $scope.checkTreeSanity = function (field, type) {
    if(field.children){
        // if parent is unchecked then all the children should be unchecked
        $scope.setIncludeRec(field.children, field.include);
    }

    // if some child is checked, then parent have to be checked
    // if no child is checked, then parent have to be unchecked
    $scope.checkParents($scope.uwmfields[type]);
  };

  $scope.checkParents = function(children){
    for (var i = 0; i < children.length; ++i) {
      if(children[i].children){
        if($scope.hasCheckedChild(children[i].children)){
          children[i].include = true;
        }else{
          children[i].include = false;
        }
        $scope.checkParents(children[i].children);
      }
    }
  };

  $scope.hasCheckedChild = function(children){
    for (var i = 0; i < children.length; ++i) {
      if(children[i].include){
        return true;
      }
      if(children[i].children){
        return $scope.hasCheckedChild(children[i].children)
      }
    }
  };

  $scope.setIncludeRec = function (children, include){
    for (var i = 0; i < children.length; ++i) {
      children[i].include = include;
      if(children[i].children){
        $scope.setIncludeRec(children[i].children, include);
      }
    }
  };

  // used to filter array of elements: if 'hidden' is set, the field will not be included in the array
    $scope.filterHidden = function(e)
    {
        return !e.hidden;
    };

  $scope.defaultAssigneeDisplayName = function() {
    if($scope.settings.project.members){
      for (var i = 0; i < $scope.settings.project.members.length; ++i) {
        if($scope.settings.project.members[i].username == $scope.settings.project.default_assignee){
          return $scope.settings.project.members[i].displayname;
        }
      }
    }
  }

    $scope.forceLoadPage = function(link) {
      $window.location = link;
    };

    $scope.hitEnterSearch = function(evt){
      if(angular.equals(evt.keyCode,13) && !(angular.equals($scope.query,null) || angular.equals($scope.query,''))){
        window.location = $('head base').attr('href')+'search?q='+encodeURIComponent($scope.query);
      }
    };

    $scope.search = function(){
      if(!(angular.equals($scope.query,null) || angular.equals($scope.query,''))){
        window.location = $('head base').attr('href')+'search?q='+encodeURIComponent($scope.query);
      }
    };

    $scope.closeAlert = function(index) {
      $scope.alerts.splice(index, 1);
    };

    $scope.signin_open = function () {

      var modalInstance = $modal.open({
            templateUrl: $('head base').attr('href')+'views/modals/loginform.html',
            controller: SigninModalCtrl
      });
    };

    $scope.init = function () {
      if($('#signin').attr('data-open') == 1){
        $scope.signin_open();
      }
    };

     $scope.setLang = function(langKey) {
            $translate.use(langKey);
         };
});

var AddMemberModalCtrl = function ($scope, $modalInstance, $http, FrontendService, promiseTracker) {

        $scope.selected_role;
        $scope.new_displayname;
        $scope.searchMembers = [];
        $scope.selected_member = {};

        $scope.refreshMembers = function(query) {

             var promise = FrontendService.getUsers(query);
             $scope.loadingTracker.addPromise(promise);
             promise.then(
                   function(response) {
                           $scope.alerts = response.data.alerts;
                           $scope.form_disabled = false;
                           console.log('refreshMembers', response.data);
                           if(response.data.accounts){
                                    if(response.data.accounts.constructor === Array){
                                            $scope.searchMembers = response.data.accounts;
                                    }
                           }
                   }
                  ,function(response) {
                           console.log('refreshMembers', response.data);
                           $scope.alerts = response.data.alerts;
                           $scope.alerts.unshift({type: 'danger', msg: "Error code "+response.status});
                           $scope.form_disabled = false;
                   }
             );
        }

        $scope.save = function (new_displayname) {

            console.log('new_displayname', new_displayname);
            console.log('selected_member', $scope.selected_member.selected.uid);
            console.log('selected_role', $scope.selected_role);

            if(!$scope.settings.project.members){
                   $scope.settings.project.members = [];
            }
            var newMember = {};
            newMember.username = $scope.selected_member.selected.uid;
            newMember.displayname = new_displayname;
            newMember.role = $scope.selected_role;
            $scope.settings.project.members.push(newMember);

            $scope.saveSettings('members');
            $modalInstance.dismiss('OK');

        }

        $scope.setMembersRole = function (new_role) {
             $scope.selected_role = new_role;
        };

        $scope.cancel = function () {
            $modalInstance.dismiss('Save');
        };

        $scope.hitEnter = function(evt){
              if(angular.equals(evt.keyCode,13)){
                  //$scope.deleteAllBookmark();
                  $modalInstance.dismiss('OK');
              }
        };

}

var EditMemberModalCtrl = function ($scope, $modalInstance, promiseTracker, username, role, displayname) {

    $scope.selected_role = role;
    $scope.new_displayname = displayname;

    $scope.setMembersRole = function (new_role) {
             console.log('role username', new_role, username);
             for (var i = 0; i < $scope.settings.project.members.length; ++i) {
                  if(typeof $scope.settings.project.members[i].username != 'undefined' ){
                         if($scope.settings.project.members[i].username == username){
                               $scope.settings.project.members[i].role = new_role;
                               $scope.selected_role = new_role;
                         }
                  }
             }
             console.log('setMembersRole', $scope.settings);
             console.log('selected_role',$scope.selected_role);
    };

    $scope.save = function (new_displayname) {

            console.log('new_displayname', new_displayname);
            for (var i = 0; i < $scope.settings.project.members.length; ++i) {
                  if(typeof $scope.settings.project.members[i].username != 'undefined' ){
                         if($scope.settings.project.members[i].username == username){
                               $scope.settings.project.members[i].displayname = new_displayname;
                         }
                  }
            }
            $scope.saveSettings('members');
            $modalInstance.dismiss('OK');
    }

    $scope.cancel = function () {
        $modalInstance.dismiss('Save');
    };

    $scope.hitEnter = function(evt){
           if(angular.equals(evt.keyCode,13)){
                  //$scope.deleteAllBookmark();
                  $modalInstance.dismiss('OK');
           }
   };
};

var SigninModalCtrl = function ($scope, $modalInstance, DirectoryService, FrontendService, promiseTracker) {

  $scope.user = {username: '', password: ''};
  $scope.alerts = [];

  $scope.baseurl = $('head base').attr('href');

  // we will use this to track running ajax requests to show spinner
  $scope.loadingTracker = promiseTracker('loadingTrackerFrontend');

  $scope.closeAlert = function(index) {
      $scope.alerts.splice(index, 1);
    };

    $scope.hitEnterSignin = function(evt){
      if(angular.equals(evt.keyCode,13)
          && !(angular.equals($scope.user.username,null) || angular.equals($scope.user.username,''))
          && !(angular.equals($scope.user.password,null) || angular.equals($scope.user.password,''))
          )
      $scope.signin();
    };

  $scope.signin = function () {

    $scope.form_disabled = true;

    var promise = DirectoryService.signin($scope.user.username, $scope.user.password);
      $scope.loadingTracker.addPromise(promise);
      promise.then(
        function(response) {
          $scope.form_disabled = false;
          $scope.alerts = response.data.alerts;
          $modalInstance.close();
          var red = $('#signin').attr('data-redirect');
          if(red){
            window.location = red;
          }else{
            window.location = $scope.baseurl;
          }
        }
        ,function(response) {
          $scope.form_disabled = false;
          $scope.alerts = response.data.alerts;
            }
        );
    return;

  };

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
};

/*
app.run(function(editableOptions) {
  editableOptions.theme = 'bs3';
});
*/


text:
require 'rails_helper'

describe CardRank, :type => :model do
  let(:card_ranks) { Card::RANKS + [Card::JOKER] }

  subject { CardRank.new(:rank => :queen) }

  it { is_expected.to validate_presence_of(:rank) }

  it { is_expected.to validate_length_of(:rank).is_at_most(10) }

  it do
    is_expected.to validate_uniqueness_of(:rank)
      .case_insensitive
  end

  it 'card ranks contains all of the ranks and "Joker"' do
    expect(CardRank.all.map(&:rank).map(&:to_sym)).to match(card_ranks)
  end

  describe '#from_rank' do
    let(:rank) { :queen }

    it 'returns the CardRank that matches the specified symbol' do
      expect(CardRank.from_rank(:rank => rank).rank).to eq rank.to_s
    end
  end
end


text:
/*
 * Created on 18/11/2006
 */
package japa.parser.ast.stmt;

import japa.parser.ast.visitor.GenericVisitor;
import japa.parser.ast.visitor.VoidVisitor;

import java.util.List;

/**
 * @author Julio Vilmar Gesser
 */
public final class TryStmt extends Statement {

    private BlockStmt tryBlock;

    private List<CatchClause> catchs;

    private BlockStmt finallyBlock;

    public TryStmt() {
    }

    public TryStmt(BlockStmt tryBlock, List<CatchClause> catchs, BlockStmt finallyBlock) {
        this.tryBlock = tryBlock;
        this.catchs = catchs;
        this.finallyBlock = finallyBlock;
    }

    public TryStmt(int beginLine, int beginColumn, int endLine, int endColumn, BlockStmt tryBlock, List<CatchClause> catchs, BlockStmt finallyBlock) {
        super(beginLine, beginColumn, endLine, endColumn);
        this.tryBlock = tryBlock;
        this.catchs = catchs;
        this.finallyBlock = finallyBlock;
    }

    @Override
    public <R, A> R accept(GenericVisitor<R, A> v, A arg) {
        return v.visit(this, arg);
    }

    @Override
    public <A> void accept(VoidVisitor<A> v, A arg) {
        v.visit(this, arg);
    }

    public List<CatchClause> getCatchs() {
        return catchs;
    }

    public BlockStmt getFinallyBlock() {
        return finallyBlock;
    }

    public BlockStmt getTryBlock() {
        return tryBlock;
    }

    public void setCatchs(List<CatchClause> catchs) {
        this.catchs = catchs;
    }

    public void setFinallyBlock(BlockStmt finallyBlock) {
        this.finallyBlock = finallyBlock;
    }

    public void setTryBlock(BlockStmt tryBlock) {
        this.tryBlock = tryBlock;
    }
}


text:
/*
 * File:   CoreSettingsResponse.cpp
 * Author: augcampos
 *
 * Created on June 27, 2013, 2:38 AM
 */

#include "asteriskcpp/manager/responses/CoreSettingsResponse.h"

namespace asteriskcpp {

    CoreSettingsResponse::CoreSettingsResponse(const std::string& responseStr) :
    ManagerResponse(responseStr) {

    }

    CoreSettingsResponse::~CoreSettingsResponse() {
    }

    const std::string& CoreSettingsResponse::getAmiVersion() const {
        return (getGetterValue(__FUNCTION__));
    }

    const std::string& CoreSettingsResponse::getAsteriskVersion() const {
        return (getGetterValue(__FUNCTION__));
    }

    const std::string& CoreSettingsResponse::getSystemName() const {
        return (getGetterValue(__FUNCTION__));
    }

    int CoreSettingsResponse::getCoreMaxCalls() const {
        return (getGetterValue<int>(__FUNCTION__));
    }

    double CoreSettingsResponse::getCoreMaxLoadAvg() const {
        return (getGetterValue<double>(__FUNCTION__));
    }

    const std::string& CoreSettingsResponse::getCoreRunUser() const {
        return (getGetterValue(__FUNCTION__));
    }

    const std::string& CoreSettingsResponse::getCoreRunGroup() const {
        return (getGetterValue(__FUNCTION__));
    }

    int CoreSettingsResponse::getCoreMaxFilehandles() const {
        return (getGetterValue<int>(__FUNCTION__));
    }

    bool CoreSettingsResponse::isCoreRealtimeEnabled() const {
        return (getGetterValue<bool>(__FUNCTION__));
    }

    bool CoreSettingsResponse::isCoreCdrEnabled() const {
        return (getGetterValue<bool>(__FUNCTION__));
    }

    bool CoreSettingsResponse::isCoreHttpEnabled() const {
        return (getGetterValue<bool>(__FUNCTION__));
    }
}


text:
#ifndef GenericBinding_h
#define GenericBinding_h

#include "BindingState.h"
#include "Document.h"
#include "Frame.h"

namespace WebCore {

inline KURL completeURL(BindingState* state, const String& relativeURL)
{
    Frame* frame = firstFrame(state);
    if (!frame)
        return KURL();
    return frame->document()->completeURL(relativeURL);
}

}

#endif // GenericBinding_h


text:
<?php
namespace App\Controller;

use App\Controller\AppController;

/**
 * Items Controller
 *
 * @property \App\Model\Table\ItemsTable $Items
 */
class CartController extends AppController
{

    /**
     * Index method
     *
     * @return \Cake\Network\Response|null
     */
    public function index()
    {

    }

    /**
     * View method
     *
     * @param string|null $id Item id.
     * @return \Cake\Network\Response|null
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function view($id = null)
    {

    }

    /**
     * Add method
     *
     * @return \Cake\Network\Response|null Redirects on successful add, renders view otherwise.
     */
    public function add()
    {
        $item = $this->Items->newEntity();
        if ($this->request->is('post')) {
            $item = $this->Items->patchEntity($item, $this->request->getData());
            if ($this->Items->save($item)) {
                $this->Flash->success(__('The item has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The item could not be saved. Please, try again.'));
        }
        $this->set(compact('item'));
        $this->set('_serialize', ['item']);
    }

    /**
     * Edit method
     *
     * @param string|null $id Item id.
     * @return \Cake\Network\Response|null Redirects on successful edit, renders view otherwise.
     * @throws \Cake\Network\Exception\NotFoundException When record not found.
     */
    public function edit($id = null)
    {
        $item = $this->Items->get($id, [
            'contain' => []
        ]);
        if ($this->request->is(['patch', 'post', 'put'])) {
            $item = $this->Items->patchEntity($item, $this->request->getData());
            if ($this->Items->save($item)) {
                $this->Flash->success(__('The item has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The item could not be saved. Please, try again.'));
        }
        $this->set(compact('item'));
        $this->set('_serialize', ['item']);
    }

    /**
     * Delete method
     *
     * @param string|null $id Item id.
     * @return \Cake\Network\Response|null Redirects to index.
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function delete($id = null)
    {
        $this->request->allowMethod(['post', 'delete']);
        $item = $this->Items->get($id);
        if ($this->Items->delete($item)) {
            $this->Flash->success(__('The item has been deleted.'));
        } else {
            $this->Flash->error(__('The item could not be deleted. Please, try again.'));
        }

        return $this->redirect(['action' => 'index']);
    }
}


text:
require 'spec_helper'

RSpec.describe IncidentManagement::ProjectIncidentManagementSetting do
  let_it_be(:project) { create(:project, :repository, create_templates: :issue) }

  describe 'Associations' do
    it { is_expected.to belong_to(:project) }
  end

  describe 'Validations' do
    describe 'validate issue_template_exists' do
      subject { build(:project_incident_management_setting, project: project) }

      context 'with create_issue enabled' do
        before do
          subject.create_issue = true
        end

        context 'with valid issue_template_key' do
          before do
            subject.issue_template_key = 'bug'
          end

          it { is_expected.to be_valid }
        end

        context 'with empty issue_template_key' do
          before do
            subject.issue_template_key = ''
          end

          it { is_expected.to be_valid }
        end

        context 'with nil issue_template_key' do
          before do
            subject.issue_template_key = nil
          end

          it { is_expected.to be_valid }
        end

        context 'with invalid issue_template_key' do
          before do
            subject.issue_template_key = 'unknown'
          end

          it { is_expected.to be_invalid }

          it 'returns error' do
            subject.valid?

            expect(subject.errors[:issue_template_key]).to eq(['not found'])
          end
        end
      end

      context 'with create_issue disabled' do
        before do
          subject.create_issue = false
        end

        context 'with unknown issue_template_key' do
          before do
            subject.issue_template_key = 'unknown'
          end

          it { is_expected.to be_valid }
        end
      end
    end
  end

  describe '#issue_template_content' do
    subject { build(:project_incident_management_setting, project: project) }

    shared_examples 'no content' do
      it 'returns no content' do
        expect(subject.issue_template_content).to be_nil
      end
    end

    context 'with valid issue_template_key' do
      before do
        subject.issue_template_key = 'bug'
      end

      it 'returns issue content' do
        expect(subject.issue_template_content).to eq('something valid')
      end
    end

    context 'with unknown issue_template_key' do
      before do
        subject.issue_template_key = 'unknown'
      end

      it_behaves_like 'no content'
    end

    context 'without issue_template_key' do
      before do
        subject.issue_template_key = nil
      end

      it_behaves_like 'no content'
    end
  end

  describe '#pagerduty_token' do
    let(:active) { true }

    subject do
      create(:project_incident_management_setting, project: project, pagerduty_active: active, pagerduty_token: token)
    end

    context 'when token already set' do
      let(:token) { SecureRandom.hex }

      it 'reads the token' do
        expect(subject.pagerduty_token).to eq(token)
        expect(subject.encrypted_pagerduty_token).not_to be_nil
        expect(subject.encrypted_pagerduty_token_iv).not_to be_nil
      end
    end

    context 'when not set' do
      let(:token) { nil }

      context 'when PagerDuty webhook is active' do
        it 'generates a token before validation' do
          expect(subject).to be_valid
          expect(subject.pagerduty_token).to match(/\A\h{32}\z/)
        end
      end

      context 'when PagerDuty webhook is not active' do
        let(:active) { false }

        it 'does not generate a token before validation' do
          expect(subject).to be_valid
          expect(subject.pagerduty_token).to be_nil
        end
      end
    end
  end
end


text:
require 'bcrypt'
module Blogr
  class User < ActiveRecord::Base
    set_table_name "blogr_users"

    has_many :posts, :class_name => "Blogr::Post"

    # attr_accessible :name, :email, :password, :password_confirmation

    attr_accessor :password
    before_save :encrypt_password

    validates_confirmation_of :password
    validates_presence_of     :password, :on => :create
    validates_presence_of     :name

    validates :email,   :presence => true,
              :length => {:minimum => 3, :maximum => 254},
              :uniqueness => true,
              :format => {:with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i}

    def self.authenticate(email, password)
      user = find_by_email(email)
      if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
        user
      else
        nil
      end
    end

    def encrypt_password
      if password.present?
        self.password_salt = BCrypt::Engine.generate_salt
        self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
      end
    end
  end
end


text:
package pl.grzeslowski.jsupla.protocoljava.impl.parsers.sc;

import org.junit.Test;
import org.mockito.BDDMockito;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import pl.grzeslowski.jsupla.protocol.api.structs.sc.SuplaChannelGroupRelation;
import pl.grzeslowski.jsupla.protocol.api.structs.sc.SuplaChannelGroupRelationPack;
import pl.grzeslowski.jsupla.protocoljava.api.entities.sc.ChannelGroupRelation;
import pl.grzeslowski.jsupla.protocoljava.api.entities.sc.ChannelGroupRelationPack;
import pl.grzeslowski.jsupla.protocoljava.api.parsers.Parser;
import pl.grzeslowski.jsupla.protocoljava.api.parsers.sc.ChannelGroupRelationParser;
import pl.grzeslowski.jsupla.protocoljava.impl.parsers.AbstractParserTest;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.verify;
import static pl.grzeslowski.jsupla.protocol.common.RandomSupla.RANDOM_SUPLA;

public class ChannelGroupRelationPackParserImplTest
    extends AbstractParserTest<ChannelGroupRelationPack, SuplaChannelGroupRelationPack> {
    @InjectMocks
    ChannelGroupRelationPackParserImpl parser;
    @Mock
    ChannelGroupRelationParser channelGroupRelationParser;

    @Override
    protected SuplaChannelGroupRelationPack given() {
        BDDMockito.given(channelGroupRelationParser.parse(any()))
                .willReturn(RANDOM_SUPLA.nextObject(ChannelGroupRelation.class));
        return super.given();
    }

    @Override
    protected void then(ChannelGroupRelationPack entity, SuplaChannelGroupRelationPack supla) {
        assertThat(entity.getTotalLeft()).isEqualTo(supla.totalLeft);
        assertThat(entity.getItems().size()).isEqualTo(supla.count);
        for (SuplaChannelGroupRelation item : supla.items) {
            verify(channelGroupRelationParser).parse(item);
        }
    }

    @Override
    protected Parser<ChannelGroupRelationPack, SuplaChannelGroupRelationPack> parser() {
        return parser;
    }

    @Override
    protected Class<SuplaChannelGroupRelationPack> classToTest() {
        return SuplaChannelGroupRelationPack.class;
    }

    @Test(expected = NullPointerException.class)
    public void shouldThrowNullPointerExceptionOnNullChannelGroupRelationParser() {
        new ChannelGroupRelationPackParserImpl(null);
    }
}


text:
from msrest.serialization import Model

class Incident(Model):
    """An alert incident indicates the activation status of an alert rule.

    Variables are only populated by the server, and will be ignored when
    sending a request.

    :ivar name: Incident name.
    :vartype name: str
    :ivar rule_name: Rule name that is associated with the incident.
    :vartype rule_name: str
    :ivar is_active: A boolean to indicate whether the incident is active or
     resolved.
    :vartype is_active: bool
    :ivar activated_time: The time at which the incident was activated in
     ISO8601 format.
    :vartype activated_time: datetime
    :ivar resolved_time: The time at which the incident was resolved in
     ISO8601 format. If null, it means the incident is still active.
    :vartype resolved_time: datetime
    """

    _validation = {
        'name': {'readonly': True},
        'rule_name': {'readonly': True},
        'is_active': {'readonly': True},
        'activated_time': {'readonly': True},
        'resolved_time': {'readonly': True},
    }

    _attribute_map = {
        'name': {'key': 'name', 'type': 'str'},
        'rule_name': {'key': 'ruleName', 'type': 'str'},
        'is_active': {'key': 'isActive', 'type': 'bool'},
        'activated_time': {'key': 'activatedTime', 'type': 'iso-8601'},
        'resolved_time': {'key': 'resolvedTime', 'type': 'iso-8601'},
    }

    def __init__(self):
        self.name = None
        self.rule_name = None
        self.is_active = None
        self.activated_time = None
        self.resolved_time = None


text:
<?xml version="1.0" encoding="utf-8"?>
<PRONOM-Report xmlns="http://pronom.nationalarchives.gov.uk">
  <report_format_detail>
    <FileFormat>
      <FormatID>2063</FormatID>
      <FormatName>ZFO (Proof of Delivery) File</FormatName>
      <FormatVersion>
      </FormatVersion>
      <FormatAliases>
      </FormatAliases>
      <FormatFamilies>
      </FormatFamilies>
      <FormatTypes>Aggregate</FormatTypes>
      <FormatDisclosure>
      </FormatDisclosure>
      <FormatDescription>This variant of ZFO file is container for proof of delivery of data mailbox messages provided by Česká pošta, s.p. in three versions: 1. proof of delivery; 2. confirmation of delivery; 3. delivery failure. ZFO file is a ZIP archive file  (PKCS #7 Cryptographic Message File) composing of the layout structure using XML elements. The whole structure is always embedded into a digital signature represented by XML elements of the XML Signature standard.</FormatDescription>
      <BinaryFileFormat>
      </BinaryFileFormat>
      <ByteOrders>
      </ByteOrders>
      <ReleaseDate>
      </ReleaseDate>
      <WithdrawnDate>
      </WithdrawnDate>
      <ProvenanceSourceID>242</ProvenanceSourceID>
      <ProvenanceName>The National Archives of the Czech Republic / The National Archives of the Czech Republic</ProvenanceName>
      <ProvenanceSourceDate>18 Jan 2020</ProvenanceSourceDate>
      <ProvenanceDescription>
      </ProvenanceDescription>
      <LastUpdatedDate>18 Jan 2020</LastUpdatedDate>
      <FormatNote>http://isds.czechpoint.cz/v20/delivery</FormatNote>
      <FormatRisk>
      </FormatRisk>
      <TechnicalEnvironment>
      </TechnicalEnvironment>
      <FileFormatIdentifier>
        <Identifier>application/vnd.software602.filler.form-xml-zip</Identifier>
        <IdentifierType>MIME</IdentifierType>
      </FileFormatIdentifier>
      <FileFormatIdentifier>
        <Identifier>fmt/1245</Identifier>
        <IdentifierType>PUID</IdentifierType>
      </FileFormatIdentifier>
      <ExternalSignature>
        <ExternalSignatureID>2301</ExternalSignatureID>
        <Signature>zfo</Signature>
        <SignatureType>File extension</SignatureType>
      </ExternalSignature>
      <InternalSignature>
        <SignatureID>1622</SignatureID>
        <SignatureName>ZFO (Proof of Delivery) File</SignatureName>
        <SignatureNote>Magic bytes: http://isds.czechpoint.cz/v20/delivery</SignatureNote>
        <ByteSequence>
          <ByteSequenceID>1893</ByteSequenceID>
          <PositionType>Absolute from BOF</PositionType>
          <Offset>0</Offset>
          <MaxOffset>20500</MaxOffset>
          <IndirectOffsetLocation>
          </IndirectOffsetLocation>
          <IndirectOffsetLength>
          </IndirectOffsetLength>
          <Endianness>
          </Endianness>
          <ByteSequenceValue>687474703A2F2F697364732E637A656368706F696E742E637A2F7632302F64656C6976657279</ByteSequenceValue>
        </ByteSequence>
      </InternalSignature>
      <RelatedFormat>
        <RelationshipType>Has priority over</RelationshipType>
        <RelatedFormatID>1469</RelatedFormatID>
        <RelatedFormatName>PKCS #7 Crytographic Message File</RelatedFormatName>
        <RelatedFormatVersion>
        </RelatedFormatVersion>
      </RelatedFormat>
    </FileFormat>
    <SearchCriteria>Criteria</SearchCriteria>
  </report_format_detail>
</PRONOM-Report>