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

import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.CellRendererPane;
import javax.swing.table.*;

import docking.widgets.table.GTable;
import generic.theme.GThemeDefaults.Colors.Palette;
import ghidra.framework.main.datatree.DataTreeDragNDropHandler;
import ghidra.framework.model.DomainFile;
import ghidra.util.ColorUtils;

public class ProjectDataTableDnDHandler implements DragSourceListener, DragGestureListener {

	private static final DataFlavor DOMAIN_FILE_LIST_FLAVOR =
		DataTreeDragNDropHandler.localDomainFileFlavor;
	static final DataFlavor[] ROW_DATA_FLAVORS = { DOMAIN_FILE_LIST_FLAVOR };
	public static List<DomainFileInfo> selectedData;

	private GTable table;
	private ProjectDataTableModel model;

	ProjectDataTableDnDHandler(GTable table, ProjectDataTableModel model) {
		this.table = table;
		this.model = model;

		performMultiSelectionMouseFix();

		DragSource dragSource = DragSource.getDefaultDragSource();
		dragSource.createDefaultDragGestureRecognizer(table, DnDConstants.ACTION_COPY_OR_MOVE,
			this);
	}

	private void performMultiSelectionMouseFix() {

		//
		// Insert our listener into the front of the listeners so that we get a chance to
		// handle events first.
		//

		MouseListener[] oldMouseListeners = table.getMouseListeners();
		MouseMotionListener[] oldMouseMotionListeners = table.getMouseMotionListeners();
		for (MouseListener l : oldMouseListeners) {
			table.removeMouseListener(l);
		}
		for (MouseMotionListener l : oldMouseMotionListeners) {
			table.removeMouseMotionListener(l);
		}

		DnDMouseListener newListener = new DnDMouseListener();
		table.addMouseListener(newListener);
		table.addMouseMotionListener(newListener);

		for (MouseListener l : oldMouseListeners) {
			table.addMouseListener(l);
		}
		for (MouseMotionListener l : oldMouseMotionListeners) {
			table.addMouseMotionListener(l);
		}
	}

//======================================================
// DragSourceListener method
//======================================================
	@Override
	public void dragDropEnd(DragSourceDropEvent dsde) {
//		renderer.setDropRow(-1);
//		oldRow = -1;
		table.repaint();
//		provider.setIgnoreSelectionChange(false);
	}

	@Override
	public void dragEnter(DragSourceDragEvent dsde) {
		// don't care
	}

	@Override
	public void dragExit(DragSourceEvent dse) {
		setCursor(DnDConstants.ACTION_NONE, dse.getDragSourceContext());
	}

	private void setCursor(int action, DragSourceContext dragSourceContext) {
		Cursor cursor = DragSource.DefaultCopyNoDrop;
		switch (action) {
			case DnDConstants.ACTION_COPY:
				cursor = DragSource.DefaultCopyDrop;
				break;
			case DnDConstants.ACTION_MOVE:
				cursor = DragSource.DefaultMoveDrop;
				break;
			case DnDConstants.ACTION_LINK:
				cursor = DragSource.DefaultLinkDrop;
		}
		dragSourceContext.setCursor(cursor);
	}

	@Override
	public void dragOver(DragSourceDragEvent dsde) {
		setCursor(dsde.getDropAction(), dsde.getDragSourceContext());
	}

	@Override
	public void dropActionChanged(DragSourceDragEvent dsde) {
		// don't care
	}

//======================================================
// DragGestureListener method
//======================================================
	@Override
	public void dragGestureRecognized(DragGestureEvent dragEvent) {

		// check input event: if any button other than MB1 is pressed,
		// don't attempt to process the drag and drop event.
		InputEvent ie = dragEvent.getTriggerEvent();
		int modifiers = ie.getModifiersEx();
		if ((modifiers & InputEvent.BUTTON2_DOWN_MASK) != 0 ||
			(modifiers & InputEvent.BUTTON3_DOWN_MASK) != 0) {
			return;
		}

		selectedData = createSelectionList(table);

		Transferable transferable = new DomainFileTransferable(selectedData);
		Image image = getDragImage(selectedData);

		try {

			dragEvent.startDrag(DragSource.DefaultMoveDrop, image, new Point(0, 0), transferable,
				this);
		}
		catch (InvalidDnDOperationException exc) {
			// not sure why, but apparently we don't care
		}
	}

	private Image getDragImage(List<DomainFileInfo> files) {

		Container parent = table.getParent();
		Dimension size = parent.getSize(); // assuming this is JViewport
		BufferedImage bufferedImage =
			new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);

		Graphics graphics = bufferedImage.getGraphics();
		graphics.setClip(0, 0, size.width, size.height);

		paintRecords(files, graphics);

		// now we will create a fade effect using an alpha composite and a gradient
		Graphics2D g2 = (Graphics2D) graphics;
		GradientPaint mask;
		Color treeBackground = table.getBackground();
		Color transparentTreeBackground = ColorUtils.withAlpha(treeBackground, 200);
		mask = new GradientPaint(0, 0, transparentTreeBackground, 0, size.height >> 1,
			Palette.NO_COLOR);
		g2.setPaint(mask);

		// Sets the alpha composite
		g2.setComposite(AlphaComposite.DstIn);

		// Paints the mask
		g2.fillRect(0, 0, size.width, size.height);

		return bufferedImage;
	}

	/** Paint each of the given records that is inside of the clips */
	private void paintRecords(List<DomainFileInfo> records, Graphics g) {
		CellRendererPane rendererPane = new CellRendererPane();
		paintCells(records, rendererPane, g);
	}

	private void paintCells(List<DomainFileInfo> domainFileInfos, CellRendererPane rendererPane,
			Graphics g) {
		TableColumnModel cm = table.getColumnModel();
		int columnMargin = cm.getColumnMargin();

		Rectangle clip = g.getClipBounds();
		int yOffset = clip.y;

		int rowCount = domainFileInfos.size();
		int columnCount = table.getColumnCount();

		int modelRow = model.getRowIndex(domainFileInfos.get(0));
		Rectangle cellRect = table.getCellRect(modelRow, 0, false);
		int startYOffset = cellRect.y;

		TableColumn aColumn;
		int columnWidth;
		for (int row = 0; row < rowCount; row++) {
			if (clip.y + clip.height < yOffset - startYOffset) {
				return; // no need to paint past the end of our visible area
			}

			modelRow = model.getRowIndex(domainFileInfos.get(row));
			cellRect = table.getCellRect(modelRow, 0, false);
			cellRect.y -= startYOffset; // paint the row at the top of the graphics, not where it really lives
			yOffset += cellRect.height;
			for (int column = 0; column < columnCount; column++) {
				aColumn = cm.getColumn(column);
				columnWidth = aColumn.getWidth();
				cellRect.width = columnWidth - columnMargin;
				paintCell(rendererPane, g, cellRect, modelRow, column);
				cellRect.x += columnWidth;
			}
		}
	}

	private void paintCell(CellRendererPane rendererPane, Graphics g, Rectangle cellRect, int row,
			int column) {
		TableCellRenderer tableRenderer = table.getCellRenderer(row, column);
		Component component = table.prepareRenderer(tableRenderer, row, column);
		rendererPane.paintComponent(g, component, table, cellRect.x, cellRect.y, cellRect.width,
			cellRect.height, true);
	}

	private List<DomainFileInfo> createSelectionList(GTable tableToSelect) {
		ArrayList<DomainFileInfo> list = new ArrayList<>();

		int[] rows = table.getSelectedRows();

		if (rows == null) {
			return list;
		}
		for (int row : rows) {
			list.add(model.getRowObject(row));
		}
		return list;
	}

	class DomainFileTransferable implements Transferable {
		private List<DomainFileInfo> list;

		DomainFileTransferable(List<DomainFileInfo> list) {
			this.list = list;
		}

		@Override
		public Object getTransferData(DataFlavor flavor)
				throws UnsupportedFlavorException, IOException {
			if (DOMAIN_FILE_LIST_FLAVOR.equals(flavor)) {
				return getDomainFileList();
			}
			throw new UnsupportedFlavorException(flavor);
		}

		private Object getDomainFileList() {
			List<DomainFile> domainFileList = new ArrayList<>();
			for (DomainFileInfo domainFileInfo : list) {
				domainFileList.add(domainFileInfo.getDomainFile());
			}
			return domainFileList;
		}

		@Override
		public DataFlavor[] getTransferDataFlavors() {
			return ROW_DATA_FLAVORS;
		}

		@Override
		public boolean isDataFlavorSupported(DataFlavor flavor) {
			return DOMAIN_FILE_LIST_FLAVOR.equals(flavor);
		}
	}

	private class DnDMouseListener extends MouseAdapter {

		private boolean consuming = false;

		@Override
		public void mousePressed(MouseEvent e) {
			consuming = maybeConsumeEvent(e);
		}

		@Override
		public void mouseReleased(MouseEvent e) {
			if (!consuming) {
				return;
			}

			// continue to consume the event that was started during the pressed event, for symmetry
			maybeConsumeEvent(e);
			consuming = false;
		}

		@Override
		public void mouseDragged(MouseEvent e) {
			// always consume the drag so that Java does not change the selection
			e.consume();
		}

		private boolean maybeConsumeEvent(MouseEvent e) {

			if (!isBasicLeftClick(e)) {
				return false;
			}

			// don't let other listeners process the event if we are 'pressing' the mouse
			// button on an already selected row (to prevent de-selecting a multi-selection for
			// a drag operation)
			int row = table.rowAtPoint(e.getPoint());
			if (table.isRowSelected(row)) {
				e.consume();
				return true;
			}

			return false;
		}

		private boolean isBasicLeftClick(MouseEvent e) {

			if (e.getButton() != MouseEvent.BUTTON1) {
				return false;
			}

			if (e.getClickCount() > 1) {
				return false;
			}

			if (e.isControlDown() || e.isAltDown() || e.isShiftDown() || e.isMetaDown()) {
				return false;
			}

			return true;
		}
	}

}


