text:
package findbugs;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;

import javax.swing.BorderFactory;
import javax.swing.ComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JToolBar;
import javax.swing.ListSelectionModel;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

import at.ac.tuwien.ifs.bpse.basis.export_import.Export;
import at.ac.tuwien.ifs.bpse.basis.helper.Constants;
import at.ac.tuwien.ifs.bpse.dao.IStudentDAO;
import at.ac.tuwien.ifs.bpse.domain.Student;

/**
 * The MainFrame is, as the name says, the main frame of this application. It
 * utilizes a JPanel with a ContentPane and a BorderLayout.
 *
 * @author The SE-Team
 * @version 1.1
 */
public class MainFrame extends JFrame implements ActionListener {
	/**
	 * serialVersionUID, generated by eclipse.
	 */
	private static final long serialVersionUID = -7167629968906183715L;

	/**
	 * Retrieves the logger for this class.
	 */
	private static Log log = LogFactory.getLog(MainFrame.class);

	/**
	 * The Student Table Model, default order is Matrikel Number.
	 *
	 * @see #initModels()
	 */
	private StudentenTableModel studentenTM;

	/**
	 * The Table to display the Students from the Database.
	 */
	private JTable table;

	/**
	 * Holds the item to be exported.
	 */
	private ComboBoxModel exportComboModel;

	private IStudentDAO studentDAO = null;

	/**
	 * The XML Bean Factory from Spring.
	 *
	 * @see #initDAO()
	 */
	private XmlBeanFactory xbf;

	/**
	 * The Buttons for editing and deleting Students.
	 */
	private JButton editButton, deleteButton;

	/**
	 * The default Constructor for the MainFrame, initiating the DAO, the Models
	 * and the Conponents. Additionally it defines a ActionListener to clean up
	 * before exit.
	 *
	 * @see #terminateApplication()
	 */
	public MainFrame() {
		super();
		initDAO();
		log.info("Initialising MainFrame");
		// Window Listener for Closing Frame
		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent arg0) {
				super.windowClosing(arg0);
				terminateApplication();
			}
		});
		initModels();
		initComponents();
	}

	/**
	 * Initializes the DAOs. Loads the XmlBean.
	 */
	private void initDAO() {
		ClassPathResource res = new ClassPathResource(Constants.SPRINGBEANS);
		xbf = new XmlBeanFactory(res);
		studentDAO = (IStudentDAO) xbf.getBean("StudentDAO");
	}

	/**
	 * Initializes the Models. Creates the StudentenTableModel (for the Table)
	 * and loads the ExportComboModel from the XmlBean.
	 *
	 * @see StudentenTableModel
	 * @see ExportComboModel
	 */
	private void initModels() {
		studentenTM = new StudentenTableModel("Matrikelnummer");
		exportComboModel = (ComboBoxModel) xbf.getBean("ExportComboModel");
	}

	/**
	 * Initializes all the components of the GUI.
	 */
	private void initComponents() {
		// define main panel
		JPanel mainPanel = new JPanel();
		getContentPane().add(mainPanel);
		mainPanel.setLayout(new BorderLayout(5, 5));
		// define north, center and south panel
		// a JToolBar is actually very similar to a panel; just a little bit
		// more flexible
		JToolBar northPanel = new JToolBar();
		northPanel.setFloatable(false);
		northPanel.setBorder(BorderFactory.createEmptyBorder(10, 20, 0, 20));
		JPanel centerPanel = new JPanel();
		centerPanel.setLayout(new BorderLayout());
		centerPanel.setBorder(BorderFactory.createEmptyBorder(10, 5, 0, 10));
		JPanel southPanel = new JPanel();
		JPanel eastPanel = new JPanel(new BorderLayout());
		JPanel eastNorthPanel = new JPanel(new GridLayout(0, 1, 5, 5));
		eastPanel.add(eastNorthPanel, BorderLayout.NORTH);
		eastPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 10));
		mainPanel.add(eastPanel, BorderLayout.EAST);
		mainPanel.add(northPanel, BorderLayout.NORTH);
		mainPanel.add(centerPanel, BorderLayout.CENTER);
		mainPanel.add(southPanel, BorderLayout.SOUTH);
		// define Label for Drop Down Field in North Panel
		northPanel.add(new JLabel("Sortiert nach "));
		// define Drop Down Field in North Panel
		JComboBox selectOrderCB = new JComboBox();
		selectOrderCB.setEditable(false);
		selectOrderCB.addItem("Matrikelnummer");
		selectOrderCB.addItem("Nachname");
		northPanel.add(selectOrderCB);
		selectOrderCB.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent ie) {
				if (ie.getStateChange() == ItemEvent.SELECTED) {
					log.debug("Order Combo State Changed: " + ie.getItem());
					sortOrderChanged(ie.getItem().toString());
				}
			}
		});
		// define label for export
		northPanel.addSeparator(new Dimension(20, 5));
		northPanel.add(new JLabel("Exportieren nach"));
		JComboBox exportCB = new JComboBox();
		exportCB
				.setToolTipText("Exportformat auswaehlen, danach <Export> druecken");

		exportCB.setModel(exportComboModel);
		northPanel.add(exportCB);
		northPanel.addSeparator(new Dimension(5, 5));
		JButton exportBtn = new JButton("Export");
		exportBtn.setToolTipText("Exportieren der Daten in eine Datei");
		exportBtn.addActionListener(this);
		northPanel.add(exportBtn);
		// define table in center
		table = new JTable();
		table.setModel(studentenTM);
		table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
		table.setShowGrid(true);
		table.setGridColor(Color.LIGHT_GRAY);
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		table.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				updateButtonStatus();
				if (e.getClickCount() >= 2) {
					int row = table.getSelectedRow();
					if (row > -1) {
						editStudent();
					}
				}
			}
		});
		table.addKeyListener(new KeyAdapter() {
			public void keyReleased(KeyEvent e) {
				updateButtonStatus();
			}

			public void keyTyped(KeyEvent e) {
				if (e.getKeyChar() == KeyEvent.VK_DELETE) {
					deleteStudent();
				}
			}
		});
		JScrollPane tableScrollPane = new JScrollPane(table);
		tableScrollPane.setWheelScrollingEnabled(true);
		centerPanel.add(tableScrollPane);
		// define Exit Button in South Panel
		JButton exitButton = new JButton("Exit");
		exitButton.setToolTipText("Programm beenden");
		southPanel.add(exitButton);
		exitButton.addActionListener(this);

		editButton = new JButton("Edit");
		editButton.setEnabled(false);
		editButton.addActionListener(this);
		eastNorthPanel.add(editButton);
		JButton createButton = new JButton("Create");
		createButton.addActionListener(this);
		eastNorthPanel.add(createButton);
		deleteButton = new JButton("Delete");
		deleteButton.setEnabled(false);
		deleteButton.addActionListener(this);
		eastNorthPanel.add(deleteButton);

	}

	private void updateButtonStatus() {
		if (table.getSelectedRowCount() == 1) {
			editButton.setEnabled(true);
			deleteButton.setEnabled(true);
		} else {
			editButton.setEnabled(false);
			deleteButton.setEnabled(false);
		}
	}

	private void placeNewFrame(JFrame frame) {
		frame.pack();

		Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
		Point p = this.getLocation();
		// First try:
		// new Window right next to this one:
		if (screen.width > (this.getLocation().x + this.getWidth() + frame
				.getWidth())) {
			p.x += this.getWidth();
		}
		// Second try:
		// new Window left of this one:
		else if (this.getLocation().x - frame.getWidth() >= 0) {
			p.x -= frame.getWidth();
		}
		// Fallthrough:
		// Place centered over this frame
		else {
			p.x += (this.getWidth() - frame.getWidth()) / 2;
			p.y += (this.getHeight() - frame.getHeight()) / 2;
		}
		frame.setLocation(p);
	}

	public void actionPerformed(ActionEvent ae) {
		String cmd = ae.getActionCommand();
		log.debug("Action Performed \"" + cmd + "\"");
		if (cmd.equals("Exit")) {
			terminateApplication();
		} else if (cmd.equals("Export")) {
			export();
		} else if (cmd.equals("Create")) {
			createStudent();
		} else if (cmd.equals("Edit")) {
			editStudent();
		} else if (cmd.equals("Delete")) {
			deleteStudent();
		}
	}

	// Business Methods

	/**
	 * Handle a create-request from the GUI
	 */
	private void createStudent() {
		EditStudentFrame esf = new EditStudentFrame();
		placeNewFrame(esf);
		esf.pack();
		esf.addUpdateListener(new UpdateListener());
		esf.setVisible(true);
	}

	/**
	 * Handle a edit-request from the GUI
	 *
	 */
	private void editStudent() {
		int row = table.getSelectedRow();
		if (row > -1) {
			EditStudentFrame esf = new EditStudentFrame(studentenTM
					.getStudentAt(row), EditStudentFrame.Mode.Update);
			placeNewFrame(esf);
			esf.pack();
			esf.addUpdateListener(new UpdateListener());
			esf.setVisible(true);
		}
	}

	/**
	 * Handle a delete-request from the GUI
	 *
	 */
	private void deleteStudent() {
		int row = table.getSelectedRow();
		if (row > -1) {
			Student victim = studentenTM.getStudentAt(row);
			int yesno = JOptionPane.showConfirmDialog(this, "Student \""
					+ victim.getFirstname() + " " + victim.getLastname() + " ("
					+ victim.getMatnr() + ")\"" + " wirklich löschen?", "Delete",
					JOptionPane.YES_NO_OPTION);
			if (yesno == 0) {
				if (studentDAO.deleteStudent(victim.getId())) {
					studentenTM.reload();
					JOptionPane.showMessageDialog(this, "Löschen erfolgreich!");
				} else {
					JOptionPane.showMessageDialog(this, "Fehler beim löschen");
				}
			}
		}
	}

	/**
	 * Clean up and exit
	 */
	private void terminateApplication() {
		log.info("Closing MainFrame and Exit");
		System.exit(0);
	}

	/**
	 * Change order and reload
	 *
	 * @param order
	 *            the new order
	 * @see StudentenTableModel#setOrder(String)
	 */
	private void sortOrderChanged(String order) {
		log.info("Sort Order Changed to \"" + order + "\"");
		studentenTM.setOrder(order);
	}

	/**
	 * Export current view to XML or HTML file. Before saving a
	 * FileSelect-Dialog is shown to choose a filename and a location to save.
	 */
	private void export() {
		Export export = (Export) exportComboModel.getSelectedItem();
		// Create a file dialog to choose filename for export
		JFileChooser jfc = new JFileChooser();
		jfc.setDialogTitle("Filenamen fuer Export eingeben");
		jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
		int returnVal = jfc.showSaveDialog(this);
		// check if Export was confirmed or canceled by user
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			String filename = jfc.getSelectedFile().getPath();
			String extension = export.getExtension();
			if (!extension.startsWith(".")) {
				extension = "." + extension;
			}
			if (!filename.endsWith(extension)) {
				filename += extension;
			}
			log.info("Filename for export = \"" + filename + "\"");
			try {
				export.write(studentenTM.getStudenten(), filename);
				JOptionPane.showMessageDialog(this,
						"Daten wurden erfolgreich exportiert!", "File Export",
						JOptionPane.INFORMATION_MESSAGE);
			} catch (IOException e) {
				JOptionPane.showMessageDialog(this,
						"Beim Export ist ein Fehler aufgetreten!",
						"File Export", JOptionPane.WARNING_MESSAGE);
				log.error("File Writing Error: " + e);
			}
		}

	}

	/**
	 * UpdateListener waits for database-changes and udates the table.
	 *
	 * @author The SE-Team
	 * @see EditStudentFrame#addUpdateListener(ActionListener)
	 * @since 1.1
	 */
	class UpdateListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			log.info("Update studentTM");
			studentenTM.reload();
		}
	}

}


