text:
package net.coobird.paint.driver;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.lang.reflect.InvocationTargetException;

import javax.swing.DefaultListModel;
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JSplitPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.filechooser.FileFilter;

import net.coobird.paint.BlendingMode;
import net.coobird.paint.application.ApplicationUtils;
import net.coobird.paint.application.BrushListCellRenderer;
import net.coobird.paint.application.ImageLayerListCellRenderer;
import net.coobird.paint.brush.Brush;
import net.coobird.paint.brush.BrushController;
import net.coobird.paint.brush.BrushRenderProgressListener;
import net.coobird.paint.brush.RandomSplashBrush;
import net.coobird.paint.brush.RegularCircularBrush;
import net.coobird.paint.brush.RegularEllipticalBrush;
import net.coobird.paint.brush.RegularEllipticalEraser;
import net.coobird.paint.brush.SolidCircularBrush;
import net.coobird.paint.brush.StagedBrush;
import net.coobird.paint.filter.ImageFilter;
import net.coobird.paint.filter.ImageFilterThreadingWrapper;
import net.coobird.paint.filter.MatrixImageFilter;
import net.coobird.paint.filter.RepeatableMatrixFilter;
import net.coobird.paint.filter.ResizeFilter;
import net.coobird.paint.gui.PositionListener;
import net.coobird.paint.image.Canvas;
import net.coobird.paint.image.ClippableImageRenderer;
import net.coobird.paint.image.PartialImageRenderer;
import net.coobird.paint.io.FormatManager;
import net.coobird.paint.io.ImageInput;
import net.coobird.paint.io.ImageInputOutputException;
import net.coobird.paint.io.ImageOutput;
import net.coobird.paint.layer.ImageLayer;
import net.coobird.paint.layer.ImageLayerUtils;
import net.coobird.paint.layer.ReferenceLayer;
import net.coobird.paint.layer.TextLayer;

public class DemoApp2
{
	class ActionMenuItem extends JMenuItem implements ActionListener
	{
		public ActionMenuItem(String s)
		{
			addActionListener(this);
			setText(s);
		}

		public void actionPerformed(ActionEvent e) {};
	}

	private void makeGUI()
	{
		final JFrame f = new JFrame("Paint Dot Jar Demonstration 2");
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		f.getContentPane().setLayout(new BorderLayout());

		final JPanel statusBar = new JPanel(new BorderLayout());
		final JLabel statusLabel = new JLabel("Ready.");
		final JProgressBar progressBar = new JProgressBar();
		progressBar.setStringPainted(true);

		statusBar.add(statusLabel, BorderLayout.WEST);
		statusBar.add(progressBar, BorderLayout.EAST);

		f.getContentPane().add(statusBar, BorderLayout.SOUTH);

		ApplicationUtils.setMainComponent(f);

		JPanel listPanels = new JPanel(new GridLayout(0, 1));

		/*
		 * Brush initializations
		 */
		final JList brushList = new JList();
		brushList.setCellRenderer(new BrushListCellRenderer());
		final DefaultListModel brushListModel = new DefaultListModel();
		brushList.setModel(brushListModel);
		brushListModel.addElement(new RegularCircularBrush(null, 80, new Color(0,0,255,32)));
		brushListModel.addElement(new SolidCircularBrush(null, 80, Color.red));
		brushListModel.addElement(new SolidCircularBrush(null, 40, Color.orange));
		brushListModel.addElement(new SolidCircularBrush(null, 120, Color.white));
		brushListModel.addElement(new RegularCircularBrush("Small black brush", 40, new Color(0,0,0,32)));
		brushListModel.addElement(new RegularCircularBrush("Thin black brush", 80, new Color(0,0,0,4)));
		brushListModel.addElement(new RegularCircularBrush("Emerald green 40 px brush", 40, new Color(0,255,96,32)));
		brushListModel.addElement(new RegularEllipticalBrush(null, 60, Math.PI * 0.67, 0.3, new Color(0,0,128,4)));
		brushListModel.addElement(new RegularEllipticalBrush(null, 60, Math.PI * 0.67, 0.5, new Color(0,0,128,4)));
		brushListModel.addElement(new RegularEllipticalBrush(null, 60, Math.PI * 0.8, 0.8, new Color(0,0,128,4)));
		brushListModel.addElement(new RegularEllipticalBrush(null, 120, Math.PI * 0.4, 0.8, new Color(0,0,0,16)));
		brushListModel.addElement(new RegularEllipticalBrush(null, 240, Math.PI * 0.4, 0.8, new Color(255,0,0,16)));
		brushListModel.addElement(new RegularEllipticalBrush(null, 240, Math.PI * 0.2, 0.6, new Color(255,0,0,4)));
		brushListModel.addElement(new RegularEllipticalBrush(null, 40, Math.PI * 0.9, 0.2, new Color(0,255,128,4)));
		brushListModel.addElement(new RegularEllipticalBrush(null, 60, Math.PI * 0.5, 0.4, new Color(0,0,128,16)));
		brushListModel.addElement(new RegularEllipticalEraser(null, 40, 0, 1, 1f));
		brushListModel.addElement(new RegularEllipticalEraser(null, 80, 0, 1, 1f));
		brushListModel.addElement(new RegularEllipticalEraser(null, 80, Math.PI * 0.25, 0.5, 0.5f));
		brushListModel.addElement(new SolidCircularBrush(null, 4));
		brushListModel.addElement(new RegularCircularBrush(null, 4, Color.black));
		brushListModel.addElement(new RegularEllipticalEraser(null, 4, 0, 1, 1f));
		brushListModel.addElement(new StagedBrush(null, 10, Color.black));
		brushListModel.addElement(new RandomSplashBrush(null, 400, 50, Color.black));

		final JPopupMenu brushPopupMenu = new JPopupMenu();
		brushPopupMenu.add(new ActionMenuItem("Change Color...") {
			public void actionPerformed(ActionEvent e)
			{
				Brush b = (Brush)brushList.getSelectedValue();

				if (b == null)
				{
					return;
				}

				Color c = JColorChooser.showDialog(f, "Choose Color...", b.getColor());
				if (c == null)
				{
					return;
				}

				b.setColor(c);
				brushList.repaint();
			}
		});
		brushPopupMenu.add(new ActionMenuItem("Change Size...") {
			public void actionPerformed(ActionEvent e)
			{
				Brush b = (Brush)brushList.getSelectedValue();

				String s = JOptionPane.showInputDialog(f, "Size:");

				b.setSize(Integer.parseInt(s));

				brushList.repaint();
			}
		});
		brushPopupMenu.add(new ActionMenuItem("Properties...") {
			public void actionPerformed(ActionEvent e)
			{
				Brush b = (Brush)brushList.getSelectedValue();

				JPanel p = new JPanel(new BorderLayout());
				JSlider brushSize = new JSlider(1, 200, b.getSize());
				JSlider alpha = new JSlider(0, 100, Math.round(b.getAlpha() * 100));
				JCheckBox rotatable = new JCheckBox("Rotatable brush");
				rotatable.setSelected(b.isRotatable());
				JColorChooser color = new JColorChooser(b.getColor());

				JPanel ip = new JPanel(new GridLayout(0,1));

				ip.add(new JLabel("Brush size:"));
				ip.add(brushSize);
				ip.add(new JLabel("Alpha:"));
				ip.add(alpha);
				ip.add(rotatable);

				p.add(ip, BorderLayout.CENTER);
				p.add(color, BorderLayout.SOUTH);
				p.validate();

				int option = JOptionPane.showConfirmDialog(f, p, "Properties", JOptionPane.OK_CANCEL_OPTION);

				if (option == JOptionPane.CANCEL_OPTION)
				{
					return;
				}

				b.setSize(brushSize.getValue());
				b.setAlpha(((float)alpha.getValue()/100f));
				b.setColor(color.getColor());
				b.setRotatable(rotatable.isSelected());

				brushList.repaint();
			}
		});

		brushList.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e)
			{
				if (e.isPopupTrigger())
				{
					brushPopupMenu.show(e.getComponent(), e.getX(), e.getY());
				}
			}
			public void mouseReleased(MouseEvent e)
			{
				if (e.isPopupTrigger())
				{
					brushPopupMenu.show(e.getComponent(), e.getX(), e.getY());
				}
			}
		});

		final JScrollPane brushListSp = new JScrollPane(brushList);
		listPanels.add(brushListSp);

		final BrushController bc = new BrushController();

		final JList ilList = new JList();
		ilList.setCellRenderer(new ImageLayerListCellRenderer());
		final DefaultListModel ilListModel = new DefaultListModel();
		ilList.setModel(ilListModel);

		/*
		 * Canvas and ImageLayer initializations.
		 */
		final int SIZE = 400;
		final CanvasHolder ch = new CanvasHolder();
		Canvas c = new Canvas(SIZE, SIZE);

		ImageLayer layer0 = new ImageLayer(SIZE, SIZE);

		c.addLayer();
		c.addLayer();
		c.addLayer();
		c.addLayer(layer0);
		c.addLayer(
				new TextLayer(
						SIZE,
						SIZE,
						"Hello World!",
						new Font("Serif", Font.BOLD, 48)
				)
		);

		c.addLayer(new ReferenceLayer(layer0));

		ch.setCanvas(c);

		for (ImageLayer il : c.getLayers())
		{
			ilListModel.addElement(il);
		}

		final JScrollPane ilListSp = new JScrollPane(ilList);
		listPanels.add(ilListSp);

//		final ImageRenderer renderer = ImageRendererFactory.getInstance();
		final PartialImageRenderer renderer = new ClippableImageRenderer();