text:
[![Build Status](https://travis-ci.org/UWFlow/rmc.svg?branch=master)](https://travis-ci.org/UWFlow/rmc)

# Flow

Plan your courses

## Getting up and running

To set up your dev environment, run `make install`.

We work inside a [virtualenv][], so remember to `source
~/.virtualenv/rmc/bin/activate` whenever you're working within the repo.

You should now be ready to boot the local server, with `make local`.

Once it starts running, point your browser to http://localhost:5000/

### MongoDB error on Linux

If you are getting a connection refused error when trying to run `make local` and are on Linux, this is
most likely due to MongoDB taking too long to start the first time it's run. To fix this, run `mongod --config config/mongodb_local.conf`
and let it warm up for about 30 seconds to 1 minute. Then kill the process, and run `make local` again. It should work now.

### Getting seed data

Run the following to get some basic course data into the DB.

```sh
make init_data
```

### Dependency issues on Linux

You may encounter errors regarding inheritance issues, invalid json conversions, or missing mock data while/after running `make install`, `make init_data`, or `make local`. If this is the case, you might have the wrong dependency versions installed or the installation didn't include certain dependencies in the first place. You can check by comparing `requirements.txt` with `pip freeze`.

If they are different, replace the dependencies you currently have using:
```sh
pip freeze | xargs pip uninstall -y
pip install -r requirements.txt
```
## Why RMC?

It might seem funny that this repository and a bunch of the code references `rmc`.

RMC stands for "Rate My Courses", which was the prototype name for this project
before it was given the (slightly) better name of Flow.

Because of the profileration of this 3 letter prefix throughout the code, and the
unfortunate coupling of the repository name and our python namespace, we decided
to leave it be.

## Directory structure

If you're eager to dive into the code, you might want to read this first. This
isn't exhaustive, but it should be enough to get you started if you want to contribute.

- `config/`: Configuration for frameworks, databases, or anything that might vary between
            the development environment and production.
- `data/`: This is where we collect data and load it into the database
    - `crawler.py` downloads data by scraping pages and hitting APIs
    - `processor.py` processes the data grabbed by `crawler.py` and loads it into the DB
    - `aggregator.py` is run on a regular schedule (daily for the most part) to keep our data up to date
- `models/`: "Schema" definitions for our models backed by [MongoEngine][]
- `server/`: Request handlers, static assets, and templates
    - `templates/`: [Jinja2][] templates
        - Files in here ending with `_page.html` (e.g. `course_page.html`) are rendered directly by the
          [Flask][] server with `render_template` calls, with the exception of the `base_*_page.html`
          files which other `_page.html` templates inherit from.
        - Most of the other files (e.g. `course.html`) contain [Underscore templates][] used to render
          stuff on the client-side
    - `static`: Static assets eventually ending up as files served directly by [nginx][] when on production
        - `js`: All our JavaScript code, organized into [RequireJS][] modules
            - `ext/`: All third party JavaScript code
            - `main.js`: The entry point for JavaScript executing on page load
        - `sass`: We don't write CSS directly for Flow, we use the SCSS flavor of [Sass][], which compiles
                  down to CSS
    - `server.py`: The majority of the request handlers for the application, written in [Flask][]

[MongoEngine]: http://mongoengine.org/
[Jinja2]: http://jinja.pocoo.org/docs/
[Flask]: http://flask.pocoo.org/
[Underscore templates]: http://underscorejs.org/#template
[nginx]: http://wiki.nginx.org/Main
[RequireJS]: http://requirejs.org/
[Sass]: http://sass-lang.com/

## Using the REPL

If you need a REPL to fool around with the database or test out some code, check
out `tools/devshell.py`.

It automatically loads some imports and connects to the database for you. This
setup code can be found in `tools/devshell_eval.py`.

Here's what an example session might look like:

    $ tools/devshell.py
    Python 2.7.1 (r271:86832, Jul 31 2011, 19:30:53)
    Type "copyright", "credits" or "license" for more information.

    IPython 0.13.1 -- An enhanced Interactive Python.
    ?         -> Introduction and overview of IPython's features.
    %quickref -> Quick reference.
    help      -> Python's own help system.
    object?   -> Details about 'object', use 'object??' for extra details.

    In [1]: m.User.objects(first_name__in=['Jamie', 'David', 'Sandy', 'Mack'],
    last_name__in=['Wong', 'Hu', 'Duan', 'Wu'])
    Out[1]: [<User: David Hu>, <User: Mack Duan>, <User: Sandy Wu>, <User: Jamie Wong>]

[virtualenv]: http://www.virtualenv.org/en/latest/

## Running tests

To run all the tests in the entire system:

```
make alltest
```

To run all the tests except the really slow ones (namely [Selenium][] tests):

```
make test
```

To run all the tests under a specific directory tree or in a specific file:
```
PYTHONPATH=.. nosetests server/api
PYTHONPATH=.. nosetests server/api/v1_test.py
```

[Selenium]: http://docs.seleniumhq.org/projects/webdriver/

## Contributing

When you're ready to contribute, take a look at [the contributing
guidelines](https://github.com/UWFlow/rmc/blob/master/CONTRIBUTING.md) and our
[style guide](https://github.com/UWFlow/rmc/wiki/Flow-Style-Guide).

redpajama_set_name: RedPajamaGithub


text:
package org.pbrt.core;

public class Film {

    // Film Private Data
    private class Pixel {
        Pixel() {}
        float xyz[] = {0, 0, 0};
        float filterWeightSum = 0;
        AtomicFloat splatXYZ[] = {new AtomicFloat(0), new AtomicFloat(0), new AtomicFloat(0)};
    }
    private Pixel[] pixels;
    private static final int filterTableWidth = 16;
    private float filterTable[] = new float[filterTableWidth * filterTableWidth];
    private final float scale;
    private final float maxSampleLuminance;

    // FilmTilePixel Declarations
    public class FilmTilePixel {
        Spectrum contribSum = new Spectrum(0);
        float filterWeightSum = 0;
    }

    public class FilmTile {
        // FilmTile Public Methods
        public FilmTile(Bounds2i pixelBounds, Vector2f filterRadius,
             float[] filterTable, int filterTableSize, float maxSampleLuminance) {
            this.pixelBounds = pixelBounds;
            this.filterRadius = filterRadius;
            this.invFilterRadius = new Vector2f(1 / filterRadius.x, 1 / filterRadius.y);
            this.filterTable = filterTable;
            this.filterTableSize = filterTableSize;
            this.maxSampleLuminance = maxSampleLuminance;
            this.pixels = new FilmTilePixel[Math.max(0, pixelBounds.Area())];
            for (int i = 0; i < this.pixels.length; i++) {
                this.pixels[i] = new FilmTilePixel();
            }
        }
        public void AddSample(Point2f pFilm, Spectrum L, float sampleWeight) {
            if (L.y() > maxSampleLuminance)
                L.scale(maxSampleLuminance / L.y());

            // Compute sample's raster bounds
            Point2f pFilmDiscrete = pFilm.subtract(new Vector2f(0.5f, 0.5f));
            Point2i p0 = new Point2i(Point2f.Ceil(pFilmDiscrete.subtract(filterRadius)));
            Point2i p1 = new Point2i(Point2f.Floor(pFilmDiscrete.add(filterRadius))).add(new Point2i(1, 1));
            p0 = Point2i.Max(p0, pixelBounds.pMin);
            p1 = Point2i.Min(p1, pixelBounds.pMax);

            // Loop over filter support and add sample to pixel arrays

            // Precompute $x$ and $y$ filter table offsets
            int[] ifx = new int[p1.x - p0.x];
            for (int x = p0.x; x < p1.x; ++x) {
                float fx = Math.abs((x - pFilmDiscrete.x) * invFilterRadius.x *
                        filterTableSize);
                ifx[x - p0.x] = Math.min((int)Math.floor(fx), filterTableSize - 1);
            }
            int[] ify = new int[p1.y - p0.y];
            for (int y = p0.y; y < p1.y; ++y) {
                float fy = Math.abs((y - pFilmDiscrete.y) * invFilterRadius.y *
                        filterTableSize);
                ify[y - p0.y] = Math.min((int)Math.floor(fy), filterTableSize - 1);
            }
            for (int y = p0.y; y < p1.y; ++y) {
                for (int x = p0.x; x < p1.x; ++x) {
                    // Evaluate filter value at $(x,y)$ pixel
                    int offset = ify[y - p0.y] * filterTableSize + ifx[x - p0.x];
                    float filterWeight = filterTable[offset];

                    // Update pixel values with filtered sample contribution
                    FilmTilePixel pixel = GetPixel(new Point2i(x, y));
                    pixel.contribSum = Spectrum.Add(pixel.contribSum, Spectrum.Scale(L, sampleWeight * filterWeight));
                    pixel.filterWeightSum += filterWeight;
                }
            }
        }
        public FilmTilePixel GetPixel(Point2i p) {
            assert (Bounds2i.InsideExclusive(p, pixelBounds));
            int width = pixelBounds.pMax.x - pixelBounds.pMin.x;
            int offset = (p.x - pixelBounds.pMin.x) + (p.y - pixelBounds.pMin.y) * width;
            return pixels[offset];
        }
        public Bounds2i GetPixelBounds() { return pixelBounds; }

        // FilmTile Private Data
        private Bounds2i pixelBounds;
        private Vector2f filterRadius, invFilterRadius;
        private float[] filterTable;
        private int filterTableSize;
        private FilmTilePixel[] pixels;
        private float maxSampleLuminance;
    }

    // Film Public Methods
    public Film(Point2i resolution, Bounds2f cropWindow, Filter filter, float diagonal, String filename, float scale, float maxSampleLuminance) {
        this.fullResolution = resolution;
        this.diagonal = diagonal * 0.001f;
        this.filter = filter;
        this.filename = filename;
        this.scale = scale;
        this.maxSampleLuminance = maxSampleLuminance;

        // Compute film image bounds
        this.croppedPixelBounds =
                new Bounds2i(new Point2i((int)Math.ceil(fullResolution.x * cropWindow.pMin.x),
                        (int)Math.ceil(fullResolution.y * cropWindow.pMin.y)),
                new Point2i((int)Math.ceil(fullResolution.x * cropWindow.pMax.x),
                        (int)Math.ceil(fullResolution.y * cropWindow.pMax.y)));
        PBrtTLogger.Info("Created film with full resolution %s. Crop window of %s -> croppedPixelBounds %s", resolution.toString(), cropWindow, croppedPixelBounds);

        // Allocate film image storage
        this.pixels = new Pixel[croppedPixelBounds.Area()];
        for (int i = 0; i < this.pixels.length; i++) this.pixels[i] = new Pixel();
        filmPixelMemory.increment(croppedPixelBounds.Area() * 8*4);

        // Precompute filter weight table
        int offset = 0;
        for (int y = 0; y < filterTableWidth; ++y) {
            for (int x = 0; x < filterTableWidth; ++x, ++offset) {
                Point2f p = new Point2f();
                p.x = (x + 0.5f) * filter.radius.x / filterTableWidth;
                p.y = (y + 0.5f) * filter.radius.y / filterTableWidth;
                filterTable[offset] = filter.Evaluate(p);
            }
        }
    }

    public Bounds2i GetSampleBounds() {
        Vector2f halfPixel = new Vector2f(0.5f, 0.5f);
        Bounds2f floatBounds = new Bounds2f(Point2f.Floor(new Point2f(croppedPixelBounds.pMin).add(halfPixel.subtract(filter.radius))),
                Point2f.Ceil(new Point2f(croppedPixelBounds.pMax).subtract(halfPixel.add(filter.radius))));
        return new Bounds2i(floatBounds);
    }

    public Bounds2f GetPhysicalExtent() {
        float aspect = (float)fullResolution.y / (float)fullResolution.x;
        float x = (float)Math.sqrt(diagonal * diagonal / (1 + aspect * aspect));
        float y = aspect * x;
        return new Bounds2f(new Point2f(-x / 2, -y / 2), new Point2f(x / 2, y / 2));
    }

    public FilmTile GetFilmTile(Bounds2i sampleBounds) {
        // Bound image pixels that samples in _sampleBounds_ contribute to
        Vector2f halfPixel = new Vector2f(0.5f, 0.5f);
        Bounds2f floatBounds = new Bounds2f(sampleBounds);
        Point2i p0 = new Point2i(Point2f.Ceil(floatBounds.pMin.subtract(halfPixel).subtract(filter.radius)));
        Point2i p1 = new Point2i(Point2f.Floor(floatBounds.pMax.subtract(halfPixel).add(filter.radius))).add(new Point2i(1, 1));
        Bounds2i tilePixelBounds = Bounds2i.Intersect(new Bounds2i(p0, p1), croppedPixelBounds);
        return new FilmTile(tilePixelBounds, filter.radius, filterTable, filterTableWidth, maxSampleLuminance);
    }

    public void MergeFilmTile(FilmTile tile) {
        //Api.logger.trace("Merging film tile %s", tile.pixelBounds.toString());
        //std::lock_guard<std::mutex> lock(mutex);
        for (int y = tile.GetPixelBounds().pMin.y; y < tile.GetPixelBounds().pMax.y; y++) {
            for (int x = tile.GetPixelBounds().pMin.x; x < tile.GetPixelBounds().pMax.x; x++) {
                Point2i pixel = new Point2i(x, y);
                // Merge _pixel_ into _Film::pixels_
                final FilmTilePixel tilePixel = tile.GetPixel(pixel);
                Pixel mergePixel = GetPixel(pixel);
                float[] xyz = tilePixel.contribSum.toXYZ();
                for (int i = 0; i < 3; ++i) mergePixel.xyz[i] += xyz[i];
                mergePixel.filterWeightSum += tilePixel.filterWeightSum;
                SetPixel(pixel, mergePixel);
            }
        }
    }

    public void SetImage(Spectrum[] img) {
        int nPixels = croppedPixelBounds.Area();
        for (int i = 0; i < nPixels; ++i) {
            Pixel p = pixels[i];
            p.xyz = img[i].toXYZ();
            p.filterWeightSum = 1;
            p.splatXYZ[0].set(0);
            p.splatXYZ[1].set(0);
            p.splatXYZ[2].set(0);
        }
    }

    public void AddSplat(Point2f p, Spectrum v) {
        if (v.hasNaNs()) {
            PBrtTLogger.Error("Ignoring splatted spectrum with NaN values at (%f, %f)", p.x, p.y);
            return;
        } else if (v.y() < 0) {
            PBrtTLogger.Error("Ignoring splatted spectrum with negative luminance %f at (%f, %f)", v.y(), p.x, p.y);
            return;
        } else if (Float.isInfinite(v.y())) {
            PBrtTLogger.Error("Ignoring splatted spectrum with infinite luminance at (%f, %f)", p.x, p.y);
            return;
        }

        Point2i pi = new Point2i((int)Math.floor(p.x), (int)Math.floor(p.y));
        if (!Bounds2i.InsideExclusive(pi, croppedPixelBounds)) return;

        if (v.y() > maxSampleLuminance)
            v = v.scale(maxSampleLuminance / v.y());
        float[] xyz = v.toXYZ();
        Pixel pixel = GetPixel(pi);
        for (int i = 0; i < 3; ++i) pixel.splatXYZ[i].add(xyz[i]);

    }

    public void WriteImage(float splatScale) {

        // Convert image to RGB and compute final pixel values
        //LOG(INFO) << "Converting image to RGB and computing final weighted pixel values";
        float[] pixRGB = new float[3];
        float[] splatRGB = new float[3];
        float[] rgb = new float[3 * croppedPixelBounds.Area()];
        int offset = 0;
        for (int py = croppedPixelBounds.pMin.y; py < croppedPixelBounds.pMax.y; py++) {
            for (int px = croppedPixelBounds.pMin.x; px < croppedPixelBounds.pMax.x; px++) {
                Point2i p = new Point2i(px, py);

                // Convert pixel XYZ color to RGB
                Pixel pixel = GetPixel(p);
                pixRGB = Spectrum.XYZToRGB(pixel.xyz, pixRGB);
                rgb[3 * offset] = pixRGB[0];
                rgb[3 * offset+1] = pixRGB[1];
                rgb[3 * offset+2] = pixRGB[2];

                // Normalize pixel with weight sum
                float filterWeightSum = pixel.filterWeightSum;
                if (filterWeightSum != 0) {
                    float invWt = 1 / filterWeightSum;
                    rgb[3 * offset] = Math.max(0, rgb[3 * offset] * invWt);
                    rgb[3 * offset + 1] = Math.max(0, rgb[3 * offset + 1] * invWt);
                    rgb[3 * offset + 2] = Math.max(0, rgb[3 * offset + 2] * invWt);
                }

                // Add splat value at pixel
                float[] splatXYZ = {pixel.splatXYZ[0].get(), pixel.splatXYZ[1].get(), pixel.splatXYZ[2].get()};
                splatRGB = Spectrum.XYZToRGB(splatXYZ, splatRGB);
                rgb[3 * offset] += splatScale * splatRGB[0];
                rgb[3 * offset + 1] += splatScale * splatRGB[1];
                rgb[3 * offset + 2] += splatScale * splatRGB[2];

                // Scale pixel value by _scale_
                rgb[3 * offset] *= scale;
                rgb[3 * offset + 1] *= scale;
                rgb[3 * offset + 2] *= scale;
                ++offset;
            }
        }

        // Write RGB image
        PBrtTLogger.Info("Writing image %s with bounds %s", filename, croppedPixelBounds.toString());
        ImageIO.Write(filename, rgb, croppedPixelBounds, fullResolution);
    }

    public void Clear() {
        for (int py = croppedPixelBounds.pMin.y; py < croppedPixelBounds.pMax.y; py++) {
            for (int px = croppedPixelBounds.pMin.x; px < croppedPixelBounds.pMax.x; px++) {
                Point2i p = new Point2i(px, py);
                Pixel pixel = GetPixel(p);
                for (int c = 0; c < 3; ++c) {
                    pixel.splatXYZ[c].set(0);
                    pixel.xyz[c] = 0;
                }
                pixel.filterWeightSum = 0;
            }
        }
    }

    // Film Public Data
    public final Point2i fullResolution;
    public final float diagonal;
    public Filter filter;
    public final String filename;
    public Bounds2i croppedPixelBounds;

    public static Film Create(ParamSet paramSet, Filter filter) {
        String filename = new String();
        if (!Pbrt.options.ImageFile.isEmpty()) {
            filename = Pbrt.options.ImageFile;
            String paramsFilename = paramSet.FindOneString("filename", "");
            if (!paramsFilename.isEmpty()) {
                PBrtTLogger.Warning("Output filename supplied on command line, \"%s\" is overriding " +
                        "filename provided in scene description file, \"%s\".",
                        Pbrt.options.ImageFile, paramsFilename);
            } else {
                filename = Pbrt.options.ImageFile;
            }
        }
        else {
            filename = paramSet.FindOneString("filename", "pbrt.exr");
        }

        int xres = paramSet.FindOneInt("xresolution", 1280);
        int yres = paramSet.FindOneInt("yresolution", 720);
        if (Pbrt.options.QuickRender) xres = Math.max(1, xres / 4);
        if (Pbrt.options.QuickRender) yres = Math.max(1, yres / 4);
        Bounds2f crop = new Bounds2f(new Point2f(0, 0), new Point2f(1, 1));
        Float[] cr = paramSet.FindFloat("cropwindow");
        if (cr != null && cr.length == 4) {
            crop.pMin.x = Pbrt.Clamp(Math.min(cr[0], cr[1]), 0, 1);
            crop.pMax.x = Pbrt.Clamp(Math.max(cr[0], cr[1]), 0, 1);
            crop.pMin.y = Pbrt.Clamp(Math.min(cr[2], cr[3]), 0, 1);
            crop.pMax.y = Pbrt.Clamp(Math.max(cr[2], cr[3]), 0, 1);
        } else if (cr != null) {
            PBrtTLogger.Error("%d values supplied for \"cropwindow\". Expected 4.", cr.length);
        } else {
            crop = new Bounds2f(new Point2f(Pbrt.Clamp(Pbrt.options.CropWindow[0][0], 0, 1),
                                Pbrt.Clamp(Pbrt.options.CropWindow[1][0], 0, 1)),
                        new Point2f(Pbrt.Clamp(Pbrt.options.CropWindow[0][1], 0, 1),
                                Pbrt.Clamp(Pbrt.options.CropWindow[1][1], 0, 1)));
        }

        float scale = paramSet.FindOneFloat("scale", 1);
        float diagonal = paramSet.FindOneFloat("diagonal", 35);
        float maxSampleLuminance = paramSet.FindOneFloat("maxsampleluminance", Pbrt.Infinity);
        return new Film(new Point2i(xres, yres), crop, filter, diagonal, filename, scale, maxSampleLuminance);
    }

    // Film Private Methods
    private Pixel GetPixel(Point2i p) {
        assert (Bounds2i.InsideExclusive(p, croppedPixelBounds));
        int width = croppedPixelBounds.pMax.x - croppedPixelBounds.pMin.x;
        int offset = (p.x - croppedPixelBounds.pMin.x) + (p.y - croppedPixelBounds.pMin.y) * width;
        return pixels[offset];
    }
    private void SetPixel(Point2i p, Pixel pix) {
        assert (Bounds2i.InsideExclusive(p, croppedPixelBounds));
        int width = croppedPixelBounds.pMax.x - croppedPixelBounds.pMin.x;
        int offset = (p.x - croppedPixelBounds.pMin.x) + (p.y - croppedPixelBounds.pMin.y) * width;
        pixels[offset] = pix;
    }

    private static Stats.MemoryCounter filmPixelMemory = new Stats.MemoryCounter("Memory/Film pixels");

}


text:
'use strict';

var assign     = require('es5-ext/object/assign')
  , isObject   = require('es5-ext/object/is-object')
  , startsWith = require('es5-ext/string/#/starts-with')

  , getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor
  , defineProperty = Object.defineProperty
  , hasOwnProperty = Object.prototype.hasOwnProperty;

module.exports = function (obj, name, desc) {
	var old;
	if (
		// Error - fallback to native
		!isObject(obj) || !isObject(desc) ||
			// If it's defined for first time - will work
			!hasOwnProperty.call(obj, name) ||
			// Will be writable - will work
			desc.writable ||
			// Is writable - will work
			((old = getOwnPropertyDescriptor(obj, name)) && (old.writable ||
				// Error - fallback to native
				!old.configurable))
	) {
		try {
			return defineProperty(obj, name, desc);
		} catch (e) {
			if (!startsWith.call(e.message,
					"defineProperty is not supported on ") || !('value' in desc)) {
				throw e;
			}
			// Fallback to direct assign
			obj[name] = desc.value;
			return obj;
		}
	}
	delete obj[name];
	if (!old) return defineProperty(obj, name, desc);
	if (('get' in desc) || ('set' in desc)) {
		delete old.value;
	} else {
		delete old.get;
		delete old.set;
	}
	return defineProperty(obj, name, assign(old, desc));
};


text:
htpasswd -c -i -b auth.htpasswd USERNAME PASSWORD \
&& touch newfile \
&& cat <<EOF > Dockerfile
FROM google/cadvisor:latest
ADD auth.htpasswd /auth.htpasswd

EXPOSE 8080
ENTRYPOINT ["/usr/bin/cadvisor", "--http_auth_file", "auth.htpasswd", "--http_auth_realm", "localhost"]
EOF
docker build -t cadvisor . \
&& docker run \
  --volume=/:/rootfs:ro \
  --volume=/var/run:/var/run:rw \
  --volume=/sys:/sys:ro \
  --volume=/var/lib/docker/:/var/lib/docker:ro \
  --volume=/dev/disk/:/dev/disk:ro \
  --publish=8080:8080 \
  --detach=true \
  --name=cadvisor \
  --restart=always \
 cadvisor


text:
<?php

namespace Concrete\Controller\Backend;

use Concrete\Core\Command\Process\ProcessConfigurationResponseFactory;
use Concrete\Core\Command\Process\ProcessResponseFactory;
use Concrete\Core\Controller\AbstractController;
use Concrete\Core\Entity\Command\Process;
use Concrete\Core\Validation\CSRF\Token;
use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpFoundation\JsonResponse;

class Processes extends AbstractController
{

    /**
     * @var Token
     */
    protected $token;

    /**
     * @var EntityManager
     */
    protected $entityManager;

    /**
     * @var
     */
    protected $responseFactory;

    /**
     * @var ProcessConfigurationResponseFactory
     */
    protected $configurationResponseFactory;

    public function __construct(
        Token $token,
        EntityManager $entityManager,
        ProcessResponseFactory $responseFactory,
        ProcessConfigurationResponseFactory $configurationResponseFactory
    ) {
        $this->token = $token;
        $this->entityManager = $entityManager;
        $this->responseFactory = $responseFactory;
        $this->configurationResponseFactory = $configurationResponseFactory;
        parent::__construct();
    }

    public function getConfiguration()
    {
        if ($this->token->validate()) {
            return $this->configurationResponseFactory->createResponse();
        }
        throw new \Exception(t('Access Denied'));
    }

    public function poll()
    {
        if ($this->token->validate('poll', $this->request->request->get('token'))) {
            session_write_close();

            $processes = [];
            foreach ((array) $this->request->request->get('watchedProcessIds') as $processId) {
                $process = $this->entityManager->find(Process::class, $processId);
                if ($process) {
                    $processes[] = $process;
                }
            }

            return $this->responseFactory->createResponse($processes);
        }
        throw new \Exception(t('Access Denied'));
    }

}


text:
    Attendance

  <input data-name="attendance-url" data-value="<?= base_url('attendance/log')?>" disabled>
  <object id="webcard" type="application/x-webcard" width="0" height="0">
    <param name="onload" value="pluginLoaded" />
  </object>

              Department

              Time in

              Time out


text:
% read_bin_list_file() - Extracts "bin" information from a text file called
%         a "bin list file."  The bin list file (blf) indicates which types
%         of events belong to which bins.  Each line of the blf needs to
%         start with a number followed by a closed parenthesis, which
%         indicates the bin number.  Next comes a string, number, or a
%         series of numbers indicting the "type" of events that fall in
%         that bin (note the "type" of an event is stored in the field
%         EEG.epoch(#).eventtype and EEG.event(#).type of an EEGLAB EEG
%         variable).  Finally, comes an equal sign and text that describes
%         the kinds of trials that fall into that bin.
%
% For example, the following line would classify epochs of type 22 as
% members of Bin 1, which is described as containing "Targets in Auditory Task".
% 1) 22=Targets in Auditory Task
%
% The following would classify epochs of type 22 and 26 as members of Bin 1,
% which is described as containing "Targets in Auditory Task".
% 1) 22 26=Targets in Auditory Task
%
% The following would classify epochs of type 22, 23, 24 and 25 as members
% of Bin 1, which is described as containing "Targets in Auditory Task"
% (note that using MATLAB notation to indicate vectors is acceptable).
% 1) 22:25=Targets in Auditory Task
%
% The following would classify epochs of type 'aud_targ' as members of Bin 1,
% which is described as containing "Targets in Auditory Task".
% 1) aud_targ=Targets in Auditory Task
%
% The following would classify epochs of type 'aud targ' as members of Bin 1,
% which is described as containing "Targets in Auditory Task". Note, the
% use of single quotes to include the space in the type name.  Without the
% single quotes, two types would be read: "aud" and "targ".
% 1) 'aud targ'=Targets in Auditory Task
%
%
% Usage:
%  >> [bindesc, bintype]=read_bin_list_file(blf_fname, verblevel);
%
%
% Required Input:
%   blf_fname  - [string] A set of integers specifying the subject ID
%                numbers to include in the grand average.  Only necessary
%                if a filename template is given as the input to
%                gui_infiles_or_tmplt.
%
% Optional Input:
%   verblevel        - An integer specifiying the amount of information you want
%                      this function to provide about what it is doing during runtime.
%                       Options are:
%                        0 - quiet, only show errors, warnings, and EEGLAB reports
%                        1 - stuff anyone should probably know
%                        2 - stuff you should know the first time you start working
%                            with a data set {default value if not globally specified}
%                        3 - stuff that might help you debug (show all
%                            reports)
%
% Output:
%   bindesc  - A cell array of strings describing the contents of each bin.
%   bintype  - A cell array of cell arrays of strings listing the types of
%              events that fall in each bin
%
% Global Variable:
%   VERBLEVEL - Mass Univariate ERP Toolbox level of verbosity (i.e., tells
%               functions how much to report about what they're doing during
%               runtime) set by the optional function argument 'verblevel'
%
%
% NOTES:
% -You can use single quotes to define type names that have spaces in them
% (e.g., 'S  1').  However you may only do this once per line of your blf
% file.  In other words you can have exactly zero or two single quotes per
% line.
%
% Author:
% David Groppe
% Kutaslab, 9/2010

