text:
/** @file
 * @brief USART driver for Atmel SAM MCU family.
 *
 * Note:
 * - Only basic USART features sufficient to support printf functionality
 *   are currently implemented.
 */

#include <errno.h>
#include <misc/__assert.h>
#include <device.h>
#include <init.h>
#include <soc.h>
#include <uart.h>

/*
 * Verify Kconfig configuration
 */

#if CONFIG_USART_SAM_PORT_0 == 1

#if CONFIG_USART_SAM_PORT_0_BAUD_RATE == 0
#error "CONFIG_USART_SAM_PORT_0_BAUD_RATE has to be bigger than 0"
#endif

#endif

#if CONFIG_USART_SAM_PORT_1 == 1

#if CONFIG_USART_SAM_PORT_1_BAUD_RATE == 0
#error "CONFIG_USART_SAM_PORT_1_BAUD_RATE has to be bigger than 0"
#endif

#endif

#if CONFIG_USART_SAM_PORT_2 == 1

#if CONFIG_USART_SAM_PORT_2_BAUD_RATE == 0
#error "CONFIG_USART_SAM_PORT_2_BAUD_RATE has to be bigger than 0"
#endif

#endif

/* Device constant configuration parameters */
struct usart_sam_dev_cfg {
	Usart *regs;
	u32_t periph_id;
	struct soc_gpio_pin pin_rx;
	struct soc_gpio_pin pin_tx;

#ifdef CONFIG_UART_INTERRUPT_DRIVEN
	uart_irq_config_func_t	irq_config_func;
#endif
};

/* Device run time data */
struct usart_sam_dev_data {
	u32_t baud_rate;

#ifdef CONFIG_UART_INTERRUPT_DRIVEN
	uart_irq_callback_user_data_t irq_cb;	/* Interrupt Callback */
	void *cb_data;	/* Interrupt Callback Arg */
#endif /* CONFIG_UART_INTERRUPT_DRIVEN */
};

#define DEV_CFG(dev) \
	((const struct usart_sam_dev_cfg *const)(dev)->config->config_info)
#define DEV_DATA(dev) \
	((struct usart_sam_dev_data *const)(dev)->driver_data)

static int baudrate_set(Usart *const usart, u32_t baudrate,
			u32_t mck_freq_hz);

static int usart_sam_init(struct device *dev)
{
	int retval;
	const struct usart_sam_dev_cfg *const cfg = DEV_CFG(dev);
	struct usart_sam_dev_data *const dev_data = DEV_DATA(dev);
	Usart *const usart = cfg->regs;

	/* Enable USART clock in PMC */
	soc_pmc_peripheral_enable(cfg->periph_id);

	/* Connect pins to the peripheral */
	soc_gpio_configure(&cfg->pin_rx);
	soc_gpio_configure(&cfg->pin_tx);

	/* Reset and disable USART */
	usart->US_CR =   US_CR_RSTRX | US_CR_RSTTX
		       | US_CR_RXDIS | US_CR_TXDIS | US_CR_RSTSTA;

	/* Disable Interrupts */
	usart->US_IDR = 0xFFFFFFFF;

	/* 8 bits of data, no parity, 1 stop bit in normal mode */
	usart->US_MR =   US_MR_NBSTOP_1_BIT
		       | US_MR_PAR_NO
		       | US_MR_CHRL_8_BIT
		       | US_MR_USCLKS_MCK
		       | US_MR_CHMODE_NORMAL;

	/* Set baud rate */
	retval = baudrate_set(usart, dev_data->baud_rate,
			      SOC_ATMEL_SAM_MCK_FREQ_HZ);
	if (retval != 0) {
		return retval;
	};

	/* Enable receiver and transmitter */
	usart->US_CR = US_CR_RXEN | US_CR_TXEN;

#ifdef CONFIG_UART_INTERRUPT_DRIVEN
	cfg->irq_config_func(dev);
#endif /* CONFIG_UART_INTERRUPT_DRIVEN */

	return 0;
}

static int usart_sam_poll_in(struct device *dev, unsigned char *c)
{
	Usart *const usart = DEV_CFG(dev)->regs;

	if (!(usart->US_CSR & US_CSR_RXRDY)) {
		return -EBUSY;
	}

	/* got a character */
	*c = (unsigned char)usart->US_RHR;

	return 0;
}

static unsigned char usart_sam_poll_out(struct device *dev, unsigned char c)
{
	Usart *const usart = DEV_CFG(dev)->regs;

	/* Wait for transmitter to be ready */
	while (!(usart->US_CSR & US_CSR_TXRDY)) {
		;
	}

	/* send a character */
	usart->US_THR = (u32_t)c;
	return c;
}

static int usart_sam_err_check(struct device *dev)
{
	volatile Usart * const usart = DEV_CFG(dev)->regs;
	int errors = 0;

	if (usart->US_CSR & US_CSR_OVRE) {
		errors |= UART_ERROR_OVERRUN;
	}

	if (usart->US_CSR & US_CSR_PARE) {
		errors |= UART_ERROR_PARITY;
	}

	if (usart->US_CSR & US_CSR_FRAME) {
		errors |= UART_ERROR_FRAMING;
	}

	return errors;
}

static int baudrate_set(Usart *const usart, u32_t baudrate,
			u32_t mck_freq_hz)
{
	u32_t divisor;

	__ASSERT(baudrate,
		 "baud rate has to be bigger than 0");
	__ASSERT(mck_freq_hz/16 >= baudrate,
		 "MCK frequency is too small to set required baud rate");

	divisor = mck_freq_hz / 16 / baudrate;

	if (divisor > 0xFFFF) {
		return -EINVAL;
	};

	usart->US_BRGR = US_BRGR_CD(divisor);

	return 0;
}

#if CONFIG_UART_INTERRUPT_DRIVEN

static int usart_sam_fifo_fill(struct device *dev, const uint8_t *tx_data,
			       int size)
{
	volatile Usart * const usart = DEV_CFG(dev)->regs;

	/* Wait for transmitter to be ready. */
	while ((usart->US_CSR & US_CSR_TXRDY) == 0) {
		;
	}

	usart->US_THR = *tx_data;

	return 1;
}

static int usart_sam_fifo_read(struct device *dev, uint8_t *rx_data,
			       const int size)
{
	volatile Usart * const usart = DEV_CFG(dev)->regs;
	int bytes_read;

	bytes_read = 0;

	while (bytes_read < size) {
		if (usart->US_CSR & US_CSR_RXRDY) {
			rx_data[bytes_read] = usart->US_RHR;
			bytes_read++;
		} else {
			break;
		}
	}

	return bytes_read;
}

static void usart_sam_irq_tx_enable(struct device *dev)
{
	volatile Usart * const usart = DEV_CFG(dev)->regs;

	usart->US_IER = US_IER_TXRDY;
}

static void usart_sam_irq_tx_disable(struct device *dev)
{
	volatile Usart * const usart = DEV_CFG(dev)->regs;

	usart->US_IDR = US_IDR_TXRDY;
}

static int usart_sam_irq_tx_ready(struct device *dev)
{
	volatile Usart * const usart = DEV_CFG(dev)->regs;

	return (usart->US_CSR & US_CSR_TXRDY);
}

static void usart_sam_irq_rx_enable(struct device *dev)
{
	volatile Usart * const usart = DEV_CFG(dev)->regs;

	usart->US_IER = US_IER_RXRDY;
}

static void usart_sam_irq_rx_disable(struct device *dev)
{
	volatile Usart * const usart = DEV_CFG(dev)->regs;

	usart->US_IDR = US_IDR_RXRDY;
}

static int usart_sam_irq_tx_complete(struct device *dev)
{
	volatile Usart * const usart = DEV_CFG(dev)->regs;

	return !(usart->US_CSR & US_CSR_TXRDY);
}

static int usart_sam_irq_rx_ready(struct device *dev)
{
	volatile Usart * const usart = DEV_CFG(dev)->regs;

	return (usart->US_CSR & US_CSR_RXRDY);
}

static void usart_sam_irq_err_enable(struct device *dev)
{
	volatile Usart * const usart = DEV_CFG(dev)->regs;

	usart->US_IER = US_IER_OVRE | US_IER_FRAME | US_IER_PARE;
}

static void usart_sam_irq_err_disable(struct device *dev)
{
	volatile Usart * const usart = DEV_CFG(dev)->regs;

	usart->US_IDR = US_IDR_OVRE | US_IDR_FRAME | US_IDR_PARE;
}

static int usart_sam_irq_is_pending(struct device *dev)
{
	volatile Usart * const usart = DEV_CFG(dev)->regs;

	return    ((usart->US_CSR & US_CSR_TXRDY)
		| (usart->US_CSR & US_CSR_RXRDY));
}

static int usart_sam_irq_update(struct device *dev)
{
	volatile Usart * const usart = DEV_CFG(dev)->regs;

	return (usart->US_CSR & US_CSR_TXEMPTY);
}

static void usart_sam_irq_callback_set(struct device *dev,
				       uart_irq_callback_user_data_t cb,
				       void *cb_data)
{
	struct usart_sam_dev_data *const dev_data = DEV_DATA(dev);

	dev_data->irq_cb = cb;
	dev_data->cb_data = cb_data;
}

static void usart_sam_isr(void *arg)
{
	struct device *dev = arg;
	struct usart_sam_dev_data *const dev_data = DEV_DATA(dev);

	if (dev_data->irq_cb) {
		dev_data->irq_cb(dev_data->cb_data);
	}
}

#endif /* CONFIG_UART_INTERRUPT_DRIVEN */

static const struct uart_driver_api usart_sam_driver_api = {
	.poll_in = usart_sam_poll_in,
	.poll_out = usart_sam_poll_out,
	.err_check = usart_sam_err_check,
#ifdef CONFIG_UART_INTERRUPT_DRIVEN
	.fifo_fill = usart_sam_fifo_fill,
	.fifo_read = usart_sam_fifo_read,
	.irq_tx_enable = usart_sam_irq_tx_enable,
	.irq_tx_disable = usart_sam_irq_tx_disable,
	.irq_tx_ready = usart_sam_irq_tx_ready,
	.irq_rx_enable = usart_sam_irq_rx_enable,
	.irq_rx_disable = usart_sam_irq_rx_disable,
	.irq_tx_complete = usart_sam_irq_tx_complete,
	.irq_rx_ready = usart_sam_irq_rx_ready,
	.irq_err_enable = usart_sam_irq_err_enable,
	.irq_err_disable = usart_sam_irq_err_disable,
	.irq_is_pending = usart_sam_irq_is_pending,
	.irq_update = usart_sam_irq_update,
	.irq_callback_set = usart_sam_irq_callback_set,
#endif	/* CONFIG_UART_INTERRUPT_DRIVEN */
};

/* USART0 */

#ifdef CONFIG_USART_SAM_PORT_0

#ifdef CONFIG_UART_INTERRUPT_DRIVEN
/* Forward declare function */
static void usart0_sam_irq_config_func(struct device *port);
#endif /* CONFIG_UART_INTERRUPT_DRIVEN */

static const struct usart_sam_dev_cfg usart0_sam_config = {
	.regs = USART0,
	.periph_id = CONFIG_USART_SAM_PORT_0_PERIPHERAL_ID,
	.pin_rx = PIN_USART0_RXD,
	.pin_tx = PIN_USART0_TXD,

#ifdef CONFIG_UART_INTERRUPT_DRIVEN
	.irq_config_func = usart0_sam_irq_config_func,
#endif
};

static struct usart_sam_dev_data usart0_sam_data = {
	.baud_rate = CONFIG_USART_SAM_PORT_0_BAUD_RATE,
};

DEVICE_AND_API_INIT(usart0_sam, CONFIG_USART_SAM_PORT_0_NAME, &usart_sam_init,
		    &usart0_sam_data, &usart0_sam_config, PRE_KERNEL_1,
		    CONFIG_KERNEL_INIT_PRIORITY_DEVICE, &usart_sam_driver_api);

#ifdef CONFIG_UART_INTERRUPT_DRIVEN
static void usart0_sam_irq_config_func(struct device *port)
{
	IRQ_CONNECT(CONFIG_USART_SAM_PORT_0_IRQ,
		    CONFIG_USART_SAM_PORT_0_IRQ_PRIO,
		    usart_sam_isr,
		    DEVICE_GET(usart0_sam), 0);
	irq_enable(CONFIG_USART_SAM_PORT_0_IRQ);
}
#endif /* CONFIG_UART_INTERRUPT_DRIVEN */

