text:
package features

import (
	"testing"

	backendconfigv1 "k8s.io/ingress-gce/pkg/apis/backendconfig/v1"
	"k8s.io/ingress-gce/pkg/composite"
	"k8s.io/ingress-gce/pkg/utils"
)

func TestEnsureDraining(t *testing.T) {
	testCases := []struct {
		desc           string
		sp             utils.ServicePort
		be             *composite.BackendService
		updateExpected bool
	}{
		{
			desc: "connection draining timeout setting is defined on serviceport but missing from spec, update needed",
			sp: utils.ServicePort{
				BackendConfig: &backendconfigv1.BackendConfig{
					Spec: backendconfigv1.BackendConfigSpec{
						ConnectionDraining: &backendconfigv1.ConnectionDrainingConfig{
							DrainingTimeoutSec: 111,
						},
					},
				},
			},
			be: &composite.BackendService{
				ConnectionDraining: &composite.ConnectionDraining{},
			},
			updateExpected: true,
		},
		{
			desc: "connection draining setting are missing from spec, no update needed",
			sp: utils.ServicePort{
				BackendConfig: &backendconfigv1.BackendConfig{
					Spec: backendconfigv1.BackendConfigSpec{},
				},
			},
			be: &composite.BackendService{
				ConnectionDraining: &composite.ConnectionDraining{
					DrainingTimeoutSec: 111,
				},
			},
			updateExpected: false,
		},
		{
			desc: "connection draining settings are identical, no update needed",
			sp: utils.ServicePort{
				BackendConfig: &backendconfigv1.BackendConfig{
					Spec: backendconfigv1.BackendConfigSpec{
						ConnectionDraining: &backendconfigv1.ConnectionDrainingConfig{
							DrainingTimeoutSec: 111,
						},
					},
				},
			},
			be: &composite.BackendService{
				ConnectionDraining: &composite.ConnectionDraining{
					DrainingTimeoutSec: 111,
				},
			},
			updateExpected: false,
		},
		{
			desc: "connection draining settings differs, update needed",
			sp: utils.ServicePort{
				BackendConfig: &backendconfigv1.BackendConfig{
					Spec: backendconfigv1.BackendConfigSpec{
						ConnectionDraining: &backendconfigv1.ConnectionDrainingConfig{
							DrainingTimeoutSec: 111,
						},
					},
				},
			},
			be: &composite.BackendService{
				ConnectionDraining: &composite.ConnectionDraining{
					DrainingTimeoutSec: 222,
				},
			},
			updateExpected: true,
		},
	}

	for _, tc := range testCases {
		t.Run(tc.desc, func(t *testing.T) {
			result := EnsureDraining(tc.sp, tc.be)
			if result != tc.updateExpected {
				t.Errorf("%v: expected %v but got %v", tc.desc, tc.updateExpected, result)
			}
		})
	}
}


text:
namespace Utility{

//! The physical constants class
class PhysicalConstants : public RawPhysicalConstants
{
private:

  // The MeV-s unit
  typedef UnitTraits<Units::MegaElectronVolt>::template GetMultipliedUnitType<boost::units::cgs::time>::type MeVSecond;

  // The MeV/K unit
  typedef UnitTraits<Units::MegaElectronVolt>::template GetMultipliedUnitType<UnitTraits<boost::units::si::temperature>::InverseUnit>::type MeVPerK;

public:

  //! The speed of light (cm/s)
  static const boost::units::quantity<boost::units::cgs::velocity> speed_of_light_q;

  //! Planck's constant (MeV-s)
  static const boost::units::quantity<MeVSecond> planck_constant_q;

  //! Plank's constant by pi (MeV-s)
  static const boost::units::quantity<MeVSecond> h_bar_q;

  //! Rest mass energy of electron (MeV)
  static const boost::units::quantity<Units::MegaElectronVolt> electron_rest_mass_energy_q;

  //! Rest mass energy of neutron (MeV)
  static const boost::units::quantity<Units::MegaElectronVolt> neutron_rest_mass_energy_q;

  //! The rest mass of neutron (amu)
  static const boost::units::quantity<Units::AtomicMass> neutron_rest_mass_amu_q;

  //! The classical electron radius (cm)
  static const boost::units::quantity<boost::units::cgs::length> classical_electron_radius_q;

  //! The boltzmann constant (MeV/K)
  static const boost::units::quantity<MeVPerK> boltzmann_constant_q;
};

} // end Utility namespace

#endif // end UTILITY_PHYSICAL_CONSTANTS_HPP

//---------------------------------------------------------------------------//
// end Utility_PhysicalConstants.hpp
//---------------------------------------------------------------------------//

redpajama_set_name: RedPajamaGithub


text:
/*
 * Vector rendering for IE7-8 through VMF.Leaflet.
 * Thanks to Dmitry Baranovsky and his Raphael library for inspiration!
 */

F.Browser.vml = !F.Browser.svg && (function () {
	try {
		var div = document.createElement('div');
		div.innerHTML = '<v:shape adj="1"/>';

		var shape = div.firstChild;
		shape.style.behavior = 'url(#default#VML)';

		return shape && (typeof shape.adj === 'object');

	} catch (e) {
		return false;
	}
}());