//		final ProgressiveImageRenderer renderer = new ProgressiveImageRenderer();

		final CanvasViewPanel p = new CanvasViewPanel(renderer, c);

		class DrawEventListener extends MouseAdapter
			implements BrushRenderProgressListener
		{
			// Counter used to keep track of maximum number of steps in the
			// queue for background drawing.
			private int maxSteps = 0;

			public void mouseDragged(MouseEvent e)
			{
				ImageLayer il = (ImageLayer)ilList.getSelectedValue();
				Brush b = (Brush)brushList.getSelectedValue();

				if (il == null || b == null)
				{
					return;
				}

				int offsetX = il.getX();
				int offsetY = il.getY();

				double zoom = ch.getCanvas().getZoom();
				int sx = (int)Math.round((e.getX() - offsetX) / zoom);
				int sy = (int)Math.round((e.getY() - offsetY) / zoom);

				bc.drawBrush(il, b, sx, sy);

				SwingUtilities.invokeLater(new Runnable() {
					public void run()
					{
						p.repaint();
					}
				});
			}

			public void mouseReleased(MouseEvent e)
			{
				if (ilList.getSelectedValue() == null)
				{
					return;
				}

				((ImageLayer)ilList.getSelectedValue()).update();
				ilList.repaint();

				bc.releaseBrush();

				p.repaint();
			}

			public void mousePressed(MouseEvent e)
			{
				ImageLayer il = (ImageLayer)ilList.getSelectedValue();
				Brush b = (Brush)brushList.getSelectedValue();

				if (il == null || b == null)
				{
					return;
				}

				int offsetX = il.getX();
				int offsetY = il.getY();

				double zoom = ch.getCanvas().getZoom();
				int sx = (int)Math.round((e.getX() - offsetX) / zoom);
				int sy = (int)Math.round((e.getY() - offsetY) / zoom);

				bc.drawBrush(il, b, sx, sy);
			}

			/**
			 * callback for background drawing completing
			 */
			@Override
			public void drawComplete()
			{
				SwingUtilities.invokeLater(new Runnable() {
					public void run()
					{
						p.repaint();

						((ImageLayer)ilList.getSelectedValue()).update();
						ilList.repaint();

						statusLabel.setText("Done.");
						progressBar.setValue(0);
						maxSteps = 0;
					}
				});
			}

			/**
			 * callback for drawing progress occurring in the background.
			 */
			@Override
			public void drawProgress(final int stepsLeft)
			{
				SwingUtilities.invokeLater(new Runnable() {
					public void run()
					{
						if (stepsLeft > maxSteps)
						{
							maxSteps = stepsLeft;
							progressBar.setMaximum(maxSteps);
						}

						statusLabel.setText("Rendering brush...");
						progressBar.setValue(maxSteps - stepsLeft);

						// update imagelayer thumbnail and imagelayer list
						((ImageLayer)ilList.getSelectedValue()).update();
						ilList.repaint();
					}
				});
			}
		};

		DrawEventListener drawEventListener = new DrawEventListener();
		bc.addBrushRenderProgressListener(drawEventListener);

		p.addMouseListener(drawEventListener);
		p.addMouseMotionListener(drawEventListener);

		ilList.setDropTarget(new DropTarget()
		{
			/* (non-Javadoc)
			 * @see java.awt.dnd.DropTarget#drop(java.awt.dnd.DropTargetDropEvent)
			 */
			@Override
			public synchronized void drop(DropTargetDropEvent e)
			{
				super.drop(e);
				Point pt = e.getLocation();
				int fromIndex = ilList.getSelectedIndex();
				int toIndex = ilList.locationToIndex(pt);

				ch.getCanvas().moveLayer(fromIndex, toIndex);

				ilListModel.removeAllElements();
				for (ImageLayer il : ch.getCanvas().getLayers())
				{
					ilListModel.addElement(il);
				}
				p.repaint();
			}
		});
		ilList.setDragEnabled(true);

		final JPopupMenu ilPopupMenu = new JPopupMenu();

		ilPopupMenu.add(new ActionMenuItem("Change Name...") {
			public void actionPerformed(ActionEvent e)
			{
				String s = JOptionPane.showInputDialog(f, "Name:");
				((ImageLayer)ilList.getSelectedValue()).setCaption(s);
				p.repaint();
			}
		});
		ilPopupMenu.add(new ActionMenuItem("Change Alpha...") {
			public void actionPerformed(ActionEvent e)
			{
				String s = JOptionPane.showInputDialog(f, "Alpha:");
				((ImageLayer)ilList.getSelectedValue()).setAlpha(Float.parseFloat(s));
				p.repaint();
			}
		});
		ilPopupMenu.add(new ActionMenuItem("Change Location...") {
			public void actionPerformed(ActionEvent e)
			{
				String s = JOptionPane.showInputDialog(f, "Location (x,y):");
				String[] t = s.split(",");
				int x = Integer.parseInt(t[0]);
				int y = Integer.parseInt(t[1]);

				((ImageLayer)ilList.getSelectedValue()).setLocation(x, y);
				p.repaint();
			}
		});
		ilPopupMenu.add(new ActionMenuItem("Change Mode...") {
			public void actionPerformed(ActionEvent e)
			{
				ImageLayer il = (ImageLayer)ilList.getSelectedValue();
				JComboBox cb = new JComboBox(BlendingMode.Layer.values());
				cb.setSelectedItem(il.getMode());
				JOptionPane.showMessageDialog(f, cb);
				il.setMode((BlendingMode.Layer)cb.getSelectedItem());
				p.repaint();
			}
		});
		ilPopupMenu.addSeparator();

		ilPopupMenu.add(new ActionMenuItem("New Layer") {
			public void actionPerformed(ActionEvent e)
			{
				ImageLayer il = new ImageLayer(
						ch.getCanvas().getWidth(),
						ch.getCanvas().getHeight()
				);
				il.setCaption(ch.getCanvas().getNextLayerName());

				ch.getCanvas().addLayer(il);

				updateGUI(ilListModel, ch, p);
			}
		});

		ilPopupMenu.add(new ActionMenuItem("Delete Layer") {
			public void actionPerformed(ActionEvent e)
			{
				ImageLayer il = (ImageLayer)ilList.getSelectedValue();
				ch.getCanvas().removeLayer(il);

				updateGUI(ilListModel, ch, p);
			}
		});

		ilPopupMenu.add(new ActionMenuItem("Merge Layer") {
			public void actionPerformed(ActionEvent e)
			{
				int index = ilList.getSelectedIndex();
				if (index >= ilListModel.size() - 1)
				{
					return;
				}

				ImageLayer topIl = (ImageLayer)ilListModel.get(index);
				ImageLayer bottomIl = (ImageLayer)ilListModel.get(index + 1);

				ch.getCanvas().removeLayer(topIl);
				ch.getCanvas().removeLayer(bottomIl);

				ch.getCanvas().addLayer(ImageLayerUtils.mergeLayers(topIl, bottomIl), index);

				updateGUI(ilListModel, ch, p);
			}
		});

		ilList.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e)
			{
				if (e.isPopupTrigger())
				{
					ilPopupMenu.show(e.getComponent(), e.getX(), e.getY());
				}
			}
			public void mouseReleased(MouseEvent e)
			{
				if (e.isPopupTrigger())
				{
					ilPopupMenu.show(e.getComponent(), e.getX(), e.getY());
				}
			}
		});

		final JMenuBar menubar = new JMenuBar();
		final JMenu fileMenu = new JMenu("File");
		final JMenu layerMenu = new JMenu("Layer");
		final JMenu filterMenu = new JMenu("Filter");

		fileMenu.add(new ActionMenuItem("New...") {
			public void actionPerformed(ActionEvent e)
			{
				System.out.println("new");

				String s = JOptionPane.showInputDialog(f, "Enter dimensions in (w,h):");

				if (s == null)
				{
					return;
				}

				int width = SIZE;
				int height = SIZE;

				String[] t = s.split(",");

				try
				{
					width = Integer.parseInt(t[0]);
					height = Integer.parseInt(t[1]);
				}
				catch (Exception ex)
				{
					JOptionPane.showMessageDialog(f, "Invalid dimensions.\n" + ex);
				}

				Canvas c = new Canvas(width, height);
				c.addLayer(new ImageLayer(width, height));
				ch.setCanvas(c);

				updateGUI(ilListModel, ch, p);
			}
		});

		fileMenu.addSeparator();

		fileMenu.add(new ActionMenuItem("Open...") {
			public void actionPerformed(ActionEvent e)
			{
				JFileChooser fc = new JFileChooser();
				for (FileFilter filter : FormatManager.getInputFileFilters())
				{
					fc.addChoosableFileFilter(filter);
				}

				while (true)
				{
					int option = fc.showOpenDialog(f);

					if (option != JFileChooser.APPROVE_OPTION)
						return;

					File inFile = fc.getSelectedFile();

					ImageInput input = FormatManager.getImageInput(inFile);

					if (input != null)
					{
						try
						{
							ch.setCanvas(input.read(inFile));
						}
						catch (ImageInputOutputException e1)
						{
							ApplicationUtils.showExceptionMessage(e1);
						}
						updateGUI(ilListModel, ch, p);
						return;
					}
					else
					{
						JOptionPane.showMessageDialog(f, "Could not open file: " + inFile);
					}
				}
			}
		});

		fileMenu.add(new ActionMenuItem("Save As...") {
			public void actionPerformed(ActionEvent e)
			{
				JFileChooser fc = new JFileChooser();
				for (FileFilter filter : FormatManager.getOutputFileFilters())
				{
					fc.addChoosableFileFilter(filter);
				}
				fc.setFileFilter(fc.getAcceptAllFileFilter());

				while (true)
				{
					int option = fc.showSaveDialog(f);

					if (option != JFileChooser.APPROVE_OPTION)
					{
						return;
					}

					File outFile = fc.getSelectedFile();
					ImageOutput output = FormatManager.getImageOutput(outFile);

					// fc.getFileFilter();

					if (output != null)
					{
						try
						{
							output.write(ch.getCanvas(), outFile);
						}
						catch (ImageInputOutputException e1)
						{
							ApplicationUtils.showExceptionMessage(e1);
						}
						return;
					}
					else
					{
						JOptionPane.showMessageDialog(f, "Could not write file" + outFile);
					}
				}
			}
		});

		fileMenu.addSeparator();

		fileMenu.add(new ActionMenuItem("Import Layer...") {
			public void actionPerformed(ActionEvent e)
			{
				JFileChooser fc = new JFileChooser();
				for (FileFilter filter : FormatManager.getInputFileFilters())
				{
					fc.addChoosableFileFilter(filter);
				}

				while (true)
				{
					int option = fc.showOpenDialog(f);

					if (option != JFileChooser.APPROVE_OPTION)
						return;

					File inFile = fc.getSelectedFile();

					ImageInput input = FormatManager.getImageInput(inFile);

					if (input != null)
					{

						Canvas c;
						try
						{
							c = input.read(inFile);

							for (ImageLayer layer : c.getLayers())
							{
								ch.getCanvas().addLayer(layer);
							}

							updateGUI(ilListModel, ch, p);
						}
						catch (ImageInputOutputException e1)
						{
							ApplicationUtils.showExceptionMessage(e1);
						}
						return;
					}
					else
					{
						JOptionPane.showMessageDialog(f, "ZCould not open file: " + inFile);
					}
				}
			}
		});

		fileMenu.addSeparator();

		fileMenu.add(new ActionMenuItem("Exit") {
			public void actionPerformed(ActionEvent arg0)
			{
				f.setVisible(false);
			}
		});

		////////////////

		layerMenu.add(new ActionMenuItem("New Layer") {
			public void actionPerformed(ActionEvent e)
			{
				ch.getCanvas().addLayer(new ImageLayer(ch.getCanvas().getWidth(), ch.getCanvas().getHeight()));

				updateGUI(ilListModel, ch, p);
			}
		});

		layerMenu.add(new ActionMenuItem("Delete Layer") {
			public void actionPerformed(ActionEvent e)
			{
				if (ilList.getSelectedIndex() == -1)
				{
					return;
				}

				ImageLayer il = (ImageLayer)ilList.getSelectedValue();
				ch.getCanvas().removeLayer(il);

				updateGUI(ilListModel, ch, p);
			}
		});

		layerMenu.add(new ActionMenuItem("Merge Layer") {
			public void actionPerformed(ActionEvent e)
			{
				if (ilList.getSelectedIndex() == -1)
				{
					return;
				}

				int index = ilList.getSelectedIndex();
				if (index >= ilListModel.size() - 1)
				{
					return;
				}

				ImageLayer topIl = (ImageLayer)ilListModel.get(index);
				ImageLayer bottomIl = (ImageLayer)ilListModel.get(index + 1);

				ch.getCanvas().removeLayer(topIl);
				ch.getCanvas().removeLayer(bottomIl);

				ch.getCanvas().addLayer(ImageLayerUtils.mergeLayers(topIl, bottomIl), index);

				updateGUI(ilListModel, ch, p);
			}
		});

		layerMenu.addSeparator();

		layerMenu.add(new ActionMenuItem("Size Canvas to Largest Layer") {
			public void actionPerformed(ActionEvent e)
			{
				ch.getCanvas().pack();

				ilList.repaint();
				p.repaint();
			}
		});

		layerMenu.add(new ActionMenuItem("Grow Layer to Canvas") {
			public void actionPerformed(ActionEvent e)
			{
			}
		});

		layerMenu.add(new ActionMenuItem("Resize Canvas...") {
			public void actionPerformed(ActionEvent e)
			{
			}
		});

		layerMenu.addSeparator();

		layerMenu.add(new ActionMenuItem("Select Layer") {
			public void actionPerformed(ActionEvent e)
			{
				((ImageLayer)(ilList.getSelectedValue())).getGraphics().setClip(50,50,300,300);
			}
		});
		layerMenu.add(new ActionMenuItem("Deselect Layer") {
			public void actionPerformed(ActionEvent e)
			{
				((ImageLayer)(ilList.getSelectedValue())).getGraphics().setClip(null);
			}
		});

		////////////////

		class FilterWithProgressBar
		{
			final ImageFilter filter;
			final JProgressBar pb;
			final JDialog d;

			public FilterWithProgressBar(final ImageFilter filter)
			{
				pb = new JProgressBar();
				d = new JDialog(f);
				JPanel panel = new JPanel(new BorderLayout());
				pb.setValue(0);
				pb.setStringPainted(true);
				panel.add(new JLabel("Processing filter..."), BorderLayout.NORTH);
				panel.add(pb, BorderLayout.CENTER);
				d.getContentPane().add(panel);
				d.pack();
				d.setVisible(true);

				this.filter = filter;
			}

			public void run()
			{
				new Thread(new Runnable() {
					public void run()
					{
						long st = System.currentTimeMillis();

						final int inc = 100 / ch.getCanvas().getLayers().size();

						for (ImageLayer il : ch.getCanvas().getLayers())
						{
							il.setImage(filter.processImage(il.getImage()));

							try
							{
								SwingUtilities.invokeAndWait(new Runnable() {
									public void run()
									{
										pb.setValue(pb.getValue() + inc);
									}
								});
							}
							catch (InterruptedException e)
							{
								e.printStackTrace();
							}
							catch (InvocationTargetException e)
							{
								e.printStackTrace();
							}
						}

						long tp = System.currentTimeMillis() - st;
						System.out.println("complete in: " + tp);

						pb.setValue(100);
						d.dispose();
						p.repaint();
						ilList.repaint();
					}
				}).start();
			}
		}

		filterMenu.add(new ActionMenuItem("Blur") {
			public void actionPerformed(ActionEvent e)
			{
				ImageFilter filter = new MatrixImageFilter(3, 3, new float[]{
						0.0f,	0.1f,	 0.0f,
						0.1f,	0.6f,	 0.1f,
						0.0f,	0.1f,	 0.0f
				});

				new FilterWithProgressBar(filter).run();
			}
		});

		filterMenu.add(new ActionMenuItem("Blur More") {
			public void actionPerformed(ActionEvent e)
			{
				ImageFilter filter = new RepeatableMatrixFilter(
						"Blur More",
						3,
						3,
						10,
						new float[]{
						0.0f,	0.1f,	 0.0f,
						0.1f,	0.6f,	 0.1f,
						0.0f,	0.1f,	 0.0f
				});

				new FilterWithProgressBar(filter).run();
			}
		});

		filterMenu.add(new ActionMenuItem("Blur More Concurrent") {
			public void actionPerformed(ActionEvent e)
			{
				ImageFilter filter = new ImageFilterThreadingWrapper(
						new RepeatableMatrixFilter(
							3,
							3,
							10,
							new float[] {
									0.0f,	0.1f,	 0.0f,
									0.1f,	0.6f,	 0.1f,
									0.0f,	0.1f,	 0.0f
							}
						)
				);

				new FilterWithProgressBar(filter).run();
			}
		});

		filterMenu.add(new ActionMenuItem("Blur More Concurrent (1/9 all)") {
			public void actionPerformed(ActionEvent e)
			{
				ImageFilter filter = new ImageFilterThreadingWrapper(
						new RepeatableMatrixFilter(
							3,
							3,
							10,
							new float[] {
									1f/9f,	1f/9f,	 1f/9f,
									1f/9f,	1f/9f,	 1f/9f,
									1f/9f,	1f/9f,	 1f/9f
							}
						)
				);

				new FilterWithProgressBar(filter).run();
			}
		});

		filterMenu.add(new ActionMenuItem("Blur More Concurrent 7x7") {
			public void actionPerformed(ActionEvent e)
			{
				ImageFilter filter = new ImageFilterThreadingWrapper(
						new RepeatableMatrixFilter(
								7,
								7,
								1,
								new float[] {
										0.0f,	0.0f,	0.0f,	 0.05f,	0.0f,	0.0f,	0.0f,
										0.0f,	0.0f,	0.0f,	 0.05f,	0.0f,	0.0f,	0.0f,
										0.0f,	0.0f,	0.0f,	 0.1f,	0.0f,	0.0f,	0.0f,
										0.05f,	0.05f,	0.1f,	 0.2f,	0.1f,	0.05f,	0.05f,
										0.0f,	0.0f,	0.0f,	 0.1f,	0.0f,	0.0f,	0.0f,
										0.0f,	0.0f,	0.0f,	 0.05f,	0.0f,	0.0f,	0.0f,
										0.0f,	0.0f,	0.0f,	 0.05f,	0.0f,	0.0f,	0.0f
								}
						),
						10
				);

				new FilterWithProgressBar(filter).run();
			}
		});

		filterMenu.add(new ActionMenuItem("No Effect") {
			public void actionPerformed(ActionEvent e)
			{
				ImageFilter filter = new MatrixImageFilter(
						"No Effect",
						3, 3, new float[]{
						0.0f,	0.0f,	 0.0f,
						0.0f,	1.0f,	 0.0f,
						0.0f,	0.0f,	 0.0f
				});

				new FilterWithProgressBar(filter).run();
			}
		});

		filterMenu.add(new ActionMenuItem("Saturate") {
			public void actionPerformed(ActionEvent e)
			{
				ImageFilter filter = new MatrixImageFilter(3, 3, new float[]{
						0.0f,	0.0f,	 0.0f,
						0.0f,	2.0f,	 0.0f,
						0.0f,	0.0f,	 0.0f
				});

				new FilterWithProgressBar(filter).run();
			}
		});

		filterMenu.add(new ActionMenuItem("Blur + Lighten") {
			public void actionPerformed(ActionEvent e)
			{
				ImageFilter filter = new MatrixImageFilter(5, 5, new float[]{
						0.0f,	0.0f,	 0.25f,	0.0f,	0.0f,
						0.0f,	0.0f,	 0.0f,	0.0f,	0.0f,
						0.25f,	0.0f,	 1.0f,	0.0f,	0.25f,
						0.0f,	0.0f,	 0.0f,	0.0f,	0.0f,
						0.0f,	0.0f,	 0.25f,	0.0f,	0.0f
				});

				new FilterWithProgressBar(filter).run();
			}
		});

		filterMenu.add(new ActionMenuItem("Resize...") {
			public void actionPerformed(ActionEvent e)
			{
				String s = JOptionPane.showInputDialog(f, "Resize scale:");
				final double scale = Double.parseDouble(s);

				final JProgressBar pb = new JProgressBar();
				final JDialog d = new JDialog(f);
				JPanel panel = new JPanel(new BorderLayout());
				pb.setValue(0);
				pb.setStringPainted(true);
				panel.add(new JLabel("Processing filter..."), BorderLayout.NORTH);
				panel.add(pb, BorderLayout.CENTER);
				d.getContentPane().add(panel);
				d.pack();
				d.setVisible(true);

				new Thread(new Runnable() {
					public void run()
					{
						long st = System.currentTimeMillis();

						ImageFilter filter = new ResizeFilter("Resize", scale);

						for (ImageLayer il : ch.getCanvas().getLayers())
						{
							il.setImage(filter.processImage(il.getImage()));
						}

						final int inc = 100 / ch.getCanvas().getLayers().size();

						for (ImageLayer il : ch.getCanvas().getLayers())
						{
							il.setImage(filter.processImage(il.getImage()));

							try
							{
								SwingUtilities.invokeAndWait(new Runnable() {
									public void run()
									{
										pb.setValue(pb.getValue() + inc);
									}
								});
							}
							catch (InterruptedException e)
							{
								e.printStackTrace();
							}
							catch (InvocationTargetException e)
							{
								e.printStackTrace();
							}
						}

						long tp = System.currentTimeMillis() - st;
						System.out.println("complete in: " + tp);

						pb.setValue(100);
						d.dispose();

						Rectangle r = new Rectangle();

						for (ImageLayer il : ch.getCanvas().getLayers())
						{
							r.add(new Rectangle(
									il.getX(),
									il.getY(),
									il.getWidth(),
									il.getHeight()
							));
						}

						ch.getCanvas().setSize(r.width, r.height);

						p.repaint();
						ilList.repaint();
						p.revalidate();
					}
				}).start();
			}
		});

		filterMenu.add(new ActionMenuItem("Resize Concurrent...") {
			public void actionPerformed(ActionEvent e)
			{
				String s = JOptionPane.showInputDialog(f, "Resize scale:");
				final double scale = Double.parseDouble(s);

				final JProgressBar pb = new JProgressBar();
				final JDialog d = new JDialog(f);
				JPanel panel = new JPanel(new BorderLayout());
				pb.setValue(0);
				pb.setStringPainted(true);
				panel.add(new JLabel("Processing filter..."), BorderLayout.NORTH);
				panel.add(pb, BorderLayout.CENTER);
				d.getContentPane().add(panel);
				d.pack();
				d.setVisible(true);

				new Thread(new Runnable() {
					public void run()
					{
						long st = System.currentTimeMillis();

						ImageFilter filter = new ImageFilterThreadingWrapper(new ResizeFilter("Resize Concurrent", scale));

						for (ImageLayer il : ch.getCanvas().getLayers())
						{
							il.setImage(filter.processImage(il.getImage()));
						}

						final int inc = 100 / ch.getCanvas().getLayers().size();

						for (ImageLayer il : ch.getCanvas().getLayers())
						{
							il.setImage(filter.processImage(il.getImage()));

							try
							{
								SwingUtilities.invokeAndWait(new Runnable() {
									public void run()
									{
										pb.setValue(pb.getValue() + inc);
									}
								});
							}
							catch (InterruptedException e)
							{
								e.printStackTrace();
							}
							catch (InvocationTargetException e)
							{
								e.printStackTrace();
							}
						}

						long tp = System.currentTimeMillis() - st;
						System.out.println("complete in: " + tp);

						pb.setValue(100);
						d.dispose();

						Rectangle r = new Rectangle();

						for (ImageLayer il : ch.getCanvas().getLayers())
						{
							r.add(new Rectangle(
									il.getX(),
									il.getY(),
									il.getWidth(),
									il.getHeight()
							));
						}

						ch.getCanvas().setSize(r.width, r.height);

						p.repaint();
						ilList.repaint();
						p.revalidate();
					}
				}).start();
			}
		});

		layerMenu.addSeparator();

		layerMenu.add(new ActionMenuItem("Throw Exception") {
			public void actionPerformed(ActionEvent e)
			{
				try
				{
					class CatchMeIfYouCanException extends Exception
					{
						private CatchMeIfYouCanException(String s)
						{
							super(s);
						}
					}

					throw new CatchMeIfYouCanException("Ha! Catch me if you can!");
				}
				catch (Exception ex)
				{
					ApplicationUtils.showExceptionMessage(ex);
				}
			}
		});

		layerMenu.addSeparator();

		final JScrollPane sp = new JScrollPane(p);
		sp.getViewport().addChangeListener(new ChangeListener() {
			@Override
			public void stateChanged(ChangeEvent e)
			{
				sp.repaint();
			}
		});

		layerMenu.add(new ActionMenuItem("Zoom...") {
			public void actionPerformed(ActionEvent e)
			{
				String s = JOptionPane.showInputDialog(f, "Zoom:");

				ch.getCanvas().setZoom(Double.parseDouble(s));

				p.revalidate();
				p.repaint();
			}
		});

		JMenu helpMenu = new JMenu("Help");

		helpMenu.add(new ActionMenuItem("About...") {
			public void actionPerformed(ActionEvent e)
			{
				String msg = "Coobird's Paint dot Jar Demonstration 2";
				JOptionPane.showMessageDialog(f, msg, "About Paint dot Jar", JOptionPane.INFORMATION_MESSAGE);
			}
		});

		menubar.add(fileMenu);
		menubar.add(layerMenu);
		menubar.add(filterMenu);
		menubar.add(helpMenu);
		f.setJMenuBar(menubar);

		f.setSize(800, 600);
		f.setLocation(100, 100);
		f.setLocation(1, 1);
		JSplitPane splitPane = new JSplitPane(
				JSplitPane.HORIZONTAL_SPLIT,
				true,
				sp,
				listPanels
		);
		f.getContentPane().add(splitPane, BorderLayout.CENTER);

		f.validate();
		f.setVisible(true);
		splitPane.setDividerLocation(0.7);
	}

	private void updateGUI(final DefaultListModel ilListModel,
			final CanvasHolder ch, final CanvasViewPanel p)
	{
		SwingUtilities.invokeLater(new Runnable() {

			public void run()
			{
				ilListModel.removeAllElements();
				for (ImageLayer il : ch.getCanvas().getLayers())
				{
					ilListModel.addElement(il);
				}

				p.setCanvas(ch.getCanvas());
				p.repaint();
				p.revalidate();
			}
		});
	}

	public static void main(String[] args)
	{
		try
		{
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		}
		catch (UnsupportedLookAndFeelException e)
		{
			e.printStackTrace();
		}
		catch (ClassNotFoundException e)
		{
			e.printStackTrace();
		}
		catch (InstantiationException e)
		{
			e.printStackTrace();
		}
		catch (IllegalAccessException e)
		{
			e.printStackTrace();
		}

		SwingUtilities.invokeLater(new Runnable()
		{
			public void run()
			{
				new DemoApp2().makeGUI();
			}
		});
	}

	private static class CanvasHolder
	{
		Canvas c;

		public Canvas getCanvas()
		{
			return c;
		}

		public void setCanvas(Canvas c)
		{
			this.c = c;
		}
	}
}