#endif

/* USART1 */

#ifdef CONFIG_USART_SAM_PORT_1

#ifdef CONFIG_UART_INTERRUPT_DRIVEN
/* Forward declare function */
static void usart1_sam_irq_config_func(struct device *port);
#endif /* CONFIG_UART_INTERRUPT_DRIVEN */

static const struct usart_sam_dev_cfg usart1_sam_config = {
	.regs = USART1,
	.periph_id = CONFIG_USART_SAM_PORT_1_PERIPHERAL_ID,
	.pin_rx = PIN_USART1_RXD,
	.pin_tx = PIN_USART1_TXD,

#ifdef CONFIG_UART_INTERRUPT_DRIVEN
	.irq_config_func = usart1_sam_irq_config_func,
#endif
};

static struct usart_sam_dev_data usart1_sam_data = {
	.baud_rate = CONFIG_USART_SAM_PORT_1_BAUD_RATE,
};

DEVICE_AND_API_INIT(usart1_sam, CONFIG_USART_SAM_PORT_1_NAME, &usart_sam_init,
		    &usart1_sam_data, &usart1_sam_config, PRE_KERNEL_1,
		    CONFIG_KERNEL_INIT_PRIORITY_DEVICE, &usart_sam_driver_api);

#ifdef CONFIG_UART_INTERRUPT_DRIVEN
static void usart1_sam_irq_config_func(struct device *port)
{
	IRQ_CONNECT(CONFIG_USART_SAM_PORT_1_IRQ,
		    CONFIG_USART_SAM_PORT_1_IRQ_PRIO,
		    usart_sam_isr,
		    DEVICE_GET(usart1_sam), 0);
	irq_enable(CONFIG_USART_SAM_PORT_1_IRQ);
}
#endif /* CONFIG_UART_INTERRUPT_DRIVEN */

#endif

/* USART2 */

#ifdef CONFIG_USART_SAM_PORT_2
static const struct usart_sam_dev_cfg usart2_sam_config = {
	.regs = USART2,
	.periph_id = CONFIG_USART_SAM_PORT_3_PERIPHERAL_ID,
	.pin_rx = PIN_USART2_RXD,
	.pin_tx = PIN_USART2_TXD,
};

static struct usart_sam_dev_data usart2_sam_data = {
	.baud_rate = CONFIG_USART_SAM_PORT_2_BAUD_RATE,
};

DEVICE_AND_API_INIT(usart2_sam, CONFIG_USART_SAM_PORT_2_NAME, &usart_sam_init,
		    &usart2_sam_data, &usart2_sam_config, PRE_KERNEL_1,
		    CONFIG_KERNEL_INIT_PRIORITY_DEVICE, &usart_sam_driver_api);
#endif


text:
<?php

echo modules::run('_main/top');
?>

<?php
$views = array(
	'default' 		=> 'Best Match',
	'price_asc' 	=> 'Price Lowest First',
	'price_desc' 	=> 'Price Highest First',
	'item_az' 		=> 'Condition a-Z',
	'item_za' 		=> 'Condition Z-a'
	);

echo '

';
echo ''.$category['parent_title'].' > '.$category['cat_title'].'	';
echo 'Sort by  ';
echo '<select id="sort_by" onchange="sort_view(this.value)">';
foreach ($views as $key => $value) {
	if ($sort_view==$key){$selected=' SELECTED';}else{$selected='';}
	echo '<option value="'.$key.'"'.$selected.'>'.$value.'</option>';
}
echo '</select>

';
echo '	';
echo '

';
$i=0;
foreach ($products as $product_info) {
	if ($i!=0){
	echo '
';
	}
	echo '
';
	echo '
';
	echo '
';
	if ($product_info['image']!=''){
		$image_file = 'assets/images/products/'.$product_info['image'];
		if (file_exists($image_file)){
			echo ''.image_thumb('assets/images/products/'.$product_info['image'], 100, 100).'';
		}else{
			echo '';
		}
	}else{
		echo '';
	}
	echo '	'.$product_info['title'].'
';
	echo '
'.$product_info['description'].'
';
	echo '
<input type="button" class="buttonstyle" value="More Details" onclick="parent.location=\''.url().'products/p/'.$product_info['key'].'\';">	';
	echo '';
	echo 'Price: £'.number_format($product_info['price'],2).'';
	echo '	';
	echo '

 ';
	if ($product_info['buy']==1){
		echo '<input type="button" class="buttonstyle" value="Add To Basket" onclick="add_to_basket(\''.$product_info['key'].'\');">';
	}else{
		echo 'Product currently unavailable!';
	}
	echo '

';
	echo '
';
	$i++;
}
echo '

'.$this->pagination->create_links();
echo '
';
if ($num_pages>1){
	echo '
Items per page: ';
	$i=0;
	foreach ($per_page_array as $value) {
		if ($i!=0){
			echo ' | ';
		}
		if ($per_page==$value){
			echo $value;
		}else{
			echo ''.$value.'';
		}
		$i++;
	}
	echo '
';
}
?>

<?php echo modules::run('_main/bottom'); ?>

redpajama_set_name: RedPajamaGithub