text:
In an earlier post on [`rescue_from`](rescue_from.md), I showed how you can
write an exception handler with a block argument.

If instead you'd prefer to implement the exception handler as a separate
method, you can do that by passing
[`rescue_from`](http://api.rubyonrails.org/classes/ActiveSupport/Rescuable/ClassMethods.html)
a `with` keyword argument. This too will behave as a catch-all for a particular
exception raised in your controller.

Here is what that can look like:

```ruby
class ApplicationController < ActionController::Base
  rescue_from User::NotAuthorized, with: :handle_unauthorized_user

  def index
    # ...
  end

  private

  def handle_unauthorized_user(exception)
    # respond with some Not Authorized page
  end
end
```

If the `User::NotAuthorized` exception bubbles up to the `rescue_from`, then it
will hand that exception off to the `handle_unauthorized_user` method. We can
include whatever logic and monitoring we want here and then render an
appropriate response.

redpajama_set_name: RedPajamaGithub


text:
package org.apache.felix.sigil.common.model;

import java.util.HashMap;
import java.util.Map;

/**
 * @author dave
 *
 */
public enum OverrideOptions
{
    NO("no"), MAY("may"), MUST("must");

    private String str;

    private static Map<String, OverrideOptions> map = new HashMap<String, OverrideOptions>();

    static
    {
        for (OverrideOptions option : OverrideOptions.values())
        {
            map.put(option.str.toLowerCase(), option);
        }
    }

    private OverrideOptions(String str)
    {
        this.str = str;
    }

    public static OverrideOptions parse(String val)
    {
        OverrideOptions option = map.get(val.toLowerCase());

        if (option == null)
        {
            throw new IllegalArgumentException("Invalid override value " + val);
        }

        return option;
    }

    @Override
    public String toString()
    {
        return str;
    }

}


text:
/**
 *  user
 */
#define USER_ID [FileCacheManager getValueInMyLocalStoreForKey:kUSER_ID_KEY]
/**
 *  Bounds
 */
#define kWindow [UIApplication sharedApplication].keyWindow
#define kScreenBounds [[UIScreen mainScreen] bounds]
#define kScreenWidth kScreenBounds.size.width
#define kScreenHeight kScreenBounds.size.height
/**
 *  Version
 */
#define kVersion [NSString stringWithFormat:@"%@",[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]]
#define kSystemVersion [[UIDevice currentDevice].systemVersion floatValue]
/**
 *  Network
 */
#define kNetworkType [AppUtility getNetworkType]

/**
 *  lazy
 */
#define kNotificationCenter [NSNotificationCenter defaultCenter]
#define WS(weakSelf)  __weak __typeof(&*self)weakSelf = self;

/**
 *  iPhone or iPad
 */
#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
#define IS_PAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
/**
 *  NSLog
 */
#if DEBUG
#define NSLog(FORMAT, ...) fprintf(stderr,"\nfunction:%s line:%d content:%s\n", __FUNCTION__, __LINE__, [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);
#else
#define NSLog(FORMAT, ...) nil
#endif

//NSCoding协议遵循
#define kObjectCodingAction  -(id)initWithCoder:(NSCoder *)aDecoder\
{\
self = [super init];\
if (self) {\
[self autoDecode:aDecoder];\
\
}\
return self;\
}\
-(void)encodeWithCoder:(NSCoder *)aCoder\
{\
[self autoEncodeWithCoder:aCoder];\
}\
-(void)setValue:(id)value forUndefinedKey:(NSString *)key\
{\
\
}
/**
 *  @param instead 需要给用户提醒的话,例子:XMCDeprecated("此方法已经过期")
 */
#define XMCDeprecated(instead) NS_DEPRECATED(2_0, 2_0, 2_0, 2_0, instead)

//#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_9_0
//
//#endif


text:
(function(){
  var requires, PermitRegistry, RuleRepo, createPermit;
  requires = require('../../requires');
  requires.test('test_setup');
  PermitRegistry = requires.permit('permit_registry');
  RuleRepo = requires.rule('rule_repo');
  createPermit = requires.fac('create-permit');
  describe('PermitRegistry', function(){
    var permits;
    permits = {};
    describe('create instance', function(){
      return specify('should throw error', function(){
        return function(){
          return new PermitRegistry;
        }.should['throw'];
      });
    });
    return context('singleton', function(){
      describe('initial state', function(){
        describe('permits', function(){
          return specify('should be empty', function(){
            return PermitRegistry.permits.should.eql({});
          });
        });
        describe('permit-counter', function(){
          return specify('should be 0', function(){
            return PermitRegistry.permitCounter.should.eql(0);
          });
        });
        return describe('calc-name', function(){
          return context('no argument', function(){
            return specify('should generate name Permit-0', function(){
              return PermitRegistry.calcName().should.eql('Permit-0');
            });
          });
        });
      });
      describe('register-permit', function(){
        return context('cleared permits', function(){
          before(function(){
            return PermitRegistry.clearAll();
          });
          return describe('permit-counter', function(){
            return specify('should reset to 0', function(){
              return PermitRegistry.calcName().should.eql('Permit-0');
            });
          });
        });
      });
      describe('create a permit', function(){
        before(function(){
          PermitRegistry.clearAll();
          return permits.guest = createPermit.guest();
        });
        describe('permits', function(){
          return specify('should have guest permit', function(){
            return PermitRegistry.permits['guest books'].should.eql(permits.guest);
          });
        });
        return describe('permit-counter', function(){
          return specify('should be 1', function(){
            return PermitRegistry.permitCounter.should.eql(1);
          });
        });
      });
      return context('guest permit', function(){
        before(function(){
          PermitRegistry.clearAll();
          return permits.guest = createPermit.guest();
        });
        describe('clear-all', function(){
          return context('cleared permits', function(){
            before(function(){
              return PermitRegistry.clearAll();
            });
            describe('permit-counter', function(){
              return specify('should reset to 0', function(){
                return PermitRegistry.calcName().should.eql('Permit-0');
              });
            });
            return describe('permits', function(){
              return specify('should be empty', function(){
                return PermitRegistry.permits.should.eql({});
              });
            });
          });
        });
        return describe('clean-all', function(){
          return context('cleaned permits', function(){
            var counters, repos;
            counters = {};
            repos = {};
            before(function(){
              PermitRegistry.clearAll();
              permits.guest = createPermit.guest();
              counters.old = PermitRegistry.permitCounter;
              permits.old = PermitRegistry.permits;
              repos.old = permits.guest.ruleRepo;
              permits.guest.debugOn();
              return PermitRegistry.cleanAll();
            });
            specify('old repo is a RuleRepo', function(){
              return repos.old.constructor.should.eql(RuleRepo);
            });
            describe('permit-counter', function(){
              return specify('should not change', function(){
                return PermitRegistry.permitCounter.should.eql(counters.old);
              });
            });
            describe('permits', function(){
              return specify('should not change', function(){
                return PermitRegistry.permits.should.eql(permits.old);
              });
            });
            return describe('repo', function(){
              return describe('should be cleaned', function(){
                var cleanedPermit;
                before(function(){
                  return cleanedPermit = PermitRegistry.permits['guest books'];
                });
                specify('repo is same instance', function(){
                  return cleanedPermit.ruleRepo.should.eql(repos.old);
                });
                specify('repo can-rules are empty', function(){
                  return cleanedPermit.ruleRepo.canRules.should.eql({});
                });
                specify('repo cannot-rules are empty', function(){
                  return cleanedPermit.ruleRepo.cannotRules.should.eql({});
                });
                specify('can-rules are empty', function(){
                  return cleanedPermit.canRules().should.eql({});
                });
                return specify('cannot-rules are empty', function(){
                  return cleanedPermit.cannotRules().should.eql({});
                });
              });
            });
          });
        });
      });
    });
  });
}).call(this);


text:
'use strict';

var expect = require('chai').expect,
    isValidMove = require('./is-valid-move'),
    constants = require('../get-constants')(),
    updateBoardSpace = require('../update/update-board-space'),
    createEmptyGame = require('../init/create-empty-game');

describe('is-valid-move', function() {

    it('empty moves are valid', function() {
        expect(isValidMove(createEmptyGame(), [])).to.equal(true);
    });

    it('does not allow moves that do not start on a valid space', function() {
        expect(isValidMove(createEmptyGame(), [{
            row: 9933,
            col: 232
        }])).to.equal(false);
    });

    it('does not allow moves that do not start on space with a piece', function() {
        expect(isValidMove(createEmptyGame(), [{
            row: 5,
            col: 1
        }])).to.equal(false);
    });

    describe('movingPlayer is specified', function() {

        it("allows starting with one of that player's pieces", function() {
            expect(isValidMove(createEmptyGame(), [{
                row: 5,
                col: 4
            }], 'playerA')).to.equal(true);
        });

        it("prohibits starting with one of the opponent's pieces", function() {
            expect(isValidMove(createEmptyGame(), [{
                row: 9,
                col: 4
            }], 'playerA')).to.equal(false);
        });

    });

    it('does not allow moves that do not start on a valid space and continue on to another invalid space', function() {
        expect(isValidMove(createEmptyGame(), [{
            row: 9933,
            col: 232
        }, {
            row: 234,
            col: 49
        }])).to.equal(false);
    });

    it('does not allow moves that do not start on a space containing a piece', function() {
        expect(isValidMove(createEmptyGame(), [{
            row: 6,
            col: 1
        },
        {
            row: 6,
            col: 2
        }])).to.equal(false);
    });

    it('allows a piece to move into an empty space', function() {
        var game = createEmptyGame();
        expect(isValidMove(game, [
            {
                row: 6,
                col: 4
            },
            {
                row: 7,
                col: 4
            }
        ])).to.equal(true);
    });

    it('allows a piece to jump over its own pieces', function() {
        var game = createEmptyGame();
        expect(isValidMove(game, [
            {
                row: 5,
                col: 6
            },
            {
                row: 7,
                col: 6
            }
        ])).to.equal(true);
    });

    it('does not allow a piece to jump over an empty space', function() {
        var game = createEmptyGame();
        expect(isValidMove(game, [
            {
                row: 5,
                col: 2
            },
            {
                row: 3,
                col: 2
            }
        ])).to.equal(false);
    });

    it('does not allow movement outside of the board', function() {
        var game = createEmptyGame(),
            outOfBoundsCol = 12;

        expect(isValidMove(game, [
            {
                row: 10,
                col: 11
            },
            {
                row: 10,
                col: outOfBoundsCol
            }
        ])).to.equal(false);
    });

    it('does not allow movement into another piece', function() {
        var game = createEmptyGame();
        expect(isValidMove(game, [
            {
                row: 5,
                col: 3
            },
            {
                row: 5,
                col: 4
            }
        ])).to.equal(false);
    });

    it('does not allow a jump of greater than one space', function() {
        var game = createEmptyGame();
        expect(isValidMove(game, [
            {
                row: 5,
                col: 3
            },
            {
                row: 12,
                col: 3
            }
        ])).to.equal(false);
    });

    it('does not allow a jump of greater than one space in the same row', function() {
        var game = createEmptyGame();
        expect(isValidMove(game, [
            {
                row: 5,
                col: 8
            },
            {
                row: 5,
                col: 0
            }
        ])).to.equal(false);
    });

    it('does not allow pawns to jump over both friendly and enemy pieces in the same jump', function() {
        var game = createEmptyGame(),
            withPawnInJumpRange = updateBoardSpace(game, 8, 5, {piece: {type: constants.PAWN, player: 'playerA'}});

        expect(isValidMove(withPawnInJumpRange, [
            {
                row: 10,
                col: 4
            },
            {
                row: 8,
                col: 4
            },
            {
                row: 8,
                col: 6
            }
        ])).to.equal(false);
    });

    it('does allow knights to jump over both friendly and enemy pieces in the same jump', function() {
        var game = createEmptyGame(),
            withPawnInJumpRange = updateBoardSpace(game, 4, 9, {piece: {type: constants.PAWN, player: 'playerB'}});

        expect(isValidMove(withPawnInJumpRange, [
            {
                row: 6,
                col: 8
            },
            {
                row: 4,
                col: 8
            },
            {
                row: 4,
                col: 10
            }
        ])).to.equal(true);
    });

    it('does not allow a jump followed by a non-jump', function() {
        var game = createEmptyGame();
        expect(isValidMove(game, [
            {
                row: 5,
                col: 6
            },
            {
                row: 7,
                col: 6
            },
            {
                row: 7,
                col: 7
            }
        ])).to.equal(false);
    });

    it('does not allow a non-jump followed by a jump', function() {
        var game = createEmptyGame();
        expect(isValidMove(game, [
            {
                row: 5,
                col: 6
            },
            {
                row: 7,
                col: 6
            },
            {
                row: 7,
                col: 7
            }
        ])).to.equal(false);
    });

    it('does not allow more than one non-jump', function() {
        var game = createEmptyGame();
        expect(isValidMove(game, [
            {
                row: 5,
                col: 6
            },
            {
                row: 4,
                col: 6
            },
            {
                row: 3,
                col: 6
            }
        ])).to.equal(false);
    });

    it('does not allow playerA to move into its own goal', function() {
        var game = createEmptyGame(),
            withPawnNearGoal = updateBoardSpace(game, 1, 5, {piece: {type: constants.PAWN, player: 'playerA'}});

        expect(isValidMove(withPawnNearGoal, [
            {
                row: 1,
                col: 5
            },
            {
                row: 0,
                col: 5
            }
        ])).to.equal(false);
    });

    it("does allow playerB to move into playerA's goal", function() {
        var game = createEmptyGame(),
            withPawnNearGoal = updateBoardSpace(game, 1, 5, {piece: {type: constants.PAWN, player: 'playerB'}});

        expect(isValidMove(withPawnNearGoal, [
            {
                row: 1,
                col: 5
            },
            {
                row: 0,
                col: 5
            }
        ])).to.equal(true);
    });

    it("does allow playerA to move into playerB's goal", function() {
        var game = createEmptyGame(),
            withPawnNearGoal = updateBoardSpace(game, 15, 5, {piece: {type: constants.PAWN, player: 'playerA'}});

        expect(isValidMove(withPawnNearGoal, [
            {
                row: 15,
                col: 5
            },
            {
                row: 16,
                col: 5
            }
        ])).to.equal(true);
    });

    it('does not allow playerB to move into its own goal', function() {
        var game = createEmptyGame(),
            withPawnNearGoal = updateBoardSpace(game, 15, 5, {piece: {type: constants.PAWN, player: 'playerB'}});

        expect(isValidMove(withPawnNearGoal, [
            {
                row: 15,
                col: 5
            },
            {
                row: 16,
                col: 5
            }
        ])).to.equal(false);
    });

    // Trying to avoid: https://cloud.githubusercontent.com/assets/829827/4100675/5b8df33a-30aa-11e4-8b06-b59e9b7b9433.PNG
    it('does not allow uneven diagonal movement along a col', function() {
        var game = createEmptyGame();

        expect(isValidMove(game, [
            {
                row: 6,
                col: 5
            },
            {
                row: 7,
                col: 7
            }
        ])).to.equal(false);
    });

    it('does not allow uneven diagonal movement along a row', function() {
        var game = createEmptyGame();

        expect(isValidMove(game, [
            {
                row: 6,
                col: 5
            },
            {
                row: 4,
                col: 4
            }
        ])).to.equal(false);
    });

});


text:
/*
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/

#include "stdafx.h"

#include "MediaCoordinate.h"

using namespace Nequeo::Net::PjSip;

/// <summary>
/// Representation of media coordinate.
/// </summary>
MediaCoordinate::MediaCoordinate() : _disposed(false)
{
}

///	<summary>
///	Representation of media coordinate.
///	</summary>
MediaCoordinate::~MediaCoordinate()
{
	if (!_disposed)
	{
		_disposed = true;
	}
}

/// <summary>
/// Gets or sets the X position of the coordinate.
/// </summary>
int MediaCoordinate::X::get()
{
	return _x;
}

/// <summary>
/// Gets or sets the X position of the coordinate.
/// </summary>
void MediaCoordinate::X::set(int value)
{
	_x = value;
}

/// <summary>
/// Gets or sets the Y position of the coordinate.
/// </summary>
int MediaCoordinate::Y::get()
{
	return _y;
}

/// <summary>
/// Gets or sets the Y position of the coordinate.
/// </summary>
void MediaCoordinate::Y::set(int value)
{
	_y = value;
}


text:
def startTrail():
    print("There are three trails to hike.")
    print("Type red, blue or green to choose your trail.")
    trail = input("> ")

    if trail == "red":
        redTrail()
    elif trail == "blue":
        blueTrail()
    else:
        greenTrail()

    print("The end.")

def redTrail():
    print("You hike the red trail.")
    print("The red trail is adventurous.")

startTrail()

# Challenge 1.1 - What happens if you try to hike the blue trail?
#    Fix it by defining and implementing the greenTrail and blueTrail
#    functions. For each, print strings of your choice!

# Challenge 1.2 - Make another function, chooseTrail, and move the
#    code that assigns the variable trail and the if-elif-else code there.
#    Change startTrail to call chooseTrail two times
#    in a row so you can now hike two different trails.

# BONUS Challenge 1.3 - Make the code allow you to go on an infinite hike...
#    until you input "stop", then it will say "The end." and stop.
# Hint: You will have to have a function call itself! Tricky!


text:
namespace sol {

	namespace detail {
		template <typename T>
		struct is_speshul : std::false_type {};
	} // namespace detail

	template <typename T>
	struct tie_size : std::tuple_size<T> {};

	template <typename T>
	struct is_tieable : std::integral_constant<bool, (::sol::tie_size<T>::value > 0)> {};

	template <typename... Tn>
	struct tie_t : public std::tuple<std::add_lvalue_reference_t<Tn>...> {
	private:
		typedef std::tuple<std::add_lvalue_reference_t<Tn>...> base_t;

		template <typename T>
		void set(std::false_type, T&& target) {
			std::get<0>(*this) = std::forward<T>(target);
		}

		template <typename T>
		void set(std::true_type, T&& target) {
			typedef tie_size<meta::unqualified_t<T>> value_size;
			typedef tie_size<std::tuple<Tn...>> tie_size;
			typedef meta::conditional_t<(value_size::value < tie_size::value), value_size, tie_size> indices_size;
			typedef std::make_index_sequence<indices_size::value> indices;
			set_extra(detail::is_speshul<meta::unqualified_t<T>>(), indices(), std::forward<T>(target));
		}

		template <std::size_t... I, typename T>
		void set_extra(std::true_type, std::index_sequence<I...>, T&& target) {
			using std::get;
			(void)detail::swallow{0,
				(get<I>(static_cast<base_t&>(*this)) = get<I>(types<Tn...>(), target), 0)..., 0};
		}

		template <std::size_t... I, typename T>
		void set_extra(std::false_type, std::index_sequence<I...>, T&& target) {
			using std::get;
			(void)detail::swallow{0,
				(get<I>(static_cast<base_t&>(*this)) = get<I>(target), 0)..., 0};
		}

	public:
		using base_t::base_t;

		template <typename T>
		tie_t& operator=(T&& value) {
			typedef is_tieable<meta::unqualified_t<T>> tieable;
			set(tieable(), std::forward<T>(value));
			return *this;
		}
	};

	template <typename... Tn>
	struct tie_size<tie_t<Tn...>> : std::tuple_size<std::tuple<Tn...>> {};

	namespace adl_barrier_detail {
		template <typename... Tn>
		inline tie_t<std::remove_reference_t<Tn>...> tie(Tn&&... argn) {
			return tie_t<std::remove_reference_t<Tn>...>(std::forward<Tn>(argn)...);
		}
	} // namespace adl_barrier_detail

	using namespace adl_barrier_detail;

} // namespace sol

#endif // SOL_TIE_HPP


text:
import { spy, stub } from "sinon";
import * as chai from "chai";
import * as chaiAsPromised from "chai-as-promised";
import * as proxyquire from "proxyquire";
import Client from "../src/client";
import EndpointNotFoundError from "../src/errors/endpoint-not-found";
import FormatNotImplementedError from "../src/errors/format-not-implemented";
import InvalidProviderResponseError from "../src/errors/invalid-provider-response";
import InvalidProviderResponseStatusError from "../src/errors/invalid-provider-response-status";
import Provider from "../src/provider";
import ResourceNotFoundError from "../src/errors/resource-not-found";
import StatusCodeError from "./helpers/status-code-error";
import UnauthorizedError from "../src/errors/unauthorized";

chai.use(chaiAsPromised);

const expect = chai.expect;

const providers: Provider[] = [
    {
        name: "Provider 1",
        url: "http://provider.one",
        endpoints: [
            {
                url: "http://provider.one",
                schemes: [ "http://*.provider.one", "http://provider.one/*" ],
                discovery: true,
            },
            {
                url: "https://provider.one",
                schemes: [ "https://*.provider.one", "https://provider.one/*" ],
                discovery: false,
            },
        ],
    },
    {
        name: "Provider 2",
        url: "http://provider.two",
        endpoints: [
            {
                url: "http://provider.two",
                schemes: [ "http://*.provider.two", "http://provider.two/*" ],
                discovery: true,
            },
            {
                url: "https://provider.two",
                schemes: [ "https://*.provider.two", "https://provider.two/*" ],
                discovery: false,
            },
        ],
    },
    {
        name: "Provider 3",
        url: "http://provider.three",
        endpoints: [
            { url: "http://provider.three" },
        ],
    },
];

describe("Client", () => {
    describe("#new()", () => {
        it("adds provided providers", () => {
            const client = new Client({ providers, importOembedProviders: false });

            expect(client.providers).to.eql(providers);
        });

        it("imports oembed providers", () => {
            const importer = spy();
            const client: Client = new (proxyquire("../src/client", {
                "./provider-importer": { import: importer },
            }).Client)({ importOembedProviders: true });

            importer.calledWith(client);
        });

        it("imports selected oembed providers", () => {
            const importer = spy();
            const client: Client = new (proxyquire("../src/client", {
                "./provider-importer": { import: importer },
            }).Client)({ importOembedProviders: providers.map((provider) => provider.name) });

            importer.calledWith(client, providers.map((provider) => provider.name));
        });
    });

    describe("#fetch()", () => {
        [
            {
                expectation: "fetches from provider matching scheme",
                url: "http://provider.two/something",
                providerUrl: providers[1].endpoints[0].url,
            },
            {
                expectation: "falls back to fetching from provider matching URL",
                url: "http://provider.three/something",
                providerUrl: providers[2].endpoints[0].url,
            },
        ].forEach((data) => {
            it(data.expectation, async () => {
                const response = { type: "type", version: "1.1" };

                const request = stub();
                const client = new (proxyquire("../src/client", {
                    "request-promise-native": request,
                }).Client)({ providers, importOembedProviders: false });

                request.withArgs({
                    method: "GET",
                    uri: data.providerUrl,
                    qs: { url: data.url, format: "json" },
                }).returns(JSON.stringify(response));

                expect(await client.fetch(data.url)).to.eql(response);
            });
        });

        it("passes through provided options", async () => {
            const url = "http://provider.one/something";

            const request = stub();
            const client = new (proxyquire("../src/client", {
                "request-promise-native": request,
            }).Client)({ providers, importOembedProviders: false });

            request.withArgs({
                method: "GET",
                uri: providers[0].endpoints[0].url,
                qs: { url, format: "json", maxwidth: 1000, maxheight: 2000, maxWow: 1337 },
            }).returns(JSON.stringify({ type: "type", version: "1.1" }));

            await client.fetch(url, { maxWidth: 1000, maxHeight: 2000, maxWow: 1337 });
        });

        it("throws exception if provider is not found", async () => {
            const client = new (proxyquire("../src/client", {
                "request-promise-native": stub(),
            }).Client)({ providers, importOembedProviders: false });

            await expect(client.fetch("http://non-existing-provider.com/something"))
                .to.eventually.be.rejectedWith(EndpointNotFoundError);
        });

        [
            {
                expectation: "throws exception if resource is not public",
                statusCode: 401,
                error: UnauthorizedError,
            },
            {
                expectation: "throws exception if resource is not found",
                statusCode: 404,
                error: ResourceNotFoundError,
            },
            {
                expectation: "throws exception if format is not supported",
                statusCode: 501,
                error: FormatNotImplementedError,
            },
            {
                expectation: "throws exception if provider response status isn't supported",
                statusCode: 500,
                error: InvalidProviderResponseStatusError,
            },
        ].forEach((data) => {
            it(data.expectation, async () => {
                const request = stub();
                const client = new (proxyquire("../src/client", {
                    "request-promise-native": request,
                }).Client)({ providers, importOembedProviders: false });

                request.throws(new StatusCodeError(data.statusCode));

                await expect(client.fetch("http://provider.one/something"))
                    .to.eventually.be.rejectedWith(data.error);
            });
        });

        [
            {
                expectation: "throws exception if provider response can't be JSON decoded",
                providerResponse: [],
                errorMessage: "valid JSON",
            },
            {
                expectation: "throws exception if provider response doesn't decode to object",
                providerResponse: "wowbed",
                errorMessage: "valid JSON",
            },
            {
                expectation: "throws exception if provider response doesn't have type",
                providerResponse: JSON.stringify({ version: "1.0" }),
                errorMessage: "type",
            },
            {
                expectation: "throws exception if provider response doesn't have version",
                providerResponse: JSON.stringify({ type: "type" }),
                errorMessage: "version",
            },
            {
                expectation: "throws exception if provider photo response doesn't have width",
                providerResponse: JSON.stringify({ type: "photo", version: "1.0", height: 1000, url: "" }),
                errorMessage: "width",
            },
            {
                expectation: "throws exception if provider photo response doesn't have height",
                providerResponse: JSON.stringify({ type: "photo", version: "1.0", width: 1000, url: "" }),
                errorMessage: "height",
            },
            {
                expectation: "throws exception if provider photo response doesn't have url",
                providerResponse: JSON.stringify({ type: "photo", version: "1.0", width: 1000, height: 1000 }),
                errorMessage: "url",
            },
            {
                expectation: "throws exception if provider rich response doesn't have width",
                providerResponse: JSON.stringify({ type: "rich", version: "1.0", height: 1000, html: "" }),
                errorMessage: "width",
            },
            {
                expectation: "throws exception if provider rich response doesn't have height",
                providerResponse: JSON.stringify({ type: "rich", version: "1.0", width: 1000, html: "" }),
                errorMessage: "height",
            },
            {
                expectation: "throws exception if provider rich response doesn't have html",
                providerResponse: JSON.stringify({ type: "rich", version: "1.0", width: 1000, height: 1000 }),
                errorMessage: "html",
            },
            {
                expectation: "throws exception if provider video response doesn't have width",
                providerResponse: JSON.stringify({ type: "video", version: "1.0", height: 1000, html: "" }),
                errorMessage: "width",
            },
            {
                expectation: "throws exception if provider video response doesn't have height",
                providerResponse: JSON.stringify({ type: "video", version: "1.0", width: 1000, html: "" }),
                errorMessage: "height",
            },
            {
                expectation: "throws exception if provider video response doesn't have html",
                providerResponse: JSON.stringify({ type: "video", version: "1.0", width: 1000, height: 1000 }),
                errorMessage: "html",
            },
        ].forEach((data) => {
            it(data.expectation, async () => {
                const request = stub();
                const client = new (proxyquire("../src/client", {
                    "request-promise-native": request,
                }).Client)({ providers, importOembedProviders: false });

                request.returns(data.providerResponse);

                await expect(client.fetch("http://provider.one/something"))
                    .to.eventually.be.rejectedWith(InvalidProviderResponseError, data.errorMessage);
            });
        });
    });
});


text:
package org.apache.camel.component.atomix.client.queue;

import java.util.Collections;
import java.util.Map;
import java.util.UUID;

import io.atomix.collections.DistributedQueue;
import org.apache.camel.Component;
import org.apache.camel.EndpointInject;
import org.apache.camel.FluentProducerTemplate;
import org.apache.camel.Message;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.atomix.client.AtomixClientConstants;
import org.apache.camel.component.atomix.client.AtomixClientTestSupport;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class AtomixQueueProducerTest extends AtomixClientTestSupport {
    private static final String QUEUE_NAME = UUID.randomUUID().toString();
    private DistributedQueue<Object> queue;

    @EndpointInject("direct:start")
    private FluentProducerTemplate fluent;

    // ************************************
    // Setup
    // ************************************

    @Override
    protected Map<String, Component> createComponents() {
        AtomixQueueComponent component = new AtomixQueueComponent();
        component.setNodes(Collections.singletonList(getReplicaAddress()));

        return Collections.singletonMap("atomix-queue", component);
    }

    @Override
    protected void doPreSetup() throws Exception {
        super.doPreSetup();

        queue = getClient().getQueue(QUEUE_NAME).join();
    }

    @Override
    @AfterEach
    public void tearDown() throws Exception {
        queue.close();

        super.tearDown();
    }

    // ************************************
    // Test
    // ************************************

    @Test
    void testAdd() {
        final String val1 = context().getUuidGenerator().generateUuid();
        final String val2 = context().getUuidGenerator().generateUuid();

        Message result;

        result = fluent.clearAll()
            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixQueue.Action.ADD)
            .withBody(val1)
            .request(Message.class);

        assertTrue(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
        assertTrue(queue.contains(val1).join());

        result = fluent.clearAll()
            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixQueue.Action.ADD)
            .withBody(val2)
            .request(Message.class);

        assertTrue(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
        assertTrue(queue.contains(val2).join());
    }

    @Test
    void testOfferPeekAndPoll() {
        final String val = context().getUuidGenerator().generateUuid();

        Message result;

        result = fluent.clearAll()
            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixQueue.Action.OFFER)
            .withBody(val)
            .request(Message.class);

        assertTrue(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
        assertTrue(queue.contains(val).join());

        result = fluent.clearAll()
            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixQueue.Action.PEEK)
            .request(Message.class);

        assertTrue(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
        assertTrue(queue.contains(val).join());
        assertEquals(val, result.getBody());

        result = fluent.clearAll()
            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixQueue.Action.POLL)
            .request(Message.class);

        assertTrue(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
        assertFalse(queue.contains(val).join());
        assertEquals(val, result.getBody());
    }

    @Test
    void testSizeClearIsEmpty() {
        final String val1 = context().getUuidGenerator().generateUuid();
        final String val2 = context().getUuidGenerator().generateUuid();

        Message result;

        result = fluent.clearAll()
            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixQueue.Action.SIZE)
            .request(Message.class);

        assertTrue(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
        assertEquals(0, result.getBody(Integer.class).intValue());
        assertEquals(queue.size().join(), result.getBody(Integer.class));

        queue.add(val1).join();
        queue.add(val2).join();

        result = fluent.clearAll()
            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixQueue.Action.SIZE)
            .request(Message.class);

        assertTrue(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
        assertEquals(queue.size().join(), result.getBody(Integer.class));

        result = fluent.clearAll()
            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixQueue.Action.IS_EMPTY)
            .request(Message.class);

        assertTrue(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
        assertFalse(result.getBody(Boolean.class));
        assertFalse(queue.isEmpty().join());

        result = fluent.clearAll()
            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixQueue.Action.CLEAR)
            .request(Message.class);

        assertFalse(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
        assertEquals(0, queue.size().join().intValue());

        result = fluent.clearAll()
            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixQueue.Action.IS_EMPTY)
            .request(Message.class);

        assertTrue(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
        assertTrue(result.getBody(Boolean.class));
        assertTrue(queue.isEmpty().join());
    }

    @Test
    void testContains() {
        final String val = context().getUuidGenerator().generateUuid();

        Message result;

        result = fluent.clearAll()
            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixQueue.Action.CONTAINS)
            .withBody(val)
            .request(Message.class);

        assertTrue(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
        assertFalse(result.getBody(Boolean.class));
        assertFalse(queue.contains(val).join());

        queue.add(val);

        result = fluent.clearAll()
            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixQueue.Action.CONTAINS)
            .withBody(val)
            .request(Message.class);

        assertTrue(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
        assertTrue(result.getBody(Boolean.class));
        assertTrue(queue.contains(val).join());
    }

    @Test
    void testRemove() {
        final String val1 = context().getUuidGenerator().generateUuid();
        final String val2 = context().getUuidGenerator().generateUuid();

        queue.add(val1).join();
        queue.add(val2).join();

        Message result;

        result = fluent.clearAll()
            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixQueue.Action.REMOVE)
            .withHeader(AtomixClientConstants.RESOURCE_VALUE, val1)
            .request(Message.class);

        assertTrue(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
        assertFalse(queue.contains(val1).join());
        assertTrue(queue.contains(val2).join());
    }

    // ************************************
    // Routes
    // ************************************
    @Override
    protected RoutesBuilder createRouteBuilder() {
        return new RouteBuilder() {
            public void configure() {
                from("direct:start")
                    .toF("atomix-queue:%s", QUEUE_NAME);
            }
        };
    }
}


text:
"""
Global cms settings, are applied if there isn't value defined in project
settings. All available settings are listed here. Please don't put any
functions / test inside, if you need to create some dynamic values / tests,
take look at cms.conf.patch
"""
import os
from django.conf import settings

# The id of default Site instance to be used for multisite purposes.
SITE_ID = 1

# Which templates should be used for extracting the placeholders?
# example: CMS_TEMPLATES = (('base.html', 'default template'),)
CMS_TEMPLATES = None

CMS_TEMPLATE_INHERITANCE = True
CMS_TEMPLATE_INHERITANCE_MAGIC = 'INHERIT'

CMS_PLACEHOLDER_CONF = {}

# Whether to enable permissions.
CMS_PERMISSION = False

# Show the publication date field in the admin, allows for future dating
# Changing this from True to False could cause some weirdness.  If that is required,
# you should update your database to correct any future dated pages
CMS_SHOW_START_DATE = False

# Show the publication end date field in the admin, allows for page expiration
# Changing this from True to False could cause some weirdness.  If that is required,
# you should update your database and null any pages with publication_end_date set.
CMS_SHOW_END_DATE = False

# Whether the user can overwrite the url of a page
CMS_URL_OVERWRITE = True

# Allow to overwrite the menu title
CMS_MENU_TITLE_OVERWRITE = False

# Are redirects activated?
CMS_REDIRECTS = False

# Allow the description, title and keywords meta tags to be edited from the
# admin
CMS_SEO_FIELDS = False

# a tuble with a python path to a function that returns a list of navigation nodes
CMS_NAVIGATION_EXTENDERS = ()

# a tuple with a python path to a function that receives all navigation nodes and can add or remove them
CMS_NAVIGATION_MODIFIERS = ()

# a tuple of hookable applications, e.g.:
# CMS_APPLICATIONS_URLS = (
#    ('sampleapp.urls', 'Sample application'),
# )
CMS_APPLICATIONS_URLS = ()

#Should the tree of the pages be also be displayed in the urls? or should a flat slug structure be used?
CMS_FLAT_URLS = False

# Wheter the cms has a softroot functionionality
CMS_SOFTROOT = False

#Hide untranslated Pages
CMS_HIDE_UNTRANSLATED = True

#Fall back to another language if the requested page isn't available in the preferred language
CMS_LANGUAGE_FALLBACK = True

#Configuration on how to order the fallbacks for languages.
# example: {'de': ['en', 'fr'],
#           'en': ['de'],
#          }
CMS_LANGUAGE_CONF = ()

# Defines which languages should be offered.
CMS_LANGUAGES = settings.LANGUAGES

# Defines how long page content should be cached, including navigation
CMS_CONTENT_CACHE_DURATION = 60

# Path for CMS media (uses <MEDIA_ROOT>/cms by default)
CMS_MEDIA_PATH = 'cms/'
CMS_MEDIA_ROOT = os.path.join(settings.MEDIA_ROOT, CMS_MEDIA_PATH)
CMS_MEDIA_URL = os.path.join(settings.MEDIA_URL, CMS_MEDIA_PATH)

# Path (relative to MEDIA_ROOT/MEDIA_URL) to directory for storing page-scope files.
CMS_PAGE_MEDIA_PATH = 'cms_page_media/'

# moderator mode - if True, approve path can be setup for every page, so there
# will be some control over the published stuff
CMS_MODERATOR = False

# Defines what character will be used for the __unicode__ handling of cms pages
CMS_TITLE_CHARACTER = '+'


text:
<?php

namespace Modules\Users\Database\Seeds;

use Nova\Database\ORM\Model;
use Nova\Database\Seeder;
use Nova\Support\Facades\DB;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the Database Seeds.
     *
     * @return void
     */
    public function run()
    {
        Model::unguard();

        // Disable the Foreign Key Checks.
        DB::statement('SET FOREIGN_KEY_CHECKS=0;');

        // Call the seeders.
        $this->call('Modules\Users\Database\Seeds\UsersTableSeeder');
        $this->call('Modules\Users\Database\Seeds\FieldItemsTableSeeder');
        $this->call('Modules\Users\Database\Seeds\FieldsTableSeeder');
        $this->call('Modules\Users\Database\Seeds\PermissionsTableSeeder');

        // Enable the Foreign Key Checks.
        DB::statement('SET FOREIGN_KEY_CHECKS=1;');
    }
}