%%%%%%%%%%%%%%%% Future Work  %%%%%%%%%%%%%%%%%
%

function [bindesc, bintype]=read_bin_list_file(blf_fname, verblevel)

if nargin<2,
   verblevel=2;
end

[fid, msg]=fopen(blf_fname);
if fid==-1,
    error('Couldn''t open blf file %s because: %s',blf_fname,msg);
end
line_ct=0;
n_bin=0;
while 1
    tline = fgetl(fid);
    if ~ischar(tline),
        break; %leave while loop
    end
    line_ct=line_ct+1;
    [bin_str tline]=strtok(tline);
    bin_id(line_ct)=str2double(bin_str(1:length(bin_str)-1)); %str2double returns NaN if the string it's converting contains alpha numeric characters
    if isnan(bin_id(line_ct)),
        error('Line #%d of file %s should start with a bin number followed by a close parenthesis\n',line_ct, ...
            blf_fname,line_ct);
    end
    eql_id=0;
    for a=1:length(tline),
        if tline(a)=='=',
            eql_id=a;
            break;
        end
    end
    if eql_id,
        line_type=rm_leading_whitespace(tline(1:eql_id-1));
        line_type_as_num=str2num(line_type); %str2num returns the empty set
        %if the string cannot be interpreted as numbers at the MATLAB command line (e.g., ':')
        if ~isempty(line_type_as_num),
           line_type=num2str(line_type_as_num); %convert it back to string
        end
        if line_type(1)==39,
           if sum(line_type==39)~=2,
              error('Problem with Line %d. You can only use a pair of single quotes to indicate a type.',line_ct);
           end
           quote_locs=find(line_type==39);
           type_array{1}=line_type(2:quote_locs(2)-1);
        else
            type_array=strread(line_type,'%s');
        end
    else
        error('Line %d needs to have an equals sign\n',line_ct);
    end

    if (bin_id(line_ct)>n_bin) || isempty(bindesc{bin_id(line_ct)})
        %new bin
        bindesc{bin_id(line_ct)}=rm_leading_whitespace(tline(eql_id+1:end));
        n_bin=n_bin+1;
        n_type=length(type_array);
        for x=1:n_type,
           bintype{bin_id(line_ct)}{x}=type_array{x};
        end
    else
       %The bin for this line has already been entered, make sure it's
       %consistent
       neo_bindesc=rm_leading_whitespace(tline(eql_id+1:end));
       if ~strcmpi(neo_bindesc,bindesc{bin_id(line_ct)})
           error('Bin descriptor on Line %d (%s) does not equal previous descriptor for that bin (i.e., Bin %d: %s)', ...
               line_ct,neo_bindesc,bin_id(line_ct),bindesc{bin_id(line_ct)});
       end
       n_old_type=length(bintype{bin_id(line_ct)});
       n_new_type=length(type_array);
       for x=1:n_new_type,
           bintype{bin_id(line_ct)}{x+n_old_type}=type_array{x};
       end
    end