// redefine some SVG methods to handle VML syntax which is similar but with some differences
F.Leaflet.SVG.include(!F.Browser.vml ? {} : {

	_initContainer: function () {
		this._container = F.DomUtil.create('div', 'vml-container');

		this._paths = {};
		this._initEvents();
	},

	_update: function () {
		if (this._map._animatingZoom) { return; }
		F.Leaflet.Renderer.prototype._update.call(this);
	},

	_initPath: function (layer) {
		var container = layer._container = F.Leaflet.SVG.create('shape');

		F.DomUtil.addClass(container, 'vml-shape ' + (this.options.className || ''));

		container.coordsize = '1 1';

		layer._path = F.Leaflet.SVG.create('path');
		container.appendChild(layer._path);

		this._updateStyle(layer);
	},

	_addPath: function (layer) {
		var container = layer._container;
		this._container.appendChild(container);
		this._paths[F.stamp(container)] = layer;
	},

	_removePath: function (layer) {
		var container = layer._container;
		F.DomUtil.remove(container);
		delete this._paths[F.stamp(container)];
	},

	_updateStyle: function (layer) {
		var stroke = layer._stroke,
		    fill = layer._fill,
		    options = layer.options,
		    container = layer._container;

		container.stroked = !!options.stroke;
		container.filled = !!options.fill;

		if (options.stroke) {
			if (!stroke) {
				stroke = layer._stroke = F.Leaflet.SVG.create('stroke');
				container.appendChild(stroke);
			}
			stroke.weight = options.weight + 'px';
			stroke.color = options.color;
			stroke.opacity = options.opacity;

			if (options.dashArray) {
				stroke.dashStyle = F.Util.isArray(options.dashArray) ?
				    options.dashArray.join(' ') :
				    options.dashArray.replace(/( *, *)/g, ' ');
			} else {
				stroke.dashStyle = '';
			}
			stroke.endcap = options.lineCap.replace('butt', 'flat');
			stroke.joinstyle = options.lineJoin;

		} else if (stroke) {
			container.removeChild(stroke);
			layer._stroke = null;
		}

		if (options.fill) {
			if (!fill) {
				fill = layer._fill = F.Leaflet.SVG.create('fill');
				container.appendChild(fill);
			}
			fill.color = options.fillColor || options.color;
			fill.opacity = options.fillOpacity;

		} else if (fill) {
			container.removeChild(fill);
			layer._fill = null;
		}
	},

	_updateCircle: function (layer) {
		var p = layer._point,
		    r = Math.round(layer._radius),
		    r2 = Math.round(layer._radiusY || r);

		this._setPath(layer, layer._empty() ? 'M0 0' :
				'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r2 + ' 0,' + (65535 * 360));
	},

	_setPath: function (layer, path) {
		layer._path.v = path;
	}
});

if (F.Browser.vml) {
	F.Leaflet.SVG.create = (function () {
		try {
			document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml');
			return function (name) {
				return document.createElement('<lvml:' + name + ' class="lvml">');
			};
		} catch (e) {
			return function (name) {
				return document.createElement('<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">');
			};
		}
	})();
}


text:
package com.tle.admin.baseentity;

import com.dytech.gui.Changeable;
import com.dytech.gui.ComponentHelper;
import com.dytech.gui.JStatusBar;
import com.tle.admin.Driver;
import com.tle.admin.common.gui.EditorHelper;
import com.tle.admin.gui.EditorException;
import com.tle.admin.gui.EditorInterface;
import com.tle.admin.gui.common.JChangeDetectorPanel;
import com.tle.admin.gui.common.actions.CloseAction;
import com.tle.admin.gui.common.actions.SaveAction;
import com.tle.admin.gui.common.actions.TLEAction;
import com.tle.admin.tools.common.BaseEntityTool;
import com.tle.beans.entity.BaseEntity;
import com.tle.beans.entity.BaseEntityLabel;
import com.tle.client.gui.StatusBarContainer;
import com.tle.common.Check;
import com.tle.common.EntityPack;
import com.tle.common.NameValue;
import com.tle.common.applet.client.ClientService;
import com.tle.common.beans.exception.InvalidDataException;
import com.tle.common.beans.exception.ValidationError;
import com.tle.common.i18n.CurrentLocale;
import com.tle.core.plugins.AbstractPluginService;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.text.JTextComponent;
import net.miginfocom.swing.MigLayout;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/** @author Nicholas Read */
@SuppressWarnings("nls")
public abstract class BaseEntityEditor<T extends BaseEntity>
    implements EditorInterface, DynamicTabService, StatusBarContainer {
  protected static final Log LOGGER = LogFactory.getLog(BaseEntityEditor.class);

  protected final EditorState<T> state;

  protected JDialog dialog;
  private JPanel content;
  protected Changeable changeDetector;

  protected List<? extends BaseEntityTab<T>> btabs;
  private List<? extends BaseEntityTab<T>> tabLoadSaveOrder;
  protected JTabbedPane tabs;

  private final BaseEntityTool<T> tool;
  protected final ClientService clientService;

  protected JStatusBar statusbar;
  @Deprecated protected Driver driver;
  protected AbstractDetailsTab<T> detailsTab;
  private String KEY_PFX = AbstractPluginService.getMyPluginId(getClass()) + ".";

  protected String getString(String key) {
    return CurrentLocale.get(KEY_PFX + key);
  }

  public BaseEntityEditor(BaseEntityTool<T> tool, boolean readonly) {
    this.tool = tool;
    this.driver = tool.getDriver();
    this.clientService = tool.getClientService();

    state = new EditorState<T>();
    state.setReadonly(readonly);
  }

  private void setupGUI() {
    tabs = new JTabbedPane();
    tabs = new JTabbedPane(SwingConstants.TOP, JTabbedPane.SCROLL_TAB_LAYOUT);

    statusbar = new JStatusBar(EditorHelper.getStatusBarSpinner());

    JButton saveButton = new JButton(saveAction);
    JButton closeButton = new JButton(closeAction);

    saveAction.setEnabled(!state.isReadonly());

    setup();

    detailsTab = constructDetailsTab();

    addTabs();

    detailsTab.addNameListener(new NameChangeListener());

    JChangeDetectorPanel content1 = new JChangeDetectorPanel();
    changeDetector = content1;
    content1.setLayout(new MigLayout("wrap", "[][]"));
    content1.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

    JComponent main;
    if (btabs.size() == 1) {
      main = btabs.get(0).getComponent();
    } else {
      main = tabs;
    }
    content1.add(main, "grow, pushy, span 2");
    content1.add(saveButton, "pushx, align right");
    content1.add(closeButton);

    this.content = statusbar.attachToPanel(content1);
  }

  protected void addTabs() {
    btabs = getTabs();
    tabLoadSaveOrder = getTabLoadOrder(btabs);

    for (BaseEntityTab<T> tab : btabs) {
      addTab(tab);
    }
  }

  protected List<? extends BaseEntityTab<T>> getTabLoadOrder(
      List<? extends BaseEntityTab<T>> btabs2) {
    return btabs;
  }

  public void addTab(BaseEntityTab<T> tab) {
    tab.setState(state);
    tab.setDriver(driver);
    tab.setStatusBar(statusbar);
    tab.setDynamicTabService(this);
    tab.init(dialog);

    addTab(tab.getComponent(), tab.getTitle(), -1);
  }

  @Override
  public void addTab(JComponent comp, String tabTitle, int index) {
    comp.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    if (index >= 0) {
      tabs.insertTab(tabTitle, null, comp, null, index);
    } else {
      tabs.addTab(tabTitle, comp);
    }
  }

  @Override
  public void removeTab(JComponent comp) {
    tabs.remove(comp);
  }

  private String getCurrentName() {
    T ent = getEntity();
    return CurrentLocale.get(ent.getName(), null);
  }

  protected void setup() {
    // TO BE OVERRIDEN
  }

  protected abstract AbstractDetailsTab<T> constructDetailsTab();

  protected abstract String getEntityName();

  protected abstract String getWindowTitle();

  protected abstract List<? extends BaseEntityTab<T>> getTabs();

  /**
   * Shows the schema manager window.
   *
   * @return true if the schema was saved/added.
   */
  public boolean showEditor(Component parent) {
    dialog = ComponentHelper.createJDialog(parent);

    for (BaseEntityTab<T> tab : btabs) {
      tab.setParent(dialog);
    }

    dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    dialog.setContentPane(content);
    dialog.setModal(true);

    refreshWindowTitle(null);
    ComponentHelper.percentageOfScreen(dialog, 0.9f, 0.9f);
    ComponentHelper.centreOnScreen(dialog);
    EditorHelper.listenForClosing(dialog, this);

    dialog.setVisible(true);
    dialog = null;

    return state.isSaved();
  }

  /** Loads the given entity in the editor. */
  public void load(EntityPack<T> entityPack, boolean isLoaded) {
    state.setEntityPack(entityPack);
    state.setLoaded(isLoaded);

    setupGUI();

    for (BaseEntityTab<T> tab : tabLoadSaveOrder) {
      tab.load();
    }

    clearChanges();
  }

  public void refreshWindowTitle(String newTitle) {
    if (dialog != null) {
      if (newTitle == null) {
        newTitle = getCurrentName();
      }

      final String key =
          "com.tle.admin.baseentity.baseentityeditor.title-for-"
              + (Check.isEmpty(newTitle) ? "unnamed" : "named")
              + "-entity"; //$NON-NLS-2$ //$NON-NLS-3$
      dialog.setTitle(
          CurrentLocale.get(key, getWindowTitle(), driver.getInstitutionName(), newTitle));
    }
  }

  public NameValue getEntityDetails() {
    return new NameValue(getCurrentName(), Long.toString(getEntity().getId()));
  }

  /*
   * (non-Javadoc)
   * @see com.dytech.edge.admin.gui.EditorInterface#getParentWindow()
   */
  @Override
  public Component getParentWindow() {
    return dialog;
  }

  /*
   * (non-Javadoc)
   * @see com.dytech.edge.admin.gui.EditorInterface#close()
   */
  @Override
  public void close(Integer confirmOption) {
    dialog.dispose();
  }

  /*
   * (non-Javadoc)
   * @see com.dytech.edge.admin.gui.EditorInterface#getStatusBar()
   */
  @Override
  public final JStatusBar getStatusBar() {
    return statusbar;
  }

  /*
   * (non-Javadoc)
   * @see com.dytech.edge.admin.gui.EditorInterface#isReadOnly()
   */
  @Override
  public final boolean isReadOnly() {
    return state.isReadonly();
  }

  @Override
  public final void unlock() {
    if (state.isLoaded()) {
      try {
        tool.cancelEdit(state.getEntity().getId());
      } catch (Exception ex) {
        LOGGER.warn("Problem unlocking schema", ex);
      }
    }
  }

  @Override
  public final void save() throws EditorException {
    for (BaseEntityTab<T> tab : tabLoadSaveOrder) {
      tab.save();
    }

    try {
      if (state.isLoaded()) {
        state.setEntity(tool.stopEdit(state.getEntityPack(), false));
      } else {
        T entity = state.getEntity();
        if (Check.isEmpty(entity.getOwner())) {
          entity.setOwner(driver.getLoggedInUserUUID());
        }

        BaseEntityLabel label = tool.add(state.getEntityPack(), true);
        entity.setId(label.getId());
        state.setLoaded(true);
      }

      state.setSaved(true);
      clearChanges();

      for (BaseEntityTab<T> tab : tabLoadSaveOrder) {
        tab.afterSave();
      }
    } catch (InvalidDataException ex) {
      for (ValidationError error : ex.getErrors()) {
        LOGGER.error(
            "Validation error in " + error.getField() + ": " + error.getMessage()); // $NON-NLS-2$
      }
      ValidationError error = ex.getErrors().get(0);
      throw new EditorException(
          "Validation error in " + error.getField() + ": " + error.getMessage());
    } catch (Exception ex) {
      throw new EditorException(tool.getSavingErrorMessage(), ex);
    }
  }

  @Override
  public final void validation() throws EditorException {
    int current = 0;

    try {
      for (BaseEntityTab<T> tab : btabs) {
        tab.validation();
        current++;
      }

      // If we get to here, all the tabs are valid.
    } catch (EditorException ex) {
      // If we get to here, one of the tabs is invalid.
      tabs.setSelectedIndex(current);
      throw ex;
    }
  }

  @Override
  public boolean beforeSaving() {
    return true;
  }

  private final TLEAction saveAction =
      new SaveAction() {
        private static final long serialVersionUID = 1L;

        @Override
        public void actionPerformed(ActionEvent e) {
          EditorHelper.onSave(BaseEntityEditor.this);
        }
      };

  private final TLEAction closeAction =
      new CloseAction() {
        private static final long serialVersionUID = 1L;

        @Override
        public void actionPerformed(ActionEvent e) {
          EditorHelper.onClose(BaseEntityEditor.this, null);
        }
      };

  protected class NameChangeListener extends KeyAdapter {
    @Override
    public void keyTyped(final KeyEvent e) {
      SwingUtilities.invokeLater(
          new Runnable() {
            @Override
            public void run() {
              String t = ((JTextComponent) e.getComponent()).getText();
              refreshWindowTitle(t);
            }
          });
    }
  }

  public interface AbstractDetailsTab<T> {
    void addNameListener(KeyListener listener);
  }

  protected T getEntity() {
    return state.getEntity();
  }

  public JDialog getDialog() {
    return dialog;
  }

  public JTabbedPane getTabbedPane() {
    return tabs;
  }

  @Override
  public void clearChanges() {
    changeDetector.clearChanges();
  }

  @Override
  public boolean hasDetectedChanges() {
    return changeDetector.hasDetectedChanges();
  }
}


text:
import { ChangeDetectionStrategy, Component, OnDestroy, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable, Subject } from 'rxjs';
import { mergeMap, share, takeUntil } from 'rxjs/operators';

import { JobsItem } from '@flink-runtime-web/interfaces';
import { JobService, StatusService } from '@flink-runtime-web/services';

@Component({
  selector: 'flink-overview',
  templateUrl: './overview.component.html',
  styleUrls: ['./overview.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class OverviewComponent implements OnInit, OnDestroy {
  public jobData$: Observable<JobsItem[]>;

  private readonly destroy$ = new Subject<void>();

  constructor(
    private readonly statusService: StatusService,
    private readonly jobService: JobService,
    private router: Router
  ) {}

  public ngOnInit(): void {
    this.jobData$ = this.statusService.refresh$.pipe(
      takeUntil(this.destroy$),
      mergeMap(() => this.jobService.loadJobs()),
      share()
    );
  }

  public ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }

  public navigateToJob(commands: string[]): void {
    this.router.navigate(commands).then();
  }
}


text:
import json
import os
import sqlite3
import sys
import yaml
from collections import namedtuple

path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../lib'))
sys.path.insert(1, path)
import processor
import tables

def namedtuple_factory(cursor, row):
    fields = [col[0] for col in cursor.description]
    Row = namedtuple("Row", fields)
    return Row(*row)

class BaseTestCase(object):

    def _query(self, q):
        return self.c.execute(q).fetchall()

    def _load(self, f):
        f = os.path.abspath(os.path.join(os.path.dirname(__file__), f))
        with open(f, 'r') as f:
            lines = f.readlines()
        return lines

    def _load_JSON(self, f):
        f = os.path.abspath(os.path.join(os.path.dirname(__file__), f))
        with open(f, 'r') as f:
            data = json.load(f)
        return data

    def _load_YAML(self, f):
        f = os.path.abspath(os.path.join(os.path.dirname(__file__), f))
        with open(f, 'r') as f:
            data = yaml.load(f.read())
        return data

    def setUp(self):
        self.conn = sqlite3.connect(':memory:')
        self.conn.row_factory = namedtuple_factory
        self.c = self.conn.cursor()
        tables.create(self.conn)

    def tearDown(self):
        self.conn.close()
        self.c = None


text:
package com.bitbreeds.webrtc.sctp.model;

public class FullBufferException extends RuntimeException {

    public FullBufferException(String message) {
        super(message);
    }
}


text:
package org.sleuthkit.autopsy.keywordsearch;

import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
import org.openide.util.NbBundle;
import org.sleuthkit.autopsy.coreutils.Logger;
import javax.swing.SwingWorker;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.api.progress.ProgressHandleFactory;
import org.openide.nodes.ChildFactory;
import org.openide.nodes.Children;
import org.openide.nodes.Node;
import org.openide.util.Cancellable;
import org.openide.util.lookup.Lookups;
import org.sleuthkit.autopsy.corecomponents.DataResultTopComponent;
import org.sleuthkit.autopsy.datamodel.AbstractAbstractFileNode;
import org.sleuthkit.autopsy.datamodel.AbstractFsContentNode;
import org.sleuthkit.autopsy.datamodel.KeyValue;
import org.sleuthkit.autopsy.datamodel.KeyValueNode;
import org.sleuthkit.autopsy.keywordsearch.KeywordSearchResultFactory.KeyValueQueryContent;
import org.sleuthkit.datamodel.AbstractFile;
import org.sleuthkit.datamodel.BlackboardArtifact;
import org.sleuthkit.datamodel.BlackboardAttribute;
import org.sleuthkit.datamodel.Content;

/**
 * Node factory that performs the keyword search and creates children nodes for
 each content.
 *
 * Responsible for assembling nodes and columns in the right way and performing
 * lazy queries as needed.
 */
class KeywordSearchResultFactory extends ChildFactory<KeyValueQueryContent> {

    //common properties (superset of all Node properties) to be displayed as columns
    //these are merged with FsContentPropertyType defined properties
    public static enum CommonPropertyTypes {

        KEYWORD {
                    @Override
                    public String toString() {
                        return BlackboardAttribute.ATTRIBUTE_TYPE.TSK_KEYWORD.getDisplayName();
                    }
                },
        REGEX {
                    @Override
                    public String toString() {
                        return BlackboardAttribute.ATTRIBUTE_TYPE.TSK_KEYWORD_REGEXP.getDisplayName();
                    }
                },
        CONTEXT {
                    @Override
                    public String toString() {
                        return BlackboardAttribute.ATTRIBUTE_TYPE.TSK_KEYWORD_PREVIEW.getDisplayName();
                    }
                },
    }
    private Collection<QueryRequest> queryRequests;
    private final DataResultTopComponent viewer; //viewer driving this child node factory
    private static final Logger logger = Logger.getLogger(KeywordSearchResultFactory.class.getName());

    KeywordSearchResultFactory(Collection<QueryRequest> queryRequests, DataResultTopComponent viewer) {
        this.queryRequests = queryRequests;
        this.viewer = viewer;
    }

    /**
     * call this at least for the parent Node, to make sure all common
     * properties are displayed as columns (since we are doing lazy child Node
     * load we need to preinitialize properties when sending parent Node)
     *
     * @param toSet property set map for a Node
     */
    public static void initCommonProperties(Map<String, Object> toSet) {
        CommonPropertyTypes[] commonTypes = CommonPropertyTypes.values();
        final int COMMON_PROPS_LEN = commonTypes.length;
        for (int i = 0; i < COMMON_PROPS_LEN; ++i) {
            toSet.put(commonTypes[i].toString(), "");
        }

        AbstractAbstractFileNode.AbstractFilePropertyType[] fsTypes = AbstractAbstractFileNode.AbstractFilePropertyType.values();
        final int FS_PROPS_LEN = fsTypes.length;
        for (int i = 0; i < FS_PROPS_LEN; ++i) {
            toSet.put(fsTypes[i].toString(), "");
        }
    }

    public static void setCommonProperty(Map<String, Object> toSet, CommonPropertyTypes type, String value) {
        final String typeStr = type.toString();
        toSet.put(typeStr, value);
    }

    public static void setCommonProperty(Map<String, Object> toSet, CommonPropertyTypes type, Boolean value) {
        final String typeStr = type.toString();
        toSet.put(typeStr, value);
    }

    @Override
    protected boolean createKeys(List<KeyValueQueryContent> toPopulate) {

        for (QueryRequest queryRequest : queryRequests) {
            Map<String, Object> map = queryRequest.getProperties();
            initCommonProperties(map);
            final String query = queryRequest.getQueryString();
            setCommonProperty(map, CommonPropertyTypes.KEYWORD, query);
            setCommonProperty(map, CommonPropertyTypes.REGEX, !queryRequest.getQuery().isLiteral());
            createFlatKeys(queryRequest, toPopulate);
        }

        return true;
    }

    /**
     *
     * @param queryRequest
     * @param toPopulate
     * @return
     */
    private boolean createFlatKeys(QueryRequest queryRequest, List<KeyValueQueryContent> toPopulate) {
        /**
         * Check the validity of the requested query.
         */
        final KeywordSearchQuery keywordSearchQuery = queryRequest.getQuery();
        if (!keywordSearchQuery.validate()) {
            //TODO mark the particular query node RED
            return false;
        }

        /**
         * Execute the requested query.
         */
        QueryResults queryResults;
        try {
            queryResults = keywordSearchQuery.performQuery();
        } catch (NoOpenCoreException ex) {
            logger.log(Level.SEVERE, "Could not perform the query " + keywordSearchQuery.getQueryString(), ex); //NON-NLS
            return false;
        }

        int id = 0;
        List<KeyValueQueryContent> tempList = new ArrayList<>();
        for (KeywordHit hit : getOneHitPerObject(queryResults)) {
            /**
             * Get file properties.
             */
            Map<String, Object> properties = new LinkedHashMap<>();
            Content content = hit.getContent();
            if (content instanceof AbstractFile) {
                AbstractFsContentNode.fillPropertyMap(properties, (AbstractFile)content);
            }
            else {
                properties.put(AbstractAbstractFileNode.AbstractFilePropertyType.LOCATION.toString(), content.getName());
            }

            /**
             * Add a snippet property, if available.
             */
            if (hit.hasSnippet()) {
                setCommonProperty(properties, CommonPropertyTypes.CONTEXT, hit.getSnippet());
            }

            //@@@ USE ConentHit in UniqueFileMap instead of the below search
            //get unique match result files
            // BC: @@@ THis is really ineffecient.  We should keep track of this when
            // we flattened the list of files to the unique files.
            final String highlightQueryEscaped = getHighlightQuery(keywordSearchQuery, keywordSearchQuery.isLiteral(), queryResults, content);

            String name = content.getName();
            if (hit.isArtifactHit())
                name = hit.getArtifact().getDisplayName() + " Artifact"; // NON-NLS

            tempList.add(new KeyValueQueryContent(name, properties, ++id, hit.getSolrObjectId(), content, highlightQueryEscaped, keywordSearchQuery, queryResults));
        }

        // Add all the nodes to toPopulate at once. Minimizes node creation
        // EDT threads, which can slow and/or hang the UI on large queries.
        toPopulate.addAll(tempList);

        //write to bb
        //cannot reuse snippet in BlackboardResultWriter
        //because for regex searches in UI we compress results by showing a content per regex once (even if multiple term hits)
        //whereas in bb we write every hit per content separately
        new BlackboardResultWriter(queryResults, queryRequest.getQuery().getKeywordList().getName()).execute();

        return true;
    }

    /**
     * This method returns a collection of KeywordHits with lowest SolrObjectID-
     * Chunk-ID combination. The output generated is consistent across multiple
     * runs.
     * @param queryResults QueryResult object
     * @return A consistent collection of keyword hits
     */
    Collection<KeywordHit> getOneHitPerObject(QueryResults queryResults) {
        HashMap<Long, KeywordHit> hits = new HashMap<Long, KeywordHit>();
        for (Keyword keyWord : queryResults.getKeywords()) {
            for (KeywordHit hit : queryResults.getResults(keyWord)) {
                // add hit with lowest SolrObjectID-Chunk-ID combination.
                if (!hits.containsKey(hit.getSolrObjectId())) {
                    hits.put(hit.getSolrObjectId(), hit);
                } else {
                    if (hit.getChunkId() < hits.get(hit.getSolrObjectId()).getChunkId()) {
                        hits.put(hit.getSolrObjectId(), hit);
                    }
                }
            }
        }
        return hits.values();
    }

    /**
     * Return the string used to later have SOLR highlight the document with.
     *
     * @param query
     * @param literal_query
     * @param queryResults
     * @param file
     * @return
     */
    private String getHighlightQuery(KeywordSearchQuery query, boolean literal_query, QueryResults queryResults, Content content) {
        String highlightQueryEscaped;
        if (literal_query) {
            //literal, treat as non-regex, non-term component query
            highlightQueryEscaped = query.getQueryString();
        } else {
            //construct a Solr query using aggregated terms to get highlighting
            //the query is executed later on demand
            StringBuilder highlightQuery = new StringBuilder();

            if (queryResults.getKeywords().size() == 1) {
                //simple case, no need to process subqueries and do special escaping
                Keyword term = queryResults.getKeywords().iterator().next();
                highlightQuery.append(term.toString());
            } else {
                //find terms for this content hit
                List<String> hitTerms = new ArrayList<>();
                for (Keyword keyword : queryResults.getKeywords()) {
                    for (KeywordHit hit : queryResults.getResults(keyword)) {
                        if (hit.getContent().equals(content)) {
                            hitTerms.add(keyword.toString());
                            break; //go to next term
                        }
                    }
                }

                final int lastTerm = hitTerms.size() - 1;
                int curTerm = 0;
                for (String term : hitTerms) {
                    //escape subqueries, they shouldn't be escaped again later
                    final String termS = KeywordSearchUtil.escapeLuceneQuery(term);
                    highlightQuery.append("\"");
                    highlightQuery.append(termS);
                    highlightQuery.append("\"");
                    if (lastTerm != curTerm) {
                        highlightQuery.append(" "); //acts as OR ||
                        //force HIGHLIGHT_FIELD_REGEX index and stored content
                        //in each term after first. First term taken care by HighlightedMatchesSource
                        highlightQuery.append(LuceneQuery.HIGHLIGHT_FIELD_REGEX).append(":");
                    }

                    ++curTerm;
                }
            }
            //String highlightQueryEscaped = KeywordSearchUtil.escapeLuceneQuery(highlightQuery.toString());
            highlightQueryEscaped = highlightQuery.toString();
        }

        return highlightQueryEscaped;
    }

    @Override
    protected Node createNodeForKey(KeyValueQueryContent key) {
        final Content content = key.getContent();
        final String queryStr = key.getQueryStr();;
        QueryResults hits = key.getHits();

        Node kvNode = new KeyValueNode(key, Children.LEAF, Lookups.singleton(content));

        //wrap in KeywordSearchFilterNode for the markup content, might need to override FilterNode for more customization
        // store the data in HighlightedMatchesSource so that it can be looked up (in content viewer)
        HighlightedTextMarkup highlights = new HighlightedTextMarkup(key.solrObjectId, queryStr, !key.getQuery().isLiteral(), false, hits);
        return new KeywordSearchFilterNode(highlights, kvNode);
    }

    /**
     * Used to display keyword search results in table. Eventually turned into a
     * node.
     */
    class KeyValueQueryContent extends KeyValue {

        private long solrObjectId;
        private Content content;
        private String queryStr;
        private QueryResults hits;
        private KeywordSearchQuery query;

        /**
         * NOTE Parameters are defined based on how they are currently used in
         * practice
         *
         * @param name File name that has hit.
         * @param map Contains content metadata, snippets, etc. (property map)
         * @param id User incremented ID
         * @param content File that had the hit.
         * @param queryStr Query used in search
         * @param query Query used in search
         * @param hits Full set of search results (for all files!
         * @@@)
         */
        public KeyValueQueryContent(String name, Map<String, Object> map, int id, long solrObjectId, Content content, String queryStr, KeywordSearchQuery query, QueryResults hits) {
            super(name, map, id);
            this.solrObjectId = solrObjectId;
            this.content = content;
            this.queryStr = queryStr;
            this.hits = hits;
            this.query = query;
        }

        Content getContent() {
            return content;
        }

        String getQueryStr() {
            return queryStr;
        }

        QueryResults getHits() {
            return hits;
        }

        KeywordSearchQuery getQuery() {
            return query;
        }
    }

    /**
     * worker for writing results to bb, with progress bar, cancellation, and
     * central registry of workers to be stopped when case is closed
     */
    static class BlackboardResultWriter extends SwingWorker<Object, Void> {

        private static List<BlackboardResultWriter> writers = new ArrayList<>();
        //lock utilized to enqueue writers and limit execution to 1 at a time
        private static final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock(true); //use fairness policy
        //private static final Lock writerLock = rwLock.writeLock();
        private ProgressHandle progress;
        private KeywordSearchQuery query;
        private String listName;
        private QueryResults hits;
        private Collection<BlackboardArtifact> newArtifacts = new ArrayList<>();
        private static final int QUERY_DISPLAY_LEN = 40;

        BlackboardResultWriter(QueryResults hits, String listName) {
            this.hits = hits;
            this.query = hits.getQuery();
            this.listName = listName;
        }

        protected void finalizeWorker() {
            deregisterWriter(this);

            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    progress.finish();
                }
            });
        }

        @Override
        protected Object doInBackground() throws Exception {
            registerWriter(this); //register (synchronized on class) outside of writerLock to prevent deadlock
            final String queryStr = query.getQueryString();
            final String queryDisp = queryStr.length() > QUERY_DISPLAY_LEN ? queryStr.substring(0, QUERY_DISPLAY_LEN - 1) + " ..." : queryStr;
            //block until previous writer is done
            //writerLock.lock();

            try {
                progress = ProgressHandleFactory.createHandle(
                        NbBundle.getMessage(this.getClass(), "KeywordSearchResultFactory.progress.saving", queryDisp), new Cancellable() {
                            @Override
                            public boolean cancel() {
                                return BlackboardResultWriter.this.cancel(true);
                            }
                        });

                // Create blackboard artifacts
                newArtifacts = hits.writeAllHitsToBlackBoard(progress, null, this, false);
            } finally {
                finalizeWorker();
            }

            return null;
        }

        @Override
        protected void done() {
            try {
                // test if any exceptions were thrown
                get();
            } catch (InterruptedException | ExecutionException ex) {
                logger.log(Level.SEVERE, "Error querying ", ex); //NON-NLS
            }
        }

        private static synchronized void registerWriter(BlackboardResultWriter writer) {
            writers.add(writer);
        }

        private static synchronized void deregisterWriter(BlackboardResultWriter writer) {
            writers.remove(writer);
        }

        static synchronized void stopAllWriters() {
            for (BlackboardResultWriter w : writers) {
                w.cancel(true);
                writers.remove(w);
            }
        }
    }
}


