text:
<?php
/**
 * @package go\DB
 */

namespace go\Tests\DB\Real\Mysqlold;

use go\Tests\DB\Real\Base;

class IteratorsTest extends Base
{
    /**
     * {@inheritdoc}
     */
    protected $adapter = 'mysqlold';

    /**
     * {@inheritdoc}
     */
    protected $reqExt = 'mysql';

    public function testIterators()
    {
        $db = $this->createDB(__DIR__.'/dump.sql');
        $sql = 'SELECT `id`,`num` FROM `godbtest` ORDER BY `id` ASC';
        $assoc = $db($sql)->assoc();
        $it = $db($sql)->iassoc();
        $this->assertSame($assoc, iterator_to_array($it));
        $this->assertSame($db($sql)->numerics(), iterator_to_array($db($sql)->inumerics()));
        $this->assertSame($assoc, iterator_to_array($it));
        $this->assertSame($db($sql)->col(), iterator_to_array($db($sql)->icol()));
        $this->assertSame($db($sql)->vars(), iterator_to_array($db($sql)->ivars()));
        $this->assertSame($db($sql)->assoc(), iterator_to_array($db($sql)));
        $this->assertCount(5, $db($sql)->iassoc());
        $this->assertCount(5, $db($sql));
        $this->assertSame($db($sql)->assoc('id'), iterator_to_array($db($sql)->iassoc('id')));
    }
}


text:
package vip

import (
	"context"
	"testing"

	. "github.com/smartystreets/goconvey/convey"
)