text:
package me.yoerger.geoff.edu.progClass.bookClasses;

import java.awt.Graphics;

public interface ModelDisplay
{
  /** method to notify the thing that displays that
   * the model has changed */
  public void modelChanged();

  /** method to add the model to the world
   * @param model the model object to add */
  public void addModel(Object model);

  /**
   * Method to remove the model from the world
   * @param model the model object to remove */
  public void remove(Object model);

  /**
   * Method that returns the graphics context
   * for this model display
   * @return the graphics context
   */
  public Graphics getGraphics();

  /**
   * Method to clear the background
   */
  public void clearBackground();

  /** Method to get the width of the display
   * @return the width in pixels of the display
   */
  public int getWidth();

  /** Method to get the height of the display
   * @return the height in pixels of the display
   */
  public int getHeight();
}

redpajama_set_name: RedPajamaGithub


text:
    /**
     * @ngdoc model
     * @name ExtendedDataDisplay
     * @function
     *
     * @description
     * Represents a JS version of Merchello's ExtendedDataDisplay object
     */
    var ExtendedDataDisplay = function() {
        var self = this;
        self.items = [];
    };

    ExtendedDataDisplay.prototype = (function() {

        function isEmpty() {
            return this.items.length === 0;
        }

        function getValue(key) {
            if (isEmpty.call(this)) {
                return '';
            }
            var found = false;
            var i = 0;
            var value = '';
            while(i < this.items.length && !found) {
                if (this.items[ i ].key === key) {
                    found = true;

                    value = this.items[ i ].value;
                } else {
                    i++;
                }
            }
            return value;
        }

        function setValue(key, value) {

            var existing = _.find(this.items, function(item) {
              return item.key === key;
            });
            if(existing) {
                existing.value = value;
                return;
            }

            this.items.push({ key: key, value: value });
        }

        function toArray() {
            return this.items;
        }

        function asDetachedValueArray() {
            var values = [];
            angular.forEach(this.items, function(dcv) {

                // ensure there are not null values
                if (dcv.value === null) {
                    dcv.value = '';
                }

                // ensure property did not set an array
                if (angular.isArray(dcv.value) && dcv.value.length == 0) {
                    dcv.value = '';
                }
                values.push(dcv);
            });

            return values;
        }

        return {
            isEmpty: isEmpty,
            getValue: getValue,
            setValue: setValue,
            toArray: toArray,
            asDetachedValueArray: asDetachedValueArray
        };
    }());

    angular.module('merchello.models').constant('ExtendedDataDisplay', ExtendedDataDisplay);