text:
<?php

class DummyUserIdentity extends CUserIdentity
{
	private $_id;

	public function __construct($id, $username)
	{
		$this->username = $username;
		$this->_id = $id;
		$this->errorCode=self::ERROR_NONE;
	}

	/**
	 * Authenticates a user.
	 * @return boolean whether authentication succeeds.
	 */
	public function authenticate()
	{
		return $this->errorCode==self::ERROR_NONE;
	}

	public function getId()
	{
		return $this->_id;
	}
}


text:
function [files, digits, img_info] = get_image_files(img_path, regexp_pattern)
% This function scans a directory and get all valid image files infomation.
%
% INPUT
%   img_path:           string
%   regexp_pattern:     string
% OUTPUT
%   files:      file structure array
%   digits:     number array
%   img_info:   image info structure cell array

orig_state = warning;
warning('off','all');

files = dir(img_path);
digits = zeros(length(files), 1);
img_info = cell(length(files), 1);

is_valid_file = true(length(files), 1);
fprintf('Checking all image files...\n');
for i = 1:length(files)
    d = regexp(files(i).name, regexp_pattern, 'tokens');
    if isempty(d)
        is_valid_file(i) = false;
    else
        digits(i) = str2double(d{1});
        img_info{i} = imfinfo([img_path, files(i).name]);
    end
end

files = files(is_valid_file);
digits = digits(is_valid_file);
img_info = img_info(is_valid_file);

[digits, idx] = sort(digits);
files = files(idx);
img_info = img_info(idx);

warning(orig_state);
end


text:
package org.apache.jena.sdb.core;

import org.apache.jena.sdb.SDB ;
import org.apache.jena.sdb.SDBException ;
import org.apache.jena.sparql.util.Symbol ;

public class SDBConstants
{
    // Not "Integer.MIN_VALUE" which is meaningful to MySQL.
    public static final int jdbcFetchSizeOff            = -1 ;

    public static Symbol allocSymbol(String shortName)
    {
        if ( shortName.matches("^[a-zA-Z]*:") )
            throw new SDBException("Symbol short name begins URI scheme") ;
        return Symbol.create(SDB.symbolSpace+shortName) ;
    }
}


text:
import sys

is_python3 = (sys.version_info[0] >= 3)

if is_python3:
    def u(text, errors=''):
        return str(text)

    def is_string(var):
        return isinstance(var, str)