// go test  -test.v -test.run TestServiceCouponsForPanel
func TestServiceCouponsForPanel(t *testing.T) {
	Convey("TestServiceCouponsForPanel", t, func() {
		res, err := s.CouponsForPanel(context.TODO(), int64(1), int64(96), "pc")
		t.Logf("%v", res)
		So(err, ShouldBeNil)
	})
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef otbIkonosImageMetadataInterface_h
#define otbIkonosImageMetadataInterface_h

#include "otbOpticalImageMetadataInterface.h"

namespace otb
{
/** \class IkonosImageMetadataInterface
 *
 * \brief Creation of an "otb" IkonosImageMetadataInterface that gets metadata.
 *
 *
 * \ingroup OTBMetadata
 */
class OTBMetadata_EXPORT IkonosImageMetadataInterface : public OpticalImageMetadataInterface
{
public:
  typedef IkonosImageMetadataInterface  Self;
  typedef ImageMetadataInterfaceBase    Superclass;
  typedef itk::SmartPointer<Self>       Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  /** Method for creation through the object factory. */
  itkNewMacro(Self);

  /** Run-time type information (and related methods). */
  itkTypeMacro(IkonosImageMetadataInterface, ImageMetadataInterfaceBase);

  typedef Superclass::ImageType                ImageType;
  typedef Superclass::MetaDataDictionaryType   MetaDataDictionaryType;
  typedef Superclass::VectorType               VectorType;
  typedef Superclass::VariableLengthVectorType VariableLengthVectorType;

  void Parse(ImageMetadata &) override;

protected:
  IkonosImageMetadataInterface() = default;
  ~IkonosImageMetadataInterface() override = default;

private:
  IkonosImageMetadataInterface(const Self&) = delete;
  void operator=(const Self&) = delete;

  void FetchProductionDate(const std::string & productionDate, ImageMetadata &imd);

  void FetchAcquisitionDate(const std::string & acquisitionDate,
                            const std::string & acquisitionTime,
                            ImageMetadata &imd);

  /** Vector that contains the filter function value in 6S format (step of 0.0025 micro m).
     * There values a computed by 6S. */
  void FetchSpectralSensitivity(const std::string & bandName, ImageMetadata &imd);

};

} // end namespace otb

#endif


text:
package com.intellij.ide.ui;

import com.intellij.ide.IdeBundle;
import com.intellij.ide.ui.laf.darcula.DarculaInstaller;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ServiceKt;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.colors.ex.DefaultColorSchemesManager;
import com.intellij.openapi.editor.colors.impl.EditorColorsManagerImpl;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import com.intellij.openapi.options.BaseConfigurable;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.wm.ex.WindowManagerEx;
import com.intellij.ui.FontComboBox;
import com.intellij.ui.ListCellRendererWrapper;
import com.intellij.ui.components.JBCheckBox;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import sun.swing.SwingUtilities2;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Dictionary;
import java.util.Hashtable;

/**
 * @author Eugene Belyaev
 */
public class AppearanceConfigurable extends BaseConfigurable implements SearchableConfigurable {
  private static final Logger LOG = Logger.getInstance("#com.intellij.ide.ui.AppearanceConfigurable");

  private MyComponent myComponent;

  public AppearanceConfigurable() {
    myComponent = new MyComponent();
  }

  private void initComponent() {
    if (myComponent == null)  {
      myComponent = new MyComponent();
    }
  }

  @Override
  public String getDisplayName() {
    return IdeBundle.message("title.appearance");
  }

  @Override
  @NotNull
  public String getId() {
    //noinspection ConstantConditions
    return getHelpTopic();
  }

  @SuppressWarnings("unchecked")
  @Override
  public JComponent createComponent() {
    UISettings settings = UISettings.getInstance();

    initComponent();

    myComponent.myFontSizeCombo.setModel(new DefaultComboBoxModel(UIUtil.getStandardFontSizes()));
    myComponent.myPresentationModeFontSize.setModel(new DefaultComboBoxModel(UIUtil.getStandardFontSizes()));
    myComponent.myFontSizeCombo.setEditable(true);
    myComponent.myPresentationModeFontSize.setEditable(true);

    myComponent.myLafComboBox.setModel(new DefaultComboBoxModel(LafManager.getInstance().getInstalledLookAndFeels()));
    myComponent.myLafComboBox.setRenderer(new LafComboBoxRenderer());

    myComponent.myAntialiasingInIDE.setModel(new DefaultComboBoxModel(AntialiasingType.values()));
    myComponent.myAntialiasingInEditor.setModel(new DefaultComboBoxModel(AntialiasingType.values()));

    myComponent.myAntialiasingInIDE.setSelectedItem(settings.IDE_AA_TYPE);
    myComponent.myAntialiasingInEditor.setSelectedItem(settings.EDITOR_AA_TYPE);
    myComponent.myAntialiasingInIDE.setRenderer(new AAListCellRenderer(false));
    myComponent.myAntialiasingInEditor.setRenderer(new AAListCellRenderer(true));

    @SuppressWarnings("UseOfObsoleteCollectionType") Dictionary<Integer, JComponent> delayDictionary = new Hashtable<>();
    delayDictionary.put(new Integer(0), new JLabel("0"));
    delayDictionary.put(new Integer(1200), new JLabel("1200"));
    //delayDictionary.put(new Integer(2400), new JLabel("2400"));
    myComponent.myInitialTooltipDelaySlider.setLabelTable(delayDictionary);
    UIUtil.setSliderIsFilled(myComponent.myInitialTooltipDelaySlider, Boolean.TRUE);
    myComponent.myInitialTooltipDelaySlider.setMinimum(0);
    myComponent.myInitialTooltipDelaySlider.setMaximum(1200);
    myComponent.myInitialTooltipDelaySlider.setPaintLabels(true);
    myComponent.myInitialTooltipDelaySlider.setPaintTicks(true);
    myComponent.myInitialTooltipDelaySlider.setPaintTrack(true);
    myComponent.myInitialTooltipDelaySlider.setMajorTickSpacing(1200);
    myComponent.myInitialTooltipDelaySlider.setMinorTickSpacing(100);

    myComponent.myEnableAlphaModeCheckBox.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        boolean state = myComponent.myEnableAlphaModeCheckBox.isSelected();
        myComponent.myAlphaModeDelayTextField.setEnabled(state);
        myComponent.myAlphaModeRatioSlider.setEnabled(state);
      }
    });

    myComponent.myAlphaModeRatioSlider.setSize(100, 50);
    @SuppressWarnings({"UseOfObsoleteCollectionType"})
    Dictionary<Integer, JComponent> dictionary = new Hashtable<>();
    dictionary.put(new Integer(0), new JLabel("0%"));
    dictionary.put(new Integer(50), new JLabel("50%"));
    dictionary.put(new Integer(100), new JLabel("100%"));
    myComponent.myAlphaModeRatioSlider.setLabelTable(dictionary);
    UIUtil.setSliderIsFilled(myComponent.myAlphaModeRatioSlider, Boolean.TRUE);
    myComponent.myAlphaModeRatioSlider.setPaintLabels(true);
    myComponent.myAlphaModeRatioSlider.setPaintTicks(true);
    myComponent.myAlphaModeRatioSlider.setPaintTrack(true);
    myComponent.myAlphaModeRatioSlider.setMajorTickSpacing(50);
    myComponent.myAlphaModeRatioSlider.setMinorTickSpacing(10);
    myComponent.myAlphaModeRatioSlider.addChangeListener(new ChangeListener() {
      @Override
      public void stateChanged(ChangeEvent e) {
        myComponent.myAlphaModeRatioSlider.setToolTipText(myComponent.myAlphaModeRatioSlider.getValue() + "%");
      }
    });

    myComponent.myTransparencyPanel.setVisible(WindowManagerEx.getInstanceEx().isAlphaModeSupported());

    return myComponent.myPanel;
  }

  @Override
  public void apply() {
    initComponent();
    UISettings settings = UISettings.getInstance();
    int _fontSize = getIntValue(myComponent.myFontSizeCombo, settings.FONT_SIZE);
    int _presentationFontSize = getIntValue(myComponent.myPresentationModeFontSize, settings.PRESENTATION_MODE_FONT_SIZE);
    boolean update = false;
    boolean shouldUpdateUI = false;
    String _fontFace = myComponent.myFontCombo.getFontName();
    LafManager lafManager = LafManager.getInstance();
    if (_fontSize != settings.FONT_SIZE || !Comparing.equal(settings.FONT_FACE, _fontFace)) {
      settings.FONT_SIZE = _fontSize;
      settings.FONT_FACE = _fontFace;
      shouldUpdateUI = true;
      update = true;
    }

    if (_presentationFontSize != settings.PRESENTATION_MODE_FONT_SIZE) {
      settings.PRESENTATION_MODE_FONT_SIZE = _presentationFontSize;
      shouldUpdateUI = true;
    }

    if (myComponent.myAntialiasingInIDE.getSelectedItem() != settings.IDE_AA_TYPE) {
      settings.IDE_AA_TYPE = (AntialiasingType)myComponent.myAntialiasingInIDE.getSelectedItem();
      for (Window w : Window.getWindows()) {
        for (JComponent c : UIUtil.uiTraverser(w).filter(JComponent.class)) {
          c.putClientProperty(SwingUtilities2.AA_TEXT_PROPERTY_KEY, AntialiasingType.getAAHintForSwingComponent());
        }
      }
      shouldUpdateUI = true;
    }

    if (myComponent.myAntialiasingInEditor.getSelectedItem() != settings.EDITOR_AA_TYPE) {
      settings.EDITOR_AA_TYPE = (AntialiasingType)myComponent.myAntialiasingInEditor.getSelectedItem();
      shouldUpdateUI = true;
    }

    settings.ANIMATE_WINDOWS = myComponent.myAnimateWindowsCheckBox.isSelected();
    update |= settings.SHOW_TOOL_WINDOW_NUMBERS != myComponent.myWindowShortcutsCheckBox.isSelected();
    settings.SHOW_TOOL_WINDOW_NUMBERS = myComponent.myWindowShortcutsCheckBox.isSelected();
    update |= settings.HIDE_TOOL_STRIPES != !myComponent.myShowToolStripesCheckBox.isSelected();
    settings.HIDE_TOOL_STRIPES = !myComponent.myShowToolStripesCheckBox.isSelected();
    update |= settings.SHOW_ICONS_IN_MENUS != myComponent.myCbDisplayIconsInMenu.isSelected();
    settings.SHOW_ICONS_IN_MENUS = myComponent.myCbDisplayIconsInMenu.isSelected();
    update |= settings.SHOW_MEMORY_INDICATOR != myComponent.myShowMemoryIndicatorCheckBox.isSelected();
    settings.SHOW_MEMORY_INDICATOR = myComponent.myShowMemoryIndicatorCheckBox.isSelected();
    update |= settings.ALLOW_MERGE_BUTTONS != myComponent.myAllowMergeButtons.isSelected();
    settings.ALLOW_MERGE_BUTTONS = myComponent.myAllowMergeButtons.isSelected();
    update |= settings.CYCLE_SCROLLING != myComponent.myCycleScrollingCheckBox.isSelected();
    settings.CYCLE_SCROLLING = myComponent.myCycleScrollingCheckBox.isSelected();
    if (settings.OVERRIDE_NONIDEA_LAF_FONTS != myComponent.myOverrideLAFFonts.isSelected()) {
      shouldUpdateUI = true;
      update = true;
    }
    settings.OVERRIDE_NONIDEA_LAF_FONTS = myComponent.myOverrideLAFFonts.isSelected();
    settings.MOVE_MOUSE_ON_DEFAULT_BUTTON = myComponent.myMoveMouseOnDefaultButtonCheckBox.isSelected();
    settings.HIDE_NAVIGATION_ON_FOCUS_LOSS = myComponent.myHideNavigationPopupsCheckBox.isSelected();
    settings.DND_WITH_PRESSED_ALT_ONLY = myComponent.myAltDNDCheckBox.isSelected();

    update |= settings.DISABLE_MNEMONICS != myComponent.myDisableMnemonics.isSelected();
    settings.DISABLE_MNEMONICS = myComponent.myDisableMnemonics.isSelected();

    update |= settings.USE_SMALL_LABELS_ON_TABS != myComponent.myUseSmallLabelsOnTabs.isSelected();
    settings.USE_SMALL_LABELS_ON_TABS = myComponent.myUseSmallLabelsOnTabs.isSelected();

    update |= settings.WIDESCREEN_SUPPORT != myComponent.myWidescreenLayoutCheckBox.isSelected();
    settings.WIDESCREEN_SUPPORT = myComponent.myWidescreenLayoutCheckBox.isSelected();

    update |= settings.LEFT_HORIZONTAL_SPLIT != myComponent.myLeftLayoutCheckBox.isSelected();
    settings.LEFT_HORIZONTAL_SPLIT = myComponent.myLeftLayoutCheckBox.isSelected();

    update |= settings.RIGHT_HORIZONTAL_SPLIT != myComponent.myRightLayoutCheckBox.isSelected();
    settings.RIGHT_HORIZONTAL_SPLIT = myComponent.myRightLayoutCheckBox.isSelected();

    update |= settings.NAVIGATE_TO_PREVIEW != (myComponent.myNavigateToPreviewCheckBox.isVisible() && myComponent.myNavigateToPreviewCheckBox.isSelected());
    settings.NAVIGATE_TO_PREVIEW = myComponent.myNavigateToPreviewCheckBox.isSelected();

    ColorBlindness blindness = myComponent.myColorBlindnessPanel.getColorBlindness();
    boolean updateEditorScheme = false;
    if (settings.COLOR_BLINDNESS != blindness) {
      settings.COLOR_BLINDNESS = blindness;
      update = true;
      ServiceKt.getStateStore(ApplicationManager.getApplication()).reloadState(DefaultColorSchemesManager.class);
      updateEditorScheme = true;
    }

    update |= settings.DISABLE_MNEMONICS_IN_CONTROLS != myComponent.myDisableMnemonicInControlsCheckBox.isSelected();
    settings.DISABLE_MNEMONICS_IN_CONTROLS = myComponent.myDisableMnemonicInControlsCheckBox.isSelected();

    update |= settings.SHOW_ICONS_IN_QUICK_NAVIGATION != myComponent.myHideIconsInQuickNavigation.isSelected();
    settings.SHOW_ICONS_IN_QUICK_NAVIGATION = myComponent.myHideIconsInQuickNavigation.isSelected();

    if (!Comparing.equal(myComponent.myLafComboBox.getSelectedItem(), lafManager.getCurrentLookAndFeel())) {
      final UIManager.LookAndFeelInfo lafInfo = (UIManager.LookAndFeelInfo)myComponent.myLafComboBox.getSelectedItem();
      if (lafManager.checkLookAndFeel(lafInfo)) {
        update = shouldUpdateUI = true;
        final boolean wasDarcula = UIUtil.isUnderDarcula();
        lafManager.setCurrentLookAndFeel(lafInfo);
        //noinspection SSBasedInspection
        SwingUtilities.invokeLater(() -> {
          if (UIUtil.isUnderDarcula()) {
            DarculaInstaller.install();
          } else if (wasDarcula) {
            DarculaInstaller.uninstall();
          }
        });
      }
    }

    if (shouldUpdateUI) {
      lafManager.updateUI();
    }

    if (WindowManagerEx.getInstanceEx().isAlphaModeSupported()) {
      int delay = -1;
      try {
        delay = Integer.parseInt(myComponent.myAlphaModeDelayTextField.getText());
      }
      catch (NumberFormatException ignored) {
      }
      float ratio = myComponent.myAlphaModeRatioSlider.getValue() / 100f;
      if (myComponent.myEnableAlphaModeCheckBox.isSelected() != settings.ENABLE_ALPHA_MODE ||
          delay != -1 && delay != settings.ALPHA_MODE_DELAY || ratio != settings.ALPHA_MODE_RATIO) {
        update = true;
        settings.ENABLE_ALPHA_MODE = myComponent.myEnableAlphaModeCheckBox.isSelected();
        settings.ALPHA_MODE_DELAY = delay;
        settings.ALPHA_MODE_RATIO = ratio;
      }
    }
    int tooltipDelay = Math.min(myComponent.myInitialTooltipDelaySlider.getValue(), 5000);
    if (tooltipDelay != Registry.intValue("ide.tooltip.initialDelay")) {
      update = true;
      Registry.get("ide.tooltip.initialDelay").setValue(tooltipDelay);
    }

    if (update) {
      settings.fireUISettingsChanged();
    }
    myComponent.updateCombo();

    EditorUtil.reinitSettings();

    if (updateEditorScheme) {
      EditorColorsManagerImpl.schemeChangedOrSwitched();
    }
  }

  private static int getIntValue(JComboBox combo, int defaultValue) {
    String temp = (String)combo.getEditor().getItem();
    int value = -1;
    if (temp != null && temp.trim().length() > 0) {
      try {
        value = Integer.parseInt(temp);
      }
      catch (NumberFormatException ignore) {
      }
      if (value <= 0) {
        value = defaultValue;
      }
    }
    else {
      value = defaultValue;
    }
    return value;
  }

  @Override
  public void reset() {
    initComponent();
    UISettings settings = UISettings.getInstance();

    myComponent.myFontCombo.setFontName(settings.FONT_FACE);

    // todo migrate
    //myComponent.myAntialiasingCheckBox.setSelected(settings.ANTIALIASING_IN_IDE);
    //myComponent.myLCDRenderingScopeCombo.setSelectedItem(settings.LCD_RENDERING_SCOPE);

    myComponent.myAntialiasingInIDE.setSelectedItem(settings.IDE_AA_TYPE);
    myComponent.myAntialiasingInEditor.setSelectedItem(settings.EDITOR_AA_TYPE);

    myComponent.myFontSizeCombo.setSelectedItem(Integer.toString(settings.FONT_SIZE));
    myComponent.myPresentationModeFontSize.setSelectedItem(Integer.toString(settings.PRESENTATION_MODE_FONT_SIZE));
    myComponent.myAnimateWindowsCheckBox.setSelected(settings.ANIMATE_WINDOWS);
    myComponent.myWindowShortcutsCheckBox.setSelected(settings.SHOW_TOOL_WINDOW_NUMBERS);
    myComponent.myShowToolStripesCheckBox.setSelected(!settings.HIDE_TOOL_STRIPES);
    myComponent.myCbDisplayIconsInMenu.setSelected(settings.SHOW_ICONS_IN_MENUS);
    myComponent.myShowMemoryIndicatorCheckBox.setSelected(settings.SHOW_MEMORY_INDICATOR);
    myComponent.myAllowMergeButtons.setSelected(settings.ALLOW_MERGE_BUTTONS);
    myComponent.myCycleScrollingCheckBox.setSelected(settings.CYCLE_SCROLLING);

    myComponent.myHideIconsInQuickNavigation.setSelected(settings.SHOW_ICONS_IN_QUICK_NAVIGATION);
    myComponent.myMoveMouseOnDefaultButtonCheckBox.setSelected(settings.MOVE_MOUSE_ON_DEFAULT_BUTTON);
    myComponent.myHideNavigationPopupsCheckBox.setSelected(settings.HIDE_NAVIGATION_ON_FOCUS_LOSS);
    myComponent.myAltDNDCheckBox.setSelected(settings.DND_WITH_PRESSED_ALT_ONLY);
    myComponent.myLafComboBox.setSelectedItem(LafManager.getInstance().getCurrentLookAndFeel());
    myComponent.myOverrideLAFFonts.setSelected(settings.OVERRIDE_NONIDEA_LAF_FONTS);
    myComponent.myDisableMnemonics.setSelected(settings.DISABLE_MNEMONICS);
    myComponent.myUseSmallLabelsOnTabs.setSelected(settings.USE_SMALL_LABELS_ON_TABS);
    myComponent.myWidescreenLayoutCheckBox.setSelected(settings.WIDESCREEN_SUPPORT);
    myComponent.myLeftLayoutCheckBox.setSelected(settings.LEFT_HORIZONTAL_SPLIT);
    myComponent.myRightLayoutCheckBox.setSelected(settings.RIGHT_HORIZONTAL_SPLIT);
    myComponent.myNavigateToPreviewCheckBox.setSelected(settings.NAVIGATE_TO_PREVIEW);
    myComponent.myNavigateToPreviewCheckBox.setVisible(false);//disabled for a while
    myComponent.myColorBlindnessPanel.setColorBlindness(settings.COLOR_BLINDNESS);
    myComponent.myDisableMnemonicInControlsCheckBox.setSelected(settings.DISABLE_MNEMONICS_IN_CONTROLS);

    boolean alphaModeEnabled = WindowManagerEx.getInstanceEx().isAlphaModeSupported();
    if (alphaModeEnabled) {
      myComponent.myEnableAlphaModeCheckBox.setSelected(settings.ENABLE_ALPHA_MODE);
    }
    else {
      myComponent.myEnableAlphaModeCheckBox.setSelected(false);
    }
    myComponent.myEnableAlphaModeCheckBox.setEnabled(alphaModeEnabled);
    myComponent.myAlphaModeDelayTextField.setText(Integer.toString(settings.ALPHA_MODE_DELAY));
    myComponent.myAlphaModeDelayTextField.setEnabled(alphaModeEnabled && settings.ENABLE_ALPHA_MODE);
    int ratio = (int)(settings.ALPHA_MODE_RATIO * 100f);
    myComponent.myAlphaModeRatioSlider.setValue(ratio);
    myComponent.myAlphaModeRatioSlider.setToolTipText(ratio + "%");
    myComponent.myAlphaModeRatioSlider.setEnabled(alphaModeEnabled && settings.ENABLE_ALPHA_MODE);
    myComponent.myInitialTooltipDelaySlider.setValue(Registry.intValue("ide.tooltip.initialDelay"));
    myComponent.updateCombo();
  }

  public static String antialiasingTypeInEditorAsString (boolean antialiased, LCDRenderingScope scope) {
    if (!antialiased) return "No antialiasing";
    switch (scope) {
      case IDE:
        return "Subpixel";
      case OFF:
      case EXCLUDING_EDITOR:
        return "Greyscale";
    }
    LOG.info("Wrong antialiasing state");
    return "No antialiasing";
  }

  @Override
  public boolean isModified() {
    initComponent();
    UISettings settings = UISettings.getInstance();

    boolean isModified = false;
    isModified |= !Comparing.equal(myComponent.myFontCombo.getFontName(), settings.FONT_FACE);
    isModified |= !Comparing.equal(myComponent.myFontSizeCombo.getEditor().getItem(), Integer.toString(settings.FONT_SIZE));

    isModified |= myComponent.myAntialiasingInIDE.getSelectedItem() != settings.IDE_AA_TYPE;
    isModified |= myComponent.myAntialiasingInEditor.getSelectedItem() != settings.EDITOR_AA_TYPE;

    isModified |= myComponent.myAnimateWindowsCheckBox.isSelected() != settings.ANIMATE_WINDOWS;
    isModified |= myComponent.myWindowShortcutsCheckBox.isSelected() != settings.SHOW_TOOL_WINDOW_NUMBERS;
    isModified |= myComponent.myShowToolStripesCheckBox.isSelected() == settings.HIDE_TOOL_STRIPES;
    isModified |= myComponent.myCbDisplayIconsInMenu.isSelected() != settings.SHOW_ICONS_IN_MENUS;
    isModified |= myComponent.myShowMemoryIndicatorCheckBox.isSelected() != settings.SHOW_MEMORY_INDICATOR;
    isModified |= myComponent.myAllowMergeButtons.isSelected() != settings.ALLOW_MERGE_BUTTONS;
    isModified |= myComponent.myCycleScrollingCheckBox.isSelected() != settings.CYCLE_SCROLLING;

    isModified |= myComponent.myOverrideLAFFonts.isSelected() != settings.OVERRIDE_NONIDEA_LAF_FONTS;

    isModified |= myComponent.myDisableMnemonics.isSelected() != settings.DISABLE_MNEMONICS;
    isModified |= myComponent.myDisableMnemonicInControlsCheckBox.isSelected() != settings.DISABLE_MNEMONICS_IN_CONTROLS;

    isModified |= myComponent.myUseSmallLabelsOnTabs.isSelected() != settings.USE_SMALL_LABELS_ON_TABS;
    isModified |= myComponent.myWidescreenLayoutCheckBox.isSelected() != settings.WIDESCREEN_SUPPORT;
    isModified |= myComponent.myLeftLayoutCheckBox.isSelected() != settings.LEFT_HORIZONTAL_SPLIT;
    isModified |= myComponent.myRightLayoutCheckBox.isSelected() != settings.RIGHT_HORIZONTAL_SPLIT;
    isModified |= myComponent.myNavigateToPreviewCheckBox.isSelected() != settings.NAVIGATE_TO_PREVIEW;
    isModified |= myComponent.myColorBlindnessPanel.getColorBlindness() != settings.COLOR_BLINDNESS;

    isModified |= myComponent.myHideIconsInQuickNavigation.isSelected() != settings.SHOW_ICONS_IN_QUICK_NAVIGATION;

    isModified |= !Comparing.equal(myComponent.myPresentationModeFontSize.getEditor().getItem(), Integer.toString(settings.PRESENTATION_MODE_FONT_SIZE));

    isModified |= myComponent.myMoveMouseOnDefaultButtonCheckBox.isSelected() != settings.MOVE_MOUSE_ON_DEFAULT_BUTTON;
    isModified |= myComponent.myHideNavigationPopupsCheckBox.isSelected() != settings.HIDE_NAVIGATION_ON_FOCUS_LOSS;
    isModified |= myComponent.myAltDNDCheckBox.isSelected() != settings.DND_WITH_PRESSED_ALT_ONLY;
    isModified |= !Comparing.equal(myComponent.myLafComboBox.getSelectedItem(), LafManager.getInstance().getCurrentLookAndFeel());
    if (WindowManagerEx.getInstanceEx().isAlphaModeSupported()) {
      isModified |= myComponent.myEnableAlphaModeCheckBox.isSelected() != settings.ENABLE_ALPHA_MODE;
      int delay = -1;
      try {
        delay = Integer.parseInt(myComponent.myAlphaModeDelayTextField.getText());
      }
      catch (NumberFormatException ignored) {
      }
      if (delay != -1) {
        isModified |= delay != settings.ALPHA_MODE_DELAY;
      }
      float ratio = myComponent.myAlphaModeRatioSlider.getValue() / 100f;
      isModified |= ratio != settings.ALPHA_MODE_RATIO;
    }
    int tooltipDelay = -1;
    tooltipDelay = myComponent.myInitialTooltipDelaySlider.getValue();
    isModified |=  tooltipDelay != Registry.intValue("ide.tooltip.initialDelay");

    return isModified;
  }

  @Override
  public void disposeUIResources() {
    myComponent = null;
  }

  @Override
  public String getHelpTopic() {
    return "preferences.lookFeel";
  }

  private static class MyComponent {
    private JPanel myPanel;
    private FontComboBox myFontCombo;
    private JComboBox myFontSizeCombo;
    private JCheckBox myAnimateWindowsCheckBox;
    private JCheckBox myWindowShortcutsCheckBox;
    private JCheckBox myShowToolStripesCheckBox;
    private JCheckBox myShowMemoryIndicatorCheckBox;
    private JComboBox myLafComboBox;
    private JCheckBox myCycleScrollingCheckBox;

    private JCheckBox myMoveMouseOnDefaultButtonCheckBox;
    private JCheckBox myEnableAlphaModeCheckBox;
    private JTextField myAlphaModeDelayTextField;
    private JSlider myAlphaModeRatioSlider;
    private JLabel myFontSizeLabel;
    private JLabel myFontNameLabel;
    private JPanel myTransparencyPanel;
    private JCheckBox myOverrideLAFFonts;

    private JCheckBox myHideIconsInQuickNavigation;
    private JCheckBox myCbDisplayIconsInMenu;
    private JCheckBox myDisableMnemonics;
    private JCheckBox myDisableMnemonicInControlsCheckBox;
    private JCheckBox myHideNavigationPopupsCheckBox;
    private JCheckBox myAltDNDCheckBox;
    private JCheckBox myAllowMergeButtons;
    private JBCheckBox myUseSmallLabelsOnTabs;
    private JBCheckBox myWidescreenLayoutCheckBox;
    private JCheckBox myLeftLayoutCheckBox;
    private JCheckBox myRightLayoutCheckBox;
    private JSlider myInitialTooltipDelaySlider;
    private ComboBox myPresentationModeFontSize;
    private JCheckBox myNavigateToPreviewCheckBox;
    private ColorBlindnessPanel myColorBlindnessPanel;
    private JComboBox myAntialiasingInIDE;
    private JComboBox myAntialiasingInEditor;

    public MyComponent() {
      myOverrideLAFFonts.addActionListener( new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
          updateCombo();
        }
      });
      if (!Registry.is("ide.transparency.mode.for.windows")) {
        myTransparencyPanel.getParent().remove(myTransparencyPanel);
      }
    }

    public void updateCombo() {
      boolean enableChooser = myOverrideLAFFonts.isSelected();

      myFontCombo.setEnabled(enableChooser);
      myFontSizeCombo.setEnabled(enableChooser);
      myFontNameLabel.setEnabled(enableChooser);
      myFontSizeLabel.setEnabled(enableChooser);
    }

    private void createUIComponents() {
      myFontSizeCombo = new ComboBox();
      myPresentationModeFontSize = new ComboBox();
    }
  }

  private static class AAListCellRenderer extends ListCellRendererWrapper<AntialiasingType> {
    private static final SwingUtilities2.AATextInfo SUBPIXEL_HINT = new SwingUtilities2.AATextInfo(
      RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB, UIUtil.getLcdContrastValue());
    private static final SwingUtilities2.AATextInfo GREYSCALE_HINT = new SwingUtilities2.AATextInfo(
      RenderingHints.VALUE_TEXT_ANTIALIAS_ON, UIUtil.getLcdContrastValue());

    private final boolean useEditorAASettings;

    public AAListCellRenderer(boolean useEditorAASettings) {
      super();
      this.useEditorAASettings = useEditorAASettings;
    }

    @Override
    public void customize(JList list, AntialiasingType value, int index, boolean selected, boolean hasFocus) {
      if (value == AntialiasingType.SUBPIXEL) {
        setClientProperty(SwingUtilities2.AA_TEXT_PROPERTY_KEY, SUBPIXEL_HINT);
      }
      else if (value == AntialiasingType.GREYSCALE) {
        setClientProperty(SwingUtilities2.AA_TEXT_PROPERTY_KEY, GREYSCALE_HINT);
      }
      else if (value == AntialiasingType.OFF) {
        setClientProperty(SwingUtilities2.AA_TEXT_PROPERTY_KEY, null);
      }

      if (useEditorAASettings) {
        EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme();
        setFont(new Font(scheme.getEditorFontName(), Font.PLAIN, scheme.getEditorFontSize()));
      }

      setText(String.valueOf(value));
    }
  }
}