text:
@class Dog;
@interface People : NSObject

@property (nonatomic,strong) NSString * name ;
@property (nonatomic,weak) Dog * dog;

@end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Threax.AspNetCore.FileRepository;

namespace Microsoft.Extensions.DependencyInjection
{
    /// <summary>
    /// Options for the file repository.
    /// </summary>
    public class FileRepositoryOptions
    {
        /// <summary>
        /// Callback function to
        /// </summary>
        public Action<IFileVerifier> ConfigureVerifier { get; set; }

        public String OutputDir { get; set; }
    }

    public static class FileRepositoryServiceExtensions
    {
        /// <summary>
        /// Add a file repository. Use ConfigureVerifier in the options to add the file types you want to support.
        /// </summary>
        /// <param name="services">The service colleciton to add the file verifier to.</param>
        /// <param name="options">The options.</param>
        /// <returns>The service collection.</returns>
        public static IServiceCollection AddFileRepository(this IServiceCollection services, FileRepositoryOptions options)
        {
            if (String.IsNullOrEmpty(options.OutputDir))
            {
                throw new InvalidOperationException("You must include an output directory");
            }

            if(options.ConfigureVerifier == null)
            {
                throw new InvalidOperationException("You must include a function to configure your file validator.");
            }

            services.AddSingleton<IFileVerifier>(s =>
            {
                var verifier = new FileVerifier();
                options.ConfigureVerifier(verifier);
                return verifier;
            });
            services.AddSingleton<IFileRepository>(s =>
            {
                return new FileRepository<IFileRepository>(options.OutputDir, s.GetRequiredService<IFileVerifier>());
            });

            return services;
        }

        /// <summary>
        /// Add a file repository. Use ConfigureVerifier in the options to add the file types you want to support.
        /// This version allows you to use a type for injection so you can have multiple file repositories with different
        /// configurations.
        /// </summary>
        /// <typeparam name="InjectT">The type to uniquly identify this repository with. This type is not used anywhere in the actual repository.</typeparam>
        /// <param name="services">The service colleciton to add the file verifier to.</param>
        /// <param name="options">The options.</param>
        /// <returns>The service collection.</returns>
        public static IServiceCollection AddFileRepository<InjectT>(this IServiceCollection services, FileRepositoryOptions options)
        {
            if (String.IsNullOrEmpty(options.OutputDir))
            {
                throw new Exception("You must include an output directory");
            }

            if (options.ConfigureVerifier == null)
            {
                throw new InvalidOperationException("You must include a function to configure your file validator.");
            }

            services.AddSingleton<IFileVerifier<InjectT>>(s =>
            {
                var verifier = new FileVerifier<InjectT>();
                options.ConfigureVerifier(verifier);
                return verifier;
            });

            services.AddSingleton<IFileRepository<InjectT>>(s =>
            {
                return new FileRepository<InjectT>(options.OutputDir, s.GetRequiredService<IFileVerifier<InjectT>>());
            });

            return services;
        }
    }
}


text:
var MongoClient = require('mongodb').MongoClient;
var properties = require('./envProperties');
  //, assert = require('assert');