else:

    def u(text, errors=''):
        return unicode(text, 'utf8', errors)  # noqa: F821

    def is_string(var):
        return isinstance(var, basestring)  # noqa: F821


text:
// MainFrm.cpp : implementation of the CMainFrame class
//

#include "stdafx.h"
#include "Step6502.h"
#include "MainFrm.h"
#include "machine.h"
#include "Sym.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

// CMainToolBar

IMPLEMENT_DYNAMIC(CMainToolBar, CMFCToolBar)

CMainToolBar::CMainToolBar()
{

}

CMainToolBar::~CMainToolBar()
{
}

BEGIN_MESSAGE_MAP(CMainToolBar, CMFCToolBar)
END_MESSAGE_MAP()

// CMainToolBar message handlers

// CMainFrame

IMPLEMENT_DYNAMIC(CMainFrame, CFrameWndEx)

const int  iMaxUserToolbars = 10;
const UINT uiFirstUserToolBarId = AFX_IDW_CONTROLBAR_FIRST + 40;
const UINT uiLastUserToolBarId = uiFirstUserToolBarId + iMaxUserToolbars - 1;

BEGIN_MESSAGE_MAP(CMainFrame, CFrameWndEx)
	ON_WM_CREATE()
	ON_WM_SETFOCUS()
	ON_COMMAND(ID_VIEW_CUSTOMIZE, &CMainFrame::OnViewCustomize)
	ON_REGISTERED_MESSAGE(AFX_WM_CREATETOOLBAR, &CMainFrame::OnToolbarCreateNew)
	ON_COMMAND_RANGE(ID_VIEW_APPLOOK_WIN_2000, ID_VIEW_APPLOOK_WINDOWS_7, &CMainFrame::OnApplicationLook)
	ON_UPDATE_COMMAND_UI_RANGE(ID_VIEW_APPLOOK_WIN_2000, ID_VIEW_APPLOOK_WINDOWS_7, &CMainFrame::OnUpdateApplicationLook)
	ON_COMMAND(ID_VIEW_OUTPUTWND, &CMainFrame::OnViewOutputWindow)
	ON_UPDATE_COMMAND_UI(ID_VIEW_OUTPUTWND, &CMainFrame::OnUpdateViewOutputWindow)
	ON_WM_SETTINGCHANGE()
	ON_COMMAND(ID_BUTTON_STOP, &CMainFrame::OnButtonStop)
	ON_COMMAND(ID_BUTTON_STEP_BACK, &CMainFrame::OnButtonStepBack)
	ON_COMMAND(ID_BUTTON_STEP, &CMainFrame::OnButtonStep)
	ON_COMMAND(ID_BUTTON_REVERSE, &CMainFrame::OnButtonReverse)
	ON_COMMAND(ID_BUTTON_GO, &CMainFrame::OnButtonGo)
	ON_COMMAND(ID_BUTTON_BREAK, &CMainFrame::OnButtonBreak)
	ON_COMMAND(ID_BUTTON_IRQ, &CMainFrame::OnButtonIrq)
	ON_COMMAND(ID_BUTTON_NMI, &CMainFrame::OnButtonNmi)
	ON_COMMAND(ID_BUTTON_RELOAD, &CMainFrame::OnButtonReload)
	ON_COMMAND(ID_BUTTON_RESET, &CMainFrame::OnButtonReset)
	ON_COMMAND(ID_BUTTON_LOAD, &CMainFrame::OnButtonLoad)
	ON_COMMAND(ID_BUTTON_VICE, &CMainFrame::OnButtonVice)
	ON_COMMAND(ID_FONTSIZE_12, &CMainFrame::OnFontsize12)
	ON_COMMAND(ID_FONTSIZE_14, &CMainFrame::OnFontsize14)
	ON_COMMAND(ID_FONTSIZE_16, &CMainFrame::OnFontsize16)
	ON_COMMAND(ID_FONTSIZE_18, &CMainFrame::OnFontsize18)
	ON_COMMAND(ID_FONTSIZE_20, &CMainFrame::OnFontsize20)
	ON_COMMAND(ID_FONTSIZE_22, &CMainFrame::OnFontsize22)
	ON_COMMAND(ID_FONTSIZE_24, &CMainFrame::OnFontsize24)
	ON_COMMAND(ID_EDIT_COPY, &CMainFrame::OnEditCopy)
END_MESSAGE_MAP()

static UINT indicators[] =
{
	ID_SEPARATOR,           // status line indicator
	ID_INDICATOR_CAPS,
	ID_INDICATOR_NUM,
	ID_INDICATOR_SCRL,
};

// CMainFrame construction/destruction

CMainFrame::CMainFrame()
{
	// TODO: add member initialization code here
	theApp.m_nAppLook = theApp.GetInt(_T("ApplicationLook"), ID_VIEW_APPLOOK_VS_2008);

	m_currFontSize = theApp.GetProfileInt(L"Font", L"Size", 12);
	m_actionID = 0;

	LOGFONT lf;
	memset(&lf, 0, sizeof(LOGFONT));
	lf.lfHeight = m_currFontSize;
	wcscpy_s(lf.lfFaceName, L"Lucida Console");
	m_font.CreateFontIndirect(&lf);
}

CMainFrame::~CMainFrame()
{
}

int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	if (CFrameWndEx::OnCreate(lpCreateStruct) == -1)
		return -1;

	BOOL bNameValid;

	if (!m_wndMenuBar.Create(this))
	{
		TRACE0("Failed to create menubar\n");
		return -1;      // fail to create
	}

	m_wndMenuBar.SetPaneStyle(m_wndMenuBar.GetPaneStyle() | CBRS_SIZE_DYNAMIC | CBRS_TOOLTIPS | CBRS_FLYBY);

	// prevent the menu bar from taking the focus on activation
	CMFCPopupMenu::SetForceMenuFocus(FALSE);

	// create a view to occupy the client area of the frame
	if (!m_wndView.Create(NULL, NULL, AFX_WS_DEFAULT_VIEW, CRect(0, 0, 0, 0), this, AFX_IDW_PANE_FIRST, NULL))
	{
		TRACE0("Failed to create view window\n");
		return -1;
	}

	if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
		!m_wndToolBar.LoadToolBar(theApp.m_bHiColorIcons ? IDR_MAINFRAME_256 : IDR_MAINFRAME))
	{
		TRACE0("Failed to create toolbar\n");
		return -1;      // fail to create
	}

	CString strToolBarName;
	bNameValid = strToolBarName.LoadString(IDS_TOOLBAR_STANDARD);
	ASSERT(bNameValid);
	m_wndToolBar.SetWindowText(strToolBarName);

	CString strCustomize;
	bNameValid = strCustomize.LoadString(IDS_TOOLBAR_CUSTOMIZE);
	ASSERT(bNameValid);
	m_wndToolBar.EnableCustomizeButton(TRUE, ID_VIEW_CUSTOMIZE, strCustomize);

	// Allow user-defined toolbars operations:
	InitUserToolbars(NULL, uiFirstUserToolBarId, uiLastUserToolBarId);

	if (!m_wndStatusBar.Create(this)) {
		TRACE0("Failed to create status bar\n");
		return -1;      // fail to create
	}
	m_wndStatusBar.SetIndicators(indicators, sizeof(indicators)/sizeof(UINT));

	// TODO: Delete these five lines if you don't want the toolbar and menubar to be dockable
	m_wndMenuBar.EnableDocking(CBRS_ALIGN_ANY);
	m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
	EnableDocking(CBRS_ALIGN_ANY);
	DockPane(&m_wndMenuBar);
	DockPane(&m_wndToolBar);

	// enable Visual Studio 2005 style docking window behavior
	CDockingManager::SetDockingMode(DT_SMART);
	// enable Visual Studio 2005 style docking window auto-hide behavior
	EnableAutoHidePanes(CBRS_ALIGN_ANY);

	// create docking windows
	if (!CreateDockingWindows())
	{
		TRACE0("Failed to create docking windows\n");
		return -1;
	}

	m_memory.EnableDocking(CBRS_ALIGN_ANY);
	DockPane(&m_memory);

	m_code.EnableDocking(CBRS_ALIGN_ANY);
	DockPane(&m_code);

	m_memory2.EnableDocking(CBRS_ALIGN_ANY);
	DockPane(&m_memory2);

	m_registers.EnableDocking(CBRS_ALIGN_ANY);
	DockPane(&m_registers);

	m_graphicView.EnableDocking(CBRS_ALIGN_ANY);
	DockPane(&m_graphicView);

	m_breakpoints.EnableDocking(CBRS_ALIGN_ANY);
	DockPane(&m_breakpoints);

	m_watch.EnableDocking(CBRS_ALIGN_ANY);
	DockPane(&m_watch);

	m_vice.EnableDocking(CBRS_ALIGN_ANY);
	DockPane(&m_vice);

	// set the visual manager and style based on persisted value
	OnApplicationLook(theApp.m_nAppLook);

	// Enable toolbar and docking window menu replacement
	EnablePaneMenu(TRUE, ID_VIEW_CUSTOMIZE, strCustomize, ID_VIEW_TOOLBAR);

	// enable quick (Alt+drag) toolbar customization
	CMFCToolBar::EnableQuickCustomization();

	if (CMFCToolBar::GetUserImages() == NULL)
	{
		// load user-defined toolbar images
		if (m_UserImages.Load(_T(".\\UserImages.bmp")))
		{
			CMFCToolBar::SetUserImages(&m_UserImages);
		}
	}

	// enable menu personalization (most-recently used commands)
	// TODO: define your own basic commands, ensuring that each pulldown menu has at least one basic command.
	CList<UINT, UINT> lstBasicCommands;

	lstBasicCommands.AddTail(ID_APP_EXIT);
	lstBasicCommands.AddTail(ID_EDIT_CUT);
	lstBasicCommands.AddTail(ID_EDIT_PASTE);
	lstBasicCommands.AddTail(ID_EDIT_UNDO);
	lstBasicCommands.AddTail(ID_APP_ABOUT);
	lstBasicCommands.AddTail(ID_BUTTON_STOP);
	lstBasicCommands.AddTail(ID_BUTTON_GO);
	lstBasicCommands.AddTail(ID_BUTTON_REVERSE);
	lstBasicCommands.AddTail(ID_BUTTON_STEP);
	lstBasicCommands.AddTail(ID_BUTTON_STEP_BACK);
	lstBasicCommands.AddTail(ID_BUTTON_BREAK);
	lstBasicCommands.AddTail(ID_VIEW_STATUS_BAR);
	lstBasicCommands.AddTail(ID_VIEW_TOOLBAR);
	lstBasicCommands.AddTail(ID_VIEW_APPLOOK_OFF_2003);
	lstBasicCommands.AddTail(ID_VIEW_APPLOOK_VS_2005);
	lstBasicCommands.AddTail(ID_VIEW_APPLOOK_OFF_2007_BLUE);
	lstBasicCommands.AddTail(ID_VIEW_APPLOOK_OFF_2007_SILVER);
	lstBasicCommands.AddTail(ID_VIEW_APPLOOK_OFF_2007_BLACK);
	lstBasicCommands.AddTail(ID_VIEW_APPLOOK_OFF_2007_AQUA);
	lstBasicCommands.AddTail(ID_VIEW_APPLOOK_WINDOWS_7);

	CMFCToolBar::SetBasicCommands(lstBasicCommands);

	return 0;
}

void CMainFrame::InvalidateRegs()
{
	if (m_registers)
		m_registers.Invalidate();
}

void CMainFrame::InvalidateMem()
{
	if (m_memory)
		m_memory.Invalidate();
	if (m_memory2)
		m_memory2.Invalidate();
}

void CMainFrame::InvalidateAll()
{
	m_code.Invalidate();
	m_memory.Invalidate();
	m_memory2.Invalidate();
	m_registers.Invalidate();
	Invalidate();
}

BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
	if( !CFrameWndEx::PreCreateWindow(cs) )
		return FALSE;
	// TODO: Modify the Window class or styles here by modifying
	//  the CREATESTRUCT cs

	cs.dwExStyle &= ~WS_EX_CLIENTEDGE;
	cs.lpszClass = AfxRegisterWndClass(0);
	return TRUE;
}