text:
package org.gradle.api.internal.artifacts;

import org.gradle.api.artifacts.DependencyResolveDetails;
import org.gradle.api.artifacts.result.ComponentSelectionReason;

public interface DependencyResolveDetailsInternal extends DependencyResolveDetails {

    void useVersion(String version, ComponentSelectionReason selectionReason);

    ComponentSelectionReason getSelectionReason();

    boolean isUpdated();
}


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 org.camunda.bpm.engine.impl.delegate;

import org.camunda.bpm.engine.delegate.VariableScope;
import org.camunda.bpm.engine.impl.context.Context;
import org.camunda.bpm.engine.impl.scripting.ExecutableScript;

/**
 * @author Roman Smirnov
 *
 */
public class ScriptInvocation extends DelegateInvocation {

  protected ExecutableScript script;
  protected VariableScope scope;

  public ScriptInvocation(ExecutableScript script, VariableScope scope) {
    this.script = script;
    this.scope = scope;
  }

  protected void invoke() throws Exception {
    invocationResult = Context
      .getProcessEngineConfiguration()
      .getScriptingEnvironment()
      .execute(script, scope);
  }

  public Object getTarget() {
    return script;
  }

}


text:
require 'rubygems'
require 'active_support'
require 'lib/active_merchant'

class GatewaySupport #:nodoc:
  ACTIONS = [:purchase, :authorize, :capture, :void, :credit, :recurring]

  include ActiveMerchant::Billing

  attr_reader :gateways

  def initialize
    @gateways = Gateway.implementations.sort_by(&:name)
    @gateways.delete(ActiveMerchant::Billing::BogusGateway)
  end

  def each_gateway
    @gateways.each{|g| yield g }
  end

  def features
    width = 15

    print "Name".center(width + 20)
    ACTIONS.each{|f| print "#{f.to_s.capitalize.center(width)}" }
    puts

    each_gateway do |g|
      print "#{g.display_name.ljust(width + 20)}"
      ACTIONS.each do |f|
        print "#{(g.instance_methods.include?(f.to_s) ? "Y" : "N").center(width)}"
      end
      puts
    end
  end

  def to_rdoc
    each_gateway do |g|
      puts "* {#{g.display_name}}[#{g.homepage_url}] - #{g.supported_countries.join(', ')}"
    end
  end

  def to_textile
    each_gateway do |g|
      puts %/ * "#{g.display_name}":#{g.homepage_url} [#{g.supported_countries.join(', ')}]/
    end
  end

  def to_s
    each_gateway do |g|
      puts "#{g.display_name} - #{g.homepage_url} [#{g.supported_countries.join(', ')}]"
    end
  end
end


text:
package eu.f3rog.blade.compiler;

import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.TypeElement;

import eu.f3rog.blade.compiler.util.ProcessorError;

/**
 * Interface {@link ProcessorModule}
 *
 * @author FrantisekGazo
 * @version 2015-12-19
 */
public interface ProcessorModule {

    void process(TypeElement bladeElement) throws ProcessorError;

    void process(RoundEnvironment roundEnv) throws ProcessorError;

}


text:
#include<iostream>
using namespace std;
#define MAX_SIZE 100
/**
	To display array from start to end
*/
template<class Type>
void display(Type array[], int start, int end) {
	for(int i = start; i <= end; i++) {
		cout << array[i] << " ";
	}
	cout << endl;
}
/**
	merge array[left, center] and array[center + 1, right] into temp[left, right]
*/
template<class Type>
void merge(Type array[], Type temp[], int left, int center, int right) {
	int i = left;
	int j = center + 1;
	int k = left;

	// merge the common counts array
	while((i <= center) && (j <= right)) {
		// merge array[i] into temp
		if(array[i] <= array[j]) {
			temp[k++] = array[i++];
		} else {// merge array[j] into temp
			temp[k++] = array[j++];
		}
	}

	// merge last array[j] to array[right] into temp
	if(i > center) {
		for(int p = j; p <= right; p++) {
			temp[k++] = array[p];
		}
	} else {// merge last array[i] to array[left] into temp
		for(int p = i; p <= center; p++) {
			temp[k++] = array[p];
		}
	}
}
/**
	To copy temp to array from left to right
*/
template<class Type>
void copy(Type array[], Type temp[], int left, int right) {
	for(int i = left; i <= right; i++) {
		array[i] = temp[i];
	}
}
/**
	meegeSort array[left, right]
	使用分治实现对n个元素进行排序的算法
	基本思想是:
		将待排序元素分成大小大致相同的两个子集合,分别对两个子集合进行排序,最终将
		排好序的子集合进行合成有序的集合
*/
template<class Type>
void mergeSort(Type array[], int left, int right) {
	Type temp[MAX_SIZE];
	// more than 2 elements
	if(left < right) {
		int center = (left + right) / 2;

		// meegeSort array[left, center]
		mergeSort(array, left, center);

		// meegeSort array[center + 1, right]
		mergeSort(array, center + 1, right);

		// merge array into temp from left->center->right
		merge(array, temp, left, center, right);

		// copy temp to array from left to right
		copy(array, temp, left, right);

		display(array, left, right);
	}
}
void testMergeSort() {
	int array[10] = {
		3, 4, 8, 1, 6, 9, 7, 0, 2, 5
	};
	int left = 0;
	int right = 9;
	cout << "The init data : ";
	display(array, left, right);

	mergeSort(array, left, right);

	cout << "After sort data : ";
	display(array, left, right);
}
int main() {
	testMergeSort();
	return 0;
}


