text:
import sys
# get_ipython().magic('matplotlib inline')
import random
# import matplotlib.pyplot as plt
from dgraph import standardize
from lesson1 import averageClustering as ac
from dgraph import countEdges
from lesson4 import topk
from lesson4 import betweenness
from lesson5 import eigenvector_centrality as ec
from mod_genws import GenWSGridGraph
from dgraph import Page_Rank as pr
from dgraph import fill_incoming as fi
from dgraph import Independent_Cascade as ic
from dgraph import toUndirect as und

# In[2]:

def independent_cascade(graph, seed, centrality):
    adopters, haters, steps = ic(g, seed)
    # print 'Independent Cascade Model: TOP %d %s' % (len(seed), centrality)
    # print '\tFinal Adopters:\t', len(adopters)
    # print '\tFinal Haters:\t', len(haters)
    # print '\t# Iterations:\t', steps
    return len(adopters)

# In[5]:
print '# Cascade Expansion on Generalized Watts-Strogatz Graphs'
NODES = 7056
edges = random.randint(75000, 125000)
radius = 2
weak_ties = [i*5 for i in xrange(0, 3)]

# ##Create a generalized Watts-Strogatz direct graph on grid with clustering exponent *q* = 2

# In[6]:

g = GenWSGridGraph(NODES, edges, radius, weak_ties)
print '# Edges %d\tAverage Clustering = %f' % (countEdges(g)*2,ac(und(g)))
fi(g) # Fill incoming edges dictionary

# ## Execute centrality measures

# In[12]:

print '# Page Rank execution...'
pagerank, iterations, err = pr(g, alpha=1.0e-5, eps=1.0e-3)
print '#',iterations, ' iterations. Error:', err
top_pr = [a for a,b in topk(pagerank, NODES)]

# In[13]:

print '# Eigenvector Centrality...',
ecscores, _ = ec(g)
top_eigenc = [a for a, b in topk(ecscores, NODES)]
print '# Done'

# In[14]:

print '# Betweennes centrality...',
bet = betweenness(g)
top_bet = [a for a, b in topk(bet, NODES)]
print '# Done'

# ## Execute Independent Cascade Model

seed = [i for i in xrange(200, 7001, 200)]

print '# Page Rank\tEigenvector\tBetweenness'
i = 0
while True:
    max_pr_ad = independent_cascade(g, top_pr[:seed[i]], 'Page Rank')
    max_eigenc_ad = independent_cascade(g, top_eigenc[:seed[i]], 'Eigenvector')
    max_bet_ad = independent_cascade(g, top_bet[:seed[i]], 'Betweenness')

    # In[28]:
    print '%d %d\t%d %d\t%d %d' % (seed[i], max_pr_ad, seed[i], max_eigenc_ad, seed[i], max_bet_ad)
    sys.stdout.flush()

    if i == len(seed)-1 or max_pr_ad >= NODES or max_eigenc_ad >= NODES or max_bet_ad >= NODES:
        break

    i += 1

redpajama_set_name: RedPajamaGithub


text:
title: "DSC 290: Algorithmic Auditing Lab (Fall 2021)"
collection: teaching
teaching_type: "Course"
permalink: /teaching/DSC-290-algorithmic-auditing-fa21/
institution: "UC San Diego, HDSI"
date: 2021-09-01
excerpt: "Graduate-level course on auditing algorithms for bias, fairness, etc."
---

See https://auditlab.stuartgeiger.com


text:
class MiniWikiGenerator < Rails::Generator::Base
  def manifest
    record do |m|
      # add the migration
      m.migration_template 'add_mini_wiki.rb', 'db/migrate', { :migration_file_name => 'add_mini_wiki' }

      # layout
      m.directory "app/views/layouts"
      m.file 'layouts/mini_wiki.html.erb', 'app/views/layouts/mini_wiki.html.erb'

      # css
      m.directory "public/stylesheets"
      m.file 'css/mini_wiki.css', 'public/stylesheets/mini_wiki.css'

      # config
      m.directory "config"
      m.file 'config/mini_wiki.yml', 'config/mini_wiki.yml'

      # lib
      m.directory "lib"
      m.file 'lib/mini_wiki_override.rb', 'lib/mini_wiki_override.rb'

      # add route
      m.mini_wiki_route
    end
  end
end