BOOL CMainFrame::CreateDockingWindows()
{
	BOOL bNameValid;

	// Create register pane window
	CString strRegsWnd;
	bNameValid = strRegsWnd.LoadString(IDS_REGISTERS_WND);
	ASSERT(bNameValid);
	if (!m_registers.Create(strRegsWnd, this, CRect(0, 0, 640, 100), TRUE, ID_VIEW_REGISTERS, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | CBRS_TOP | CBRS_FLOAT_MULTI)) {
		TRACE0("Failed to create Registers window\n");
		return FALSE; // failed to create
	}

	// Create memory pane window
	CString strMemWnd;
	bNameValid = strMemWnd.LoadString(IDS_MEMORY_NAME);
	ASSERT(bNameValid);
	if (!m_memory.Create(strMemWnd, this, CRect(0, 0, 640, 480), TRUE, ID_VIEW_MEMORY, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | CBRS_RIGHT | CBRS_FLOAT_MULTI)) {
		TRACE0("Failed to create Memory window\n");
		return FALSE; // failed to create
	}
	m_memory.m_viewIndex = 0;

	// Create memory pane window
	CString strMem2Wnd;
	bNameValid = strMem2Wnd.LoadString(IDS_MEMORY2_NAME);
	ASSERT(bNameValid);
	if (!m_memory2.Create(strMem2Wnd, this, CRect(0, 0, 640, 480), TRUE, ID_VIEW_MEMORY2, WS_CHILD /*| WS_VISIBLE*/ | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | CBRS_BOTTOM | CBRS_FLOAT_MULTI)) {
		TRACE0("Failed to create Memory window\n");
		return FALSE; // failed to create
	}
	m_memory2.m_viewIndex = 1;

	// Create code pane window
	CString strCodeWnd;
	bNameValid = strCodeWnd.LoadString(IDS_CODE_VIEW);
	ASSERT(bNameValid);
	if (!m_code.Create(strCodeWnd, this, CRect(0, 0, 256, 512), TRUE, ID_VIEW_CODE, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | CBRS_LEFT | CBRS_FLOAT_MULTI)) {
		TRACE0("Failed to create Code window\n");
		return FALSE; // failed to create
	}

	CString strGraphicWnd;
	bNameValid = strGraphicWnd.LoadString(IDS_GRAPHIC_VIEW);
	ASSERT(bNameValid);
	if (!m_graphicView.Create(strGraphicWnd, this, CRect(0, 0, 640, 480), TRUE, ID_VIEW_GRAPHIC, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | CBRS_TOP | CBRS_FLOAT_MULTI)) {
		TRACE0("Failed to create Graphic window\n");
		return FALSE; // failed to create
	}

	CString strBreakptsWnd;
	bNameValid = strBreakptsWnd.LoadString(IDS_BREAKPOINTS);
	ASSERT(bNameValid);
	if (!m_breakpoints.Create(strBreakptsWnd, this, CRect(0, 0, 640, 480), TRUE, ID_BREAKPOINTS, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | CBRS_TOP | CBRS_FLOAT_MULTI)) {
		TRACE0("Failed to create Breakpoints window\n");
		return FALSE; // failed to create
	}

	CString strWatchWnd;
	bNameValid = strWatchWnd.LoadString(IDS_WATCH);
	ASSERT(bNameValid);
	if (!m_watch.Create(strWatchWnd, this, CRect(0, 0, 640, 480), TRUE, ID_WATCH_VIEW, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | CBRS_TOP | CBRS_FLOAT_MULTI)) {
		TRACE0("Failed to create Watch window\n");
		return FALSE; // failed to create
	}

	CString strViceMon;
	bNameValid = strViceMon.LoadString(IDS_VICE_MONITOR);
	ASSERT(bNameValid);
	if (!m_vice.Create(strViceMon, this, CRect(0, 0, 640, 480), TRUE, ID_VICE_MONITOR, WS_CHILD /*| WS_VISIBLE*/ | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | CBRS_TOP | CBRS_FLOAT_MULTI)) {
		TRACE0("Failed to create Vice Monitor window\n");
		return FALSE; // failed to create
	}

	SetDockingWindowIcons(theApp.m_bHiColorIcons);
	return TRUE;
}

void CMainFrame::SetDockingWindowIcons(BOOL bHiColorIcons)
{
	HICON hOutputBarIcon = (HICON) ::LoadImage(::AfxGetResourceHandle(), MAKEINTRESOURCE(bHiColorIcons ? IDI_OUTPUT_WND_HC : IDI_OUTPUT_WND), IMAGE_ICON, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON), 0);
}

// CMainFrame diagnostics

#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
	CFrameWndEx::AssertValid();
}

void CMainFrame::Dump(CDumpContext& dc) const
{
	CFrameWndEx::Dump(dc);
}
#endif //_DEBUG

// CMainFrame message handlers

void CMainFrame::OnSetFocus(CWnd* /*pOldWnd*/)
{
	// forward focus to the view window
	m_wndView.SetFocus();
}

BOOL CMainFrame::OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo)
{
	// let the view have first crack at the command
	if (m_wndView.OnCmdMsg(nID, nCode, pExtra, pHandlerInfo))
		return TRUE;

	// otherwise, do default handling
	return CFrameWndEx::OnCmdMsg(nID, nCode, pExtra, pHandlerInfo);
}

void CMainFrame::OnViewCustomize()
{
	CMFCToolBarsCustomizeDialog* pDlgCust = new CMFCToolBarsCustomizeDialog(this, TRUE /* scan menus */);
	pDlgCust->EnableUserDefinedToolbars();
	pDlgCust->Create();
}

LRESULT CMainFrame::OnToolbarCreateNew(WPARAM wp,LPARAM lp)
{
	LRESULT lres = CFrameWndEx::OnToolbarCreateNew(wp,lp);
	if (lres == 0)
	{
		return 0;
	}

	CMFCToolBar* pUserToolbar = (CMFCToolBar*)lres;
	ASSERT_VALID(pUserToolbar);

	BOOL bNameValid;
	CString strCustomize;
	bNameValid = strCustomize.LoadString(IDS_TOOLBAR_CUSTOMIZE);
	ASSERT(bNameValid);

	pUserToolbar->EnableCustomizeButton(TRUE, ID_VIEW_CUSTOMIZE, strCustomize);
	return lres;
}

void CMainFrame::OnApplicationLook(UINT id)
{
	CWaitCursor wait;

	theApp.m_nAppLook = id;

	switch (theApp.m_nAppLook)
	{
	case ID_VIEW_APPLOOK_WIN_2000:
		CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManager));
		break;

	case ID_VIEW_APPLOOK_OFF_XP:
		CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerOfficeXP));
		break;

	case ID_VIEW_APPLOOK_WIN_XP:
		CMFCVisualManagerWindows::m_b3DTabsXPTheme = TRUE;
		CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows));
		break;

	case ID_VIEW_APPLOOK_OFF_2003:
		CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerOffice2003));
		CDockingManager::SetDockingMode(DT_SMART);
		break;

	case ID_VIEW_APPLOOK_VS_2005:
		CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerVS2005));
		CDockingManager::SetDockingMode(DT_SMART);
		break;

	case ID_VIEW_APPLOOK_VS_2008:
		CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerVS2008));
		CDockingManager::SetDockingMode(DT_SMART);
		break;

	case ID_VIEW_APPLOOK_WINDOWS_7:
		CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows7));
		CDockingManager::SetDockingMode(DT_SMART);
		break;

	default:
		switch (theApp.m_nAppLook)
		{
		case ID_VIEW_APPLOOK_OFF_2007_BLUE:
			CMFCVisualManagerOffice2007::SetStyle(CMFCVisualManagerOffice2007::Office2007_LunaBlue);
			break;

		case ID_VIEW_APPLOOK_OFF_2007_BLACK:
			CMFCVisualManagerOffice2007::SetStyle(CMFCVisualManagerOffice2007::Office2007_ObsidianBlack);
			break;

		case ID_VIEW_APPLOOK_OFF_2007_SILVER:
			CMFCVisualManagerOffice2007::SetStyle(CMFCVisualManagerOffice2007::Office2007_Silver);
			break;

		case ID_VIEW_APPLOOK_OFF_2007_AQUA:
			CMFCVisualManagerOffice2007::SetStyle(CMFCVisualManagerOffice2007::Office2007_Aqua);
			break;
		}

		CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerOffice2007));
		CDockingManager::SetDockingMode(DT_SMART);
	}

	RedrawWindow(NULL, NULL, RDW_ALLCHILDREN | RDW_INVALIDATE | RDW_UPDATENOW | RDW_FRAME | RDW_ERASE);

	theApp.WriteInt(_T("ApplicationLook"), theApp.m_nAppLook);
}

void CMainFrame::OnUpdateApplicationLook(CCmdUI* pCmdUI)
{
	pCmdUI->SetRadio(theApp.m_nAppLook == pCmdUI->m_nID);
}

void CMainFrame::OnViewOutputWindow()
{
}

void CMainFrame::OnUpdateViewOutputWindow(CCmdUI* pCmdUI)
{
	pCmdUI->Enable(TRUE);
}

BOOL CMainFrame::LoadFrame(UINT nIDResource, DWORD dwDefaultStyle, CWnd* pParentWnd, CCreateContext* pContext)
{
	// base class does the real work

	if (!CFrameWndEx::LoadFrame(nIDResource, dwDefaultStyle, pParentWnd, pContext))
	{
		return FALSE;
	}

	// enable customization button for all user toolbars
	BOOL bNameValid;
	CString strCustomize;
	bNameValid = strCustomize.LoadString(IDS_TOOLBAR_CUSTOMIZE);
	ASSERT(bNameValid);

	for (int i = 0; i < iMaxUserToolbars; i ++)
	{
		CMFCToolBar* pUserToolbar = GetUserToolBarByIndex(i);
		if (pUserToolbar != NULL)
		{
			pUserToolbar->EnableCustomizeButton(TRUE, ID_VIEW_CUSTOMIZE, strCustomize);
		}
	}

	return TRUE;
}

void CMainFrame::OnSettingChange(UINT uFlags, LPCTSTR lpszSection)
{
	CFrameWndEx::OnSettingChange(uFlags, lpszSection);
}

bool ViceRunning();
void ViceBreak();
void CMainFrame::OnButtonStop()
{
	CPUStop();

	// TODO: Add your command handler code here
	if (ViceRunning()) {
		ViceBreak();
	} else {
		m_code.FocusPC();

		m_registers.Invalidate();
		m_memory.Invalidate();
		m_code.Invalidate();
	}
}

void CMainFrame::OnButtonStepBack()
{
	// TODO: Add your command handler code here
	CPUStepBack();
}

void CMainFrame::OnButtonStep()
{
	// TODO: Add your command handler code here
	CPUStep();
}

void CMainFrame::OnButtonReverse()
{
	// TODO: Add your command handler code here
	CPUReverse();
}

void CMainFrame::MachineUpdated()
{
	m_watch.EvaluateAll();
	m_watch.Invalidate();
	InvalidateAll();
}

void CMainFrame::VicePrint(const char * buf, int len)
{
	if (buf && len) { m_vice.AddText(buf, len); }
}

void CMainFrame::ViceMonClear()
{
	m_vice.Clear();
}

void CMainFrame::ViceInput(bool enable)
{
	m_vice.EnableInput(enable);
}

void CMainToolBar::EnableToolbarButton(int id, bool enable)
{
	int index = CommandToIndex(id);
	if (index >=0) {
		UINT iStyle = GetButtonStyle(index);
		if (enable)
			SetButtonStyle(index, iStyle & (~TBBS_DISABLED));
		else
			SetButtonStyle(index, iStyle | TBBS_DISABLED);
	}
}

void CMainToolBar::OnUpdateCmdUI(CFrameWnd *pFrame, BOOL bDisableIfNoHndler)
{
	CMFCToolBar::OnUpdateCmdUI(pFrame, bDisableIfNoHndler);
	bool running = IsCPURunning();
	EnableToolbarButton(ID_BUTTON_STOP, running || ViceRunning());
	EnableToolbarButton(ID_BUTTON_GO, !running);
	EnableToolbarButton(ID_BUTTON_REVERSE, !running);
	EnableToolbarButton(ID_BUTTON_STEP, !running);
	EnableToolbarButton(ID_BUTTON_STEP_BACK, !running);
	EnableToolbarButton(ID_BUTTON_FONTSIZE, true);
}

void CMainFrame::OnButtonGo()
{
	// TODO: Add your command handler code here
	CPUGo();
	InvalidateAll();
}

void CMainFrame::OnButtonBreak()
{
	// TODO: Add your command handler code here
	m_code.SetBP();
}

void CMainFrame::OnButtonIrq()
{
	// TODO: Add your command handler code here
	CPUIRQ();
	InvalidateAll();
}

void CMainFrame::OnButtonNmi()
{
	// TODO: Add your command handler code here
	CPUNMI();
	InvalidateAll();
}