// Connection URL
var url = properties.MONGO_DOMAIN;
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
  //assert.equal(null, err);
  console.log("Connected correctly to server");
  exports.mongodb=db;

});


text:
Public Class FormLogin
    Dim nTries As Integer = 0
    Private Sub FormLogin_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        lbTime.Text = ""
        tbUsername.Focus()
    End Sub

    Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Dim tm As Date = Date.Now
        lbTime.Text = tm.ToString()
    End Sub

    Private Sub tbUsername_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles tbUsername.KeyUp
        If e.KeyCode = Keys.Enter Then
            tbPassword.Focus()
            tbPassword.Text = ""
        End If
    End Sub

    Private Sub tbPassword_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles tbPassword.KeyUp
        If e.KeyCode = Keys.Enter Then
            btnLogin.PerformClick()
        End If
    End Sub

    Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
        Dim db As New BBDatabase
        If db.VerifyUser(tbUsername.Text, tbPassword.Text) = True Then
            Me.DialogResult = DialogResult.OK
            Me.Close()
            Exit Sub
        Else
            If nTries > 5 Then
                Me.DialogResult = DialogResult.Cancel
                Me.Close()
                Exit Sub
            End If
            nTries += 1
            MessageBox.Show("The Username or Password do not match. Please re-enter the username and password", "Invalid Username and Password", MessageBoxButtons.OK, MessageBoxIcon.Hand)
            tbUsername.Focus()
            tbUsername.Text = ""
            tbPassword.Text = ""
        End If
    End Sub
End Class


text:
/*
Version: 3.0 Timestamp: Tue Jul 31 21:09:16 PDT 2012
*/
.select2-container {
    position: relative;
    display: inline-block;
    /* inline-block for ie7 */
    zoom: 1;
    *display: inline;

}

.select2-container,
.select2-drop,
.select2-search,
.select2-search input{
  /*
    Force border-box so that % widths fit the parent
    container without overlap because of margin/padding.

    More Info : http://www.quirksmode.org/css/box.html
  */
  -moz-box-sizing: border-box;    /* firefox */
  -ms-box-sizing: border-box;     /* ie */
  -webkit-box-sizing: border-box; /* webkit */
  -khtml-box-sizing: border-box;  /* konqueror */
  box-sizing: border-box;         /* css3 */
}

