text:
package GUI;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.activity.InvalidActivityException;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SpringLayout;
import javax.swing.SwingUtilities;

import startup.Start;
import tournament.Tournament;
import tournament.Tournament.Side;
import API.Match;
import API.Player;
import API.TournamentTree.Node;
import API.TourneyNight;
import DataHandle.ReadExcel;
import DataHandle.WriteExcel;

public class MainView extends JFrame implements ActionListener {

	JFrame frame;
	JPanel panel;
	JPanel endPanel;
	JButton startTourney;
	JButton importTourney;
	JLabel label;
	JTextArea players;
	public static Set<Player> eligablePlayers;
	public static Set<Player> playingPlayers;
	private int thisWeek;
	Tournament tournament;
	Map<String, Node<Match>> buttonToGame;
	public static boolean doubles;
	String bSideMatchConjunctive;

	private KeyListener focusChanger;

	final Color white = new Color(255, 255, 255);
	final Dimension buttonDimension = new Dimension(BUTTON_WIDTH, BUTTON_HEIGHT);
	final Dimension dialogDimension = new Dimension(500, 300);

	private static int WIDTH = 1200;
	private static int HEIGHT = 800;
	private static int BUTTON_WIDTH = 200;
	private static int BUTTON_HEIGHT = 40;

	public enum Source {
		BUTTON
	}

	public MainView(int thisWeek) {
		this.thisWeek = thisWeek;
		playingPlayers = new HashSet<Player>();
		buttonToGame = new HashMap<String, Node<Match>>();
		panel = new JPanel();
		label = new JLabel();
		getContentPane().add(panel);
		focusChanger = new KeyListener(this);
		setButtons();
		panel.add(startTourney);
		panel.add(importTourney);
		panel.add(label);
		setLocationRelativeTo(null);
	}

	private void setButtons() {
		startTourney = new JButton("Start Tournament");
		startTourney.addActionListener(this);
		startTourney.addKeyListener(focusChanger);
		startTourney.setVisible(true);

		importTourney = new JButton("Import Tournament");
		importTourney.addActionListener(this);
		importTourney.addKeyListener(focusChanger);
		importTourney.setVisible(true);
	}

	@Override
	public void actionPerformed(ActionEvent event) {
		if (event.getSource() == startTourney) {
			if(Start.file == null || !Start.fileWasRead){
				new MessageDialog("You must select an xls file for the tournament.");
			} else{
			tourneyInitView();
			}
		} else if (event.getSource() == importTourney) {
			FileChooserDialog fcd = new FileChooserDialog();
			if(Start.file == null){
				new MessageDialog("You must select an xls file for the tournament.");
			} else{
			ReadExcel read = new ReadExcel();
			MainView.eligablePlayers = read.read();
			}
		}

	}