void CMainFrame::OnButtonReload()
{
	// TODO: Add your command handler code here
	if (!IsCPURunning()) {
		int fileType = theApp.GetProfileInt(L"Last binary file", L"Filetype", 0);
		CString address = theApp.GetProfileString(L"Last binary file", L"LoadAddress", L"800");
		int forceLoadAddress = theApp.GetProfileInt(L"Last binary file", L"Force Load Address", 0);
		int setPC = theApp.GetProfileInt(L"Last binary file", L"Set PC to Load Address", 1);
		int resetUndo = theApp.GetProfileInt(L"Last binary file", L"Reset backtrace", 1);

		wchar_t *end;
		int addr = wcstol((const wchar_t*)address+(address[0]=='$' ? 1 : 0), &end, 16);

		CString file = theApp.GetProfileString(L"Last binary file", L"Filename");
		if (file)
			LoadBinary(file, fileType, addr, setPC, forceLoadAddress, resetUndo);
	}
}

void CMainFrame::OnButtonReset()
{
	// TODO: Add your command handler code here
	CPUReset();
	InvalidateAll();
}

void CMainFrame::LoadBinary(CString &file, int filetype, int address, int setPC, int forceAddress, int resetUndo)
{
	FILE *f = nullptr;

	if (_wfopen_s(&f, file, L"rb")==0) {

		// assume .prg for now
		fseek(f, 0, SEEK_END);
		size_t size = ftell(f);
		fseek(f, 0, SEEK_SET);

		if (filetype == 0 || filetype == 1) {
			int8_t addr8[2];
			fread(addr8, 1, 2, f);
			size_t addr = addr8[0] + (uint16_t(addr8[1])<<8);
			size -= 2;
			if (filetype == 1) {
				fread(addr8, 1, 2, f);
				size = addr8[0] + (uint16_t(addr8[1])<<8);
			}
			if (!forceAddress)
				address = (int)addr;
		}

		size_t read = size < size_t(0x10000-address) ?
			size : size_t(0x10000-address);

		uint8_t *trg = Get6502Mem((uint16_t)address);
		fread(trg, read, 1, f);
		fclose(f);

		GetRegs().T = 0;
		if (setPC) {
			GetRegs().PC = address;
			FocusPC();
		}

		if (resetUndo) {
			ResetUndoBuffer();
		}

		ReadSymbols(file);
		m_breakpoints.Rebuild();

		InvalidateAll();
	}
}

void CMainFrame::TryLoadBinary(const wchar_t *file)
{
	m_loadAddressDialog.m_bFileType = theApp.GetProfileInt(L"Last binary file", L"Filetype", 0);
	m_loadAddressDialog.m_AddrStr = theApp.GetProfileString(L"Last binary file", L"LoadAddress", L"800");
	m_loadAddressDialog.m_bForceLoadAddress = theApp.GetProfileInt(L"Last binary file", L"Force Load Address", 0);
	m_loadAddressDialog.m_bResetUndo = theApp.GetProfileInt(L"Last binary file", L"Reset backtrace", 1);
	m_loadAddressDialog.m_bSetPCToLoadAddress = theApp.GetProfileInt(L"Last binary file", L"Set PC to Load Address", 1);

	if (m_loadAddressDialog.DoModal() == IDCANCEL)
		return;

	theApp.WriteProfileInt(L"Last binary file", L"Filetype", m_loadAddressDialog.m_bFileType);
	theApp.WriteProfileString(L"Last binary file", L"LoadAddress", m_loadAddressDialog.m_AddrStr);
	theApp.WriteProfileInt(L"Last binary file", L"Force Load Address", m_loadAddressDialog.m_bForceLoadAddress);
	theApp.WriteProfileInt(L"Last binary file", L"Set PC to Load Address", m_loadAddressDialog.m_bSetPCToLoadAddress);
	theApp.WriteProfileInt(L"Last binary file", L"Reset backtrace", m_loadAddressDialog.m_bResetUndo);

	// remember the file for reloading

	theApp.WriteProfileString(L"Last binary file", L"Filename", file);

	wchar_t *end;
	int addr = wcstol((const wchar_t*)m_loadAddressDialog.m_AddrStr+(m_loadAddressDialog.m_AddrStr[0]=='$' ? 1 : 0), &end, 16);

	LoadBinary(CString(file), m_loadAddressDialog.m_bFileType, addr, m_loadAddressDialog.m_bSetPCToLoadAddress,
			   m_loadAddressDialog.m_bForceLoadAddress, m_loadAddressDialog.m_bResetUndo);
}

void CMainFrame::OnButtonLoad()
{
	// can't load code while CPU is running
	if (IsCPURunning())
		return;

	// TODO: Add your command handler code here
	CFileDialog fileDialog(true);
	fileDialog.AddText(ID_LOAD_ADDRESS_TEXT, L"Address:");

	if (fileDialog.DoModal() == IDCANCEL)
		return;

	m_loadAddressDialog.m_bFileType = theApp.GetProfileInt(L"Last binary file", L"Filetype", 0);
	m_loadAddressDialog.m_AddrStr = theApp.GetProfileString(L"Last binary file", L"LoadAddress", L"800");
	m_loadAddressDialog.m_bForceLoadAddress = theApp.GetProfileInt(L"Last binary file", L"Force Load Address", 0);
	m_loadAddressDialog.m_bResetUndo = theApp.GetProfileInt(L"Last binary file", L"Reset backtrace", 1);
	m_loadAddressDialog.m_bSetPCToLoadAddress = theApp.GetProfileInt(L"Last binary file", L"Set PC to Load Address", 1);

	m_loadAddressDialog.DoModal();

	theApp.WriteProfileInt(L"Last binary file", L"Filetype", m_loadAddressDialog.m_bFileType);
	theApp.WriteProfileString(L"Last binary file", L"LoadAddress", m_loadAddressDialog.m_AddrStr);
	theApp.WriteProfileInt(L"Last binary file", L"Force Load Address", m_loadAddressDialog.m_bForceLoadAddress);
	theApp.WriteProfileInt(L"Last binary file", L"Set PC to Load Address", m_loadAddressDialog.m_bSetPCToLoadAddress);
	theApp.WriteProfileInt(L"Last binary file", L"Reset backtrace", m_loadAddressDialog.m_bResetUndo);

	CString file = fileDialog.GetPathName();

	// remember the file for reloading

	theApp.WriteProfileString(L"Last binary file", L"Filename", file);

	wchar_t *end;
	int addr = wcstol((const wchar_t*)m_loadAddressDialog.m_AddrStr+(m_loadAddressDialog.m_AddrStr[0]=='$' ? 1 : 0), &end, 16);

	LoadBinary(file, m_loadAddressDialog.m_bFileType, addr, m_loadAddressDialog.m_bSetPCToLoadAddress,
			   m_loadAddressDialog.m_bForceLoadAddress, m_loadAddressDialog.m_bResetUndo);
}

bool ViceAction();
void CMainFrame::OnButtonVice()
{
	ViceAction();
}

// D:\test\step6502\MainFrm.cpp : implementation file
//

void CMainFrame::UpdateFontSize(int newSize)
{
	if (m_currFontSize != newSize) {
		theApp.WriteProfileInt(L"Font", L"Size", newSize);
		m_currFontSize = newSize;

		LOGFONT lf;
		memset(&lf, 0, sizeof(LOGFONT));
		lf.lfHeight = m_currFontSize;
		wcscpy_s(lf.lfFaceName, L"Lucida Console");
		m_font.DeleteObject();
		m_font.CreateFontIndirect(&lf);
		InvalidateAll();
	}
}

void CMainFrame::OnFontsize12()
{
	UpdateFontSize(12);
}

void CMainFrame::OnFontsize14()
{
	UpdateFontSize(14);
}

void CMainFrame::OnFontsize16()
{
	UpdateFontSize(16);
}

void CMainFrame::OnFontsize18()
{
	UpdateFontSize(18);
}

void CMainFrame::OnFontsize20()
{
	UpdateFontSize(20);
}

void CMainFrame::OnFontsize22()
{
	UpdateFontSize(22);
}

void CMainFrame::OnFontsize24()
{
	UpdateFontSize(24);
}

void CMainFrame::OnEditCopy()
{
	switch (m_currView) {
		case S6_REG:
			m_registers.OnEditCopy();
			break;
		case S6_GFX:
			m_graphicView.OnEditCopy();
			break;
		case S6_MEM1:
			m_memory.OnEditCopy();
			break;
		case S6_MEM2:
			m_memory2.OnEditCopy();
			break;
		case S6_CODE:
			m_code.OnEditCopy();
			break;
	}
}

void CMainFrame::StepOver()
{
	if (!IsCPURunning()) {
		CPUStepOver();
		if (CMainFrame *pFrame = theApp.GetMainFrame())
			pFrame->m_actionID++;
		if (GetRegs().PC<m_code.currAddr||(m_code.currAddr<m_code.bottomAddr && GetRegs().PC>=m_code.bottomAddr))
			m_code.currAddr = GetRegs().PC;
		Invalidate();
	}
}

void CMainFrame::Step(bool back)
{
	if (!IsCPURunning()) {
		if (back) {
			CPUStepBack();
			if (CMainFrame *pFrame = theApp.GetMainFrame()) {
				pFrame->m_actionID++;
				pFrame->InvalidateRegs();
			}
		} else {
			CPUStep();
			if (CMainFrame *pFrame = theApp.GetMainFrame())
				pFrame->m_actionID++;
		}
		if (GetRegs().PC<m_code.currAddr||(m_code.currAddr<m_code.bottomAddr && GetRegs().PC>=m_code.bottomAddr))
			m_code.currAddr = GetRegs().PC;
		Invalidate();
	}
}

void CMainFrame::ToggleBreakpoint()
{
	if (m_code.m_cursor!=0xffff&&m_code.m_aLinePC[m_code.m_cursor]>0) {
		if (m_code.m_cursor<CCodeView::MAX_CODE_LINES) {
			uint32_t id = TogglePCBreakpoint(m_code.m_aLinePC[m_code.m_cursor]);
			theApp.GetMainFrame()->BreakpointChanged(id);
		}
		Invalidate();
	}
}

void CMainFrame::Go(bool back)
{
	if (back)
		CPUReverse();
	else
		CPUGo();
	Invalidate();
}

void CMainFrame::Stop()
{
	m_code.m_selecting = false;
	if (IsCPURunning()) {
		CPUStop();
	}
	if (m_code.m_cursor != 0xffff) {
		m_code.m_cursor = 0xffff;
		Invalidate();
	}
}


text:
<!doctype html>

	<title>CSS Columns</title>
	<link rel="stylesheet" href="css/columns.css" />

Demo: CSS Columns

Below you see a container and we tell it to have .three .columns.

Each child .column will float left and receive a width defined by the number of columns.

Column 1

This is column #1

Column 2

This is column #2

Column 3

This is column #3


text:
{ # This ensures the entire script is downloaded.

  basedir=$HOME/.dotfiles
  repourl=https://github.com/MrPickles/dotfiles.git

  if ! command -v git >/dev/null ; then
    echo "Error: Git is not installed!"
    exit 1
  fi

  if [ -d "$basedir/.git" ]; then
    cd "$basedir" || exit
    git pull --quiet --rebase origin master
  else
    rm -rf "$basedir"
    git clone --quiet --filter=blob:none "$repourl" "$basedir"
  fi

  cd "$basedir" || exit
  # shellcheck source=setup.sh
  . setup.sh -t build

} # This ensures the entire script is downloaded.


text:
namespace chrome_cleaner {

LoggingDecision UwSLoggingDecision(UwSId pup_id) {
  if (!PUPData::IsKnownPUP(pup_id)) {
    LOG(ERROR) << "Found unsupported UwS " << pup_id;
    return LoggingDecision::kUnsupported;
  }

  PUPData::PUP* pup = PUPData::GetPUP(pup_id);

  // In case no matched file still exists, consider the UwS as not matched.
  pup->expanded_disk_footprints.DiscardNonExistingFiles();

  if (pup->expanded_disk_footprints.size() == 0) {
    LOG(INFO) << "Detected " << pup->signature().name
              << ", but not logging because files are missing.";
    return LoggingDecision::kNotLogged;
  }

  LOG(INFO) << "Detected " << pup->signature().name;
  return LoggingDecision::kLogged;
}

ResultCode ScanningResultCode(uint32_t engine_operation_status) {
  // IMPORTANT: When adding new possible exit codes here, you may need to update
  // their handling in MainController::DoneScanning,
  // MainController::DoneValidation and MainController::DoneCleanupValidation.
  LOG(INFO) << "Engine Scan exited with status code 0x" << std::hex
            << engine_operation_status << std::dec;
  if (engine_operation_status == EngineResultCode::kCancelled)
    return RESULT_CODE_CANCELED;
  if (engine_operation_status != EngineResultCode::kSuccess)
    return RESULT_CODE_SCANNING_ENGINE_ERROR;
  return RESULT_CODE_SUCCESS;
}

ResultCode CleaningResultCode(uint32_t result_code, bool needs_reboot) {
  LOG(INFO) << "Engine cleanup exited with status code 0x" << std::hex
            << result_code << std::dec;
  if (result_code == EngineResultCode::kCancelled)
    return RESULT_CODE_CANCELED;
  if (result_code == EngineResultCode::kCleaningFailed) {
    LOG(ERROR) << "Engine failed to clean the system";
    return RESULT_CODE_FAILED;
  }
  if (result_code != EngineResultCode::kSuccess)
    return RESULT_CODE_FAILED;
  if (needs_reboot)
    return RESULT_CODE_PENDING_REBOOT;
  return RESULT_CODE_SUCCESS;
}

}  // namespace chrome_cleaner