.select2-container .select2-choice {
    background-color: #fff;
    background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0, #eeeeee), color-stop(0.5, white));
    background-image: -webkit-linear-gradient(center bottom, #eeeeee 0%, white 50%);
    background-image: -moz-linear-gradient(center bottom, #eeeeee 0%, white 50%);
    background-image: -o-linear-gradient(bottom, #eeeeee 0%, #ffffff 50%);
    background-image: -ms-linear-gradient(top, #eeeeee 0%, #ffffff 50%);
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr = '#eeeeee', endColorstr = '#ffffff', GradientType = 0);
    background-image: linear-gradient(top, #eeeeee 0%, #ffffff 50%);
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
    -moz-background-clip: padding;
    -webkit-background-clip: padding-box;
    background-clip: padding-box;
    border: 1px solid #aaa;
    display: block;
    overflow: hidden;
    white-space: nowrap;
    position: relative;
    height: 26px;
    line-height: 26px;
    padding: 0 0 0 8px;
    color: #444;
    text-decoration: none;
}

.select2-container.select2-drop-above .select2-choice
{
    border-bottom-color: #aaa;
    -webkit-border-radius:0px 0px 4px 4px;
    -moz-border-radius:0px 0px 4px 4px;
    border-radius:0px 0px 4px 4px;
    background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0, #eeeeee), color-stop(0.9, white));
    background-image: -webkit-linear-gradient(center bottom, #eeeeee 0%, white 90%);
    background-image: -moz-linear-gradient(center bottom, #eeeeee 0%, white 90%);
    background-image: -o-linear-gradient(bottom, #eeeeee 0%, white 90%);
    background-image: -ms-linear-gradient(top, #eeeeee 0%,#ffffff 90%);
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#eeeeee', endColorstr='#ffffff',GradientType=0 );
    background-image: linear-gradient(top, #eeeeee 0%,#ffffff 90%);
}

.select2-container .select2-choice span {
    margin-right: 26px;
    display: block;
    overflow: hidden;
    white-space: nowrap;
    -o-text-overflow: ellipsis;
    -ms-text-overflow: ellipsis;
    text-overflow: ellipsis;
}

.select2-container .select2-choice abbr {
  display: block;
  position: absolute;
  right: 26px;
  top: 8px;
  width: 12px;
  height: 12px;
  font-size: 1px;
  background: url('../img/select2.png') right top no-repeat;
  cursor: pointer;
  text-decoration: none;
  border:0;
  outline: 0;
}
.select2-container .select2-choice abbr:hover {
  background-position: right -11px;
  cursor: pointer;
}

.select2-drop {
    background: #fff;
    color: #000;
    border: 1px solid #aaa;
    border-top: 0;
    position: absolute;
    top: 100%;
    -webkit-box-shadow: 0 4px 5px rgba(0, 0, 0, .15);
    -moz-box-shadow: 0 4px 5px rgba(0, 0, 0, .15);
    -o-box-shadow: 0 4px 5px rgba(0, 0, 0, .15);
    box-shadow: 0 4px 5px rgba(0, 0, 0, .15);
    z-index: 9999;
    width:100%;
    margin-top:-1px;

  -webkit-border-radius: 0 0 4px 4px;
  -moz-border-radius: 0 0 4px 4px;
  border-radius: 0 0 4px 4px;
}

.select2-drop.select2-drop-above {
    -webkit-border-radius: 4px 4px 0px 0px;
    -moz-border-radius: 4px 4px 0px 0px;
    border-radius: 4px 4px 0px 0px;
    margin-top:1px;
    border-top: 1px solid #aaa;
    border-bottom: 0;

    -webkit-box-shadow: 0 -4px 5px rgba(0, 0, 0, .15);
    -moz-box-shadow: 0 -4px 5px rgba(0, 0, 0, .15);
    -o-box-shadow: 0 -4px 5px rgba(0, 0, 0, .15);
    box-shadow: 0 -4px 5px rgba(0, 0, 0, .15);
}

.select2-container .select2-choice div {
    -webkit-border-radius: 0 4px 4px 0;
    -moz-border-radius: 0 4px 4px 0;
    border-radius: 0 4px 4px 0;
    -moz-background-clip: padding;
    -webkit-background-clip: padding-box;
    background-clip: padding-box;
    background: #ccc;
    background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0, #ccc), color-stop(0.6, #eee));
    background-image: -webkit-linear-gradient(center bottom, #ccc 0%, #eee 60%);
    background-image: -moz-linear-gradient(center bottom, #ccc 0%, #eee 60%);
    background-image: -o-linear-gradient(bottom, #ccc 0%, #eee 60%);
    background-image: -ms-linear-gradient(top, #cccccc 0%, #eeeeee 60%);
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr = '#cccccc', endColorstr = '#eeeeee', GradientType = 0);
    background-image: linear-gradient(top, #cccccc 0%, #eeeeee 60%);
    border-left: 1px solid #aaa;
    position: absolute;
    right: 0;
    top: 0;
    display: block;
    height: 100%;
    width: 18px;
}

.select2-container .select2-choice div b {
    background: url('../img/select2.png') no-repeat 0 1px;
    display: block;
    width: 100%;
    height: 100%;
}

.select2-search {
  display: inline-block;
    white-space: nowrap;
    z-index: 10000;
  min-height: 26px;
  width: 100%;
  margin: 0;
  padding-left: 4px;
  padding-right: 4px;
}

.select2-search-hidden {
  display: block;
  position: absolute;
  left: -10000px;
}

.select2-search input {
    background: #fff url('../img/select2.png') no-repeat 100% -22px;
    background: url('../img/select2.png') no-repeat 100% -22px, -webkit-gradient(linear, left bottom, left top, color-stop(0.85, white), color-stop(0.99, #eeeeee));
    background: url('../img/select2.png') no-repeat 100% -22px, -webkit-linear-gradient(center bottom, white 85%, #eeeeee 99%);
    background: url('../img/select2.png') no-repeat 100% -22px, -moz-linear-gradient(center bottom, white 85%, #eeeeee 99%);
    background: url('../img/select2.png') no-repeat 100% -22px, -o-linear-gradient(bottom, white 85%, #eeeeee 99%);
    background: url('../img/select2.png') no-repeat 100% -22px, -ms-linear-gradient(top, #ffffff 85%, #eeeeee 99%);
    background: url('../img/select2.png') no-repeat 100% -22px, linear-gradient(top, #ffffff 85%, #eeeeee 99%);
    padding: 4px 20px 4px 5px;
    outline: 0;
    border: 1px solid #aaa;
    font-family: sans-serif;
    font-size: 1em;
    width:100%;
    margin:0;
    height:auto !important;
    min-height: 26px;
    -webkit-box-shadow: none;
    -moz-box-shadow: none;
    box-shadow: none;
    border-radius: 0;
    -moz-border-radius: 0;
    -webkit-border-radius: 0;
}

.select2-drop.select2-drop-above .select2-search input
{
    margin-top:4px;
}

.select2-search input.select2-active {
    background: #fff url('../img/spinner.gif') no-repeat 100%;
    background: url('../img/spinner.gif') no-repeat 100%, -webkit-gradient(linear, left bottom, left top, color-stop(0.85, white), color-stop(0.99, #eeeeee));
    background: url('../img/spinner.gif') no-repeat 100%, -webkit-linear-gradient(center bottom, white 85%, #eeeeee 99%);
    background: url('../img/spinner.gif') no-repeat 100%, -moz-linear-gradient(center bottom, white 85%, #eeeeee 99%);
    background: url('../img/spinner.gif') no-repeat 100%, -o-linear-gradient(bottom, white 85%, #eeeeee 99%);
    background: url('../img/spinner.gif') no-repeat 100%, -ms-linear-gradient(top, #ffffff 85%, #eeeeee 99%);
    background: url('../img/spinner.gif') no-repeat 100%, linear-gradient(top, #ffffff 85%, #eeeeee 99%);
}

.select2-container-active .select2-choice,
.select2-container-active .select2-choices {
    -webkit-box-shadow: 0 0 5px rgba(0,0,0,.3);
    -moz-box-shadow   : 0 0 5px rgba(0,0,0,.3);
    -o-box-shadow     : 0 0 5px rgba(0,0,0,.3);
    box-shadow        : 0 0 5px rgba(0,0,0,.3);
    border: 1px solid #5897fb;
    outline: none;
}

.select2-dropdown-open .select2-choice {
  border: 1px solid #aaa;
  border-bottom-color: transparent;
  -webkit-box-shadow: 0 1px 0 #fff inset;
  -moz-box-shadow   : 0 1px 0 #fff inset;
  -o-box-shadow     : 0 1px 0 #fff inset;
  box-shadow        : 0 1px 0 #fff inset;
  background-color: #eee;
  background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0, white), color-stop(0.5, #eeeeee));
  background-image: -webkit-linear-gradient(center bottom, white 0%, #eeeeee 50%);
  background-image: -moz-linear-gradient(center bottom, white 0%, #eeeeee 50%);
  background-image: -o-linear-gradient(bottom, white 0%, #eeeeee 50%);
  background-image: -ms-linear-gradient(top, #ffffff 0%,#eeeeee 50%);
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#eeeeee',GradientType=0 );
  background-image: linear-gradient(top, #ffffff 0%,#eeeeee 50%);
  -webkit-border-bottom-left-radius : 0;
  -webkit-border-bottom-right-radius: 0;
  -moz-border-radius-bottomleft : 0;
  -moz-border-radius-bottomright: 0;
  border-bottom-left-radius : 0;
  border-bottom-right-radius: 0;
}

.select2-dropdown-open .select2-choice div {
  background: transparent;
  border-left: none;
}
.select2-dropdown-open .select2-choice div b {
  background-position: -18px 1px;
}

/* results */
.select2-results {
  margin: 4px 4px 4px 0;
  padding: 0 0 0 4px;
  position: relative;
  overflow-x: hidden;
  overflow-y: auto;
  max-height: 200px;
}

.select2-results ul.select2-result-sub {
  margin: 0 0 0 0;
}

.select2-results ul.select2-result-sub > li .select2-result-label { padding-left: 20px }
.select2-results ul.select2-result-sub ul.select2-result-sub > li .select2-result-label { padding-left: 40px }
.select2-results ul.select2-result-sub ul.select2-result-sub ul.select2-result-sub > li .select2-result-label { padding-left: 60px }
.select2-results ul.select2-result-sub ul.select2-result-sub ul.select2-result-sub ul.select2-result-sub > li .select2-result-label { padding-left: 80px }
.select2-results ul.select2-result-sub ul.select2-result-sub ul.select2-result-sub ul.select2-result-sub ul.select2-result-sub > li .select2-result-label { padding-left: 100px }
.select2-results ul.select2-result-sub ul.select2-result-sub ul.select2-result-sub ul.select2-result-sub ul.select2-result-sub ul.select2-result-sub > li .select2-result-label { padding-left: 110px }
.select2-results ul.select2-result-sub ul.select2-result-sub ul.select2-result-sub ul.select2-result-sub ul.select2-result-sub ul.select2-result-sub ul.select2-result-sub > li .select2-result-label { padding-left: 120px }

.select2-results li {
  list-style: none;
  display: list-item;
}

.select2-results li.select2-result-with-children > .select2-result-label {
  font-weight: bold;
}

.select2-results .select2-result-label {
  padding: 3px 7px 4px;
  margin: 0;
  cursor: pointer;
}

.select2-results .select2-highlighted {
  background: #3875d7;
  color: #fff;
}
.select2-results li em {
  background: #feffde;
  font-style: normal;
}
.select2-results .select2-highlighted em {
  background: transparent;
}
.select2-results .select2-no-results {
  background: #f4f4f4;
  display: list-item;
}

.select2-results .select2-selection-limit {
  background: #f4f4f4;
  display: list-item;
}

/*
disabled look for already selected choices in the results dropdown
.select2-results .select2-disabled.select2-highlighted {
    color: #666;
    background: #f4f4f4;
    display: list-item;
    cursor: default;
}
.select2-results .select2-disabled {
  background: #f4f4f4;
  display: list-item;
  cursor: default;
}
*/
.select2-results .select2-disabled {
    display: none;
}

.select2-more-results.select2-active {
    background: #f4f4f4 url('../img/spinner.gif') no-repeat 100%;
}

.select2-more-results {
  background: #f4f4f4;
  display: list-item;
}

/* disabled styles */

.select2-container.select2-container-disabled .select2-choice {
    background-color: #f4f4f4;
    background-image: none;
    border: 1px solid #ddd;
    cursor: default;
}

.select2-container.select2-container-disabled .select2-choice div {
    background-color: #f4f4f4;
    background-image: none;
    border-left: 0;
}

/* multiselect */

.select2-container-multi .select2-choices {
    background-color: #fff;
      background-image: -webkit-gradient(linear, 0% 0%, 0% 100%, color-stop(1%, #eeeeee), color-stop(15%, #ffffff));
      background-image: -webkit-linear-gradient(top, #eeeeee 1%, #ffffff 15%);
      background-image: -moz-linear-gradient(top, #eeeeee 1%, #ffffff 15%);
      background-image: -o-linear-gradient(top, #eeeeee 1%, #ffffff 15%);
      background-image: -ms-linear-gradient(top, #eeeeee 1%, #ffffff 15%);
      background-image: linear-gradient(top, #eeeeee 1%, #ffffff 15%);
      border: 1px solid #ccc;
      margin: 0;
      padding: 0;
      cursor: text;
      overflow: hidden;
      height: auto !important;
      height: 1%;
      position: relative;
      border-radius: 4px 4px 4px 4px;
}

.select2-container-multi .select2-choices {
    min-height: 26px;
}

.select2-container-multi.select2-container-active .select2-choices {
    -webkit-box-shadow: 0 0 5px rgba(0,0,0,.3);
    -moz-box-shadow   : 0 0 5px rgba(0,0,0,.3);
    -o-box-shadow     : 0 0 5px rgba(0,0,0,.3);
    box-shadow        : 0 0 5px rgba(0,0,0,.3);
    border: 1px solid #5897fb;
    outline: none;
    border-radius: 0px 0px 0px 0px;
}
.select2-container-multi .select2-choices li {
  float: left;
  list-style: none;
}
.select2-container-multi .select2-choices .select2-search-field {
  white-space: nowrap;
  margin: 0;
  padding: 0;
}

.select2-container-multi .select2-choices .select2-search-field input {
  color: #666;
  background: transparent !important;
  font-family: sans-serif;
  font-size: 100%;
  height: 15px;
  padding: 5px;
  margin: 1px 0;
  outline: 0;
  border: 0;
  -webkit-box-shadow: none;
  -moz-box-shadow   : none;
  -o-box-shadow     : none;
  box-shadow        : none;
}

.select2-container-multi .select2-choices .select2-search-field input.select2-active {
    background: #fff url('../img/spinner.gif') no-repeat 100% !important;
}

.select2-default {
  color: #999 !important;
}

.select2-container-multi .select2-choices .select2-search-choice {
  -webkit-border-radius: 3px;
  -moz-border-radius   : 3px;
  border-radius        : 3px;
  -moz-background-clip   : padding;
  -webkit-background-clip: padding-box;
  background-clip        : padding-box;
  background-color: #e4e4e4;
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f4f4f4', endColorstr='#eeeeee', GradientType=0 );
  background-image: -webkit-gradient(linear, 0% 0%, 0% 100%, color-stop(20%, #f4f4f4), color-stop(50%, #f0f0f0), color-stop(52%, #e8e8e8), color-stop(100%, #eeeeee));
  background-image: -webkit-linear-gradient(top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%);
  background-image: -moz-linear-gradient(top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%);
  background-image: -o-linear-gradient(top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%);
  background-image: -ms-linear-gradient(top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%);
  background-image: linear-gradient(top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%);
  -webkit-box-shadow: 0 0 2px #ffffff inset, 0 1px 0 rgba(0,0,0,0.05);
  -moz-box-shadow   : 0 0 2px #ffffff inset, 0 1px 0 rgba(0,0,0,0.05);
  box-shadow        : 0 0 2px #ffffff inset, 0 1px 0 rgba(0,0,0,0.05);
  color: #333;
  border: 1px solid #aaaaaa;
  line-height: 13px;
  padding: 3px 5px 3px 18px;
  margin: 3px 0 0px 3px;
  position: relative;
  cursor: default;
}
.select2-container-multi .select2-choices .select2-search-choice span {
  cursor: default;
}
.select2-container-multi .select2-choices .select2-search-choice-focus {
  background: #d4d4d4;
}

.select2-search-choice-close {
  display: block;
  position: absolute;
  right: 3px;
  top: 4px;
  width: 12px;
  height: 13px;
  font-size: 1px;
  background: url('../img/select2.png') right top no-repeat;
  outline: none;
}

.select2-container-multi .select2-search-choice-close {
  left: 3px;
}

.select2-container-multi .select2-choices .select2-search-choice .select2-search-choice-close:hover {
  background-position: right -11px;
}
.select2-container-multi .select2-choices .select2-search-choice-focus .select2-search-choice-close {
  background-position: right -11px;
}

/* disabled styles */

.select2-container-multi.select2-container-disabled .select2-choices{
    background-color: #f4f4f4;
    background-image: none;
    border: 1px solid #ddd;
    cursor: default;
}

.select2-container-multi.select2-container-disabled .select2-choices .select2-search-choice {
    background-image: none;
    background-color: #f4f4f4;
    border: 1px solid #ddd;
    padding: 3px 5px 3px 5px;
}

.select2-container-multi.select2-container-disabled .select2-choices .select2-search-choice .select2-search-choice-close {
    display: none;
}
/* end multiselect */

.select2-result-selectable .select2-match,
.select2-result-unselectable .select2-result-selectable .select2-match { text-decoration: underline; }
.select2-result-unselectable .select2-match { text-decoration: none; }

.select2-offscreen { position: absolute; left: -10000px; }


text:
var iterator = new Intl.v8BreakIterator(['en']);

var textToSegment = 'Jack and Jill, went over hill, and got lost. Alert!';
iterator.adoptText(textToSegment);

var slices = [];
var types = [];
var pos = iterator.first();
while (pos !== -1) {
  var nextPos = iterator.next();
  if (nextPos === -1) break;

  slices.push(textToSegment.slice(pos, nextPos));
  types.push(iterator.breakType());

  pos = nextPos;
}

assertEquals('Jack', slices[0]);
assertEquals(' ', slices[1]);
assertEquals('and', slices[2]);
assertEquals(' ', slices[3]);
assertEquals('Jill', slices[4]);
assertEquals(',', slices[5]);
assertEquals('!', slices[slices.length - 1]);

assertEquals('letter', types[0]);
assertEquals('none', types[1]);
assertEquals('letter', types[2]);
assertEquals('none', types[3]);
assertEquals('letter', types[4]);
assertEquals('none', types[types.length - 1]);


text:
<!doctype html>

    <meta charset="utf-8" />
    <link rel="stylesheet" type="text/css" href="../../../../support/github-web/physcomp.css" />
    <title>Exercise: Pure Data Melody</title>

Exercise: Pure Data Melody

Objective

Use Pure Data to play a simple melody.

The melody is represented as a sequence of notes, stored in a table as integers between 0-127 (this range happens to be the standard representation of "pitch" in the MIDI protocol.

The procedure for exploring this exercise applies to all exercises in 1.c.iii. Each exercise has an associated Pure Data patch, in which you will find step by step instructions. Follow the steps; get the patch working; and begin making changes, variations, additions.

Consider the following important concepts, implications and questions of this example:

A very simplistic representation of a "melody" is a series of notes played in a particular order. What sonic and/or musical considerations are left out if we only consider pitches in a melody?

A metro object is a fundamental timing object in Pure Data. It
	can generate a regular beat which can in turn trigger
	other events; in this patch, the triggered event are changes in
	the frequency of an oscillator
	(the osc~ object). The metro object can also be used
	to trigger events in the real world (motors, servos, lights, etc.) when
	a microcontroller is connected to Pure Data.

Building simple counters in Pure Data is easy and extremely useful. Look in the intro-to-counters abstraction to see more examples.

Steps and observations

Open the 1.c.iii.1_music-pitch.pd patch in Pd-extended.

Follow the instructions in the patch.

Comments

For a challenge, try creating a more exciting rhythmic pattern.

Other Files

1.c.iii.1_music-pitch.pd

intro-to-counters.pd


text:
/*
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package com.ocs.dynamo.domain;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;

import com.ocs.dynamo.domain.model.CascadeMode;
import com.ocs.dynamo.domain.model.annotation.Attribute;
import com.ocs.dynamo.domain.model.annotation.Cascade;
import com.ocs.dynamo.domain.model.annotation.SearchMode;

@Entity
public class CascadeEntity extends AbstractEntity<Integer> {

    private static final long serialVersionUID = 9196343420168206197L;

    @Id
    @GeneratedValue
    private Integer id;

    @ManyToOne
    @Attribute(cascade = @Cascade(cascadeTo = "testEntity2", filterPath = "testEntity", mode = CascadeMode.BOTH), searchable = SearchMode.ALWAYS)
    private TestEntity testEntity;

    @ManyToOne
    @Attribute(searchable = SearchMode.ALWAYS)
    private TestEntity2 testEntity2;

    @Override
    public Integer getId() {
        return id;
    }

    @Override
    public void setId(Integer id) {
        this.id = id;
    }

    public TestEntity getTestEntity() {
        return testEntity;
    }

    public void setTestEntity(TestEntity testEntity) {
        this.testEntity = testEntity;
    }

    public TestEntity2 getTestEntity2() {
        return testEntity2;
    }

    public void setTestEntity2(TestEntity2 testEntity2) {
        this.testEntity2 = testEntity2;
    }

}


text:
<!doctype html>

  <meta charset="UTF-8">
  <title>Example - example-filter-decorator-production</title>

Initial Commit default to short date: {{ genesis | date }}

ng-conf 2016 default short date: {{ ngConf | date }}

ng-conf 2016 with full date format: {{ ngConf | date:'fullDate' }}


text:
import ApplicationAdapter from './application';

export default ApplicationAdapter.extend({
  urlForFindRecord(id, typeKey) {
    // Github no longer lets you query for another user by id
    // requires you to use user's login name
    // but I never was actually doing so
    // so this code now assumes that always querying for current user
    // Gaurav - 8/8/20

    let url = this._buildURL(typeKey);
    return url.substring(0, url.length-1);
  }
});


text:
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="scrollbar-style.html">
<link rel="import" href="tensorboard-color.html">

<dom-module id="tf-dashboard-layout">
  <template>

      <content select=".sidebar"></content>

      <content select=".center"></content>

  </template>

</dom-module>


text:
<?xml version="1.0" encoding="UTF-8"?>
<ti:app xmlns:ti="http://ti.appcelerator.org">
    <deployment-targets>
        <target device="mobileweb">true</target>
        <target device="iphone">true</target>
        <target device="ipad">true</target>
        <target device="android">true</target>
        <target device="blackberry">false</target>
    </deployment-targets>
    <sdk-version>3.0.0.GA</sdk-version>
    <id>com.appcelerator.todolistalloykinvey</id>
    <name>TodoListAlloyKinvey</name>
    <version>1.0</version>
    <publisher>aaronksaunders</publisher>
    <url>http://</url>
    <description>not specified</description>
    <copyright>2013 by aaronksaunders</copyright>
    <icon>appicon.png</icon>
    <persistent-wifi>false</persistent-wifi>
    <prerendered-icon>false</prerendered-icon>
    <statusbar-style>default</statusbar-style>
    <statusbar-hidden>false</statusbar-hidden>
    <fullscreen>false</fullscreen>
    <navbar-hidden>false</navbar-hidden>
    <analytics>false</analytics>
    <guid>f1195a0a-3007-4dc7-a284-7365e50d626d</guid>
    <property name="ti.ui.defaultunit">system</property>
    <iphone>
        <orientations device="iphone">
            <orientation>Ti.UI.PORTRAIT</orientation>
        </orientations>
        <orientations device="ipad">
            <orientation>Ti.UI.PORTRAIT</orientation>
            <orientation>Ti.UI.UPSIDE_PORTRAIT</orientation>
            <orientation>Ti.UI.LANDSCAPE_LEFT</orientation>
            <orientation>Ti.UI.LANDSCAPE_RIGHT</orientation>
        </orientations>
    </iphone>
    <android xmlns:android="http://schemas.android.com/apk/res/android"/>
    <mobileweb>
        <precache/>
        <splash>
            <enabled>true</enabled>
            <inline-css-images>true</inline-css-images>
        </splash>
        <theme>default</theme>
    </mobileweb>
    <modules>
        <module platform="android" version="1.0">ti.physicalSizeCategory</module>
    </modules>
    <plugins>
        <plugin version="1.0">ti.alloy</plugin>
    </plugins>
</ti:app>


text:
Joshfire.define(['joshfire/uielements/video', 'joshfire/class', 'joshfire/vendor/jquery', 'joshfire/vendor/underscore', 'joshfire/vendor/mediaelement'], function(Video, Class, $, _, mejs) {

  /**
  * @class MediaElementJs video backend
  * @name adapters_browser_uielements_video.mediaelement
  * @augments uielements_video
  */
  return Class(Video, /** @lends adapters_browser_uielements_video.mediaelement.prototype */ {

    /**
    * init video
    * @function
    *
    */
    init: function() {

      // Event listeners
      this.listeners = {};

      // Should have an HTML5 <video>-like API
      this.player = false;

      // Status of the video
      this.videoStatus = false;

      // Current video duration
      this.videoDuration = 0;

      var self = this;
      this.app.subscribe('input', function(ev, data) {
        if (self.isDefaultPlayer) {
          self.handleInputEvent(data);
        }
      });

      this.subscribe('input', function(ev, data) {
        self.handleInputEvent(data);
      });

      // Memory leak fixes
      $(window).bind('unload', function() {
        try {
          self.remove();
        } catch (e) {}
      });

      // tweak default configuration of the mediaelement (https://github.com/johndyer/mediaelement/)
      this.MediaElementDefaults = _.clone(mejs.MediaElementDefaults);

      if (typeof this.options['mediaElementDefaultsPluginPath'] === 'string')
        this.MediaElementDefaults.pluginPath = this.options['mediaElementDefaultsPluginPath'];
      else
        this.MediaElementDefaults.pluginPath = '/public/swf/';
      this.MediaElementDefaults.plugins = ['flash'];

      this.__super();

    },

    /**
    * Handle inputs: play, pause, next, seek,..
    * @function
    * @param {Object} data
    */
    handleInputEvent: function(data) {
      //console.log('handleInputEvent', JSON.stringify(data));
      if (data[0] == 'play') {
        this.resume();
      } else if (data[0] == 'stop') {
        this.stop();
      } else if (data[0] == 'pause') {
        this.pause();
      } else if (data[0] == 'next') {
        this.playNext();
      } else if (data[0] == 'prev') {
        this.playPrev();
      } else if (data[0] == 'seekTo') {
        this.setCurrentTime(data[1]);
      } else if (data[0] == 'seekBy') {
        this.setCurrentTime(this.getCurrentTime() + data[1]);
      }
    },

    /**
    * publish the error event with an error message in a span. Default messages can be overwritten
    * @param {DOMElement} [error.srcElement] the video element where the error code resides. Will use this.errorCode if not defined.
    * @see options.errorMessages.aborted
    * @see options.errorMessages.network
    * @see options.errorMessages.decode
    * @see options.errorMessages.notsupported
    * @see options.errorMessages.other
    * @see message
    * @see errorCode
    */
    error: function(ev) {
      this.errorCode = this.errorCode != 0 ? this.errorCode : ev.srcElement.error.code;
      var errorMessages = this.options.errorMessages || {};

      switch (this.errorCode) {
        case 1:
          //MEDIA_ERR_ABORTED
          this.message = '' + (errorMessages.aborted || 'The loading of the video was aborted') + '';
          break;
        case 2:
          //MEDIA_ERR_NETWORK:
          this.message = '' + (errorMessages.network || 'A network problem is preventing the video from loading') + '';

          break;
        case 3:
          //MEDIA_ERR_DECODE
          this.message = '' + (errorMessages.decode || 'The video format is not recognized') + '';
          break;
        case 4:
          //MEDIA_ERR_SRC_NOT_SUPPORTED
          //TODO check this error message
          this.message = '' + (errorMessages.notsupported || "The video couldn't be loaded because of a server issue") + '';
          break;
        default:
          this.message = '' + (errorMessages.other || 'Unknown error') + '';
          break;
      }
      this.publish('error', { message: this.message, number: this.errorCode, origin: 'adapters/browser/uielements/video.mediaelement' });
    },

    /**
    * Register listeners
    * @function
    * @param {Object} target
    * @param {string} eventName
    * @param {Object} listener
    */
    startListening: function(target, eventName, listener) {
      this.listeners[eventName] = listener;
      target.addEventListener(eventName, listener);
    },

    /**
    * Remove listeners
    * @function
    * @param {Object} target
    */
    stopListeningAll: function(target) {

      $.each(this.listeners, function(i, o) {
        try {
          target.removeEventListener(i, o);
        } catch (e) {}
      });
    },

    /**
    * @ignore
    * @function refresh
    *
    */
    refresh: function() {

    },

    /**
    * Set status
    * @function
    * @param {String} status
    */
    setVideoStatus: function(status) {
      this.videoStatus = status;
      this.publish(status);
    },

    /**
    * Play video
    * @function
    * @param {Object} options Hash of options.
    * @param {String} options.url URL of the video.
    * @param {String} [options.mime] mime type (video/mp4).
    * @param {String} [options.image] thumbnail
    * @param {Function} [options.cleanup] cleaning function.
    * @param {bool} [options.forceAspectRatio] adapt player to video stream or fixed size ?
    * @param {int} [options.width] If forceAspectRatio is true,.
    * @param {bool} [options.noAutoPlay=false].
    * @param {String} [options.pluginPath=../joshfire/adapters/browser/uielements/] where is the flashmediaelement.swf file.
    */
    playWithStaticUrl: function(options) {
      this.playData = options;
      if (options.url === undefined) {
        return this.error(-1);
      }

      var isFLV = options.url.match(/\.flv$/) || options.mime == 'video/flv';

      //try to reuse existing instances because of http://code.google.com/p/chromium/issues/detail?id=68010
      if (this.player && $('#' + this.htmlId + '_video').size()) {

        this.stopListeningAll(this.player);

        if (this.options.cleanup) {
          this.options.cleanup(this);
        }

        try {
          this.player.stop();
        } catch (e) {}

        $('#' + this.htmlId + '_video').attr('src', options.url);
        if (options.image) $('#' + this.htmlId + '_video').attr('poster', options.image);
        $('#' + this.htmlId + '_video').attr('autoplay', isFLV ? false : true);
        $('#' + this.htmlId + '_video').attr('autobuffer', isFLV ? false : true);
        $('#' + this.htmlId + '_video').attr('preload', isFLV ? false : true);
        $('#' + this.htmlId + '_video').css({
          'display': isFLV ? 'none' : 'block'
        });

        $('#' + this.htmlId + ' .me-plugin').remove();

      } else {

        if (isFLV) {
          // No autoplay here because <video src='xxx.flv' autoplay> will start playing on a GoogleTV
          // even if video.canPlayType("video/flv")==""
          $('#' + this.htmlId)[0].innerHTML = "<video id='" + this.htmlId + "_video' src='" + options.url + "' " + (options.image ? "poster='" + options.image + "'" : '') + ' />';
        } else {
          $('#' + this.htmlId)[0].innerHTML = "<video id='" + this.htmlId + "_video' src='" + options.url + "' " + (options.noautoplay ? '' : "autoplay='true'") + ' autobuffer preload ' + (options.image ? "poster='" + options.image + "'" : '') + ' />';
        }
      }

      //(typeof this.options['width'] !== 'undefined') ?

      $('#' + this.htmlId + '_video').css({
        //'width'  : (typeof this.options['width'] !== 'undefined') ? this.options['width'] : '100%',
        //'height' : (typeof this.options['height'] !== 'undefined') ? this.options['height'] : '100%',
        //'width': $('#' + this.htmlId).width() + 'px',
        //'height': $('#' + this.htmlId).height() + 'px',
        'z-index': 0
      });

      if (this.options.forceAspectRatio) {
        if (!this.options.width) {
          $('#' + this.htmlId + '_video').css({
            'height': ($('#' + this.htmlId + '_video').width() / this.options.forceAspectRatio) + 'px'
          });
        }
      }

      var that = this;

      //Pull this in MediaElement later
      /**
      * Pull this in MediaElement later
      * @function
      * @param {Object}
      * @param {Object}
      */
      mejs.HtmlMediaElementShim.myCreate = function(el, o) {
        //console.warn('myCreate');
        // that.MediaElementDefaults
        var options = mejs.MediaElementDefaults = that.MediaElementDefaults,
            htmlMediaElement = (typeof(el) == 'string') ? document.getElementById(el) : el,
            isVideo = (htmlMediaElement.tagName.toLowerCase() == 'video'),
            supportsMediaTag = (typeof(htmlMediaElement.canPlayType) != 'undefined'),
            playback = {
              method: '',
              url: ''
            },
            poster = htmlMediaElement.getAttribute('poster'),
            autoplay = htmlMediaElement.getAttribute('autoplay'),
            preload = htmlMediaElement.getAttribute('preload'),
            prop;

        // extend options
        for (prop in o) {
          options[prop] = o[prop];
        }

        // check for real poster
        poster = (typeof poster == 'undefined' || poster === null) ? '' : poster;
        preload = true;
        autoplay = !that.playData.noautoplay;

        isVideo = true;//false;

        // test for HTML5 and plugin capabilities
        playback = this.determinePlayback(htmlMediaElement, options, isVideo, supportsMediaTag);
        playback.url = htmlMediaElement.getAttribute('src');

        //console.log("AUTO",options["noautoplay"],autoplay,playback,$("#" + this.htmlId)[0].innerHTML);
        //console.log(playback);
        if (playback.method == 'native') {
          // add methods to native HTMLMediaElement
          this.updateNative(htmlMediaElement, options, autoplay, preload, playback);
        } else if (playback.method !== '') {
          // create plugin to mimic HTMLMediaElement
          this.createPlugin(htmlMediaElement, options, isVideo, playback.method, (playback.url !== null) ? mejs.Utility.absolutizeUrl(playback.url).replace('&', '%26') : '', poster, autoplay, preload);
        } else {
          // boo, no HTML5, no Flash, no Silverlight.
          this.createErrorMessage(htmlMediaElement, options, (playback.url !== null) ? mejs.Utility.absolutizeUrl(playback.url) : '', poster);
        }
      };

      mejs.HtmlMediaElementShim.myCreate($('#' + this.htmlId + '_video')[0], {
        //pluginPath: '/swf/',
        videoWidth: $('#' + this.htmlId + '_video').width(),
        videoHeight: $('#' + this.htmlId + '_video').height(),
        pluginWidth: $('#' + this.htmlId + '_video').width(),
        pluginHeight: $('#' + this.htmlId + '_video').height(),

        enablePluginSmoothing: true,

        type: options.mime,
        //mode:"shim",
        //enablePluginDebug:true,
        /**
        * @function
        * @param {String} error
        */
        error: function(e) {
          that.error(e);
        },
        /**
        * @function
        * @param {Object} me
        * @param {Object} domNode
        */
        success: function(me, domNode) {

          that.player = me;

          that.publish('success');

          that.startListening(me, 'progress', function(ev) {

            /*if(me.duration != that.videoDuration)
            that.videoDuration = me.duration;
            */
            var progressTime = 0;
            if (me.bufferedBytes && me.bytesTotal > 0) {
              progressTime = (me.bufferedBytes / me.bytesTotal) * me.duration;
            } else if (me.loaded && me.total > 0) {
              progressTime = (me.loaded / me.total) * me.duration;
            } else if (me.buffered && me.buffered.end) {
              try {
                progressTime = me.buffered.end();
              } catch (e) {}
            }

            /*if(me.duration == that.videoDuration
            && progressTime == that.getCurrentTime())
            return;
            */
            that.publish('progress', [{
              'totalTime': me.duration,
              'bufferedTime': progressTime
            }]);
          });

          that.startListening(me, 'playing', function(ev) {
            that.setVideoStatus('playing');
          });

          that.startListening(me, 'timeupdate', function(ev) {
            that.videoDuration = me.duration;
            that.publish('timeupdate', [{
              'currentTime': me.currentTime,
              'totalTime': me.duration
            }]);
          });

          that.startListening(me, 'ended', function(ev) {
            that.setVideoStatus('stopped');
            that.publish('ended');
            that.playNext();
          });

          that.startListening(me, 'canplay', function(ev) {

            //todo test more
            if (options.position) {
              that.setCurrentTime(options.position);
            }

            if (!options.noautoplay && that.videoStatus != 'playing') {
              me.play();
              that.setVideoStatus('playing');
            }

          });

          that.startListening(me, 'error', function(ev) {
            //ignore errors about the gif img unloader
            if (ev.target.src.match(/\.gif$/)) {
              return;
            }
            that.setVideoStatus('stopped');
            that.error(ev);
          });

        }
      }
      );

      this.setVideoStatus('loading');

    },

    /**
    * pause a video
    * @function
    *
    */
    pause: function() {
      this.setVideoStatus('paused');
      if (this.player) this.player.pause();
    },

    /**
    * resume a video
    * @function
    *
    */
    resume: function() {
      this.setVideoStatus('playing');
      if (this.player) this.player.play();
    },

    /**
    * stop a video
    * @function
    *
    */
    stop: function() {
      this.setVideoStatus('stopped');
      if (this.player) this.player.stop();
    },

    /**
    * get current time
    * @function
    * @return {int}
    */
    getCurrentTime: function() {
      if (this.player) return this.player.currentTime;
      return 0;
    },

    /**
    * get video duration
    * @function
    * return {int}
    *
    */
    getTotalTime: function() {
      return this.videoDuration;
    },

    /**
    * @function
    * @param {int} seconds
    */
    setCurrentTime: function(seconds) {
      if (this.player) this.player.setCurrentTime(Math.max(0, seconds));
    },

    /**
    * @function
    *
    */
    remove: function() {
      this.playingPath = false;
      //if (typeof this.player != 'undefined')
      if (this.player) {
        try {
          //console.log('remove workflow: stopAll', this.id);
          this.stopListeningAll(this.player);
        } catch (e0) {}

        try {
          //console.log('remove workflow: pause', this.id);
          this.player.pause();

        } catch (e1) {}

        try {
          //console.log('remove workflow: stop', this.id);
          this.player.stop();
        } catch (e2) {}

        try {
          //console.log('remove workflow: stopped', this.id);
          this.setVideoStatus('stopped');
        } catch (e3) {}

        try {
          //console.log('remove workflow: src', this.id);
          //this.player.src ='/images/mediaelement/empty.mp4'; // setSrc('/images/mediaelement/empty.mp4'); //data:image/gif;base64,R0lGODlhAQABAJH/AP///wAAAP///wAAACH/C0FET0JFOklSMS4wAt7tACH5BAEAAAIALAAAAAABAAEAAAICVAEAOw==');
          this.player.setSrc('/images/mediaelement/spacer.gif');
          //console.log('remove workflow: load', this.id);
          this.player.load();
        } catch (e4) {}

        try {
          //console.log('remove workflow: restop', this.id);
          this.player.stop();
        } catch (e5) {}

        try {
          //console.log('remove workflow: remove', this.id);
          $(this.player).remove();
        } catch (e6) {}

        try {
          //console.log('remove workflow: delete', this.id);
          delete this.player;
        } catch (e7) {}

      }

      //console.log("REMOVED VIDEO", this.id);
      //$("#"+this.htmlId).html('');
    },

    /**
    * @function
    * @return {String} html.
    */
    getHtml: function() {
      return "

"; //"

";
    }

  });

});