	public void tourneyInitView() {

		getContentPane().removeAll();
		setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));

		add(Box.createRigidArea(new Dimension(0, 50)));
		JPanel panel = new JPanel();
		panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
		panel.setLayout(new GridLayout(1, 2, 5, 5));
		players = new JTextArea();
		players.addKeyListener(focusChanger);
		players.setLineWrap(true);
		players.setPreferredSize(new Dimension(200, 100));
		players.setBorder(BorderFactory.createLineBorder(new Color(32, 23, 23),
				3));
		JScrollPane scroll = new JScrollPane(players);
		scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		panel.add(scroll);
		JLabel comment = new JLabel(
				"
Please enter the names of the players "
						+ "in the tournament,"
						+ " seperated by a new line or comma
");
		comment.setPreferredSize(new Dimension(100, 30));
		panel.add(comment);

		add(panel);
		add(Box.createRigidArea(new Dimension(0, 50)));

		JButton start = new JButton("Start Tourney");
		start.addKeyListener(focusChanger);
		start.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent event) {
				String input = players.getText();
				String[] playerNames = input.split("\n|\\, |\\,");
				List<String> newPlayers = new ArrayList<String>();
				Player player = null;
				for (String s : playerNames) {
					boolean exists = false;
					for (Player p : eligablePlayers) {
						if (p.getName().equalsIgnoreCase(s)) {
							exists = true;
							player = p;
							break;
						}
					}
					if (!exists) {
						newPlayers.add(s);
					} else {
						playingPlayers.add(player);
					}
				}
				if (!newPlayers.isEmpty()) {
					NewPlayersDialog npd = new NewPlayersDialog(newPlayers);
					npd.setVisible(true);
					npd.setAlwaysOnTop(true);
					return;
				}
				if (tournament == null) {
					tournament = new Tournament(thisWeek, playingPlayers);
				}
				tourneyView();
			}
		});

		start.setAlignmentX(0.5f);
		add(start);

		setTitle("Tournament Setup");
		setSize(100, 200);
		pack();
	}

	public void tourneyView() {
		bSideMatchConjunctive = doubles ? " and " : " vs ";
		getContentPane().removeAll();
		SpringLayout layout = new SpringLayout();
		setLayout(layout);

		int rounds = Tournament.findExponentBase2(playingPlayers.size());

		List<Node<Match>> aSidePlayableGames = tournament.getaSide()
				.getAllPlayableGames();
		List<Node<Match>> bSidePlayableGames = tournament.getbSide()
				.getAllPlayableGames();

		if (aSidePlayableGames.isEmpty() && bSidePlayableGames.isEmpty()) {
			Node<Match> finalGame = tournament.getfinalGame();
			if (!tournament.isFinished()) {
				JLabel finalLabel = new JLabel("FINAL GAME");
				finalLabel.setFont(new Font(null, Font.BOLD, 30));
				add(finalLabel);
				layout.putConstraint(SpringLayout.WEST, finalLabel, 10,
						SpringLayout.WEST, this.getContentPane());
				layout.putConstraint(SpringLayout.NORTH, finalLabel, 15,
						SpringLayout.NORTH, this.getContentPane());
				String buttonName = finalGame.getMatch().getPlayerOne()
						.getName()
						+ " vs "
						+ finalGame.getMatch().getPlayerTwo().getName();
				buttonToGame.put(buttonName, finalGame);

				JButton button = new JButton(buttonName);
				button.addKeyListener(focusChanger);
				button.addMouseListener(new ButtonClickListener(finalGame));
				button.addActionListener(new ButtonListener());
				add(button);

				layout.putConstraint(SpringLayout.WEST, button, 10,
						SpringLayout.WEST, this.getContentPane());
				layout.putConstraint(SpringLayout.NORTH, button, 15,
						SpringLayout.SOUTH, finalLabel);
			} else {
				JLabel winnerLabel = new JLabel("Congratulations "
						+ finalGame.getMatch().getWinner().getName() + "!");
				winnerLabel.setFont(new Font(null, Font.BOLD, 30));
				add(winnerLabel);
				layout.putConstraint(SpringLayout.WEST, winnerLabel, 10,
						SpringLayout.WEST, this.getContentPane());
				layout.putConstraint(SpringLayout.NORTH, winnerLabel, 15,
						SpringLayout.NORTH, this.getContentPane());

				JButton close = new JButton("Close");
				close.addKeyListener(focusChanger);
				close.addActionListener(new ActionListener() {

					public void actionPerformed(ActionEvent event) {
						playingPlayers.addAll(eligablePlayers);
						WriteExcel write = new WriteExcel();
						write.writeWeekly(playingPlayers);
						dispose();
					}
				});

				add(close);
				layout.putConstraint(SpringLayout.WEST, close, 30,
						SpringLayout.WEST, this.getContentPane());
				layout.putConstraint(SpringLayout.NORTH, close, 30,
						SpringLayout.SOUTH, winnerLabel);

			}

		} else {
			int ASideSize = (int) Math.pow(2, rounds) + 1;
			JPanel mainPanel = new JPanel();
			// mainPanel.setPreferredSize(new Dimension(1600, 800));
			mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
			mainPanel.setLayout(layout);
			mainPanel.setPreferredSize(new Dimension(BUTTON_WIDTH
					* (rounds + 8), BUTTON_HEIGHT * (2 * ASideSize)));
			setLayout(new BorderLayout());
			JScrollPane scroll = new JScrollPane(mainPanel,
					JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
					JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
			scroll.getVerticalScrollBar().setUnitIncrement(15);
			add(scroll, BorderLayout.CENTER);
			JLabel aSideLabel = new JLabel("A Side Games");
			aSideLabel.setFont(new Font(null, Font.BOLD, 20));
			mainPanel.add(aSideLabel);
			layout.putConstraint(SpringLayout.WEST, aSideLabel, 10,
					SpringLayout.WEST, this.getContentPane());
			layout.putConstraint(SpringLayout.NORTH, aSideLabel, 15,
					SpringLayout.NORTH, this.getContentPane());

			JPanel aPanel = new JPanel();
			aPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
			aPanel.setLayout(new GridLayout(1, rounds, 5, 0));
			layout.putConstraint(SpringLayout.WEST, aPanel, 5,
					SpringLayout.WEST, this.getContentPane());
			layout.putConstraint(SpringLayout.NORTH, aPanel, 20,
					SpringLayout.NORTH, aSideLabel);
			mainPanel.add(aPanel);
			int spacing = 0;
			for (int x = 1; x <= rounds; x++) {
				List<Node<Match>> aSideRoundGames = tournament.getaSide()
						.getRound(x);
				JPanel panel = new JPanel();
				panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
				panel.setLayout(new GridLayout(ASideSize, 1, 5, 5));
				aPanel.add(panel);
				if (x > 1) {
					spacing += Math.pow(2, (x - 2));
				}
				for (int y = 0; y < spacing; y++) {
					panel.add(new JLabel(""));
				}
				Iterator<Node<Match>> aSideIterator = aSideRoundGames
						.iterator();
				Node<Match> game = null;
				while (aSideIterator.hasNext()) {
					game = aSideIterator.next();
					String buttonName = "";
					Match match = game.getMatch();
					if (match.getPlayerOne() != null
							|| match.getPlayerTwo() != null) {
						if (match.getPlayerOne() != null) {
							if (match.getPlayerTwo() != null) {
								if (match.getWinner() != null) {
									buttonName = ""
											+ match.getWinner().getName()
													.toUpperCase() + " ("
											+ match.getWinnerScore()
											+ ") beats "
											+ match.getLoser().getName() + "("
											+ match.getLoserScore() + ")";
								} else {
									buttonName = match.getPlayerOne().getName()
											+ " vs "
											+ match.getPlayerTwo().getName();
								}
							} else {
								buttonName = match.getPlayerOne().getName();
							}
						} else if (match.getPlayerTwo() != null) {
							buttonName = match.getPlayerTwo().getName();
						}
						if (match.getByePlayer() == null) {
							buttonName = "
Round " + game.getRound()
									+ " : " + buttonName + "
";
							if (match.getWinner() == null) {
								buttonToGame.put(buttonName, game);
								JButton button = new JButton(buttonName);
								button.setPreferredSize(buttonDimension);
								button.addMouseListener(new ButtonClickListener(
										game));
								button.addKeyListener(focusChanger);
								button.addActionListener(new ButtonListener());
								panel.add(button);
							} else {
								panel.add(new JLabel(buttonName));
							}
						} else {
							JLabel label = new JLabel(buttonName
									+ " was given a bye");
							panel.add(label);
						}
					} else {
						JLabel label = new JLabel("Round " + game.getRound()
								+ " : " + "No Players");
						panel.add(label);
					}
					if (aSideIterator.hasNext()) {
						for (int y = 0; y < (spacing * 2 + 1); y++) {
							JLabel label = new JLabel("");
							label.setBackground(white);
							panel.add(label);
						}
					}
				}
			}
			JLabel bSideLabel = new JLabel("B Side Games");
			bSideLabel.setFont(new Font(null, Font.BOLD, 20));
			mainPanel.add(bSideLabel);
			layout.putConstraint(SpringLayout.WEST, bSideLabel, 10,
					SpringLayout.WEST, this.getContentPane());
			layout.putConstraint(SpringLayout.NORTH, bSideLabel, 5,
					SpringLayout.SOUTH, aPanel);

			JPanel bPanel = new JPanel();
			bPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
			bPanel.setLayout(new GridLayout(1, rounds, 5, 5));
			layout.putConstraint(SpringLayout.WEST, bPanel, 5,
					SpringLayout.WEST, this.getContentPane());
			layout.putConstraint(SpringLayout.NORTH, bPanel, 20,
					SpringLayout.SOUTH, bSideLabel);
			mainPanel.add(bPanel);

			spacing = 0;
			for (int x = 1; x <= rounds; x++) {
				List<Node<Match>> bSideRoundGames = tournament.getbSide()
						.getRound(x);
				Iterator<Node<Match>> bSideIterator = bSideRoundGames
						.iterator();

				Node<Match> game = null;

				JPanel panelOne = new JPanel();
				panelOne.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
				panelOne.setLayout(new GridLayout(
						(playingPlayers.size() * 3 + 1), 1, 5, 5));
				bPanel.add(panelOne);

				for (int y = 0; y < spacing; y++) {
					JLabel label = new JLabel("");
					label.setBackground(white);
					panelOne.add(label);
				}

				List<Node<Match>> parentGames = new ArrayList<Node<Match>>();
				while (bSideIterator.hasNext()) {
					game = bSideIterator.next();

					if (bSideRoundGames.contains(game.getLeftChild())) {
						parentGames.add(game);

					} else {

						addToBSideGrid(game, spacing, panelOne);
						for (int y = 0; y < (spacing * 2 + 1); y++) {
							JLabel label = new JLabel("");
							label.setBackground(white);
							panelOne.add(label);
						}
					}
				}

				spacing += Math.pow(2, (x - 2));
				if (x > 1) {

					JPanel panelTwo = new JPanel();
					panelTwo.setBorder(BorderFactory.createEmptyBorder(5, 5, 5,
							5));
					panelTwo.setLayout(new GridLayout(
							(playingPlayers.size() * 3 + 1), 1, 5, 5));
					bPanel.add(panelTwo);

					if (x == rounds) {
						// last round the spacing should be the same as
						// the previous round
						spacing = (spacing - 1) / 2;
					}
					for (int y = 0; y < spacing; y++) {
						JLabel label = new JLabel("");
						label.setBackground(white);
						panelTwo.add(label);
					}

					// second column of round
					for (Node<Match> parentGame : parentGames) {
						addToBSideGrid(parentGame, spacing, panelTwo);
						for (int y = 0; y < (spacing * 2 + 1); y++) {
							JLabel label = new JLabel("");
							label.setBackground(white);
							panelTwo.add(label);
						}
					}
				}
			}
			createEndPanel();
		}
		setTitle("Match Manager");
		setSize(WIDTH, HEIGHT);
	}

	private void addToBSideGrid(Node<Match> game, int spacing, JPanel panel) {
		String buttonName = "";
		Match match = game.getMatch();
		if (match.getPlayerOne() != null || match.getPlayerTwo() != null) {
			if (match.getPlayerOne() != null) {
				if (match.getPlayerTwo() != null) {
					if (match.getWinner() != null) {
						buttonName = ""
								+ match.getWinner().getName().toUpperCase()
								+ " (" + match.getWinnerScore()
								+ ") beats " + match.getLoser().getName() + "("
								+ match.getLoserScore() + ")";
					} else {
						buttonName = match.getPlayerOne().getName()
								+ bSideMatchConjunctive
								+ match.getPlayerTwo().getName();
					}
				} else {
					buttonName = match.getPlayerOne().getName();
				}
			} else if (match.getPlayerTwo() != null) {
				buttonName = match.getPlayerTwo().getName();
			}
			buttonName = "
Round " + game.getRound() + " : "
					+ buttonName + "
";
			if (match.getByePlayer() == null) {
				if (match.getWinner() == null) {
					buttonToGame.put(buttonName, game);
					JButton button = new JButton(buttonName);
					button.addMouseListener(new ButtonClickListener(game));
					button.addKeyListener(focusChanger);
					button.setPreferredSize(buttonDimension);
					button.addActionListener(new ButtonListener());
					panel.add(button);
				} else {
					panel.add(new JLabel(buttonName));
				}
			} else {
				JLabel label = new JLabel(buttonName + " was given a bye");
				panel.add(label);
			}
		} else {
			JLabel label = new JLabel("Round " + game.getRound() + " : "
					+ "No Players");
			panel.add(label);
		}
	}

	private void createEndPanel() {
		if (endPanel == null) {
			endPanel = new JPanel();
			endPanel.setLayout(new GridLayout(10, 1, 0, 10));
			endPanel.setBorder(BorderFactory.createLineBorder(new Color(10, 90,
					30), 5));
			add(endPanel, BorderLayout.LINE_END);

			JButton close = new JButton(
					"
End tournament without saving
");
			close.setPreferredSize(new Dimension(150, 0));
			close.addKeyListener(focusChanger);
			close.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent event) {
					dispose();
				}
			});
			endPanel.add(close);

			JButton finish = new JButton(
					"
Finish tournament early
");

			finish.addKeyListener(focusChanger);
			finish.setPreferredSize(new Dimension(150, 0));
			finish.addActionListener(new ActionListener() {

				public void actionPerformed(ActionEvent event) {
					playingPlayers.addAll(eligablePlayers);
					WriteExcel write = new WriteExcel();
					write.writeWeekly(playingPlayers);
					dispose();
				}
			});
			endPanel.add(finish);

			JButton playDoubles = new JButton(
					(doubles) ? "
Split Doubles
"
							: "
Play Doubles
");
			playDoubles.setPreferredSize(new Dimension(150, 0));
			playDoubles.addKeyListener(focusChanger);
			playDoubles.addActionListener(new ActionListener() {

				public void actionPerformed(ActionEvent event) {
					doubles = !doubles;
					if (doubles)
						((JButton) event.getSource())
								.setText("
Split Doubles
");
					else {
						((JButton) event.getSource())
								.setText("
Play Doubles
");

					}
					createEndPanel();

				}
			});
			endPanel.add(playDoubles);

			JButton insertPlayer = new JButton(
					"
Insert a player
");
			insertPlayer.setPreferredSize(new Dimension(150, 0));
			insertPlayer.addKeyListener(focusChanger);
			insertPlayer.addActionListener(new ActionListener() {

				public void actionPerformed(ActionEvent event) {
					JDialog d = new JDialog();
					d.setLayout(new BoxLayout(d.getContentPane(),
							BoxLayout.Y_AXIS));
					d.setSize(dialogDimension);
					d.setVisible(true);
					d.add(Box.createRigidArea(new Dimension(0, 50)));
					JPanel panel = new JPanel();
					panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
					panel.setLayout(new GridLayout(1, 2, 5, 5));
					players = new JTextArea();
					players.addKeyListener(focusChanger);
					players.setLineWrap(true);
					players.setPreferredSize(new Dimension(200, 100));
					players.setBorder(BorderFactory.createLineBorder(new Color(
							32, 23, 23), 3));
					JScrollPane scroll = new JScrollPane(players);
					scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
					panel.add(scroll);
					JLabel comment = new JLabel(
							"
Please enter the names of the players "
									+ "to be entered in the tournament,"
									+ " seperated by a new line or comma
");
					comment.setPreferredSize(new Dimension(100, 30));
					panel.add(comment);

					d.add(panel);
					d.add(Box.createRigidArea(new Dimension(0, 50)));
					JButton submit = new JButton("Submit");
					submit.setAlignmentX(0.5f);
					d.add(submit);
					d.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
					final JDialog finalDialog = d;
					submit.addKeyListener(focusChanger);

					submit.addActionListener(new ActionListener() {

						public void actionPerformed(ActionEvent event) {
							String input = players.getText();
							String[] playerNames = input.split("\n|\\, |\\,");

							List<String> newPlayers = new ArrayList<String>();
							List<Player> insertPlayers = new ArrayList<Player>();
							Player player = null;
							for (String s : playerNames) {
								boolean exists = false;
								for (Player p : eligablePlayers) {
									if (p.getName().equalsIgnoreCase(s)) {
										exists = true;
										player = p;
										break;
									}
								}
								if (!exists) {
									newPlayers.add(s);
									insertPlayers.add(new Player(s));
								} else {
									insertPlayers.add(player);
									playingPlayers.add(player);
								}
							}
							if (!newPlayers.isEmpty()) {
								NewPlayersDialog npd = new NewPlayersDialog(
										newPlayers);
								npd.setVisible(true);
								npd.setAlwaysOnTop(true);
								return;
							}

							List<Node<Match>> aSideGameList = tournament
									.getRound(tournament.getaSide(), 1);

							Iterator<Node<Match>> gameListIterator = aSideGameList
									.iterator();
							Node<Match> game = null;

							// randomize player entry
							Collections.shuffle(insertPlayers);
							Iterator<Player> pIterator = insertPlayers
									.iterator();
							boolean playableGames = false;
							List<Node<Match>> insertableGames = new ArrayList<Node<Match>>();
							List<Node<Match>> byeGames = new ArrayList<Node<Match>>();
							while (pIterator.hasNext()) {
								Match match = null;
								if (gameListIterator.hasNext()) {
									gameIterator: while (gameListIterator
											.hasNext()) {
										game = gameListIterator.next();
										match = game.getMatch();
										if (!playableGames) {
											playableGames = (match.getWinner() == null) ? true
													: false;
										}

										if (game.getMatch().getPlayerOne() != null
												&& game.getMatch()
														.getPlayerTwo() != null) {
											continue gameIterator;
										} else if (((game.getMatch()
												.getPlayerOne() == null) != (game
												.getMatch().getPlayerTwo() == null))
												&& (game.getMatch().getWinner() == null && game
														.getMatch()
														.getByePlayer() == null)) {
											insertableGames.add(game);
										} else if (game.getMatch()
												.getByePlayer() != null) {
											if (game.getParent()
													.getMatch()
													.getPlayerOne()
													.equals(game.getMatch()
															.getByePlayer())) {
												game.getParent().getMatch()
														.setPlayerOne(null);
											} else if (game
													.getParent()
													.getMatch()
													.getPlayerTwo()
													.equals(game.getMatch()
															.getByePlayer())) {
												game.getParent().getMatch()
														.setPlayerTwo(null);
											}
											game.getMatch().setByePlayer(null);
											insertableGames.add(game);
											// byeGames.add(game.getCousin());
										}
									}
									if (!playableGames) {
										int available = byeGames.size()
												+ insertableGames.size()
												- insertPlayers.size();
										if (available < 0) {
											if (byeGames.size()
													+ insertableGames.size() == 0) {
												MessageDialog md = new MessageDialog(
														" No spaces available for new players ");
											} else {
												MessageDialog md = new MessageDialog(
														" Not enough available spaces to enter players, only "
																+ byeGames
																		.size()
																+ insertableGames
																		.size()
																+ " spots available");
											}
											return;
										}
									}
									if (!insertableGames.isEmpty()) {

										boolean doLow = (playingPlayers.size() % 2 == 0) ? true
												: false;
										tournament.getaSide().insertPlayers(
												insertPlayers, doLow);
										pIterator = insertPlayers.iterator();
									}
									if (pIterator.hasNext()) {
										if (playableGames) {
											// if bside cousins have bye
											// players,
											// room for inserted players, else
											// cannot insert players
											tournament.expandBracket();
											this.actionPerformed(null);
											finalDialog.dispose();
											tourneyView();
											return;
										}
									}
									/**
									 * inserting on BSide
									 */
									// if (pIterator.hasNext()) {
									//
									// if (!byeGames.isEmpty()) {
									//
									// String s = null;
									// for (Player pl : insertPlayers) {
									// s += pl.getName() + " - ";
									// }
									// MessageDialog md = new MessageDialog(
									// "Enter the following players on BSide?\n"
									// + s, true);
									// if (md.isConfirmed()) {
									// tournament.getbSide()
									// .startPlayers(
									// insertPlayers);
									// tournament.getbSide()
									// .insertPlayers(
									// insertPlayers,
									// false);
									// pIterator = insertPlayers
									// .iterator();
									// }
									// }
									// }
									if (pIterator.hasNext()) {
										new MessageDialog(
												"Players could not be allocated");
										break;
									}
								}

							}
							finalDialog.dispose();
							tourneyView();
							SwingUtilities
									.updateComponentTreeUI(getContentPane());

						}
					});
				}
			});
			endPanel.add(insertPlayer);
			for (int y = 0; y < 6; y++) {
				endPanel.add(new JLabel(""));
			}
		} else {
			add(endPanel, BorderLayout.LINE_END);
		}
	}

	public class ButtonListener implements ActionListener {

		public void actionPerformed(ActionEvent event) {
			Node<Match> game = buttonToGame.get(event.getActionCommand());
			Match match = game.getMatch();
			try {
				CurrentGameDialog cgd = new CurrentGameDialog(game);
				cgd.setVisible(true);
				cgd.setAlwaysOnTop(true);
			} catch (InvalidActivityException iae) {
				// TODO: Error dialog
				System.out.println(iae.getMessage());
				iae.printStackTrace();
			}
			if (match.getByePlayer() == null && match.getWinner() != null) {
				tournament.finishGame(game);
			} else if (match.getByePlayer() != null) {
				if (game == tournament.getaSide().getRoot()) {
					tournament.getfinalGame().getMatch()
							.setPlayerOne(match.getByePlayer());
				} else if (game == tournament.getbSide().getRoot()) {
					tournament.getfinalGame().getMatch()
							.setPlayerTwo(match.getByePlayer());
				} else {

					Match parentMatch = game.getParent().getMatch();
					if (parentMatch.getPlayerOne() == null) {
						parentMatch.setPlayerOne(match.getByePlayer());
					} else if (parentMatch.getPlayerTwo() == null) {
						parentMatch.setPlayerTwo(match.getByePlayer());
					}
				}
			}
			tourneyView();
			SwingUtilities.updateComponentTreeUI(getContentPane());
		}
	}

	private class ButtonClickListener extends ClickListener {
		JMenuItem doRevert;
		Node<Match> game;

		protected ButtonClickListener(Node<Match> game) {
			this.game = game;
			doRevert = new JMenuItem("Revert to previous games");
			doRevert.addMouseListener(this);
		}

		@Override
		public void mouseReleased(MouseEvent e) {
		}

		@Override
		public void mousePressed(MouseEvent e) {
			check(e);
		}

		private void check(MouseEvent e) {
			Match match1 = null;
			Match match2 = null;
			Node<Match> childGame = null;
			Player playerOne = game.getMatch().getPlayerOne();
			Player playerTwo = game.getMatch().getPlayerTwo();
			if (e.isPopupTrigger() || e.getSource() == doRevert) {
				if (game.getLeftChild() != null) {
					if (playerOne != null) {
						if (playerOne.equals(game.getLeftChild().getMatch()
								.getPlayerOne())
								|| playerOne.equals(game.getLeftChild()
										.getMatch().getPlayerTwo())) {
							childGame = game.getLeftChild();
							match1 = childGame.getMatch();

						} else if (game.getRightChild() != null) {
							if (playerOne.equals(game.getRightChild()

							.getMatch().getPlayerOne())
									|| playerOne.equals(game.getRightChild()
											.getMatch().getPlayerTwo())) {
								childGame = game.getRightChild();
								match1 = childGame.getMatch();
							}
						}

					}
					if (playerTwo != null) {
						if (playerTwo.equals(game.getLeftChild().getMatch()
								.getPlayerOne())
								|| playerTwo.equals(game.getLeftChild()
										.getMatch().getPlayerTwo())) {
							childGame = game.getLeftChild();
							match2 = childGame.getMatch();

						} else if (game.getRightChild() != null) {
							if (playerTwo.equals(game.getRightChild()
									.getMatch().getPlayerOne())
									|| playerTwo.equals(game.getRightChild()
											.getMatch().getPlayerTwo())) {
								childGame = game.getRightChild();
								match2 = childGame.getMatch();
							}
						}

					}
					Match cousinMatch = null;
					if (game.getSide() == Side.ASIDE) {
						cousinMatch = childGame.getCousin().getMatch();

						if (cousinMatch.getWinner() == null) {
							if (e.isPopupTrigger()) {
								JPopupMenu popUp = new JPopupMenu();
								popUp.add(doRevert);
								popUp.show(e.getComponent(), e.getX(), e.getY());
								return;
							}

							else if (e.getSource() == doRevert) {
								if (match1 != null) {
									if (match1.getByePlayer() == null) {
										if (match1.getLoser().equals(
												cousinMatch.getPlayerOne())) {
											cousinMatch.setPlayerOne(null);
										} else if (match1.getLoser().equals(
												cousinMatch.getPlayerTwo())) {
											cousinMatch.setPlayerTwo(null);
										}
									}
								}
								if (match2 != null) {
									if (match2.getByePlayer() == null) {
										if (match2.getLoser().equals(
												cousinMatch.getPlayerOne())) {
											cousinMatch.setPlayerOne(null);
										} else if (match2.getLoser().equals(
												cousinMatch.getPlayerTwo())) {
											cousinMatch.setPlayerTwo(null);
										}
									}
								}

								if (match1 != null) {
									resetMatch(match1, game.getSide());
								}
								if (match2 != null) {
									resetMatch(match2, game.getSide());
								}
								game.setMatch(new Match());
								tourneyView();
							}
						}
					}

					else if (game.getSide() == Side.BSIDE) {
						if (e.isPopupTrigger()) {
							JPopupMenu popUp = new JPopupMenu();
							popUp.add(doRevert);
							popUp.show(e.getComponent(), e.getX(), e.getY());
							return;
						} else if (e.getSource() == doRevert) {
							if (game.getCousin() != null) {
								cousinMatch = game.getCousin().getMatch();
								if (match1 == null) {
									match1 = cousinMatch;
								} else if (match2 == null) {
									match2 = cousinMatch;
								}

							}

							if (match1 != null) {
								resetMatch(match1, game.getSide());
							}
							if (match2 != null) {
								resetMatch(match2, game.getSide());
							}
							game.setMatch(new Match());
						}
						tourneyView();
						System.out
								.println("end of bside reset; tourney view called");

					} else if (game.getSide() == Side.FINAL) {
						if (e.isPopupTrigger()) {
							JPopupMenu popUp = new JPopupMenu();
							popUp.add(doRevert);
							popUp.show(e.getComponent(), e.getX(), e.getY());
							return;
						} else if (e.getSource() == doRevert) {
							if (match1 != null) {
								resetMatch(match1, game.getLeftChild()
										.getSide());
							}
							game.setMatch(new Match());
							tourneyView();
						}
					}
				}

				SwingUtilities.updateComponentTreeUI(getContentPane());
				return;
			}

		}

		private void resetMatch(Match match, Side side) {
			if (match.getByePlayer() == null) {
				Player winner = null;
				Player loser = null;
				TourneyNight tn = null;
				winner = match.getWinner();
				if (winner != null) {
					tn = winner.getWeekly().get(thisWeek);
					tn.setGamesPlayed(tn.getGamesPlayed() - 1);
					tn.setBallsPocketed(tn.getBallsPocketed()
							- match.getWinnerScore());
					tn.setHandicapPoints(tn.getHandicapPoints()
							- match.getWinnerHandicapPoints());
					if (side == Side.ASIDE) {
						tn.setBasicPoints(tn.getBasicPoints() - 3);
					} else {
						tn.setBasicPoints(tn.getBasicPoints() - 2);
					}
				}
				loser = match.getLoser();
				if (loser != null) {
					tn = loser.getWeekly().get(thisWeek);
					tn.setGamesPlayed(tn.getGamesPlayed() - 1);
					tn.setBallsPocketed(tn.getBallsPocketed()
							- match.getLoserScore());
					tn.setHandicapPoints(tn.getHandicapPoints()
							- match.getLoserHandicapPoints());
					tn.setBasicPoints(tn.getBasicPoints() - 1);
				}
				match.setLoserScore(0);
				match.setWinnerScore(0);
				match.setWinner(null);
				match.setLoser(null);
				match.setLoserHandicapPoints(0);
				match.setWinnerHandicapPoints(0);
				String s = "";

				if (match.getPlayerOne() != null) {
					s += match.getPlayerOne().getName()
							+ " handicap: "
							+ match.getPlayerOne().getHandicap()
							+ " total handicap points: "
							+ match.getPlayerOne().getWeekly().get(thisWeek)
									.getHandicapPoints();
				}
				if (match.getPlayerTwo() != null) {
					s += "  "
							+ match.getPlayerTwo().getName()
							+ " handicap : "
							+ match.getPlayerTwo().getHandicap()
							+ " total handicap points: "
							+ match.getPlayerTwo().getWeekly().get(thisWeek)
									.getHandicapPoints();
				}
				System.out.println("***RESET MATCH***\n\n" + s + "\n");
			} else {
				match.setByePlayer(null);
			}
		}
	}
}


text:
from __future__ import unicode_literals
from ...vocab import Vocab
from ...tokens.doc import Doc

def test_token_is_hashable():
    doc = Doc(Vocab(), ['hello', 'world'])
    token = doc[0]
    s = set([token])
    items = list(s)
    assert items[0] is token

redpajama_set_name: RedPajamaGithub


text:
'use strict'

const leaf = ({ privates, core }) => {
  privates.leaf = function*(){
    const { getApi } = core

    for( let current of privates.dfs() )
      if( current.firstChild === undefined ){
        yield current
      }
  }

  privates.registerGenerator( 'leaf' )
}

module.exports = leaf


text: opposite = lambda n: -n


text:
class AddDefaultToBudget < ActiveRecord::Migration[5.2]
  def change
  	add_column :draft_budgets, :default, :boolean, default: :false
  end
end


text:
"""
Analyse the UCSC promoters for binding sites.
"""

import biopsy.data.ucsc; reload(biopsy.data.ucsc)
import biopsy.data.ucsc as UCSC
import biopsy.transfac as T
import logging
from IPython.kernel import client
from itertools import imap

def parse_record_id(_id):
    fields = _id.split('_')
    assert 7 == len(fields)
    nm_id = int(fields[1])
    assert fields[2] == 'up'
    assert fields[3] == '5000'
    chr = fields[4]
    pos = int(fields[5])
    tag = fields[6]
    return nm_id, chr, pos, tag

def make_sequence_vec(l):
    import biopsy
    result = biopsy.SequenceVec()
    result.extend(l)
    return result

def get_TRANSFAC_vertebrate_pssms():
    return [str(m.acc) for m in T.Matrix.all() if m.name.startswith('V')]

def calculate_p_binding_from_hits(hits):
    from collections import defaultdict
    p_not_binding = defaultdict(lambda: 1.)
    for hit in hits:
        p_not_binding[hit.binder] *= (1.-hit.p_binding)
    return dict((binder, 1.-p) for binder, p in p_not_binding.iteritems())

def score_pssms_on_record(pssms, record):
    import biopsy
    promoter_hits = biopsy.score_pssms_on_sequence(make_sequence_vec(pssms), record.seq.tostring())
    promoter_p_binding = calculate_p_binding_from_hits(promoter_hits)
    return promoter_p_binding

def factor_info(f):
    return "%s;%s" % (f.name, ";".join(species.replace(',', ' -').replace(';', ' -').replace(':', ' -') for species in  f.species))

logging.basicConfig(level=logging.INFO)

pssms = get_TRANSFAC_vertebrate_pssms()
logging.info('Have %d PSSMs from TRANSFAC', len(pssms))

#
# Distribute function to engines
#
mec = client.MultiEngineClient()
mec.push_function(
    dict(
        calculate_p_binding_from_hits=calculate_p_binding_from_hits,
        make_sequence_vec=make_sequence_vec,
    )
)

#
# pass tasks to engines
#
logging.info('Passing tasks to engines')
tc = client.TaskClient()
task_ids = []
task_args = dict()
promoters = dict()
positions_analysed = set()
skipped = set()
for record in UCSC.upstream('hg19', length=5000):

    #
    # Parse record id
    #
    try:
        nm_id, chr, pos, tag = parse_record_id(record.id)
    except:
        logging.warning('Skipping unparseable record ID: %s', record.id)
	skipped.add(record.id)
    else:
        logging.debug('Creating task for NM_%-16d %6s %10d %s %r', nm_id, chr, pos, tag, record.seq)
        promoters[nm_id] = chr, pos, tag, record
        pos_key = chr, pos, tag

        #
        # Check we have not analysed this genomic position
        #
        if pos_key not in positions_analysed:

            #
            # Pass task to engine
            #
            args = (map(str, pssms), record)
            task = client.MapTask(score_pssms_on_record, args)
            task_id = tc.run(task, block=False)
            task_ids.append(task_id)
            task_args[task_id] = args
            positions_analysed.add(pos_key)
            #if len(task_ids) > 4: break # for debugging
logging.info('Skipped %d unparseable records', len(skipped))

#
# Write info about the PSSMs
#
logging.info('Writing PSSMs info.')
pssm_file = open('pssms.csv', 'w')
pssm_file.write("chr:pos:orientation,%s\n" % ",".join(imap(str, pssms))) # write header
for pssm in pssms:
    m = T.Matrix(pssm)
    pssm_file.write(
        "%s,%s,%s\n" % (
            pssm,
            m.name,
            ":".join(imap(factor_info, m.factors))
        )
    )
pssm_file.close()

#
# Write info about each promoter
#
logging.info('Writing transcripts info.')
transcripts_file = open('transcripts.csv', 'w')
transcripts_file.write("RefSeq,Chr,Pos,Orientation\n") # write header
for nm_id, (chr, pos, tag, record) in promoters.iteritems():
    transcripts_file.write('NM_%d,%s,%d,%s\n' % (nm_id, chr, pos, tag))
transcripts_file.close()

#
# Get results from engines
#
logging.info('Blocking on %d results...', len(task_ids))
genome_p_binding = dict()
for task_id in task_ids:
    pssms, record = task_args[task_id]
    nm_id, chr, pos, tag = parse_record_id(record.id)
    pos_key = chr, pos, tag
    logging.debug('Blocking on result for NM_%-16d %6s %10d %s %r', nm_id, chr, pos, tag, record.seq)
    promoter_p_binding = tc.get_task_result(task_id, block=True)
    genome_p_binding[pos_key] = promoter_p_binding

logging.info('Analysed %d promoters', len(promoters))

#
# Write results out
#
logging.info('Writing results.')
tf_nm_matrix = open('tf-nm-matrix.csv', 'w')
tf_nm_matrix.write("chr:pos:orientation,%s\n" % ",".join(imap(str, pssms))) # write header
for (chr, pos, tag), p_binding_map in genome_p_binding.iteritems():
    tf_nm_matrix.write(
        "%s:%d:%s,%s\n" % (
        chr, pos, tag, ",".join(str(p_binding_map.get(pssm, 0)) for pssm in pssms))
    )
tf_nm_matrix.close()


text:
using System.IO;

namespace pal.EventLog
{
    public class CsvEventLogFile : AbstractEventLogFile
    {
        private readonly StreamReader _fileReader;

        public CsvEventLogFile(string fileName) : base(fileName)
        {
            _fileReader = new StreamReader(_fileName);
        }

        public override void Parse()
        {
            while (!_fileReader.EndOfStream)
            {
                string line = _fileReader.ReadLine();
                if (!isComment(line))
                {
                    CsvEventLogRecord eventLogRecord = CsvEventLogRecord.Fetch(line);
                    eventLogRecord.ContainingFile = this;
                    _records.Add(eventLogRecord);
                }
            }
            _fileReader.Close();
        }

        private bool isComment(string line)
        {
            return line.Trim().StartsWith("#");
        }

        public override string ToString()
        {
            return Path.GetFileName(_fileName);
        }

        public override void Dispose()
        {
            _fileReader.Dispose();
        }
    }
}


text:
using UnityEngine;
using System.Collections;

#if UNITY_EDITOR
using UnityEditor;
#endif

namespace Xft
{

    public class GlobalConfig
    {
        static public float SoundVolume = 1f;
    }

    public class XftEvent
    {
        protected XEventType m_type;
        protected XftEventComponent m_owner;
        protected float m_elapsedTime = 0f;

		protected bool m_canUpdate = false;

		protected Camera m_myCamera;

		public Camera MyCamera
		{
			get{
#if UNITY_EDITOR
                if (!EditorApplication.isPlaying)
                {
                    if (m_myCamera == null)
                    {
                        m_myCamera = FindMyCamera();
                    }
                    return m_myCamera;
                }
                else
                {
                    return m_owner.Owner.MyCamera;
                }
#else
                return m_owner.Owner.MyCamera;
#endif

            }
		}

		protected Camera FindMyCamera()
        {
            int layerMask = 1 << m_owner.gameObject.layer;
            Camera[] cameras = GameObject.FindObjectsOfType(typeof(Camera)) as Camera[];
            for (int i = 0, imax = cameras.Length; i < imax; ++i)
            {
                Camera cam = cameras[i];

                if ((cam.cullingMask & layerMask) != 0)
                {
					return cam;
                }
            }
            Debug.LogError("can't find proper camera for event:" + m_type);

			return null;
        }

		public bool CanUpdate
		{
			get{
				return m_canUpdate;
			}
			set{
				m_canUpdate = value;
			}
		}

        public XftEvent (XEventType type, XftEventComponent owner)
        {
            m_type = type;
            m_owner = owner;
        }

        public virtual void OnBegin ()
        {
			CanUpdate = true;
        }

		public virtual void Initialize ()
        {
        }

        public virtual void Update (float deltaTime)
        {
        }

        public virtual void Reset ()
        {
			m_elapsedTime = 0f;
			CanUpdate = false;
        }

    }
}


text:
"""
Methods for detecting objects leading to pickling failures.
"""

from __future__ import absolute_import, with_statement
import dis
from inspect import ismethod, isfunction, istraceback, isframe, iscode
from inspect import getmodule
from .pointers import parent, reference, at, parents, children

from .dill import _trace as trace
from .dill import PY3

def outermost(func): # is analogous to getsource(func,enclosing=True)
    """get outermost enclosing object (i.e. the outer function in a closure)

    NOTE: this is the object-equivalent of getsource(func, enclosing=True)
    """
    if PY3:
        if ismethod(func):
            _globals = func.__func__.__globals__ or {}
        elif isfunction(func):
            _globals = func.__globals__ or {}
        else:
            return #XXX: or raise? no matches
        _globals = _globals.items()
    else:
        if ismethod(func):
            _globals = func.im_func.func_globals or {}
        elif isfunction(func):
            _globals = func.func_globals or {}
        else:
            return #XXX: or raise? no matches
        _globals = _globals.iteritems()
    # get the enclosing source
    from .source import getsourcelines
    try: lines,lnum = getsourcelines(func, enclosing=True)
    except: #TypeError, IOError
        lines,lnum = [],None
    code = ''.join(lines)
    # get all possible names,objects that are named in the enclosing source
    _locals = ((name,obj) for (name,obj) in _globals if name in code)
    # now only save the objects that generate the enclosing block
    for name,obj in _locals: #XXX: don't really need 'name'
        try:
            if getsourcelines(obj) == (lines,lnum): return obj
        except: #TypeError, IOError
            pass
    return #XXX: or raise? no matches

def nestedcode(func, recurse=True): #XXX: or return dict of {co_name: co} ?
    """get the code objects for any nested functions (e.g. in a closure)"""
    func = code(func)
    if not iscode(func): return [] #XXX: or raise? no matches
    nested = set()
    for co in func.co_consts:
        if co is None: continue
        co = code(co)
        if co:
            nested.add(co)
            if recurse: nested |= set(nestedcode(co, recurse=True))
    return list(nested)

def code(func):
    '''get the code object for the given function or method

    NOTE: use dill.source.getsource(CODEOBJ) to get the source code
    '''
    if PY3:
        im_func = '__func__'
        func_code = '__code__'
    else:
        im_func = 'im_func'
        func_code = 'func_code'
    if ismethod(func): func = getattr(func, im_func)
    if isfunction(func): func = getattr(func, func_code)
    if istraceback(func): func = func.tb_frame
    if isframe(func): func = func.f_code
    if iscode(func): return func
    return

#XXX: ugly: parse dis.dis for name after "<code object" in line and in globals?
def referrednested(func, recurse=True): #XXX: return dict of {__name__: obj} ?
    """get functions defined inside of func (e.g. inner functions in a closure)

    NOTE: results may differ if the function has been executed or not.
    If len(nestedcode(func)) > len(referrednested(func)), try calling func().
    If possible, python builds code objects, but delays building functions
    until func() is called.
    """
    if PY3:
        att1 = '__code__'
        att0 = '__func__'
    else:
        att1 = 'func_code' # functions
        att0 = 'im_func'   # methods

    import gc
    funcs = set()
    # get the code objects, and try to track down by referrence
    for co in nestedcode(func, recurse):
        # look for function objects that refer to the code object
        for obj in gc.get_referrers(co):
            # get methods
            _ = getattr(obj, att0, None) # ismethod
            if getattr(_, att1, None) is co: funcs.add(obj)
            # get functions
            elif getattr(obj, att1, None) is co: funcs.add(obj)
            # get frame objects
            elif getattr(obj, 'f_code', None) is co: funcs.add(obj)
            # get code objects
            elif hasattr(obj, 'co_code') and obj is co: funcs.add(obj)
#     frameobjs => func.func_code.co_varnames not in func.func_code.co_cellvars
#     funcobjs => func.func_code.co_cellvars not in func.func_code.co_varnames
#     frameobjs are not found, however funcobjs are...
#     (see: test_mixins.quad ... and test_mixins.wtf)
#     after execution, code objects get compiled, and then may be found by gc
    return list(funcs)

def freevars(func):
    """get objects defined in enclosing code that are referred to by func

    returns a dict of {name:object}"""
    if PY3:
        im_func = '__func__'
        func_code = '__code__'
        func_closure = '__closure__'
    else:
        im_func = 'im_func'
        func_code = 'func_code'
        func_closure = 'func_closure'
    if ismethod(func): func = getattr(func, im_func)
    if isfunction(func):
        closures = getattr(func, func_closure) or ()
        func = getattr(func, func_code).co_freevars # get freevars
    else:
        return {}
    return dict((name,c.cell_contents) for (name,c) in zip(func,closures))

# thanks to Davies Liu for recursion of globals
def nestedglobals(func, recurse=True):
    """get the names of any globals found within func"""
    func = code(func)
    if func is None: return list()
    from .temp import capture
    names = set()
    with capture('stdout') as out:
        dis.dis(func) #XXX: dis.dis(None) disassembles last traceback
    for line in out.getvalue().splitlines():
        if '_GLOBAL' in line:
            name = line.split('(')[-1].split(')')[0]
            names.add(name)
    for co in getattr(func, 'co_consts', tuple()):
        if co and recurse and iscode(co):
            names.update(nestedglobals(co, recurse=True))
    return list(names)

def referredglobals(func, recurse=True):
    """get the names of objects in the global scope referred to by func"""
    return globalvars(func, recurse).keys()

def globalvars(func, recurse=True):
    """get objects defined in global scope that are referred to by func

    return a dict of {name:object}"""
    if PY3:
        im_func = '__func__'
        func_code = '__code__'
        func_globals = '__globals__'
    else:
        im_func = 'im_func'
        func_code = 'func_code'
        func_globals = 'func_globals'
    if ismethod(func): func = getattr(func, im_func)
    if isfunction(func):
        globs = {} #FIXME: vars(getmodule(object)) # get dict of __builtins__
        globs.update(getattr(func, func_globals) or {})
        if not recurse:
            func = getattr(func, func_code).co_names # get names
        else:
            func = set(nestedglobals(getattr(func, func_code)))
            # find globals for all entries of func
            for key in func.copy(): #XXX: unnecessary...?
                func.update(globalvars(globs.get(key), recurse=True).keys())
    else:
        return {}
    #NOTE: if name not in func_globals, then we skip it...
    return dict((name,globs[name]) for name in func if name in globs)

def varnames(func):
    """get names of variables defined by func

    returns a tuple (local vars, local vars referrenced by nested functions)"""
    func = code(func)
    if not iscode(func):
        return () #XXX: better ((),())? or None?
    return func.co_varnames, func.co_cellvars

def baditems(obj, exact=False, safe=False): #XXX: obj=globals() ?
    """get items in object that fail to pickle"""
    if not hasattr(obj,'__iter__'): # is not iterable
        return [j for j in (badobjects(obj,0,exact,safe),) if j is not None]
    obj = obj.values() if getattr(obj,'values',None) else obj
    _obj = [] # can't use a set, as items may be unhashable
    [_obj.append(badobjects(i,0,exact,safe)) for i in obj if i not in _obj]
    return [j for j in _obj if j is not None]

def badobjects(obj, depth=0, exact=False, safe=False):
    """get objects that fail to pickle"""
    from dill import pickles
    if not depth:
        if pickles(obj,exact,safe): return None
        return obj
    return dict(((attr, badobjects(getattr(obj,attr),depth-1,exact,safe)) \
           for attr in dir(obj) if not pickles(getattr(obj,attr),exact,safe)))

def badtypes(obj, depth=0, exact=False, safe=False):
    """get types for objects that fail to pickle"""
    from dill import pickles
    if not depth:
        if pickles(obj,exact,safe): return None
        return type(obj)
    return dict(((attr, badtypes(getattr(obj,attr),depth-1,exact,safe)) \
           for attr in dir(obj) if not pickles(getattr(obj,attr),exact,safe)))

def errors(obj, depth=0, exact=False, safe=False):
    """get errors for objects that fail to pickle"""
    from dill import pickles, copy
    if not depth:
        try:
            pik = copy(obj)
            if exact:
                assert pik == obj, \
                    "Unpickling produces %s instead of %s" % (pik,obj)
            assert type(pik) == type(obj), \
                "Unpickling produces %s instead of %s" % (type(pik),type(obj))
            return None
        except Exception:
            import sys
            return sys.exc_info()[1]
    return dict(((attr, errors(getattr(obj,attr),depth-1,exact,safe)) \
           for attr in dir(obj) if not pickles(getattr(obj,attr),exact,safe)))

del absolute_import, with_statement

# EOF


text:
@import UIKit;
@import OBAKit;

@interface OBATestAppDelegate : UIResponder <UIApplicationDelegate>
@end
@implementation OBATestAppDelegate
@end

int main(int argc, char *argv[]) {
    @autoreleasepool {

#if DEBUG
        NSLog(@"Bundle Path: %@", [NSBundle mainBundle].bundlePath);
        NSLog(@"Caches path: %@", [FileHelpers pathToFileName:@"whatever" inDirectory:NSCachesDirectory]);
#endif

        NSDictionary *processInfoEnv = [NSProcessInfo processInfo].environment;

        BOOL executingTests = [[processInfoEnv[@"XCInjectBundle"] pathExtension] isEqual:@"xctest"];
        if (!executingTests) {
            executingTests = !!processInfoEnv[@"XCInjectBundleInto"];
        }

        NSString *appDelegateClass = executingTests ? @"OBATestAppDelegate" : @"OBAApplicationDelegate";

        [OBACommon setRunningInsideTests:executingTests];

        int retVal = UIApplicationMain(argc, argv, nil, appDelegateClass);
        return retVal;
    }
}


text:
backup_mysql ()
{
    if [ -z "$1" ]; then
        echo "No MySQL database specified to backup."
    else
        local database="$1"
        local backup="${BACKUP}/sql"

        mkdir -p "${backup}"
        mysqldump -u"${MYSQL_USERNAME}" -p"${MYSQL_PASSWORD}" -h"${MYSQL_HOSTNAME}" "${database}" > "${backup}/${database}.sql"
    fi
}

########################################
## Restores a MySQL database from backup.
## Dependencies:
##   * mysql
## Usage: restore_mysql <database>
##
## Required Variables:
##   * MYSQL_USERNAME
##   * MYSQL_PASSWORD
##   * MYSQL_HOSTNAME
########################################
restore_mysql ()
{
    echo "Restore functionality has not been implemented."
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Nova Hedwigia 60(3-4): 600 (1995)

#### Original name
Cocoicola K.D. Hyde

### Remarks
null


text:
using content::WebContents;

namespace {

// The space above the titlebars.
const int kTitlebarHeight = 14;

// The thickness in pixels of the tab border.
const int kTabOuterThickness = 1;

// Amount to offset the tab images relative to the background.
const int kNormalVerticalOffset = kTitlebarHeight + kTabOuterThickness;

// A linux specific menu item for toggling window decorations.
const int kShowWindowDecorationsCommand = 200;

const int kAvatarBottomSpacing = 1;
// There are 2 px on each side of the avatar (between the frame border and
// it on the left, and between it and the tabstrip on the right).
const int kAvatarSideSpacing = 2;

// The thickness of the custom frame border; we need it here to enlarge the
// close button whent the custom frame border isn't showing but the custom
// titlebar is showing.
const int kFrameBorderThickness = 4;

// There is a 4px gap between the icon and the title text.
const int kIconTitleSpacing = 4;

// Padding around the icon when in app mode or popup mode.
const int kAppModePaddingTop = 5;
const int kAppModePaddingBottom = 4;
const int kAppModePaddingLeft = 2;

// The left padding of the tab strip.  In Views, the tab strip has a left
// margin of FrameBorderThickness + kClientEdgeThickness.  This offset is to
// account for kClientEdgeThickness.
const int kTabStripLeftPadding = 1;

// Spacing between buttons of the titlebar.
const int kButtonSpacing = 2;

// Spacing around outside of titlebar buttons.
const int kButtonOuterPadding = 2;

// Spacing between tabstrip and window control buttons (when the window is
// maximized).
const int kMaximizedTabstripPadding = 16;

gboolean OnMouseMoveEvent(GtkWidget* widget, GdkEventMotion* event,
                          BrowserWindowGtk* browser_window) {
  // Reset to the default mouse cursor.
  browser_window->ResetCustomFrameCursor();
  return TRUE;
}

// Converts a GdkColor to a color_utils::HSL.
color_utils::HSL GdkColorToHSL(const GdkColor* color) {
  color_utils::HSL hsl;
  color_utils::SkColorToHSL(SkColorSetRGB(color->red >> 8,
                                          color->green >> 8,
                                          color->blue >> 8), &hsl);
  return hsl;
}

// Returns either |one| or |two| based on which has a greater difference in
// luminosity.
GdkColor PickLuminosityContrastingColor(const GdkColor* base,
                                        const GdkColor* one,
                                        const GdkColor* two) {
  // Convert all GdkColors to color_utils::HSLs.
  color_utils::HSL baseHSL = GdkColorToHSL(base);
  color_utils::HSL oneHSL = GdkColorToHSL(one);
  color_utils::HSL twoHSL = GdkColorToHSL(two);
  double one_difference = fabs(baseHSL.l - oneHSL.l);
  double two_difference = fabs(baseHSL.l - twoHSL.l);

  // Be biased towards the first color presented.
  if (two_difference > one_difference + 0.1)
    return *two;
  else
    return *one;
}

}  // namespace

////////////////////////////////////////////////////////////////////////////////
// PopupPageMenuModel

// A menu model that builds the contents of the menu shown for popups (when the
// user clicks on the favicon) and all of its submenus.
class PopupPageMenuModel : public ui::SimpleMenuModel {
 public:
  PopupPageMenuModel(ui::SimpleMenuModel::Delegate* delegate, Browser* browser);
  virtual ~PopupPageMenuModel() { }

 private:
  void Build();

  // Models for submenus referenced by this model. SimpleMenuModel only uses
  // weak references so these must be kept for the lifetime of the top-level
  // model.
  scoped_ptr<ZoomMenuModel> zoom_menu_model_;
  scoped_ptr<EncodingMenuModel> encoding_menu_model_;
  Browser* browser_;  // weak

  DISALLOW_COPY_AND_ASSIGN(PopupPageMenuModel);
};

PopupPageMenuModel::PopupPageMenuModel(
    ui::SimpleMenuModel::Delegate* delegate,
    Browser* browser)
    : ui::SimpleMenuModel(delegate), browser_(browser) {
  Build();
}

void PopupPageMenuModel::Build() {
  AddItemWithStringId(IDC_BACK, IDS_CONTENT_CONTEXT_BACK);
  AddItemWithStringId(IDC_FORWARD, IDS_CONTENT_CONTEXT_FORWARD);
  AddItemWithStringId(IDC_RELOAD, IDS_APP_MENU_RELOAD);
  AddSeparator(ui::NORMAL_SEPARATOR);
  AddItemWithStringId(IDC_SHOW_AS_TAB, IDS_SHOW_AS_TAB);
  AddSeparator(ui::NORMAL_SEPARATOR);
  AddItemWithStringId(IDC_CUT, IDS_CUT);
  AddItemWithStringId(IDC_COPY, IDS_COPY);
  AddItemWithStringId(IDC_PASTE, IDS_PASTE);
  AddSeparator(ui::NORMAL_SEPARATOR);
  AddItemWithStringId(IDC_FIND, IDS_FIND);
  AddItemWithStringId(IDC_PRINT, IDS_PRINT);
  zoom_menu_model_.reset(new ZoomMenuModel(delegate()));
  AddSubMenuWithStringId(IDC_ZOOM_MENU, IDS_ZOOM_MENU, zoom_menu_model_.get());

  encoding_menu_model_.reset(new EncodingMenuModel(browser_));
  AddSubMenuWithStringId(IDC_ENCODING_MENU, IDS_ENCODING_MENU,
                         encoding_menu_model_.get());

  AddSeparator(ui::NORMAL_SEPARATOR);
  AddItemWithStringId(IDC_CLOSE_WINDOW, IDS_CLOSE);
}

////////////////////////////////////////////////////////////////////////////////
// BrowserTitlebar

// static
const char BrowserTitlebar::kDefaultButtonString[] = ":minimize,maximize,close";

BrowserTitlebar::BrowserTitlebar(BrowserWindowGtk* browser_window,
                                 GtkWindow* window)
    : browser_window_(browser_window),
      window_(window),
      container_(NULL),
      container_hbox_(NULL),
      titlebar_left_buttons_vbox_(NULL),
      titlebar_right_buttons_vbox_(NULL),
      titlebar_left_buttons_hbox_(NULL),
      titlebar_right_buttons_hbox_(NULL),
      titlebar_left_avatar_frame_(NULL),
      titlebar_right_avatar_frame_(NULL),
      avatar_(NULL),
      top_padding_left_(NULL),
      top_padding_right_(NULL),
      titlebar_alignment_(NULL),
      app_mode_favicon_(NULL),
      app_mode_title_(NULL),
      using_custom_frame_(false),
      window_has_focus_(false),
      display_avatar_on_left_(false),
      theme_service_(NULL) {
}

void BrowserTitlebar::Init() {
  // The widget hierarchy is shown below.
  //
  // +- EventBox (container_) ------------------------------------------------+
  // +- HBox (container_hbox_) -----------------------------------------------+
  // |+ VBox ---++- Algn. -++- Alignment --------------++- Algn. -++ VBox ---+|
  // || titlebar||titlebar ||   (titlebar_alignment_)  ||titlebar || titlebar||
  // || left    ||left     ||                          ||right    || right   ||
  // || button  ||spy      ||                          ||spy      || button  ||
  // || vbox    ||frame    ||+- TabStripGtk  ---------+||frame    || vbox    ||
  // ||         ||         || tab   tab   tabclose    |||         ||         ||
  // ||         ||         ||+------------------------+||         ||         ||
  // |+---------++---------++--------------------------++---------++---------+|
  // +------------------------------------------------------------------------+
  //
  // There are two vboxes on either side of |container_hbox_| because when the
  // desktop is GNOME, the button placement is configurable based on a metacity
  // gconf key. We can't just have one vbox and move it back and forth because
  // the gconf language allows you to place buttons on both sides of the
  // window.  This being Linux, I'm sure there's a bunch of people who have
  // already configured their window manager to do so and we don't want to get
  // confused when that happens. The actual contents of these vboxes are lazily
  // generated so they don't interfere with alignment when everything is
  // stuffed in the other box.
  //
  // Each vbox has the following hierarchy if it contains buttons:
  //
  // +- VBox (titlebar_{l,r}_buttons_vbox_) ---------+
  // |+- Fixed (top_padding_{l,r}_) ----------------+|
  // ||+- HBox (titlebar_{l,r}_buttons_hbox_ ------+||
  // ||| (buttons of a configurable layout)        |||
  // ||+-------------------------------------------+||
  // |+---------------------------------------------+|
  // +-----------------------------------------------+
  //
  // The two spy alignments are only allocated if this window is an incognito
  // window. Only one of them holds the spy image.
  //
  // If we're a popup window or in app mode, we don't display the spy guy or
  // the tab strip.  Instead, put an hbox in titlebar_alignment_ in place of
  // the tab strip.
  // +- Alignment (titlebar_alignment_) -----------------------------------+
  // |+ HBox -------------------------------------------------------------+|
  // ||+- TabStripGtk -++- Image ----------------++- Label --------------+||
  // ||| hidden        ++    (app_mode_favicon_) ||    (app_mode_title_) |||
  // |||               ||  favicon               ||  page title          |||
  // ||+---------------++------------------------++----------------------+||
  // |+-------------------------------------------------------------------+|
  // +---------------------------------------------------------------------+
  container_hbox_ = gtk_hbox_new(FALSE, 0);

  container_ = gtk_event_box_new();
  gtk_widget_set_name(container_, "chrome-browser-titlebar");
  gtk_event_box_set_visible_window(GTK_EVENT_BOX(container_), FALSE);
  gtk_container_add(GTK_CONTAINER(container_), container_hbox_);

  g_signal_connect(container_, "scroll-event", G_CALLBACK(OnScrollThunk), this);

  g_signal_connect(window_, "window-state-event",
                   G_CALLBACK(OnWindowStateChangedThunk), this);

  // Allocate the two button boxes on the left and right parts of the bar. These
  // are always allocated, but only displayed in incognito mode or when using
  // multiple profiles.
  titlebar_left_buttons_vbox_ = gtk_vbox_new(FALSE, 0);
  gtk_box_pack_start(GTK_BOX(container_hbox_), titlebar_left_buttons_vbox_,
                     FALSE, FALSE, 0);
  titlebar_left_avatar_frame_ = gtk_alignment_new(0.0, 0.0, 1.0, 1.0);
  gtk_widget_set_no_show_all(titlebar_left_avatar_frame_, TRUE);
  gtk_alignment_set_padding(GTK_ALIGNMENT(titlebar_left_avatar_frame_), 0,
      kAvatarBottomSpacing, kAvatarSideSpacing, kAvatarSideSpacing);
  gtk_box_pack_start(GTK_BOX(container_hbox_), titlebar_left_avatar_frame_,
                     FALSE, FALSE, 0);

  titlebar_right_avatar_frame_ = gtk_alignment_new(0.0, 0.0, 1.0, 1.0);
  gtk_widget_set_no_show_all(titlebar_right_avatar_frame_, TRUE);
  gtk_alignment_set_padding(GTK_ALIGNMENT(titlebar_right_avatar_frame_), 0,
      kAvatarBottomSpacing, kAvatarSideSpacing, kAvatarSideSpacing);
  gtk_box_pack_end(GTK_BOX(container_hbox_), titlebar_right_avatar_frame_,
                   FALSE, FALSE, 0);

  titlebar_right_buttons_vbox_ = gtk_vbox_new(FALSE, 0);
  gtk_box_pack_end(GTK_BOX(container_hbox_), titlebar_right_buttons_vbox_,
                   FALSE, FALSE, 0);

  // Create the Avatar button and listen for notifications. It must always be
  // created because a new profile can be added at any time.
  avatar_button_.reset(new AvatarMenuButtonGtk(browser_window_->browser()));

  registrar_.Add(this, chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
                 content::NotificationService::AllSources());

#if defined(USE_GCONF)
  // Either read the gconf database and register for updates (on GNOME), or use
  // the default value (anywhere else).
  GConfTitlebarListener::GetInstance()->SetTitlebarButtons(this);
#else
  BuildButtons(kDefaultButtonString);
#endif

  UpdateAvatar();

  // We use an alignment to control the titlebar height.
  titlebar_alignment_ = gtk_alignment_new(0.0, 0.0, 1.0, 1.0);
  if (browser_window_->browser()->is_type_tabbed()) {
    gtk_box_pack_start(GTK_BOX(container_hbox_), titlebar_alignment_, TRUE,
                       TRUE, 0);

    // Put the tab strip in the titlebar.
    gtk_container_add(GTK_CONTAINER(titlebar_alignment_),
                      browser_window_->tabstrip()->widget());
  } else {
    // App mode specific widgets.
    gtk_box_pack_start(GTK_BOX(container_hbox_), titlebar_alignment_, TRUE,
                       TRUE, 0);
    GtkWidget* app_mode_hbox = gtk_hbox_new(FALSE, kIconTitleSpacing);
    gtk_container_add(GTK_CONTAINER(titlebar_alignment_), app_mode_hbox);

    // Put the tab strip in the hbox even though we don't show it.  Sometimes
    // we need the position of the tab strip so make sure it's in our widget
    // hierarchy.
    gtk_box_pack_start(GTK_BOX(app_mode_hbox),
        browser_window_->tabstrip()->widget(), FALSE, FALSE, 0);

    GtkWidget* favicon_event_box = gtk_event_box_new();
    gtk_event_box_set_visible_window(GTK_EVENT_BOX(favicon_event_box), FALSE);
    g_signal_connect(favicon_event_box, "button-press-event",
                     G_CALLBACK(OnFaviconMenuButtonPressedThunk), this);
    gtk_box_pack_start(GTK_BOX(app_mode_hbox), favicon_event_box, FALSE,
                       FALSE, 0);
    // We use the app logo as a placeholder image so the title doesn't jump
    // around.
    ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
    app_mode_favicon_ = gtk_image_new_from_pixbuf(rb.GetNativeImageNamed(
        IDR_PRODUCT_LOGO_16, ui::ResourceBundle::RTL_ENABLED).ToGdkPixbuf());
    g_object_set_data(G_OBJECT(app_mode_favicon_), "left-align-popup",
                      reinterpret_cast<void*>(true));
    gtk_container_add(GTK_CONTAINER(favicon_event_box), app_mode_favicon_);

    app_mode_title_ = gtk_label_new(NULL);
    gtk_label_set_ellipsize(GTK_LABEL(app_mode_title_), PANGO_ELLIPSIZE_END);
    gtk_misc_set_alignment(GTK_MISC(app_mode_title_), 0.0, 0.5);
    gtk_box_pack_start(GTK_BOX(app_mode_hbox), app_mode_title_, TRUE, TRUE,
                       0);

    UpdateTitleAndIcon();
  }

  theme_service_ = GtkThemeService::GetFrom(
      browser_window_->browser()->profile());
  registrar_.Add(this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED,
                 content::Source<ThemeService>(theme_service_));
  theme_service_->InitThemesFor(this);

  gtk_widget_show_all(container_);

  ui::ActiveWindowWatcherX::AddObserver(this);
}

BrowserTitlebar::~BrowserTitlebar() {
  ui::ActiveWindowWatcherX::RemoveObserver(this);
#if defined(USE_GCONF)
  GConfTitlebarListener::GetInstance()->RemoveObserver(this);
#endif
}

void BrowserTitlebar::BuildButtons(const std::string& button_string) {
  // Clear out all previous data.
  close_button_.reset();
  restore_button_.reset();
  maximize_button_.reset();
  minimize_button_.reset();
  gtk_util::RemoveAllChildren(titlebar_left_buttons_vbox_);
  gtk_util::RemoveAllChildren(titlebar_right_buttons_vbox_);
  titlebar_left_buttons_hbox_ = NULL;
  titlebar_right_buttons_hbox_ = NULL;
  top_padding_left_ = NULL;
  top_padding_right_ = NULL;

  bool left_side = true;
  base::StringTokenizer tokenizer(button_string, ":,");
  tokenizer.set_options(base::StringTokenizer::RETURN_DELIMS);
  int left_count = 0;
  int right_count = 0;
  while (tokenizer.GetNext()) {
    if (tokenizer.token_is_delim()) {
      if (*tokenizer.token_begin() == ':')
        left_side = false;
    } else {
      base::StringPiece token = tokenizer.token_piece();
      if (BuildButton(token.as_string(), left_side))
        (left_side ? left_count : right_count)++;
    }
  }

  // If we are in incognito mode, add the spy guy to either the end of the left
  // or the beginning of the right depending on which side has fewer buttons.
  display_avatar_on_left_ = right_count > left_count;

  // Now show the correct widgets in the two hierarchies.
  if (using_custom_frame_) {
    gtk_widget_show_all(titlebar_left_buttons_vbox_);
    gtk_widget_show_all(titlebar_right_buttons_vbox_);
  }
  UpdateMaximizeRestoreVisibility();
}

bool BrowserTitlebar::BuildButton(const std::string& button_token,
                                  bool left_side) {
  if (button_token == "minimize") {
    minimize_button_.reset(CreateTitlebarButton("minimize", left_side));

    gtk_widget_size_request(minimize_button_->widget(),
                            &minimize_button_req_);
    return true;
  } else if (button_token == "maximize") {
    restore_button_.reset(CreateTitlebarButton("unmaximize", left_side));
    maximize_button_.reset(CreateTitlebarButton("maximize", left_side));

    gtk_util::SetButtonClickableByMouseButtons(maximize_button_->widget(),
                                               true, true, true);
    gtk_widget_size_request(restore_button_->widget(),
                            &restore_button_req_);
    return true;
  } else if (button_token == "close") {
    close_button_.reset(CreateTitlebarButton("close", left_side));
    close_button_->set_flipped(left_side);

    gtk_widget_size_request(close_button_->widget(), &close_button_req_);
    return true;
  }
  // Ignore any other values like "pin" since we don't have images for
  // those.
  return false;
}

GtkWidget* BrowserTitlebar::GetButtonHBox(bool left_side) {
  if (left_side && titlebar_left_buttons_hbox_)
    return titlebar_left_buttons_hbox_;
  else if (!left_side && titlebar_right_buttons_hbox_)
    return titlebar_right_buttons_hbox_;

  // We put the min/max/restore/close buttons in a vbox so they are top aligned
  // (up to padding) and don't vertically stretch.
  GtkWidget* vbox = left_side ? titlebar_left_buttons_vbox_ :
                    titlebar_right_buttons_vbox_;

  GtkWidget* top_padding = gtk_fixed_new();
  gtk_widget_set_size_request(top_padding, -1, kButtonOuterPadding);
  gtk_box_pack_start(GTK_BOX(vbox), top_padding, FALSE, FALSE, 0);

  GtkWidget* buttons_hbox = gtk_hbox_new(FALSE, kButtonSpacing);
  gtk_box_pack_start(GTK_BOX(vbox), buttons_hbox, FALSE, FALSE, 0);

  if (left_side) {
    titlebar_left_buttons_hbox_ = buttons_hbox;
    top_padding_left_ = top_padding;
  } else {
    titlebar_right_buttons_hbox_ = buttons_hbox;
    top_padding_right_ = top_padding;
  }

  return buttons_hbox;
}

CustomDrawButton* BrowserTitlebar::CreateTitlebarButton(
    const std::string& button_name, bool left_side) {
  int normal_image_id;
  int pressed_image_id;
  int hover_image_id;
  int tooltip_id;
  GetButtonResources(button_name, &normal_image_id, &pressed_image_id,
                     &hover_image_id, &tooltip_id);

  CustomDrawButton* button = new CustomDrawButton(normal_image_id,
                                                  pressed_image_id,
                                                  hover_image_id,
                                                  0);
  gtk_widget_add_events(GTK_WIDGET(button->widget()), GDK_POINTER_MOTION_MASK);
  g_signal_connect(button->widget(), "clicked",
                   G_CALLBACK(OnButtonClickedThunk), this);
  g_signal_connect(button->widget(), "motion-notify-event",
                   G_CALLBACK(OnMouseMoveEvent), browser_window_);

  std::string localized_tooltip = l10n_util::GetStringUTF8(tooltip_id);
  gtk_widget_set_tooltip_text(button->widget(),
                              localized_tooltip.c_str());

  GtkWidget* box = GetButtonHBox(left_side);
  gtk_box_pack_start(GTK_BOX(box), button->widget(), FALSE, FALSE, 0);
  return button;
}

void BrowserTitlebar::GetButtonResources(const std::string& button_name,
                                         int* normal_image_id,
                                         int* pressed_image_id,
                                         int* hover_image_id,
                                         int* tooltip_id) const {
  if (button_name == "close") {
    *normal_image_id = IDR_CLOSE;
    *pressed_image_id = IDR_CLOSE_P;
    *hover_image_id = IDR_CLOSE_H;
    *tooltip_id = IDS_XPFRAME_CLOSE_TOOLTIP;
  } else if (button_name == "minimize") {
    *normal_image_id = IDR_MINIMIZE;
    *pressed_image_id = IDR_MINIMIZE_P;
    *hover_image_id = IDR_MINIMIZE_H;
    *tooltip_id = IDS_XPFRAME_MINIMIZE_TOOLTIP;
  } else if (button_name == "maximize") {
    *normal_image_id = IDR_MAXIMIZE;
    *pressed_image_id = IDR_MAXIMIZE_P;
    *hover_image_id = IDR_MAXIMIZE_H;
    *tooltip_id = IDS_XPFRAME_MAXIMIZE_TOOLTIP;
  } else if (button_name == "unmaximize") {
    *normal_image_id = IDR_RESTORE;
    *pressed_image_id = IDR_RESTORE_P;
    *hover_image_id = IDR_RESTORE_H;
    *tooltip_id = IDS_XPFRAME_RESTORE_TOOLTIP;
  }
}

void BrowserTitlebar::UpdateButtonBackground(CustomDrawButton* button) {
  SkColor color = theme_service_->GetColor(
      ThemeService::COLOR_BUTTON_BACKGROUND);
  SkBitmap background = theme_service_->GetImageNamed(
      IDR_THEME_WINDOW_CONTROL_BACKGROUND).AsBitmap();

  // TODO(erg): For now, we just use a completely black mask and we can get
  // away with this in the short term because our buttons are rectangles. We
  // should get Glen to make properly hinted masks that match our min/max/close
  // buttons (which have some odd alpha blending around the
  // edges). http://crbug.com/103661
  SkBitmap mask;
  mask.setConfig(SkBitmap::kARGB_8888_Config,
                 button->SurfaceWidth(), button->SurfaceHeight(), 0);
  mask.allocPixels();
  mask.eraseColor(SK_ColorBLACK);

  button->SetBackground(color, background, mask);
}

void BrowserTitlebar::UpdateCustomFrame(bool use_custom_frame) {
  using_custom_frame_ = use_custom_frame;
  if (!use_custom_frame ||
      (browser_window_->IsMaximized() && unity::IsRunning())) {
    if (titlebar_left_buttons_vbox_)
      gtk_widget_hide(titlebar_left_buttons_vbox_);
    if (titlebar_right_buttons_vbox_)
      gtk_widget_hide(titlebar_right_buttons_vbox_);
  } else {
    if (titlebar_left_buttons_vbox_)
      gtk_widget_show_all(titlebar_left_buttons_vbox_);
    if (titlebar_right_buttons_vbox_)
      gtk_widget_show_all(titlebar_right_buttons_vbox_);
  }
  UpdateTitlebarAlignment();
  UpdateMaximizeRestoreVisibility();
}

void BrowserTitlebar::UpdateTitleAndIcon() {
  if (!app_mode_title_)
    return;

  // Get the page title and elide it to the available space.
  string16 title = browser_window_->browser()->GetWindowTitleForCurrentTab();
  gtk_label_set_text(GTK_LABEL(app_mode_title_), UTF16ToUTF8(title).c_str());

  if (browser_window_->browser()->is_app()) {
    switch (browser_window_->browser()->type()) {
      case Browser::TYPE_POPUP: {
        // Update the system app icon.  We don't need to update the icon in the
        // top left of the custom frame, that will get updated when the
        // throbber is updated.
        Profile* profile = browser_window_->browser()->profile();
        gfx::Image icon = browser_window_->browser()->GetCurrentPageIcon();
        if (icon.IsEmpty()) {
          gtk_util::SetWindowIcon(window_, profile);
        } else {
          gtk_util::SetWindowIcon(window_, profile, icon.ToGdkPixbuf());
        }
        break;
      }
      case Browser::TYPE_TABBED: {
        NOTREACHED() << "We should never have a tabbed app window.";
        break;
      }
      case Browser::TYPE_PANEL: {
        NOTREACHED();
        break;
      }
    }
  }
}

void BrowserTitlebar::UpdateThrobber(WebContents* web_contents) {
  DCHECK(app_mode_favicon_);

  if (web_contents && web_contents->IsLoading()) {
    GdkPixbuf* icon_pixbuf =
        throbber_.GetNextFrame(web_contents->IsWaitingForResponse());
    gtk_image_set_from_pixbuf(GTK_IMAGE(app_mode_favicon_), icon_pixbuf);
  } else {
    ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();

    // Note: we want to exclude the application popup/panel window.
    if ((browser_window_->browser()->is_app() &&
        !browser_window_->browser()->is_type_tabbed())) {
      gfx::Image icon = browser_window_->browser()->GetCurrentPageIcon();
      if (icon.IsEmpty()) {
        // Fallback to the Chromium icon if the page has no icon.
        gtk_image_set_from_pixbuf(GTK_IMAGE(app_mode_favicon_),
            rb.GetNativeImageNamed(IDR_PRODUCT_LOGO_16).ToGdkPixbuf());
      } else {
        gtk_image_set_from_pixbuf(GTK_IMAGE(app_mode_favicon_),
                                  icon.ToGdkPixbuf());
      }
    } else {
      gtk_image_set_from_pixbuf(GTK_IMAGE(app_mode_favicon_),
          rb.GetNativeImageNamed(IDR_PRODUCT_LOGO_16).ToGdkPixbuf());
    }
    throbber_.Reset();
  }
}

void BrowserTitlebar::UpdateTitlebarAlignment() {
  if (browser_window_->browser()->is_type_tabbed()) {
    int top_padding = 0;
    int side_padding = 0;
    int vertical_offset = kNormalVerticalOffset;

    if (using_custom_frame_) {
      if (!browser_window_->IsMaximized()) {
        top_padding = kTitlebarHeight;
      } else if (using_custom_frame_ && browser_window_->IsMaximized()) {
        vertical_offset = 0;
        if (!unity::IsRunning())
          side_padding = kMaximizedTabstripPadding;
      }
    }

    int right_padding = 0;
    int left_padding = kTabStripLeftPadding;
    if (titlebar_right_buttons_hbox_)
      right_padding = side_padding;
    if (titlebar_left_buttons_hbox_)
      left_padding = side_padding;

    gtk_alignment_set_padding(GTK_ALIGNMENT(titlebar_alignment_),
                              top_padding, 0,
                              left_padding, right_padding);
    browser_window_->tabstrip()->SetVerticalOffset(vertical_offset);
  } else {
    if (using_custom_frame_ && !browser_window_->IsFullscreen()) {
      gtk_alignment_set_padding(GTK_ALIGNMENT(titlebar_alignment_),
          kAppModePaddingTop, kAppModePaddingBottom, kAppModePaddingLeft, 0);
      gtk_widget_show(titlebar_alignment_);
    } else {
      gtk_widget_hide(titlebar_alignment_);
    }
  }

  // Resize the buttons so that the clickable area extends all the way to the
  // edge of the browser window.
  GtkRequisition close_button_req = close_button_req_;
  GtkRequisition minimize_button_req = minimize_button_req_;
  GtkRequisition restore_button_req = restore_button_req_;
  if (using_custom_frame_ && browser_window_->IsMaximized()) {
    close_button_req.width += kButtonOuterPadding;
    close_button_req.height += kButtonOuterPadding;
    minimize_button_req.height += kButtonOuterPadding;
    restore_button_req.height += kButtonOuterPadding;
    if (top_padding_left_)
      gtk_widget_hide(top_padding_left_);
    if (top_padding_right_)
      gtk_widget_hide(top_padding_right_);
  } else {
    if (top_padding_left_)
      gtk_widget_show(top_padding_left_);
    if (top_padding_right_)
      gtk_widget_show(top_padding_right_);
  }
  if (close_button_.get()) {
    gtk_widget_set_size_request(close_button_->widget(),
                                close_button_req.width,
                                close_button_req.height);
  }
  if (minimize_button_.get()) {
    gtk_widget_set_size_request(minimize_button_->widget(),
                                minimize_button_req.width,
                                minimize_button_req.height);
  }
  if (maximize_button_.get()) {
    gtk_widget_set_size_request(restore_button_->widget(),
                                restore_button_req.width,
                                restore_button_req.height);
  }
}

void BrowserTitlebar::UpdateTextColor() {
  if (!app_mode_title_)
    return;

  if (theme_service_ && theme_service_->UsingNativeTheme()) {
    // We don't really have any good options here.
    //
    // Colors from window manager themes aren't exposed in GTK; the window
    // manager is a separate component and when there is information sharing
    // (in the case of metacity), it's one way where the window manager reads
    // data from the GTK theme (which allows us to do a decent job with
    // picking the frame color).
    //
    // We probably won't match in the majority of cases, but we can at the
    // very least make things legible. The default metacity and xfwm themes
    // on ubuntu have white text hardcoded. Determine whether black or white
    // has more luminosity contrast and then set that color as the text
    // color.
    GdkColor frame_color;
    if (window_has_focus_) {
      frame_color = theme_service_->GetGdkColor(
          ThemeService::COLOR_FRAME);
    } else {
      frame_color = theme_service_->GetGdkColor(
          ThemeService::COLOR_FRAME_INACTIVE);
    }
    GdkColor text_color = PickLuminosityContrastingColor(
        &frame_color, &ui::kGdkWhite, &ui::kGdkBlack);
    gtk_util::SetLabelColor(app_mode_title_, &text_color);
  } else {
    gtk_util::SetLabelColor(app_mode_title_, &ui::kGdkWhite);
  }
}

void BrowserTitlebar::UpdateAvatar() {
  // Remove previous state.
  gtk_util::RemoveAllChildren(titlebar_left_avatar_frame_);
  gtk_util::RemoveAllChildren(titlebar_right_avatar_frame_);

  if (!ShouldDisplayAvatar())
    return;

  if (!avatar_) {
    if (IsOffTheRecord()) {
      ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
      gfx::Image avatar_image =
          rb.GetNativeImageNamed(IDR_OTR_ICON, ui::ResourceBundle::RTL_ENABLED);
      avatar_ = gtk_image_new_from_pixbuf(avatar_image.ToGdkPixbuf());
      gtk_misc_set_alignment(GTK_MISC(avatar_), 0.0, 1.0);
      gtk_widget_set_size_request(avatar_, -1, 0);
    } else {
      // Use a clickable avatar.
      avatar_ = avatar_button_->widget();
    }
  }

  gtk_widget_show_all(avatar_);

  if (display_avatar_on_left_) {
    gtk_container_add(GTK_CONTAINER(titlebar_left_avatar_frame_), avatar_);
    gtk_widget_show(titlebar_left_avatar_frame_);
    gtk_widget_hide(titlebar_right_avatar_frame_);
  } else {
    gtk_container_add(GTK_CONTAINER(titlebar_right_avatar_frame_), avatar_);
    gtk_widget_show(titlebar_right_avatar_frame_);
    gtk_widget_hide(titlebar_left_avatar_frame_);
  }

  if (IsOffTheRecord())
    return;

  bool is_gaia_picture = false;
  gfx::Image avatar;
  if (ManagedMode::IsInManagedMode()) {
    ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
    avatar = rb.GetNativeImageNamed(IDR_MANAGED_MODE_AVATAR,
                                    ui::ResourceBundle::RTL_ENABLED);
  } else {
    ProfileInfoCache& cache =
        g_browser_process->profile_manager()->GetProfileInfoCache();
    Profile* profile = browser_window_->browser()->profile();
    size_t index = cache.GetIndexOfProfileWithPath(profile->GetPath());
    if (index == std::string::npos)
      return;

    is_gaia_picture =
        cache.IsUsingGAIAPictureOfProfileAtIndex(index) &&
        cache.GetGAIAPictureOfProfileAtIndex(index);
    avatar = cache.GetAvatarIconOfProfileAtIndex(index);
  }
  avatar_button_->SetIcon(avatar, is_gaia_picture);
  avatar_button_->set_menu_frame_style(display_avatar_on_left_ ?
      BubbleGtk::ANCHOR_TOP_LEFT : BubbleGtk::ANCHOR_TOP_RIGHT);
}

void BrowserTitlebar::MaximizeButtonClicked() {
  GdkEvent* event = gtk_get_current_event();
  if (event->button.button == 1) {
    gtk_window_maximize(window_);
  } else {
    GtkWidget* widget = GTK_WIDGET(window_);
    GdkScreen* screen = gtk_widget_get_screen(widget);
    gint monitor = gdk_screen_get_monitor_at_window(
        screen, gtk_widget_get_window(widget));
    GdkRectangle screen_rect;
    gdk_screen_get_monitor_geometry(screen, monitor, &screen_rect);

    gint x, y;
    gtk_window_get_position(window_, &x, &y);

    GtkAllocation allocation;
    gtk_widget_get_allocation(widget, &allocation);
    gint width = allocation.width;
    gint height = allocation.height;

    if (event->button.button == 3) {
      x = 0;
      width = screen_rect.width;
    } else if (event->button.button == 2) {
      y = 0;
      height = screen_rect.height;
    }

    browser_window_->SetBounds(gfx::Rect(x, y, width, height));
  }
  gdk_event_free(event);
}

void BrowserTitlebar::UpdateMaximizeRestoreVisibility() {
  if (maximize_button_.get()) {
    if (browser_window_->IsMaximized()) {
      gtk_widget_hide(maximize_button_->widget());
      gtk_widget_show(restore_button_->widget());
    } else {
      gtk_widget_hide(restore_button_->widget());
      gtk_widget_show(maximize_button_->widget());
    }
  }
}

gboolean BrowserTitlebar::OnWindowStateChanged(GtkWindow* window,
                                               GdkEventWindowState* event) {
  UpdateMaximizeRestoreVisibility();
  UpdateTitlebarAlignment();
  UpdateTextColor();
  return FALSE;
}

gboolean BrowserTitlebar::OnScroll(GtkWidget* widget, GdkEventScroll* event) {
  Browser* browser = browser_window_->browser();
  int index = browser->tab_strip_model()->active_index();
  if (event->direction == GDK_SCROLL_LEFT ||
      event->direction == GDK_SCROLL_UP) {
    if (index != 0)
      chrome::SelectPreviousTab(browser);
  } else if (index + 1 < browser->tab_strip_model()->count()) {
    chrome::SelectNextTab(browser);
  }
  return TRUE;
}

void BrowserTitlebar::OnButtonClicked(GtkWidget* button) {
  if (close_button_.get() && close_button_->widget() == button) {
    browser_window_->Close();
  } else if (restore_button_.get() && restore_button_->widget() == button) {
    browser_window_->UnMaximize();
  } else if (maximize_button_.get() && maximize_button_->widget() == button) {
    MaximizeButtonClicked();
  } else if (minimize_button_.get() && minimize_button_->widget() == button) {
    gtk_window_iconify(window_);
  }
}

gboolean BrowserTitlebar::OnFaviconMenuButtonPressed(GtkWidget* widget,
                                                     GdkEventButton* event) {
  if (event->button != 1)
    return FALSE;

  if (!favicon_menu_model_.get()) {
    favicon_menu_model_.reset(
        new PopupPageMenuModel(this, browser_window_->browser()));

    favicon_menu_.reset(new MenuGtk(NULL, favicon_menu_model_.get()));
  }

  favicon_menu_->PopupForWidget(app_mode_favicon_, event->button, event->time);

  return TRUE;
}

void BrowserTitlebar::ShowContextMenu(GdkEventButton* event) {
  if (!context_menu_.get()) {
    context_menu_model_.reset(new ContextMenuModel(this));
    context_menu_.reset(new MenuGtk(NULL, context_menu_model_.get()));
  }

  context_menu_->PopupAsContext(gfx::Point(event->x_root, event->y_root),
                                event->time);
}

bool BrowserTitlebar::IsCommandIdEnabled(int command_id) const {
  if (command_id == kShowWindowDecorationsCommand)
    return true;

  return chrome::IsCommandEnabled(browser_window_->browser(), command_id);
}

bool BrowserTitlebar::IsCommandIdChecked(int command_id) const {
  if (command_id == kShowWindowDecorationsCommand) {
    PrefService* prefs = browser_window_->browser()->profile()->GetPrefs();
    return !prefs->GetBoolean(prefs::kUseCustomChromeFrame);
  }

  EncodingMenuController controller;
  if (controller.DoesCommandBelongToEncodingMenu(command_id)) {
    WebContents* web_contents =
        browser_window_->browser()->tab_strip_model()->GetActiveWebContents();
    if (web_contents) {
      return controller.IsItemChecked(browser_window_->browser()->profile(),
                                      web_contents->GetEncoding(),
                                      command_id);
    }
    return false;
  }

  NOTREACHED();
  return false;
}

void BrowserTitlebar::ExecuteCommand(int command_id) {
  if (command_id == kShowWindowDecorationsCommand) {
    PrefService* prefs = browser_window_->browser()->profile()->GetPrefs();
    prefs->SetBoolean(prefs::kUseCustomChromeFrame,
                  !prefs->GetBoolean(prefs::kUseCustomChromeFrame));
    return;
  }

  chrome::ExecuteCommand(browser_window_->browser(), command_id);
}

bool BrowserTitlebar::GetAcceleratorForCommandId(
    int command_id,
    ui::Accelerator* out_accelerator) {
  const ui::Accelerator* accelerator =
      AcceleratorsGtk::GetInstance()->GetPrimaryAcceleratorForCommand(
          command_id);
  if (!accelerator)
    return false;
  *out_accelerator = *accelerator;
  return true;
}

void BrowserTitlebar::Observe(int type,
                              const content::NotificationSource& source,
                              const content::NotificationDetails& details) {
  switch (type) {
    case chrome::NOTIFICATION_BROWSER_THEME_CHANGED: {
      UpdateTextColor();

      if (minimize_button_.get())
        UpdateButtonBackground(minimize_button_.get());
      if (maximize_button_.get())
        UpdateButtonBackground(maximize_button_.get());
      if (restore_button_.get())
        UpdateButtonBackground(restore_button_.get());
      if (close_button_.get())
        UpdateButtonBackground(close_button_.get());
      break;
    }

    case chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED:
      if (!IsOffTheRecord())
        UpdateAvatar();
      break;

    default:
      NOTREACHED();
  }
}

void BrowserTitlebar::ActiveWindowChanged(GdkWindow* active_window) {
  // Can be called during shutdown; BrowserWindowGtk will set our |window_|
  // to NULL during that time.
  if (!window_)
    return;

  window_has_focus_ =
      gtk_widget_get_window(GTK_WIDGET(window_)) == active_window;
  UpdateTextColor();
}

bool BrowserTitlebar::ShouldDisplayAvatar() {
  if (IsOffTheRecord() || ManagedMode::IsInManagedMode())
    return true;

  if (!browser_window_->browser()->is_type_tabbed())
    return false;

  return AvatarMenuModel::ShouldShowAvatarMenu();
}

bool BrowserTitlebar::IsOffTheRecord() {
  return browser_window_->browser()->profile()->IsOffTheRecord();
}

BrowserTitlebar::ContextMenuModel::ContextMenuModel(
    ui::SimpleMenuModel::Delegate* delegate)
    : SimpleMenuModel(delegate) {
  AddItemWithStringId(IDC_NEW_TAB, IDS_TAB_CXMENU_NEWTAB);
  AddItemWithStringId(IDC_RESTORE_TAB, IDS_RESTORE_TAB);
  AddSeparator(ui::NORMAL_SEPARATOR);
  AddItemWithStringId(IDC_TASK_MANAGER, IDS_TASK_MANAGER);
  AddSeparator(ui::NORMAL_SEPARATOR);
  AddCheckItemWithStringId(kShowWindowDecorationsCommand,
                           IDS_SHOW_WINDOW_DECORATIONS_MENU);
}


text:
namespace {

void local_mousePress(
    QWidget *pWgt,
    int x,
    int y,
    Qt::MouseButton bt = Qt::LeftButton,
    Qt::MouseButtons bts = Qt::LeftButton)
{
    if (not pWgt)
        return;

    QMouseEvent *pMousePressEvent =
        new QMouseEvent(
            QEvent::MouseButtonPress,
            QPoint(x, y),
            bt,
            bts,
            Qt::NoModifier);

    QApplication::postEvent(pWgt, pMousePressEvent);
}
} // unonymous

int main(int argc, char **argv) {
    QApplication app{ argc, argv };

    ExampleWidget wgt{};
    wgt.resize(250, 130);
    wgt.show();

    local_mousePress(&wgt, 125, 65);

    return app.exec();
}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape
  xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke android:width="1.0px" android:color="#66000000" />
    <size android:height="48.0px" android:width="600.0px" />
    <solid android:color="#ffffffff" />
</shape>


text:
'use strict';

var chai = require('chai');
var should = chai.should();

var models = require('../../lib/models');
var WalletTransaction = models.WalletTransaction;

describe('Wallet Transaction Model', function() {
  function checkTransaction(tx) {
    tx.walletId.toString('hex').should.equal('b4f97411dadf3882296997ade99f4a0891b07e768a76898b837ac41d2c2622e7');
    tx.value.blockHash.should.equal('000000000000000006035200f6e6aa8b59751291d5c704c2f94acd3b04a67cb4');
    tx.value.inputs[0].prevTxId.should.equal('ffa9b1388c3ec2a05d57117bc053d07bda6284c9732672d69cdf21bb8b9c293c');
    tx.value.inputs[0].outputIndex.should.equal(0);
    tx.value.outputs[0].satoshis.should.equal(382504);
    tx.value.feeSatoshis.should.equal(10000);
    tx.value.inputSatoshis.should.equal(50000000);
    tx.value.outputSatoshis.should.equal(49990000);
  }
  var walletId = new Buffer('b4f97411dadf3882296997ade99f4a0891b07e768a76898b837ac41d2c2622e7', 'hex');
  var detailedData = {
    blockHash: '000000000000000006035200f6e6aa8b59751291d5c704c2f94acd3b04a67cb4',
    blockIndex: 179,
    height: 348346,
    blockTimestamp: 1426812067,
    version: 1,
    hash: '477a1b4a632187319bfdf78675555ef18af554d2d7caa86b27a3a5230f7c6e98',
    locktime: 0,
    inputSatoshis: 50000000,
    outputSatoshis: 49990000,
    inputs: [
      {
        wallet: false,
        satoshis: 50000000,
        address: '17gaaSEKNyrsnx5zq2yNUC6giZYykXLqr6',
        prevTxId: 'ffa9b1388c3ec2a05d57117bc053d07bda6284c9732672d69cdf21bb8b9c293c',
        outputIndex: 0,
        sequence: 4294967295
      }
    ],
    outputs: [
      {
        script: '76a914d8a01e1a7e81d3003005cf162694fff1c41dfc2f88ac',
        satoshis: 382504,
        address: '1LkQmbqhf34BS8RuV6nq4BjUVtEgrVCcRW',
        wallet: false
      },
      {
        script: '76a9142b0b59f889a580d29d0ac07af6d6cef0970e429988ac',
        satoshis: 49607496,
        address: '14vbexkRxksaicBQUu8CVHwpPeDiJesRXy',
        wallet: true
      }
    ],
    feeSatoshis: 10000
  };
  describe('@constructor', function() {
    it('will construct from detailed transaction', function() {
      var tx = new WalletTransaction(walletId, detailedData);
      should.exist(tx);
      checkTransaction(tx);
    });
    it('will construct from id string', function() {
      var tx = new WalletTransaction(walletId.toString('hex'), detailedData);
      should.exist(tx);
      checkTransaction(tx);
    });
    it('will construct class', function() {
      var tx = WalletTransaction(walletId, detailedData);
      should.exist(tx);
      checkTransaction(tx);
    });
  });
  describe('@create', function() {
    it('create an object', function() {
      var tx = WalletTransaction.create(walletId, detailedData);
      should.exist(tx);
      checkTransaction(tx);
    });
  });
  describe('#getValue/#fromBuffer', function() {
    it('roundtrip', function() {
      var tx = new WalletTransaction(walletId, detailedData);
      var value = tx.getValue();
      var tx2 = WalletTransaction.fromBuffer(walletId, value);
      checkTransaction(tx2);
    });
  });
  describe('@getDelta', function() {
    it('will return wallet delta for the transaction', function() {
      var tx = {
        inputs: [{wallet: true, satoshis: 150}, {wallet: false, satoshis: 200}],
        outputs: [{wallet: true, satoshis: 100}, {wallet: false, satoshis: 150}]
      };
      WalletTransaction.getDelta(tx).should.equal(-50);
    });
  });
  describe('@getInputSatoshis', function() {
    it('will return sum of inputs for this wallet', function() {
      var tx = {
        inputs: [{wallet: true, satoshis: 150}, {wallet: false, satoshis: 200}, {wallet: true, satoshis: 100}],
        outputs: []
      };
      WalletTransaction.getInputSatoshis(tx).should.equal(250);
    });
    it('will not return an amount if transaction is coinbase', function() {
      var tx = {
        coinbase: true,
        inputs: [],
        outputs: [{wallet: true, satoshis: 1250000000}]
      };
      WalletTransaction.getInputSatoshis(tx).should.equal(0);
    });
  });
  describe('@getOutputSatoshis', function() {
    it('will return sum of outputs for this wallet', function() {
      var tx = {
        inputs: [],
        outputs: [{wallet: true, satoshis: 150}, {wallet: false, satoshis: 200}, {wallet: true, satoshis: 100}]
      };
      WalletTransaction.getOutputSatoshis(tx).should.equal(250);
    });
  });
  describe('@classify', function() {
    it('it will return "send"', function() {
      var tx = {
        inputs: [{wallet: true}, {wallet: true}]
      };
      var delta = -100000;
      WalletTransaction.classify(tx, delta).should.equal('send');
    });
    it('it will return "join"', function() {
      var tx = {
        inputs: [{wallet: true}, {wallet: false}]
      };
      var delta = -100000;
      WalletTransaction.classify(tx, delta).should.equal('join');
    });
    describe('@isJoin', function() {
      it('will return "false"', function() {
	WalletTransaction.isJoin({coinbase: true}, 10).should.equal(false);
      });
    });
    it('it will return "receive"', function() {
      var tx = {
        inputs: [{wallet: false}, {wallet: false}],
        outputs: [{wallet: true}, {wallet: false}]
      };
      var delta = 100000;
      WalletTransaction.classify(tx, delta).should.equal('receive');
    });
    it('it will return "coinbase"', function() {
      var tx = {
        coinbase: true,
        inputs: [],
        outputs: [{wallet: true}]
      };
      var delta = 100000;
      WalletTransaction.classify(tx, delta).should.equal('coinbase');
    });
    it('it will return "move"', function() {
      var tx = {
        inputs: [{wallet: true}],
        outputs: [{wallet: true}]
      };
      var delta = 0;
      WalletTransaction.classify(tx, delta).should.equal('move');
    });
  });
  describe('#getKey', function() {
    it('will get the key', function() {
      var tx = new WalletTransaction(walletId, detailedData);
      var bufferKey = tx.getKey();
      var hex = 'b4f97411dadf3882296997ade99f4a0891b07e768a76898b837ac41d2c2622e7477a1b4a632187319bfdf78675555ef18af554d2d7caa86b27a3a5230f7c6e98';
      bufferKey.toString('hex').should.equal(hex);
      var expectedKey = walletId.toString('hex') + tx.value.hash;
      bufferKey.toString('hex').should.equal(expectedKey);
    });
  });
  describe('@getKey', function() {
    it('will get the key', function() {
      var bufferKey = WalletTransaction.getKey(walletId.toString('hex'), new Buffer(detailedData.hash, 'hex'));
      var expectedKey = walletId.toString('hex') + detailedData.hash;
      bufferKey.toString('hex').should.equal(expectedKey);
    });
  });
});


text:
===========
Development
===========

Crabpy is still in alpha development. Currently we're just happy to have gotten
a SOAP service working in python.

We try to cover as much code as we can with unit tests. You can run them using
tox_ or directly through nose. Currently tox_ and integration tests with the
service don't seem to get along, so we only run integration tests through nose.

.. code-block:: bash

    $ tox
    # No coverage
    $ nosetests
    # Coverage
    $ nosetests --config nose_cover.cfg

If you have access to the capakey service, you can enter your credentials in
the `nose_development.ini` file and use that as a test config.

.. code-block:: bash

    # Integration tests with nose but no coverage
    $ nosetests --tc-file nose_development.ini
    # Integration tests with nose and coverage
    $ nosetests --tc-file nose_development.ini --config nose_cover.cfg

.. _tox: http://tox.testrun.org