text:
from __future__ import division
import sys
import math
import collections

def inside(self, radius):
	return self[0] * self[0] + self[1] * self[1] < radius * radius

def intersection_horizontal(self, radius):
	x = math.sqrt(radius * radius - self[1] * self[1])
	return (x, self[1])

def intersection_vertical(self, radius):
	y = math.sqrt(radius * radius - self[0] * self[0])
	return (self[0], y)

def distance(self, other):
	dx = other[0] - self[0]
	dy = other[1] - self[1]
	return math.sqrt(dx * dx + dy * dy)

def triangle_area(pointA, pointB, pointC):
	a = distance(pointB, pointC)
	b = distance(pointC, pointA)
	c = distance(pointA, pointB)
	s = (a + b + c) / 2
	return math.sqrt(s * (s - a) * (s - b) * (s - c))

def segment_area(a, b, life_radius):
	chord = distance(a, b)
	theta = 2 * math.asin(chord / (2 * life_radius))
	return 0.5 * life_radius * life_radius * (theta - math.sin(theta))

def life_area(left_down, inner, life_radius):
	right_up = (left_down[0] + inner, left_down[1] + inner)
	ru = inside(right_up, life_radius)
	if ru:
		return inner * inner
	right_down = (left_down[0] + inner, left_down[1])
	left_up = (left_down[0], left_down[1] + inner)
	ld = inside(left_down, life_radius)
	rd = inside(right_down, life_radius)
	lu = inside(left_up, life_radius)
	if ld:
		if rd and lu:
			a = intersection_horizontal(right_up, life_radius)
			b = intersection_vertical(right_up, life_radius)
		elif rd:
			a = intersection_vertical(left_up, life_radius)
			b = intersection_vertical(right_up, life_radius)
		elif lu:
			a = intersection_horizontal(right_up, life_radius)
			b = intersection_horizontal(right_down, life_radius)
		else:
			a = intersection_vertical(left_down, life_radius)
			b = intersection_horizontal(left_down, life_radius)
		area = 0.0
		area += triangle_area(left_down, right_down, b)
		area += triangle_area(left_down, b, a)
		area += triangle_area(left_down, a, left_up)
		area += segment_area(a, b, life_radius)
		return area
	return 0.0

def solve(f, R, t, r, g):
	life_radius = R - t - f
	if life_radius <= 0.0:
		return 1.0
	inner = g - 2 * f
	if inner <= 0.0:
		return 1.0
	block = g + 2 * r
	block_count = int(math.ceil(R / block))
	x = [r + f + x * block  for x in xrange(block_count)]
	y = list(x)
	suma = 0.0
	for ldx in x:
		for ldy in y:
			suma += life_area((ldx, ldy), inner, life_radius)
	quarter_circle = R * R * math.pi / 4
	return 1.0 - suma / quarter_circle

def main(stdin):
	n = int(stdin.readline())
	for i in xrange(1, n + 1):
		f, R, t, r, g = map(float, stdin.readline().split())
		print "Case #%d: %.6lf" % (i, solve(f, R, t, r, g))

if __name__ == '__main__':
	"""
	python fly_swatter.py < C-examp-practice.in > C-examp-practice.out
	python fly_swatter.py < C-small-practice.in > C-small-practice.out
	python fly_swatter.py < C-large-practice.in > C-large-practice.out
	"""
	main(sys.stdin if len(sys.argv) == 1 else open("C-examp-practice.in", "r"))


text:
using System;
using System.Collections.Generic;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using ShoppingList.Application.Common;

namespace ShoppingList.Tests.Unit.Common
{
    [TestClass]
    public class VerifyTests
    {
        [Test]
        public void VerifyWhenFalseShouldThrowErrorMessage()
        {
            // ReSharper disable once UseObjectOrCollectionInitializer
            var verifications = new List<Verify>();

            verifications.Add(new Verify(false).IdentifyAs("1").OnFailureShowMessage("The error message"));

            Action action = () => Verify.These(verifications);

            action.ShouldThrow<VerificationFailedException>().WithMessage("One or more validations have failed.");
        }

        [Test]
        public void VerifyWhenTrueShouldNotThrowErrorMessage()
        {
            // ReSharper disable once UseObjectOrCollectionInitializer
            var verifications = new List<Verify>();

            verifications.Add(new Verify(true).IdentifyAs("2").OnFailureShowMessage("The error message"));

            Action action = () => Verify.These(verifications);

            action.ShouldNotThrow<VerificationFailedException>();
        }

        [Test]
        public void SingleVerifyWhenFalseShouldThrowErrorMessage()
        {
            Action action = () => new Verify(false).OnFailureShowMessage("The error message").Immediately();

            action.ShouldThrow<VerificationFailedException>().WithMessage("One or more validations have failed.");
        }
    }
}


text:
from IceCertUtils.PyOpenSSLCertificateUtils import PyOpenSSLCertificateFactory
from IceCertUtils.OpenSSLCertificateUtils import OpenSSLCertificateFactory
from IceCertUtils.KeyToolCertificateUtils import KeyToolCertificateFactory
from IceCertUtils.CertificateUtils import DistinguishedName, Certificate, defaultDN

CertificateFactory = CertificateUtils.getDefaultImplementation()


text:
#ifndef _MULTI_CHERI_UART_
#define _MULTI_CHERI_UART_

void uart_putc(char c);
void uart_putd(unsigned long long d);
void uart_putx(unsigned long long x);
unsigned int uart_puts(char * str);
char uart_getc();

void uart_lock_init();
void uart_lock_acquire();
void uart_lock_release();
void uart_locked_putc(char c);
void uart_locked_putd(unsigned long long d);
void uart_locked_putx(unsigned long long x);
unsigned int uart_locked_puts(char * str);
char uart_locked_getc();

#endif


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('issues', '0003_auto_20141210_1108'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='issue',
            options={'ordering': ['project', '-id'], 'permissions': (('view_issue', 'Can view issue'),), 'verbose_name_plural': 'issues', 'verbose_name': 'issue'},
        ),
    ]


text:
package com.amazonaws.services.lightsail.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * Describes the configuration for an Amazon Lightsail container service to access private container image repositories,
 * such as Amazon Elastic Container Registry (Amazon ECR) private repositories.
 *

 *

 * For more information, see Configuring access to an Amazon ECR private repository for an Amazon Lightsail container service in the
 * Amazon Lightsail Developer Guide.
 *

 *
 * @see AWS
 *      API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class PrivateRegistryAccess implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * An object that describes the activation status of the role that you can use to grant a Lightsail container
     * service access to Amazon ECR private repositories. If the role is activated, the Amazon Resource Name (ARN) of
     * the role is also listed.
     *

     */
    private ContainerServiceECRImagePullerRole ecrImagePullerRole;

    /**
     *

     * An object that describes the activation status of the role that you can use to grant a Lightsail container
     * service access to Amazon ECR private repositories. If the role is activated, the Amazon Resource Name (ARN) of
     * the role is also listed.
     *

     *
     * @param ecrImagePullerRole
     *        An object that describes the activation status of the role that you can use to grant a Lightsail container
     *        service access to Amazon ECR private repositories. If the role is activated, the Amazon Resource Name
     *        (ARN) of the role is also listed.
     */

    public void setEcrImagePullerRole(ContainerServiceECRImagePullerRole ecrImagePullerRole) {
        this.ecrImagePullerRole = ecrImagePullerRole;
    }

    /**
     *

     * An object that describes the activation status of the role that you can use to grant a Lightsail container
     * service access to Amazon ECR private repositories. If the role is activated, the Amazon Resource Name (ARN) of
     * the role is also listed.
     *

     *
     * @return An object that describes the activation status of the role that you can use to grant a Lightsail
     *         container service access to Amazon ECR private repositories. If the role is activated, the Amazon
     *         Resource Name (ARN) of the role is also listed.
     */

    public ContainerServiceECRImagePullerRole getEcrImagePullerRole() {
        return this.ecrImagePullerRole;
    }

    /**
     *

     * An object that describes the activation status of the role that you can use to grant a Lightsail container
     * service access to Amazon ECR private repositories. If the role is activated, the Amazon Resource Name (ARN) of
     * the role is also listed.
     *

     *
     * @param ecrImagePullerRole
     *        An object that describes the activation status of the role that you can use to grant a Lightsail container
     *        service access to Amazon ECR private repositories. If the role is activated, the Amazon Resource Name
     *        (ARN) of the role is also listed.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public PrivateRegistryAccess withEcrImagePullerRole(ContainerServiceECRImagePullerRole ecrImagePullerRole) {
        setEcrImagePullerRole(ecrImagePullerRole);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getEcrImagePullerRole() != null)
            sb.append("EcrImagePullerRole: ").append(getEcrImagePullerRole());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof PrivateRegistryAccess == false)
            return false;
        PrivateRegistryAccess other = (PrivateRegistryAccess) obj;
        if (other.getEcrImagePullerRole() == null ^ this.getEcrImagePullerRole() == null)
            return false;
        if (other.getEcrImagePullerRole() != null && other.getEcrImagePullerRole().equals(this.getEcrImagePullerRole()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getEcrImagePullerRole() == null) ? 0 : getEcrImagePullerRole().hashCode());
        return hashCode;
    }

    @Override
    public PrivateRegistryAccess clone() {
        try {
            return (PrivateRegistryAccess) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.lightsail.model.transform.PrivateRegistryAccessMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
<?php

namespace Serafim\Asset\Compiler;

use LogicException;
use InvalidArgumentException;

/**
 * Class ManifestReader
 * @package Serafim\Asset\Compiler
 */
class ManifestReader
{
    /**
     * @var File
     */
    protected $file;

    /**
     * Pattern for pre-compiled files
     *
     * @var string
     */
    protected $compilePattern = '(\s*)[/#]+\s*=\s*(require\s*(.*))';

    /**
     * Pattern for require-first files
     *
     * @var string
     */
    protected $requirePattern = '(\s*)[/#]+\s*=\s*(source(?:s)?\s*(.*))';

    /**
     * @var string
     */
    protected $sources;

    /**
     * @param File $file
     */
    public function __construct(File $file)
    {
        $this->file    = $file;
        $this->sources = str_replace("\r", '', $this->file->getSourceCode());
    }

    /**
     * @return string
     */
    public function getCompilePattern()
    {
        return $this->compilePattern;
    }

    /**
     * @param string $pattern
     */
    public function setCompilePattern($pattern)
    {
        $this->compilePattern = $pattern;
    }

    /**
     * @return string
     */
    public function getRequirePattern()
    {
        return $this->compilePattern;
    }

    /**
     * @param string $pattern
     */
    public function setRequirePattern($pattern)
    {
        $this->compilePattern = $pattern;
    }

    /**
     * @return \Generator
     * @throws LogicException
     */
    public function getSourceDependencies()
    {
        return $this->getDependencies($this->requirePattern);
    }

    /**
     * @return \Generator
     * @throws LogicException
     */
    public function getCompiledDependencies()
    {
        return $this->getDependencies($this->compilePattern);
    }

    /**
     * @return \Generator
     * @throws LogicException
     */
    protected function getDependencies($pattern)
    {
        $pattern = sprintf('/%s/', str_replace('/', '\/', $pattern));
        preg_match_all($pattern, $this->sources, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);

        foreach ($matches as $id => $match) {
            yield trim($match[0][0]) => $this->parseQuery($this->sources, $match);
        }
    }

    /**
     * @param $sources
     * @param $matches
     * @return File[]
     * @throws LogicException
     * @throws InvalidArgumentException
     */
    protected function parseQuery($sources, $matches)
    {
        // Format matches
        list($fullQuery, $whitespaces, $requireQuery, $query) = $matches;
        list($fullQuery, $whitespaces, $requireQuery, $char, $query) =
            [$fullQuery[0], $whitespaces[0], $requireQuery[0], $query[1], $query[0]];

        $collection = (new FileCollection($query, $this->file->getInputPaths()))
            ->attachDriverStorage($this->file->getDriverStorage());

        // Check dependencies
        if (!count($collection->getFiles())) {
            $line    = count(explode("\n", substr($sources, 0, $char)));
            $message = sprintf('Query "%s" has no found any files.', trim($requireQuery));

            throw (new CompilerException($message))
                ->setFile($this->file->getSplFileObject()->getPathname())
                ->setLine($line);
        }

        return $collection->getFiles();
    }

}