end
fclose(fid);

%% Error checking

%Make sure Bin ID #'s are contiguous and start with 1
uni_bin=unique(bin_id);
if max(abs(uni_bin-[1:n_bin])),
   error('Bin numbers need to be contiguous and start a "1".  Your bin numbers are: %s\n',num2str(uni_bin));
end

%Get rid of redundant types (just in case)
for a=1:n_bin,
    bintype{a}=unique(bintype{a});
end

if verblevel>1,
    %Print which event types belong to each bin for user to double check
    for a=1:n_bin,
        fprintf('\nBin %d: %s\n',a,bindesc{a});
        fprintf('Event types belonging to this bin:')
        for b=1:length(bintype{a})
            fprintf(' ''%s''',bintype{a}{b});
        end
        fprintf('\n')
    end
end

function str=rm_leading_whitespace(str)

n=length(str);
for a=1:n,
   if str(a)~=' ',
      str=str(a:end);
      break;
   end
end


text:
<?php
namespace ImmutableStateStatusTracker\Exception;

use Exception;

class CalculatingJobStatusException extends Exception
{
}


text:
In computer operating systems, virtual memory is a management technique to handle the computer's primary memory. A page, memory page or virtual page is a fixed-length contiguous block of virtual memory and in similar a page frame is the smallest fixed-length contiguous block of physical memory. Virtual memory maps the virtual addresses (organized in pages) used by a program into physical addresses (organized in page frames) in computer memory, using a page table, which is a data structure to store this mapping.