text:
import CmsModal from '../index';
import { shallow } from 'enzyme';
import { shallowToJson } from 'enzyme-to-json';
import React from 'react';
import mockTags, { selectedTags } from './mocks';

describe('<CmsModal />', () => {
  it('should render with default props', () => {
    const wrapper = shallow(
      <CmsModal
        isShowing
        onClose={e => e}
        spotlighted
        onToggleSpotlight={e => e}
        onSetStatus={e => e}
        status={0}
        onSave={e => e}
        canSubmit
        tags={mockTags}
        onChangeValue={e => e}
        selectedTags={selectedTags}
      />
    );
    expect(shallowToJson(wrapper)).toMatchSnapshot();
  });
});


text:
import { controllerLookup } from 'helpers/toolkit';

let instance = null;

export class RouteChangeListener {
  constructor() {
    if (instance) {
      return instance;
    }

    let routeChangeListener = this;
    routeChangeListener.features = [];

    let applicationController = controllerLookup('application');
    applicationController.reopen({
      onRouteChanged: Ember.observer(
        'currentRouteName', // this will handle accounts -> budget and vise versa
        'budgetVersionId', // this will handle changing budgets
        'selectedAccountId', // this will handle switching around accounts
        'monthString', // this will handle changing which month of a budget you're looking at
        (controller, changedProperty) => {
          if (changedProperty === 'budgetVersionId') {
            Ember.run.scheduleOnce('afterRender', controller, 'emitBudgetRouteChange');
          } else {
            Ember.run.scheduleOnce('afterRender', controller, 'emitSameBudgetRouteChange');
          }
        }),

      emitSameBudgetRouteChange: function () {
        let currentRoute = applicationController.get('currentRouteName');
        routeChangeListener.features.forEach((feature) => {
          setTimeout(feature.onRouteChanged.bind(feature, currentRoute), 0);
        });
      },

      emitBudgetRouteChange: function () {
        let currentRoute = applicationController.get('currentRouteName');
        routeChangeListener.features.forEach((feature) => {
          setTimeout(feature.onBudgetChanged.bind(feature, currentRoute), 0);
        });
      }
    });

    instance = this;
  }

  addFeature(feature) {
    if (this.features.indexOf(feature) === -1) {
      this.features.push(feature);
    }
  }
}


text:
/* Lua System: Win32 specifics: Service */

#define WSVC_TYPENAME	"sys.win32.service"

typedef DWORD (WINAPI *svc_func_t) (void *);

/*
 * Arguments: name (string), filename (string), [manual_start (boolean)]
 * Returns: [boolean]
 */
static int
svc_install (lua_State *L)
{
  const char *name = luaL_checkstring(L, 1);
  int pathlen = lua_rawlen(L, 2);
  const int manual = lua_toboolean(L, 3);
  SC_HANDLE mngr = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);
  SC_HANDLE sc = NULL;

  /* include space & term. '\0' */
  if (!pathlen || ++pathlen >= MAX_PATHNAME)
    return 0;

  if (mngr) {
    char path[MAX_PATHNAME*2];
    const int n = GetModuleFileNameA(NULL, path, MAX_PATHNAME);

    if (n) {
      path[n] = ' ';
      memcpy(path + n + 1, lua_tostring(L, 2), pathlen);
      sc = CreateServiceA(mngr, name, name,
       SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
       manual ? SERVICE_DEMAND_START : SERVICE_AUTO_START,
       SERVICE_ERROR_NORMAL,
       path, 0, 0, 0, 0, 0);
      if (sc) CloseServiceHandle(sc);
    }
    CloseServiceHandle(mngr);
  }
  if (sc) {
    lua_pushboolean(L, 1);
    return 1;
  }
  return sys_seterror(L, 0);
}

/*
 * Arguments: name (string)
 * Returns: [boolean]
 */
static int
svc_uninstall (lua_State *L)
{
  const char *name = lua_tostring(L, 1);
  SC_HANDLE mngr = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);
  int res = 0;

  if (mngr) {
    SC_HANDLE sc = OpenServiceA(mngr, name, SERVICE_ALL_ACCESS | DELETE);

    if (sc) {
      SERVICE_STATUS status;
      int n = 2;  /* count of attempts to stop the service */

      do {
        if (QueryServiceStatus(sc, &status)
         && status.dwCurrentState == SERVICE_STOPPED) {
          res = DeleteService(sc);
          break;
        }
        ControlService(sc, SERVICE_CONTROL_STOP, &status);
        Sleep(1000);
      } while (--n);
      CloseServiceHandle(sc);
    }
    CloseServiceHandle(mngr);
  }
  if (res) {
    lua_pushboolean(L, 1);
    return 1;
  }
  return sys_seterror(L, 0);
}

/* Service global variables */
static struct {
  SERVICE_STATUS status;
  SERVICE_STATUS_HANDLE hstatus;
  HANDLE event;
  int accept_pause_cont;
} g_Service;

static void WINAPI
svc_controller (DWORD code)
{
  int is_accept = 0;

  switch (code) {
  case SERVICE_CONTROL_SHUTDOWN:
  case SERVICE_CONTROL_STOP:
    g_Service.status.dwCurrentState = SERVICE_STOP_PENDING;
    is_accept = 1;
    break;
  case SERVICE_CONTROL_PAUSE:
  case SERVICE_CONTROL_CONTINUE:
    if (g_Service.accept_pause_cont) {
      g_Service.status.dwCurrentState = (code == SERVICE_CONTROL_PAUSE)
       ? SERVICE_PAUSE_PENDING : SERVICE_CONTINUE_PENDING;
      is_accept = 1;
    }
    break;
  }

  SetServiceStatus(g_Service.hstatus, &g_Service.status);
  if (is_accept)
    SetEvent(g_Service.event);
}

static void WINAPI
svc_main (DWORD argc, char *argv[])
{
  (void) argc;

  g_Service.hstatus = RegisterServiceCtrlHandlerA(argv[0], svc_controller);
  if (g_Service.hstatus) {
    /* initialise service status */
    g_Service.status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
    g_Service.status.dwControlsAccepted = SERVICE_ACCEPT_STOP
     | SERVICE_ACCEPT_SHUTDOWN
     | (g_Service.accept_pause_cont ? SERVICE_ACCEPT_PAUSE_CONTINUE : 0);
    g_Service.status.dwWin32ExitCode = NO_ERROR;
    g_Service.status.dwServiceSpecificExitCode = 0;
    g_Service.status.dwCheckPoint = 0;
    g_Service.status.dwWaitHint = 10000;

    g_Service.status.dwCurrentState = SERVICE_RUNNING;
    SetServiceStatus(g_Service.hstatus, &g_Service.status);
  }
  SetEvent(g_Service.event);
}

static DWORD WINAPI
svc_start (char *svc_name)
{
  SERVICE_TABLE_ENTRY table[] = {{NULL, NULL}, {NULL, NULL}};

  table[0].lpServiceName = svc_name;
  table[0].lpServiceProc = svc_main;

  return !StartServiceCtrlDispatcher(table);
}

/*
 * Arguments: name (string), [accept pause & continue (boolean)]
 * Returns: [svc_udata]
 */
static int
svc_handle (lua_State *L)
{
  const char *svc_name = luaL_checkstring(L, 1);
  const int accept_pause_cont = lua_toboolean(L, 2);
  char name_buf[128];
  HANDLE hThr;
  DWORD id;

  if (g_Service.event)
    luaL_argerror(L, 0, "already running");
  else {
    HANDLE *hep = lua_newuserdata(L, sizeof(HANDLE));
    luaL_getmetatable(L, WSVC_TYPENAME);
    lua_setmetatable(L, -2);

    *hep = CreateEvent(NULL, TRUE, FALSE, NULL);  /* manual-reset */
    if (!*hep) goto err;

    g_Service.event = *hep;
    g_Service.accept_pause_cont = accept_pause_cont;
  }

  strncpy(name_buf, svc_name, sizeof(name_buf));
  name_buf[sizeof(name_buf) - 1] = '\0';

  hThr = CreateThread(NULL, 4096, (svc_func_t) svc_start, name_buf, 0, &id);
  if (hThr != NULL) {
    CloseHandle(hThr);

    WaitForSingleObject(g_Service.event, INFINITE);
    ResetEvent(g_Service.event);

    if (g_Service.hstatus)
      return 1;
  }
 err:
  return sys_seterror(L, 0);
}

/*
 * Arguments: svc_udata
 */
static int
svc_close (lua_State *L)
{
  HANDLE *hep = checkudata(L, 1, WSVC_TYPENAME);
  if (*hep) {
    CloseHandle(*hep);
    *hep = NULL;
  }
  return 0;
}

/*
 * Arguments: svc_udata, [status (string: "stopped", "paused", "running")]
 * Returns: [svc_udata | control_code (string: "stop", "pause", "continue")]
 */
static int
svc_status (lua_State *L)
{
  const char *s = lua_tostring(L, 2);

  if (s) {
    int st;
    switch (s[0]) {
    case 's': st = SERVICE_STOPPED; break;
    case 'p': st = SERVICE_PAUSED; break;
    case 'r': st = SERVICE_RUNNING; break;
    default: return 0;
    }
    g_Service.status.dwCurrentState = st;

    SetServiceStatus(g_Service.hstatus, &g_Service.status);
    Sleep(0);  /* yield to service controller thread */

    lua_settop(L, 1);
  } else {
    switch (g_Service.status.dwCurrentState) {
    case SERVICE_STOPPED:
    case SERVICE_STOP_PENDING:
      s = "stop"; break;
    case SERVICE_RUNNING:
      s = "running"; break;
    case SERVICE_CONTINUE_PENDING:
      s = "continue"; break;
    case SERVICE_PAUSE_PENDING:
    case SERVICE_PAUSED:
      s = "pause"; break;
    }
    lua_pushstring(L, s);
  }
  return 1;
}

/*
 * Arguments: svc_udata, [timeout (milliseconds)]
 * Returns: [signalled/timedout (boolean)]
 */
static int
svc_wait (lua_State *L)
{
  HANDLE he = (HANDLE) lua_unboxpointer(L, 1, WSVC_TYPENAME);
  DWORD res = luaL_optinteger(L, 2, INFINITE);

  sys_vm_leave(L);
  res = WaitForSingleObject(he, res);
  ResetEvent(he);
  sys_vm_enter(L);

  if (res != WAIT_FAILED) {
    lua_pushboolean(L, res == WAIT_OBJECT_0);
    return 1;
  }
  return 0;
}

/*
 * Arguments: svc_udata
 * Returns: string
 */
static int
svc_tostring (lua_State *L)
{
  HANDLE he = (HANDLE) lua_unboxpointer(L, 1, WSVC_TYPENAME);
  lua_pushfstring(L, WSVC_TYPENAME " (%p)", he);
  return 1;
}

static luaL_Reg svc_meth[] = {
  {"status",		svc_status},
  {"wait",		svc_wait},
  {"__tostring",	svc_tostring},
  {"__gc",		svc_close},
  {NULL, NULL}
};

static luaL_Reg svc_lib[] = {
  {"install",		svc_install},
  {"uninstall",		svc_uninstall},
  {"handle",		svc_handle},
  {NULL, NULL}
};

/*
 * Arguments: ..., win32_lib (table)
 */
static void
luaopen_sys_win32_service (lua_State *L)
{
  luaL_newlib(L, svc_lib);
  lua_setfield(L, -2, "service");

  luaL_newmetatable(L, WSVC_TYPENAME);
  lua_pushvalue(L, -1);  /* push metatable */
  lua_setfield(L, -2, "__index");  /* metatable.__index = metatable */
  luaL_setfuncs(L, svc_meth, 0);
  lua_pop(L, 1);
}


text:
package registry

import (
	"context"
	"errors"
	"net/url"

	"github.com/manifoldco/torus-cli/apitypes"
	"github.com/manifoldco/torus-cli/envelope"
	"github.com/manifoldco/torus-cli/identity"
	"github.com/manifoldco/torus-cli/primitive"
)