text:
body {color: #000; font-family: 'Terminal Dosis', sans-serif;}
body:not([id="index"]) {background: url(pixel-grid.png); }
a {color: #000; background-color: hsla(0, 0%, 100%, 0.5); padding: 0 0.2em 0 0.2em; border-radius: 2px; text-decoration: none;}
article {background: hsla(209, 62%, 51%, 0.8); padding: 10px; border-radius: 10px; overflow: hidden;}
h1 {font-size: 1.5em; font-weight: bold; background-color: hsla(0, 0%, 100%, 0.7); border-radius: 4px; padding: 0 5px 5px 5px; clear:left;}
p {font-size: 1.2em;}
ul {margin-left: 0; padding-left: 0; list-style: none}
li {font-size: 1em; margin-bottom: 0.2em;}
pre, output {font-size: 1em; font-family: monospace; white-space: pre-wrap; display: block;}
pre {font-weight: bold;}
h1, p, pre, output {margin: 0 0 10px 0;}
.fold {border-radius: 10px 250px 10px 10px;}
.fold #top {width: 180px;}


text:
<?xml version="1.0" encoding="utf-8"?>
<project>
	<!-- NMML reference: https://gist.github.com/1763850 -->

	<!-- metadata, make sure 'package' is at least 3 segments (ie. com.mycompany.myproject) -->
	<meta title="MAN-Haxe" package="MANHaxe" version="1.0.0" company="Gamepopper" />

	<!-- output -->
	<app main="Main" file="MANHaxe" path="bin" />

	<window background="#FFFFFF" fps="60" />
	<window width="800" height="800" unless="mobile" />
	<window orientation="landscape" vsync="false" antialiasing="0" if="cpp" />

	<!-- classpath, haxe libs -->
	<source path="sample" />
	<haxelib name="openfl" />

	<!-- optimize output
	<haxeflag name="-dce full" /> -->

</project>


text:
import { Component, OnInit } from '@angular/core';
import { db, model } from 'baqend';

@Component({
  selector: 'app-chats',
  templateUrl: './chats.component.html',
  styleUrls: ['./chats.component.scss']
})
export class ChatsComponent implements OnInit {

  public messages: Array<model.Message>;

  constructor() {}

  getImageUrl(message) {
    return new db.File(message.face).url;
  }

  ngOnInit() {
    db.Message
      .find()
      .resultList()
      .then(messages => this.messages = messages);
  }

}


text:
package freemind.view.mindmapview;

import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.MalformedURLException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.logging.Logger;

import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.SwingConstants;
import javax.swing.ToolTipManager;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeNode;

import freemind.controller.Controller;
import freemind.main.FreeMind;
import freemind.main.FreeMindMain;
import freemind.main.HtmlTools;
import freemind.main.Resources;
import freemind.main.Tools;
import freemind.modes.MindIcon;
import freemind.modes.MindMapCloud;
import freemind.modes.MindMapNode;
import freemind.modes.ModeController;
import freemind.modes.NodeAdapter;
import freemind.preferences.FreemindPropertyListener;
import freemind.view.mindmapview.attributeview.AttributeView;

/**
 * This class represents a single Node of a MindMap (in analogy to
 * TreeCellRenderer).
 */
public class NodeView extends JComponent implements TreeModelListener {
	public void setFocusCycleRoot(boolean pFocusCycleRoot) {
		// FIXME: On purpose removed. test this!
		// super.setFocusCycleRoot(pFocusCycleRoot);
	}

	static private int FOLDING_SYMBOL_WIDTH = -1;

	protected MindMapNode model;
	protected MapView map;
	private MainView mainView;
	private AttributeView attributeView;
	protected final static Color dragColor = Color.lightGray; // the Color of
																// appearing
																// GradientBox
																// on
																// drag over
	private boolean left = true; // is the node left of root?
	private boolean isLong = false;

	public final static int DRAGGED_OVER_NO = 0;
	public final static int DRAGGED_OVER_SON = 1;
	public final static int DRAGGED_OVER_SIBLING = 2;
	/** For RootNodeView. */
	public final static int DRAGGED_OVER_SON_LEFT = 3;

	final static int ALIGN_BOTTOM = -1;
	final static int ALIGN_CENTER = 0;
	final static int ALIGN_TOP = 1;

	final private static Point zeroPoint = new Point(0, 0);
	private static Logger logger;
	private static FreemindPropertyListener sListener;
	//
	// Constructors
	//

	private Object viewDeletionEvent;
	private int maxToolTipWidth;
	private NodeView preferredChild;
	private JComponent contentPane;
	protected NodeMotionListenerView motionListenerView;

	static final int SPACE_AROUND = 50;

	private NodeFoldingComponent mFoldingListener;

	protected NodeView(MindMapNode model, int position, MapView map,
			Container parent) {
		if (logger == null) {
			logger = map.getController().getFrame()
					.getLogger(this.getClass().getName());
		}
		if(sListener == null){
			sListener = new FreemindPropertyListener() {

				public void propertyChanged(String pPropertyName,
						String pNewValue, String pOldValue) {
					if (Tools.safeEquals(pPropertyName,
							FreeMind.TOOLTIP_DISPLAY_TIME)) {
						// control tooltip times:
						ToolTipManager.sharedInstance().setDismissDelay(
								Resources.getInstance().getIntProperty(
										FreeMind.TOOLTIP_DISPLAY_TIME, 4000));
					}
				}
			};
			Controller.addPropertyChangeListenerAndPropagate(sListener);
		}

		setFocusCycleRoot(true);

		this.model = model;
		this.map = map;
		final TreeNode parentNode = model.getParent();
		final int index = parentNode == null ? 0 : parentNode.getIndex(model);
		createAttributeView();

		parent.add(this, index);

		addFoldingListener();
	}

	protected void addFoldingListener() {
		if(mFoldingListener == null && getModel().hasVisibleChilds() && !getModel().isRoot()) {
			mFoldingListener = new NodeFoldingComponent(this);
			add(mFoldingListener, getComponentCount()-1);

			mFoldingListener.addActionListener(new ActionListener() {

				public void actionPerformed(ActionEvent pE) {
					getModeController().setFolded(getModel(), !getModel().isFolded());
				}
			});
		}
	}

	protected void removeFoldingListener() {
		if(mFoldingListener != null) {
			mFoldingListener.dispose();
			remove(mFoldingListener);
			mFoldingListener = null;
		}
	}

	public void propertyChanged(String pPropertyName, String pNewValue,
			String pOldValue) {
	}

	void setMainView(MainView newMainView) {
		if (mainView != null) {
			final Container c = mainView.getParent();
			int i;
			for (i = c.getComponentCount() - 1; i >= 0
					&& mainView != c.getComponent(i); i--) {
				// left blank on purpose
			}
			c.remove(i);
			ToolTipManager.sharedInstance().unregisterComponent(mainView);
			mainView.removeMouseListener(this.map.getNodeMouseMotionListener());
			mainView.removeMouseMotionListener(this.map
					.getNodeMouseMotionListener());
			c.add(newMainView, i);
		} else {
			add(newMainView);
		}
		this.mainView = newMainView;
		ToolTipManager.sharedInstance().registerComponent(mainView);
		mainView.addMouseListener(this.map.getNodeMouseMotionListener());
		mainView.addMouseMotionListener(this.map.getNodeMouseMotionListener());
		addDragListener(map.getNodeDragListener());
		addDropListener(map.getNodeDropListener());
		if (!model.isRoot() && "true".equals(map.getController().getProperty(FreeMindMain.ENABLE_NODE_MOVEMENT))) {
			motionListenerView = new NodeMotionListenerView(this);
			add(motionListenerView);
		}

	}

	protected void removeFromMap() {
		setFocusCycleRoot(false);
		getParent().remove(this);
		if (motionListenerView != null) {
			remove(motionListenerView);
			motionListenerView = null;
		}
		removeFoldingListener();
		ToolTipManager.sharedInstance().unregisterComponent(mainView);
	}

	void addDragListener(DragGestureListener dgl) {
		if (dgl == null)
			return;
		DragSource dragSource = DragSource.getDefaultDragSource();
		dragSource.createDefaultDragGestureRecognizer(getMainView(),
				DnDConstants.ACTION_COPY | DnDConstants.ACTION_MOVE
						| DnDConstants.ACTION_LINK, dgl);
	}

	void addDropListener(DropTargetListener dtl) {
		if (dtl == null)
			return;
		DropTarget dropTarget = new DropTarget(getMainView(), dtl);
		dropTarget.setActive(true);
	}

	public boolean isRoot() {
		return getModel().isRoot();
	}

	public boolean getIsLong() {
		return isLong;
	}

	/* fc, 25.1.2004: Refactoring necessary: should call the model. */
	public boolean isSiblingOf(NodeView myNodeView) {
		return getParentView() == myNodeView.getParentView();
	}

	/* fc, 25.1.2004: Refactoring necessary: should call the model. */
	public boolean isChildOf(NodeView myNodeView) {
		return getParentView() == myNodeView;
	}

	/* fc, 25.1.2004: Refactoring necessary: should call the model. */
	public boolean isParentOf(NodeView myNodeView) {
		return (this == myNodeView.getParentView());
	}

	public MindMapNode getModel() {
		return model;
	}

	/**
	 * Returns the coordinates occupied by the node and its children as a vector
	 * of four point per node.
	 */
	public void getCoordinates(LinkedList inList) {
		getCoordinates(inList, 0, false, 0, 0);
	}

	private void getCoordinates(LinkedList inList,
			int additionalDistanceForConvexHull, boolean byChildren,
			int transX, int transY) {
		if (!isVisible())
			return;

		if (isContentVisible()) {
			MindMapCloud cloud = getModel().getCloud();

			// consider existing clouds of children
			if (byChildren && cloud != null) {
				additionalDistanceForConvexHull += CloudView
						.getAdditionalHeigth(cloud, this) / 5;
			}
			final int x = transX + getContent().getX() - getDeltaX();
			final int y = transY + getContent().getY() - getDeltaY();
			final int width = getMainViewWidthWithFoldingMark();
			int heightWithFoldingMark = getMainViewHeightWithFoldingMark();
			final int height = Math.max(heightWithFoldingMark, getContent()
					.getHeight());
			inList.addLast(new Point(-additionalDistanceForConvexHull + x,
					-additionalDistanceForConvexHull + y));
			inList.addLast(new Point(-additionalDistanceForConvexHull + x,
					additionalDistanceForConvexHull + y + height));
			inList.addLast(new Point(additionalDistanceForConvexHull + x
					+ width, additionalDistanceForConvexHull + y + height));
			inList.addLast(new Point(additionalDistanceForConvexHull + x
					+ width, -additionalDistanceForConvexHull + y));
		}

		LinkedList childrenViews = getChildrenViews();
		ListIterator children_it = childrenViews.listIterator();
		while (children_it.hasNext()) {
			NodeView child = (NodeView) children_it.next();
			child.getCoordinates(inList, additionalDistanceForConvexHull, true,
					transX + child.getX(), transY + child.getY());
		}
	}

	/**
     */
	public void setText(String string) {
		mainView.setText(string);
	}

	/**
     */
	public String getText() {
		return mainView.getText();
	}

	protected int getMainViewWidthWithFoldingMark() {
		return mainView.getMainViewWidthWithFoldingMark();
	}

	/** get height including folding symbol */
	protected int getMainViewHeightWithFoldingMark() {
		return mainView.getMainViewHeightWithFoldingMark();
	}

	/** get x coordinate including folding symbol */
	public int getDeltaX() {
		return mainView.getDeltaX();
	}

	/** get y coordinate including folding symbol */
	public int getDeltaY() {
		return mainView.getDeltaY();
	}

	public void requestFocus() {
		// delegate to mapview:
		getController().obtainFocusForSelected();
	}

	//
	// get/set methods
	//

	/**
	 * Calculates the tree height increment because of the clouds.
	 */
	public int getAdditionalCloudHeigth() {
		if (!isContentVisible()) {
			return 0;
		}

		MindMapCloud cloud = getModel().getCloud();
		if (cloud != null) {
			return CloudView.getAdditionalHeigth(cloud, this);
		} else {
			return 0;
		}
	}

	public boolean isSelected() {
		return (getMap().isSelected(this));
	}

	/** Is the node left of root? */
	public boolean isLeft() {
		return getModel().isLeft();
	}

	protected void setModel(MindMapNode model) {
		this.model = model;
	}

	public MapView getMap() {
		return map;
	}

	protected Controller getController() {
		return map.getController();
	}

	protected ModeController getModeController() {
		return getMap().getModel().getModeController();
	}

	protected FreeMindMain getFrame() {
		return getController().getFrame();
	}

	boolean isParentHidden() {
		final Container parent = getParent();
		if (!(parent instanceof NodeView))
			return false;
		NodeView parentView = (NodeView) parent;
		return !parentView.isContentVisible();
	}

	public NodeView getParentView() {
		final Container parent = getParent();
		if (parent instanceof NodeView)
			return (NodeView) parent;
		return null;
	}

	public NodeView getVisibleParentView() {
		final Container parent = getParent();
		if (!(parent instanceof NodeView))
			return null;
		NodeView parentView = (NodeView) parent;
		if (parentView.isContentVisible()) {
			return parentView;
		}
		return parentView.getVisibleParentView();
	}

	/**
	 * This method returns the NodeViews that are children of this node.
	 */
	public LinkedList getChildrenViews() {
		LinkedList childrenViews = new LinkedList();
		final Component[] components = getComponents();
		for (int i = 0; i < components.length; i++) {
			if (!(components[i] instanceof NodeView)) {
				continue;
			}
			NodeView view = (NodeView) components[i];
			childrenViews.add(view); // child.getViewer() );
		}
		return childrenViews;
	}

	protected LinkedList getSiblingViews() {
		return getParentView().getChildrenViews();
	}

	/**
	 * Returns the point the edge should start given the point of the child node
	 * that should be connected.
	 *
	 * @param targetView
	 *            TODO
	 */
	Point getMainViewOutPoint(NodeView targetView, Point destinationPoint) {
		final NodeViewLayout layoutManager = (NodeViewLayout) getLayout();
		Point out = layoutManager.getMainViewOutPoint(this, targetView,
				destinationPoint);
		return out;
	}

	/**
	 * Returns the Point where the InEdge should arrive the Node.
	 */
	Point getMainViewInPoint() {
		final NodeViewLayout layoutManager = (NodeViewLayout) getLayout();
		Point in = layoutManager.getMainViewInPoint(this);
		return in;
	}

	/**
	 * Returns the Point where the Links should arrive the Node.
	 */
	public Point getLinkPoint(Point declination) {
		int x, y;
		Point linkPoint;
		if (declination != null) {
			x = getMap().getZoomed(declination.x);
			y = getMap().getZoomed(declination.y);
		} else {
			x = 1;
			y = 0;
		}
		if (isLeft()) {
			x = -x;
		}
		if (y != 0) {
			double ctgRect = Math.abs((double) getContent().getWidth()
					/ getContent().getHeight());
			double ctgLine = Math.abs((double) x / y);
			int absLinkX, absLinkY;
			if (ctgRect > ctgLine) {
				absLinkX = Math.abs(x * getContent().getHeight() / (2 * y));
				absLinkY = getContent().getHeight() / 2;
			} else {
				absLinkX = getContent().getWidth() / 2;
				absLinkY = Math.abs(y * getContent().getWidth() / (2 * x));
			}
			linkPoint = new Point(getContent().getWidth() / 2
					+ (x > 0 ? absLinkX : -absLinkX), getContent().getHeight()
					/ 2 + (y > 0 ? absLinkY : -absLinkY));
		} else {
			linkPoint = new Point((x > 0 ? getContent().getWidth() : 0),
					(getContent().getHeight() / 2));
		}
		linkPoint.translate(getContent().getX(), getContent().getY());
		convertPointToMap(linkPoint);
		return linkPoint;
	}

	protected Point convertPointToMap(Point p) {
		return Tools.convertPointToAncestor(this, p, getMap());
	}

	/**
	 * Returns the relative position of the Edge. This is used by bold edge to
	 * know how to shift the line.
	 */
	int getAlignment() {
		return mainView.getAlignment();
	}

	//
	// Navigation
	//
	/**
	 * The algorithm should be here the following (see Eclipse editor):
	 * Selected is the n-th node from above.
	 * Look for the last node visible on the screen and make this node the first one.
	 * Now select the n-th node from above.
	 *
	 * Easier idea to implement:
	 * Store node y position as y0.
	 * Search for a node with the same parent with y position y0+height
	 * Scroll the window by height.
	 */
	protected NodeView getNextPage() {
		// from root we cannot jump
		if (getModel().isRoot()) {
			return this; // I'm root
		}
		int y0 = getInPointInMap().y + getMap().getViewportSize().height;
		NodeView sibling = getNextVisibleSibling();
		if (sibling == this) {
			return this; // at the end
		}
		// if (sibling.getParentView() != this.getParentView()) {
		// return sibling; // sibling on another page (has different parent)
		// }
		NodeView nextSibling = sibling.getNextVisibleSibling();
		while (nextSibling != sibling
				&& sibling.getParentView() == nextSibling.getParentView()) {
			// has the same position after one page?
			if(nextSibling.getInPointInMap().y >= y0) {
				break;
			}
			sibling = nextSibling;
			nextSibling = nextSibling.getNextVisibleSibling();
		}
		return sibling; // last on the page
	}
	/**
	 * @return the position of the in-point of this node in view coordinates
	 */
	protected Point getInPointInMap() {
		return convertPointToMap(getMainViewInPoint());
	}

	protected NodeView getPreviousPage() {
		if (getModel().isRoot()) {
			return this; // I'm root
		}
		int y0 = getInPointInMap().y - getMap().getViewportSize().height;
		NodeView sibling = getPreviousVisibleSibling();
		if (sibling == this) {
			return this; // at the end
		}
		// if (sibling.getParentView() != this.getParentView()) {
		// return sibling; // sibling on another page (has different parent)
		// }
		NodeView previousSibling = sibling.getPreviousVisibleSibling();
		while (previousSibling != sibling
				&& sibling.getParentView() == previousSibling.getParentView()) {
			// has the same position after one page?
			if(previousSibling.getInPointInMap().y <= y0) {
				break;
			}
			sibling = previousSibling;
			previousSibling = previousSibling.getPreviousVisibleSibling();
		}
		return sibling; // last on the page
	}

	protected NodeView getNextVisibleSibling() {
		NodeView sibling;
		NodeView lastSibling = this;
		// get next sibling even in higher levels
		for (sibling = this; !sibling.getModel().isRoot(); sibling = sibling
				.getParentView()) {
			lastSibling = sibling;
			sibling = sibling.getNextSiblingSingle();
			if (sibling != lastSibling) {
				break; // found sibling
			}
		}

		// we have the nextSibling, search in childs
		// untill: leaf, closed node, max level
		while (sibling.getModel().getNodeLevel() < getMap()
				.getSiblingMaxLevel()) {
			// can we drill down?
			NodeView first = sibling.getFirst(sibling.isRoot() ? lastSibling
					: null, this.isLeft(), !this.isLeft());
			if (first == null) {
				break;
			}
			sibling = first;
		}
		if (sibling.isRoot()) {
			return this; // didn't find (we are at the end)
		}

		return sibling;
	}

	/**
	 * @param startAfter
	 *            TODO
	 */
	NodeView getFirst(Component startAfter, boolean leftOnly, boolean rightOnly) {
		final Component[] components = getComponents();
		for (int i = 0; i < components.length; i++) {
			if (startAfter != null) {
				if (components[i] == startAfter) {
					startAfter = null;
				}
				continue;
			}
			if (!(components[i] instanceof NodeView)) {
				continue;
			}
			NodeView view = (NodeView) components[i];
			if (leftOnly && !view.isLeft() || rightOnly && view.isLeft()) {
				continue;
			}
			if (view.isContentVisible()) {
				return view;
			}
			NodeView child = view.getFirst(null, leftOnly, rightOnly);
			if (child != null) {
				return child;
			}
		}
		return null;
	}

	/**
	 */
	public boolean isContentVisible() {
		return getModel().isVisible();
	}

	private NodeView getLast(Component startBefore, boolean leftOnly,
			boolean rightOnly) {
		final Component[] components = getComponents();
		for (int i = components.length - 1; i >= 0; i--) {
			if (startBefore != null) {
				if (components[i] == startBefore) {
					startBefore = null;
				}
				continue;
			}
			if (!(components[i] instanceof NodeView)) {
				continue;
			}
			NodeView view = (NodeView) components[i];
			if (leftOnly && !view.isLeft() || rightOnly && view.isLeft()) {
				continue;
			}
			if (view.isContentVisible()) {
				return view;
			}
			NodeView child = view.getLast(null, leftOnly, rightOnly);
			if (child != null) {
				return child;
			}
		}
		return null;
	}

	LinkedList getLeft(boolean onlyVisible) {
		LinkedList all = getChildrenViews();
		LinkedList left = new LinkedList();
		for (ListIterator e = all.listIterator(); e.hasNext();) {
			NodeView node = (NodeView) e.next();
			if (node == null)
				continue;
			if (node.isLeft())
				left.add(node);
		}
		return left;
	}

	LinkedList getRight(boolean onlyVisible) {
		LinkedList all = getChildrenViews();
		LinkedList right = new LinkedList();
		for (ListIterator e = all.listIterator(); e.hasNext();) {
			NodeView node = (NodeView) e.next();
			if (node == null)
				continue;
			if (!node.isLeft())
				right.add(node);
		}
		return right;
	}

	protected NodeView getPreviousVisibleSibling() {
		NodeView sibling;
		NodeView previousSibling = this;

		// get Previous sibling even in higher levels
		for (sibling = this; !sibling.getModel().isRoot(); sibling = sibling
				.getParentView()) {
			previousSibling = sibling;
			sibling = sibling.getPreviousSiblingSingle();
			if (sibling != previousSibling) {
				break; // found sibling
			}
		}
		// we have the PreviousSibling, search in childs
		// untill: leaf, closed node, max level
		while (sibling.getModel().getNodeLevel() < getMap()
				.getSiblingMaxLevel()) {
			NodeView last = sibling.getLast(sibling.isRoot() ? previousSibling
					: null, this.isLeft(), !this.isLeft());
			if (last == null) {
				break;
			}
			sibling = last;
		}
		if (sibling.isRoot()) {
			return this; // didn't find (we are at the end)
		}

		return sibling;
	}

	protected NodeView getNextSiblingSingle() {
		LinkedList v = null;
		if (getParentView().getModel().isRoot()) {
			if (this.isLeft()) {
				v = (getParentView()).getLeft(true);
			} else {
				v = (getParentView()).getRight(true);
			}
		} else {
			v = getParentView().getChildrenViews();
		}
		final int index = v.indexOf(this);
		for (int i = index + 1; i < v.size(); i++) {
			final NodeView nextView = (NodeView) v.get(i);
			if (nextView.isContentVisible()) {
				return nextView;
			} else {
				final NodeView first = nextView.getFirst(null, false, false);
				if (first != null) {
					return first;
				}
			}
		}
		return this;
	}

	protected NodeView getPreviousSiblingSingle() {
		LinkedList v = null;
		if (getParentView().getModel().isRoot()) {
			if (this.isLeft()) {
				v = (getParentView()).getLeft(true);
			} else {
				v = (getParentView()).getRight(true);
			}
		} else {
			v = getParentView().getChildrenViews();
		}
		final int index = v.indexOf(this);
		for (int i = index - 1; i >= 0; i--) {
			final NodeView nextView = (NodeView) v.get(i);
			if (nextView.isContentVisible()) {
				return nextView;
			} else {
				final NodeView last = nextView.getLast(null, false, false);
				if (last != null) {
					return last;
				}
			}
		}
		return this;
	}

	//
	// Update from Model
	//

	void insert() {
		ListIterator it = getModel().childrenFolded();
		while (it.hasNext()) {
			insert((MindMapNode) it.next(), 0);
		}
	}

	/**
	 * Create views for the newNode and all his descendants, set their isLeft
	 * attribute according to this view.
	 */

	NodeView insert(MindMapNode newNode, int position) {
		NodeView newView = NodeViewFactory.getInstance().newNodeView(newNode,
				position, getMap(), this);
		newView.insert();
		return newView;
	}

	/**
	 * This is a bit problematic, because getChildrenViews() only works if model
	 * is not yet removed. (So do not _really_ delete the model before the view
	 * removed (it needs to stay in memory)
	 */
	void remove() {
		for (ListIterator e = getChildrenViews().listIterator(); e.hasNext();) {
			((NodeView) e.next()).remove();
		}
		if (isSelected()) {
			getMap().deselect(this);
		}
		getModeController().onViewRemovedHook(this);
		removeFromMap();
		if (attributeView != null) {
			attributeView.viewRemoved();
		}
		getModel().removeViewer(this); // Let the model know he is invisible
	}

	void update() {
		updateStyle();
		if (!isContentVisible()) {
			// not visible at all
			removeFoldingListener();
			mainView.setVisible(false);
			return;
		}
		mainView.setVisible(true);
		updateTextColor();
		updateFont();
		updateIcons();
		createAttributeView();
		if (attributeView != null) {
			attributeView.update();
		}
		// visible. has it still visible children?
		if(getModel().hasVisibleChilds()) {
			addFoldingListener();
		} else {
			removeFoldingListener();
		}
		updateText();
		updateToolTip();
		revalidate(); // Because of zoom?
	}

	public void createAttributeView() {
		if (attributeView == null && model.getAttributes().getNode() != null) {
			attributeView = new AttributeView(this);
		}
	}

	void repaintSelected() {
		updateTextColor();
		repaint();
	}

	private void updateText() {
		String nodeText = getModel().toString();
		final boolean isHtml = nodeText.startsWith("<html>");
		// 6) Set the text
		// Right now, this implementation is quite logical, although it allows
		// for nonconvex feature of nodes starting with <html>.

		// For plain text, tell if node is long and its width has to be
		// restricted
		// boolean isMultiline = nodeText.indexOf("\n") >= 0;
		boolean widthMustBeRestricted = false;
		if (!isHtml) {
			String[] lines = nodeText.split("\n");
			for (int line = 0; line < lines.length; line++) {
				// Compute the width the node would spontaneously take,
				// by preliminarily setting the text.
				setText(lines[line]);
				widthMustBeRestricted = mainView.getPreferredSize().width > map
						.getZoomed(map.getMaxNodeWidth())
						+ mainView.getIconWidth();
				if (widthMustBeRestricted) {
					break;
				}
			}
			isLong = widthMustBeRestricted || lines.length > 1;
		}

		if (isHtml) {
			// Make it possible to use relative img references in HTML using tag
			// <base>.
			if (nodeText.indexOf("<img") >= 0 && nodeText.indexOf("<base ") < 0) {
				try {
					nodeText = "<html><base href=\"" + map.getModel().getURL()
							+ "\">" + nodeText.substring(6);
				} catch (MalformedURLException e) {
				}
			}
			// If user does not want us to set the width automatically, he'll
			// use <body width="">,
			// <body width="800">, or avoid the <body> tag altogether.

			// Set user HTML head
			String htmlLongNodeHead = getFrame()
					.getProperty("html_long_node_head");
			if (htmlLongNodeHead != null && !htmlLongNodeHead.equals("")) {
				if (nodeText.matches("(?ims).*<head>.*")) {
					nodeText = nodeText.replaceFirst("(?ims).*<head>.*",
							"<head>" + htmlLongNodeHead);
				} else {
					nodeText = nodeText.replaceFirst("(?ims)<html>",
							"<html><head>" + htmlLongNodeHead + "</head>");
				}
			}

			// Find out if the width has to be restricted.
			if (nodeText.length() < 30000) {
				// Empirically determined limit, above which we restrict the
				// width without actually checking it.
				// The purpose of that is to speed up rendering of very long
				// nodes.
				setText(nodeText);
				widthMustBeRestricted = mainView.getPreferredSize().width > map
						.getZoomed(map.getMaxNodeWidth())
						+ mainView.getIconWidth();
			} else {
				widthMustBeRestricted = true;
			}

			if (widthMustBeRestricted) {
				nodeText = nodeText.replaceFirst("(?i)<body>", "<body width=\""
						+ map.getMaxNodeWidth() + "\">");
			}
			setText(nodeText);
		} else if (nodeText.startsWith("<table>")) {
			String[] lines = nodeText.split("\n");
			lines[0] = lines[0].substring(7); // remove <table> tag
			int startingLine = lines[0].matches("\\s*") ? 1 : 0;
			// ^ If the remaining first line is empty, do not draw it

			String text = "<html><table border=1 style=\"border-color: white\">";
			// String[] lines = nodeText.split("\n");
			for (int line = startingLine; line < lines.length; line++) {
				text += "<tr><td style=\"border-color: white;\">"
						+ HtmlTools.toXMLEscapedText(lines[line]).replaceAll(
								"\t", "<td style=\"border-color: white\">");
			}
			setText(text);
		} else if (isLong) {
			String text = HtmlTools.plainToHTML(nodeText);
			if (widthMustBeRestricted) {
				text = text.replaceFirst("(?i)<p>",
						"<p width=\"" + map.getMaxNodeWidth() + "\">");
			}
			setText(text);
		} else {
			setText(nodeText);
		}
	}

	private void updateFont() {
		Font font = getModel().getFont();
		font = font == null ? getController().getDefaultFont() : font;
		if (font != null) {
			mainView.setFont(font);
		} else {
			// We can survive this trouble.
			System.err.println("NodeView.update(): default font is null.");
		}
	}

	private void updateIcons() {
		updateIconPosition();
		MultipleImage iconImages = new MultipleImage(1.0f);
		boolean iconPresent = false;
		/* fc, 06.10.2003: images? */

		FreeMindMain frame = getFrame();
		Map stateIcons = (getModel()).getStateIcons();
		for (Iterator i = stateIcons.keySet().iterator(); i.hasNext();) {
			String key = (String) i.next();
			iconPresent = true;
			ImageIcon myIcon = (ImageIcon) stateIcons.get(key);
			iconImages.addImage(myIcon);

		}

		List icons = (getModel()).getIcons();
		for (Iterator i = icons.iterator(); i.hasNext();) {
			MindIcon myIcon = (MindIcon) i.next();
			iconPresent = true;
			// System.out.println("print the icon " + myicon.toString());
			iconImages.addImage(myIcon.getIcon());
		}
		String link = ((NodeAdapter) getModel()).getLink();
		if (link != null) {
			iconPresent = true;
			String iconPath = "images/Link.png";
			if (link.startsWith("#")) {
				iconPath = "images/LinkLocal.png";
			} else if (link.startsWith("mailto:")) {
				iconPath = "images/Mail.png";
			} else if (Tools.executableByExtension(link)) {
				iconPath = "images/Executable.png";
			}
			ImageIcon icon = new ImageIcon(frame.getResource(iconPath));
			iconImages.addImage(icon);
		}
		// /* Folded icon by Matthias Schade (mascha2), fc, 20.12.2003*/
		// if (((NodeAdapter)getModel()).isFolded()) {
		// iconPresent = true;
		// ImageIcon icon = new
		// ImageIcon(((NodeAdapter)getModel()).getFrame().getResource("images/Folded.png"));
		// iconImages.addImage(icon);
		// }
		// DanielPolansky: set icon only if icon is present, because
		// we don't want to insert any additional white space.
		setIcon(iconPresent ? iconImages : null);
	}

	private void updateIconPosition() {
		getMainView().setHorizontalTextPosition(
				isLeft() ? SwingConstants.LEADING : SwingConstants.TRAILING);
	}

	private void updateTextColor() {
		Color color;
		color = getModel().getColor();
		if (color == null) {
			color = MapView.standardNodeTextColor;
		}
		mainView.setForeground(color);
	}

	boolean useSelectionColors() {
		return isSelected() && !MapView.standardDrawRectangleForSelection
				&& !map.isCurrentlyPrinting();
	}

	void updateStyle() {
		if (mainView != null
				&& (mainView.getStyle().equals(model.getStyle()) || model
						.isRoot())) {
			return;
		}
		final MainView newMainView = NodeViewFactory.getInstance().newMainView(
				model);
		setMainView(newMainView);

	}

	/**
	 * Updates the tool tip of the node.
	 */
	public void updateToolTip() {
		Map tooltips = getModel().getToolTip();
		/*
		 * if(tooltips.size() == 1) { String toolTipText = (String)
		 * tooltips.values().iterator().next();
		 * logger.finest("setting tooltip to "+toolTipText);
		 * mainView.setToolTipText(toolTipText); } else
		 */if (tooltips.size() == 0) {
			mainView.setToolTipText(null);
		} else {
			// html table
			StringBuffer text = new StringBuffer("<html><table width=\""
					+ getMaxToolTipWidth() + "\">");
			for (Iterator i = tooltips.keySet().iterator(); i.hasNext();) {
				String key = (String) i.next();
				String value = (String) tooltips.get(key);
				// no html end inside the value:
				value = value.replaceAll("</html>", "");
				text.append("<tr><td>");
				text.append(value);
				text.append("</td></tr>");
			}
			text.append("</table></html>");
			mainView.setToolTipText(text.toString());
		}
	}

	public int getMaxToolTipWidth() {
		if (maxToolTipWidth == 0) {
			try {
				maxToolTipWidth = getController().getIntProperty(
						"max_tooltip_width", 600);
			} catch (NumberFormatException e) {
				maxToolTipWidth = 600;
			}
		}
		return maxToolTipWidth;
	}

	/**
     */
	public void setIcon(MultipleImage image) {
		mainView.setIcon(image);
	}

	void updateAll() {
		update();
		invalidate();
		for (ListIterator e = getChildrenViews().listIterator(); e.hasNext();) {
			NodeView child = (NodeView) e.next();
			child.updateAll();
		}
	}

	String getStyle() {
		return mainView.getStyle();
	}

	/**
	 * @return returns the color that should used to select the node.
	 */
	protected Color getSelectedColor() {
		// Color backgroundColor = getModel().getBackgroundColor();
		// // if(backgroundColor != null) {
		// // Color backBrighter = backgroundColor.brighter();
		// // // white?
		// // if(backBrighter.getRGB() == Color.WHITE.getRGB()) {
		// // return standardSelectColor;
		// // }
		// // // == standard??
		// // if (backBrighter.equals (standardSelectColor) ) {
		// // return backgroundColor.darker();
		// // }
		// // return backBrighter;
		// // }
		// // == standard??
		// if (backgroundColor != null /*&&
		// backgroundColor.equals(standardSelectColor)*/ ) {
		// // bad hack:
		// return getAntiColor1(backgroundColor);
		// // return new Color(0xFFFFFF - backgroundColor.getRGB());
		// }
		return MapView.standardSelectColor;
	}

	/*
	 * http://groups.google.de/groups?hl=de&lr=&ie=UTF-8&threadm=9i5bbo%24h1kmi%243
	 * %
	 * 40ID-77081.news.dfncis.de&rnum=1&prev=/groups%3Fq%3Djava%2520komplement%25
	 * C3
	 * %25A4rfarbe%2520helligkeit%26hl%3Dde%26lr%3D%26ie%3DUTF-8%26sa%3DN%26as_qdr
	 * %3Dall%26tab%3Dwg
	 */
	/**
	 * Determines to a given color a color, that is the best contrary color. It
	 * is different from {@link #getAntiColor2}.
	 *
	 * @since PPS 1.1.1
	 */
	protected static Color getAntiColor1(Color c) {
		float[] hsb = Color.RGBtoHSB(c.getRed(), c.getGreen(), c.getBlue(),
				null);
		hsb[0] += 0.40;
		if (hsb[0] > 1)
			hsb[0]--;
		hsb[1] = 1;
		hsb[2] = 0.7f;
		return Color.getHSBColor(hsb[0], hsb[1], hsb[2]);
	}

	/**
	 * Determines to a given color a color, that is the best contrary color. It
	 * is different from {@link #getAntiColor1}.
	 *
	 * @since PPS 1.1.1
	 */
	protected static Color getAntiColor2(Color c) {
		float[] hsb = Color.RGBtoHSB(c.getRed(), c.getGreen(), c.getBlue(),
				null);
		hsb[0] -= 0.40;
		if (hsb[0] < 0)
			hsb[0]++;
		hsb[1] = 1;
		hsb[2] = (float) 0.8;
		return Color.getHSBColor(hsb[0], hsb[1], hsb[2]);
	}

	/**
	 * @return Returns the sHIFT.
	 */

	public int getShift() {
		return map.getZoomed(model.calcShiftY());
	}

	/**
	 * @return Returns the VGAP.
	 */
	public int getVGap() {
		return map.getZoomed(model.getVGap());
	}

	public int getHGap() {
		return map.getZoomed(model.getHGap());
	}

	public MainView getMainView() {
		return mainView;
	}

	void syncronizeAttributeView() {
		if (attributeView != null) {
			attributeView.syncronizeAttributeView();
		}
	}

	public Font getTextFont() {
		return getMainView().getFont();
	}

	public Color getTextColor() {
		Color color = getModel().getColor();
		if (color == null) {
			color = MapView.standardNodeTextColor;
		}
		return color;

	}

	/**
     */
	public AttributeView getAttributeView() {
		if (attributeView == null) {
			model.createAttributeTableModel();
			attributeView = new AttributeView(this);
		}

		return attributeView;
	}

	public NodeView getPreferredVisibleChild(boolean left) { // mind preferred
																// child
		// :-) (PN)
		if (preferredChild != null && (left == preferredChild.isLeft())
				&& this.preferredChild.getParent() == this) {
			if (preferredChild.isContentVisible()) {
				return preferredChild;
			} else {
				NodeView newSelected = preferredChild
						.getPreferredVisibleChild(left);
				if (newSelected != null) {
					return newSelected;
				}
			}
		}
		if (!getModel().isLeaf()) {
			int yGap = Integer.MAX_VALUE;
			final NodeView baseComponent;
			if (isContentVisible()) {
				baseComponent = this;
			} else {
				baseComponent = getVisibleParentView();
			}
			int ownY = baseComponent.getMainView().getY()
					+ baseComponent.getMainView().getHeight() / 2;
			NodeView newSelected = null;
			for (int i = 0; i < getComponentCount(); i++) {
				Component c = getComponent(i);
				if (!(c instanceof NodeView)) {
					continue;
				}
				NodeView childView = (NodeView) c;
				if (!(childView.isLeft() == left)) {
					continue;
				}
				if (!childView.isContentVisible()) {
					childView = childView.getPreferredVisibleChild(left);
					if (childView == null) {
						continue;
					}
				}
				Point childPoint = new Point(0, childView.getMainView()
						.getHeight() / 2);
				Tools.convertPointToAncestor(childView.getMainView(),
						childPoint, baseComponent);
				final int gapToChild = Math.abs(childPoint.y - ownY);
				if (gapToChild < yGap) {
					newSelected = childView;
					preferredChild = (NodeView) c;
					yGap = gapToChild;
				} else {
					break;
				}
			}
			return newSelected;
		}
		return null;
	}

	public void setPreferredChild(NodeView view) {
		this.preferredChild = view;
		final Container parent = this.getParent();
		if (view == null) {
			return;
		} else if (parent instanceof NodeView) {
			// set also preffered child of parents...
			((NodeView) parent).setPreferredChild(this);
		}
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * javax.swing.event.TreeModelListener#treeNodesChanged(javax.swing.event
	 * .TreeModelEvent)
	 */
	public void treeNodesChanged(TreeModelEvent e) {
		update();
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * javax.swing.event.TreeModelListener#treeNodesInserted(javax.swing.event
	 * .TreeModelEvent)
	 */
	public void treeNodesInserted(TreeModelEvent e) {
		addFoldingListener();
		if (getModel().isFolded()) {
			return;
		}
		final int[] childIndices = e.getChildIndices();

		for (int i = 0; i < childIndices.length; i++) {
			int index = childIndices[i];
			insert((MindMapNode) getModel().getChildAt(index), index);
		}
		revalidate();

	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * javax.swing.event.TreeModelListener#treeNodesRemoved(javax.swing.event
	 * .TreeModelEvent)
	 */
	public void treeNodesRemoved(TreeModelEvent e) {
		if(!getModel().hasVisibleChilds()) {
			removeFoldingListener();
		}
		getMap().resetShiftSelectionOrigin();
		if (getModel().isFolded()) {
			return;
		}

		final int[] childIndices = e.getChildIndices();
		boolean preferredChildIsLeft = preferredChild != null
				&& preferredChild.isLeft();

		for (int i = childIndices.length - 1; i >= 0; i--) {
			final int index = childIndices[i];
			final NodeView node = (NodeView) getComponent(index);
			if (node == this.preferredChild) { // mind preferred child :-) (PN)
				this.preferredChild = null;
				for (int j = index + 1; j < getComponentCount(); j++) {
					final Component c = getComponent(j);
					if (!(c instanceof NodeView)) {
						break;
					}
					NodeView candidate = (NodeView) c;
					if (candidate.isVisible()
							&& node.isLeft() == candidate.isLeft()) {
						this.preferredChild = candidate;
						break;
					}
				}
				if (this.preferredChild == null) {
					for (int j = index - 1; j >= 0; j--) {
						final Component c = getComponent(j);
						if (!(c instanceof NodeView)) {
							break;
						}
						NodeView candidate = (NodeView) c;
						if (candidate.isVisible()
								&& node.isLeft() == candidate.isLeft()) {
							this.preferredChild = candidate;
							break;
						}
					}
				}
			}
			node.remove();
		}
		NodeView preferred = getPreferredVisibleChild(preferredChildIsLeft);
		if (preferred != null) { // after delete focus on a brother (PN)
			getMap().selectAsTheOnlyOneSelected(preferred);
		} else {
			getMap().selectAsTheOnlyOneSelected(this);
		}
		revalidate();
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * javax.swing.event.TreeModelListener#treeStructureChanged(javax.swing.
	 * event.TreeModelEvent)
	 */
	public void treeStructureChanged(TreeModelEvent e) {
		getMap().resetShiftSelectionOrigin();
		for (ListIterator i = getChildrenViews().listIterator(); i.hasNext();) {
			((NodeView) i.next()).remove();
		}
		insert();
		if (map.getSelected() == null) {
			map.selectAsTheOnlyOneSelected(this);
		}
		map.revalidateSelecteds();
		revalidate();
	}

	public int getZoomedFoldingSymbolHalfWidth() {
		int preferredFoldingSymbolHalfWidth = (int) ((getFoldingSymbolWidth() * map
				.getZoom()) / 2);
		return Math.min(preferredFoldingSymbolHalfWidth, getHeight() / 2);
	}

	/**
	 * @return the left/right point of the folding circle. To receive its
	 * center, the amount has to be moved to left/right (depending on its side)
	 * by the folding circle width.
	 */
	public Point getFoldingMarkPosition() {
		Point out = getMainViewOutPoint(this, new Point());
		return out;
	}

	public JComponent getContent() {
		return contentPane == null ? mainView : contentPane;
	}

	public Container getContentPane() {
		if (contentPane == null) {
			contentPane = NodeViewFactory.getInstance().newContentPane(this);
			remove(mainView);
			contentPane.add(mainView);
			add(contentPane);
		}
		return contentPane;
	}

	public NodeMotionListenerView getMotionListenerView() {
		return motionListenerView;
	}

	public void setBounds(int x, int y, int width, int height) {
		super.setBounds(x, y, width, height);
		if (motionListenerView != null) {
			motionListenerView.invalidate();
		}
		if (mFoldingListener != null) {
			mFoldingListener.invalidate();
		}
	}

	public void setVisible(boolean isVisible) {
		super.setVisible(isVisible);
		if (motionListenerView != null) {
			motionListenerView.setVisible(isVisible);
		}
		if (mFoldingListener != null) {
			mFoldingListener.setVisible(isVisible);
		}
	}

	private void paintCloudsAndEdges(Graphics2D g) {
		Object renderingHint = getController().setEdgesRenderingHint(g);
		for (int i = 0; i < getComponentCount(); i++) {
			final Component component = getComponent(i);
			if (!(component instanceof NodeView)) {
				continue;
			}
			NodeView nodeView = (NodeView) component;
			if (nodeView.isContentVisible()) {
				Point p = new Point();
				Tools.convertPointToAncestor(nodeView, p, this);
				g.translate(p.x, p.y);
				nodeView.paintCloud(g);
				g.translate(-p.x, -p.y);
				EdgeView edge = NodeViewFactory.getInstance().getEdge(nodeView);
				edge.paint(nodeView, g);
			} else {
				nodeView.paintCloudsAndEdges(g);
			}
		}
		Tools.restoreAntialiasing(g, renderingHint);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see javax.swing.JComponent#paint(java.awt.Graphics)
	 */
	public void paint(Graphics g) {
		final boolean isRoot = isRoot();
		if (isRoot) {
			paintCloud(g);
		}
		if (isContentVisible()) {
			Graphics2D g2d = (Graphics2D) g;
			paintCloudsAndEdges(g2d);
			super.paint(g);
			// return to std stroke
			g2d.setStroke(BubbleMainView.DEF_STROKE);
//			if (!isRoot) {
//				paintFoldingMark(g2d);
//			}
		} else {
			super.paint(g);
		}
		// g.setColor(Color.BLACK);
		// g.drawRect(0, 0, getWidth()-1, getHeight()-1);
	}

	private void paintCloud(Graphics g) {
		if (isContentVisible() && model.getCloud() != null) {
			CloudView cloud = new CloudView(model.getCloud(), this);
			cloud.paint(g);
		}
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see java.awt.Component#toString()
	 */
	public String toString() {
		return getModel().toString() + ", " + super.toString();
	}

	public Rectangle getInnerBounds() {
		final int space = getMap().getZoomed(SPACE_AROUND);
		return new Rectangle(space, space, getWidth() - 2 * space, getHeight()
				- 2 * space);
	}

	public boolean contains(int x, int y) {
		final int space = getMap().getZoomed(SPACE_AROUND) - 2
				* getZoomedFoldingSymbolHalfWidth();
		return (x >= space) && (x < getWidth() - space) && (y >= space)
				&& (y < getHeight() - space);
	}

	public Color getTextBackground() {
		final Color modelBackgroundColor = getModel().getBackgroundColor();
		if (modelBackgroundColor != null) {
			return modelBackgroundColor;
		}
		return getBackgroundColor();
	}

	private Color getBackgroundColor() {
		final MindMapCloud cloud = getModel().getCloud();
		if (cloud != null) {
			return cloud.getColor();
		}
		if (isRoot()) {
			return getMap().getBackground();
		}
		return getParentView().getBackgroundColor();
	}

	public static int getFoldingSymbolWidth() {
		if (FOLDING_SYMBOL_WIDTH == -1) {
			FOLDING_SYMBOL_WIDTH = Resources.getInstance().getIntProperty(
					"foldingsymbolwidth", 8);
		}
		return FOLDING_SYMBOL_WIDTH;
	}

}


text:
/**
 * PositionTableCellRenderer.java
 */
package gui;

import java.awt.Color;
import java.awt.Component;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;

/**
 * This class displays the position table and cells for the market display.
 *
 * @author hieldc
 * @version StockExVirtuoso.Version.1.0
 */
public class PositionTableCellRenderer extends DefaultTableCellRenderer {

    /**
     * Public Constructor method.
     */
    public PositionTableCellRenderer() {
        super();
        setOpaque(true);
    }

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int row, int column) {

        String num = (String) table.getValueAt(row, 2);
        int intValue = Integer.parseInt(num);

        if (intValue <= 0) {
            setForeground(Color.black);
            setBackground(Color.red);

        } else {
            setForeground(Color.black);
            setBackground(Color.green);
        }
        if (column == 2) {
            setText("" + Math.abs(intValue));
        } else {
            setText(value.toString());
        }
        return this;
    }
}
//end of file


text:
import functools
import multiprocessing

from django.conf import settings

from .base import MigrationExecutor, run_migrations

def run_migrations_percent(args, options, codename, count, idx_schema_name):
    idx, schema_name = idx_schema_name
    return run_migrations(
        args,
        options,
        codename,
        schema_name,
        allow_atomic=False,
        idx=idx,
        count=count
    )

def run_multi_type_migrations_percent(args, options, codename, count, idx_schema_name):
    idx, tenant = idx_schema_name
    return run_migrations(
        args,
        options,
        codename,
        schema_name=tenant[0],
        tenant_type=tenant[1],
        allow_atomic=False,
        idx=idx,
        count=count
    )

class MultiprocessingExecutor(MigrationExecutor):
    codename = 'multiprocessing'

    def run_migrations(self, tenants=None):
        tenants = tenants or []

        if self.PUBLIC_SCHEMA_NAME in tenants:
            run_migrations(self.args, self.options, self.codename, self.PUBLIC_SCHEMA_NAME)
            tenants.pop(tenants.index(self.PUBLIC_SCHEMA_NAME))

        if tenants:
            processes = getattr(
                settings,
                'TENANT_MULTIPROCESSING_MAX_PROCESSES',
                2
            )
            chunks = getattr(
                settings,
                'TENANT_MULTIPROCESSING_CHUNKS',
                2
            )

            from django.db import connections

            connection = connections[self.TENANT_DB_ALIAS]
            connection.close()
            connection.connection = None

            run_migrations_p = functools.partial(
                run_migrations_percent,
                self.args,
                self.options,
                self.codename,
                len(tenants)
            )
            p = multiprocessing.Pool(processes=processes)
            p.map(
                run_migrations_p,
                enumerate(tenants),
                chunks
            )

    def run_multi_type_migrations(self, tenants):
        tenants = tenants or []
        processes = getattr(
            settings,
            'TENANT_MULTIPROCESSING_MAX_PROCESSES',
            2
        )
        chunks = getattr(
            settings,
            'TENANT_MULTIPROCESSING_CHUNKS',
            2
        )

        from django.db import connections

        connection = connections[self.TENANT_DB_ALIAS]
        connection.close()
        connection.connection = None

        run_migrations_p = functools.partial(
            run_multi_type_migrations_percent,
            self.args,
            self.options,
            self.codename,
            len(tenants)
        )
        p = multiprocessing.Pool(processes=processes)
        p.map(
            run_migrations_p,
            enumerate(tenants),
            chunks
        )


text:
import { NgModule } from '@angular/core';
import { IonicApp, IonicModule } from 'ionic-angular';
import { HttpModule } from '@angular/http';

// Components
import { MyApp } from './app.component';
import { ContactPage } from '../pages/contact/contact';
import { TabsPage } from '../pages/tabs/tabs';
import { EmailLoginForm } from '../pages/login/login';
import { RegisterPage } from '../pages/login/register';
import { PhotoPage } from '../pages/photo/photo';
import { EmotionPage } from '../pages/emotion/emotion';

// Services
import { Storage } from '@ionic/storage';
import { AuthService } from '../providers/AuthService';
import { EmotionService } from '../providers/EmotionService';

@NgModule({
  declarations: [
    MyApp,
    ContactPage,
    TabsPage,
    EmailLoginForm,
    RegisterPage,
    PhotoPage,
    EmotionPage
  ],
  imports: [
    IonicModule.forRoot(MyApp),
    HttpModule
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    ContactPage,
    TabsPage,
    EmailLoginForm,
    RegisterPage,
    PhotoPage,
    EmotionPage
  ],
  providers: [AuthService, EmotionService, Storage]
})
export class AppModule {}


text:
/*
 * Arekkuusu / Improbable plot machine. 2018
 *
 * This project is licensed under the MIT.
 * The source code is available on github:
 * https://github.com/ArekkuusuJerii/Improbable-plot-machine
 */
package arekkuusu.implom.common.block;

import arekkuusu.implom.api.util.IPMMaterial;
import arekkuusu.implom.client.effect.Light;
import arekkuusu.implom.common.IPM;
import arekkuusu.implom.common.lib.LibNames;
import com.google.common.collect.ImmutableMap;
import net.katsstuff.teamnightclipse.mirror.data.Quat;
import net.katsstuff.teamnightclipse.mirror.data.Vector3;
import net.minecraft.block.BlockDirectional;
import net.minecraft.block.state.BlockFaceShape;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;

import java.util.Map;
import java.util.Random;

/*
 * Created by <Arekkuusu> on 5/2/2018.
 * It's distributed as part of Improbable plot machine.
 */
@SuppressWarnings("deprecation")
public class BlockLumenCompressor extends BlockBaseFacing {

	private static final Map<EnumFacing, Vector3> FACING_MAP = ImmutableMap.<EnumFacing, Vector3>builder()
			.put(EnumFacing.UP, Vector3.apply(0.5D, 0.05D, 0.5D))
			.put(EnumFacing.DOWN, Vector3.apply(0.5D, 0.95D, 0.5D))
			.put(EnumFacing.NORTH, Vector3.apply(0.5D, 0.5D, 0.95D))
			.put(EnumFacing.SOUTH, Vector3.apply(0.5D, 0.5D, 0.05D))
			.put(EnumFacing.EAST, Vector3.apply(0.05D, 0.5D, 0.5D))
			.put(EnumFacing.WEST, Vector3.apply(0.95D, 0.5D, 0.5D))
			.build();
	private static final ImmutableMap<EnumFacing, AxisAlignedBB> BB_MAP = FacingAlignedBB.create(
			new Vector3(0, 8, 0),
			new Vector3(16, 16, 16),
			EnumFacing.UP
	).build();

	public BlockLumenCompressor() {
		super(LibNames.LUMEN_COMPRESSOR, IPMMaterial.MONOLITH);
		setDefaultState(getDefaultState().withProperty(BlockDirectional.FACING, EnumFacing.DOWN));
		setHarvestLevel(Tool.PICK, ToolLevel.STONE);
		setHardness(1F);
	}

	@Override
	public IBlockState getStateForPlacement(World world, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer, EnumHand hand) {
		return defaultState().withProperty(BlockDirectional.FACING, facing.getOpposite());
	}

	@Override
	public void randomDisplayTick(IBlockState state, World world, BlockPos pos, Random rand) {
		EnumFacing facing = state.getValue(BlockDirectional.FACING);
		IBlockState stateFacing = world.getBlockState(pos.offset(facing));
		if(!stateFacing.getBlock().isFullCube(stateFacing)) {
			Vector3 back = getOffSet(facing.getOpposite(), pos);
			for(int i = 0; i < 3 + rand.nextInt(2); i++) {
				Quat x = Quat.fromAxisAngle(Vector3.Forward(), (rand.nextFloat() * 2F - 1F) * 45);
				Quat z = Quat.fromAxisAngle(Vector3.Right(), (rand.nextFloat() * 2F - 1F) * 45);
				double speed = 0.005D + rand.nextDouble() * 0.015D;
				Vector3 speedVec = new Vector3.WrappedVec3i(facing.getDirectionVec())
						.asImmutable()
						.multiply(speed)
						.rotate(x.multiply(z));
				Vector3 posVec = back.add(Vector3.rotateRandom().multiply(0.2D));
				IPM.getProxy().spawnMute(world, posVec, speedVec, 45, 1F, 0xFFE077, Light.GLOW);
			}
			for(int i = 0; i < 3; i++) {
				double speed = 0.005D + rand.nextDouble() * 0.015D;
				Vector3 speedVec = new Vector3.WrappedVec3i(facing.getDirectionVec()).asImmutable().multiply(speed);
				IPM.getProxy().spawnMute(world, back, speedVec, 45, 2F, 0xFFE077, Light.GLOW);
			}
		}
	}

	private Vector3 getOffSet(EnumFacing facing, BlockPos pos) {
		return FACING_MAP.get(facing).add(pos.getX(), pos.getY(), pos.getZ());
	}

	@Override
	public BlockFaceShape getBlockFaceShape(IBlockAccess world, IBlockState state, BlockPos pos, EnumFacing facing) {
		return state.getValue(BlockDirectional.FACING).getOpposite() == facing ? BlockFaceShape.BOWL : BlockFaceShape.SOLID;
	}

	@Override
	public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) {
		EnumFacing facing = state.getValue(BlockDirectional.FACING);
		return BB_MAP.getOrDefault(facing, FULL_BLOCK_AABB);
	}
}


text:
@implementation Dish_Order

-(Dish_Order *) initWithDishCell:(DishTableViewCell *)dish_cell {
    Dishes *dish = dish_cell.dish;
    _name = dish.name;
    _ident = dish.id;
    NSMutableArray *opts = [[NSMutableArray alloc] init];
    NSLog(@"OPTIONVIEWS: %d", [dish_cell.option_views count]);
    for(OptionsView *o in dish_cell.option_views){
        Options_Order *oo = [[Options_Order alloc] init];
        oo.options = [o.option_order_json copy];
        NSLog(@"Option Size: %d", [oo.options count]);
        oo.name = o.op.name;
        oo.ident = o.op.id;
        [opts addObject:oo];
    }
    _quantity = [[NSNumber numberWithDouble:dish_cell.dishFooterView.stepper.value] intValue];
    _options = [opts copy];
    return self;
}

@end


text:
using System.Text;
using System.Web.Configuration;

namespace System.Web.Util
{
	internal class WebEncoding
	{
		static public Encoding FileEncoding {
			get {
				GlobalizationConfiguration gc = GlobalizationConfiguration.GetInstance (null);
				if (gc == null)
					return Encoding.Default;

				return gc.FileEncoding;
			}
		}

		static public Encoding ResponseEncoding {
			get {
				GlobalizationConfiguration gc = GlobalizationConfiguration.GetInstance (null);
				if (gc == null)
					return Encoding.Default;

				return gc.ResponseEncoding;
			}
		}

		static public Encoding RequestEncoding {
			get {
				GlobalizationConfiguration gc = GlobalizationConfiguration.GetInstance (null);
				if (gc == null)
					return Encoding.Default;

				return gc.RequestEncoding;
			}
		}
	}
}


text:
activesupport_path = "#{File.dirname(__FILE__)}/../vendor/activesupport/lib"
$:.unshift(activesupport_path) if File.directory?(activesupport_path)

activemodel_path = "#{File.dirname(__FILE__)}/../vendor/activemodel/lib"
$:.unshift(activemodel_path) if File.directory?(activemodel_path)

require 'active_support'
require 'active_model'

require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/module/attribute_accessors'

require 'json'
require 'restclient'
require 'uri'

require 'recliner/core_extensions'
require 'recliner/exceptions'
require 'recliner/configuration'

module Recliner
  VERSION = '0.0.1'

  autoload :Conversions,         'recliner/conversions'

  autoload :Document,            'recliner/document'
  autoload :Database,            'recliner/database'

  autoload :AttributeMethods,    'recliner/attribute_methods'

  autoload :Properties,          'recliner/properties'
  autoload :Property,            'recliner/properties/property'
  autoload :Map,                 'recliner/properties/map'
  autoload :Set,                 'recliner/properties/set'

  autoload :Views,               'recliner/views'
  autoload :View,                'recliner/views/view'
  autoload :ViewDocument,        'recliner/views/document'
  autoload :ViewFunction,        'recliner/views/function'
  autoload :ViewGenerator,       'recliner/views/generator'

  autoload :Associations,        'recliner/associations'

  autoload :Validations,         'recliner/validations'
  autoload :Callbacks,           'recliner/callbacks'

  autoload :Timestamps,          'recliner/timestamps'
  autoload :PrettyInspect,       'recliner/pretty_inspect'

  # Accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class.
  mattr_accessor :logger, :instance_writer => false

  class << self
    # Performs a HTTP GET request on a JSON resource, deserializing the response.
    #
    # ==== Parameters
    #
    # * +uri+    - the URI of the resource
    # * +params+ - a hash of parameters to serialize with the URI
    #
    # ==== Example
    #
    #   >> Recliner.get('http://localhost:5984/my-database/some-document', :rev => '12-3220752267')
    #   => { '_id' => 'some-document', '_rev' => '12-3220752267', 'title' => 'Document title' }
    def get(uri, params={})
      request(:get, uri, params)
    end

    # Performs a HTTP POST request on a JSON resource, deserializing the response.
    #
    # ==== Parameters
    #
    # * +uri+     - the URI of the resource
    # * +payload+ - a hash of the data to POST
    # * +params+  - a hash of parameters to serialize with the URI
    #
    # ==== Example
    #
    #   >> Recliner.post('http://localhost:5984/my-database', { :title => 'Document title' })
    #   => { 'id' => '12eec4c198ef0e843cd16761fc565208', 'rev' => '1-1503678650', 'ok' => true }
    def post(uri, payload={}, params={})
      request(:post, uri, params, payload)
    end

    # Performs a HTTP PUT request on a JSON resource, deserializing the response.
    #
    # ==== Parameters
    #
    # * +uri+    - the URI of the resource
    # * +payload+ - a hash of the data to PUT
    # * +params+  - a hash of parameters to serialize with the URI
    #
    # ==== Example
    #
    #   >> Recliner.put('http://localhost:5984/my-database/some-document', { :title => 'Document title' })
    #   => { 'id' => 'some-document', 'rev' => '2-2152886926', 'ok' => true }
    def put(uri, payload={}, params={})
      request(:put, uri, params, payload)
    end

    # Performs a HTTP DELETE request on a JSON resource, deserializing the response.
    #
    # ==== Parameters
    #
    # * +uri+    - the URI of the resource
    # * +params+ - a hash of parameters to serialize with the URI, in particular the revision :rev
    #
    # ==== Example
    #
    #   >> Recliner.delete('http://localhost:5984/my-database/some-document', :rev => '2-2152886926')
    #   => { 'id' => 'some-document', 'rev' => '3-3894620555', 'ok' => true }
    def delete(uri, params={})
      uri << "?rev=#{params.delete(:rev)}" if params[:rev]
      request(:delete, uri, params)
    end

  private
    def request(type, uri, params={}, payload=nil)
      args = [type, "#{uri}#{to_query_string(params)}"]
      log(*args)
      args << payload.to_json if payload

      JSON.parse(RestClient.send(*args))
    rescue RestClient::ResourceNotFound
      raise DocumentNotFound, "Could not find document at #{uri}"
    rescue RestClient::RequestFailed => e
      rescue_from_failed_request(e)
    end

    def log(type, uri)
      if logger
        logger.debug("  [#{type.to_s.upcase}] #{uri}")
      end
    end

    def rescue_from_failed_request(e)
      case e.http_code
      when 409
        raise StaleRevisionError
      else
        raise CouchDBError, e.http_body
      end
    end

    def to_query_string(params)
      str = params.map { |k, v| "#{URI.escape(k.to_s)}=#{URI.escape(v.to_json)}" }.join('&')
      str.blank? ? '' : "?#{str}"
    end
  end
end

I18n.load_path << File.dirname(__FILE__) + '/recliner/locale/en.yml'


text:
package nam.model.dependency;

import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.enterprise.context.SessionScoped;
import javax.faces.model.DataModel;
import javax.inject.Inject;
import javax.inject.Named;

import org.aries.runtime.BeanContext;
import org.aries.ui.AbstractSelectManager;

import nam.model.Dependency;
import nam.model.util.DependencyUtil;

@SessionScoped
@Named("dependencySelectManager")
public class DependencySelectManager extends AbstractSelectManager<Dependency, DependencyListObject> implements Serializable {

	@Inject
	private DependencyDataManager dependencyDataManager;

	@Inject
	private DependencyHelper dependencyHelper;

	@Override
	public String getClientId() {
		return "dependencySelect";
	}

	@Override
	public String getTitle() {
		return "Dependency Selection";
	}

	@Override
	protected Class<Dependency> getRecordClass() {
		return Dependency.class;
	}

	@Override
	public boolean isEmpty(Dependency dependency) {
		return dependencyHelper.isEmpty(dependency);
	}

	@Override
	public String toString(Dependency dependency) {
		return dependencyHelper.toString(dependency);
	}

	protected DependencyHelper getDependencyHelper() {
		return BeanContext.getFromSession("dependencyHelper");
	}

	protected DependencyListManager getDependencyListManager() {
		return BeanContext.getFromSession("dependencyListManager");
	}

	@Override
	public void initialize() {
		initializeContext();
		refreshDependencyList();
		populate(selectedRecords);
	}

	@Override
	public void populateItems(Collection<Dependency> recordList) {
		DependencyListManager dependencyListManager = getDependencyListManager();
		DataModel<DependencyListObject> dataModel = dependencyListManager.getDataModel(recordList);
		setSelectedItems(dataModel);
	}

	public void refreshDependencyList() {
		masterList = refreshRecords();
	}

	@Override
	protected Collection<Dependency> refreshRecords() {
		try {
			Collection<Dependency> records = dependencyDataManager.getDependencyList();
			return records;
		} catch (Exception e) {
			handleException(e);
			return null;
		}
	}

	@Override
	public void activate() {
		initialize();
		super.show();
	}

	@Override
	public String submit() {
		setModule(targetField);
		return super.submit();
	}

	@Override
	public void sortRecords() {
		sortRecords(recordList);
	}

	@Override
	public void sortRecords(List<Dependency> dependencyList) {
		Collections.sort(dependencyList, new Comparator<Dependency>() {
			public int compare(Dependency dependency1, Dependency dependency2) {
				String text1 = DependencyUtil.toString(dependency1);
				String text2 = DependencyUtil.toString(dependency2);
				return text1.compareTo(text2);
			}
		});
	}

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Cucurbitaria insecura Ellis

### Remarks
null


text:
package pq

import (
	"context"
	"database/sql"
	"database/sql/driver"
	"fmt"
	"io"
	"io/ioutil"
	"sync/atomic"
	"time"
)

// Implement the "QueryerContext" interface
func (cn *conn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) {
	list := make([]driver.Value, len(args))
	for i, nv := range args {
		list[i] = nv.Value
	}
	finish := cn.watchCancel(ctx)
	r, err := cn.query(query, list)
	if err != nil {
		if finish != nil {
			finish()
		}
		return nil, err
	}
	r.finish = finish
	return r, nil
}

// Implement the "ExecerContext" interface
func (cn *conn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) {
	list := make([]driver.Value, len(args))
	for i, nv := range args {
		list[i] = nv.Value
	}

	if finish := cn.watchCancel(ctx); finish != nil {
		defer finish()
	}

	return cn.Exec(query, list)
}

// Implement the "ConnBeginTx" interface
func (cn *conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) {
	var mode string

	switch sql.IsolationLevel(opts.Isolation) {
	case sql.LevelDefault:
		// Don't touch mode: use the server's default
	case sql.LevelReadUncommitted:
		mode = " ISOLATION LEVEL READ UNCOMMITTED"
	case sql.LevelReadCommitted:
		mode = " ISOLATION LEVEL READ COMMITTED"
	case sql.LevelRepeatableRead:
		mode = " ISOLATION LEVEL REPEATABLE READ"
	case sql.LevelSerializable:
		mode = " ISOLATION LEVEL SERIALIZABLE"
	default:
		return nil, fmt.Errorf("pq: isolation level not supported: %d", opts.Isolation)
	}

	if opts.ReadOnly {
		mode += " READ ONLY"
	} else {
		mode += " READ WRITE"
	}

	tx, err := cn.begin(mode)
	if err != nil {
		return nil, err
	}
	cn.txnFinish = cn.watchCancel(ctx)
	return tx, nil
}

func (cn *conn) Ping(ctx context.Context) error {
	if finish := cn.watchCancel(ctx); finish != nil {
		defer finish()
	}
	rows, err := cn.simpleQuery(";")
	if err != nil {
		return driver.ErrBadConn // https://golang.org/pkg/database/sql/driver/#Pinger
	}
	rows.Close()
	return nil
}

func (cn *conn) watchCancel(ctx context.Context) func() {
	if done := ctx.Done(); done != nil {
		finished := make(chan struct{}, 1)
		go func() {
			select {
			case <-done:
				select {
				case finished <- struct{}{}:
				default:
					// We raced with the finish func, let the next query handle this with the
					// context.
					return
				}

				// Set the connection state to bad so it does not get reused.
				cn.setBad()

				// At this point the function level context is canceled,
				// so it must not be used for the additional network
				// request to cancel the query.
				// Create a new context to pass into the dial.
				ctxCancel, cancel := context.WithTimeout(context.Background(), time.Second*10)
				defer cancel()

				_ = cn.cancel(ctxCancel)
			case <-finished:
			}
		}()
		return func() {
			select {
			case <-finished:
				cn.setBad()
				cn.Close()
			case finished <- struct{}{}:
			}
		}
	}
	return nil
}

func (cn *conn) cancel(ctx context.Context) error {
	// Create a new values map (copy). This makes sure the connection created
	// in this method cannot write to the same underlying data, which could
	// cause a concurrent map write panic. This is necessary because cancel
	// is called from a goroutine in watchCancel.
	o := make(values)
	for k, v := range cn.opts {
		o[k] = v
	}

	c, err := dial(ctx, cn.dialer, o)
	if err != nil {
		return err
	}
	defer c.Close()

	{
		bad := &atomic.Value{}
		bad.Store(false)
		can := conn{
			c:   c,
			bad: bad,
		}
		err = can.ssl(o)
		if err != nil {
			return err
		}

		w := can.writeBuf(0)
		w.int32(80877102) // cancel request code
		w.int32(cn.processID)
		w.int32(cn.secretKey)

		if err := can.sendStartupPacket(w); err != nil {
			return err
		}
	}

	// Read until EOF to ensure that the server received the cancel.
	{
		_, err := io.Copy(ioutil.Discard, c)
		return err
	}
}


text:
@font-face {
    font-family: 'codingfontregular';
    src: url('codingfont-webfont.eot');
    src: url('codingfont-webfont.eot?#iefix') format('embedded-opentype'),
         url('codingfont-webfont.woff') format('woff'),
         url('codingfont-webfont.ttf') format('truetype'),
         url('codingfont-webfont.svg#codingfontregular') format('svg');
    font-weight: normal;
    font-style: normal;
}


text:
So you want to contribute to brsHamcrest? Awesome! Go for it! You should give this document a read before starting anything. If you're new to Open Source projects on GitHub, I suggest you also give [this GitHub Guide on Contributing](https://guides.github.com/activities/contributing-to-open-source/) a read too.

## Source Code Location
The project git repository is [hosted on GitHub](https://github.com/imbenjamin/brsHamcrest). You should fork from this repository to commit changes, then create a Pull Request to merge back into the original repository. (See **Contributing Source Code**.)

## Creating an Issue, Idea or Question
If you have an issue, idea or question you want to create, use [GitHub Issues](https://github.com/imbenjamin/brsHamcrest/issues) and assign a label to match your issue:
- **bug**: You've found a bug when using brsHamcrest and wish to report it (See **Reporting Bugs**)
- **question**: You have a question about brsHamcrest
- **enhancement**: You have an idea about a new feature or improvement

Make sure to search existing Issues to see if your query has already been addressed.

### Reporting Bugs
If you are creating an Issue labeled as a **bug**, then please include the following information:
- **Overview of the Issue** - if an error is being thrown a stack trace helps
- **Motivation or Use Case** - explain why this is a bug for you. Perhaps provide a snippet of the code you are trying to execute.
- **brsHamcrest Version(s)** - is it a regression?
- **Roku Device Model and Firmware Version** - is this a problem with all Roku Devices?
- **Steps to Reproduce** - provide an example or an unambiguous set of steps.
- **Related Issues** - has a similar issue been reported before?
- **Suggest a Fix** - if you can't fix the bug yourself, perhaps you can point to what might be causing the problem (line of code or commit)

## Contributing Source Code
Contributions should be handled by [forking](https://help.github.com/articles/fork-a-repo/) brsHamcrest, creating commits and then creating a [Pull Request](https://help.github.com/articles/using-pull-requests/) to the original repository. All Pull Requests should be to merge into the `develop` branch.

Pull Request comments and commit messages should [properly reference](https://help.github.com/articles/closing-issues-via-commit-messages/) any Issues the Pull Request closes. There is a good [GitHub Blog entry](https://github.com/blog/1506-closing-issues-via-pull-requests) showing an example.


text:
class ChangeVenueConferenceAssociation < ActiveRecord::Migration
  class TempConference < ActiveRecord::Base
    self.table_name = 'conferences'
  end

  class TempVenue < ActiveRecord::Base
    self.table_name = 'venues'
    attr_accessible :conference_id
  end

  def change
    add_column :venues, :conference_id, :integer
    TempVenue.reset_column_information

    # Change association from venue and conference
    TempConference.all.each do |conference|
      if TempVenue.exists?(id: conference.venue_id)
        venue = TempVenue.find_by(id: conference.venue_id)
        venue.update_attributes(conference_id: conference.id)
      end
    end

    remove_column :conferences, :venue_id, :integer
  end
end


text:
git pull
rm -rf _site
jekyll build


text:
'use strict';

function Cube() {
  this.initialize();
}

Cube.prototype.initialize = function() {
  this.position = {x: 200, y: 100}; // px
  this.speed = 40;
  this.velocity = {x: 0, y: 0}; // px/s
  this.lifeTime = 0;
  this.inputs = [];
};

Cube.prototype.tick = function(interval) {
  this.lifeTime += interval;
  this.position.x += (this.velocity.x * interval / 1000);
  this.position.y += (this.velocity.y * interval / 1000);
};

Cube.prototype.process = function(start, stop) {
  var self = this;
  var lastInputTime = start;
  this.inputs.forEach(function(input) {
    var interval = input.time - lastInputTime;
    self.tick(interval);
    switch (input.action) {
      case 'up':
        self.velocity.y += input.press ? -self.speed : self.speed;
        break;
      case 'down':
        self.velocity.y += input.press ? self.speed : -self.speed;
        break;
      case 'right':
        self.velocity.x += input.press ? self.speed : -self.speed;
        break;
      case 'left':
        self.velocity.x += input.press ? -self.speed : self.speed;
        break;
    }
    lastInputTime = input.time;
  });
  this.inputs = [];
  var interval = stop - lastInputTime;
  this.tick(interval);
};

module.exports = Cube;


text:
layout: default
---

    {{ page.date | date:"%Y %B %d" }}
    {% if page.tags.size > 0 %}
    {{ page.tags | join: ', ' }}
    {% endif %}

{{ page.title }}

  {{ content }}

{% if site.disqus.shortname %}

{% endif %}


text:
#if !defined(BOOST_FUSION_ITERATOR_RANGE_IS_SEGMENTED_HPP_INCLUDED)
#define BOOST_FUSION_ITERATOR_RANGE_IS_SEGMENTED_HPP_INCLUDED

#include <boost/mpl/assert.hpp>
#include <boost/mpl/bool.hpp>

namespace boost { namespace fusion
{
    struct iterator_range_tag;

    template <typename Context>
    struct segmented_iterator;

    namespace extension
    {
        template <typename Tag>
        struct is_segmented_impl;

        // An iterator_range of segmented_iterators is segmented
        template <>
        struct is_segmented_impl<iterator_range_tag>
        {
        private:
            template <typename Iterator>
            struct is_segmented_iterator
              : mpl::false_
            {};

            template <typename Iterator>
            struct is_segmented_iterator<Iterator &>
              : is_segmented_iterator<Iterator>
            {};

            template <typename Iterator>
            struct is_segmented_iterator<Iterator const>
              : is_segmented_iterator<Iterator>
            {};

            template <typename Context>
            struct is_segmented_iterator<segmented_iterator<Context> >
              : mpl::true_
            {};

        public:
            template <typename Sequence>
            struct apply
              : is_segmented_iterator<typename Sequence::begin_type>
            {
                BOOST_MPL_ASSERT_RELATION(
                    is_segmented_iterator<typename Sequence::begin_type>::value
                  , ==
                  , is_segmented_iterator<typename Sequence::end_type>::value);
            };
        };
    }
}}

#endif


text:
//
//  NetBaseService.h
//  FrameWorkPractice
//
//  Created by 李赐岩 on 15/11/9.
//  Copyright © 2015年 李赐岩. All rights reserved.
//

#import <Foundation/Foundation.h>
typedef void(^success)();
typedef void(^failure)();
@interface NetBaseService : NSObject
/**
 * @brief POST网络请求
 *@parm 域名, 参数, 成功失败block
 */
+ (void)fetchPOSTHTTPMethodWithURL:(NSString *)url
                        parameter:(NSDictionary *)parameters
                          success:(success)successful
                          failure:(failure)failure;
/**
 * @brief get网络请求
 * @parm 域名, 参数, 成功失败block
 */
+ (void)fetchGETHTTPMethodWithURL:(NSString *)url
                        parameter:(NSDictionary *)parameters
                          success:(success)successful
                          failure:(failure)failure;

@end


text:
var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
var egret;
(function (egret) {
    var gui;
    (function (gui) {
        /**
         * @class egret.gui.OverrideBase
         * @classdesc
         * OverrideBase 类是视图状态所用的 override 类的基类。
         * @extends egret.HashObject
         * @implements egret.gui.IOverride
         */
        var OverrideBase = (function (_super) {
            __extends(OverrideBase, _super);
            function OverrideBase() {
                _super.call(this);
            }
            OverrideBase.prototype.initialize = function (parent) {
            };
            OverrideBase.prototype.apply = function (parent) {
            };
            OverrideBase.prototype.remove = function (parent) {
                if (parent === null) {
                }
            };
            /**
             * 从对象初始化,这是一个便利方法
             * @method egret.gui.OverrideBase#initializeFromObject
             * @param properties {any}
             * @returns {any}
             */
            OverrideBase.prototype.initializeFromObject = function (properties) {
                for (var p in properties) {
                    this[p] = properties[p];
                }
                return this;
            };
            return OverrideBase;
        })(egret.HashObject);
        gui.OverrideBase = OverrideBase;
        OverrideBase.prototype.__class__ = "egret.gui.OverrideBase";
    })(gui = egret.gui || (egret.gui = {}));
})(egret || (egret = {}));