![Inverted page table](https://github.com/chanioxaris/virtual-memory/blob/master/img/IPT.png)

This program simulates the function of an operation system that uses paging for virtual memory management, alongside with Inverted page table and Flush When Full (FWF) as a page replacement algorithm. Round-robin algorithm is used for scheduling between the reference traces of two processes.

### Inverted page table (IPT)

Inverted page table is a advanced type of page table. In contrast with classical (where each process has it's own), inverted page table is global and maintained by the operating system for all the processes. There is just one page table in the entire system, implying that additional information needs to be stored in the page table to identify page table entries corresponding to each process.
<br />
The page table stores the frame number into an array indexed by page number: given the page number, the frame number is achieved by a simple indexed load. An inverted page table stores the page number in an array indexed by frame number. Given the page number, you search for the entry with that page number: the entry number specifies the frame.

### Flush When Full (FTW)

Flush When Full algorithm allows up to k page faults to occur for a single process. When the k+1 page fault appears, all pages from the specific process in page table are evicted (flush).

### Round-robin algorithm (RR)
Round-robin (RR) is one of the algorithms employed by process schedulers. To schedule processes fairly, a round-robin scheduler generally employs time-sharing, giving each job a time slot or quantum (its allowance of CPU time), and interrupting the job if it is not completed by then. The job is resumed next time a time slot is assigned to that process. The scheduler selects the first process in the ready queue to execute, thus handling all processes without priority.

## Statistics

After the simulation is over, some statistics are printed which are:
- Number of Page Faults occured
- Number of writes back on disk for the dirty traces
- Number of reads from disk
- Number of total traces

The below table includes the results of the simulation for different numbers of input argument k (FWF parameter)

|         | Page Faults | PT Frames  | Reads | Writes | Traces |
| :------ | :---------: | :--------: | :---: | :----: | :----: |
| k = 10  |     817     |     20     |  817  |   506  |  2000  |
| k = 25  |     582     |     50     |  582  |   361  |  2000  |
| k = 50  |     496     |     100    |  496  |   318  |  2000  |
| k = 100 |     439     |     200    |  439  |   280  |  2000  |
| k = 250 |     399     |     500    |  399  |   255  |  2000  |

## Compile

`./makefile`

## Usage

`./simulation -k [parameter of FWF algorithm] -q [round-robin quantum] -m [number of traces to examine]`


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

import javax.annotation.Generated;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum SortTrialComponentsBy {

    Name("Name"),
    CreationTime("CreationTime");

    private String value;

    private SortTrialComponentsBy(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return SortTrialComponentsBy corresponding to the value
     *
     * @throws IllegalArgumentException
     *         If the specified value does not map to one of the known values in this enum.
     */
    public static SortTrialComponentsBy fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (SortTrialComponentsBy enumEntry : SortTrialComponentsBy.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
#import "CALayer.h"

@class BubbleTextLayer, NSMutableArray, NSString, NSTimer, TopoNumberBadge, TopoProgressBar, UIImage;

@interface NetTopoObjectLayer : CALayer
{
    id _associatedNode;
    id _owningView;
    double _layoutScale;
    _Bool _smallSize;
    int _topoStyle;
    struct CGSize _boundsSizeConstraint;
    UIImage *_statusBadgeImage;
    _Bool _selectable;
    struct CGColor *_selectionColor;
    struct CGColor *_labelUnselectedFillColor;
    struct CGColor *_labelSelectedFillColor;
    struct CGColor *_labelSelectedFillColor2;
    struct CGColor *_labelUnselectedTextColor;
    struct CGColor *_labelSelectedTextColor;
    struct CGColor *_secondaryLabelUnselectedTextColor;
    struct CGColor *_secondaryLabelSelectedTextColor;
    struct CGRect _imageFrame;
    struct CGRect _imageCoreFrame;
    struct CGRect _imageSelectionFrame;
    double _selectionCornerRadius;
    double _selectionRectOutset;
    NSString *_labelString;
    BubbleTextLayer *_labelLayer;
    double _labelPinnedHeight;
    NSString *_secondaryLabelString;
    BubbleTextLayer *_secondaryLabelLayer;
    UIImage *_statusLights[4];
    NSTimer *_statusLightTimer;
    float _statusLightInterval;
    unsigned int _statusLightState;
    unsigned int _statusLightMode;
    TopoNumberBadge *_topoNumberBadge;
    unsigned long long _topoBadgeNumber;
    TopoProgressBar *_topoProgressBar;
    float _topoProgressValue;
    id _userObject;
    NSString *_saveLable;
    unsigned long long _row;
    unsigned long long _column;
    struct CGPoint _layoutOrigin;
    unsigned long long _number;
    double _prelim;
    double _mod;
    double _change;
    double _shift;
    _Bool _isExpanded;
    NetTopoObjectLayer *_contourThread;
    NetTopoObjectLayer *_ancestor;
    _Bool _selected;
    _Bool _ghosted;
    NetTopoObjectLayer *_parent;
    NSMutableArray *_children;
    NSString *_saveLabel;
    struct CGImage *_objectImage;
}

+ (_Bool)needsDisplayForKey:(id)arg1;
@property(retain, nonatomic) struct CGImage *objectImage; // @synthesize objectImage=_objectImage;
@property(retain, nonatomic) NSString *saveLabel; // @synthesize saveLabel=_saveLabel;
@property(retain, nonatomic) id userObject; // @synthesize userObject=_userObject;
@property(nonatomic) unsigned long long topoBadgeNumber; // @synthesize topoBadgeNumber=_topoBadgeNumber;
@property(nonatomic, getter=isSelectable) _Bool selectable; // @synthesize selectable=_selectable;
@property(retain, nonatomic) NSMutableArray *children; // @synthesize children=_children;
@property(retain, nonatomic) NetTopoObjectLayer *parent; // @synthesize parent=_parent;
@property(retain, nonatomic) id associatedNode; // @synthesize associatedNode=_associatedNode;
@property(nonatomic) NetTopoObjectLayer *ancestor; // @synthesize ancestor=_ancestor;
@property(nonatomic) NetTopoObjectLayer *contourThread; // @synthesize contourThread=_contourThread;
@property(nonatomic, getter=isExpanded) _Bool expanded; // @synthesize expanded=_isExpanded;
@property(nonatomic) unsigned long long number; // @synthesize number=_number;
@property(nonatomic) double shift; // @synthesize shift=_shift;
@property(nonatomic) double change; // @synthesize change=_change;
@property(nonatomic) double mod; // @synthesize mod=_mod;
@property(nonatomic) double prelim; // @synthesize prelim=_prelim;
@property(nonatomic) struct CGPoint layoutOrigin; // @synthesize layoutOrigin=_layoutOrigin;
@property(nonatomic) unsigned long long column; // @synthesize column=_column;
@property(nonatomic) unsigned long long row; // @synthesize row=_row;
@property(nonatomic) _Bool smallSize; // @synthesize smallSize=_smallSize;
- (id)debugDescription;
- (id)describeOne:(id)arg1 uiLayer:(id)arg2 indent:(unsigned long long)arg3;
- (struct CGRect)getFrameContainingAllSublayers;
- (struct CGRect)getUserInteractionBounds;
- (CDStruct_f9662865)getConnectionAttachmentLocations;
- (void)drawInContext:(struct CGContext *)arg1;
- (void)layoutSublayers;
@property(nonatomic) double layoutScale; // @synthesize layoutScale=_layoutScale;
@property(nonatomic) unsigned int statusLightMode;
- (void)statusLightUpdateTimer:(id)arg1;
- (void)setStatusLightStateFromMode;
@property(retain, nonatomic) UIImage *statusBadgeImage;
- (void)setStatusBadgeImagePriv:(id)arg1;
- (void)deallocStatusImages;
- (void)loadStatusImagesForScale:(double)arg1;
@property(nonatomic) float topoProgressValue; // @synthesize topoProgressValue=_topoProgressValue;
@property(retain, nonatomic) NSString *secondaryLabel;
@property(nonatomic) double labelPinnedHeight;
@property(retain, nonatomic) NSString *label;
@property(nonatomic, getter=isGhosted) _Bool ghosted; // @synthesize ghosted=_ghosted;
@property(nonatomic, getter=isSelected) _Bool selected; // @synthesize selected=_selected;
@property(nonatomic) id owningView; // @synthesize owningView=_owningView;
@property(nonatomic) struct CGSize boundsSizeConstraint;
- (void)removeChild:(id)arg1;
- (void)addChild:(id)arg1;
- (void)insertChild:(id)arg1 atIndex:(unsigned long long)arg2;
- (id)lastChild;
- (id)firstChild;
- (id)childAtIndex:(unsigned long long)arg1;
@property(readonly, nonatomic) unsigned long long numberOfChildren;
@property(readonly, nonatomic) NetTopoObjectLayer *parentDevice;
- (void)pickCorrectImagesForContentsScale:(double)arg1;
- (void)dealloc;
- (id)init;
- (id)initWithUIStyle:(int)arg1 andOwningView:(id)arg2;
- (void)initNetTopoObjectLayerCommonWithStyle:(int)arg1 andOwningView:(id)arg2;

@end


text:
jest.dontMock('../decode');
jest.dontMock('../encode');
jest.dontMock('../ObjectStateMutations');
jest.dontMock('../ParseFile');
jest.dontMock('../ParseGeoPoint');
jest.dontMock('../ParseOp');
jest.dontMock('../ParsePromise');
jest.dontMock('../SingleInstanceStateController');
jest.dontMock('../TaskQueue');

var mockObject = function() {};
mockObject.registerSubclass = function() {};
jest.setMock('../ParseObject', mockObject);

var ParseFile = require('../ParseFile');
var ParseGeoPoint = require('../ParseGeoPoint');
var ParseOps = require('../ParseOp');
var ParsePromise = require('../ParsePromise');
var SingleInstanceStateController = require('../SingleInstanceStateController');
var TaskQueue = require('../TaskQueue');

describe('SingleInstanceStateController', () => {
  it('returns null state for an unknown object', () => {
    expect(SingleInstanceStateController.getState({ className: 'someClass', id: 'someId' })).toBe(null);
  });

  it('returns empty data for an unknown object', () => {
    expect(SingleInstanceStateController.getServerData({ className: 'someClass', id: 'someId' })).toEqual({});
  });

  it('returns an empty op queue for an unknown object', () => {
    expect(SingleInstanceStateController.getPendingOps({ className: 'someClass', id: 'someId' })).toEqual([{}]);
  });

  it('initializes server data when setting state', () => {
    expect(SingleInstanceStateController.getState({ className: 'someClass', id: 'A' })).toBe(null);
    SingleInstanceStateController.setServerData({ className: 'someClass', id: 'A' }, { counter: 12 });
    expect(SingleInstanceStateController.getState({ className: 'someClass', id: 'A' })).toEqual({
      serverData: { counter: 12 },
      pendingOps: [{}],
      objectCache: {},
      tasks: new TaskQueue(),
      existed: false
    });
  });

  it('can clear all data', () => {
    SingleInstanceStateController.setServerData({ className: 'someClass', id: 'A' }, { counter: 12 });
    expect(SingleInstanceStateController.getState({ className: 'someClass', id: 'A' })).toEqual({
      serverData: { counter: 12 },
      pendingOps: [{}],
      objectCache: {},
      tasks: new TaskQueue(),
      existed: false
    });
    SingleInstanceStateController.clearAllState();
    expect(SingleInstanceStateController.getState({ className: 'someClass', id: 'A' })).toEqual(null);
  });

  it('initializes server data when setting pending ops', () => {
    expect(SingleInstanceStateController.getState({ className: 'someClass', id: 'B' })).toBe(null);
    var op = new ParseOps.IncrementOp(1);
    SingleInstanceStateController.setPendingOp({ className: 'someClass', id: 'B' }, 'counter', op);
    expect(SingleInstanceStateController.getState({ className: 'someClass', id: 'B' })).toEqual({
      serverData: {},
      pendingOps: [{ counter: op }],
      objectCache: {},
      tasks: new TaskQueue(),
      existed: false
    });
  });

  it('can set server data on an existing state', () => {
    SingleInstanceStateController.setServerData({ className: 'someClass', id: 'C' }, { counter: 12 });
    expect(SingleInstanceStateController.getState({ className: 'someClass', id: 'C' })).toEqual({
      serverData: { counter: 12 },
      pendingOps: [{}],
      objectCache: {},
      tasks: new TaskQueue(),
      existed: false
    });
    SingleInstanceStateController.setServerData({ className: 'someClass', id: 'C' }, { valid: true });
    expect(SingleInstanceStateController.getState({ className: 'someClass', id: 'C' })).toEqual({
      serverData: { counter: 12, valid: true },
      pendingOps: [{}],
      objectCache: {},
      tasks: new TaskQueue(),
      existed: false
    });
    SingleInstanceStateController.setServerData({ className: 'someClass', id: 'C' }, { counter: 0 });
    expect(SingleInstanceStateController.getState({ className: 'someClass', id: 'C' })).toEqual({
      serverData: { counter: 0, valid: true },
      pendingOps: [{}],
      objectCache: {},
      tasks: new TaskQueue(),
      existed: false
    });
  });

  it('can remove server data from a state', () => {
    SingleInstanceStateController.setServerData({ className: 'someClass', id: 'D' }, { counter: 12 });
    expect(SingleInstanceStateController.getState({ className: 'someClass', id: 'D' })).toEqual({
      serverData: { counter: 12 },
      pendingOps: [{}],
      objectCache: {},
      tasks: new TaskQueue(),
      existed: false
    });
    SingleInstanceStateController.setServerData({ className: 'someClass', id: 'D' }, { counter: undefined });
    expect(SingleInstanceStateController.getState({ className: 'someClass', id: 'D' })).toEqual({
      serverData: {},
      pendingOps: [{}],
      objectCache: {},
      tasks: new TaskQueue(),
      existed: false
    });
  });

  it('can add multiple pending Ops', () => {
    var op = new ParseOps.IncrementOp(1);
    var op2 = new ParseOps.SetOp(true);
    SingleInstanceStateController.setPendingOp({ className: 'someClass', id: 'E' }, 'counter', op);
    SingleInstanceStateController.setPendingOp({ className: 'someClass', id: 'E' }, 'valid', op2);
    expect(SingleInstanceStateController.getState({ className: 'someClass', id: 'E' })).toEqual({
      serverData: {},
      pendingOps: [{ counter: op, valid: op2 }],
      objectCache: {},
      tasks: new TaskQueue(),
      existed: false
    });
    var op3 = new ParseOps.UnsetOp();
    SingleInstanceStateController.setPendingOp({ className: 'someClass', id: 'E' }, 'valid', op3);
    expect(SingleInstanceStateController.getState({ className: 'someClass', id: 'E' })).toEqual({
      serverData: {},
      pendingOps: [{ counter: op, valid: op3 }],
      objectCache: {},
      tasks: new TaskQueue(),
      existed: false
    });
  });

  it('can unset pending Ops', () => {
    var op = new ParseOps.IncrementOp(1);
    SingleInstanceStateController.setPendingOp({ className: 'someClass', id: 'F' }, 'counter', op);
    expect(SingleInstanceStateController.getState({ className: 'someClass', id: 'F' })).toEqual({
      serverData: {},
      pendingOps: [{ counter: op }],
      objectCache: {},
      tasks: new TaskQueue(),
      existed: false
    });
    SingleInstanceStateController.setPendingOp({ className: 'someClass', id: 'F' }, 'counter', null);
    expect(SingleInstanceStateController.getState({ className: 'someClass', id: 'F' })).toEqual({
      serverData: {},
      pendingOps: [{}],
      objectCache: {},
      tasks: new TaskQueue(),
      existed: false
    });
  });

  it('can push a new pending state frame', () => {
    var op = new ParseOps.IncrementOp(1);
    SingleInstanceStateController.setPendingOp({ className: 'someClass', id: 'G' }, 'counter', op);
    expect(SingleInstanceStateController.getState({ className: 'someClass', id: 'G' })).toEqual({
      serverData: {},
      pendingOps: [{ counter: op }],
      objectCache: {},
      tasks: new TaskQueue(),
      existed: false
    });
    SingleInstanceStateController.pushPendingState({ className: 'someClass', id: 'G' });
    expect(SingleInstanceStateController.getState({ className: 'someClass', id: 'G' })).toEqual({
      serverData: {},
      pendingOps: [{ counter: op }, {}],
      objectCache: {},
      tasks: new TaskQueue(),
      existed: false
    });
    var op2 = new ParseOps.SetOp(true);
    SingleInstanceStateController.setPendingOp({ className: 'someClass', id: 'G' }, 'valid', op2);
    expect(SingleInstanceStateController.getState({ className: 'someClass', id: 'G' })).toEqual({
      serverData: {},
      pendingOps: [{ counter: op }, { valid: op2 }],
      objectCache: {},
      tasks: new TaskQueue(),
      existed: false
    });
  });

  it('can pop a pending state frame', () => {
    var op = new ParseOps.IncrementOp(1);
    SingleInstanceStateController.setPendingOp({ className: 'someClass', id: 'H' }, 'counter', op);
    SingleInstanceStateController.pushPendingState({ className: 'someClass', id: 'H' });
    expect(SingleInstanceStateController.getState({ className: 'someClass', id: 'H' })).toEqual({
      serverData: {},
      pendingOps: [{ counter: op }, {}],
      objectCache: {},
      tasks: new TaskQueue(),
      existed: false
    });
    expect(SingleInstanceStateController.popPendingState({ className: 'someClass', id: 'H' })).toEqual({
      counter: op
    });
    expect(SingleInstanceStateController.getState({ className: 'someClass', id: 'H' })).toEqual({
      serverData: {},
      pendingOps: [{}],
      objectCache: {},
      tasks: new TaskQueue(),
      existed: false
    });
  });

  it('will never leave the pending Op queue empty', () => {
    SingleInstanceStateController.pushPendingState({ className: 'someClass', id: 'I' });
    expect(SingleInstanceStateController.getState({ className: 'someClass', id: 'I' })).toEqual({
      serverData: {},
      pendingOps: [{}, {}],
      objectCache: {},
      tasks: new TaskQueue(),
      existed: false
    });
    SingleInstanceStateController.popPendingState({ className: 'someClass', id: 'I' });
    SingleInstanceStateController.popPendingState({ className: 'someClass', id: 'I' });
    expect(SingleInstanceStateController.getState({ className: 'someClass', id: 'I' })).toEqual({
      serverData: {},
      pendingOps: [{}],
      objectCache: {},
      tasks: new TaskQueue(),
      existed: false
    });
  });

  it('can estimate a single attribute', () => {
    expect(SingleInstanceStateController.estimateAttribute({ className: 'someClass', id: 'J' }, 'unset'))
      .toBe(undefined);
    SingleInstanceStateController.setServerData({ className: 'someClass', id: 'J' }, { counter: 11 });
    expect(SingleInstanceStateController.estimateAttribute({ className: 'someClass', id: 'J' }, 'counter')).toBe(11);
    var op = new ParseOps.IncrementOp(1);
    SingleInstanceStateController.setPendingOp({ className: 'someClass', id: 'J' }, 'counter', op);
    expect(SingleInstanceStateController.estimateAttribute({ className: 'someClass', id: 'J' }, 'counter')).toBe(12);
    SingleInstanceStateController.pushPendingState({ className: 'someClass', id: 'J' });
    var op2 = new ParseOps.IncrementOp(10);
    SingleInstanceStateController.setPendingOp({ className: 'someClass', id: 'J' }, 'counter', op2);
    expect(SingleInstanceStateController.estimateAttribute({ className: 'someClass', id: 'J' }, 'counter')).toBe(22);
  });

  it('can estimate all attributes', () => {
    expect(SingleInstanceStateController.estimateAttributes({ className: 'someClass', id: 'K' })).toEqual({});
    SingleInstanceStateController.setServerData({ className: 'someClass', id: 'K' }, { counter: 11 });
    var op = new ParseOps.IncrementOp(1);
    var op2 = new ParseOps.SetOp(false);
    SingleInstanceStateController.setPendingOp({ className: 'someClass', id: 'K' }, 'counter', op);
    SingleInstanceStateController.setPendingOp({ className: 'someClass', id: 'K' }, 'valid', op2);
    expect(SingleInstanceStateController.estimateAttributes({ className: 'someClass', id: 'K' })).toEqual({
      counter: 12,
      valid: false
    });
    SingleInstanceStateController.pushPendingState({ className: 'someClass', id: 'K' });
    var op3 = new ParseOps.UnsetOp();
    SingleInstanceStateController.setPendingOp({ className: 'someClass', id: 'K' }, 'valid', op3);
    expect(SingleInstanceStateController.estimateAttributes({ className: 'someClass', id: 'K' })).toEqual({
      counter: 12
    });
  });

  it('can update server data with changes', () => {
    SingleInstanceStateController.setServerData({ className: 'someClass', id: 'L' }, { counter: 11 });
    expect(SingleInstanceStateController.estimateAttributes({ className: 'someClass', id: 'L' })).toEqual({
      counter: 11
    });
    SingleInstanceStateController.commitServerChanges({ className: 'someClass', id: 'L' }, {
      counter: 12,
      valid: true
    });
    expect(SingleInstanceStateController.estimateAttributes({ className: 'someClass', id: 'L' })).toEqual({
      counter: 12,
      valid: true
    });
  });

  it('can enqueue a chain of tasks', () => {
    var p1 = new ParsePromise();
    var p2 = new ParsePromise();
    var called = [false, false, false];
    var t1 = SingleInstanceStateController.enqueueTask({ className: 'someClass', id: 'M' }, () => {
      return p1.then(() => {
        called[0] = true;
      });
    });
    var t2 = SingleInstanceStateController.enqueueTask({ className: 'someClass', id: 'M' }, () => {
      return p2.then(() => {
        called[1] = true;
      });
    });
    var t3 = SingleInstanceStateController.enqueueTask({ className: 'someClass', id: 'M' }, () => {
      called[2] = true;
      return ParsePromise.as();
    });
    expect(called).toEqual([false, false, false]);
    p1.resolve();
    jest.runAllTicks();
    expect(t1._resolved).toBe(true);
    expect(t2._resolved).toBe(false);
    expect(called).toEqual([true, false, false]);
    p2.resolve();
    jest.runAllTicks();
    expect(t2._resolved).toBe(true);
    expect(t3._resolved).toBe(true);
    expect(called).toEqual([true, true, true]);
  });

  it('can merge the first entry into the next', () => {
    var incCount = new ParseOps.IncrementOp(1);
    var setName = new ParseOps.SetOp('demo');
    SingleInstanceStateController.setPendingOp({ className: 'someClass', id: 'N' }, 'counter', incCount);
    SingleInstanceStateController.setPendingOp({ className: 'someClass', id: 'N' }, 'name', setName);
    SingleInstanceStateController.pushPendingState({ className: 'someClass', id: 'N' });
    var setCount = new ParseOps.SetOp(44);
    var setValid = new ParseOps.SetOp(true);
    SingleInstanceStateController.setPendingOp({ className: 'someClass', id: 'N' }, 'counter', setCount);
    SingleInstanceStateController.setPendingOp({ className: 'someClass', id: 'N' }, 'valid', setValid);
    SingleInstanceStateController.mergeFirstPendingState({ className: 'someClass', id: 'N' });
    expect(SingleInstanceStateController.getState({ className: 'someClass', id: 'N' })).toEqual({
      serverData: {},
      pendingOps: [{
        counter: new ParseOps.SetOp(44),
        name: new ParseOps.SetOp('demo'),
        valid: new ParseOps.SetOp(true),
      }],
      objectCache: {},
      tasks: new TaskQueue(),
      existed: false
    });
  });

  it('stores cached versions of object attributes', () => {
    var cache = SingleInstanceStateController.getObjectCache({ className: 'someClass', id: 'O' });
    expect(cache).toEqual({});
    SingleInstanceStateController.commitServerChanges({ className: 'someClass', id: 'O' }, {
      name: 'MyObject',
      obj: { a: 12, b: 21 },
      location: new ParseGeoPoint(20, 20),
      file: ParseFile.fromJSON({
        __type: 'File',
        name: 'parse.txt',
        url: 'http://files.parsetfss.com/a/parse.txt'
      })
    });
    cache = SingleInstanceStateController.getObjectCache({ className: 'someClass', id: 'O' });
    expect(cache.name).toBe(undefined);
    expect(cache.file).toBe(undefined);
    expect(JSON.parse(cache.obj)).toEqual({ a: 12, b: 21 });
    expect(JSON.parse(cache.location)).toEqual({
      __type: 'GeoPoint',
      latitude: 20,
      longitude: 20
    });
  });

  it('can remove state for an object', () => {
    expect(SingleInstanceStateController.removeState({ className: 'someClass', id: 'P' })).toBe(null);
    SingleInstanceStateController.setServerData({ className: 'someClass', id: 'P' }, { counter: 12 });
    expect(SingleInstanceStateController.getState({ className: 'someClass', id: 'P' })).toEqual({
      serverData: { counter: 12 },
      pendingOps: [{}],
      objectCache: {},
      tasks: new TaskQueue(),
      existed: false
    });
    let state = SingleInstanceStateController.removeState({ className: 'someClass', id: 'P' });
    expect(state).toEqual({
      serverData: { counter: 12 },
      pendingOps: [{}],
      objectCache: {},
      tasks: new TaskQueue(),
      existed: false
    });
    expect(SingleInstanceStateController.getState({ className: 'someClass', id: 'P' })).toBe(null);
  });
});


text:
using System;

namespace Org.BouncyCastle.Crypto
{
	/// <summary>
	/// This exception is thrown whenever a cipher requires a change of key, iv
	/// or similar after x amount of bytes enciphered
    /// </summary>
#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || NETFX_CORE)
    [Serializable]
#endif
    public class MaxBytesExceededException
		: CryptoException
	{
		public MaxBytesExceededException()
		{
		}

		public MaxBytesExceededException(
			string message)
			: base(message)
		{
		}

		public MaxBytesExceededException(
			string		message,
			Exception	e)
			: base(message, e)
		{
		}
	}
}

#endif


text:
include(processorcount)

# Grub
find_program(GRUB_MKRESCUE "grub-mkrescue")
if(NOT GRUB_MKRESCUE)
		message(FATAL_ERROR "grub-mkrescue not found, cannot create bootable iso :(")
endif()

macro(ADDEMU TGT)
# Prepare some useful variable for use in config files
set(TGT_ELF "${CMAKE_CURRENT_BINARY_DIR}/${TGT}.elf")
set(ISODIR "${PROJECT_BINARY_DIR}/grub_iso")
set(FAIL_BINARY "$ENV{EZS_BASE_DIR}/fail/fail-client")
set(ISOFILE "${PROJECT_BINARY_DIR}/${TGT}.iso")
set(ELFFILE "${PROJECT_BINARY_DIR}/${TGT}.elf")
set(RUNNER "/proj/i4ezs/tools/fail/vezs/bochs-experiment-runner.py")

set(FAILVARIANT "not_set" CACHE PATH "Variant name for Fail* injection")

####deprecated
# Setup Bochs configuration
set(BOCHS_BIOS "${CMAKE_CURRENT_SOURCE_DIR}/BIOS-bochs-latest")
set(BOCHS_GUEST_RAM 32)
set(BOCHS_HOST_RAM 32)
set(BOCHS_VGA_IMAGE "${CMAKE_CURRENT_SOURCE_DIR}/vgabios.bin")
set(BOCHS_ISO_IMAGE "${ISOFILE}")
####

set(STARTUP_SCRIPTS ${PROJECT_BINARY_DIR}/startup_scripts)
file(MAKE_DIRECTORY ${STARTUP_SCRIPTS})

#####deprecated bochsrc includes iso name :-(
#set(BOCHSRC "${STARTUP_SCRIPTS}/bochsrc")
#configure_file("${CMAKE_CURRENT_SOURCE_DIR}/bochsrc.in" ${BOCHSRC} )
#configure_file("${CMAKE_CURRENT_SOURCE_DIR}/bochsrc-gdb.in" "${BOCHSRC}-gdb" )
#configure_file("${CMAKE_CURRENT_SOURCE_DIR}/bochsrc-term.in" "${BOCHSRC}-term" )
#configure_file(${CMAKE_CURRENT_SOURCE_DIR}/frun.sh.in ${STARTUP_SCRIPTS}/frun.sh)
#configure_file(${CMAKE_CURRENT_SOURCE_DIR}/pts.sh.in ${STARTUP_SCRIPTS}/pts.sh)
#####

configure_file(${PROJECT_SOURCE_DIR}/emu/qrun.sh.in ${STARTUP_SCRIPTS}/qrun.sh)
configure_file(${SCRIPT_DIR}/findport.pl ${STARTUP_SCRIPTS}/findport.pl)

#message(STATUS "Fail* @ ${FAIL_BINARY}")
#set(GDBINITFILE ${STARTUP_SCRIPTS}/.gdbinit)
#configure_file("${CMAKE_CURRENT_SOURCE_DIR}/gdbinit.in" ${GDBINITFILE})

# message(STATUS "Building bootable ISO for ${TGT}")

# Generate build directory for grub-mkrescue
set(BOOTDIR "${ISODIR}/boot/")
set(GRUBDIR "${BOOTDIR}/grub")
file(MAKE_DIRECTORY ${GRUBDIR})

####TODO: make iso-genration generic
## Copy and configure grub configuration file
#configure_file("${CMAKE_CURRENT_SOURCE_DIR}/grub.cfg.in" "${GRUBDIR}/grub.cfg")
## Create bootable ISO from TGT
#add_custom_command(
#	DEPENDS ${TGT}
#        COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:${TGT}> ${BOOTDIR}/${TGT_ELF}
#	COMMAND ${GRUB_MKRESCUE}
#		ARGS -o ${ISOFILE} ${ISODIR}
#	COMMAND objdump -CDS ${BOOTDIR}/${TGT_ELF} > ${PROJECT_BINARY_DIR}/${TGT}.dis
#        OUTPUT ${ISOFILE} ${BOOTDIR}/${TGT_ELF} ${PROJECT_BINARY_DIR}/${TGT}.dis
#	COMMENT "Generating bootable grub iso."
#		)
#
## Create bootable ISO
#add_custom_target( iso DEPENDS ${ISOFILE} )

# Start FAIL
# comment for 02_filter
##add_custom_target( sim
##        COMMAND ${STARTUP_SCRIPTS}/frun.sh
##		DEPENDS ${ISOFILE}
##		COMMENT "Starting Fail*"
##        WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
##		)

# Start qemu
add_custom_target(run_${TGT}
		DEPENDS ${TGT_ELF} ${TGT}
		COMMAND echo "Running ${TGT_ELF}..."
        COMMAND ${STARTUP_SCRIPTS}/qrun.sh ${TGT_ELF}
        WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
		)

add_custom_target( ddd_${TGT}
# Start Qemu in Debug mode.
        DEPENDS ${TGT}
        COMMAND ${STARTUP_SCRIPTS}/qrun.sh ${TGT_ELF} ddd
		COMMENT "Debugging in Qemu"
        WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
)

add_custom_target( gdb_${TGT}
# Start Qemu in Debug mode.
        DEPENDS ${TGT}
        COMMAND ${STARTUP_SCRIPTS}/qrun.sh ${TGT_ELF} gdb
		COMMENT "Debugging in Qemu"
        WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
)

add_custom_target( gdbtui_${TGT}
# Start Qemu in Debug mode.
        DEPENDS ${TGT}
        COMMAND ${STARTUP_SCRIPTS}/qrun.sh ${TGT_ELF} gdbtui
		COMMENT "Debugging in Qemu"
        WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
)

add_custom_target( cgdb_${TGT}
# Start Qemu in Debug mode.
        DEPENDS ${TGT}
        COMMAND ${STARTUP_SCRIPTS}/qrun.sh ${TGT_ELF} cgdb
		COMMENT "Debugging in Qemu"
        WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
)

# add legacytargets
if( NOT TARGET run )
  add_custom_target(run DEPENDS run_${TGT})
  add_custom_target(ddd DEPENDS ddd_${TGT})
  add_custom_target(gdb DEPENDS gdb_${TGT})
  add_custom_target(gdbtui DEPENDS gdbtui_${TGT})
  add_custom_target(cgdb DEPENDS cgdb_${TGT})
endif()

#add_custom_target( fail-1-trace
#  # Start Qemu in Debug mode.
#  DEPENDS ${ISOFILE}
#  COMMAND LD_LIBRARY_PATH=/proj/i4ezs/tools/fail/vezs/ ${RUNNER} -e ${ELFFILE} -i ${BOCHS_ISO_IMAGE} -1
#     -f /proj/i4ezs/tools/fail/vezs/fail-x86-tracing
#     -m 32 --
#     -Wf,--start-symbol=fail_trace_start
#     -Wf,--save-symbol=fail_trace_start
#     -Wf,--end-symbol=fail_trace_stop
#     -Wf,--trace-file=${PROJECT_BINARY_DIR}/trace.pb
#     -Wf,--elf-file=${PROJECT_BINARY_DIR}/${TGT}.elf -q
#  COMMENT "Trace the app for golden run"
#  OUTPUT ${PROJECT_BINARY_DIR}/trace.pb
#  WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
#)
#
#add_custom_target( fail-2-import
#  # Start Qemu in Debug mode.
#  DEPENDS ${PROJECT_BINARY_DIR}/trace.pb
#  COMMAND  LD_LIBRARY_PATH=/proj/i4ezs/tools/fail/vezs/ /proj/i4ezs/tools/fail/vezs/import-trace -t ${PROJECT_BINARY_DIR}/trace.pb -i mem -v aufgabe1 -b ${FAILVARIANT} -e ${ELFFILE} --faultspace-rightmargin R
#  COMMAND  LD_LIBRARY_PATH=/proj/i4ezs/tools/fail/vezs/ /proj/i4ezs/tools/fail/vezs/import-trace -i ElfImporter --objdump objdump -e ${ELFFILE} -v aufgabe1 -b ${FAILVARIANT}
#  COMMAND  LD_LIBRARY_PATH=/proj/i4ezs/tools/fail/vezs/ /proj/i4ezs/tools/fail/vezs/prune-trace -p basic -v aufgabe1 -b ${FAILVARIANT} --overwrite
#  COMMENT "Import the golden run into the database"
#  WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
#)
#
#add_custom_target( fail-3-server
#  # Start Qemu in Debug mode.
#  DEPENDS ${PROJECT_BINARY_DIR}/trace.pb
#  COMMAND LD_LIBRARY_PATH=/proj/i4ezs/tools/fail/vezs/ /proj/i4ezs/tools/fail/vezs/generic-experiment-server -v aufgabe1 -b ${FAILVARIANT}
#  COMMENT "Start the campaign server"
#  WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
#)
#
#add_custom_target( fail-4-client
#  # Start Qemu in Debug mode.
#  DEPENDS ${PROJECT_BINARY_DIR}/trace.pb
#  COMMAND LD_LIBRARY_PATH=/proj/i4ezs/tools/fail/vezs/ ${RUNNER} -e ${ELFFILE} -i ${BOCHS_ISO_IMAGE}
#          -f /proj/i4ezs/tools/fail/vezs/generic-experiment-client -m 32
#           -e ${ELFFILE}
#           -i ${BOCHS_ISO_IMAGE}
#           -V vgabios.bin -b BIOS-bochs-latest --
#           -Wf,--state-dir=state
#           -Wf,--trap -Wf,--timeout=10
#           -Wf,--ok-marker=fail_marker_positive
#           -Wf,--fail-marker=fail_marker_negative
#           -Wf,--detected-marker=fail_marker_detected
#           -Wf,--catch-write-textsegment
#           -Wf,--catch-write-outerspace # 2>/dev/null | grep -C 4 'INJECT'
#  COMMENT "Start one fail-client"
#  WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
#)
#
#add_custom_target( fail-4-client-parallel
#  # Start Qemu in Debug mode.
#  DEPENDS ${PROJECT_BINARY_DIR}/trace.pb
#  COMMAND LD_LIBRARY_PATH=/proj/i4ezs/tools/fail/vezs/ nice -n 19 ionice -c3 ${RUNNER} -e ${ELFFILE} -i ${BOCHS_ISO_IMAGE}
#          -f /proj/i4ezs/tools/fail/vezs/generic-experiment-client -m 32
#           -e ${ELFFILE}
#           -i ${BOCHS_ISO_IMAGE}
#           -V vgabios.bin -b BIOS-bochs-latest -j${PROCESSOR_COUNT} --
#           -Wf,--state-dir=state
#           -Wf,--trap -Wf,--timeout=10
#           -Wf,--ok-marker=fail_marker_positive
#           -Wf,--fail-marker=fail_marker_negative
#           -Wf,--detected-marker=fail_marker_detected
#           -Wf,--catch-write-textsegment
#           -Wf,--catch-write-outerspace # 2>/dev/null | grep -C 4 'INJECT'
#  COMMENT "Start many fail-clients (use FAIL_SERVER_HOST for different campaign server)"
#  WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
#)
#
#add_custom_target( fail-5-result
#  # Start Qemu in Debug mode.
#  COMMAND mysql -t < ${PROJECT_SOURCE_DIR}/eval/report.sql
#  COMMENT "Generate a report"
#  WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
#)
#
#add_custom_target( fail-5-browse
#  # Start Qemu in Debug mode.
#  COMMAND mysql -t < ${PROJECT_SOURCE_DIR}/eval/report.sql
#  COMMAND /proj/i4ezs/tools/fail/vezs/resultbrowser/run.py
#  COMMENT "Generate HTML report"
#  WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
#)
endmacro(ADDEMU TGT)


text:
REFs:

https://medium.com/@bluepnume/learn-about-promises-before-you-start-using-async-await-eb148164a9c8


text:
<?php
/*
Plugin Name: RAMP Posts to Posts Data Sync
Description: Allows RAMP to sync data from the plugin Posts to Posts
Author: OpenDNS
Version: 1.2
Author URI: http://www.opendns.com
*/

/**
 * Action to register the callbacks; must be called at cfd_admin_init
 **/
function p2p_register_deploy_callbacks() {
	global $p2p_deploy_callbacks;
	$p2p_deploy_callbacks = new p2p_deploy_callbacks();
	$p2p_deploy_callbacks->register_deploy_callbacks();
}

add_action('cfd_admin_init', 'p2p_register_deploy_callbacks');

class p2p_deploy_callbacks {
	// The name is used to generate the callback ID in RAMP.  Using a
	// translated name may result in problems if the production and staging
	// servers have different languages set.
	protected $name = 'RAMP Posts to Posts Data Sync';
	protected $description = '';

	public function __construct() {
		// This is a good place to do initial setup, if any is needed
		$this->description = __('Allows RAMP to sync data from the plugin Posts to Posts', 'p2p_ramp');
	}

	/**
	 * Callbacks should be registered in a batch when possible.  Check the name
	 * of the callback a function is being registered to - there is no error
	 * message for using an invalid callback, and it can produce unexpected
	 * results.
	 **/
	public function register_deploy_callbacks() {
		cfd_register_deploy_callback($this->name, $this->description,
			array(
				'send_callback' => array($this, 'send_callback'),
				'receive_callback' => array($this, 'receive_callback'),
				'preflight_send_callback' => array($this, 'preflight_send_callback'),
				'preflight_check_callback' => array($this, 'preflight_check_callback'),
				'preflight_display_callback' => array($this, 'preflight_display_callback'),
				'comparison_send_callback' => array($this, 'comparison_send_callback'),
				'comparison_check_callback' => array($this, 'comparison_check_callback'),
				'comparison_selection_row_callback' => array($this, 'comparison_selection_row_callback'),
			)
		);
	}

	// -- Comparison (New Batch) callbacks

	/**
	 * Runs on the staging server
	 * Generates data to do the "new batch" comparison
	 * Data is passed to comparison_check
	 *
	 * @param array $batch_comparison_data The complete array of batch
	 * comparison data to send.
	 *
	 * @return array Returns an array of arrays of data to be passed to the
	 * comparison_check callback, with the top-level keys being internal
	 * identifiers for 'rows' of this extra's data
	 *
	 **/
	public function comparison_send_callback($batch_comparison_data) {
		// We use the 'send' callback for comparison_send as well, passing an
		// optional second parameter to force the send callback to operate;
		// the send callback can check if it is part of the batch and skip its
		// operation if not, but we want it to always run during comparison.
		$data = $this->send_callback($batch_comparison_data, true);
		return $data;
	}

	/**
 	 * Runs on the production server
	 * Generates data to do the "new batch" comparison
	 * Data is received from comparison_send
	 * Data is passed to comparison_selection_row
	 *
	 * @param array $data The data produced by the comparison_send callback
	 * @param array $batch_items The complete array of batch comparison data
	 * sent
	 *
	 * @return array An array of arrays of data to be passed to the
	 * comparison_selection_row callback, with the top-level keys being
	 * internal identifiers for 'rows' of this extra's data
	 **/
	public function comparison_check_callback($data, $batch_items) {
		$prod_rows = $this->send_callback($data, true);
		return $prod_rows;
	}

	/**
	 * Runs on staging
	 * Generates the "new batch" comparison rows
	 * Data is received from comparison_send and comparison_check
	 * Data is passed to RAMP for display
	 *
	 * Takes the comparison data returned from staging and from production,
	 * and determines if any "New Batch" rows should be displayed (and if
	 * they should have checkboxes, and if so, if those checkboxes should
	 * be checked by default).
	 *
	 * @param array $compiled_data One row of the compiled array of comparison
	 * data, including the following keys:
	 *		status: one row of the data returned by comparison_send
	 *		remote_status: one row of the data returned by comparison_check
	 *		id: the ID of the extra which produced this data
	 *		extra_id: the top-level key of the comparison_* row currently being
	 *		processed
	 *		in_batch: if the corresponding row's checkbox was checked on the
	 *		new batch page
	 *
	 *	@return array An array with three keys:
	 *		selected: true|false|null - true or false checks or unchecks the
	 *		new batch row checkbox by default; null suppresses the checkbox
	 *		forced: true|false (optional) - if true, the checkbox will be
	 *		disabled
	 *		title: The title for the row - usually the plugin name
	 *		message: The message for the row (describing changes if any, et
	 *		cetera)
	 **/
	public function comparison_selection_row_callback($compiled_data) {
		if(isset($compiled_data['remote_status']) && isset($compiled_data['status'])) {
			ksort($compiled_data['remote_status']['meta']);
			ksort($compiled_data['status']['meta']);
			if (serialize($compiled_data['remote_status']['meta']) === serialize($compiled_data['status']['meta'])) {
				return null;
			}

			$ret = array(
				'selected' => $compiled_data['in_batch'],
				'title' => "Update metadata: {$compiled_data['status']['from_name']} "
							. "-> {$compiled_data['status']['to_name']}",
				'message' => "{$compiled_data['status']['p2p_type']} Connection",
			);

		}
		else if (isset($compiled_data['status'])) {
			$ret = array(
				'selected' => $compiled_data['in_batch'],
				'title' => "{$compiled_data['status']['from_name']} "
							. "-> {$compiled_data['status']['to_name']}",
				'message' => "{$compiled_data['status']['p2p_type']} Connection",
			);
		}
		else {
			$ret = array(
				'selected' => $compiled_data['in_batch'],
				'title' => "Remove " . "{$compiled_data['remote_status']['from_name']} "
							. "-> {$compiled_data['remote_status']['to_name']}",
				'message' => "{$compiled_data['remote_status']['p2p_type']} Connection Deletion",
			);
		}

		return $ret;
	}

	// -- Preflight callbacks

	/**
	 * Runs on staging server
	 * Generates the "preflight" check data
	 * Data is passed to preflight_check
	 *
	 *
	 * Prepare staging data to send for the preflight checks
	 *
	 * @param array $batch_data
	 * @return array
	 **/
	public function preflight_send_callback($batch_data) {
		// Again, use the send callback, but this time let it decide if it
		// should run based on whether the row was selected in the batch.
		return $this->send_callback($batch_data);
	}

	/**
	 * Runs on production server
	 * Generates the "preflight" check data
	 * Data is checked by RAMP for flagged error condition
	 *
	 * Receive the staging preflight checked data, compare it to the
	 * production state, and return messages about the preflight; among
	 * other things, trigger an error if there is a change in EPT data
	 * and there is anything in the batch aside from EPT data.
	 *
	 * @param array $data The data produced by the preflight_send callback
	 * @param array $batch_items The complete array of batch preflight data
	 * sent
	 *
	 * @return array A row of preflight messages, with optional subrows
	 * Rows are an array of (all optional) '__message__', '__notice__',
	 * '__warning__', '__error__', which are in turn arrays of strings.  The
	 * presence of any of these but '__message__' will cause the preflight to
	 * block with an error. Optionally, it can also contain a key 'rows', which
	 * is an array of 'Descriptive Name' => array(), where the sub-arrays are
	 * likewise '__message__' et al, which will be shown as sub-rows on the
	 * preflight screen.
	 **/
	public function preflight_check_callback($data, $batch_data) {
		$ret = array('rows' => array());
		$errors = array();
		$delete = 'P2P Link Deletion';
		$sync = 'P2P Link Update';
		$messages = array(__('Selected connections will be synced', 'p2p_ramp'));
		$local_connections = $this->send_callback($batch_data);
		foreach($data as $key => $connection) {
			if (!is_array($connection)) {

				if (!isset($local_connections[$connection])) {
					$errors[] = sprintf(__('Could not find the connection (key %s)'), $connection);
					continue;
				}
				if (!isset($ret['rows'][$delete])) {
					$ret['rows'][$delete]  = array('__message__' => array());
				}
				$local_connection = $local_connections[$connection];
				$ret['rows'][$delete]['__message__'][] = sprintf(__('%s connection will be deleted: %s to %s', 'p2p_ramp'), $local_connection['p2p_type'], $local_connection['from_name'], $local_connection['to_name']);
				continue;
			}
			$from_valid = $this->is_guid_in_batch_data($batch_data, $connection['from_guid']);
			if(!$from_valid) {
				$from_valid = $this->get_post_by_guid($connection['from_guid']) ? true : false;
			}

			if(!$from_valid) {
				$errors[] = sprintf(__('A selected "%s" connection requires that you send %s \'%s\'', 'p2p_ramp'), $connection['p2p_type'], $connection['from_type'], $connection['from_name']);
			}

			$to_valid = $this->is_guid_in_batch_data($batch_data, $connection['to_guid']);
			if(!$to_valid) {
				$to_valid = $this->get_post_by_guid($connection['to_guid']) ? true : false;
			}

			if(!$to_valid) {
				$errors[] = sprintf(__('A selected "%s" connection requires that you send %s \'%s\'', 'p2p_ramp'), $connection['p2p_type'], $connection['to_type'], $connection['to_name']);
			}

			if ($from_valid && $to_valid) {
				if (!isset($ret['rows'][$sync])) {
					$ret['rows'][$sync]  = array('__message__' => array());
				}
				$to_post = $this->get_post_by_guid($connection['to_guid']);
				$from_post = $this->get_post_by_guid($connection['from_guid']);

				$existing_connection = p2p_get_connections($connection['p2p_type'], array(
					'from' => $from_post->ID,
					'to' => $to_post->ID,
				));
				if ($existing_connection) {
					$ret['rows'][$sync]['__message__'][] = sprintf(__('%s connection will be updated: %s to %s', 'p2p_ramp'), $connection['p2p_type'], $connection['from_name'], $connection['to_name']);
				}
				else {
					$ret['rows'][$sync]['__message__'][] = sprintf(__('%s connection will be created: %s to %s', 'p2p_ramp'), $connection['p2p_type'], $connection['from_name'], $connection['to_name']);
				}

			}

		}

		if ($errors) {
			$ret['__error__'] = $errors;
		} else {
			$ret['__message__'] = $messages;
		}

		return $ret;
	}

	/**
	 * Runs on staging server
	 * Optionally changes other messages in the preflight display
	 * Data is checked by RAMP for flagged error condition
	 *
	 * @param array $batch_preflight_data An array of messages; top-level keys
	 * are gross types (post_type, etc) including 'extras'); second-level keys
	 * are rows; below that, the format differs per type.  Extras rows are an
	 * array of (all optional) '__message__', '__notice__', '__warning__',
	 * '__error__';
	 *
	 * @return array The modified messages array
	 **/
	public function preflight_display_callback($batch_preflight_data) {
		return $batch_preflight_data;
	}

	// Transfer Callback Methods

	/**
 	 * Runs on staging server
	 * Prepare staging server data for actual deploy
	 * Data is passed to receive
	 *
	 * @param array $batch_data The complete array of batch
	 * data to send.
	 *
	 * @return array Returns data to be passed to the receive callback.
	 * If the data is empty(), the receive callback will not be called.
	 *
	 **/
	public function send_callback($batch_data, $return_all = false) {
		$extra_id = cfd_make_callback_id($this->name);

		$connection_types = P2P_Connection_Type_Factory::get_all_instances();

		$data = array();

		foreach($connection_types as $type) {
			foreach(p2p_get_connections($type->name) as $row) {
				$from = get_post($row->p2p_from);
				$to = get_post($row->p2p_to);

				$meta = p2p_get_meta($row->p2p_id);

				$key = md5($row->p2p_type . '|' . $from->guid . '|' . $to->guid);
				$data[$key] = (array)$row;
				$data[$key]['from_guid'] = $from->guid;
				$data[$key]['to_guid'] = $to->guid;
				$data[$key]['from_name'] = $from->post_title;
				$data[$key]['to_name'] = $to->post_title;
				$data[$key]['from_type'] = $from->post_type;
				$data[$key]['to_type'] = $to->post_type;
				$data[$key]['meta'] = $meta;
			}
		}

		if($return_all) {
			return $data;
		}
		if(!isset($batch_data['extras'][$extra_id])) {
			return null;
		}
		$keys = array();
		foreach ($batch_data['extras'][$extra_id] as $key => $val) {
			if (is_array($val)) {
				$keys[$key] = $key;
			}
			else {
				$keys[$val] = $val;
			}
		}
		$missing = array_diff_key($keys, $data);
		$return = array_intersect_key($data, $keys);
		foreach ($missing as $key => $ignored) {
			$return[] = $key;
		}
		return $return;
		return array_intersect_key($data, $keys);

	}

	/**
	 * Runs on production server
	 * Update the production server with staging server data
	 * Data is passed from send
	 * Data is passed to RAMP to display messages and error conditions
	 *
	 * @param array $data The data returned by the send callback.
	 *
	 * @return array An array with the following required keys:
	 *		'success': a boolean for successful or failed transfer
	 *		'message': a message to display on the batch complete page for this
	 *		plugin's data
	 **/
	public function receive_callback($data) {
		$success = true;
		$any_success = false;

		$extra_id = cfd_make_callback_id($this->name);
		$faux_batch = array(
			'extras' => array(
				$extra_id => $data
			)
		);

		$local_connections = $this->send_callback($faux_batch);
		foreach($data as $key => $connection) {
			$delete = false;
			if (!is_array($connection)) {
				if (isset($local_connections[$connection])) {
					$delete = true;
					$connection = $local_connections[$connection];
				}
				else {
					continue;
				}
			}
			$from = $this->get_post_by_guid($connection['from_guid']);
			$to = $this->get_post_by_guid($connection['to_guid']);

			if(!$from || !$to) {
				$success = false;
				continue;
			}

			$existing_connection = p2p_get_connections($connection['p2p_type'], array(
				'from' => $from->ID,
				'to' => $to->ID,
			));

			if ($delete) {
				if ($existing_connection) {
					p2p_delete_connection($existing_connection[0]->p2p_id);
					$any_success = true;
				}
				continue;
			}

			if($existing_connection) {
				$p2p_id = $existing_connection[0]->p2p_id;
			} else {
				$p2p_id = p2p_create_connection($connection['p2p_type'], array(
					'from' => $from->ID,
					'to' => $to->ID,
				));
			}

			if($p2p_id) {
				$any_success = true;
			}

			// Sync metadata if there is any
			if(!is_array($connection['meta'])) {
				$connection['meta'] = array();
			}

			$existing_meta = p2p_get_meta($p2p_id);

			// Sync new/existing keys
			foreach($connection['meta'] as $key => $value) {
				$value = $value[0];
				if (isset($existing_meta[$key])) {
					p2p_update_meta($p2p_id, $key, $value);
				} else {
					p2p_add_meta($p2p_id, $key, $value, true);
				}
			}

			// Delete existing keys that no longer exist
			foreach($existing_meta as $key => $value) {
				$value = $value[0];
				if (!isset($connection['meta'][$key])) {
					p2p_delete_meta($p2p_id, $key);
				}
			}

		}

		if($success && $any_success) {
			$message = __('Connections were successfully deployed', 'p2p_ramp');
		} elseif($success && !$any_success) {
			$message = __('No Posts to Posts connections to deploy', 'p2p_ramp');
		} elseif(!$success && $any_success) {
			$message = __('Some connctions were deployed, but others could not be because they referred to missing post or page IDs', 'p2p_ramp');
		} elseif(!$success && !$any_success) {
			$message = __('No connections could be deployed, probably because of missing post or page IDs', 'p2p_ramp');
		}

		return array(
			'success' => $success,
			'message' => $message
		);
	}

	protected function get_post_by_guid($guid) {
		global $wpdb;
		return $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->posts} WHERE guid = %s", $guid));
	}

	protected function is_guid_in_batch_data($batch_data, $guid) {
		if(!isset($batch_data['post_types'])) {
			return false;
		}

		foreach($batch_data['post_types'] as $post_type => $posts) {
			if(isset($posts[$guid])) {
				return true;
			}
		}

		return false;

	}

}


text:
Contributing
============================

#. Familiarize yourself with the [Code of Conduct](https://github.com/omec/open-mic/blob/master/CODE_OF_CONDUCT.md)
#. Join the [developers mailing list](https://groups.google.com/forum/#!forum/open-mic-dev)
#. Feel free to weigh in on issues and discussion
#. As needed, fork the repo, develop and test your code changes, adding docs.
#. Make sure that your commit messages clearly describe the changes.
#. Send a pull request.


text:
import Ember from 'ember';
import config from './config/environment';

var Router = Ember.Router.extend({
  location: config.locationType
});

//A new route to the calculator router when /calculator is accessed.
Router.map(function() {
  this.route('calculator', { path: '/' });
});

export default Router;


text:
cd "$(dirname "$(realpath "$0")")";

# git clone .. if missing

inagoctl up k8s-network
inagoctl up k8s-master
inagoctl up k8s-node 3


text:
Changes and fixes:
- dropped selective syncing.
- added ability to sync without passwords.
- added ability to sync when database is saved or opened, as well as at timed intervals.
- fixed bug whereby remote sync change log is not cleared when closing database.