text:
from rest_framework import serializers

from . import models
from clients import serializers as client_serializers
from users import serializers as user_serializers

class WorkTypeSerializer(serializers.ModelSerializer):

    name = serializers.CharField(read_only=True)

    class Meta:
        model = models.WorkType
        fields = ('id', 'work_type_id', 'name',)

class ArtTypeSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.ArtType
        fields = ('id', 'work_type', 'name',)

class ArtIgualaSerializer(serializers.ModelSerializer):

    art_type_name = serializers.CharField(source='art_type.name', read_only=True)

    class Meta:
        model = models.ArtIguala
        fields = ('id', 'iguala', 'art_type', 'quantity', 'art_type_name')

class IgualaSerializer(serializers.ModelSerializer):

    client_complete = client_serializers.ClientSerializer(source='client', read_only=True)
    art_iguala = ArtIgualaSerializer(many=True, read_only=True)

    class Meta:
        model = models.Iguala
        fields = ('id', 'client', 'client_complete', 'name', 'start_date', 'end_date',
                  'art_iguala',)

class StatusSerializer(serializers.ModelSerializer):

    name = serializers.CharField(source='__str__', read_only=True)

    class Meta:
        model = models.Status
        fields = ('id', 'status_id', 'name',)

class ArtWorkSerializer(serializers.ModelSerializer):

    art_type_complete = ArtTypeSerializer(source='art_type', read_only=True)

    class Meta:
        model = models.ArtWork
        fields = ('id', 'work', 'art_type', 'quantity', 'art_type_complete')

class FileSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.File
        fields = ('id', 'work', 'upload',)

class WorkDesignerSerializer(serializers.ModelSerializer):

    start_date = serializers.DateTimeField(read_only=True)
    end_date = serializers.DateTimeField(read_only=True)
    designer_name = serializers.CharField(source='designer.first_name', read_only=True)
    designer_last_name = serializers.CharField(source='designer.last_name', read_only=True)

    class Meta:
        model = models.WorkDesigner
        fields = ('id', 'designer', 'designer_name', 'designer_last_name', 'work',
                  'start_date', 'end_date', 'active_work',)

class StatusChangeSerializer(serializers.ModelSerializer):

    date = serializers.DateTimeField(read_only=True)

    class Meta:
        model = models.StatusChange
        fields = ('id', 'work', 'status', 'user', 'date',)

class WorkSerializer(serializers.ModelSerializer):

    creation_date = serializers.DateField(read_only=True)
    executive_complete = user_serializers.UserSerializer(source='executive', read_only=True)
    contact_complete = client_serializers.ContactSerializer(source='contact', read_only=True)
    current_status_complete = StatusSerializer(source='current_status', read_only=True)
    work_type_complete = WorkTypeSerializer(source='work_type', read_only=True)
    iguala_complete = IgualaSerializer(source='iguala', read_only=True)

    art_works = ArtWorkSerializer(many=True, read_only=True)
    files = FileSerializer(many=True, read_only=True)
    work_designers = WorkDesignerSerializer(many=True, read_only=True)
    status_changes = StatusChangeSerializer(many=True, read_only=True)

    class Meta:
        model = models.Work
        fields = ('id',
                  'executive',
                  'executive_complete',
                  'contact',
                  'contact_complete',
                  'current_status',
                  'current_status_complete',
                  'work_type',
                  'work_type_complete',
                  'iguala',
                  'iguala_complete',
                  'creation_date',
                  'name',
                  'expected_delivery_date',
                  'brief',
                  'final_link',
                  'art_works',
                  'files',
                  'work_designers',
                  'status_changes'
                  )