text:
[![Build Status](https://travis-ci.org/kallisti-dev/hs-webdriver.svg?branch=master)](https://travis-ci.org/kallisti-dev/hs-webdriver)

hs-webdriver is a Selenium WebDriver client for the Haskell programming language. You can use it to automate browser sessions for testing, system administration, etc.

For more information about Selenium itself, see http://seleniumhq.org/

# Contents
* [Installation](#installation)
    * [Installation from Hackage](#installation-from-hackage)
    * [Installation from This Repository](#installation-from-this-repository)
* [Getting Started](#getting-started)
    * [Using the Selenium Server](#using-the-selenium-server)
    * [Hello, World!](#hello-world)
* [Integration with Haskell Testing Frameworks](#integration-with-haskell-testing-frameworks)
* [Documentation](#documentation)

# Installation
hs-webdriver uses the Cabal build system to configure, build, install, and generate documentation on multiple platforms.

For more information on using Cabal and its various installation options, see the Cabal User's Guide at http://www.haskell.org/cabal/users-guide/index.html

## Installation from Hackage
hs-webdriver is hosted on Hackage under the name webdriver. Thus, the simplest way to download and install the most recent version of hs-webdriver is to run:

```sh
cabal install webdriver
```
There are also options to do system-wide installation, version selection, and other build options; see cabal-install documentation.

## Installation from this repository

To build and install a git revision for a single user on your system, run these commands from within the repository directory

### Using cabal-install

```sh
cabal install
```

### Using Cabal

For systems without cabal-install available, you can also run the Setup.hs
script, as such:

```sh
runhaskell Setup.hs configure --user
runhaskell Setup.hs build
runhaskell Setup.hs install
```

For more build options, please refer to the Cabal documentation.

# Getting Started

WebDriver is a client-server protocol. Since hs-webdriver only implements a WebDriver client, you must have a WebDriver server to which you can connect in order to make use of this library.

## Using the Selenium Server
While you can use any WebDriver server out there, probably the simplest server to use with hs-webdriver is [Selenium Server](http://docs.seleniumhq.org/download/). You'll need an installation of the Java runtime to use this server. Once you've downloaded Selenium Server to your current working directory, you can start the server with this shell command:

    java -jar selenium-server-standalone-*.jar

The server should now be listening at localhost on port 4444.

Currently, `hs-webdriver` only supports selenium version 2.
The [beginner example](/examples/readme-example-beginner.md) was
tested with `selenium-server-standalone-2.53.1`.

## Hello, World!
With the Selenium server running locally, you're ready to write browser automation scripts in Haskell.

A [simple example can be found here](/examples/readme-example-beginner.md), written in literate Haskell so that you can compile it with GHC yourself. It is very beginner friendly and assumes no prior knowledge of Haskell. For other examples see the [examples](examples/) and [test/etc](test/etc/) directory.

# Integration with Haskell Testing Frameworks

This package does not provide utilities to integrate with popular Haskell testing frameworks. However, other packages exist for this purpose:

* [hspec-webdriver](https://hackage.haskell.org/package/hspec-webdriver)
* [quickcheck-webdriver](https://hackage.haskell.org/package/quickcheck-webdriver)

# Documentation

Documentation for hs-webdriver is available on Hackage at <http://hackage.haskell.org/package/webdriver>. You can also generate local HTML documentation from this source revision with the following shell command:

```sh
runhaskell Setup.hs haddock
```

Haddock will generate documentation and save it in `dist/doc/html/webdriver`


text:
:mod:`io` --- Core tools for working with streams
=================================================

.. module:: io
   :synopsis: Core tools for working with streams.
.. moduleauthor:: Guido van Rossum <guido@python.org>
.. moduleauthor:: Mike Verdone <mike.verdone@gmail.com>
.. moduleauthor:: Mark Russell <mark.russell@zen.co.uk>
.. moduleauthor:: Antoine Pitrou <solipsis@pitrou.net>
.. moduleauthor:: Amaury Forgeot d'Arc <amauryfa@gmail.com>
.. moduleauthor:: Benjamin Peterson <benjamin@python.org>
.. sectionauthor:: Benjamin Peterson <benjamin@python.org>

.. versionadded:: 2.6

The :mod:`io` module provides the Python interfaces to stream handling.
Under Python 2.x, this is proposed as an alternative to the built-in
:class:`file` object, but in Python 3.x it is the default interface to
access files and streams.

.. note::

   Since this module has been designed primarily for Python 3.x, you have to
   be aware that all uses of "bytes" in this document refer to the
   :class:`str` type (of which :class:`bytes` is an alias), and all uses
   of "text" refer to the :class:`unicode` type.  Furthermore, those two
   types are not interchangeable in the :mod:`io` APIs.

At the top of the I/O hierarchy is the abstract base class :class:`IOBase`.  It
defines the basic interface to a stream.  Note, however, that there is no
separation between reading and writing to streams; implementations are allowed
to raise an :exc:`IOError` if they do not support a given operation.

Extending :class:`IOBase` is :class:`RawIOBase` which deals simply with the
reading and writing of raw bytes to a stream.  :class:`FileIO` subclasses
:class:`RawIOBase` to provide an interface to files in the machine's
file system.

:class:`BufferedIOBase` deals with buffering on a raw byte stream
(:class:`RawIOBase`).  Its subclasses, :class:`BufferedWriter`,
:class:`BufferedReader`, and :class:`BufferedRWPair` buffer streams that are
readable, writable, and both readable and writable.
:class:`BufferedRandom` provides a buffered interface to random access
streams.  :class:`BytesIO` is a simple stream of in-memory bytes.

Another :class:`IOBase` subclass, :class:`TextIOBase`, deals with
streams whose bytes represent text, and handles encoding and decoding
from and to :class:`unicode` strings.  :class:`TextIOWrapper`, which extends
it, is a buffered text interface to a buffered raw stream
(:class:`BufferedIOBase`). Finally, :class:`StringIO` is an in-memory
stream for unicode text.

Argument names are not part of the specification, and only the arguments of
:func:`.open` are intended to be used as keyword arguments.

Module Interface
----------------

.. data:: DEFAULT_BUFFER_SIZE

   An int containing the default buffer size used by the module's buffered I/O
   classes.  :func:`.open` uses the file's blksize (as obtained by
   :func:`os.stat`) if possible.

.. function:: open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True)

   Open *file* and return a corresponding stream.  If the file cannot be opened,
   an :exc:`IOError` is raised.

   *file* is either a string giving the pathname (absolute or
   relative to the current working directory) of the file to be opened or
   an integer file descriptor of the file to be wrapped.  (If a file descriptor
   is given, it is closed when the returned I/O object is closed, unless
   *closefd* is set to ``False``.)

   *mode* is an optional string that specifies the mode in which the file is
   opened.  It defaults to ``'r'`` which means open for reading in text mode.
   Other common values are ``'w'`` for writing (truncating the file if it
   already exists), and ``'a'`` for appending (which on *some* Unix systems,
   means that *all* writes append to the end of the file regardless of the
   current seek position).  In text mode, if *encoding* is not specified the
   encoding used is platform dependent. (For reading and writing raw bytes use
   binary mode and leave *encoding* unspecified.)  The available modes are:

   ========= ===============================================================
   Character Meaning
   --------- ---------------------------------------------------------------
   ``'r'``   open for reading (default)
   ``'w'``   open for writing, truncating the file first
   ``'a'``   open for writing, appending to the end of the file if it exists
   ``'b'``   binary mode
   ``'t'``   text mode (default)
   ``'+'``   open a disk file for updating (reading and writing)
   ``'U'``   universal newline mode (for backwards compatibility; should
             not be used in new code)
   ========= ===============================================================

   The default mode is ``'rt'`` (open for reading text).  For binary random
   access, the mode ``'w+b'`` opens and truncates the file to 0 bytes, while
   ``'r+b'`` opens the file without truncation.

   Python distinguishes between files opened in binary and text modes, even when
   the underlying operating system doesn't.  Files opened in binary mode
   (including ``'b'`` in the *mode* argument) return contents as :class:`bytes`
   objects without any decoding.  In text mode (the default, or when ``'t'`` is
   included in the *mode* argument), the contents of the file are returned as
   :class:`unicode` strings, the bytes having been first decoded using a
   platform-dependent encoding or using the specified *encoding* if given.

   *buffering* is an optional integer used to set the buffering policy.
   Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
   line buffering (only usable in text mode), and an integer > 1 to indicate
   the size of a fixed-size chunk buffer.  When no *buffering* argument is
   given, the default buffering policy works as follows:

   * Binary files are buffered in fixed-size chunks; the size of the buffer
     is chosen using a heuristic trying to determine the underlying device's
     "block size" and falling back on :attr:`DEFAULT_BUFFER_SIZE`.
     On many systems, the buffer will typically be 4096 or 8192 bytes long.

   * "Interactive" text files (files for which :meth:`isatty` returns True)
     use line buffering.  Other text files use the policy described above
     for binary files.

   *encoding* is the name of the encoding used to decode or encode the file.
   This should only be used in text mode.  The default encoding is platform
   dependent (whatever :func:`locale.getpreferredencoding` returns), but any
   encoding supported by Python can be used.  See the :mod:`codecs` module for
   the list of supported encodings.

   *errors* is an optional string that specifies how encoding and decoding
   errors are to be handled--this cannot be used in binary mode.  Pass
   ``'strict'`` to raise a :exc:`ValueError` exception if there is an encoding
   error (the default of ``None`` has the same effect), or pass ``'ignore'`` to
   ignore errors.  (Note that ignoring encoding errors can lead to data loss.)
   ``'replace'`` causes a replacement marker (such as ``'?'``) to be inserted
   where there is malformed data.  When writing, ``'xmlcharrefreplace'``
   (replace with the appropriate XML character reference) or
   ``'backslashreplace'`` (replace with backslashed escape sequences) can be
   used.  Any other error handling name that has been registered with
   :func:`codecs.register_error` is also valid.

   *newline* controls how universal newlines works (it only applies to text
   mode).  It can be ``None``, ``''``, ``'\n'``, ``'\r'``, and ``'\r\n'``.  It
   works as follows:

   * On input, if *newline* is ``None``, universal newlines mode is enabled.
     Lines in the input can end in ``'\n'``, ``'\r'``, or ``'\r\n'``, and these
     are translated into ``'\n'`` before being returned to the caller.  If it is
     ``''``, universal newline mode is enabled, but line endings are returned to
     the caller untranslated.  If it has any of the other legal values, input
     lines are only terminated by the given string, and the line ending is
     returned to the caller untranslated.

   * On output, if *newline* is ``None``, any ``'\n'`` characters written are
     translated to the system default line separator, :data:`os.linesep`.  If
     *newline* is ``''``, no translation takes place.  If *newline* is any of
     the other legal values, any ``'\n'`` characters written are translated to
     the given string.

   If *closefd* is ``False`` and a file descriptor rather than a filename was
   given, the underlying file descriptor will be kept open when the file is
   closed.  If a filename is given *closefd* has no effect and must be ``True``
   (the default).

   The type of file object returned by the :func:`.open` function depends on the
   mode.  When :func:`.open` is used to open a file in a text mode (``'w'``,
   ``'r'``, ``'wt'``, ``'rt'``, etc.), it returns a subclass of
   :class:`TextIOBase` (specifically :class:`TextIOWrapper`).  When used to open
   a file in a binary mode with buffering, the returned class is a subclass of
   :class:`BufferedIOBase`.  The exact class varies: in read binary mode, it
   returns a :class:`BufferedReader`; in write binary and append binary modes,
   it returns a :class:`BufferedWriter`, and in read/write mode, it returns a
   :class:`BufferedRandom`.  When buffering is disabled, the raw stream, a
   subclass of :class:`RawIOBase`, :class:`FileIO`, is returned.

   It is also possible to use an :class:`unicode` or :class:`bytes` string
   as a file for both reading and writing.  For :class:`unicode` strings
   :class:`StringIO` can be used like a file opened in text mode,
   and for :class:`bytes` a :class:`BytesIO` can be used like a
   file opened in a binary mode.

.. exception:: BlockingIOError

   Error raised when blocking would occur on a non-blocking stream.  It inherits
   :exc:`IOError`.

   In addition to those of :exc:`IOError`, :exc:`BlockingIOError` has one
   attribute:

   .. attribute:: characters_written

      An integer containing the number of characters written to the stream
      before it blocked.

.. exception:: UnsupportedOperation

   An exception inheriting :exc:`IOError` and :exc:`ValueError` that is raised
   when an unsupported operation is called on a stream.

I/O Base Classes
----------------

.. class:: IOBase

   The abstract base class for all I/O classes, acting on streams of bytes.
   There is no public constructor.

   This class provides empty abstract implementations for many methods
   that derived classes can override selectively; the default
   implementations represent a file that cannot be read, written or
   seeked.

   Even though :class:`IOBase` does not declare :meth:`read`, :meth:`readinto`,
   or :meth:`write` because their signatures will vary, implementations and
   clients should consider those methods part of the interface.  Also,
   implementations may raise a :exc:`IOError` when operations they do not
   support are called.

   The basic type used for binary data read from or written to a file is
   :class:`bytes` (also known as :class:`str`).  :class:`bytearray`\s are
   accepted too, and in some cases (such as :class:`readinto`) required.
   Text I/O classes work with :class:`unicode` data.

   Note that calling any method (even inquiries) on a closed stream is
   undefined.  Implementations may raise :exc:`IOError` in this case.

   IOBase (and its subclasses) support the iterator protocol, meaning that an
   :class:`IOBase` object can be iterated over yielding the lines in a stream.
   Lines are defined slightly differently depending on whether the stream is
   a binary stream (yielding :class:`bytes`), or a text stream (yielding
   :class:`unicode` strings).  See :meth:`readline` below.

   IOBase is also a context manager and therefore supports the
   :keyword:`with` statement.  In this example, *file* is closed after the
   :keyword:`with` statement's suite is finished---even if an exception occurs::

      with io.open('spam.txt', 'w') as file:
          file.write(u'Spam and eggs!')

   :class:`IOBase` provides these data attributes and methods:

   .. method:: close()

      Flush and close this stream. This method has no effect if the file is
      already closed. Once the file is closed, any operation on the file
      (e.g. reading or writing) will raise a :exc:`ValueError`.

      As a convenience, it is allowed to call this method more than once;
      only the first call, however, will have an effect.

   .. attribute:: closed

      True if the stream is closed.

   .. method:: fileno()

      Return the underlying file descriptor (an integer) of the stream if it
      exists.  An :exc:`IOError` is raised if the IO object does not use a file
      descriptor.

   .. method:: flush()

      Flush the write buffers of the stream if applicable.  This does nothing
      for read-only and non-blocking streams.

   .. method:: isatty()

      Return ``True`` if the stream is interactive (i.e., connected to
      a terminal/tty device).

   .. method:: readable()

      Return ``True`` if the stream can be read from.  If False, :meth:`read`
      will raise :exc:`IOError`.

   .. method:: readline(limit=-1)

      Read and return one line from the stream.  If *limit* is specified, at
      most *limit* bytes will be read.

      The line terminator is always ``b'\n'`` for binary files; for text files,
      the *newlines* argument to :func:`.open` can be used to select the line
      terminator(s) recognized.

   .. method:: readlines(hint=-1)

      Read and return a list of lines from the stream.  *hint* can be specified
      to control the number of lines read: no more lines will be read if the
      total size (in bytes/characters) of all lines so far exceeds *hint*.

   .. method:: seek(offset, whence=SEEK_SET)

      Change the stream position to the given byte *offset*.  *offset* is
      interpreted relative to the position indicated by *whence*.  Values for
      *whence* are:

      * :data:`SEEK_SET` or ``0`` -- start of the stream (the default);
        *offset* should be zero or positive
      * :data:`SEEK_CUR` or ``1`` -- current stream position; *offset* may
        be negative
      * :data:`SEEK_END` or ``2`` -- end of the stream; *offset* is usually
        negative

      Return the new absolute position.

      .. versionadded:: 2.7
         The ``SEEK_*`` constants

   .. method:: seekable()

      Return ``True`` if the stream supports random access.  If ``False``,
      :meth:`seek`, :meth:`tell` and :meth:`truncate` will raise :exc:`IOError`.

   .. method:: tell()

      Return the current stream position.

   .. method:: truncate(size=None)

      Resize the stream to the given *size* in bytes (or the current position
      if *size* is not specified).  The current stream position isn't changed.
      This resizing can extend or reduce the current file size.  In case of
      extension, the contents of the new file area depend on the platform
      (on most systems, additional bytes are zero-filled, on Windows they're
      undetermined).  The new file size is returned.

   .. method:: writable()

      Return ``True`` if the stream supports writing.  If ``False``,
      :meth:`write` and :meth:`truncate` will raise :exc:`IOError`.

   .. method:: writelines(lines)

      Write a list of lines to the stream.  Line separators are not added, so it
      is usual for each of the lines provided to have a line separator at the
      end.

.. class:: RawIOBase

   Base class for raw binary I/O.  It inherits :class:`IOBase`.  There is no
   public constructor.

   Raw binary I/O typically provides low-level access to an underlying OS
   device or API, and does not try to encapsulate it in high-level primitives
   (this is left to Buffered I/O and Text I/O, described later in this page).

   In addition to the attributes and methods from :class:`IOBase`,
   RawIOBase provides the following methods:

   .. method:: read(n=-1)

      Read up to *n* bytes from the object and return them.  As a convenience,
      if *n* is unspecified or -1, :meth:`readall` is called.  Otherwise,
      only one system call is ever made.  Fewer than *n* bytes may be
      returned if the operating system call returns fewer than *n* bytes.

      If 0 bytes are returned, and *n* was not 0, this indicates end of file.
      If the object is in non-blocking mode and no bytes are available,
      ``None`` is returned.

   .. method:: readall()

      Read and return all the bytes from the stream until EOF, using multiple
      calls to the stream if necessary.

   .. method:: readinto(b)

      Read up to len(b) bytes into bytearray *b* and return the number
      of bytes read.  If the object is in non-blocking mode and no
      bytes are available, ``None`` is returned.

   .. method:: write(b)

      Write the given bytes or bytearray object, *b*, to the underlying raw
      stream and return the number of bytes written.  This can be less than
      ``len(b)``, depending on specifics of the underlying raw stream, and
      especially if it is in non-blocking mode.  ``None`` is returned if the
      raw stream is set not to block and no single byte could be readily
      written to it.

.. class:: BufferedIOBase

   Base class for binary streams that support some kind of buffering.
   It inherits :class:`IOBase`. There is no public constructor.

   The main difference with :class:`RawIOBase` is that methods :meth:`read`,
   :meth:`readinto` and :meth:`write` will try (respectively) to read as much
   input as requested or to consume all given output, at the expense of
   making perhaps more than one system call.

   In addition, those methods can raise :exc:`BlockingIOError` if the
   underlying raw stream is in non-blocking mode and cannot take or give
   enough data; unlike their :class:`RawIOBase` counterparts, they will
   never return ``None``.

   Besides, the :meth:`read` method does not have a default
   implementation that defers to :meth:`readinto`.

   A typical :class:`BufferedIOBase` implementation should not inherit from a
   :class:`RawIOBase` implementation, but wrap one, like
   :class:`BufferedWriter` and :class:`BufferedReader` do.

   :class:`BufferedIOBase` provides or overrides these members in addition to
   those from :class:`IOBase`:

   .. attribute:: raw

      The underlying raw stream (a :class:`RawIOBase` instance) that
      :class:`BufferedIOBase` deals with.  This is not part of the
      :class:`BufferedIOBase` API and may not exist on some implementations.

   .. method:: detach()

      Separate the underlying raw stream from the buffer and return it.

      After the raw stream has been detached, the buffer is in an unusable
      state.

      Some buffers, like :class:`BytesIO`, do not have the concept of a single
      raw stream to return from this method.  They raise
      :exc:`UnsupportedOperation`.

      .. versionadded:: 2.7

   .. method:: read(n=-1)

      Read and return up to *n* bytes.  If the argument is omitted, ``None``, or
      negative, data is read and returned until EOF is reached.  An empty bytes
      object is returned if the stream is already at EOF.

      If the argument is positive, and the underlying raw stream is not
      interactive, multiple raw reads may be issued to satisfy the byte count
      (unless EOF is reached first).  But for interactive raw streams, at most
      one raw read will be issued, and a short result does not imply that EOF is
      imminent.

      A :exc:`BlockingIOError` is raised if the underlying raw stream is in
      non blocking-mode, and has no data available at the moment.

   .. method:: read1(n=-1)

      Read and return up to *n* bytes, with at most one call to the underlying
      raw stream's :meth:`~RawIOBase.read` method.  This can be useful if you
      are implementing your own buffering on top of a :class:`BufferedIOBase`
      object.

   .. method:: readinto(b)

      Read up to len(b) bytes into bytearray *b* and return the number of bytes
      read.

      Like :meth:`read`, multiple reads may be issued to the underlying raw
      stream, unless the latter is 'interactive'.

      A :exc:`BlockingIOError` is raised if the underlying raw stream is in
      non blocking-mode, and has no data available at the moment.

   .. method:: write(b)

      Write the given bytes or bytearray object, *b* and return the number
      of bytes written (never less than ``len(b)``, since if the write fails
      an :exc:`IOError` will be raised).  Depending on the actual
      implementation, these bytes may be readily written to the underlying
      stream, or held in a buffer for performance and latency reasons.

      When in non-blocking mode, a :exc:`BlockingIOError` is raised if the
      data needed to be written to the raw stream but it couldn't accept
      all the data without blocking.

Raw File I/O
------------

.. class:: FileIO(name, mode='r', closefd=True)

   :class:`FileIO` represents an OS-level file containing bytes data.
   It implements the :class:`RawIOBase` interface (and therefore the
   :class:`IOBase` interface, too).

   The *name* can be one of two things:

   * a string representing the path to the file which will be opened;
   * an integer representing the number of an existing OS-level file descriptor
     to which the resulting :class:`FileIO` object will give access.

   The *mode* can be ``'r'``, ``'w'`` or ``'a'`` for reading (default), writing,
   or appending.  The file will be created if it doesn't exist when opened for
   writing or appending; it will be truncated when opened for writing.  Add a
   ``'+'`` to the mode to allow simultaneous reading and writing.

   The :meth:`read` (when called with a positive argument), :meth:`readinto`
   and :meth:`write` methods on this class will only make one system call.

   In addition to the attributes and methods from :class:`IOBase` and
   :class:`RawIOBase`, :class:`FileIO` provides the following data
   attributes and methods:

   .. attribute:: mode

      The mode as given in the constructor.

   .. attribute:: name

      The file name.  This is the file descriptor of the file when no name is
      given in the constructor.

Buffered Streams
----------------

Buffered I/O streams provide a higher-level interface to an I/O device
than raw I/O does.

.. class:: BytesIO([initial_bytes])

   A stream implementation using an in-memory bytes buffer.  It inherits
   :class:`BufferedIOBase`.

   The argument *initial_bytes* is an optional initial :class:`bytes`.

   :class:`BytesIO` provides or overrides these methods in addition to those
   from :class:`BufferedIOBase` and :class:`IOBase`:

   .. method:: getvalue()

      Return ``bytes`` containing the entire contents of the buffer.

   .. method:: read1()

      In :class:`BytesIO`, this is the same as :meth:`read`.

.. class:: BufferedReader(raw, buffer_size=DEFAULT_BUFFER_SIZE)

   A buffer providing higher-level access to a readable, sequential
   :class:`RawIOBase` object.  It inherits :class:`BufferedIOBase`.
   When reading data from this object, a larger amount of data may be
   requested from the underlying raw stream, and kept in an internal buffer.
   The buffered data can then be returned directly on subsequent reads.

   The constructor creates a :class:`BufferedReader` for the given readable
   *raw* stream and *buffer_size*.  If *buffer_size* is omitted,
   :data:`DEFAULT_BUFFER_SIZE` is used.

   :class:`BufferedReader` provides or overrides these methods in addition to
   those from :class:`BufferedIOBase` and :class:`IOBase`:

   .. method:: peek([n])

      Return bytes from the stream without advancing the position.  At most one
      single read on the raw stream is done to satisfy the call. The number of
      bytes returned may be less or more than requested.

   .. method:: read([n])

      Read and return *n* bytes, or if *n* is not given or negative, until EOF
      or if the read call would block in non-blocking mode.

   .. method:: read1(n)

      Read and return up to *n* bytes with only one call on the raw stream.  If
      at least one byte is buffered, only buffered bytes are returned.
      Otherwise, one raw stream read call is made.

.. class:: BufferedWriter(raw, buffer_size=DEFAULT_BUFFER_SIZE)

   A buffer providing higher-level access to a writeable, sequential
   :class:`RawIOBase` object.  It inherits :class:`BufferedIOBase`.
   When writing to this object, data is normally held into an internal
   buffer.  The buffer will be written out to the underlying :class:`RawIOBase`
   object under various conditions, including:

   * when the buffer gets too small for all pending data;
   * when :meth:`flush()` is called;
   * when a :meth:`seek()` is requested (for :class:`BufferedRandom` objects);
   * when the :class:`BufferedWriter` object is closed or destroyed.

   The constructor creates a :class:`BufferedWriter` for the given writeable
   *raw* stream.  If the *buffer_size* is not given, it defaults to
   :data:`DEFAULT_BUFFER_SIZE`.

   A third argument, *max_buffer_size*, is supported, but unused and deprecated.

   :class:`BufferedWriter` provides or overrides these methods in addition to
   those from :class:`BufferedIOBase` and :class:`IOBase`:

   .. method:: flush()

      Force bytes held in the buffer into the raw stream.  A
      :exc:`BlockingIOError` should be raised if the raw stream blocks.

   .. method:: write(b)

      Write the bytes or bytearray object, *b* and return the number of bytes
      written.  When in non-blocking mode, a :exc:`BlockingIOError` is raised
      if the buffer needs to be written out but the raw stream blocks.

.. class:: BufferedRWPair(reader, writer, buffer_size=DEFAULT_BUFFER_SIZE)

   A buffered I/O object giving a combined, higher-level access to two
   sequential :class:`RawIOBase` objects: one readable, the other writeable.
   It is useful for pairs of unidirectional communication channels
   (pipes, for instance).  It inherits :class:`BufferedIOBase`.

   *reader* and *writer* are :class:`RawIOBase` objects that are readable and
   writeable respectively.  If the *buffer_size* is omitted it defaults to
   :data:`DEFAULT_BUFFER_SIZE`.

   A fourth argument, *max_buffer_size*, is supported, but unused and
   deprecated.

   :class:`BufferedRWPair` implements all of :class:`BufferedIOBase`\'s methods
   except for :meth:`~BufferedIOBase.detach`, which raises
   :exc:`UnsupportedOperation`.

.. class:: BufferedRandom(raw, buffer_size=DEFAULT_BUFFER_SIZE)

   A buffered interface to random access streams.  It inherits
   :class:`BufferedReader` and :class:`BufferedWriter`, and further supports
   :meth:`seek` and :meth:`tell` functionality.

   The constructor creates a reader and writer for a seekable raw stream, given
   in the first argument.  If the *buffer_size* is omitted it defaults to
   :data:`DEFAULT_BUFFER_SIZE`.

   A third argument, *max_buffer_size*, is supported, but unused and deprecated.

   :class:`BufferedRandom` is capable of anything :class:`BufferedReader` or
   :class:`BufferedWriter` can do.

Text I/O
--------

.. class:: TextIOBase

   Base class for text streams.  This class provides an unicode character
   and line based interface to stream I/O.  There is no :meth:`readinto`
   method because Python's :class:`unicode` strings are immutable.
   It inherits :class:`IOBase`.  There is no public constructor.

   :class:`TextIOBase` provides or overrides these data attributes and
   methods in addition to those from :class:`IOBase`:

   .. attribute:: encoding

      The name of the encoding used to decode the stream's bytes into
      strings, and to encode strings into bytes.

   .. attribute:: errors

      The error setting of the decoder or encoder.

   .. attribute:: newlines

      A string, a tuple of strings, or ``None``, indicating the newlines
      translated so far.  Depending on the implementation and the initial
      constructor flags, this may not be available.

   .. attribute:: buffer

      The underlying binary buffer (a :class:`BufferedIOBase` instance) that
      :class:`TextIOBase` deals with.  This is not part of the
      :class:`TextIOBase` API and may not exist on some implementations.

   .. method:: detach()

      Separate the underlying binary buffer from the :class:`TextIOBase` and
      return it.

      After the underlying buffer has been detached, the :class:`TextIOBase` is
      in an unusable state.

      Some :class:`TextIOBase` implementations, like :class:`StringIO`, may not
      have the concept of an underlying buffer and calling this method will
      raise :exc:`UnsupportedOperation`.

      .. versionadded:: 2.7

   .. method:: read(n)

      Read and return at most *n* characters from the stream as a single
      :class:`unicode`.  If *n* is negative or ``None``, reads until EOF.

   .. method:: readline()

      Read until newline or EOF and return a single ``unicode``.  If the
      stream is already at EOF, an empty string is returned.

   .. method:: write(s)

      Write the :class:`unicode` string *s* to the stream and return the
      number of characters written.

.. class:: TextIOWrapper(buffer, encoding=None, errors=None, newline=None, line_buffering=False)

   A buffered text stream over a :class:`BufferedIOBase` binary stream.
   It inherits :class:`TextIOBase`.

   *encoding* gives the name of the encoding that the stream will be decoded or
   encoded with.  It defaults to :func:`locale.getpreferredencoding`.

   *errors* is an optional string that specifies how encoding and decoding
   errors are to be handled.  Pass ``'strict'`` to raise a :exc:`ValueError`
   exception if there is an encoding error (the default of ``None`` has the same
   effect), or pass ``'ignore'`` to ignore errors.  (Note that ignoring encoding
   errors can lead to data loss.)  ``'replace'`` causes a replacement marker
   (such as ``'?'``) to be inserted where there is malformed data.  When
   writing, ``'xmlcharrefreplace'`` (replace with the appropriate XML character
   reference) or ``'backslashreplace'`` (replace with backslashed escape
   sequences) can be used.  Any other error handling name that has been
   registered with :func:`codecs.register_error` is also valid.

   *newline* can be ``None``, ``''``, ``'\n'``, ``'\r'``, or ``'\r\n'``.  It
   controls the handling of line endings.  If it is ``None``, universal newlines
   is enabled.  With this enabled, on input, the lines endings ``'\n'``,
   ``'\r'``, or ``'\r\n'`` are translated to ``'\n'`` before being returned to
   the caller.  Conversely, on output, ``'\n'`` is translated to the system
   default line separator, :data:`os.linesep`.  If *newline* is any other of its
   legal values, that newline becomes the newline when the file is read and it
   is returned untranslated.  On output, ``'\n'`` is converted to the *newline*.

   If *line_buffering* is ``True``, :meth:`flush` is implied when a call to
   write contains a newline character.

   :class:`TextIOWrapper` provides one attribute in addition to those of
   :class:`TextIOBase` and its parents:

   .. attribute:: line_buffering

      Whether line buffering is enabled.

.. class:: StringIO(initial_value=u'', newline=None)

   An in-memory stream for unicode text.  It inherits :class:`TextIOWrapper`.

   The initial value of the buffer (an empty unicode string by default) can
   be set by providing *initial_value*.  The *newline* argument works like
   that of :class:`TextIOWrapper`.  The default is to do no newline
   translation.

   :class:`StringIO` provides this method in addition to those from
   :class:`TextIOWrapper` and its parents:

   .. method:: getvalue()

      Return a ``unicode`` containing the entire contents of the buffer at any
      time before the :class:`StringIO` object's :meth:`close` method is
      called.

   Example usage::

      import io

      output = io.StringIO()
      output.write(u'First line.\n')
      output.write(u'Second line.\n')

      # Retrieve file contents -- this will be
      # u'First line.\nSecond line.\n'
      contents = output.getvalue()

      # Close object and discard memory buffer --
      # .getvalue() will now raise an exception.
      output.close()

.. class:: IncrementalNewlineDecoder

   A helper codec that decodes newlines for universal newlines mode.  It
   inherits :class:`codecs.IncrementalDecoder`.

Advanced topics
---------------

Here we will discuss several advanced topics pertaining to the concrete
I/O implementations described above.

Performance
^^^^^^^^^^^

Binary I/O
""""""""""

By reading and writing only large chunks of data even when the user asks
for a single byte, buffered I/O is designed to hide any inefficiency in
calling and executing the operating system's unbuffered I/O routines.  The
gain will vary very much depending on the OS and the kind of I/O which is
performed (for example, on some contemporary OSes such as Linux, unbuffered
disk I/O can be as fast as buffered I/O).  The bottom line, however, is
that buffered I/O will offer you predictable performance regardless of the
platform and the backing device.  Therefore, it is most always preferable to
use buffered I/O rather than unbuffered I/O.

Text I/O
""""""""

Text I/O over a binary storage (such as a file) is significantly slower than
binary I/O over the same storage, because it implies conversions from
unicode to binary data using a character codec.  This can become noticeable
if you handle huge amounts of text data (for example very large log files).
Also, :meth:`TextIOWrapper.tell` and :meth:`TextIOWrapper.seek` are both
quite slow due to the reconstruction algorithm used.

:class:`StringIO`, however, is a native in-memory unicode container and will
exhibit similar speed to :class:`BytesIO`.

Multi-threading
^^^^^^^^^^^^^^^

:class:`FileIO` objects are thread-safe to the extent that the operating
system calls (such as ``read(2)`` under Unix) they are wrapping are thread-safe
too.

Binary buffered objects (instances of :class:`BufferedReader`,
:class:`BufferedWriter`, :class:`BufferedRandom` and :class:`BufferedRWPair`)
protect their internal structures using a lock; it is therefore safe to call
them from multiple threads at once.

:class:`TextIOWrapper` objects are not thread-safe.

Reentrancy
^^^^^^^^^^

Binary buffered objects (instances of :class:`BufferedReader`,
:class:`BufferedWriter`, :class:`BufferedRandom` and :class:`BufferedRWPair`)
are not reentrant.  While reentrant calls will not happen in normal situations,
they can arise if you are doing I/O in a :mod:`signal` handler.  If it is
attempted to enter a buffered object again while already being accessed
*from the same thread*, then a :exc:`RuntimeError` is raised.

The above implicitly extends to text files, since the :func:`open()`
function will wrap a buffered object inside a :class:`TextIOWrapper`.  This
includes standard streams and therefore affects the built-in function
:func:`print()` as well.


text:
@implementation NSString (FUAdditions)

- (NSString *)stringByEnsuringURLSchemePrefix {
    if (![self hasSupportedSchemePrefix]) {
        return [NSString stringWithFormat:@"%@%@", kFUHTTPSchemePrefix, self];
    }
    return self;
}

- (NSString *)stringByTrimmingURLSchemePrefix {
    NSString *s = [[self copy] autorelease];

    if ([s hasPrefix:kFUHTTPSchemePrefix]) {
        s = [s substringFromIndex:[kFUHTTPSchemePrefix length]];
    } else if ([s hasPrefix:kFUHTTPSSchemePrefix]) {
        s = [s substringFromIndex:[kFUHTTPSSchemePrefix length]];
    } else if ([s hasPrefix:kFUFileSchemePrefix]) {
        s = [s substringFromIndex:[kFUFileSchemePrefix length]];
    } else if ([s hasPrefix:kFUJavaScriptSchemePrefix]) {
        s = [s substringFromIndex:[kFUJavaScriptSchemePrefix length]];
    }

    return s;
}

- (NSString *)stringByEnsuringTLDSuffix {
    if (![self hasTLDSuffix]) {
        return [NSString stringWithFormat:@"%@.com", self];
    }
    return self;
}

- (BOOL)hasHTTPSchemePrefix {
    return [self hasPrefix:kFUHTTPSchemePrefix] || [self hasPrefix:kFUHTTPSSchemePrefix];
}

- (BOOL)hasJavaScriptSchemePrefix {
    return [self hasPrefix:kFUJavaScriptSchemePrefix];
}

- (BOOL)hasSupportedSchemePrefix {
    return [self hasHTTPSchemePrefix]
        || [self hasPrefix:kFUFileSchemePrefix]
        || [self hasPrefix:@"mailto:"]
        || [self hasPrefix:@"about:"]
        || [self hasPrefix:@"data:"]
        || [self hasPrefix:@"file:"]
        || [self hasJavaScriptSchemePrefix];
}

- (BOOL)hasTLDSuffix {
    return (NSNotFound != [self rangeOfString:@"."].location);
}

@end


text:
package org.apache.nifi.processors.windows.event.log;

public class AlreadySubscribedException extends Exception {
    public AlreadySubscribedException(String message) {
        super(message);
    }
}


text:
InstantMessages Tempalate Engine
=====

This library is open source. Please help me by forking the project and adding to it.
-----------------------------------------------

About
-----------------------------------------------

A small template engine that allows you easily render your emails, messages, etc. with file or database templates.
It's really smaller and faster than Views.

Getting Started
---------------

Just create your template for message in application/views/scripts/imessages/hello.phtml

<?php echo $this->name; ?>

<?php echo $this->text; ?>

Than fill messages in your controller with data

	$substitution = array(
		array('name' => 'Alex', 'date' => date('d-m-Y', strtotime('now')), 'text' => 'Test message from user 1'),
		array('name' => 'Dmitry', 'date' => date('d-m-Y', strtotime('one hour ago')), 'text' => 'Test message from user 2'),
		array('name' => 'Jack', 'date' => date('d-m-Y', strtotime('two hour ago')), 'text' => 'Hello world'),
	);

	$messages = InstantMessage_Broker::getInstance();

	foreach ($substitution as $values)
	{
		$messages->addMessage('hello', $values, 'FileMessage', array('extension' => '.phtml'));
	}

	$this->view->messages = $messages->getMessages();

And render it in your base template (for ex. index.phtml)

	<?php echo $this->renderMessages($this->messages); ?>

Or simply one message

	$message = new InstantMessage_Message_FileMessage('hello', array('name' => 'Jack'));

	$message->text = 'Hello world!';
	$message->date = date('Y-m-d', time());

	// or echo $message;
	echo $message->render();

Demo
----

Soon


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Ccrudmapel extends CI_Controller {

/* i. function construct */
function __construct(){
  parent::__construct();
}

function showmapel(){
  ?>

                No
                Nama Matapelajaran
                Opsi

          <?php
      $this->load->model('mcrudmapel');
      $query = $this->mcrudmapel->selectmapel();
      $i = 1;
      foreach($query->result() as $row){
        ?>

                <?php echo $i ?>
                <?php echo $row->nama_mapel ?>

                  <button onclick="EditMapel(<?=$row->mapel_id?>)" type="button" class="btn btn-primary btn-xs">Edit</button>

      <?php
      $i++;
      }
      ?>

  <?php
}

public function addmapel(){
  ?>

          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            ×</button>

TAMBAH MATAPELAJARAN

  <?php
   $frmattributes = array(
       "id" => "id_FrmAddMapel",
       "name" => "FrmAddMapel"
   );
   echo form_open('cpage/manamapel',$frmattributes);
  ?>

    <?php
     $frmattributes = array(
         "id" => "id_FrmAddMapel",
         "name" => "FrmAddMapel"
     );
     echo form_open('ctrlpage/mapel',$frmattributes);
    ?>

      Nama Matapelajaran
      <input type="text" class="form-control" id="id_namamapel" placeholder="Ketik Nama Matapelajaran" required>

         <button id="id_mapelbtn" type="button" class="btn btn-primary">Simpan</button>

    <?php
}

public function showeditmapel(){
  $this->load->model('mcrudmapel');
  $query=$this->mcrudmapel->selecteditmapel();
  foreach($query->result() as $row){
    ?>

          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            ×</button>

EDIT MATAPELAJARAN

      ID List
      <input type="text" class="form-control" id="id_mapel" placeholder="Ketik Id" value="<?=$row->mapel_id?>" readonly="readonly">

      Nama Matapelajaran
      <input type="text" class="form-control" id="id_namamapel" placeholder="Ketik Nama Matapelajaran" value="<?=$row->nama_mapel?>" required>

     <button id="id_mapel1" type="button" class="btn btn-primary" onclick="Updmapel()">Save changes</button>

  <?php
  }
}

  public function savemapel(){

  $this->load->model('mcrudmapel');
  $query = $this->mcrudmapel->insertmapel();
}

 public function Editmapel(){
  $this->load->model('mcrudmapel');
  $query = $this->mcrudmapel->editmapel();
}

  public function Delmapel(){
  $this->load->model('mcrudmapel');
  $query = $this->mcrudmapel->deletemapel();

}
}
?>


text:
#include "sys/nylon-sysport-atomic.h"

namespace Atomic
{
   template< int kSize >
   class BaseMemcast
   {
   public:
      typedef long mem_t;
   };

   template<>
   class BaseMemcast<sizeof(long long)>
   {
   public:
      typedef long long mem_t;
   };

   template< int kSize >
   class Memcast : public BaseMemcast<kSize>
   {
   public:
      template<class TAnything>
      static inline
      typename BaseMemcast<kSize>::mem_t*
      memcast( TAnything* pMemory )
      {
         return reinterpret_cast<typename BaseMemcast<kSize>::mem_t*>( pMemory );
      }
   };

   template< class T >
   inline T
   cmpxchg( volatile T& var, T oldval, T newval )
   {
      typename Memcast<sizeof(T)>::mem_t rc =
         nylon_sysport_cmpxchg
         (
            reinterpret_cast<volatile typename BaseMemcast<sizeof(T)>::mem_t*>( &var ),
            *(Memcast<sizeof(T)>::memcast(&oldval)),
            *(Memcast<sizeof(T)>::memcast(&newval))
         );

      return *( (T*)(void*)&rc );
   }

   template< typename TVAR, typename TADDEND >
   inline TVAR
   add( volatile TVAR& var, TADDEND addend )
   {

      while( true )
      {
         TVAR oldVal( var );
         TVAR newVal( oldVal + addend );
         if( oldVal == Atomic::cmpxchg( var, oldVal, newVal ) )
            return oldVal;
      }
   }
}

#endif


text:
package it.cvdlab.lar.pipeline.kernelwrap.experimental;

import it.cvdlab.lar.model.CsrMatrix;
import it.cvdlab.lar.model.helpers.PointerUtils;
import it.cvdlab.lar.pipeline.helpers.MultipleFind;
import it.cvdlab.lar.pipeline.helpers.TransformNumberList;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.bridj.Pointer;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.nativelibs4java.opencl.CLEvent;
import com.nativelibs4java.opencl.CLPlatform.DeviceFeature;
import com.nativelibs4java.opencl.LocalSize;

public class CsrStepsKernel extends RunningKernel {
	private static DeviceFeature runOn = DeviceFeature.GPU;

	private static String[] KERNEL_FILE = {"csr_run_1.cl", "prefixsum.cl", "csr_run_2.cl"};
	private static String[] KERNEL_FUNCTION = {"m_mul_m_count","kernel__scan_block_anylength","m_mul_m"};

	private static int ROWS_PER_CORE = 4000;

	private static String D_TYPE = "T";
	private static String D_ROWS_A = "ROWS_A";
	private static String D_ROWS_B = "ROWS_B";

	private static String PTR_ROWPTR_A = "rowptr_a";
	private static String PTR_ROWPTR_B = "rowptr_b";
	private static String PTR_ROWPTR_C = "rowptr_c";
	private static String PTR_COLDATA_A = "coldata_a";
	private static String PTR_COLDATA_B = "coldata_b";
	private static String PTR_COLDATA_C = "coldata_c";
	private static String PTR_DATA_A = "data_a";
	private static String PTR_DATA_B = "data_b";
	private static String PTR_DATA_C = "data_c";

	private static String PTR_INPUT_KEY = PTR_ROWPTR_C;

	public CsrStepsKernel(DeviceFeature runOn2) {
		super(runOn2);
	}

	@Override
	void preProcessKernelSource(String theSource) {
		// TODO Auto-generated method stub

	}

	public void runCsrStep1(CsrMatrix mtxOne, CsrMatrix mtxTwo) {
		CsrMatrix mtxTwoT = mtxTwo.transpose();

		this.createNewPointerInteger(PTR_ROWPTR_A, mtxOne.getRowPointer());
		this.createInputMemoryBuffer(PTR_ROWPTR_A);
		this.createNewPointerInteger(PTR_ROWPTR_B, mtxTwoT.getRowPointer());
		this.createInputMemoryBuffer(PTR_ROWPTR_B);
		this.createNewPointerInteger(PTR_COLDATA_A, mtxOne.getColdata());
		this.createInputMemoryBuffer(PTR_COLDATA_A);
		this.createNewPointerInteger(PTR_COLDATA_B, mtxTwoT.getColdata());
		this.createInputMemoryBuffer(PTR_COLDATA_B);

		List<Integer> lstOutput = Lists.newArrayList(Collections.nCopies(mtxOne.getRowPointer().size(), 0));
		this.createNewPointerInteger(PTR_ROWPTR_C, lstOutput);
		this.createInputOutputMemoryBuffer(PTR_ROWPTR_C);

		Map<String,String> defineMap = Maps.newHashMap();
		defineMap.put(D_ROWS_A, String.valueOf( mtxOne.getRowCount() ) );
		defineMap.put(D_ROWS_B, String.valueOf( mtxTwoT.getRowCount() ) );

		System.out.println("ROWS_A " + mtxOne.getRowCount());
		System.out.println("ROWS_B " + mtxTwoT.getRowCount());

		this.loadkernelSourceFromFile(CsrStepsKernel.class.getResource(KERNEL_FILE[0]));
		this.initProgram(defineMap, null);
		this.addFasterMathOptions();
		this.initKernel(KERNEL_FUNCTION[0]);

		// TODO: decide number of rows per core
		int rowsWorkGroup = (int)this.getMaxKernelWorkgroupSize();
		int rowsDivisor = mtxOne.getRowCount() * rowsWorkGroup / ROWS_PER_CORE;
		int howManyWGs = 1;
		if (rowsDivisor != 0) {
			howManyWGs = mtxOne.getRowCount() / rowsDivisor;
			if ((mtxOne.getRowCount() % rowsDivisor) != 0) {
				howManyWGs++;
			}
		}

		int[] localWorkSize = { rowsWorkGroup };
		int[] globalWorkSize = { howManyWGs*rowsWorkGroup };

		System.out.println("getMaxKernelWorkgroupSize " + this.getMaxKernelWorkgroupSize());
		System.out.println("localWorkSize[0] " + localWorkSize[0]);
		System.out.println("globalWorkSize[0] " + globalWorkSize[0]);

		this.setKernelArgs( this.getBufferInteger(PTR_ROWPTR_A),
							this.getBufferInteger(PTR_COLDATA_A),
							this.getBufferInteger(PTR_ROWPTR_B),
							this.getBufferInteger(PTR_COLDATA_B),
							this.getBufferInteger(PTR_ROWPTR_C),
							ROWS_PER_CORE);

		CLEvent evtFinish = this.enqueueKernel(localWorkSize, globalWorkSize);

		// Debug
		Pointer<Integer> ptrOut = this.getBufferInteger(PTR_ROWPTR_C).read(this.getQueue(), evtFinish);
		List<Integer> lRes = PointerUtils.copyFromPointer(ptrOut);
		System.out.println(lRes);

		// Release
		// ------

		this.resetKernelAndProgram(evtFinish);
		evtFinish.release();

		return;
	}

	public List<Integer> runPrefixScan(int elementSize) {
		Map<String,String> defineMap = Maps.newHashMap();
		defineMap.put(D_TYPE, "int");

		this.loadkernelSourceFromFile(CsrStepsKernel.class.getResource(KERNEL_FILE[1]));
		this.initProgram(defineMap, null);
		this.addFasterMathOptions();
		this.initKernel(KERNEL_FUNCTION[1]);

		int wgSize = (int)this.getMaxKernelWorkgroupSize();
		int blockSize = elementSize / wgSize;
		int B = blockSize * wgSize;
		if ((elementSize % wgSize) > 0) { blockSize++; };
		int[] localWorkSize = {wgSize};
		int[] globalWorkSize = { MultipleFind.toMultipleOf(elementSize / wgSize, wgSize)};

		System.out.println("getMaxKernelWorkgroupSize " + wgSize);
		System.out.println("blockSize " + blockSize);
		System.out.println("B " + B);
		System.out.println("localWorkSize[0] " + localWorkSize[0]);
		System.out.println("globalWorkSize[0] " + globalWorkSize[0]);

		this.setKernelArgs( new LocalSize(this.getMaxKernelWorkgroupSize()*(Integer.SIZE/8)),
							this.getBufferInteger(PTR_INPUT_KEY),
							B, elementSize, blockSize);

		CLEvent evtFinish = this.enqueueKernel(localWorkSize, globalWorkSize);
		Pointer<Integer> ptrOut = this.getBufferInteger(PTR_INPUT_KEY).read(this.getQueue(), evtFinish);
		List<Integer> lRes = PointerUtils.copyFromPointer(ptrOut);

		ptrOut.release();
		this.resetKernelAndProgram(evtFinish);
		evtFinish.release();

		return lRes;
	}

	public CsrMatrix runCsrStep2(CsrMatrix mtxOne, CsrMatrix mtxTwo, List<Integer> lRes) {
		CsrMatrix mtxTwoT = mtxTwo.transpose();
		int nnzCount = lRes.get( lRes.size() - 1);

		this.createNewPointerInteger(PTR_DATA_A, TransformNumberList.toInteger( mtxOne.getData() ));
		this.createInputMemoryBuffer(PTR_DATA_A);
		this.createNewPointerInteger(PTR_DATA_B, TransformNumberList.toInteger( mtxTwoT.getData() ));
		this.createInputMemoryBuffer(PTR_DATA_B);

		this.createOutputMemoryBufferInteger(PTR_COLDATA_C, nnzCount);
		this.createOutputMemoryBufferInteger(PTR_DATA_C, nnzCount);

		Map<String,String> defineMap = Maps.newHashMap();
		defineMap.put(D_ROWS_A, String.valueOf( mtxOne.getRowCount() ) );
		defineMap.put(D_ROWS_B, String.valueOf( mtxTwoT.getRowCount() ) );

		this.loadkernelSourceFromFile(CsrStepsKernel.class.getResource(KERNEL_FILE[2]));
		this.initProgram(defineMap, null);
		this.addFasterMathOptions();
		this.initKernel(KERNEL_FUNCTION[2]);

		// TODO: decide number of rows per core
		int rowsWorkGroup = (int)this.getMaxKernelWorkgroupSize();
		int rowsDivisor = mtxOne.getRowCount() * rowsWorkGroup / ROWS_PER_CORE;
		int howManyWGs = 1;
		if (rowsDivisor != 0) {
			howManyWGs = mtxOne.getRowCount() / rowsDivisor;
			if ((mtxOne.getRowCount() % rowsDivisor) != 0) {
				howManyWGs++;
			}
		}

		int[] localWorkSize = { rowsWorkGroup };
		int[] globalWorkSize = { howManyWGs*rowsWorkGroup };

		System.out.println("getMaxKernelWorkgroupSize " + this.getMaxKernelWorkgroupSize());
		System.out.println("localWorkSize[0] " + localWorkSize[0]);
		System.out.println("globalWorkSize[0] " + globalWorkSize[0]);

		this.setKernelArgs( this.getBufferInteger(PTR_ROWPTR_A),
							this.getBufferInteger(PTR_COLDATA_A),
							this.getBufferInteger(PTR_DATA_A),
							this.getBufferInteger(PTR_ROWPTR_B),
							this.getBufferInteger(PTR_COLDATA_B),
							this.getBufferInteger(PTR_DATA_B),
							this.getBufferInteger(PTR_ROWPTR_C),
							this.getBufferInteger(PTR_COLDATA_C),
							this.getBufferInteger(PTR_DATA_C),
							ROWS_PER_CORE);

		CLEvent evtFinish = this.enqueueKernel(localWorkSize, globalWorkSize);

		// Debug
		Pointer<Integer> ptrColOut = this.getBufferInteger(PTR_COLDATA_C).read(this.getQueue(), evtFinish);
		List<Integer> lColRes = PointerUtils.copyFromPointer(ptrColOut);
		System.out.println(lColRes);

		Pointer<Integer> ptrDataOut = this.getBufferInteger(PTR_DATA_C).read(this.getQueue());
		List<Integer> lDataRes = PointerUtils.copyFromPointer(ptrDataOut);
		System.out.println(lDataRes);

		// Release
		// ------
		ptrColOut.release();
		ptrDataOut.release();

		evtFinish.release();

		return new CsrMatrix(lRes, lColRes, TransformNumberList.toFloat(lDataRes), mtxOne.getRowshape(), mtxTwoT.getRowshape());
	}

	/**
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		CsrMatrix mtxA = CsrMatrix.fromFlattenArray(matrixTest, 5);
		CsrMatrix mtxB = mtxA.transpose();

		CsrStepsKernel cskRun = new CsrStepsKernel(runOn);
		System.out.println("Context: " + cskRun.initContext());
		System.out.println("Queue: " + cskRun.initQueue());
		cskRun.runCsrStep1(mtxA, mtxB);
		List<Integer> prefixSumRes = cskRun.runPrefixScan(mtxA.getRowPointer().size());
		System.out.println( prefixSumRes );
		CsrMatrix resultCL = cskRun.runCsrStep2(mtxA, mtxB, prefixSumRes);
		System.out.println(resultCL);

		CsrMatrix result = mtxA.multiply(mtxB);
		System.out.println(result);

		cskRun.releaseAll();
	}

	public static float[] matrixTest = { 0F, 0F, 0F, 2F, 5F,
										0F, 2F, 7F, 8F, 0F,
										1F, 3F, 0F, 0F, 0F,
										4F, 5F, 0F, 0F, 4F,
										0F, 7F, 7F, 0F, 0F };
}


text:
VERSION = '0.3'

import base64
import copy
import xml.etree.ElementTree as etree
import httplib2
import mersenne

# Device data required in the headers.
USER_AGENT = 'WordsWithFriendsAndroid/3.51'
DEVICE_OS = '2.3.3'
DEVICE_ID = 'ADR6300'
PLATFORM = 'android'

# Main URL for all server requests.
WWF_URL = 'https://wordswithfriends.zyngawithfriends.com/'

GAME_OVER_BY_DECLINE = 97
GAME_OVER_BY_NO_PLAY = 99
GAME_OVER_BY_WIN = 100

# Letter distribution:
# A-9 B-2 C-2 D-5 E-13 F-2 G-3 H-4 I-8 J-1 K-1 L-4 M-2
# N-5 O-8 P-2 Q-1 R-6  S-5 T-7 U-4 V-2 W-2 X-1 Y-2 Z-1
# Blanks-2
LETTER_MAP = ['', '',
              'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E',
              'E', 'E', 'E', 'E',
              'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A',
              'I', 'I', 'I', 'I', 'I', 'I', 'I', 'I',
              'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O',
              'N', 'N', 'N', 'N', 'N',
              'R', 'R', 'R', 'R', 'R', 'R',
              'T', 'T', 'T', 'T', 'T', 'T', 'T',
              'D', 'D', 'D', 'D', 'D',
              'L', 'L', 'L', 'L',
              'S', 'S', 'S', 'S', 'S',
              'U', 'U', 'U', 'U',
              'G', 'G', 'G',
              'B', 'B',
              'C', 'C',
              'F', 'F',
              'H', 'H', 'H', 'H',
              'M', 'M',
              'P', 'P',
              'V', 'V',
              'W', 'W',
              'Y', 'Y',
              'J',
              'K',
              'Q',
              'X',
              'Z']

LETTER_VALUES = {
    '':  0,  'A': 1, 'B': 4,  'C': 4, 'D': 2,
    'E': 1,  'F': 4, 'G': 3,  'H': 3, 'I': 1,
    'J': 10, 'K': 5, 'L': 2,  'M': 4, 'N': 2,
    'O': 1,  'P': 4, 'Q': 10, 'R': 1, 'S': 1,
    'T': 1,  'U': 2, 'V': 5,  'W': 4, 'X': 8,
    'Y': 3,  'Z': 10,
}

TRIPLE_WORD = '$'
TRIPLE_LETTER = '!'
DOUBLE_WORD = '='
DOUBLE_LETTER = '+'
BONUS_SQUARES = [['-', '-', '-', '$', '-', '-', '!', '-', '!', '-', '-', '$', '-', '-', '-'],
                 ['-', '-', '+', '-', '-', '=', '-', '-', '-', '=', '-', '-', '+', '-', '-'],
                 ['-', '+', '-', '-', '+', '-', '-', '-', '-', '-', '+', '-', '-', '+', '-'],
                 ['$', '-', '-', '!', '-', '-', '-', '=', '-', '-', '-', '!', '-', '-', '$'],
                 ['-', '-', '+', '-', '-', '-', '+', '-', '+', '-', '-', '-', '+', '-', '-'],
                 ['-', '=', '-', '-', '-', '!', '-', '-', '-', '!', '-', '-', '-', '=', '-'],
                 ['!', '-', '-', '-', '+', '-', '-', '-', '-', '-', '+', '-', '-', '-', '!'],
                 ['-', '-', '-', '=', '-', '-', '-', '-', '-', '-', '-', '=', '-', '-', '-'],
                 ['!', '-', '-', '-', '+', '-', '-', '-', '-', '-', '+', '-', '-', '-', '!'],
                 ['-', '=', '-', '-', '-', '!', '-', '-', '-', '!', '-', '-', '-', '=', '-'],
                 ['-', '-', '+', '-', '-', '-', '+', '-', '+', '-', '-', '-', '+', '-', '-'],
                 ['$', '-', '-', '!', '-', '-', '-', '=', '-', '-', '-', '!', '-', '-', '$'],
                 ['-', '+', '-', '-', '+', '-', '-', '-', '-', '-', '+', '-', '-', '+', '-'],
                 ['-', '-', '+', '-', '-', '=', '-', '-', '-', '=', '-', '-', '+', '-', '-'],
                 ['-', '-', '-', '$', '-', '-', '!', '-', '!', '-', '-', '$', '-', '-', '-']]

class Fiend(object):
    def __init__(self, login, password, userAgent=USER_AGENT, deviceOs=DEVICE_OS, deviceId=DEVICE_ID, platform=PLATFORM):
        '''
        Params:
            login - Your Words with Friends login email address.
            password - Your phone's device ID. For Android, this can be found in Settings > About phone > Status > MEID.
            userAgent - The string sent in the User-Agent header.
            deviceOs - The string set in the Device-OS header.
            deviceId - The string set in the Device-Id header.
        '''

        self.login = login
        self.password = password
        self.userAgent = userAgent
        self.deviceOs = deviceOs
        self.deviceId = deviceId
        self.platform = platform

        self.userId = None
        self.userName = None
        self.userEmail = None

        self.authorization = base64.b64encode(self.login + ':' + self.password)

        self._http = httplib2.Http();

        self._games = {}

    @property
    def games(self):
        '''
        A dictionary of your games, with game IDs as the keys, and
        Game objects as the values.

        This property is lazy loaded. If you want to force a refresh, call
        refreshGames().
        '''

        if not self._games:
            self.refreshGames()

        return self._games

    @property
    def activeGames(self):
        activeGames = {}

        for id, game in self.games.items():
            if not game.gameOver:
                activeGames[id] = game

        return activeGames

    def refreshGames(self):
        '''
        Makes a call to the server to retrieve a list of your games. It sets
        the games property to be a dictionary, with game IDs as the keys, and
        Game objects as the values.
        '''

        self._games = {}

        params = {
            'game_type':           'WordGame',
            'include_invitations': 'true',
            'games_since':         '1970-0-1T0:0:0-00:00',
            'moves_since':         '0',
            'chat_messages_since': '0',
            'get_current_user':    'true'
        }

        gamesXml = etree.fromstring(self._serverGet('games', params))

        for gameXml in gamesXml:
            gameObj = Fiend.Game()
            gameObj.parent = self
            gameObj.setWithXml(gameXml)

            self._games[gameObj.id] = gameObj

    def _serverGet(self, call, params):
        url = self._makeUrl(call, params)
        headers = {
            'User-Agent':    USER_AGENT,
            'Content-Type':  'application/xml',
            'Authorization': self.authorization,
            'Device-OS':     self.deviceOs,
            'Device-Id':     self.deviceId,
            'Accept':        'text/xml',
            'Cache-Control': 'no-cache',
            'Pragma':        'no-cache'
        }

        # TODO: Check response to make sure all is well
        response, content = self._http.request(url, headers=headers)
        return content

    def _makeUrl(self, call, params):
        url = WWF_URL + call + '?'
        url += '&'.join([str(k) + '=' + str(v) for k, v in params.items()])
        return url

    class Game(object):
        def __init__(self):
            self.id = None
            self.parent = None
            self.currentMoveUserId = None
            self.createdByUserId = None
            self.chatSessionId = None
            self.isMatchmaking = None
            self.wasMatchmaking = None
            self.movesCount = None
            self.moveCount = None
            self.clientVersion = None
            self.observers = None
            self.createdAt = None
            self.boardChecksum = 0

            self._blanks = [None, None]
            self.letterBagCodes = [i for i in range(len(LETTER_MAP))]
            self._randomSeed = None
            self._random = None

            self.board = self._initBoard()
            self.creator = Fiend.User()
            self.opponent = Fiend.User()
            self.player = None
            self.moves = []
            self.gameOver = False

        def setWithXml(self, xmlElem):
            self.id = int(xmlElem.findtext('id'))

            if xmlElem.findtext('current-move-user-id'):
                self.currentMoveUserId = int(xmlElem.findtext('current-move-user-id'))

            self.createdByUserId = int(xmlElem.findtext('created-by-user-id'))
            self.chatSessionId = int(xmlElem.findtext('chat_session_id'))
            self.isMatchmaking = str(xmlElem.findtext('is-matchmaking'))
            self.wasMatchmaking = str(xmlElem.findtext('was-matchmaking'))
            self.movesCount = int(xmlElem.findtext('moves-count'))
            self.moveCount = int(xmlElem.findtext('move_count'))
            self.randomSeed = int(xmlElem.findtext('random-seed'))
            self.clientVersion = str(xmlElem.findtext('client-version'))
            self.observers = str(xmlElem.findtext('observers'))
            self.createdAt = str(xmlElem.findtext('created-at'))

            if self.parent.userId is None and xmlElem.find('current-user') is not None:
                currentUserXmlElem = xmlElem.find('current-user')
                self.parent.userId = int(currentUserXmlElem.findtext('id'))
                self.parent.userName = str(currentUserXmlElem.findtext('name'))
                self.parent.userEmail = str(currentUserXmlElem.findtext('email'))

            self._processUsers(xmlElem.find('users'))
            self._processMoves(xmlElem.find('moves'))

        @property
        def boardString(self):
            '''
            Returns a 15x15 text grid of the game board.
            '''

            board = '';

            for y in range(15):
                for x in range(15):
                    if self.board[x][y] == -1:
                        board += BONUS_SQUARES[x][y]
                    elif self.board[x][y] == 0 or self.board[x][y] == 1:
                        board += self._blanks[self.board[x][y]]
                    else:
                        board += LETTER_MAP[self.board[x][y]]

                board += '\n'

            return board

        @property
        def boardGrid(self):
            boldLetter = '\033[1;31m'
            outline = '\033[0;37m'
            reset = '\033[0;0m'

            board = outline + '   ' + ('+---'*15) + '+\n' + reset

            for y in range(15):
                if 14 - y < 10:
                    board += ' '

                board += str(14 - y) + ' ' + outline + '|' + reset

                for x in range(15):
                    board += ' '

                    if self.board[x][y] == -1:
                        if BONUS_SQUARES[x][y] == '-':
                            board += ' '
                        else:
                            board += BONUS_SQUARES[x][y]
                    elif self.board[x][y] == 0 or self.board[x][y] == 1:
                        board += boldLetter + self._blanks[self.board[x][y]] + reset
                    else:
                        board += boldLetter + LETTER_MAP[self.board[x][y]] + reset

                    board += ' ' + outline + '|' + reset

                if y == 0:
                    board += '    ' + TRIPLE_WORD + ' Triple Word'
                elif y == 1:
                    board += '    ' + TRIPLE_LETTER + ' Triple Letter'
                elif y == 2:
                    board += '    ' + DOUBLE_WORD + ' Double Word'
                elif y == 3:
                    board += '    ' + DOUBLE_LETTER + ' Double Letter'

                board += outline + '\n   ' + ('+---'*15) + '+\n' + reset

            board += '     ' + '   '.join([str(x) for x in range(10)])
            board += '   ' + '  '.join([str(x) for x in range(10,15)])
            board += '\n'

            return board

        @property
        def randomSeed(self):
            return self._randomSeed

        @randomSeed.setter
        def randomSeed(self, value):
            if self._randomSeed is not None:
                raise GameError('randomSeed is already set for game', self)

            if value is not None:
                self._randomSeed = value
                self._random = mersenne.Mersenne(self._randomSeed)
                self._assignInitialTiles()

        @property
        def remainingLetterCodes(self):
            random = copy.deepcopy(self._random)
            letterBagCodes = copy.deepcopy(self.letterBagCodes)
            return self._drawFromLetterBag(len(letterBagCodes), random, letterBagCodes)

        @property
        def remainingLetters(self):
            return [LETTER_MAP[code] for code in self.remainingLetterCodes]

        def addMove(self, move):
            '''
            Takes a Move object as an argument. Adds the Move to the Game and updates
            the Game's board.
            '''

            if self.gameOver:
                raise Fiend.MoveError('Moves cannot be added to an ended game', move, self)

            if self.randomSeed is None:
                raise Fiend.GameError('Game does not have a randomSeed', self)

            # moveIndex is 0-indexed
            nextMoveIndex = len(self.moves)
            if move.moveIndex is None:
                move.moveIndex = nextMoveIndex
            elif move.moveIndex != nextMoveIndex:
                raise Fiend.MoveError("The moveIndex is not next in this game's sequence", move, self)

            numLettersPlayed, wordPoints, wordsPlayed, passedTurn = self._updateBoard(move)

            currentPlayer = self.creator if move.userId == self.creator.id else self.opponent

            currentPlayer.score += wordPoints
            currentPlayer.rack.extend(self._drawFromLetterBag(numLettersPlayed))

            for tile in [a for a in move.textCodes if a != '*']:
                currentPlayer.rack.remove(tile)

                if passedTurn:
                    self.letterBagCodes.append(tile)

            if move.fromX == GAME_OVER_BY_WIN:
                if len(self.creator.rack) == 0:
                    giver = self.opponent
                    receiver = self.creator
                else:
                    giver = self.creator
                    receiver = self.opponent

                pointExchange = 0
                for tile in giver.rack:
                    pointExchange += LETTER_VALUES[LETTER_MAP[tile]]
                giver.score -= pointExchange
                receiver.score += pointExchange

            move.score = wordPoints
            move.words = wordsPlayed
            move.player = currentPlayer
            move.game = self
            self.moves.append(move)

        def _assignInitialTiles(self):
            self.creator.rack = self._drawFromLetterBag(7)
            self.opponent.rack = self._drawFromLetterBag(7)

        def _processUsers(self, usersXml):
            for userXml in usersXml:
                userObj = Fiend.User()
                userObj.setWithXml(userXml)

                if userObj.id == self.createdByUserId:
                    userObj.rack = self.creator.rack
                    self.creator = userObj
                else:
                    userObj.rack = self.opponent.rack
                    self.opponent = userObj

                self.player = self.creator if self.creator.id == self.parent.userId else self.opponent

        def _processMoves(self, movesXml):
            moveList = []

            # Order the moves before adding them to a Game. They should be
            # ordered in the XML, but this isn't required.
            for moveXml in movesXml:
                moveObj = Fiend.Move()
                moveObj.setWithXml(moveXml)
                moveList.insert(moveObj.moveIndex, moveObj)

            for moveObj in moveList:
                self.addMove(moveObj)

        def _initBoard(self):
            return [[-1 for y in range(15)] for x in range(15)]

        def _updateBoard(self, move):
            numLettersPlayed = 0
            wordPoints = 0
            wordsPlayed = []
            passedTurn = False
            promoted = 0

            if move.fromX > 14:
                # Out of bounds fromX is used to signify various game conditions:
                # 97 = User declined new game
                # 99 = User resigned game due to no play
                # 100 = User won game
                # 101 = Piece exchange
                numLettersPlayed = len(move.textCodes)
                passedTurn = True

                # Either a player won or the game ended due to someone not taking their
                # turn in a given amount of time.
                if GAME_OVER_BY_DECLINE <= move.fromX <= GAME_OVER_BY_WIN:
                    self.gameOver = move.fromX

            else:
                # Make a copy of the board so that if any exceptions are raised,
                # then the actual board isn't corrupted.
                workingBoard = copy.deepcopy(self.board)

                if move.fromX == move.toX and move.fromY == move.toY:
                    # Special case for one letter plays
                    promoted = 3

                    try:
                        above = workingBoard[move.fromX][move.toY+1]
                    except IndexError:
                        above = -1

                    try:
                        below = workingBoard[move.fromX][move.toY-1]
                    except IndexError:
                        below = -1

                    if above != -1 or below != -1:
                        direction = 'V'
                    else:
                        direction = 'H'
                elif move.fromX == move.toX:
                    direction = 'V'
                else:
                    direction = 'H'

                if direction == 'V':
                    if not promoted:
                        promoted = 2

                    moveCoords = [(move.fromX, y) for y in range(move.fromY, move.toY+1)]
                    extendCoordsLeft = [(move.fromX, j) for j in range(move.fromY - 1, -1, -1)]
                    extendCoordsRight = [(move.toX, j) for j in range(move.toY + 1, 15)]
                elif direction == 'H':
                    if not promoted:
                        promoted = 1

                    moveCoords = [(x, move.fromY) for x in range(move.fromX, move.toX+1)]
                    extendCoordsLeft = [(j, move.fromY) for j in range(move.fromX -1, -1, -1)]
                    extendCoordsRight = [(j, move.toY) for j in range(move.toX + 1, 15)]

                if move.promoted is None:
                    move.promoted = promoted
                elif move.promoted != promoted:
                    raise Fiend.MoveError('Promoted value mismatch', move, self)

                discoveredPoints = 0
                scoreMultiplier = 1
                mainWord = ''

                for i, (x,y) in enumerate(moveCoords):
                    if move.textCodes[i] == '*':
                        if workingBoard[x][y] == 0 or workingBoard[x][y] == 1:
                            addedLetter = self._blanks[workingBoard[x][y]]
                        else:
                            addedLetter = LETTER_MAP[workingBoard[x][y]]
                        mainWord += addedLetter

                        wordPoints += LETTER_VALUES[LETTER_MAP[workingBoard[x][y]]]

                        continue

                    else:
                        if move.textCodes[i] == 0 or move.textCodes[i] == 1:
                            addedLetter = move._blanks[move.textCodes[i]]
                        else:
                            addedLetter = LETTER_MAP[move.textCodes[i]]

                        mainWord += addedLetter

                    if workingBoard[x][y] != -1:
                        raise Fiend.MoveError('Move illegally overlaps an existing move', move, self)

                    workingBoard[x][y] = move.textCodes[i]
                    numLettersPlayed += 1

                    letterValue = LETTER_VALUES[LETTER_MAP[move.textCodes[i]]]
                    if BONUS_SQUARES[x][y] == DOUBLE_LETTER:
                        letterValue *= 2
                    elif BONUS_SQUARES[x][y] == TRIPLE_LETTER:
                        letterValue *= 3
                    wordPoints += letterValue

                    multOnLetter = False
                    if BONUS_SQUARES[x][y] == DOUBLE_WORD:
                        scoreMultiplier *= 2
                        multOnLetter = True
                    elif BONUS_SQUARES[x][y] == TRIPLE_WORD:
                        scoreMultiplier *= 3
                        multOnLetter = True

                    if direction == 'V':
                        checkCoordsLeft = [(j, y) for j in range(x-1, -1, -1)]
                        checkCoordsRight = [(j, y) for j in range(x+1, 15)]
                    elif direction == 'H':
                        checkCoordsLeft = [(x, j) for j in range(y-1, -1, -1)]
                        checkCoordsRight = [(x, j) for j in range(y+1, 15)]

                    countedLetter = False
                    onCheckCoordsLeft = True
                    if move.textCodes[i] == 0 or move.textCodes[i] == 1:
                        auxWord = move._blanks[move.textCodes[i]]
                    else:
                        auxWord = LETTER_MAP[move.textCodes[i]]

                    for coords in [checkCoordsLeft, checkCoordsRight]:
                        for (j,k) in coords:
                            if workingBoard[j][k] == -1:
                                if onCheckCoordsLeft:
                                    onCheckCoordsLeft = False
                                break

                            if workingBoard[j][k] == 0 or workingBoard[j][k] == 1:
                                addedLetter = self._blanks[workingBoard[j][k]]
                            else:
                                addedLetter = LETTER_MAP[workingBoard[j][k]]

                            if onCheckCoordsLeft:
                                auxWord = addedLetter + auxWord
                            else:
                                auxWord = auxWord + addedLetter

                            if multOnLetter:
                                wordPoints += LETTER_VALUES[LETTER_MAP[workingBoard[j][k]]]
                            else:
                                discoveredPoints += LETTER_VALUES[LETTER_MAP[workingBoard[j][k]]]

                            if not countedLetter:
                                if multOnLetter:
                                    wordPoints += letterValue
                                else:
                                    discoveredPoints += letterValue

                                countedLetter = True
                        else:
                            onCheckCoordsLeft = False

                    if len(auxWord) > 1:
                        wordsPlayed.append(auxWord)

                onExtendCoordsLeft = True
                for coords in [extendCoordsLeft, extendCoordsRight]:
                    for (j,k) in coords:
                        if workingBoard[j][k] == -1:
                            if onExtendCoordsLeft:
                                onExtendCoordsLeft = False
                            break

                        if workingBoard[j][k] == 0 or workingBoard[j][k] == 1:
                            addedLetter = self._blanks[workingBoard[j][k]]
                        else:
                            addedLetter = LETTER_MAP[workingBoard[j][k]]

                        if onExtendCoordsLeft:
                            mainWord = addedLetter + mainWord
                        else:
                            mainWord = mainWord + addedLetter

                        wordPoints += LETTER_VALUES[LETTER_MAP[workingBoard[j][k]]]
                    else:
                        onExtendCoordsLeft = False

                if mainWord:
                    # Put the main word at the front of the array
                    wordsPlayed.insert(0, mainWord)

                wordPoints *= scoreMultiplier
                wordPoints += discoveredPoints

                if numLettersPlayed == 7:
                    wordPoints += 35

                workingBoardChecksum = self._calculateBoardChecksum(workingBoard)
                if move.boardChecksum is None:
                    move.boardChecksum = workingBoardChecksum
                elif move.boardChecksum != 0 and move.boardChecksum != workingBoardChecksum:
                    raise Fiend.MoveError('Board checksum mismatch', move, self)

                # Move was successful, make working board the real board
                self.board = workingBoard
                self.boardChecksum = workingBoardChecksum

                for i in [0, 1]:
                    if move._blanks[i]:
                        self._blanks[i] = move._blanks[i]

            return (numLettersPlayed, wordPoints, wordsPlayed, passedTurn)

        def _drawFromLetterBag(self, num, random=None, letterBagCodes=None):
            if random is None:
                random = self._random

            if letterBagCodes is None:
                letterBagCodes = self.letterBagCodes

            output = []

            for dummy in range(num):
                if len(letterBagCodes) == 0:
                    break

                i = random.rand() % len(letterBagCodes)
                output.append(letterBagCodes[i])
                del letterBagCodes[i]

            return output

        def _calculateBoardChecksum(self, board=None):
            '''
            Calculates the board_checksum value for the board in its current state.
            Since _updateBoard() calls this, you shouldn't need to call it yourself and
            can just rely on game.boardChecksum.

            If anyone recognizes this as a known algorithm, let me know.
            '''

            if board is None:
                board = self.board

            checkSum = 0
            numTilesPlayed = 0

            for y in range(15):
                for x in range(15):

                    # Space doesn't have a tile on it
                    if board[x][y] == -1:
                        checkSum ^= 1

                    # Space has the first blank on it
                    elif board[x][y] == 0:
                        checkSum ^= 2 ** ((15 * y + x) % 32)
                        numTilesPlayed += 1

                    # Space has the second blank or some other letter on it
                    else:
                        checkSum ^= board[x][y]
                        numTilesPlayed += 1

            if numTilesPlayed % 2 == 1:
                checkSum = -checkSum

                if (checkSum ^ 2) % 2 == 0:
                    checkSum -= 2

            return checkSum

    class User(object):
        def __init__(self):
            self.id = None
            self.name = None

            self.rack = None
            self.score = 0

        def setWithXml(self, xmlElem):
            self.id = int(xmlElem.findtext('id'))
            self.name = str(xmlElem.findtext('name'))

        @property
        def rackLetters(self):
            return sorted([LETTER_MAP[num] for num in self.rack])

    class Move(object):
        def __init__(self):
            self.id = None
            self.game = None
            self.gameId = None
            self.userId = None
            self.fromX = None
            self.fromY = None
            self.toX = None
            self.toY = None
            self.moveIndex = None
            self.text = None
            self.createdAt = None
            self.promoted = None
            self.boardChecksum = None

            self.score = None
            self.words = []
            self.player = None

            self._textCodes = None

            self._text = None
            self._blanks = [None, None]

        def setWithXml(self, xmlElem):
            self.id = int(xmlElem.findtext('id'))
            self.gameId = int(xmlElem.findtext('game-id'))
            self.userId = int(xmlElem.findtext('user-id'))
            self.fromX = int(xmlElem.findtext('from-x'))
            self.fromY = int(xmlElem.findtext('from-y'))
            self.toX = int(xmlElem.findtext('to-x'))
            self.toY = int(xmlElem.findtext('to-y'))
            self.moveIndex = int(xmlElem.findtext('move-index'))
            self.text = str(xmlElem.findtext('text'))
            self.createdAt = str(xmlElem.findtext('created-at'))
            self.promoted = int(xmlElem.findtext('promoted'))
            self.boardChecksum = int(xmlElem.findtext('board-checksum'))

        @property
        def text(self):
            return self._text

        @text.setter
        def text(self, value):
            self._text = value

            if self._text:
                self._setBlanks()

        @property
        def textCodes(self):
            if self._textCodes is None:
                self._textCodes = []

                if self.text != '(null)':
                    self._textCodes = []
                    for code in self.text[:-1].split(','):
                        if code == '*':
                            self.textCodes.append('*')
                        else:
                            try:
                                self._textCodes.append(int(code))
                            except ValueError:
                                continue

            return self._textCodes

        @property
        def moveXml(self):
            moveXml = ''

            if len(self.words) > 0:
                moveXml += '<?xml version="1.0" encoding="UTF-8"?>\n'
                moveXml += '<move>\n'
                moveXml += '    <from_x>' + str(self.fromX) + '</from_x>\n'
                moveXml += '    <from_y>' + str(self.fromY) + '</from_y>\n'
                moveXml += '    <to_x>' + str(self.toX) + '</to_x>\n'
                moveXml += '    <to_y>' + str(self.toY) + '</to_y>\n'
                moveXml += '    <promoted>' + str(self.promoted) + '</promoted>\n'
                moveXml += '    <text>' + '</text>\n'
                moveXml += '    <game_id>' + str(self.gameId) + '</game_id>\n'
                moveXml += '    <primary_key>' + '</primary_key>\n'
                moveXml += '    <board_checksum>' + str(self.boardChecksum) + '</board_checksum>\n'
                moveXml += '    <move_index>' + str(self.moveIndex) + '</move_index>\n'
                moveXml += '</move>\n'
                moveXml += '&words=' + self.words[0].lower() + '&points=' + str(self.score) + '&platform=' + self.game.parent.platform

            return moveXml

        def _setBlanks(self):
            letterCodes = self.text[:-1].split(',')
            for i in ['0', '1']:
                if i in letterCodes:
                    self._blanks[int(i)] = letterCodes[letterCodes.index(i) + 1].upper()

    class Error(Exception):
        '''Base class for exceptions in this module.'''
        pass

    class GameError(Error):
        def __init__(self, msg, game):
            self.msg = msg
            self.game = game

        def __str__(self):
            return repr(self.msg)

    class MoveError(Error):
        '''
        Raised when an error occurs when adding a move to a board.

        Params:
            msg: Error message for the exception.
            move: The move that caused the error.
            game: The game that this move was trying to be added to.
        '''

        def __init__(self, msg, move, game):
            self.msg = msg
            self.move = move
            self.game = game

        def __str__(self):
            return repr(self.msg)