// ErrKeyNotFound represents a situation where a key could not be found
var ErrKeyNotFound = &apitypes.Error{
	Type: apitypes.NotFoundError,
	Err:  []string{"Could not locate public key segment for specified key id"},
}

// ErrMissingKeyForOwner represents a situation where a key of a specific type could not be found for the owner inside an org
var ErrMissingKeyForOwner = &apitypes.Error{
	Type: apitypes.NotFoundError,
	Err:  []string{"Could not locate public key segment in claimtree for target"},
}

// ErrClaimTreeNotFound represents a situation where a claimtree could not be
// found
var ErrClaimTreeNotFound = &apitypes.Error{
	Type: apitypes.NotFoundError,
	Err:  []string{"Could not find claim tree for org"},
}

// ClaimTreeClient represents the `/claimtree` registry endpoint, used for
// retrieving the public keys and their associated claims for an organization.
type ClaimTreeClient struct {
	client RoundTripper
}

// ClaimTree represents an organizations claim tree which contains public
// signing and encryption keys for every member.
type ClaimTree struct {
	Org        *envelope.Org               `json:"org"`
	PublicKeys []apitypes.PublicKeySegment `json:"public_keys"`
}

// Find returns the PublicKeySegment for the given PublicKeyID. Accepts a
// boolean for indicating whether or not to enforce that the key must be
// active.
//
// If a key segment could not be found an error is returned.
func (ct *ClaimTree) Find(id *identity.ID, mustActive bool) (*apitypes.PublicKeySegment, error) {
	for _, pks := range ct.PublicKeys {
		if *pks.PublicKey.ID == *id {
			if mustActive && pks.Revoked() {
				continue
			}

			return &pks, nil
		}
	}

	return nil, ErrKeyNotFound
}

// FindActive returns the PublicKeySegment for a non-revoked Public Key for
// the given owner id.
//
// If an active key cannot be found an error is returned
func (ct *ClaimTree) FindActive(ownerID *identity.ID, t primitive.KeyType) (*apitypes.PublicKeySegment, error) {
	for _, pks := range ct.PublicKeys {
		if *pks.PublicKey.Body.OwnerID != *ownerID {
			continue
		}

		if pks.PublicKey.Body.KeyType != t {
			continue
		}

		if pks.Revoked() {
			continue
		}

		return &pks, nil
	}

	return nil, ErrMissingKeyForOwner
}

// List returns a list of all claimtrees for a given orgID. If no orgID is
// provided then it returns all claimtrees for every organization the user
// belongs too.
//
// If an ownerID is provided then only public keys and claims related to that
// user or machine will be returned.
func (c *ClaimTreeClient) List(ctx context.Context, orgID *identity.ID,
	ownerID *identity.ID) ([]ClaimTree, error) {

	query := &url.Values{}
	if orgID != nil {
		query.Set("org_id", orgID.String())
	}

	if ownerID != nil {
		query.Set("owner_id", ownerID.String())
	}

	var resp []ClaimTree
	err := c.client.RoundTrip(ctx, "GET", "/claimtree", query, nil, &resp)
	return resp, err
}

// Get returns a claimtree for a specific organization by the given orgID.
//
// If an ownerID is provided then only public keys and claims related to that
// user or machine will be returned.
func (c *ClaimTreeClient) Get(ctx context.Context, orgID *identity.ID,
	ownerID *identity.ID) (*ClaimTree, error) {

	if orgID == nil {
		return nil, errors.New("An org id must be provided")
	}

	cts, err := c.List(ctx, orgID, ownerID)
	if err != nil {
		return nil, err
	}

	if len(cts) != 1 {
		return nil, ErrClaimTreeNotFound
	}

	return &cts[0], nil
}


text:
<resources>
    <string name="app_name">ViewPagerDemo</string>
</resources>


text:
const { getPath } = require('../../utils/helpers');

module.exports = {
  verbose: true,
  testRegex: 'test/.*\\.test\\.jsx?$',
  moduleFileExtensions: ['js', 'jsx', 'json'],
  modulePaths: ['<rootDir>/src'],
  // Need to compile certain modules that are published raw
  // https://jestjs.io/docs/en/configuration.html#transformignorepatterns-array-string
  transformIgnorePatterns: [
    // '/node_modules/', // Default
  ],
  transform: {
    '\\.jsx?$': `./${getPath(
      '@jakedeichert/create-app/lib/env-configs/react/jest.transform.js'
    )}`,
  },
  moduleNameMapper: {
    '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': `<rootDir>/${getPath(
      '@jakedeichert/create-app/lib/env-configs/jest-common/file-mock.js'
    )}`,
  },
};


text:
* LyX: qt5 port
* doxygen
  * +wizard: qt5 port
  * +docs: Requires texlive-fontutils for epstopdf, and texlive-fonts-extra for ecrm1000.tfm
* gnuplot +qt: qt5 port


text:
<!DOCTYPE html>

Test that calling scroll on an overflow:scroll element works with both scroll behaviors


text:
[BlendStateDX11]

[RasterizerStateDX11]
CullMode = D3D11_CULL_NONE

[RenderTargetBlendStateDX11_1]
BlendEnable = false
SrcBlend = D3D11_BLEND_SRC_ALPHA
DestBlend = D3D11_BLEND_INV_SRC_ALPHA

[DepthStencilStateDX11]
DepthEnable = false
DepthFunc = D3D11_COMPARISON_GREATER_EQUAL

[SamplerDX11_1]
MipLODBias = 0

[SamplerDX11_2]
MipLODBias = 0

[SamplerDX11_3]
MipLODBias = 0

[DepthStencilStateOGL]
DepthEnable = false

[RasterizerStateOGL]
DepthClipEnable = true
ScissorEnable = false
MultisampleEnable = false
AntialiasedLineEnable = false

[RenderTargetBlendStateOGL]
blendenable = true
srcblend = GL_SRC_ALPHA
destblend = GL_ONE_MINUS_SRC_ALPHA
srcblendalpha = GL_ONE
destblendalpha = GL_ONE
blendop = gl_func_add
blendopalpha = gl_func_add

[SamplerOGL_1]
MinFilter = GL_NEAREST
MagFilter = GL_NEAREST
AddressU = GL_CLAMP_TO_EDGE
AddressV = GL_CLAMP_TO_EDGE
AddressW = GL_CLAMP_TO_EDGE