class NotificationSerializer(serializers.ModelSerializer):

    # work_complete = WorkSerializer(source='work', read_only=True)
    # user_complete = user_serializers.UserSerializer(source='user', read_only=True)

    class Meta:
        model = models.Notification
        fields = ('id', 'work', 'user', 'date', 'text', 'seen')


text:
using Html2Markdown.Replacement;
using HtmlAgilityPack;
using MarkdownGenerator.Helpers;
using System;
using System.Linq;

namespace MarkdownGenerator.Xml.Tags
{
    public class AnchorGet : NodeBase
    {
        public string Name { get; private set; }
        public string CustomText { get; private set; }

        public AnchorGet(Version version, HtmlNode element)
            : base(version, element)
        {
            this.Name = element.Attributes["name"].Value;
            this.CustomText = element.InnerHtml;
        }

        public override void ReplaceToMarkdown()
        {
            HtmlParser.ReplaceNode(Node, ToString());
        }

        public override string ToString()
        {
            // recupera apenas as versoes da mesma lingua em outras páginas
            var allPageVersion = Version.Page.Documentation.GetVersionsFromLanguage(Version.Language);
            var anchors = allPageVersion.SelectMany(f => f.Nodes).OfType<IAnchor>();

            var anchor = anchors.FirstOrDefault(f => f.Name == Name);
            if (anchor != null)
            {
                var text = string.IsNullOrWhiteSpace(CustomText) ? anchor.Text : CustomText;
                return MarkdownHelper.GetLinkFromAnchor(text, anchor.GetAnchorLink());
            }
            else
            {
                var exceptionDesc = $"The anchor '{Name}' doesn't exist for language version {Version.Language.Name}: {Node.ToString()}";
                return "<error>" + exceptionDesc + "</error>";
                throw new Exception(exceptionDesc);
            }
        }

    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>mne.open_report — MNE 0.20.7 documentation</title>
    <link rel="stylesheet" href="../_static/bootstrap-sphinx.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />
    <link rel="stylesheet" type="text/css" href="../_static/bootstrap_divs.css" />
    <link rel="stylesheet" type="text/css" href="../_static/gallery.css" />
    <link rel="stylesheet" type="text/css" href="../_static/gallery-binder.css" />
    <link rel="stylesheet" type="text/css" href="../_static/gallery-dataframe.css" />