text:
package com.alibaba.dubbo.common.extensionloader.ext1.impl;

import com.alibaba.dubbo.common.Extension;
import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.common.extensionloader.ext1.Ext1;

/**
 * @author ding.lid
 */
@Extension("impl1")
public class Ext1Impl1 implements Ext1 {
    public String echo(URL url, String s) {
        return "Ext1Impl1-echo";
    }

    public String yell(URL url, String s) {
        return "Ext1Impl1-yell";
    }

    public String bang(URL url, int i) {
        return "bang1";
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta name="collection" content="api">

<TITLE>
SearchControls (Java 2 Platform SE 5.0)
</TITLE>

<META NAME="keywords" CONTENT="javax.naming.directory.SearchControls class">
<META NAME="keywords" CONTENT="OBJECT_SCOPE">
<META NAME="keywords" CONTENT="ONELEVEL_SCOPE">
<META NAME="keywords" CONTENT="SUBTREE_SCOPE">
<META NAME="keywords" CONTENT="getSearchScope()">
<META NAME="keywords" CONTENT="getTimeLimit()">
<META NAME="keywords" CONTENT="getDerefLinkFlag()">
<META NAME="keywords" CONTENT="getReturningObjFlag()">
<META NAME="keywords" CONTENT="getCountLimit()">
<META NAME="keywords" CONTENT="getReturningAttributes()">
<META NAME="keywords" CONTENT="setSearchScope()">
<META NAME="keywords" CONTENT="setTimeLimit()">
<META NAME="keywords" CONTENT="setDerefLinkFlag()">
<META NAME="keywords" CONTENT="setReturningObjFlag()">
<META NAME="keywords" CONTENT="setCountLimit()">
<META NAME="keywords" CONTENT="setReturningAttributes()">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

JavaTM 2 Platform
Standard Ed. 5.0

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

javax.naming.directory

Class SearchControls

java.lang.Object
  javax.naming.directory.SearchControls

All Implemented Interfaces:
Serializable

public class SearchControls
extends Object
implements Serializable

This class encapsulates
 factors that determine scope of search and what gets returned
 as a result of the search.

 A SearchControls instance is not synchronized against concurrent
 multithreaded access. Multiple threads trying to access and modify
 a single SearchControls instance should lock the object.

Since:

1.3

See Also:
Serialized Form

Field Summary

static int
OBJECT_SCOPE

          Search the named object.

static int
ONELEVEL_SCOPE

          Search one level of the named context.

static int
SUBTREE_SCOPE

          Search the entire subtree rooted at the named object.

Constructor Summary

SearchControls()

          Constructs a search constraints using defaults.

SearchControls(int scope,
               long countlim,
               int timelim,
               String[] attrs,
               boolean retobj,
               boolean deref)

          Constructs a search constraints using arguments.

Method Summary

 long
getCountLimit()

          Retrieves the maximum number of entries that will be returned
 as a result of the search.

 boolean
getDerefLinkFlag()

          Determines whether links will be dereferenced during the search.

 String[]
getReturningAttributes()

          Retrieves the attributes that will be returned as part of the search.

 boolean
getReturningObjFlag()

          Determines whether objects will be returned as part of the result.

 int
getSearchScope()

          Retrieves the search scope of these SearchControls.

 int
getTimeLimit()

          Retrieves the time limit of these SearchControls in milliseconds.

 void
setCountLimit(long limit)

          Sets the maximum number of entries to be returned
 as a result of the search.

 void
setDerefLinkFlag(boolean on)

          Enables/disables link dereferencing during the search.

 void
setReturningAttributes(String[] attrs)

          Specifies the attributes that will be returned as part of the search.

 void
setReturningObjFlag(boolean on)

          Enables/disables returning objects returned as part of the result.

 void
setSearchScope(int scope)

          Sets the search scope to one of:
 OBJECT_SCOPE, ONELEVEL_SCOPE, SUBTREE_SCOPE.

 void
setTimeLimit(int ms)

          Sets the time limit of these SearchControls in milliseconds.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

OBJECT_SCOPE

public static final int OBJECT_SCOPE

Search the named object.

 The NamingEnumeration that results from search()
 using OBJECT_SCOPE will contain one or zero element.
 The enumeration contains one element if the named object satisfies
 the search filter specified in search().
 The element will have as its name the empty string because the names
 of elements in the NamingEnumeration are relative to the
 target context--in this case, the target context is the named object.
 It contains zero element if the named object does not satisfy
 the search filter specified in search().

 The value of this constant is <tt>0</tt>.

See Also:
Constant Field Values

ONELEVEL_SCOPE

public static final int ONELEVEL_SCOPE

Search one level of the named context.

 The NamingEnumeration that results from search()
 using ONELEVEL_SCOPE contains elements with
 objects in the named context that satisfy
 the search filter specified in search().
 The names of elements in the NamingEnumeration are atomic names
 relative to the named context.

 The value of this constant is <tt>1</tt>.

See Also:
Constant Field Values

SUBTREE_SCOPE

public static final int SUBTREE_SCOPE

Search the entire subtree rooted at the named object.

 If the named object is not a DirContext, search only the object.
 If the named object is a DirContext, search the subtree
 rooted at the named object, including the named object itself.

 The search will not cross naming system boundaries.

 The NamingEnumeration that results from search()
 using SUBTREE_SCOPE contains elements of objects
 from the subtree (including the named context)
 that satisfy the search filter specified in search().
 The names of elements in the NamingEnumeration are either
 relative to the named context or is a URL string.
 If the named context satisfies the search filter, it is
 included in the enumeration with the empty string as
 its name.

 The value of this constant is <tt>2</tt>.

See Also:
Constant Field Values

Constructor Detail

SearchControls

public SearchControls()

Constructs a search constraints using defaults.

 The defaults are:

search one level

no maximum return limit for search results

no time limit for search

return all attributes associated with objects that satisfy
   the search filter.

do not return named object  (return only name and class)

do not dereference links during search

SearchControls

public SearchControls(int scope,
                      long countlim,
                      int timelim,
                      String[] attrs,
                      boolean retobj,
                      boolean deref)

Constructs a search constraints using arguments.

Parameters:
scope - The search scope.  One of:
                        OBJECT_SCOPE, ONELEVEL_SCOPE, SUBTREE_SCOPE.
timelim - The number of milliseconds to wait before returning.
                        If 0, wait indefinitely.
deref - If true, dereference links during search.
countlim - The maximum number of entries to return.  If 0, return
                        all entries that satisfy filter.
retobj - If true, return the object bound to the name of the
                        entry; if false, do not return object.
attrs - The identifiers of the attributes to return along with
                        the entry.  If null, return all attributes. If empty
                        return no attributes.

Method Detail

getSearchScope

public int getSearchScope()

Retrieves the search scope of these SearchControls.

 One of OBJECT_SCOPE, ONELEVEL_SCOPE, SUBTREE_SCOPE.

Returns:
The search scope of this SearchControls.
See Also:
setSearchScope(int)

getTimeLimit

public int getTimeLimit()

Retrieves the time limit of these SearchControls in milliseconds.

 If the value is 0, this means to wait indefinitely.

Returns:
The time limit of these SearchControls in milliseconds.
See Also:
setTimeLimit(int)

getDerefLinkFlag

public boolean getDerefLinkFlag()

Determines whether links will be dereferenced during the search.

Returns:
true if links will be dereferenced; false otherwise.
See Also:
setDerefLinkFlag(boolean)

getReturningObjFlag

public boolean getReturningObjFlag()

Determines whether objects will be returned as part of the result.

Returns:
true if objects will be returned; false otherwise.
See Also:
setReturningObjFlag(boolean)

getCountLimit

public long getCountLimit()

Retrieves the maximum number of entries that will be returned
 as a result of the search.

 0 indicates that all entries will be returned.

Returns:
The maximum number of entries that will be returned.
See Also:
setCountLimit(long)

getReturningAttributes

public String[] getReturningAttributes()

Retrieves the attributes that will be returned as part of the search.

 A value of null indicates that all attributes will be returned.
 An empty array indicates that no attributes are to be returned.

Returns:
An array of attribute ids identifying the attributes that
 will be returned. Can be null.
See Also:
setReturningAttributes(java.lang.String[])

setSearchScope

public void setSearchScope(int scope)

Sets the search scope to one of:
 OBJECT_SCOPE, ONELEVEL_SCOPE, SUBTREE_SCOPE.

Parameters:
scope - The search scope of this SearchControls.
See Also:
getSearchScope()

setTimeLimit

public void setTimeLimit(int ms)

Sets the time limit of these SearchControls in milliseconds.

 If the value is 0, this means to wait indefinitely.

Parameters:
ms - The time limit of these SearchControls in milliseconds.
See Also:
getTimeLimit()

setDerefLinkFlag

public void setDerefLinkFlag(boolean on)

Enables/disables link dereferencing during the search.

Parameters:
on - if true links will be dereferenced; if false, not followed.
See Also:
getDerefLinkFlag()

setReturningObjFlag

public void setReturningObjFlag(boolean on)

Enables/disables returning objects returned as part of the result.

 If disabled, only the name and class of the object is returned.
 If enabled, the object will be returned.

Parameters:
on - if true, objects will be returned; if false,
                        objects will not be returned.
See Also:
getReturningObjFlag()

setCountLimit

public void setCountLimit(long limit)

Sets the maximum number of entries to be returned
 as a result of the search.

 0 indicates no limit:  all entries will be returned.

Parameters:
limit - The maximum number of entries that will be returned.
See Also:
getCountLimit()

setReturningAttributes

public void setReturningAttributes(String[] attrs)

Specifies the attributes that will be returned as part of the search.

 null indicates that all attributes will be returned.
 An empty array indicates no attributes are returned.

Parameters:
attrs - An array of attribute ids identifying the attributes that
                    will be returned. Can be null.
See Also:
getReturningAttributes()

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

JavaTM 2 Platform
Standard Ed. 5.0

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Submit a bug or feature
For further API reference and developer documentation, see Java 2 SDK SE Developer Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 2004, 2010 Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.


text:
import os
import sys

list_conversions = [('import keras.', 'import tensorflow.keras.'),
                    ('import keras ', 'from tensorflow import keras '),
                    ('import keras\n', 'from tensorflow import keras\n'),
                    ('from keras.', 'from tensorflow.keras.'),
                    ('from keras ', 'from tensorflow.keras ')]

def replace_imports_in_text(string, revert):
    if revert:
        list_imports_to_change = [x[::-1] for x in list_conversions]
    else:
        list_imports_to_change = list_conversions

    text_updated = string
    for old_str, new_str in list_imports_to_change:
        text_updated = text_updated.replace(old_str, new_str)
    return text_updated

def replace_imports_in_file(file_path, revert):
    if not file_path.endswith('.py'):
        return False
    if os.path.abspath(file_path) == os.path.abspath(__file__):
        return False
    with open(file_path, 'r') as f:
        text = f.read()

    text_updated = replace_imports_in_text(text, revert)

    with open(file_path, 'w+') as f:
        f.write(text_updated)

    return text_updated != text

def convert_codebase(revert):
    nb_of_files_changed = 0
    keras_dir = os.path.dirname(os.path.abspath(__file__))
    for root, dirs, files in os.walk(keras_dir):
        for name in files:
            if replace_imports_in_file(os.path.join(root, name), revert):
                nb_of_files_changed += 1
    print('Changed imports in ' + str(nb_of_files_changed) + ' files.')
    print('Those files were found in the directory ' + keras_dir)

def convert_to_tf_keras():
    """Convert the codebase to tf.keras"""
    convert_codebase(False)

def convert_to_keras_team_keras():
    """Convert the codebase from tf.keras to keras-team/keras"""
    convert_codebase(True)

def test_replace_imports():
    python_code = """
    import keras
    from keras import backend as K
    import os
    import keras_contrib
    import keras_contrib.layers as lay
    import keras.layers
    from keras.layers import Dense

    if K.backend() == 'tensorflow':
        import tensorflow as tf
        function = tf.max
    """

    expected_code = """
    from tensorflow import keras
    from tensorflow.keras import backend as K
    import os
    import keras_contrib
    import keras_contrib.layers as lay
    import tensorflow.keras.layers
    from tensorflow.keras.layers import Dense

    if K.backend() == 'tensorflow':
        import tensorflow as tf
        function = tf.max
    """

    code_with_replacement = replace_imports_in_text(python_code, False)
    assert expected_code == code_with_replacement
    assert python_code == replace_imports_in_text(code_with_replacement, True)

if __name__ == '__main__':
    if '--revert' in sys.argv:
        convert_to_keras_team_keras()
    else:
        convert_to_tf_keras()