text:
/*!
	@file
	@author		Albert Semenov
	@date		02/2008
*/
/*
	This file is part of MyGUI.

	MyGUI is free software: you can redistribute it and/or modify
	it under the terms of the GNU Lesser General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	MyGUI is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Lesser General Public License for more details.

	You should have received a copy of the GNU Lesser General Public License
	along with MyGUI.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __MYGUI_POPUP_MENU_H__
#define __MYGUI_POPUP_MENU_H__

#include "MyGUI_Prerequest.h"
#include "MyGUI_MenuControl.h"

namespace MyGUI
{

	class MYGUI_EXPORT PopupMenu :
		public MenuControl
	{
		MYGUI_RTTI_DERIVED( PopupMenu )

	public:
		PopupMenu();
	};

} // namespace MyGUI

#endif // __MYGUI_POPUP_MENU_H__


text:
.. :index:

===========================================
py-translate
===========================================
**py-translate is a CLI Tool for Google Translate written in Python!**

------------------------------------------------------------------------

.. sidebar:: Current Supported Platforms

    Linux & Mac OS X

:Author:  Sang Han 2014
:License: `Apache Software License v2 <http://opensource.org/licenses/Apache-2.0>`_
:Version: v\ |version|

------------------------------------------------------------------------

Quickstart Guide
--------------------
.. toctree::
    :maxdepth: 1

    README.rst

Overview
----------------
.. toctree::
    :maxdepth: 2
    :glob:

    users/*

API Documentation
-----------------
.. toctree::
    :maxdepth: 2
    :glob:

    /devs/*

Notes
------
.. toctree::
    :maxdepth: 2

    HISTORY
    TODO

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
package io.flutter.editor;

public class WidgetViewModelData {
  public final WidgetEditingContext context;

  public WidgetViewModelData(
    WidgetEditingContext context
  ) {
    this.context = context;
  }
}


text:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class BattleController : MonoBehaviour
{
	[SerializeField]
	private List<TargetData> _targets;

	[SerializeField]
	private Transform _field;

	private Target _currentTarget;

	private void Update()
	{
		if (_currentTarget == null)
		{
			_currentTarget = Target.Create(_targets[Random.Range(0, _targets.Count)]);
			_currentTarget.transform.SetParent(_field, true);
			_currentTarget.Update();
		}
	}
}


text:
from astar import *

# the win state for the problem
winState = 'rrr.bbb'

# sub class of SearchNode for the linear checkers problem
class CheckersSearchNode(SearchNode):
    def __init__(self, state):
        h = 1 # set the h value
        self.g = 1 # set the g value
        SearchNode.__init__(self, state, [],h,state==winState) # call the super init method

    # implementing expandNode for the problem
    def expandNode(self):
        space = self.state.find('.') # find the space in the string
        for i, s in enumerate(self.state):
            if i+1 == space or i+2 == space or i-1 == space or i-2 == space: # if there is a legal move from the current  positition in the string, create a neighbour
                childState = list(self.state) # immutable stuff
                color = self.state[i] #find out which color w are
                childState[space] = color # do the swap
                childState[i] = '.'
                childStateStr = "".join(childState) # create string from the list
                if childStateStr not in states:
                    # if the state is not in the already explored states, add it to the children.
                    self.children.append(CheckersSearchNode(childStateStr))

start = CheckersSearchNode('bbb.rrr')
result = aStarSearch(start)
#print(result)
for a in result:
    print(a.state)


text:
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Rank2Types #-}

module Main where

import           Control.Concurrent
import           Control.Exception (finally)

import           Snap.Http.Server
import           Test.Common.TestHandler

{-

/pong
/fileserve
/echo
pipelined POST requests
slowloris attack / timeout test

-}

main :: IO ()
main = do
    m <- newEmptyMVar

    forkIO $ go m
    takeMVar m

    return ()

  where
    go m = quickHttpServe testHandler `finally` putMVar m ()


text:
"""Basic sequence-to-sequence model with dynamic RNN support."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import abc
import inspect
from enum import Enum

import numpy as np
import tensorflow as tf

from px.nmt import environment_client
from px.nmt import context_encoder
from px.nmt import model_helper
from px.nmt.utils import diverse_decoder_utils
from px.nmt.utils import iterator_utils
from px.nmt.utils import loss_utils
from px.nmt.utils import trie_decoder_utils
from px.nmt.optimistic_restore_saver import OptimisticRestoreSaver

from tensorflow.python.layers import core as layers_core
from third_party.nmt.utils import misc_utils as utils

utils.check_tensorflow_version()

__all__ = ['BaseModel', 'Model']

class DecoderType(Enum):
  TRAINING = 0
  SAMPLE = 1
  GREEDY = 2
  BEAM_SEARCH = 3
  TRIE_BEAM_SEARCH = 4
  TRIE_SAMPLE = 5
  TRIE_GREEDY = 6
  DIVERSE_BEAM_SEARCH = 7

class BaseModel(object):
  """Sequence-to-sequence base class.
  """

  def __init__(self,
               hparams,
               mode,
               iterator,
               source_vocab_table,
               target_vocab_table,
               reverse_target_vocab_table=None,
               scope=None,
               extra_args=None,
               trie=None):
    """Create the model.

    Args:
      hparams: Hyperparameter configurations.
      mode: TRAIN | EVAL | INFER
      iterator: Dataset Iterator that feeds data.
      source_vocab_table: Lookup table mapping source words to ids.
      target_vocab_table: Lookup table mapping target words to ids.
      reverse_target_vocab_table: Lookup table mapping ids to target words. Only
        required in INFER mode. Defaults to None.
      scope: scope of the model.
      extra_args: model_helper.ExtraArgs, for passing customizable functions.
      trie: pygtrie.Trie to decode into

    """
    assert isinstance(iterator, iterator_utils.BatchedInput)
    self.iterator = iterator
    self.mode = mode
    self.src_vocab_table = source_vocab_table
    self.tgt_vocab_table = target_vocab_table

    self.src_vocab_size = hparams.src_vocab_size
    self.tgt_vocab_size = hparams.tgt_vocab_size
    self.num_gpus = hparams.num_gpus
    self.reverse_target_vocab_table = reverse_target_vocab_table
    # extra_args: to make it flexible for adding external customizable code
    self.single_cell_fn = None
    if extra_args:
      self.single_cell_fn = extra_args.single_cell_fn

    # Set num layers
    self.num_encoder_layers = hparams.num_encoder_layers
    self.num_decoder_layers = hparams.num_decoder_layers
    assert self.num_encoder_layers
    assert self.num_decoder_layers

    self.trie = trie

    # Set num residual layers
    if hasattr(hparams, 'num_residual_layers'):  # compatible common_test_utils
      self.num_encoder_residual_layers = hparams.num_residual_layers
      self.num_decoder_residual_layers = hparams.num_residual_layers
    else:
      self.num_encoder_residual_layers = hparams.num_encoder_residual_layers
      self.num_decoder_residual_layers = hparams.num_decoder_residual_layers

    # Initializer
    initializer = model_helper.get_initializer(
        hparams.init_op, hparams.random_seed, hparams.init_weight)
    tf.get_variable_scope().set_initializer(initializer)

    # Embeddings
    self.init_embeddings(hparams, scope)
    self.batch_size = tf.size(self.iterator.source_sequence_length)

    # Projection
    with tf.variable_scope(scope or 'build_network', reuse=tf.AUTO_REUSE):
      with tf.variable_scope('decoder/output_projection'):
        self.output_layer = layers_core.Dense(
            hparams.tgt_vocab_size, use_bias=False, name='output_projection')

    if hparams.use_rl:
      # Create environment function
      self._environment_reward_fn = (
          environment_client.make_environment_reward_fn(
              hparams.environment_server, mode=hparams.environment_mode))

    ## Train graph
    res = self.build_graph(hparams, scope=scope)

    (self.loss, self.rewards, self.logits, self.final_context_state,
     self.sample_id, self.sample_words, self.sample_strings,
     train_summaries) = res
    if self.mode == tf.contrib.learn.ModeKeys.TRAIN:
      self.word_count = tf.reduce_sum(
          self.iterator.source_sequence_length) + tf.reduce_sum(
              self.iterator.target_sequence_length)

    if self.mode != tf.contrib.learn.ModeKeys.INFER:
      ## Count the number of predicted words for compute ppl.
      self.predict_count = tf.reduce_sum(self.iterator.target_sequence_length)

    self.global_step = tf.Variable(0, trainable=False)
    params = tf.trainable_variables()

    # Gradients and SGD update operation for training the model.
    # Arrage for the embedding vars to appear at the beginning.
    if self.mode == tf.contrib.learn.ModeKeys.TRAIN:
      self.learning_rate = tf.constant(hparams.learning_rate)
      # warm-up
      self.learning_rate = self._get_learning_rate_warmup(hparams)
      # decay
      self.learning_rate = self._get_learning_rate_decay(hparams)

      # Optimizer
      if hparams.optimizer == 'sgd':
        opt = tf.train.GradientDescentOptimizer(self.learning_rate)
      elif hparams.optimizer == 'adam':
        opt = tf.train.AdamOptimizer(self.learning_rate)
      elif hparams.optimizer == 'rmsprop':
        opt = tf.train.RMSPropOptimizer(self.learning_rate)
      elif hparams.optimizer == 'adadelta':
        opt = tf.train.AdadeltaOptimizer(self.learning_rate)

      # Gradients
      gradients = tf.gradients(
          self.loss,
          params,
          colocate_gradients_with_ops=hparams.colocate_gradients_with_ops)

      (clipped_gradients, gradients_norm_summary,
       gradients_norm) = model_helper.gradient_clip(
           gradients, max_gradient_norm=hparams.max_gradient_norm)
      self.gradients_norm = gradients_norm

      self.update = opt.apply_gradients(
          zip(clipped_gradients, params), global_step=self.global_step)

      # Summary
      self.train_summary = tf.summary.merge([
          tf.summary.scalar('lr', self.learning_rate),
          tf.summary.scalar('train_loss', self.loss),
      ] + train_summaries + gradients_norm_summary)

    if self.mode == tf.contrib.learn.ModeKeys.INFER:
      self.infer_summary = self._get_infer_summary(hparams)

    # Saver
    self.saver = OptimisticRestoreSaver(
        max_to_keep=hparams.num_keep_ckpts, init_uninitialized_variables=True)

    # Print trainable variables
    utils.print_out('# Trainable variables')
    for param in params:
      utils.print_out('  {}, {}, {}'.format(param.name, param.get_shape(),
                                            param.op.device))

  def _get_learning_rate_warmup(self, hparams):
    """Get learning rate warmup."""
    warmup_steps = hparams.warmup_steps
    warmup_scheme = hparams.warmup_scheme
    utils.print_out(
        '  learning_rate={}, warmup_steps={}, warmup_scheme={}'.format(
            hparams.learning_rate, warmup_steps, warmup_scheme))

    # Apply inverse decay if global steps less than warmup steps.
    # Inspired by https://arxiv.org/pdf/1706.03762.pdf (Section 5.3)
    # When step < warmup_steps,
    #   learing_rate *= warmup_factor ** (warmup_steps - step)
    if warmup_scheme == 't2t':
      # 0.01^(1/warmup_steps): we start with a lr, 100 times smaller
      warmup_factor = tf.exp(tf.log(0.01) / warmup_steps)
      inv_decay = warmup_factor**(tf.to_float(warmup_steps - self.global_step))
    else:
      raise ValueError('Unknown warmup scheme {}'.format(warmup_scheme))

    return tf.cond(
        self.global_step < hparams.warmup_steps,
        lambda: inv_decay * self.learning_rate,
        lambda: self.learning_rate,
        name='learning_rate_warump_cond')

  def _get_learning_rate_decay(self, hparams):
    """Get learning rate decay."""
    if hparams.decay_scheme == 'luong10':
      start_decay_step = int(hparams.num_train_steps / 2)
      remain_steps = hparams.num_train_steps - start_decay_step
      decay_steps = int(remain_steps / 10)  # decay 10 times
      decay_factor = 0.5
    elif hparams.decay_scheme == 'luong234':
      start_decay_step = int(hparams.num_train_steps * 2 / 3)
      remain_steps = hparams.num_train_steps - start_decay_step
      decay_steps = int(remain_steps / 4)  # decay 4 times
      decay_factor = 0.5
    elif not hparams.decay_scheme:  # no decay
      start_decay_step = hparams.num_train_steps
      decay_steps = 0
      decay_factor = 1.0
    elif hparams.decay_scheme:
      raise ValueError('Unknown decay scheme %s' % hparams.decay_scheme)
    utils.print_out('  decay_scheme=%s, start_decay_step=%d, decay_steps %d, '
                    'decay_factor %g' % (hparams.decay_scheme, start_decay_step,
                                         decay_steps, decay_factor))

    return tf.cond(
        self.global_step < start_decay_step,
        lambda: self.learning_rate,
        lambda: tf.train.exponential_decay(
            self.learning_rate,
            (self.global_step - start_decay_step),
            decay_steps, decay_factor, staircase=True),
        name='learning_rate_decay_cond')

  def init_embeddings(self, hparams, scope):
    """Init embeddings."""
    self.embedding_encoder, self.embedding_decoder = (
        model_helper.create_emb_for_encoder_and_decoder(
            share_vocab=hparams.share_vocab,
            src_vocab_size=self.src_vocab_size,
            tgt_vocab_size=self.tgt_vocab_size,
            src_embed_size=hparams.num_units,
            tgt_embed_size=hparams.num_units,
            num_partitions=hparams.num_embeddings_partitions,
            src_vocab_file=hparams.src_vocab_file,
            tgt_vocab_file=hparams.tgt_vocab_file,
            src_embed_file=hparams.src_embed_file,
            tgt_embed_file=hparams.tgt_embed_file,
            scope=scope,
        ))

  def train(self, sess):
    assert self.mode == tf.contrib.learn.ModeKeys.TRAIN
    return sess.run([
        self.update, self.loss, self.rewards, self.predict_count,
        self.train_summary, self.global_step, self.word_count, self.batch_size,
        self.gradients_norm, self.learning_rate, self.sample_strings
    ])

  def eval(self, sess):
    assert self.mode == tf.contrib.learn.ModeKeys.EVAL
    return sess.run([
        self.loss, self.rewards, self.sample_words, self.predict_count,
        self.batch_size
    ])

  def build_graph(self, hparams, scope=None):
    """Subclass must implement this method.

    Creates a sequence-to-sequence model with dynamic RNN decoder API.
    Args:
      hparams: Hyperparameter configurations.
      scope: VariableScope for the created subgraph; default "dynamic_seq2seq".

    Returns:
      A tuple of the form (logits, loss, final_context_state),
      where:
        logits: float32 Tensor [batch_size x num_decoder_symbols].
        loss: the total loss / batch_size.
        final_context_state: The final state of decoder RNN.

    Raises:
      ValueError: if encoder_type differs from mono and bi, or
        attention_option is not (luong | scaled_luong |
        bahdanau | normed_bahdanau).
    """
    utils.print_out('# creating {} graph ...'.format(self.mode))
    dtype = tf.float32
    train_summaries = []

    with tf.variable_scope(
        scope or 'dynamic_seq2seq', dtype=dtype, reuse=tf.AUTO_REUSE):
      ## Context
      if hparams.ctx is not None:
        vector_size = hparams.num_units
        if (hparams.encoder_type == 'bi' and
            hparams.context_feed == 'encoder_output'):
          vector_size *= 2

        context_vector = context_encoder.get_context_vector(
            self.mode, self.iterator, hparams, vector_size=vector_size)

      ## Encoder
      encoder_outputs, encoder_state = self._build_encoder(hparams)

      ## Feed the Context
      if hparams.ctx is not None:
        encoder_outputs, encoder_state = context_encoder.feed(
            context_vector, encoder_outputs, encoder_state, hparams)

      ## Decoder
      logits, sample_ids, final_context_state = self._build_decoder(
          encoder_outputs, encoder_state, hparams)

      sample_words = self.reverse_target_vocab_table.lookup(
          tf.to_int64(sample_ids))

      # Make output shape = [batch_size, time] or [beam_width, batch_size, time]
      # when using beam search.
      sample_ids = tf.transpose(sample_ids)
      sample_words = tf.transpose(sample_words)
      sample_strings = tf.py_func(self.tokens_to_strings,
                                  [sample_words, hparams.eos], (tf.string),
                                  'TokensToStrings')

      if hparams.server_mode:
        rewards = self.iterator.weights
      elif hparams.use_rl:
        # Compute rewards when in TRAIN or EVAL mode
        iterator = self.iterator
        doc_ids = iterator.annotation

        rewards, _ = self.compute_rewards(
            questions=sample_strings, doc_ids=doc_ids)

        train_summaries.append(
            tf.summary.scalar('train_avg_reward', tf.reduce_mean(rewards)))
      else:
        # tf does only accepts tensors as returned values
        rewards = tf.constant([1.0])

      ## Loss
      if self.mode != tf.contrib.learn.ModeKeys.INFER:

        with tf.device(
            model_helper.get_device_str(self.num_encoder_layers - 1,
                                        self.num_gpus)):
          # encoder_outputs.shape = [max_time, batch_size, embeddings_dim]
          question_embeddings = tf.reduce_mean(encoder_outputs, 0)
          loss = self._compute_loss(
              hparams=hparams,
              logits=logits,
              sample_ids=sample_ids,
              sample_words=sample_words,
              rewards=rewards,
              question_embeddings=question_embeddings,
              train_summaries=train_summaries)
      else:
        loss = None

      return (loss, rewards, logits, final_context_state, sample_ids,
              sample_words, sample_strings, train_summaries)

  @abc.abstractmethod
  def _build_encoder(self, hparams):
    """Subclass must implement this.

    Build and run an RNN encoder.

    Args:
      hparams: Hyperparameters configurations.

    Returns:
      A tuple of encoder_outputs and encoder_state.
    """
    pass

  def _build_encoder_cell(self,
                          hparams,
                          num_layers,
                          num_residual_layers,
                          base_gpu=0):
    """Build a multi-layer RNN cell that can be used by encoder."""

    return model_helper.create_rnn_cell(
        unit_type=hparams.unit_type,
        num_units=hparams.num_units,
        num_layers=num_layers,
        num_residual_layers=num_residual_layers,
        forget_bias=hparams.forget_bias,
        dropout=hparams.dropout,
        num_gpus=hparams.num_gpus,
        mode=self.mode,
        base_gpu=base_gpu,
        single_cell_fn=self.single_cell_fn)

  def _get_infer_maximum_iterations(self, hparams, source_sequence_length):
    """Maximum decoding steps at inference time."""
    if hparams.tgt_max_len_infer:
      maximum_iterations = hparams.tgt_max_len_infer
      utils.print_out('  decoding maximum_iterations %d' % maximum_iterations)
    else:
      decoding_length_factor = 2.0
      max_encoder_length = tf.reduce_max(source_sequence_length)
      maximum_iterations = tf.to_int32(
          tf.round(tf.to_float(max_encoder_length) * decoding_length_factor))
    return maximum_iterations

  def _build_decoder(self, encoder_outputs, encoder_state, hparams):
    """Build and run a RNN decoder with a final projection layer.

    Args:
      encoder_outputs: The outputs of encoder for every time step.
      encoder_state: The final state of the encoder.
      hparams: The Hyperparameters configurations.

    Returns:
      A tuple of final logits and final decoder state:
        logits: size [time, batch_size, vocab_size].

    Raises:
      ValueError: In case of incompatible hparams.
    """
    tgt_sos_id = tf.cast(
        self.tgt_vocab_table.lookup(tf.constant(hparams.sos)), tf.int32)
    tgt_eos_id = tf.cast(
        self.tgt_vocab_table.lookup(tf.constant(hparams.eos)), tf.int32)

    iterator = self.iterator
    source_sequence_length = iterator.source_sequence_length
    # add 1 into the source length
    if hparams.context_feed == 'encoder_output':
      if hparams.context_vector == 'bilstm_full':
        context_length = self.get_max_time(self.iterator.context)
        source_sequence_length = tf.add(context_length, source_sequence_length)
      else:
        source_sequence_length = tf.add(1, source_sequence_length)

    # maximum_iteration: The maximum decoding steps.
    maximum_iterations = self._get_infer_maximum_iterations(
        hparams, iterator.source_sequence_length)

    ## Decoder.
    with tf.variable_scope('decoder') as decoder_scope:
      cell, decoder_initial_state = self._build_decoder_cell(
          hparams, encoder_outputs, encoder_state, source_sequence_length)

      start_tokens = tf.fill([self.batch_size], tgt_sos_id)
      end_token = tgt_eos_id

      # decoder_type:
      # Train and SL: Training (0)
      # Eval and SL: Training (0)
      # Train and RL: Sample (1)
      # Eval and RL: Greedy (2)
      # INFER and no beam: Greedy (2)
      # INFER and beam: BeamSearch (3)

      if self.mode == tf.contrib.learn.ModeKeys.TRAIN and not hparams.use_rl:
        decoder_type = DecoderType.TRAINING
      elif self.mode == tf.contrib.learn.ModeKeys.EVAL and not hparams.use_rl:
        decoder_type = DecoderType.TRAINING
      elif self.mode == tf.contrib.learn.ModeKeys.TRAIN and hparams.use_rl:
        if hparams.infer_mode.startswith('trie_'):
          decoder_type = DecoderType.TRIE_SAMPLE
        else:
          decoder_type = DecoderType.SAMPLE
      elif self.mode == tf.contrib.learn.ModeKeys.EVAL and hparams.use_rl:
        if hparams.infer_mode.startswith('trie_'):
          decoder_type = DecoderType.TRIE_GREEDY
        else:
          decoder_type = DecoderType.GREEDY
      elif self.mode == tf.contrib.learn.ModeKeys.INFER:
        if hparams.infer_mode == 'greedy':
          if hparams.beam_width != 0:
            raise ValueError('Greedy decoding requires beam_width == 0')
          decoder_type = DecoderType.GREEDY
        elif hparams.infer_mode == 'trie_greedy':
          if hparams.beam_width != 0:
            raise ValueError('Trie greedy decoding requires beam_width == 0')
          decoder_type = DecoderType.TRIE_GREEDY
        elif hparams.infer_mode == 'sample':
          if hparams.beam_width != 0:
            raise ValueError('Sampling requires beam_width == 0')
          decoder_type = DecoderType.SAMPLE
        elif hparams.infer_mode == 'trie_sample':
          if hparams.beam_width != 0:
            raise ValueError('Trie sampling requires beam_width == 0')
          decoder_type = DecoderType.TRIE_SAMPLE
        elif hparams.infer_mode == 'beam_search':
          if hparams.beam_width <= 0:
            raise ValueError('Beam search requires beam_width > 0')
          decoder_type = DecoderType.BEAM_SEARCH
        elif hparams.infer_mode == 'trie_beam_search':
          if hparams.beam_width <= 0:
            raise ValueError('Trie beam search requires beam_width > 0')
          decoder_type = DecoderType.TRIE_BEAM_SEARCH
        elif hparams.infer_mode == 'diverse_beam_search':
          if hparams.beam_width <= 0:
            raise ValueError('Diverse beam search requires beam_width > 0')
          decoder_type = DecoderType.DIVERSE_BEAM_SEARCH
        else:
          raise ValueError('Invalid infer_mode: {}.'.format(hparams.infer_mode))
      else:
        raise ValueError(
            'No decoder found for the given combination of mode ({})'
            'use_rl ({}) and beam_width ({}).'.format(self.mode, self.use_rl,
                                                      hparams.beam_width))

      if decoder_type == DecoderType.TRAINING:
        # TrainingHelper
        # decoder_emp_inp: [max_time, batch_size, num_units]
        target_input = iterator.target_input
        # Make shape [max_time, batch_size].
        target_input = tf.transpose(target_input)
        decoder_emb_inp = tf.nn.embedding_lookup(self.embedding_decoder,
                                                 target_input)
        helper = tf.contrib.seq2seq.TrainingHelper(
            decoder_emb_inp, iterator.target_sequence_length, time_major=True)
        maximum_iterations = None
        output_layer = None

      elif decoder_type in [DecoderType.SAMPLE, DecoderType.TRIE_SAMPLE]:
        # Sample
        if hparams.sampling_temperature > 0:
          helper = tf.contrib.seq2seq.SampleEmbeddingHelper(
              self.embedding_decoder,
              start_tokens,
              end_token,
              softmax_temperature=hparams.sampling_temperature,
              seed=hparams.random_seed)
        else:
          helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(
              self.embedding_decoder, start_tokens, end_token)
        output_layer = self.output_layer

      elif decoder_type in [DecoderType.GREEDY, DecoderType.TRIE_GREEDY]:
        # Greedy
        helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(
            self.embedding_decoder, start_tokens, end_token)
        output_layer = self.output_layer

      if decoder_type in [
          DecoderType.TRAINING, DecoderType.SAMPLE, DecoderType.GREEDY
      ]:
        # Decoder
        my_decoder = tf.contrib.seq2seq.BasicDecoder(
            cell, helper, decoder_initial_state,
            output_layer=output_layer)  # applied per timestep

      elif decoder_type in [DecoderType.TRIE_GREEDY, DecoderType.TRIE_SAMPLE]:

        assert self.trie is not None

        my_decoder = trie_decoder_utils.TrieSamplerDecoder(
            trie=self.trie,
            cell=cell,
            helper=helper,
            initial_state=decoder_initial_state,
            trie_exclude=self.iterator.trie_exclude,
            output_layer=output_layer)

      elif decoder_type == DecoderType.DIVERSE_BEAM_SEARCH:
        # Diverse Beam Search decoder
        my_decoder = diverse_decoder_utils.DiverseBeamSearchDecoder(
            maximum_iterations=maximum_iterations,
            decoder_scope=decoder_scope,
            decoding_iterations=hparams.diverse_beam_search_iterations,
            cell=cell,
            embedding=self.embedding_decoder,
            start_tokens=start_tokens,
            end_token=end_token,
            initial_state=decoder_initial_state,
            beam_width=hparams.beam_width,
            output_layer=self.output_layer,
            length_penalty_weight=hparams.length_penalty_weight)

      elif decoder_type == DecoderType.BEAM_SEARCH:
        # Beam Search decoder
        my_decoder = tf.contrib.seq2seq.BeamSearchDecoder(
            cell=cell,
            embedding=self.embedding_decoder,
            start_tokens=start_tokens,
            end_token=end_token,
            initial_state=decoder_initial_state,
            beam_width=hparams.beam_width,
            output_layer=self.output_layer,
            length_penalty_weight=hparams.length_penalty_weight)

      elif decoder_type == DecoderType.TRIE_BEAM_SEARCH:
        assert self.trie is not None

        my_decoder = trie_decoder_utils.TrieBeamSearchDecoder(
            cell=cell,
            embedding=self.embedding_decoder,
            start_tokens=start_tokens,
            end_token=end_token,
            initial_state=decoder_initial_state,
            beam_width=hparams.beam_width,
            output_layer=self.output_layer,
            length_penalty_weight=hparams.length_penalty_weight,
            trie=self.trie,
            trie_exclude=self.iterator.trie_exclude)

      # Dynamic decoding
      outputs, final_context_state, _ = tf.contrib.seq2seq.dynamic_decode(
          my_decoder,
          maximum_iterations=maximum_iterations,
          output_time_major=True,
          swap_memory=True,
          scope=decoder_scope)

      if decoder_type == DecoderType.TRAINING:
        sample_id = outputs.sample_id

        # Note: there's a subtle difference here between train and inference.
        # We could have set output_layer when create my_decoder
        #   and shared more code between train and inference.
        # We chose to apply the output_layer to all timesteps for speed:
        #   10% improvements for small models & 20% for larger ones.
        # If memory is a concern, we should apply output_layer per timestep.
        logits = self.output_layer(outputs.rnn_output)

      elif decoder_type in [
          DecoderType.GREEDY, DecoderType.SAMPLE, DecoderType.TRIE_GREEDY,
          DecoderType.TRIE_SAMPLE
      ]:
        logits = outputs.rnn_output
        sample_id = outputs.sample_id

      elif decoder_type in [
          DecoderType.BEAM_SEARCH,
          DecoderType.TRIE_BEAM_SEARCH,
          DecoderType.DIVERSE_BEAM_SEARCH,
      ]:
        logits = tf.no_op()
        sample_id = outputs.predicted_ids

    return logits, sample_id, final_context_state

  def get_sequence_length(self, hparams, tokens):
    """Given an array of tokens, returns the length of each one.

    Args:
      hparams: hyperparameters object.
      tokens: a numpy array of shape=(batch_size, max_seq_len)

    Returns:
      sequence_length: a numpy array of shape=(batch_size)
    """
    batch_size = tokens.get_shape()[0].value

    def get_sequence_length_py(tokens):
      lengths = []
      for line in tokens:
        line = [token.decode('utf-8') for token in line]
        if hparams.eos in line:
          lengths.append(line.index(hparams.eos) + 1)
        else:
          lengths.append(len(line))
      return np.array(lengths, dtype=np.int32)

    sequence_length = tf.py_func(get_sequence_length_py, [tokens], tf.int32,
                                 'GetSequenceLength')
    sequence_length.set_shape([batch_size])
    return sequence_length

  def tokens_to_strings(self, all_tokens, eos):
    """Convert a numpy matrix of tokens to an array of strings

    Args:
      all_tokens: tokens as a numpy array of shape [batch_size, max_seq_len]
      eos: a string representing the end-of-sequence token.

    Returns:
      strings: a numpy array of strings of shape [batch_size]
    """

    strings = []
    for tokens in all_tokens:
      try:
        tokens = [token.decode('utf-8') for token in tokens]
        if eos in tokens:
          length = tokens.index(eos)
        else:
          length = len(tokens) + 1
        string = u''.join(tokens[:length])
      except UnicodeEncodeError as e:
        tf.logging.error(e)
        tf.logging.error(repr(tokens))
      except UnicodeDecodeError as e:
        tf.logging.error(e)
        tf.logging.error(repr(tokens))
      except TypeError as e:
        tf.logging.error(e)
        tf.logging.error(repr(tokens))

      string = string.replace(u'\u2581', u' ').lstrip()

      strings.append(string)
    return np.array(strings, dtype=np.object)

  def compute_rewards(self, questions, doc_ids):
    """Compute rewards by calling a environment server.

    Args:
      questions: an array of shape=(batch_size,) containing the question
          strings.
      doc_ids: an array of shape=(batch_size,) containing the doc ids that will
          be used by the environment server to answer the question.

    Returns:
       rewards: an array of shape=(batch_size) containing the rewards (normally,
           f1 scores of each question.
       answer: an array of shape(batch_size) containing the answer strings for
           the questions.
    """

    batch_size = questions.get_shape()[0].value

    rewards, _, answers = tf.py_func(
        self._environment_reward_fn, [questions, doc_ids],
        (tf.float32, tf.float32, tf.string), 'CallEnvironment')

    rewards.set_shape([batch_size])
    answers.set_shape([batch_size])

    return rewards, answers

  def get_max_time(self, tensor):
    return tensor.shape[0].value or tf.shape(tensor)[0]

  @abc.abstractmethod
  def _build_decoder_cell(self, hparams, encoder_outputs, encoder_state,
                          source_sequence_length):
    """Subclass must implement this.

    Args:
      hparams: Hyperparameters configurations.
      encoder_outputs: The outputs of encoder for every time step.
      encoder_state: The final state of the encoder.
      source_sequence_length: sequence length of encoder_outputs.

    Returns:
      A tuple of a multi-layer RNN cell used by decoder
        and the initial state of the decoder RNN.
    """
    pass

  def init_weights(self, shape):
    """Weight initialization using a normal distribution."""
    weights = tf.random_normal(shape, stddev=0.1)
    return tf.Variable(weights)

  def _value_network(self, question_embeddings):
    """A feedforward neural net that takes as input the original question and
    outputs a prediction for the reward.

    Args:
      question_embeddings: original question embeddings of shape=
        [batch_size,embeddings_dimension]

    Returns:
      The logits of shape=[batch_size]

    """
    layer_1 = tf.add(tf.matmul(question_embeddings, self.pw_1), self.pb_1)
    layer_1 = tf.tanh(layer_1)
    layer_2 = tf.add(tf.matmul(layer_1, self.pw_2), self.pb_2)
    layer_2 = tf.sigmoid(layer_2)
    logits = tf.reshape(layer_2, shape=[-1])

    return logits

  def _compute_loss(self, hparams, logits, sample_ids, sample_words, rewards,
                    question_embeddings, train_summaries):
    """Compute optimization loss."""
    if hparams.use_rl:
      target_output = sample_ids
      sequence_length = self.get_sequence_length(hparams, sample_words)
      losses, advantages = self._compute_loss_offset_and_advantages(
          rewards=rewards,
          baseline_type=hparams.baseline_type,
          replication_factor=hparams.replication_factor,
          question_embeddings=question_embeddings,
          train_summaries=train_summaries)
    else:
      target_output = self.iterator.target_output
      sequence_length = self.iterator.target_sequence_length
      losses = 0.0
      advantages = None

    if hparams.server_mode:
      advantages = rewards

    # Make shape [max_time, batch_size].
    target_output = tf.transpose(target_output, name='transpose_targets')
    losses += loss_utils.cross_entropy_sequence_loss(
        logits=logits,
        targets=target_output,
        sequence_length=sequence_length,
        weights=advantages)

    if hparams.entropy_regularization_weight > 0:
      entropy_reg = loss_utils.entropy_regularization(
          logits=logits, sequence_length=sequence_length
      ) * hparams.entropy_regularization_weight
      losses -= entropy_reg
      train_summaries.append(
          tf.summary.histogram('Entropy_Regularization',
                               tf.to_float(entropy_reg)))

    average_length = tf.reduce_mean(tf.to_float(sequence_length))
    train_summaries.append(tf.summary.scalar('AverageLength', average_length))

    # In RL training, normalize the loss by sequence length, otherwise by batch.
    if hparams.use_rl or hparams.server_mode:
      losses /= tf.to_float(sequence_length + 1)
      loss = tf.reduce_sum(losses)
    else:
      loss = tf.reduce_sum(losses) / tf.to_float(self.batch_size)
    return loss

  def _compute_loss_offset_and_advantages(self,
                                          rewards,
                                          baseline_type=2,
                                          replication_factor=1,
                                          question_embeddings=None,
                                          train_summaries=None):
    """Compute the baseline and apply it to the rewards.

    Args:
      rewards: A tensor of shape [B].
      baseline_type: int that selects the baseline to apply; possible values
        0: Computes the baseline as average reward per source.
        1: Computes the baseline using a value network.
        2: This baseline is just the average reward over the whole batch. So
           this baseline may combine averages of different sources (depending on
           replication).
        Otherwise: ignore baseline and return rewards as they are.
      replication_factor: int; how many copies of each input to expect.
      question_embeddings: A tensor of embeddings used for the value network.
      train_summaries: this is passed around to collect summaries for
                       TensorBoard.

    Returns:
      A tuple consisting of:
        losses: The losses of the value network (a tensor of shape [B]) when the
                value network is used; otherwise 0.0.
        rewards: A tensor of shape [B] that contains rewards with baseline
                 subtracted.
    """
    losses = 0.0
    if baseline_type == 0:
      baseline = tf.reshape(rewards, [-1, replication_factor])
      baseline = tf.reduce_mean(baseline, 1, keep_dims=True)
      baseline = tf.tile(baseline, [1, replication_factor])
      baseline = tf.reshape(baseline, [-1])
    elif baseline_type == 1:
      # Initialize the weights of the value network
      n_dim = question_embeddings.get_shape()[1].value
      self.pw_1 = self.init_weights((n_dim, n_dim))
      self.pb_1 = self.init_weights((n_dim,))
      self.pw_2 = self.init_weights((n_dim, 1))
      self.pb_2 = self.init_weights((1,))

      # The gradient here is stopped because we do not want a degenerated
      # cooperation between policy and value networks in which they always
      # produce predicted and real rewards that are close to zero.
      # We might want to remove this in the future but leaving it here
      # normally leads to a more stable training.
      question_embeddings = tf.stop_gradient(question_embeddings)
      baseline = self._value_network(question_embeddings)

      losses_baseline = tf.pow(rewards - baseline, 2)
      losses += losses_baseline
      if train_summaries:
        train_summaries.append(
            tf.summary.histogram('Losses_Baseline',
                                 tf.to_float(losses_baseline)))
    elif baseline_type == 2:
      # baseline has shape [].
      baseline = tf.reduce_mean(rewards)
    else:
      baseline = 0.0

    return losses, rewards - baseline

  def _get_infer_summary(self, hparams):
    return tf.no_op()

  def infer(self, sess):
    assert self.mode == tf.contrib.learn.ModeKeys.INFER

    return sess.run([
        self.logits, self.infer_summary, self.sample_id, self.sample_words,
        self.rewards
    ])

class Model(BaseModel):
  """Sequence-to-sequence dynamic model.

  This class implements a multi-layer recurrent neural network as encoder,
  and a multi-layer recurrent neural network decoder.
  """

  def _build_encoder(self, hparams):
    """Build an encoder."""
    num_layers = self.num_encoder_layers
    num_residual_layers = self.num_encoder_residual_layers

    iterator = self.iterator

    source = iterator.source
    # Make shape [max_time, batch_size].
    source = tf.transpose(source)

    with tf.variable_scope('encoder') as scope:
      dtype = scope.dtype
      # Look up embedding, emp_inp: [max_time, batch_size, num_units]
      encoder_emb_inp = tf.nn.embedding_lookup(self.embedding_encoder, source)

      # encoder_outputs: [max_time, batch_size, num_units]
      if hparams.encoder_type == 'uni':
        utils.print_out('  num_layers={}, num_residual_layers={}'.format(
            num_layers, num_residual_layers))
        cell = self._build_encoder_cell(hparams, num_layers,
                                        num_residual_layers)

        encoder_outputs, encoder_state = tf.nn.dynamic_rnn(
            cell,
            encoder_emb_inp,
            dtype=dtype,
            sequence_length=iterator.source_sequence_length,
            time_major=True,
            swap_memory=True)
      elif hparams.encoder_type == 'bi':
        num_bi_layers = int(num_layers / 2)
        num_bi_residual_layers = int(num_residual_layers / 2)
        utils.print_out('  num_bi_layers={}, num_bi_residual_layers={}'.format(
            num_bi_layers, num_bi_residual_layers))

        encoder_outputs, bi_encoder_state = (
            self._build_bidirectional_rnn(
                inputs=encoder_emb_inp,
                sequence_length=iterator.source_sequence_length,
                dtype=dtype,
                hparams=hparams,
                num_bi_layers=num_bi_layers,
                num_bi_residual_layers=num_bi_residual_layers))

        if num_bi_layers == 1:
          encoder_state = bi_encoder_state
        else:
          # alternatively concat forward and backward states
          encoder_state = []
          for layer_id in range(num_bi_layers):
            encoder_state.append(bi_encoder_state[0][layer_id])  # forward
            encoder_state.append(bi_encoder_state[1][layer_id])  # backward
          encoder_state = tuple(encoder_state)
      else:
        raise ValueError('Unknown encoder_type {}'.format(hparams.encoder_type))
    return encoder_outputs, encoder_state

  def _build_bidirectional_rnn(self,
                               inputs,
                               sequence_length,
                               dtype,
                               hparams,
                               num_bi_layers,
                               num_bi_residual_layers,
                               base_gpu=0):
    """Create and call biddirectional RNN cells.

    Args:
      num_residual_layers: Number of residual layers from top to bottom. For
        example, if `num_bi_layers=4` and `num_residual_layers=2`, the last 2
        RNN layers in each RNN cell will be wrapped with `ResidualWrapper`.
      base_gpu: The gpu device id to use for the first forward RNN layer. The
        i-th forward RNN layer will use `(base_gpu + i) % num_gpus` as its
        device id. The `base_gpu` for backward RNN cell is `(base_gpu +
        num_bi_layers)`.

    Returns:
      The concatenated bidirectional output and the bidirectional RNN cell"s
      state.
    """
    # Construct forward and backward cells
    fw_cell = self._build_encoder_cell(
        hparams, num_bi_layers, num_bi_residual_layers, base_gpu=base_gpu)
    bw_cell = self._build_encoder_cell(
        hparams,
        num_bi_layers,
        num_bi_residual_layers,
        base_gpu=(base_gpu + num_bi_layers))

    bi_outputs, bi_state = tf.nn.bidirectional_dynamic_rnn(
        fw_cell,
        bw_cell,
        inputs,
        dtype=dtype,
        sequence_length=sequence_length,
        time_major=True,
        swap_memory=True)

    return tf.concat(bi_outputs, -1), bi_state

  def _build_decoder_cell(self, hparams, encoder_outputs, encoder_state,
                          source_sequence_length):
    """Build an RNN cell that can be used by decoder."""
    # We only make use of encoder_outputs in attention-based models
    if hparams.attention:
      raise ValueError('BasicModel does not support attention.')

    cell = model_helper.create_rnn_cell(
        unit_type=hparams.unit_type,
        num_units=hparams.num_units,
        num_layers=self.num_decoder_layers,
        num_residual_layers=self.num_decoder_residual_layers,
        forget_bias=hparams.forget_bias,
        dropout=hparams.dropout,
        num_gpus=self.num_gpus,
        mode=self.mode,
        single_cell_fn=self.single_cell_fn)

    # For beam search, we need to replicate encoder infos beam_width times
    if self.mode == tf.contrib.learn.ModeKeys.INFER and hparams.beam_width > 0:
      decoder_initial_state = tf.contrib.seq2seq.tile_batch(
          encoder_state, multiplier=hparams.beam_width)
    else:
      decoder_initial_state = encoder_state

    return cell, decoder_initial_state


text:
package com.greenpepper.document;

import com.greenpepper.Example;
import com.greenpepper.util.ExampleUtil;
import com.greenpepper.util.Tables;
import com.greenpepper.util.TestCase;

public class EagerFilterTest extends TestCase
{

    public void testShouldContinueUntilNothingIsLeftToFilter()
    {
        Tables tables = Tables.parse(
            "****\n" +
            "[Begin Info]\n" +
            "****\n" +
            "[should not be interpreted]" +
            "****\n" +
            "[End Info]\n" +
            "****\n" +
            "[ a table ]\n" +
            "****\n" +
            "[Begin Info]\n" +
            "****\n" +
            "[should not be interpreted]" +
            "****\n" +
            "[End Info]\n" +
            "****\n" +
            "[Begin Info]\n" +
            "****\n" +
            "[should not be interpreted]" +
            "****\n" +
            "[End Info]\n" +
            "****\n" +
            "[ the last table ]\n"
        );

        ExampleFilter filter=new EagerFilter( new CommentTableFilter() );
        Example next = filter.filter( tables );
        assertEquals( "a table", ExampleUtil.contentOf( next.at( 0, 0, 0 ) ) );
        next = filter.filter( next.nextSibling() );
        assertEquals( "the last table", ExampleUtil.contentOf( next.at( 0, 0, 0 ) ) );
    }
}


text:
$(function() {

  Dropzone.autoDiscover = false;
  $('#xlsx-dropzone').dropzone({
    method: 'POST',
    url: '/api/upload',
    paramName: 'xlsx',
    success: function(file, response) {
      calculateDiagram(response);
    },
    complete: function(file) {
      this.removeFile(file);
    }
  });
});