    <link rel="shortcut icon" href="../_static/favicon.ico"/>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />

    <link rel="canonical" href="https://mne.tools/stable/index.html" />

    <link rel="stylesheet" href="../_static/style.css " type="text/css" />
    <link rel="stylesheet" href="../_static/font-awesome.css" type="text/css" />
    <link rel="stylesheet" href="../_static/font-source-code-pro.css" type="text/css" />
    <link rel="stylesheet" href="../_static/font-source-sans-pro.css" type="text/css" />
    <link rel="stylesheet" href="../_static/flag-icon.css" type="text/css" />

<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1'>
<meta name="apple-mobile-web-app-capable" content="yes">

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse">

        </button>

        0.20.7

Install

Overview

Tutorials

Examples

Glossary

API

Contribute

  Site

  <button type="button" class="btn btn-primary navbar-btn dropdown-toggle" id="dropdownMenu1" data-toggle="dropdown">
    v0.20.7

  </button>

Development

v0.20 (stable)

v0.19

v0.18

v0.17

v0.16

v0.15

v0.14

v0.13

v0.12

v0.11

<form class="navbar-form navbar-right" action="../search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

mne.open_report

Examples using mne.open_report

<form action="../search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

mne.open_report¶

mne.open_report(fname, **params)[source]¶

Read a saved report or, if it doesn't exist yet, create a new one.

The returned report can be used as a context manager, in which case any
changes to the report are saved when exiting the context block.

Parameters

fnamestr

The file containing the report, stored in the HDF5 format. If the file
does not exist yet, a new report is created that will be saved to the
specified file.

**paramskwargs

When creating a new report, any named parameters other than fname
are passed to the __init__ function of the Report object. When
reading an existing report, the parameters are checked with the
loaded report and an exception is raised when they don't match.

Returns

reportinstance of Report

The report.

Examples using mne.open_report¶

Getting started with mne.Report¶

GitHub

·

Mailing list

·

Gitter

·

What's new

·

Cite MNE

Back to top

© Copyright 2012-2020, MNE Developers. Last updated on 2020-07-10.


text:
Manage milestones on a issue tracker.

### Prepare:
```php
$issue = new Bitbucket\API\Repositories\Issues();
$issue->setCredentials( new Bitbucket\API\Authentication\Basic($bb_user, $bb_pass) );
```

### Fetch all milestones:
```php
$issue->milestones()->all($accountname, $repo_slug);
```

### Fetch a single milestone:
```php
$issue->milestones()->get($accountname, $repo_slug, 56735);
```

### Add a new milestone:
```php
$issue->milestones()->create($accountname, $repo_slug, 'dummy');
```

### Update an existing milestone:
```php
$issue->milestones()->update($accountname, $repo_slug, 56736, 'not dummy');
```

### Delete an existing milestone:
```php
$issue->milestones()->delete($accountname, $repo_slug, 56736);
```

----

#### Related:
  * [Authentication](../../authentication.md)
  * [Repository issues](../issues.md)
  * [BB Wiki](https://confluence.atlassian.com/display/BITBUCKET/issues+Resource#issuesResource-Overview)


text:
<?php

namespace Zend\Mvc;

use ArrayObject;
use Zend\EventManager\AbstractListenerAggregate;
use Zend\EventManager\EventManagerInterface;
use Zend\Router\RouteMatch;
use Zend\ServiceManager\Exception\InvalidServiceException;
use Zend\Stdlib\ArrayUtils;

/**
 * Default dispatch listener
 *
 * Pulls controllers from the service manager's "ControllerManager" service.
 *
 * If the controller cannot be found a "404" result is set up. Otherwise it
 * will continue to try to load the controller.
 *
 * If the controller is not dispatchable it sets up a "404" result. In case
 * of any other exceptions it trigger the "dispatch.error" event in an attempt
 * to return a 500 status.
 *
 * If the controller subscribes to InjectApplicationEventInterface, it injects
 * the current MvcEvent into the controller.
 *
 * It then calls the controller's "dispatch" method, passing it the request and
 * response. If an exception occurs, it triggers the "dispatch.error" event,
 * in an attempt to return a 500 status.
 *
 * The return value of dispatching the controller is placed into the result
 * property of the MvcEvent, and returned.
 */
class DispatchListener extends AbstractListenerAggregate
{
    /**
     * @var Controller\ControllerManager
     */
    private $controllerManager;

    /**
     * @param Controller\ControllerManager $controllerManager
     */
    public function __construct(Controller\ControllerManager $controllerManager)
    {
        $this->controllerManager = $controllerManager;
    }

    /**
     * Attach listeners to an event manager
     *
     * @param  EventManagerInterface $events
     * @param  int $priority
     * @return void
     */
    public function attach(EventManagerInterface $events, $priority = 1)
    {
        $this->listeners[] = $events->attach(MvcEvent::EVENT_DISPATCH, [$this, 'onDispatch']);
        if (function_exists('zend_monitor_custom_event_ex')) {
            $this->listeners[] = $events->attach(MvcEvent::EVENT_DISPATCH_ERROR, [$this, 'reportMonitorEvent']);
        }
    }

    /**
     * Listen to the "dispatch" event
     *
     * @param  MvcEvent $e
     * @return mixed
     */
    public function onDispatch(MvcEvent $e)
    {
        $routeMatch        = $e->getRouteMatch();
        $controllerName    = $routeMatch instanceof RouteMatch
            ? $routeMatch->getParam('controller', 'not-found')
            : 'not-found';
        $application       = $e->getApplication();
        $events            = $application->getEventManager();
        $controllerManager = $this->controllerManager;

        // Query abstract controllers, too!
        if (! $controllerManager->has($controllerName)) {
            $return = $this->marshalControllerNotFoundEvent($application::ERROR_CONTROLLER_NOT_FOUND, $controllerName, $e, $application);
            return $this->complete($return, $e);
        }

        try {
            $controller = $controllerManager->get($controllerName);
        } catch (Exception\InvalidControllerException $exception) {
            $return = $this->marshalControllerNotFoundEvent($application::ERROR_CONTROLLER_INVALID, $controllerName, $e, $application, $exception);
            return $this->complete($return, $e);
        } catch (InvalidServiceException $exception) {
            $return = $this->marshalControllerNotFoundEvent($application::ERROR_CONTROLLER_INVALID, $controllerName, $e, $application, $exception);
            return $this->complete($return, $e);
        } catch (\Throwable $exception) {
            $return = $this->marshalBadControllerEvent($controllerName, $e, $application, $exception);
            return $this->complete($return, $e);
        } catch (\Exception $exception) {  // @TODO clean up once PHP 7 requirement is enforced
            $return = $this->marshalBadControllerEvent($controllerName, $e, $application, $exception);
            return $this->complete($return, $e);
        }

        if ($controller instanceof InjectApplicationEventInterface) {
            $controller->setEvent($e);
        }

        $request  = $e->getRequest();
        $response = $application->getResponse();
        $caughtException = null;

        try {
            $return = $controller->dispatch($request, $response);
        } catch (\Throwable $ex) {
            $caughtException = $ex;
        } catch (\Exception $ex) {  // @TODO clean up once PHP 7 requirement is enforced
            $caughtException = $ex;
        }

        if ($caughtException !== null) {
            $e->setName(MvcEvent::EVENT_DISPATCH_ERROR);
            $e->setError($application::ERROR_EXCEPTION);
            $e->setController($controllerName);
            $e->setControllerClass(get_class($controller));
            $e->setParam('exception', $caughtException);

            $return = $application->getEventManager()->triggerEvent($e)->last();
            if (! $return) {
                $return = $e->getResult();
            }
        }

        return $this->complete($return, $e);
    }

    /**
     * @param MvcEvent $e
     */
    public function reportMonitorEvent(MvcEvent $e)
    {
        $error     = $e->getError();
        $exception = $e->getParam('exception');
        if ($exception instanceof \Exception || $exception instanceof \Throwable) {  // @TODO clean up once PHP 7 requirement is enforced
            zend_monitor_custom_event_ex($error, $exception->getMessage(), 'Zend Framework Exception', ['code' => $exception->getCode(), 'trace' => $exception->getTraceAsString()]);
        }
    }

    /**
     * Complete the dispatch
     *
     * @param  mixed $return
     * @param  MvcEvent $event
     * @return mixed
     */
    protected function complete($return, MvcEvent $event)
    {
        if (!is_object($return)) {
            if (ArrayUtils::hasStringKeys($return)) {
                $return = new ArrayObject($return, ArrayObject::ARRAY_AS_PROPS);
            }
        }
        $event->setResult($return);
        return $return;
    }

    /**
     * Marshal a controller not found exception event
     *
     * @param  string $type
     * @param  string $controllerName
     * @param  MvcEvent $event
     * @param  Application $application
     * @param  \Exception $exception
     * @return mixed
     */
    protected function marshalControllerNotFoundEvent(
        $type,
        $controllerName,
        MvcEvent $event,
        Application $application,
        \Exception $exception = null
    ) {
        $event->setName(MvcEvent::EVENT_DISPATCH_ERROR);
        $event->setError($type);
        $event->setController($controllerName);
        $event->setControllerClass('invalid controller class or alias: ' . $controllerName);
        if ($exception !== null) {
            $event->setParam('exception', $exception);
        }

        $events  = $application->getEventManager();
        $results = $events->triggerEvent($event);
        $return  = $results->last();
        if (! $return) {
            $return = $event->getResult();
        }
        return $return;
    }

    /**
     * Marshal a bad controller exception event
     *
     * @param  string $controllerName
     * @param  MvcEvent $event
     * @param  Application $application
     * @param  \Throwable|\Exception $exception
     * @return mixed
     */
    protected function marshalBadControllerEvent(
        $controllerName,
        MvcEvent $event,
        Application $application,
        $exception
    ) {
        $event->setName(MvcEvent::EVENT_DISPATCH_ERROR);
        $event->setError($application::ERROR_EXCEPTION);
        $event->setController($controllerName);
        $event->setParam('exception', $exception);

        $events  = $application->getEventManager();
        $results = $events->triggerEvent($event);
        $return  = $results->last();
        if (! $return) {
            return $event->getResult();
        }

        return $return;
    }
}


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

# mocap2mav
A publish/subscribe version of the mocap2mav architecture for controlling the IRIS quadcopter.


text:
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;

[assembly: AssemblyTitle("Caliburn Test Library")]
[assembly: Guid("8ad1d314-c977-421b-af73-5d5e258d0696")]

#if !SILVERLIGHT
[assembly: CLSCompliant(true)]
#endif

#if !NO_PARTIAL_TRUST
[assembly: AllowPartiallyTrustedCallers]
#endif


text:
package co.geomati.netcdf.aemet;

import java.awt.geom.Point2D;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;

import co.geomati.netcdf.Converter;
import co.geomati.netcdf.ConverterException;
import co.geomati.netcdf.DatasetConversion;
import co.geomati.netcdf.IConverter;
import co.geomati.netcdf.TimeUnit;
import co.geomati.netcdf.dataset.Dataset;

/**
 *

 * Converts the data from the aemet.
 *

 *

 * The converter takes a file and the suffix to search for the variables in the
 * vocabulary
 *

 *
 * @author fergonco, Micho Garcia
 *
 */
public class ConvertAEMET implements IConverter {

	private static final String RELATIVE_HUMIDITY = "rh";
	private static final String ATMOSPHERIC_TEMPERATURE = "at";
	private static final String WIND_SPEED = "ws";
	private static final String WIND_DIRECTION = "wd";
	private static Properties vocabulary;

	@Override
	public void doConversion(String[] files, String path) throws ConverterException, IOException {

		String[] meanDescriptions = new String[] { "hourly means",
				"daily night means (20:00-08:00)", "monthly means" };
		for (int i = 0; i < meanDescriptions.length; i++) {
			final String fileName = files[i];
			final String meanDescription = meanDescriptions[i];
			ByteArrayOutputStream os;
			try {
				BufferedInputStream is = new BufferedInputStream(
						new FileInputStream(new File(path + File.separator
								+ fileName + ".txt")));
				os = new ByteArrayOutputStream();
				IOUtils.copy(is, os);
				is.close();
				os.close();
			} catch (FileNotFoundException e) {
				throw new ConverterException("Cannot locate source file", e);
			} catch (IOException e) {
				throw new ConverterException("Cannot read source file", e);
			}
			String content = new String(os.toByteArray());

			String lat = getMatch(content, "LATITUDE: (.*)");
			String lon = getMatch(content, "LONGITUDE: (.*)");
			final Point2D pos = getPosition(lat, lon);

			final String variableName = getVariableName(
					getMatch(content, "PARAMETER: (.*)"), meanDescription);
			final String variableUnit = getMatch(content, "UNIT: (.*)");

			final Date referenceDate = new Date(0);
			final TimeUnit timeUnits = TimeUnit.SECOND;

			Pattern p = Pattern.compile("REM.*\n");
			Matcher matcher = p.matcher(content);
			int lastLineStart = -1;
			int lastLineEnd = -1;
			while (matcher.find()) {
				lastLineStart = matcher.start();
				lastLineEnd = matcher.end();
			}
			if (lastLineStart == -1 || lastLineEnd == -1) {
				throw new ConverterException("Cannot find last header line");
			}
			lastLineStart = lastLineStart + 5;// The REM0x
			String lastLine = content.substring(lastLineStart, lastLineEnd);
			final String[] fields = lastLine.trim().split("\\s+");

			// Add the prefix
			for (int j = 0; j < fields.length; j++) {
				fields[j] = getVariableName(fields[j], meanDescription);
			}

			// Get the data section
			final ArrayList<Integer> timestamps = new ArrayList<Integer>();
			final ArrayList<?>[] data = new ArrayList<?>[fields.length];

			content = content.substring(lastLineEnd);
			String[] lines = content.split("\n");
			for (String line : lines) {
				String[] fieldValues = line.split("\\s+");

				// Get seconds
				String date = fieldValues[0] + " " + fieldValues[1];
				try {
					int seconds = (int) (new SimpleDateFormat(
							"yyyy-MM-dd HH:mm").parse(date).getTime() / 1000);
					timestamps.add(seconds);
				} catch (ParseException e) {
					throw new ConverterException("Cannot parse date: " + date);
				}

				// get the rest
				for (int j = 2; j < fieldValues.length; j++) {
					String fieldValue = fieldValues[j];
					String fieldName = fields[j];

					// Ignore second date/time
					if (fieldName.equals("date")) {
						if (!fieldValue.equals("9999-99-99")) {
							throw new ConverterException(
									"Only continuous meassures supported");
						} else {
							continue;
						}
					}
					if (fieldName.equals("time")) {
						if (!fieldValue.equals("99:99")) {
							throw new ConverterException(
									"Only continuous meassures supported");
						} else {
							continue;
						}
					}

					// Fill the data
					ArrayList<?> array = data[j];
					if (fieldName.startsWith("nd")) {
						@SuppressWarnings("unchecked")
						ArrayList<Integer> intArray = (ArrayList<Integer>) array;
						if (intArray == null) {
							intArray = new ArrayList<Integer>();
							data[j] = intArray;
						}
						intArray.add(new Integer(fieldValue));
					} else {
						@SuppressWarnings("unchecked")
						ArrayList<Double> doubleArray = (ArrayList<Double>) array;
						if (doubleArray == null) {
							doubleArray = new ArrayList<Double>();
							data[j] = doubleArray;
						}
						doubleArray.add(new Double(fieldValue));
					}
				}
			}

			final ArrayList<String> atmosphericMeassures = new ArrayList<String>();
			for (String field : fields) {
				if (field.equals(WIND_DIRECTION) || field.equals(WIND_SPEED)
						|| field.equals(RELATIVE_HUMIDITY)
						|| field.equals(ATMOSPHERIC_TEMPERATURE)) {
					atmosphericMeassures.add(field);
				}
			}

			Converter.convert(new DatasetConversion() {

				@Override
				public int getDatasetCount() {
					return 1 + atmosphericMeassures.size();
				}

				@Override
				public Dataset getDataset(int index) throws ConverterException {
					String varName;
					if (index == 0) {
						varName = variableName;
					} else {
						varName = atmosphericMeassures.get(index - 1);
					}
					String longName;
					try {
						longName = getLongName(varName);
					} catch (IOException e) {
						throw new ConverterException(
								"Cannot access aemet vocabulary", e);
					}

					List<Double> mainVarData = getVariableData(varName, fields, data);

					if (index == 0) {
						List<Integer> ndData = getVariableData("nd", fields, data);
						List<Double> sdData = getVariableData("sd", fields, data);
						return new AEMETDataset(Collections.singletonList(pos),
								variableUnit, longName, varName,
								meanDescription, mainVarData, ndData, sdData,
								timestamps, referenceDate, timeUnits);
					} else {
						return new AEMETDataset(Collections.singletonList(pos),
								getUnit(varName), longName, varName,
								mainVarData, timestamps, referenceDate,
								timeUnits);
					}
				}

				private String getUnit(String varName) {
					if (varName.equals(RELATIVE_HUMIDITY)) {
						return "%";
					} else if (varName.equals(WIND_SPEED)) {
						return "m/s";
					} else if (varName.equals(ATMOSPHERIC_TEMPERATURE)) {
						return "ºC";
					} else if (varName.equals(WIND_DIRECTION)) {
						return "degree between true north and the wind direction. Increases in a clockwise direction";
					} else {
						throw new RuntimeException("Unsupported "
								+ "meteorological variable "
								+ "(see Table 9): " + varName);
					}
				}
			});
		}
	}

	private String getVariableName(String input, String suffix) {
		return input.toLowerCase().trim();
	}

	private <T> List<T> getVariableData(String variableName,
			String[] fields, ArrayList<?>[] data) throws ConverterException {
		for (int i = 0; i < fields.length; i++) {
			if (fields[i].startsWith(variableName)) {
				@SuppressWarnings("unchecked")
				List<T> ret = (List<T>) data[i];
				return ret;
			}
		}

		throw new ConverterException("Cannot find CO2");
	}

	private String getLongName(String variableName) throws IOException {
		if (vocabulary == null) {
			vocabulary = new Properties();
			vocabulary.load(ConvertAEMET.class
					.getResourceAsStream("vocabulary.properties"));
		}

		return vocabulary.getProperty(variableName);
	}

	private Point2D getPosition(String lat, String lon)
			throws ConverterException {
		double latitude = degreesToDouble(lat);
		double longitude = degreesToDouble(lon);

		return new Point2D.Double(longitude, latitude);
	}

	private double degreesToDouble(String latlon)
			throws ConverterException {
		latlon = latlon.trim();
		char northingWesting = latlon.charAt(latlon.length() - 1);
		int northingWestingCorrector = 1;
		if (northingWesting == 'S' || northingWesting == 'W') {
			northingWestingCorrector = -1;
		}
		String[] matches = getMatches(latlon.substring(0, latlon.length() - 1),
				"(\\d*)\\s*(\\d*)'");
		try {
			double ret = northingWestingCorrector
					* (Integer.parseInt(matches[0]) + Integer
							.parseInt(matches[1]) / 60.0);
			return ret;
		} catch (NumberFormatException e) {
			throw new ConverterException("Cannot parse "
					+ "latitude/longitude: " + latlon);
		}
	}

	private String getMatch(String content, String regexp) {
		return getMatches(content, regexp)[0];
	}

	private String[] getMatches(String content, String regexp) {
		Pattern p = Pattern.compile(regexp);
		Matcher matcher = p.matcher(content);
		if (matcher.find()) {
			String[] ret = new String[matcher.groupCount()];
			for (int i = 0; i < ret.length; i++) {
				ret[i] = matcher.group(i + 1);
			}
			return ret;
		} else {
			return null;
		}
	}
}


text:
################################################################################
# Description:
#    * Appends media information to the names of all video files in the given directory:
#       * Resolution (480p, 720p, 1080p)
#       * Number of audio channels (2ch, 6ch)
#
# Arguments:
#    * -r
#      Enables renaming of files; otherwise, merely prints out what the new file names would become if renames were
#      enabled
#
# Examples:
#    * Matrix (1999).wmv        -> Matrix (1999) [720p 6ch].wmv
#    * Star Trek (2009).mkv     -> Star Trek (2009) [720p 6ch].mkv
#    * TRON - Legacy (2010).mkv -> TRON - Legacy (2010) [1080p 6ch].mkv
#
# Limitations:
#    * Currently runs on Windows only
#    * Does not recognise when a file already has media information appended
#    * Does not attempt to synchronise names of subtitle files (*.srt) with those of video files
#    * Files with multiple audio streams result in unexpected channel counts; for instance, a file with both a
#      6-channel stream and a 2-channel stream would be appended with '62ch'
################################################################################

# Pragmas and modules
use Getopt::Std;
use File::Basename;

# Constants
use constant MEDIAINFO_PATH  => "E:\\MediaInfo_CLI_0.7.62_Windows_i386\\MediaInfo.exe";
use constant MIN_1080p_WIDTH => 1900;
use constant MIN_720p_WIDTH  => 1100;
use constant MIN_480p_WIDTH  => 600;

# Parse arguments
getopts('r');
my $num_args = $#ARGV + 1;  # Count begins at 0
my $directory;
if ($num_args != 1) {  # Expect exactly 1 argument
   my $script_name = basename($0);
   die("Usage: $script_name directory\n");
}
else {  # 1 argument given
   $directory = shift(@ARGV);
}

# If directory exists, retrieve all files in directory
my @files;
if (!-d $directory) {  # Directory does not exist
   die("Error: Directory '$directory' does not exist\n");
}
else {  # Directory exists
   # Retrieve contents of directory and populate array
   opendir(INPUT, $directory) or die ("Read of input directory '$directory' failed: $!\n");
   while(defined($file = readdir(INPUT))) {
      if (($file ne "."          ) &&  # Exclude listing for current directory
          ($file ne ".."         ) &&  # Exclude listing for parent directory
          (-f "$directory\\$file")) {  # Is a file, not a directory
         push(@files, $file);
      }
   }
   close(INPUT);  # Close directory handle

   # Print number of files found
   my $num_files_found = $#files + 1;  # Count begins at 0
   print("Found $num_files_found files in '$directory'\n");
   print("\n");
}

# Determine length of longest file name in directory
my $length_of_longest_file_name = 4;
foreach $file (@files) {
   my $file_name_length = length($file);
   if ($file_name_length > $length_of_longest_file_name) {
      $length_of_longest_file_name = $file_name_length;
   }
}

# Print column headers
printf("%-".$length_of_longest_file_name."s | %5s | %18s | %s\n",
       "File", "Width", "Information string", "New file name");
printf("%-".$length_of_longest_file_name."s-+-%5s-+-%18s-+-%s\n",
       "-" x $length_of_longest_file_name, "-" x 5, "-" x 18, "-" x 20);

# Operate on each file in directory
my $files_renamed;
foreach $file (@files) {
   # Obtain media information
   my $mediainfo_path = MEDIAINFO_PATH;  # FIXME: Is this really necessary?
   my $width = `$mediainfo_path --output=Video;%Width% \"$directory\\$file\"`;
   my $channels = `$mediainfo_path --output=Audio;%Channels% \"$directory\\$file\"`;
   chomp($width); chomp($channels);  # Remove trailing newline characters

   # Determine whether file is a video file
   my $is_video_file = ($width ne "");

   # Build information string to append to file name
   my $information_string;
   my $new_file_name;
   if ($is_video_file) {  # Is a video file
      # Parse media information
      my $resolution_descriptor = ($width >= MIN_1080p_WIDTH) ? "1080p"
                                : ($width >= MIN_720p_WIDTH)  ? "720p"
                                : ($width >= MIN_480p_WIDTH)  ? "480p"
                                :                               "SD";

      # Build information string
      $information_string = sprintf("[%s %sch]",
                                    $resolution_descriptor, $channels);

      # Build new file name
      my ($filename, $path_unused, $suffix) = fileparse($file, qr/\.[^.]*/);  # Resultant path is unused
      $new_file_name = sprintf("%s %s%s",
                               $filename, $information_string, $suffix);
   }

   # Print file name, video width, information string, and new file name
   printf("%-".$length_of_longest_file_name."s | %5s | %18s | %s\n",
          $file, $width, $information_string, $new_file_name);

   # If video file and renames enabled, perform rename
   if ($is_video_file && $opt_r) {  # Video file and renames enabled
      if (rename("$directory\\$file", "$directory\\$new_file_name")) {  # Rename successful
         $files_renamed++;
      }
   }
}
print("\n");

# Print number of files renamed
if ($opt_r) {  # Renames enabled
   printf("$files_renamed files renamed\n");
}
else {  # Renames disabled
   printf("Use '-r' option to perform renames\n");
}


text:
/****************************/
/* THIS IS OPEN SOURCE CODE */
/****************************/

/**
 * @file    example_multiple_components.c
 * @author  Vince Weaver
 *	    vweaver1@eecs.utk.edu
 * test if multiple components can be used at once
 *
 *
 * @brief
 *  This tests to see if the CPU component and Example component
 *   can be used simultaneously.
 */

#include <stdio.h>
#include <stdlib.h>
#include "papi_test.h"

#define NUM_EVENTS 1

int main (int argc, char **argv)
{

        int retval;
	int EventSet1 = PAPI_NULL, EventSet2 = PAPI_NULL;
	long long values1[NUM_EVENTS];
	long long values2[NUM_EVENTS];
	const PAPI_component_info_t *cmpinfo = NULL;
	int numcmp,cid,example_cid=-1;
	int code;

        /* Set TESTS_QUIET variable */
        tests_quiet( argc, argv );

	/* PAPI Initialization */
	retval = PAPI_library_init( PAPI_VER_CURRENT );
	if ( retval != PAPI_VER_CURRENT ) {
	   test_fail(__FILE__, __LINE__,"PAPI_library_init failed\n",retval);
	}

	if (!TESTS_QUIET) {
	   printf( "Testing simultaneous component use with PAPI %d.%d.%d\n",
			PAPI_VERSION_MAJOR( PAPI_VERSION ),
			PAPI_VERSION_MINOR( PAPI_VERSION ),
			PAPI_VERSION_REVISION( PAPI_VERSION ) );
	}

	/* Find our component */

	numcmp = PAPI_num_components();
	for( cid=0; cid<numcmp; cid++) {
	   if ( (cmpinfo = PAPI_get_component_info(cid)) == NULL) {
	      test_fail(__FILE__, __LINE__,
                           "PAPI_get_component_info failed\n", 0);
	   }
	   if (!TESTS_QUIET) {
	      printf("\tComponent %d - %d events - %s\n", cid,
		     cmpinfo->num_native_events,
		     cmpinfo->name);
	   }
	   if (strstr(cmpinfo->name,"example.c")) {
	      /* FOUND! */
	      example_cid=cid;
	   }
	}

	if (example_cid<0) {
	   test_skip(__FILE__, __LINE__,
		     "Example component not found\n", 0);
	}

	if (!TESTS_QUIET) {
	  printf("\nFound Example Component at id %d\n",example_cid);
	}

	/* Create an eventset for the Example component */

	retval = PAPI_create_eventset( &EventSet1 );
	if ( retval != PAPI_OK ) {
	   test_fail( __FILE__, __LINE__,
		      "PAPI_create_eventset() failed\n", retval );
	}

	retval = PAPI_event_name_to_code("EXAMPLE_CONSTANT", &code);
	if ( retval != PAPI_OK ) {
	   test_fail( __FILE__, __LINE__,
		      "EXAMPLE_ZERO not found\n",retval );
	}

	retval = PAPI_add_event( EventSet1, code);
	if ( retval != PAPI_OK ) {
	   test_fail( __FILE__, __LINE__,
		      "PAPI_add_events failed\n", retval );
	}

	/* Create an eventset for the CPU component */

	retval = PAPI_create_eventset( &EventSet2 );
	if ( retval != PAPI_OK ) {
	   test_fail( __FILE__, __LINE__,
		      "PAPI_create_eventset() failed\n", retval );
	}

	retval = PAPI_event_name_to_code("PAPI_TOT_CYC", &code);
	if ( retval != PAPI_OK ) {
	  test_skip( __FILE__, __LINE__,
		      "PAPI_TOT_CYC not available\n",retval );
	}

	retval = PAPI_add_event( EventSet2, code);
	if ( retval != PAPI_OK ) {
	   test_skip( __FILE__, __LINE__,
		      "NO CPU component found\n", retval );
	}

	if (!TESTS_QUIET) printf("\nStarting EXAMPLE_CONSTANT and PAPI_TOT_CYC at the same time\n");

	/* Start CPU component event */
	retval = PAPI_start( EventSet2 );
	if ( retval != PAPI_OK ) {
	   test_fail( __FILE__, __LINE__,
		      "PAPI_start failed\n",retval );
	}

	/* Start example component */
	retval = PAPI_start( EventSet1 );
	if ( retval != PAPI_OK ) {
	   test_fail( __FILE__, __LINE__,
		      "PAPI_start failed\n",retval );
	}

	/* Stop example component */
	retval = PAPI_stop( EventSet1, values1 );
	if ( retval != PAPI_OK ) {
	   test_fail(  __FILE__, __LINE__, "PAPI_stop failed\n", retval);
	}

	/* Stop CPU component */
	retval = PAPI_stop( EventSet2, values2 );
	if ( retval != PAPI_OK ) {
	   test_fail(  __FILE__, __LINE__, "PAPI_stop failed\n", retval);
	}

	if (!TESTS_QUIET) printf("Stopping EXAMPLE_CONSTANT and PAPI_TOT_CYC\n\n");

	if (!TESTS_QUIET) printf("Results from EXAMPLE_CONSTANT: %lld\n",values1[0]);

	if (values1[0]!=42) {
	   test_fail(  __FILE__, __LINE__, "Result should be 42!\n", 0);
	}

	if (!TESTS_QUIET) printf("Results from PAPI_TOT_CYC: %lld\n\n",values2[0]);

	if (values2[0]<1) {
	   test_fail(  __FILE__, __LINE__, "Result should greater than 0\n", 0);
	}

	/* Cleanup EventSets */
	retval = PAPI_cleanup_eventset(EventSet1);
	if (retval != PAPI_OK) {
	   test_fail(  __FILE__, __LINE__, "PAPI_cleanup_eventset!\n", retval);
	}

	retval = PAPI_cleanup_eventset(EventSet2);
	if (retval != PAPI_OK) {
	   test_fail(  __FILE__, __LINE__, "PAPI_cleanup_eventset!\n", retval);
	}

	/* Destroy EventSets */
	retval = PAPI_destroy_eventset(&EventSet2);
	if (retval != PAPI_OK) {
	   test_fail(  __FILE__, __LINE__, "PAPI_destroy_eventset!\n", retval);
	}

	test_pass( __FILE__, NULL, 0 );

	return 0;
}