text:
This add-on simplifies the problem of paginating content from APIs. The following pagination methods are supported:

 - **Numbered pages:** Pages are computed based on available content and accessed sequentially.
 - **Index/Offset:** Increments content by the index of the first content item in each "page" of content.
 - **Cursoring:** Specifies ranges of IDs or timestamps rather than pre-computing "pages" of results.
 - **Token-based:** Associates each page of content with a unique token, provided in each response for use in the next request.

## Popular Examples

            Service
            Pagination Method
            Pagination Parameter
            Results Parameter

            Facebook
            Cursoring
            after
            limit

            Facebook
            Index/Offset
            offset
            limit

            Flickr
            Numbered Pages
            page
            per_page

            Google+
            Token-based
            nextPageToken
            maxResults

            Instagram
            Cursoring
            max_id
            count

            SoundCloud
            Index/Offset
            offset
            limit

            Tumblr
            Index/Offset
            offset
            limit

            Twitter
            Cursoring
            max_id
            count

            YouTube
            Index/Offset
            start-index
            max-results

            Vimeo
            Numbered Pages
            page
            per_page

Setup
--------------------------------------------------------------------------------

Pagination may be easily added to your site using [Bower][bower], running the following command from the root directory of your site:

```
$ bower install storyarc/pagination
```

Usage
--------------------------------------------------------------------------------

The following example shows how to paginate the content of a proxied Tumblr blog resource, fetched via `GET /tumblr.json`. Whenever data is ready `.paginate` triggers the `success` or `error` events.

```html
<div id="tumblr-stream">
    <button type="button">More</button>
</div>

<script>
var Tumblr = Resource.extend({
    url: "/tumblr.json",
    pagination: IndexOffsetPagination
});

$( "#tumblr-stream" )
    .on( "success", function( event, data ) {
        render( data ).appentTo( event.target );
    })
    .on( "error" , function( event, data ) {
        log.error( data );
    })
    .paginate({
        resource: new Tumblr(),
        moreButton: "button"
    });
</script>
```

If you need to customize your pagination parameters, simply extend a pagination type and create your own custom one.

```html
<div id="twitter-stream">
    <button type="button">More</button>
</div>

<script>
var TwitterPagination = CursoringPagination.extend({
    parameterNames: {
        after: "max_id",
        limit: "count"
    },
    limit: 15
});

var Twitter = Resource.extend({
    url: "/twitter.json",
    pagination: TwitterPagination
});

$( "#twitter-stream" )
.on( "success", function( event, data ) {
    render( data ).appentTo( event.target );
})
.on( "error" , function( event, data ) {
    log.error( data );
})
.paginate({
    resource: new Twitter(),
    moreButton: "button"
});
</script>
```

API
--------------------------------------------------------------------------------

The building blocks.

## `$.fn.paginate`

The jQuery plugin `$.fn.paginate` is a widget that binds a resource with DOM elements. It's a helper that maps user events (via DOM events, eg. `click`) into resource actions (eg. `resource.next()`), or resource events (eg. data fetched) into DOM events (eg. the custom `success`/`error` events).

```javascript
$( element ).paginate( attributes );
```

The attributes are:
- resource: a [Resource](#resource) instance.
- moreButton: A selector, or DOM Element, or jQuery object that upon click will trigger the next page (by internally calling `resource.next()`).

The plugin fetches the 1st page on initialization, and it pre-caches the next ones in advance (one at a time).

*Future plan: allow different types of pagination interfaces (eg. auto paginate on scroll).*

Events:

### `.on( "success" )`

Whenever `.paginate` successfully fetches pages, `success` event is triggered with received `data`.

### `.on( "error" )`

Whenever `.paginate` has a failure fetching pages, `error` event is triggered with received `data`.

## Resource

Handles resource's data-fetch. It encapsulates the resources attributes (url, and pagination type) and offers a simple set of methods to manage it: `.get()`, and `.next()` (via pagination's instance `.next()`).

```javascript
var myResource = new Resource( attributes );
```

Create your own custom resource by extending Resource with custom attributes. The new class will use such attributes as default. (note, you are also allowed to extend your just extended class and so on.)

```javascript
var MyResource = Resource.extend( attributes );
var myResource = new MyResource();
```

The attributes are:
 - url: String containing the resource URL.
 - params: key-value pairs of params to be sent to the server on every request (note that pagination params will be appended to this one).
 - pagination: a [Pagination](pagination) class.

### `resource.get( params )`

`params` are optional parameters to include in the GET querystring. This method returns a Deferred object of the request.

## Pagination

Handles the pagination logic and exports `.next()` method used internally by [Resource](resource). This class is extended by the specific types of paginations below. See their respective docs for more information of each type.

### `pagination.next()`

Returns a Deferred object of the request (made internally via resource). All pagination logic is done internally, and any needed pagination-querystring is appended automatically.

`.next()` prevents any possible while-the-page-is-still-being-fetched further calls. In that case, it returns the same on-progress Deferred object.

### Cursoring

Pagination extended with the cursoring pagination logic.

```javascript
var myResource = new Resource({
    pagination: CursoringPagination( attributes )
});
```

The attributes are:
- after: The cursor that points to the end of the page. Next page will continue from this point (default: null).
- getAfter: A function that accepts one argument: the fetched data; and returns the cursor from which the next page will continue.
- limit: The number of posts to return (default: null).
- parameterNames:
 - after: String with the name of the after parameter (default: "after").
 - limit: String with the name of the limit parameter (default: "limit").

Create your own custom cursoring pagination by extending CursoringPagination with custom attributes. The new class will use such attributes as default. (note, you are also allowed to extend your just extended class and so on.)

```javascript
var MyPagination = CursoringPagination.extend( attributes );
var myResource = new Resource({
    pagination: MyPagination
});
```

### Index/Offset

Pagination extended with the index/offset pagination logic.

```javascript
var myResource = new Resource({
    pagination: IndexOffsetPagination( attributes )
});
```

The attributes are:
- count: A function that accepts one argument: the fetched data; and returns the number of fetched items.
- limit: The number of posts to return (default: null).
- offset: Post number to start at (default: 0).
- parameterNames:
 - limit: String with the name of the limit parameter (default: "limit").
 - offset: String with the name of the offset parameter (default: "offset").

Create your own custom index/offset pagination by extending IndexOffsetPagination with custom attributes. The new class will use such attributes as default. (note, you are also allowed to extend your just extended class and so on.)

```javascript
var MyPagination = IndexOffsetPagination.extend( attributes );
var myResource = new Resource({
    pagination: MyPagination
});
```

### Numbered Pages

Pagination extended with the numbered page pagination logic.

```javascript
var myResource = new Resource({
    pagination: NumberedPagePagination( attributes )
});
```

The attributes are:
- continue: A function that accepts one argument: the fetched data; and returns a boolean telling whether or not there are next pages.
- page: Page number to start at (default: 1).
- per_page: The number of items to return per page (default: null).
- parameterNames:
 - page: String with the name of the page parameter (default: "page").
 - perPage: String with the name of the perPage parameter (default: "per_page").

Create your own custom numbered page pagination by extending NumberedPagePagination with custom attributes. The new class will use such attributes as default. (note, you are also allowed to extend your just extended class and so on.)

```javascript
var MyPagination = IndexOffsetPagination.extend( attributes );
var myResource = new Resource({
    pagination: MyPagination
});
```

### Token-based

Pagination extended with the token pagination logic.

```javascript
var myResource = new Resource({
    pagination: TokenPagination( attributes )
});
```

The attributes are:
- getNextToken: A function that accepts one argument: the fetched data; and returns the next token.
- token: The token of the next page (default: null).
- limit: The number of posts to return (default: null).
- parameterNames:
 - token: String with the name of the after parameter (default: "token").
 - limit: String with the name of the limit parameter (default: "limit").

Create your own custom token pagination by extending TokenPagination with custom attributes. The new class will use such attributes as default. (note, you are also allowed to extend your just extended class and so on.)

```javascript
var MyPagination = TokenPagination.extend( attributes );
var myResource = new Resource({
    pagination: MyPagination
});
```

## Blending Resources

Blend several resources into a single "virtual" one with BlendResources.

```html
<div id="stream">
    <button type="button">More</button>
</div>

<script>
var blendedResource = new BlendResources({
    tumblr: new Tumblr(),
    twitter: new Twitter(),
    facebook: new Facebook()
});

$( "#stream" )
    .on( "success", function( event, data ) {
        render( data ).appentTo( event.target );
    })
    .on( "error" , function( event, data ) {
        log.error( data );
    })
    .paginate({
        resource: blendedResource,
        moreButton: "button"
    });
</script>
```

### `blendedResource.get( params )`

Calls `.get( params )` of all resources in bulk and returns a merged Deferred object that succeeds when *all* individuals succeeds, and fails when *any* individual fails.

On success, returns the merged data as a key-value pairs where key is the resource's `name`, ane value is the resource's data. Eg.
```
{
    tumblr: {...},
    twitter: {...},
    facebook: {...}
}
```

### `blendedResource.next()`

Calls `.next()` of all resources in bulk and returns a merged Deferred object that succeeds when *all* individuals succeeds, and fails when *any* individual fails.

Returns data in the same format as above.

[bower]: http://bower.io
[jquery]: http://jquery.com/download
[rfc6570]: http://tools.ietf.org/html/rfc6570
[storyteller]: http://storytellerhq.com+


text:
class AddIsApprovedFieldToPosts < ActiveRecord::Migration
  def change
    add_column :auth_forum_posts, :is_approved, :boolean, :default => false
  end
end

redpajama_set_name: RedPajamaGithub


text:
<webscript>
  <shortname>wikipage</shortname>
  <description>Wiki - Page details</description>
  <url>/slingshot/wiki/pages/{siteId}</url>
  <format default="json">argument</format>
  <authentication>user</authentication>
  <transaction allow="readonly">required</transaction>
  <lifecycle>internal</lifecycle>
</webscript>


text:
            email) }}?s=100"  alt="avatar">

        @if(count($user->profile) > 0)

{{ $user->present()->fullName() }}

                @if($user->profile->description)

 {{ $user->profile->description }}

                @endif

             $user->profile->id]) }}"> edit profile
        @else

{{ $user->name }}

                Avatar this site use Gravatar avatar

              make profile
        @endif


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateReportItemsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('report_items', function (Blueprint $table) {
            $table->increments('id');
            $table->text('response');
            $table->integer('report_id', false,true);
            $table->integer('goal_id', false, true)->nullable();
            $table->enum('rating', ['N', 'C', 'S']);
            $table->timestamps();

            $table->foreign('report_id')
                ->references('id')->on('reports');

            $table->foreign('goal_id')
                ->references('id')->on('goals')
                ->onDelete('set null');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('report_items');
    }
}


text:
#ifndef __TBA_CLR_EXECUTER_RUNTIME_FILELINKER_H
#define __TBA_CLR_EXECUTER_RUNTIME_FILELINKER_H

/*
 * FileLinker.h
 *
 * Link into source file (such as C/Javascript) file
 *
 * Author: Pavel Ferencz
 */
#include "executer/compiler/CompilerEngineThread.h"
#include "executer/linker/LinkerInterface.h"
#include "dismount/assembler/BinaryDependencies.h"

class FileLinker : public LinkerInterface
{
public:
    // Constructor
    FileLinker(CompilerEngineThread& compilerEngineThread, ApartmentPtr apartment);

    // See LinkerInterface::resolveAndExecuteAllDependencies
    virtual void resolveAndExecuteAllDependencies(TokenIndex& mainMethod);

protected:
    /*
     * Bind into a method and fills all the dependencies needed in order to
     * execute the method.
     *
     * Return a numeric value which can be transfer into the 'ExecuteInterface'
     */
    virtual addressNumericValue bind(SecondPassBinary& pass);

private:
    /*
     * Encode a string to a file
     */
    void writeString(basicIO& out, const cString& string);

    /*
     * Return a function
     *
     * shouldAddBody - Set to true if adding all body,
     *                 false if only the header
     */
    void writeFuntionHeaderAndBody(basicIO& out,
                                   const TokenIndex& function,
                                   const SecondPassBinary& bin,
                                   bool shouldAddBody);

    /*
     * Create a new vtbl for token
     */
    void writeVTable(basicIO& out,
                     const TokenIndex& token);

    /*
     * Convert cdecl/stdcall/c++ names into C names
     */
    cString demangleName(const cString& name);

    // Disable copy construction
    FileLinker(const FileLinker& other);
    FileLinker& operator=(const FileLinker& other);
};

#endif // __TBA_CLR_EXECUTER_RUNTIME_FILELINKER_H


text:
<!DOCTYPE html>

    <title>E-Kiosk Perpustakaan</title>

    <link rel="shortcut icon" href="<?=base_url();?>public/dist/img/favicon.ico" />

    <link rel="stylesheet" type="text/css" href="<?=base_url('public/bootstrap/css/bootstrap.min.css');?>">
    <link rel="stylesheet" type="text/css" href="<?=base_url('public/frontend/css/style.css');?>">

    <video autoplay poster="<?=base_url('public/video/video.jpg');?>" id="bgvid" loop>

    <source src="<?=base_url('public/video/video.mp4');?>" type="video/mp4">
    </video>

SELAMAT DATANG

EKIOSK PERPUSTAKAAN

POLITEKNIK ELEKTRONIKA NEGERI SURABAYA

        <img src="<?=base_url('public/frontend/img/map.png');?>" width="100%">

            <?php if(empty($this->session->userdata('user_login'))) { ?>
            LOGIN FORM

            Untuk akses ekiosk perpustakaan anda harus login.
            <?php } else { ?>
            LOGIN STATUS

            Anda masuk sebagai <?=$this->session->userdata('user_login')?>.
            <?php } ?>

        <?php if(empty($this->session->userdata('user_login'))) { ?>

            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>

            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>

        <?php echo form_open('login/dologinajax', 'id="form-login"') ?>
        <button type="button" class="btn-input btn-absolute" data-toggle="tooltip" title="" data-original-title="Lihat Buku" onclick="javascript:location.href='<?=site_url("home/daftar")?>'"></button>
        <input type="email" class="text-input" name="l_username" required placeholder="username tanpa @student.pens.ac.id">
        <input type="password" class="text-input" name="l_password" required placeholder="password">
        <button type="button" class="btn-input btn-login" id="btn-login" data-toggle="tooltip" title="" data-original-title="Login"></button>
        <?php echo form_close(); ?>
        <?php } else { ?>
            <button type="button" class="btn-input btn-absolute" data-toggle="tooltip" title="" data-original-title="Lihat Buku" onclick="javascript:location.href='<?=site_url("home/daftar")?>'"></button>
            <button type="button" class="btn-logout" id="btn-logout" data-toggle="tooltip" title="" data-original-title="Logout" onclick="javascript:location.href='<?=site_url("home/logout")?>'"></button>
        <?php } ?>


text:
<!DOCTYPE html>

<title>$.geocomplete()</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="../css/styles.css" />

	<form>
		<input id="geocomplete" type="text" placeholder="Type in an address"
			size="90" value="Hauptstraße" /> <input id="find" type="button"
			value="find" />
	</form>


text:
package org.easyweb.aop;

import org.easyweb.controller.AbstractController;

import java.util.Map;

/**
 * use to acl visit the org.easyweb.restful api ..
 */
public class TokenInterceptor implements Interceptor {

    //TODO .., may some service ,,,

    @Override
    public void intercept(ActionInvocation ai) {

        AbstractController controller = ai.getController();

        String token = controller.getToken();

        if (token != null && authorize(token)) {
            ai.invoke();
        } else {
            //TODO may return ...
//            throw new ValidateException("eror not token");
            Map<String,Object> model = controller.model();
            model.put("code",403);
            model.put("msg","not privilege to visit !");
            controller.errorRender();
        }
    }

    private boolean authorize(final String token) {
        if (token != null && token.equalsIgnoreCase("100")) return true;
        return false;
    }
}


text:
package org.eastway.echarts.client.place;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.PlaceController;
import com.google.inject.Inject;

public class EchartsPlaceController extends PlaceController {
	@Inject
	public EchartsPlaceController(EventBus eventBus) {
		super(eventBus);
	}
}


text:
<?php
define('DS', DIRECTORY_SEPARATOR);
define('ROOT', dirname(dirname(dirname(__FILE__))));

require_once (ROOT . DS . 'config' . DS . 'config.php');
require (ROOT . DS . 'library' . DS . 'frontend/search.php');


text:
import {animationFrames, debounceTime, distinctUntilChanged, filter, fromEvent, map, share, switchMap} from 'rxjs'
import {compose} from 'compose'
import Hammer from 'hammerjs'
import Keybinding from 'widget/keybinding'
import Portal from 'widget/portal'
import PropTypes from 'prop-types'
import React from 'react'
import _ from 'lodash'
import styles from './draggable.module.css'
import withSubscriptions from 'subscription'

const CLICKABLE_PAN_THRESHOLD_PX = 10

class _Draggable extends React.Component {
    draggable = React.createRef()

    state = {
        // this draggable
        dragging: false,
        position: null,
        size: null,
        // other draggable, when over
        dragOverSize: null,
        dragOverValue: null
    }

    constructor() {
        super()
        this.onMouseOver = this.onMouseOver.bind(this)
        this.onMouseOut = this.onMouseOut.bind(this)
        this.onClick = this.onClick.bind(this)
        this.onOtherDrag = this.onOtherDrag.bind(this)
        this.onDragStart = this.onDragStart.bind(this)
        this.onDragMove = this.onDragMove.bind(this)
        this.onDragEnd = this.onDragEnd.bind(this)
        this.onDragCancel = this.onDragCancel.bind(this)
    }

    getContent(original) {
        const {itemRenderer, item, index} = this.props
        return _.isFunction(itemRenderer)
            ? itemRenderer(item, {index, original})
            : itemRenderer
    }

    isDisabled() {
        const {disabled} = this.props
        return disabled
    }

    isClickable() {
        const {disabled, onClick} = this.props
        return !disabled && onClick
    }

    isDraggable() {
        const {disabled, drag$, onDragStart, onDrag, onDragEnd} = this.props
        return !disabled && (drag$ || onDragStart || onDrag || onDragEnd)
    }

    isDragging() {
        const {disabled, dragging} = this.state
        return !disabled && dragging
    }

    isOver({coords: {x: otherX, y: otherY}}) {
        const draggable = this.draggable.current
        const {x, y, width, height} = draggable.getBoundingClientRect()
        return (otherX > x) && (otherX < x + width)
            && (otherY > y) && (otherY < y + height)
    }

    isHidden() {
        const {hidden} = this.props
        return hidden
    }

    onMouseOver() {
        const {onMouseOver} = this.props
        onMouseOver && onMouseOver()
    }

    onMouseOut() {
        const {onMouseOut} = this.props
        onMouseOut && onMouseOut()
    }

    onClick() {
        const {onClick} = this.props
        if (!this.isDisabled() && !this.isDragging()) {
            onClick && onClick()
        }
    }

    render() {
        // console.log(this.state.position)
        return (
            <React.Fragment>
                {this.renderOriginal()}
                {this.isDragging() ? this.renderClone() : null}
            </React.Fragment>
        )
    }

    renderOriginal() {
        return this.renderItem(true)
    }

    renderItem(original) {
        const {showHandle, className} = this.props
        return (
            <div
                ref={original ? this.draggable : null}
                className={[
                    original ? styles.original : styles.clone,
                    this.isClickable() ? styles.clickable : null,
                    (this.isDraggable() && !this.isClickable()) ? styles.draggable : null,
                    this.isDragging() ? styles.dragging : null,
                    this.isHidden() ? styles.hidden : null,
                    className
                ].join(' ')}
                onClick={this.onClick}
                onMouseOver={this.onMouseOver}
                onMouseOut={this.onMouseOut}>
                {showHandle && this.isDraggable() ? this.renderDragHandle() : null}
                {this.getContent(original)}

        )
    }

    renderDragHandle() {
        return (

        )
    }

    renderClone() {
        const {position, size} = this.state
        const {dragCloneClassName} = this.props
        if (position && size) {
            return (
                <Keybinding keymap={{'Escape': this.onDragCancel}}>
                    <Portal type='global'>

                                {this.renderItem(false)}

                    </Portal>
                </Keybinding>
            )
        }
    }

    initializeDraggable() {
        const {drag$, dragValue, addSubscription} = this.props
        const draggable = this.draggable.current

        const hammer = new Hammer(draggable)

        hammer.get('pan').set({
            direction: Hammer.DIRECTION_ALL,
            threshold: this.isClickable() ? CLICKABLE_PAN_THRESHOLD_PX : 0
        })

        const panStart$ = fromEvent(hammer, 'panstart')
        const panMove$ = fromEvent(hammer, 'panmove')
        const panEnd$ = fromEvent(hammer, 'panend')

        const thisDragStart$ = panStart$.pipe(
            map(({changedPointers}) => changedPointers[0]),
            filter(({pageX, pageY} = {}) => pageX && pageY),
            map(({pageX, pageY}) => {
                const {x: draggableX, y: draggableY, width, height} = draggable.getBoundingClientRect()
                const offset = {
                    x: pageX - draggableX,
                    y: pageY - draggableY
                }
                const coords = {
                    x: pageX,
                    y: pageY
                }
                const position = {
                    x: draggableX,
                    y: draggableY
                }
                const size = {
                    width,
                    height
                }
                return {offset, coords, position, size}
            }),
            share()
        )

        const thisDragMove$ = thisDragStart$.pipe(
            switchMap(({offset}) =>
                animationFrames().pipe(
                    switchMap(() =>
                        panMove$.pipe(
                            map(e => e.center)
                        )
                    ),
                    debounceTime(10),
                    distinctUntilChanged(),
                    map(coords => ({
                        coords,
                        position: {
                            x: coords.x - offset.x,
                            y: coords.y - offset.y
                        }
                    }))
                )
            )
        )

        const thisDragEnd$ = panEnd$

        const otherDrag$ = drag$.pipe(
            filter(({value}) => value !== dragValue), // ignore self events
        )

        addSubscription(
            thisDragStart$.subscribe(this.onDragStart),
            thisDragMove$.subscribe(this.onDragMove),
            thisDragEnd$.subscribe(this.onDragEnd),
            otherDrag$.subscribe(this.onOtherDrag)
        )
    }

    onDragStart({coords, position, size}) {
        const {drag$, dragValue, onDragStart} = this.props
        this.setState({dragging: true, position, size}, () => {
            drag$ && drag$.next({value: dragValue, dragStart: {size}})
            drag$ && drag$.next({value: dragValue, dragMove: {coords, position}})
            onDragStart && onDragStart(dragValue)
        })
    }

    onDragMove({coords, position}) {
        const {drag$, dragValue, onDragMove} = this.props
        this.setState({position}, () => {
            drag$ && drag$.next({value: dragValue, dragMove: {coords, position}})
            onDragMove && onDragMove(dragValue, coords)
        })
    }

    onDragCancel() {
        const {drag$, dragValue, onDragCancel} = this.props
        this.setState({dragging: false, position: null, size: null}, () => {
            drag$ && drag$.next({value: dragValue, dragCancel: true})
            onDragCancel && onDragCancel(dragValue)
        })
    }

    onDragEnd() {
        const {drag$, dragValue, onDragEnd} = this.props
        const {dragging} = this.state
        if (dragging) {
            this.setState({dragging: false, position: null, size: null}, () => {
                drag$ && drag$.next({value: dragValue, dragEnd: true})
                onDragEnd && onDragEnd(dragValue)
            })
        }
    }

    componentDidMount() {
        if (this.isDraggable()) {
            this.initializeDraggable()
        }
    }

    // other draggable

    onOtherDrag({value, dragStart, dragMove, dragEnd}) {
        dragStart && this.onOtherDragStart(value, dragStart)
        dragMove && this.onOtherDragMove(value, dragMove)
        dragEnd && this.onOtherDragEnd(value, dragEnd)
    }

    onOtherDragStart(value, {size}) {
        const {onOtherDragStart} = this.props
        this.setState({dragOverSize: size}, () => {
            onOtherDragStart && onOtherDragStart(value)
        })
    }

    onOtherDragMove(value, {coords, position}) {
        const {drag$, dragValue} = this.props
        const {dragOverValue} = this.state
        if (this.isOver({coords, position})) {
            if (dragOverValue !== value) {
                this.setState({dragOverValue: value}, () =>
                    drag$.next({value: dragValue, dragOver: {srcValue: value}})
                )
            }
        } else {
            if (dragOverValue !== null) {
                this.setState({dragOverValue: null}, () =>
                    drag$.next({value: dragValue, dragOut: {srcValue: value}})
                )
            }
        }
    }

    onOtherDragEnd(value) {
        const {onOtherDragEnd} = this.props
        const {dragOverValue} = this.state
        if (dragOverValue !== null) {
            this.setState({dragOverValue: null, dragOverSize: null}, () =>
                onOtherDragEnd && onOtherDragEnd(value)
            )
        }
    }
}

export const Draggable = compose(
    _Draggable,
    withSubscriptions()
)

Draggable.propTypes = {
    drag$: PropTypes.object.isRequired,
    className: PropTypes.string,
    disabled: PropTypes.any,
    dragCloneClassName: PropTypes.string,
    dragPlaceholderClassName: PropTypes.string,
    dragTooltip: PropTypes.string,
    dragValue: PropTypes.any,
    hidden: PropTypes.any,
    index: PropTypes.any,
    item: PropTypes.any,
    itemRenderer: PropTypes.func,
    showHandle: PropTypes.any,
    onClick: PropTypes.func,
    onDragCancel: PropTypes.func,
    onDragEnd: PropTypes.func,
    onDragMove: PropTypes.func,
    onDragStart: PropTypes.func,
    onMouseOut: PropTypes.func,
    onMouseOver: PropTypes.func,
    onOtherDragEnd: PropTypes.func,
    onOtherDragStart: PropTypes.func
}


text:
package org.jrune.script.functions;

import java.util.Arrays;
import java.util.List;

import org.jrune.entity.EntityDefinitionNotFoundException;
import org.jrune.entity.RuneEntity;
import org.jrune.entity.RuneEntityLoader;
import org.jrune.script.RuneScriptContext;
import org.jrune.script.RuneScriptException;
import org.jrune.script.RuneScriptRuntimeError;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.OneArgFunction;

/**
 * Provides the function inherit for the scripting API. calling it causes
 * an entity to inherit all properties and script functions from the given
 * parent.
 *
 * To explicitly access functions of the parent (e.g. when overwriting them) use
 * the object called parent
 *
 * Example:
 * inherit('parent.entity')
 * parent:someInheritedFunction()
 *
 *
 * @author edd
 *
 */
public class Inherit extends OneArgFunction {
    private static String[] notInheritedProps = {
	    RuneEntity.PROP_ENTITY,
	    RuneEntity.PROP_BASE,
	    RuneEntity.PROP_UID,
	    RuneEntity.PROP_LOCATION,
	    RuneEntity.PROP_SCRIPT
    };

    private RuneScriptContext context = null;

    public Inherit(RuneScriptContext context) {
	this.context = context;
    }

    @Override
    public LuaValue call(LuaValue arg) {
	System.out.println("inheriting: "+arg.tostring());
	if (!arg.isstring()) {
	    throw new RuneScriptRuntimeError("invalid or missing argument");
	}

	RuneEntity self = context.getEntity();
	if (self == null) {
	    throw new RuneScriptRuntimeError("inherit is only allowed within entity context");
	}

	RuneEntity parent = self.getEngine().getBlueprint(arg.toString());
	if (parent == null) {
	    // entity not yet loaded -> try loading and fail if it does not
	    // exist
	    RuneEntityLoader loader = new RuneEntityLoader(self.getEngine());
	    try {
		loader.load(arg.toString());
	    } catch (RuneScriptException e) {
		throw new RuneScriptRuntimeError("error loading parent entity: " + e.getMessage());
	    } catch (EntityDefinitionNotFoundException e) {
		throw new RuneScriptRuntimeError("parent entity for inheritance does not exist");
	    }

	    parent = self.getEngine().getBlueprint(arg.toString());
	}

	// copy properties from parent
	List<String> excludedProps = Arrays.asList(notInheritedProps);
	for (String prop : parent.getProperties()) {
	    if (!excludedProps.contains(prop)) {
		self.setProperty(prop, parent.getProperty(prop));
	    }
	}

	self.setProperty(RuneEntity.PROP_BASE, parent.getProperty(RuneEntity.PROP_ENTITY));

	return LuaValue.valueOf(true);
    }

}


text:
package com.github.daneko.android.iab.exception;

/**
 */
public class IabException extends Exception {
    public IabException(String detailMessage) {
        super(detailMessage);
    }

    public IabException(String detailMessage, Throwable throwable) {
        super(detailMessage, throwable);
    }

    public IabException(Throwable throwable) {
        super(throwable);
    }
}


text:
#ifndef QCOREAPPLICATION_H
#define QCOREAPPLICATION_H

#include <QtCore/qglobal.h>
#include <QtCore/qstring.h>
#ifndef QT_NO_QOBJECT
#include <QtCore/qobject.h>
#include <QtCore/qcoreevent.h>
#include <QtCore/qeventloop.h>
#else
#include <QtCore/qscopedpointer.h>
#endif

#ifndef QT_NO_QOBJECT
#if defined(Q_OS_WIN) && !defined(tagMSG)
typedef struct tagMSG MSG;
#endif
#endif

QT_BEGIN_NAMESPACE

class QCoreApplicationPrivate;
class QTextCodec;
class QTranslator;
class QPostEventList;
class QStringList;
class QAbstractEventDispatcher;
class QAbstractNativeEventFilter;

#define qApp QCoreApplication::instance()

class Q_CORE_EXPORT QCoreApplication
#ifndef QT_NO_QOBJECT
    : public QObject
#endif
{
#ifndef QT_NO_QOBJECT
    Q_OBJECT
    Q_PROPERTY(QString applicationName READ applicationName WRITE setApplicationName NOTIFY applicationNameChanged)
    Q_PROPERTY(QString applicationVersion READ applicationVersion WRITE setApplicationVersion NOTIFY applicationVersionChanged)
    Q_PROPERTY(QString organizationName READ organizationName WRITE setOrganizationName NOTIFY organizationNameChanged)
    Q_PROPERTY(QString organizationDomain READ organizationDomain WRITE setOrganizationDomain NOTIFY organizationDomainChanged)
    Q_PROPERTY(bool quitLockEnabled READ isQuitLockEnabled WRITE setQuitLockEnabled)
#endif

    Q_DECLARE_PRIVATE(QCoreApplication)
public:
    enum { ApplicationFlags = QT_VERSION
    };

    QCoreApplication(int &argc, char **argv
#ifndef Q_QDOC
                     , int = ApplicationFlags
#endif
            );

    ~QCoreApplication();

    static QStringList arguments();

    static void setAttribute(Qt::ApplicationAttribute attribute, bool on = true);
    static bool testAttribute(Qt::ApplicationAttribute attribute);

    static void setOrganizationDomain(const QString &orgDomain);
    static QString organizationDomain();
    static void setOrganizationName(const QString &orgName);
    static QString organizationName();
    static void setApplicationName(const QString &application);
    static QString applicationName();
    static void setApplicationVersion(const QString &version);
    static QString applicationVersion();

    static void setSetuidAllowed(bool allow);
    static bool isSetuidAllowed();

    static QCoreApplication *instance() { return self; }

#ifndef QT_NO_QOBJECT
    static int exec();
    static void processEvents(QEventLoop::ProcessEventsFlags flags = QEventLoop::AllEvents);
    static void processEvents(QEventLoop::ProcessEventsFlags flags, int maxtime);
    static void exit(int retcode=0);

    static bool sendEvent(QObject *receiver, QEvent *event);
    static void postEvent(QObject *receiver, QEvent *event, int priority = Qt::NormalEventPriority);
    static void sendPostedEvents(QObject *receiver = Q_NULLPTR, int event_type = 0);
    static void removePostedEvents(QObject *receiver, int eventType = 0);
#if QT_DEPRECATED_SINCE(5, 3)
    QT_DEPRECATED static bool hasPendingEvents();
#endif
    static QAbstractEventDispatcher *eventDispatcher();
    static void setEventDispatcher(QAbstractEventDispatcher *eventDispatcher);

    virtual bool notify(QObject *, QEvent *);

    static bool startingUp();
    static bool closingDown();
#endif

    static QString applicationDirPath();
    static QString applicationFilePath();
    static qint64 applicationPid();

#ifndef QT_NO_LIBRARY
    static void setLibraryPaths(const QStringList &);
    static QStringList libraryPaths();
    static void addLibraryPath(const QString &);
    static void removeLibraryPath(const QString &);
#endif // QT_NO_LIBRARY

#ifndef QT_NO_TRANSLATION
    static bool installTranslator(QTranslator * messageFile);
    static bool removeTranslator(QTranslator * messageFile);
#endif

    static QString translate(const char * context,
                             const char * key,
                             const char * disambiguation = Q_NULLPTR,
                             int n = -1);
#if QT_DEPRECATED_SINCE(5, 0)
    enum Encoding { UnicodeUTF8, Latin1, DefaultCodec = UnicodeUTF8, CodecForTr = UnicodeUTF8 };
    QT_DEPRECATED static inline QString translate(const char * context, const char * key,
                             const char * disambiguation, Encoding, int n = -1)
        { return translate(context, key, disambiguation, n); }
#endif

#ifndef QT_NO_QOBJECT
    static void flush();

    void installNativeEventFilter(QAbstractNativeEventFilter *filterObj);
    void removeNativeEventFilter(QAbstractNativeEventFilter *filterObj);

    static bool isQuitLockEnabled();
    static void setQuitLockEnabled(bool enabled);

public Q_SLOTS:
    static void quit();

Q_SIGNALS:
    void aboutToQuit(QPrivateSignal);

    void organizationNameChanged();
    void organizationDomainChanged();
    void applicationNameChanged();
    void applicationVersionChanged();

protected:
    bool event(QEvent *) Q_DECL_OVERRIDE;

    virtual bool compressEvent(QEvent *, QObject *receiver, QPostEventList *);
#endif // QT_NO_QOBJECT

protected:
    QCoreApplication(QCoreApplicationPrivate &p);

#ifdef QT_NO_QOBJECT
    QScopedPointer<QCoreApplicationPrivate> d_ptr;
#endif

private:
#ifndef QT_NO_QOBJECT
    static bool sendSpontaneousEvent(QObject *receiver, QEvent *event);
#  if QT_DEPRECATED_SINCE(5,6)
    QT_DEPRECATED bool notifyInternal(QObject *receiver, QEvent *event); // ### Qt6 BIC: remove me
#  endif
    static bool notifyInternal2(QObject *receiver, QEvent *);
#endif

    static QCoreApplication *self;

    Q_DISABLE_COPY(QCoreApplication)

    friend class QApplication;
    friend class QApplicationPrivate;
    friend class QGuiApplication;
    friend class QGuiApplicationPrivate;
    friend class QWidget;
    friend class QWidgetWindow;
    friend class QWidgetPrivate;
#ifndef QT_NO_QOBJECT
    friend class QEventDispatcherUNIXPrivate;
    friend class QCocoaEventDispatcherPrivate;
    friend bool qt_sendSpontaneousEvent(QObject*, QEvent*);
#endif
    friend Q_CORE_EXPORT QString qAppName();
    friend class QClassFactory;
};

#ifndef QT_NO_QOBJECT
inline bool QCoreApplication::sendEvent(QObject *receiver, QEvent *event)
{  if (event) event->spont = false; return notifyInternal2(receiver, event); }

inline bool QCoreApplication::sendSpontaneousEvent(QObject *receiver, QEvent *event)
{ if (event) event->spont = true; return notifyInternal2(receiver, event); }
#endif

#ifdef QT_NO_DEPRECATED
#  define QT_DECLARE_DEPRECATED_TR_FUNCTIONS(context)
#else
#  define QT_DECLARE_DEPRECATED_TR_FUNCTIONS(context) \
    QT_DEPRECATED static inline QString trUtf8(const char *sourceText, const char *disambiguation = Q_NULLPTR, int n = -1) \
        { return QCoreApplication::translate(#context, sourceText, disambiguation, n); }
#endif

#define Q_DECLARE_TR_FUNCTIONS(context) \
public: \
    static inline QString tr(const char *sourceText, const char *disambiguation = Q_NULLPTR, int n = -1) \
        { return QCoreApplication::translate(#context, sourceText, disambiguation, n); } \
    QT_DECLARE_DEPRECATED_TR_FUNCTIONS(context) \
private:

typedef void (*QtStartUpFunction)();
typedef void (*QtCleanUpFunction)();

Q_CORE_EXPORT void qAddPreRoutine(QtStartUpFunction);
Q_CORE_EXPORT void qAddPostRoutine(QtCleanUpFunction);
Q_CORE_EXPORT void qRemovePostRoutine(QtCleanUpFunction);
Q_CORE_EXPORT QString qAppName();                // get application name

#define Q_COREAPP_STARTUP_FUNCTION(AFUNC) \
    static void AFUNC ## _ctor_function() {  \
        qAddPreRoutine(AFUNC);        \
    }                                 \
    Q_CONSTRUCTOR_FUNCTION(AFUNC ## _ctor_function)

#ifndef QT_NO_QOBJECT
#if defined(Q_OS_WIN) && !defined(QT_NO_DEBUG_STREAM)
Q_CORE_EXPORT QString decodeMSG(const MSG &);
Q_CORE_EXPORT QDebug operator<<(QDebug, const MSG &);
#endif
#endif

QT_END_NAMESPACE

#endif // QCOREAPPLICATION_H


text:
from iptest.assert_util import *
skiptest("silverlight")
skiptest("win32")
from iptest.console_util import IronPythonInstance

remove_ironpython_dlls(testpath.public_testdir)

from sys import executable
from System import Environment
from sys import exec_prefix

extraArgs = ""
if "-X:LightweightScopes" in Environment.GetCommandLineArgs():
    extraArgs += " -X:LightweightScopes"

def test_strings():
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)

    # String exception
    response = ipi.ExecuteLine("raise 'foo'", True)
    AreEqual(response.replace("\r\r\n", "\n").replace("\r", ""),
            """Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: exceptions must be classes, or instances, not str""")

    # Multi-line string literal
    ipi.ExecutePartialLine("\"\"\"Hello")
    ipi.ExecutePartialLine("")
    ipi.ExecutePartialLine("")
    AreEqual("'Hello\\n\\n\\nWorld'", ipi.ExecuteLine("World\"\"\""))

    ipi.ExecutePartialLine("if False: print 3")
    ipi.ExecutePartialLine("else: print 'hello'")
    AreEqual(r'hello', ipi.ExecuteLine(""))

    # Empty line
    AreEqual("", ipi.ExecuteLine(""))

    ipi.End()

def test_exceptions():
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)

    # parameterless exception
    response = ipi.ExecuteLine("raise Exception", True)
    AreEqual(response,
             '''Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Exception'''.replace("\n", "\r\r\n") + "\r")

    ipi.End()

def test_exceptions_nested():
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)

    ipi.ExecutePartialLine("def a(): return b()")
    ipi.ExecuteLine("")
    ipi.ExecutePartialLine("def b(): return 1/0")
    ipi.ExecuteLine("")
    response = ipi.ExecuteLine("a()", True)
    response = response.replace("\r\r\n", "\n").strip()
    Assert(response.startswith('''Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in a
  File "<stdin>", line 1, in b
ZeroDivisionError:'''), response)

    ipi.End()

###############################################################################
# Test "ipy.exe -i script.py"

def test_interactive_mode():
    inputScript = testpath.test_inputs_dir + "\\simpleCommand.py"
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs + " -i \"" + inputScript + "\"")
    AreEqual(ipi.Start(), True)
    ipi.EnsureInteractive()
    AreEqual("1", ipi.ExecuteLine("x"))
    ipi.End()

    inputScript = testpath.test_inputs_dir + "\\raise.py"
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs + " -i \"" + inputScript + "\"")
    AreEqual(ipi.Start(), True)
    ipi.ReadError()
    ipi.EnsureInteractive()
    AreEqual("1", ipi.ExecuteLine("x"))
    ipi.End()

    inputScript = testpath.test_inputs_dir + "\\syntaxError.py"
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs + " -i \"" + inputScript + "\"")
    AreEqual(ipi.Start(), True)
    # ipi.EnsureInteractive()
    AssertContains(ipi.ExecuteLine("x", True), "NameError")
    ipi.End()

    inputScript = testpath.test_inputs_dir + "\\exit.py"
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs + " -i \"" + inputScript + "\"")
    (result, output, output2, exitCode) = ipi.StartAndRunToCompletion()
    AreEqual(exitCode, 0)
    ipi.End()

    # interactive + -c
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs + " -i -c x=2")
    AreEqual(ipi.Start(), True)
    ipi.EnsureInteractive()
    Assert(ipi.ExecuteLine("x", True).find("2") != -1)
    ipi.End()

###############################################################################
# Test sys.exitfunc

def test_sys_exitfunc():
    import clr

    inputScript = testpath.test_inputs_dir + "\\exitFuncRuns.py"
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs + " \"" + inputScript + "\"")
    (result, output, output2, exitCode) = ipi.StartAndRunToCompletion()
    AreEqual(exitCode, 0)
    AreEqual(output.find('hello world') > -1, True)
    ipi.End()

    args = extraArgs

    if clr.GetCurrentRuntime().Configuration.DebugMode:
        args = "-D " + args

    inputScript = testpath.test_inputs_dir + "\\exitFuncRaises.py"
    ipi = IronPythonInstance(executable, exec_prefix, args + " \"" + inputScript + "\"")
    (result, output, output2, exitCode) = ipi.StartAndRunToCompletion()
    AreEqual(exitCode, 0)
    AreEqual(output2.find('Error in sys.exitfunc:') > -1, True)

    AreEqual(output2.find('exitFuncRaises.py", line 19, in foo') > -1, True)

    ipi.End()

    # verify sys.exit(True) and sys.exit(False) return 1 and 0

    ipi = IronPythonInstance(executable, exec_prefix, '-c "import sys; sys.exit(False)"')
    res = ipi.StartAndRunToCompletion()
    AreEqual(res[0], True)  # should have started
    AreEqual(res[1], '')    # no std out
    AreEqual(res[2], '')    # no std err
    AreEqual(res[3], 0)     # should return 0

    ipi = IronPythonInstance(executable, exec_prefix, '-c "import sys; sys.exit(True)"')
    res = ipi.StartAndRunToCompletion()
    AreEqual(res[0], True)  # should have started
    AreEqual(res[1], '')    # no std out
    AreEqual(res[2], '')    # no std err
    AreEqual(res[3], 1)     # should return 0

    # and verify it works at the interactive console as well
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)

    # parameterless exception
    ipi.ExecuteLine("import sys")
    AreEqual(ipi.ExecuteAndExit("sys.exit(False)"), 0)

    # and verify it works at the interactive console as well
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)

    # parameterless exception
    ipi.ExecuteLine("import sys")
    AreEqual(ipi.ExecuteAndExit("sys.exit(True)"), 1)

#############################################################################
# verify we need to dedent to a previous valid indentation level

def test_indentation():
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)
    ipi.ExecutePartialLine("if False:")
    ipi.ExecutePartialLine("    print 'hello'")
    response = ipi.ExecuteLine("  print 'goodbye'", True)
    AreEqual(response.find('IndentationError') > 1, True)
    ipi.End()

#############################################################################
# verify we dump exception details

def test_dump_exception():
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs + " -X:ExceptionDetail")
    AreEqual(ipi.Start(), True)
    response = ipi.ExecuteLine("raise 'goodbye'", True)
    AreEqual(response.count("IronPython.Hosting") >= 1, True)
    ipi.End()

#############################################################################
# make sure we can enter try/except blocks

def test_try_except():
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)
    ipi.ExecutePartialLine("try:")
    ipi.ExecutePartialLine("    raise Exception('foo')")
    ipi.ExecutePartialLine("except Exception, e:")
    ipi.ExecutePartialLine("    if e.message=='foo':")
    ipi.ExecutePartialLine("        print 'okay'")
    response = ipi.ExecuteLine("")
    Assert(response.find('okay') > -1)
    ipi.End()

###########################################################
# Throw on "complete" incomplete syntax bug #864

def test_incomplate_syntax():
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)
    ipi.ExecutePartialLine("class K:")
    response = ipi.ExecuteLine("", True)
    Assert("IndentationError:" in response)
    ipi.End()

def test_incomplate_syntax_backslash():
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)

    for i in range(4):
        for j in range(i):
            ipi.ExecutePartialLine("\\")
        ipi.ExecutePartialLine("1 + \\")
        for j in range(i):
            ipi.ExecutePartialLine("\\")
        response = ipi.ExecuteLine("2", True)
        Assert("3" in response)

    ipi.End()

###########################################################
# if , while, try, for and then EOF.
def test_missing_test():
    for x in ['if', 'while', 'for', 'try']:
        ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
        AreEqual(ipi.Start(), True)
        response = ipi.ExecuteLine(x, True)
        Assert("SyntaxError:" in response)
        ipi.End()

##########################################################
# Support multiple-levels of indentation
def test_indentation_levels():
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)
    ipi.ExecutePartialLine("class K:")
    ipi.ExecutePartialLine("  def M(self):")
    ipi.ExecutePartialLine("    if 1:")
    ipi.ExecutePartialLine("      pass")
    response = ipi.ExecuteLine("")
    ipi.End()

##########################################################
# Support partial lists
def test_partial_lists():
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)
    ipi.ExecutePartialLine("[1")
    ipi.ExecutePartialLine("  ,")
    ipi.ExecutePartialLine("    2")
    response = ipi.ExecuteLine("]")
    Assert("[1, 2]" in response)

    ipi.ExecutePartialLine("[")
    ipi.ExecutePartialLine("")
    ipi.ExecutePartialLine("")
    response = ipi.ExecuteLine("]")
    Assert("[]" in response)
    ipi.End()

def test_partial_lists_cp3530():

    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)

    try:
        ipi.ExecutePartialLine("[{'a':None},")
        response = ipi.ExecuteLine("]")
        Assert("[{'a': None}]" in response, response)

        ipi.ExecutePartialLine("[{'a'")
        response = ipi.ExecutePartialLine(":None},")
        response = ipi.ExecuteLine("]")
        Assert("[{'a': None}]" in response, response)

        ipi.ExecutePartialLine("[{'a':None},")
        ipi.ExecutePartialLine("1,")
        response = ipi.ExecuteLine("2]")
        Assert("[{'a': None}, 1, 2]" in response, response)

    finally:
        ipi.End()

##########################################################
# Support partial tuples
def test_partial_tuples():
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)
    ipi.ExecutePartialLine("(2")
    ipi.ExecutePartialLine("  ,")
    ipi.ExecutePartialLine("    3")
    response = ipi.ExecuteLine(")")
    Assert("(2, 3)" in response)

    ipi.ExecutePartialLine("(")
    response = ipi.ExecuteLine(")")
    Assert("()" in response)

    ipi.ExecutePartialLine("'abc %s %s %s %s %s' % (")
    ipi.ExecutePartialLine("    'def'")
    ipi.ExecutePartialLine("    ,'qrt',")
    ipi.ExecutePartialLine("    'jkl'")
    ipi.ExecutePartialLine(",'jkl'")
    ipi.ExecutePartialLine("")
    ipi.ExecutePartialLine(",")
    ipi.ExecutePartialLine("")
    ipi.ExecutePartialLine("")
    ipi.ExecutePartialLine("'123'")
    response = ipi.ExecuteLine(")")
    Assert("'abc def qrt jkl jkl 123'" in response)

    ipi.ExecutePartialLine("a = (")
    ipi.ExecutePartialLine("    1")
    ipi.ExecutePartialLine(" , ")
    ipi.ExecuteLine(")")
    response = ipi.ExecuteLine("a")
    Assert("(1,)" in response)

    ipi.ExecutePartialLine("(")
    ipi.ExecutePartialLine("'joe'")
    ipi.ExecutePartialLine(" ")
    ipi.ExecutePartialLine("       #")
    ipi.ExecutePartialLine(",")
    ipi.ExecutePartialLine("2")
    response = ipi.ExecuteLine(")")
    Assert("('joe', 2)" in response)

    ipi.ExecutePartialLine("(")
    ipi.ExecutePartialLine("")
    ipi.ExecutePartialLine("")
    response = ipi.ExecuteLine(")")
    Assert("()" in response)

    ipi.End()

##########################################################
# Support partial dicts
def test_partial_dicts():
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)
    ipi.ExecutePartialLine("{2:2")
    ipi.ExecutePartialLine("  ,")
    ipi.ExecutePartialLine("    2:2")
    response = ipi.ExecuteLine("}")
    Assert("{2: 2}" in response)

    ipi.ExecutePartialLine("{")
    response = ipi.ExecuteLine("}")
    Assert("{}" in response)

    ipi.ExecutePartialLine("a = {")
    ipi.ExecutePartialLine("    None:2")
    ipi.ExecutePartialLine(" , ")
    ipi.ExecuteLine("}")
    response = ipi.ExecuteLine("a")
    Assert("{None: 2}" in response)

    ipi.ExecutePartialLine("{")
    ipi.ExecutePartialLine("'joe'")
    ipi.ExecutePartialLine(": ")
    ipi.ExecutePartialLine("       42")
    ipi.ExecutePartialLine(",")
    ipi.ExecutePartialLine("3:45")
    response = ipi.ExecuteLine("}")
    Assert(repr({'joe':42, 3:45})  in response)

    ipi.ExecutePartialLine("{")
    ipi.ExecutePartialLine("")
    ipi.ExecutePartialLine("")
    response = ipi.ExecuteLine("}")
    Assert("{}" in response)

    ipi.End()

###########################################################
# Some whitespace wackiness
def test_whitespace():
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)
    ipi.ExecuteLine("  ")
    response = ipi.ExecuteLine("")
    ipi.End()

    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)
    ipi.ExecuteLine("  ")
    response = ipi.ExecuteLine("2")
    Assert("2" in response)
    ipi.End()

    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)
    ipi.ExecuteLine("  ")
    response = ipi.ExecuteLine("  2", True)
    Assert("SyntaxError:" in response)
    ipi.End()

###########################################################
# test the indentation error in the interactive mode
def test_indentation_interactive():
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)
    ipi.ExecutePartialLine("class C:pass")
    response = ipi.ExecuteLine("")
    AreEqual(response, "")
    ipi.ExecutePartialLine("class D(C):")
    response = ipi.ExecuteLine("", True)
    Assert("IndentationError:" in response)
    ipi.End()

###########################################################
# test /mta w/ no other args

def test_mta():
    ipi = IronPythonInstance(executable, exec_prefix, '-X:MTA')
    AreEqual(ipi.Start(), True)
    ipi.ExecutePartialLine("class C:pass")
    response = ipi.ExecuteLine("")
    AreEqual(response, "")
    ipi.ExecutePartialLine("class D(C):")
    response = ipi.ExecuteLine("", True)
    Assert("IndentationError:" in response)
    ipi.End()

###########################################################
# test for comments  in interactive input

def test_comments():
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)

    response = ipi.ExecuteLine("# this is some comment line")
    AreEqual(response, "")
    response = ipi.ExecuteLine("    # this is some comment line")
    AreEqual(response, "")
    response = ipi.ExecuteLine("# this is some more comment line")
    AreEqual(response, "")
    ipi.ExecutePartialLine("if 100:")
    ipi.ExecutePartialLine("    print 100")
    ipi.ExecutePartialLine("# this is some more comment line inside if")
    ipi.ExecutePartialLine("#     this is some indented comment line inside if")
    ipi.ExecutePartialLine("    print 200")
    response = ipi.ExecuteLine("")
    AreEqual(response, "100" + newline + "200")
    ipi.End()

def test_global_values():
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)
    ipi.ExecuteLine("import clr")
    response = ipi.ExecuteLine("[x for x in globals().values()]")
    Assert(response.startswith('['))
    d = eval(ipi.ExecuteLine("globals().fromkeys(['a', 'b'], 'c')"))
    AreEqual(d, {'a':'c', 'b':'c'})

def test_globals8961():
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)

    response = ipi.ExecuteLine("print globals().keys()")
    res = set(eval(response))
    AreEqual(res, set(['__builtins__', '__name__', '__doc__']))

    ipi.ExecuteLine("a = None")
    response = ipi.ExecuteLine("print globals().keys()")
    res = set(eval(response))
    AreEqual(res, set(['__builtins__', '__name__', '__doc__', 'a']))
    response = ipi.ExecuteLine("print globals().values()")
    l = eval(response.replace("<module '__builtin__' (built-in)>", '"builtin"'))
    res = set(l)
    AreEqual(len(l), 4)
    AreEqual(res, set(['builtin', '__main__', None]))

    ipi.ExecuteLine("b = None")
    response = ipi.ExecuteLine("print globals().values()")
    l = eval(response.replace("<module '__builtin__' (built-in)>", '"builtin"'))
    res = set(l)
    AreEqual(len(l), 5)
    AreEqual(res, set(['builtin', '__main__', None]))

def test_console_input_output():
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    input_output = [
    ("x=100",""),
    ("x=200\n",""),
    ("\nx=300",""),
    ("\nx=400\n",""),
    ("500","500"),
    ("600\n\n\n\n\n\n\n\n\n\n\n","600"),
    ("valid=3;more_valid=4;valid","3"),
    ("valid=5;more_valid=6;more_valid\n\n\n\n\n","6"),
    ("valid=7;more_valid=8;#valid",""),
    ("valid=9;valid;# more_valid\n","9"),
    ("valid=11;more_valid=12;more_valid# should be valid input\n\n\n\n","12"),
    ]

    for x in input_output:
        AreEqual(ipi.Start(), True)
        AreEqual(ipi.ExecuteLine(x[0]),x[1])
        ipi.End()

# expect a clean exception message/stack from thread
def test_thrown_from_thread():
    inputScript = path_combine(testpath.temporary_dir, "throwingfromthread.py")
    write_to_file(inputScript, '''
def f(): raise AssertionError, 'hello'
import thread, time
thread.start_new_thread(f, tuple())
time.sleep(2)
''')

    ipi = IronPythonInstance(executable, exec_prefix, extraArgs + " " + inputScript)
    (result, output, output2, exitCode) = ipi.StartAndRunToCompletion()
    AreEqual(exitCode, 0)
    Assert("AssertionError: hello" in output2)
    Assert("IronPython." not in output2)     # '.' is necessary here
    ipi.End()

def test_aform_feeds():
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)
    response = ipi.ExecuteLine("\fprint 'hello'")
    AreEqual(response, "hello")
    response = ipi.ExecuteLine("      \fprint 'hello'")
    AreEqual(response, "hello")

    ipi.ExecutePartialLine("def f():")
    ipi.ExecutePartialLine("\f    print 'hello'")
    ipi.ExecuteLine('')
    response = ipi.ExecuteLine('f()')
    AreEqual(response, "hello")

    # \f resets indent to 0
    ipi.ExecutePartialLine("def f():")
    ipi.ExecutePartialLine("    \f    x = 'hello'")
    ipi.ExecutePartialLine("\f    print x")

    ipi.ExecuteLine('')
    response = ipi.ExecuteLine('f()')
    AreEqual(response, "hello")

    # \f resets indent to 0
    ipi.ExecutePartialLine("def f():")
    ipi.ExecutePartialLine("    \f    x = 'hello'")
    ipi.ExecutePartialLine("    print x")

    ipi.ExecuteLine('')
    response = ipi.ExecuteLine('f()')
    AreEqual(response, "hello")

def test_ipy_dash_S():
    """ipy -S should still install Lib into sys.path"""
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs + " -S")
    AreEqual(ipi.Start(), True)
    response = ipi.ExecuteLine("import sys")
    response = ipi.ExecuteLine("print sys.path")
    Assert(response.find('Lib') != -1)

def test_startup_dir():
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)
    response = ipi.ExecuteLine("print dir()")
    AreEqual(sorted(eval(response)), sorted(['__builtins__', '__doc__', '__name__']))

def test_ipy_dash_m():
    import sys
    for path in sys.path:
        if path.find('Lib') != -1:
            filename = System.IO.Path.Combine(path, 'somemodule.py')
            break

    try:
        f = file(filename, 'w')
        f.write('print "hello"\n')
        f.write('import sys\n')
        f.write('print sys.argv')
        f.close()

        # need to run these tests where we have access to runpy.py
        path = System.IO.FileInfo(__file__).DirectoryName

        # simple case works
        ipi = IronPythonInstance(executable, path, extraArgs + " -m somemodule")
        res, output, err, exit = ipi.StartAndRunToCompletion()
        AreEqual(res, True) # run should have worked
        AreEqual(exit, 0)   # should have returned 0
        output = output.replace('\r\n', '\n')
        lines = output.split('\n')
        AreEqual(lines[0], 'hello')
        Assert(samefile(eval(lines[1])[0],
                        filename))

        # we receive any arguments in sys.argv
        ipi = IronPythonInstance(executable, path, extraArgs + " -m somemodule foo bar")
        res, output, err, exit = ipi.StartAndRunToCompletion()
        AreEqual(res, True) # run should have worked
        AreEqual(exit, 0)   # should have returned 0
        output = output.replace('\r\n', '\n')
        lines = output.split('\n')
        AreEqual(lines[0], 'hello')
        AreEqual(eval(lines[1]), [filename, 'foo', 'bar'])

        f = file(filename, 'w')
        f.write('print "hello"\n')
        f.write('import sys\n')
        f.write('sys.exit(1)')
        f.close()

        # sys.exit works
        ipi = IronPythonInstance(executable, path, extraArgs + " -m somemodule")
        res, output, err, exit = ipi.StartAndRunToCompletion()
        AreEqual(res, True) # run should have worked
        AreEqual(exit, 1)   # should have returned 0
        output = output.replace('\r\n', '\n')
        lines = output.split('\n')
        AreEqual(lines[0], 'hello')
    finally:
        nt.unlink(filename)

@disabled("CodePlex Work Item 10925")
def test_ipy_dash_m_negative():
    # builtin modules should not work
    for modname in [ "sys", "datetime" ]:
        ipi = IronPythonInstance(executable, exec_prefix,
                                 extraArgs + " -m " + modname)
        res, output, err, exit = ipi.StartAndRunToCompletion()
        AreEqual(exit, -1)

    # Modules within packages should not work
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs + " -m testpkg1.mod1")
    res, output, err, exit = ipi.StartAndRunToCompletion()
    AreEqual(res, True) # run should have worked
    AreEqual(exit, 1)   # should have returned 0
    Assert("SyntaxError: invalid syntax" in err,
           "stderr is:" + str(err))

def test_ipy_dash_m_pkgs():
    # Python packages work
    import nt
    Assert("testpkg1" in [x.lower() for x in nt.listdir(nt.getcwd())], nt.getcwd())

    old_ipy_path = get_environ_variable("IRONPYTHONPATH")
    try:
        nt.environ["IRONPYTHONPATH"] = nt.getcwd()
        ipi = IronPythonInstance(executable, exec_prefix, extraArgs + " -m testpkg1")
        res, output, err, exit = ipi.StartAndRunToCompletion()
        AreEqual(res, True) # run should have worked
        AreEqual(exit, 0)   # should have returned 0
        AreEqual(output, "")

        # Bad module names should not work
        ipi = IronPythonInstance(executable, exec_prefix, extraArgs + " -m libxyz")
        res, output, err, exit = ipi.StartAndRunToCompletion()
        AreEqual(res, True) # run should have worked
        AreEqual(exit, 1)   # should have returned 0
        Assert("ImportError: No module named libxyz" in err,
               "stderr is:" + str(err))
    finally:
        nt.environ["IRONPYTHONPATH"] = old_ipy_path

def test_ipy_dash_c():
    """verify ipy -c cmd doesn't print expression statements"""
    ipi = IronPythonInstance(executable, exec_prefix, "-c True;False")
    res = ipi.StartAndRunToCompletion()
    AreEqual(res[0], True)  # should have started
    AreEqual(res[1], '')    # no std out
    AreEqual(res[2], '')    # no std err
    AreEqual(res[3], 0)     # should return 0

#############################################################################
# CP11924 - verify 'from __future__ import division' works
def test_future_division():
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)
    ipi.ExecuteLine("from __future__ import division")
    response = ipi.ExecuteLine("11/4")
    AreEqual(response, "2.75")
    ipi.End()

#############################################################################
# CP2206
def test_future_with():
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)
    ipi.ExecutePartialLine("class K(object):")
    ipi.ExecutePartialLine("    def __enter__(self): return 3.14")
    ipi.ExecutePartialLine("    def __exit__(self, type, value, tb): return False")
    ipi.ExecuteLine("")
    ipi.ExecutePartialLine("with K() as d:")
    ipi.ExecutePartialLine("    print d")
    response = ipi.ExecuteLine("")
    AreEqual(response, "3.14")
    ipi.End()

#############################################################################
# Merlin 148481
def test_ipy_dash():
    #Verify that typing a - in the arguments starts an interactive session
    ipi = IronPythonInstance(executable, exec_prefix, "-")
    AreEqual(ipi.Start(), True)
    response = ipi.ExecuteLine("42")
    AreEqual(response, "42")
    ipi.End()

#############################################################################
def test_mta():
    ipi = IronPythonInstance(executable, exec_prefix, '-X:MTA')
    AreEqual(ipi.Start(), True)
    ipi.ExecuteLine("import System")
    response = ipi.ExecuteLine("str(System.Threading.Thread.CurrentThread.ApartmentState)")
    AreEqual(response, "'MTA'")

    ipi.ExecutePartialLine("class C:pass")
    response = ipi.ExecuteLine("")
    AreEqual(response, "")

    response = ipi.ExecuteLine("str(System.Threading.Thread.CurrentThread.ApartmentState)")
    AreEqual(response, "'MTA'")
    ipi.End()

def test_displayhook():
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)

    # parameterless exception
    ipi.ExecuteLine("import sys")
    ipi.ExecutePartialLine("def f(x): print 'foo', x")
    ipi.ExecuteLine("")
    response = ipi.ExecuteLine("sys.displayhook = f")
    response = ipi.ExecuteLine("42")
    AreEqual(response, "foo 42")

def test_excepthook():
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)

    # parameterless exception
    ipi.ExecuteLine("import sys")
    ipi.ExecutePartialLine("def f(*args): print 'foo', args")
    ipi.ExecuteLine("")
    response = ipi.ExecuteLine("sys.excepthook = f")
    response = ipi.ExecuteLine("raise Exception", True)
    AssertContains(response, "foo (<type 'exceptions.Exception'>, Exception(), <traceback object at")

def test_last_exception():
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)

    # parameterless exception
    ipi.ExecuteLine("import sys")
    response = ipi.ExecuteLine("hasattr(sys, 'last_value')")
    AreEqual(response, 'False')
    AssertContains(ipi.ExecuteLine("x", True), "NameError")
    response = ipi.ExecuteLine("sys.last_value")
    AreEqual(response, "NameError(\"name 'x' is not defined\",)")
    response = ipi.ExecuteLine("sys.last_type")
    AreEqual(response, "<type 'exceptions.NameError'>")
    response = ipi.ExecuteLine("sys.last_traceback")
    AssertContains(response, "<traceback object at ")

def test_sta_sleep_Warning():
    ipi = IronPythonInstance(executable, exec_prefix, '-c "from System.Threading import Thread;Thread.Sleep(100)"')
    retval, stdouttext, stderrtext, exitcode = ipi.StartAndRunToCompletion()
    Assert(stderrtext.endswith("RuntimeWarning: Calling Thread.Sleep on an STA thread doesn't pump messages.  Use Thread.CurrentThread.Join instead.\r\n"))

def test_newline():
    ipi = IronPythonInstance(executable, exec_prefix, "")
    ipi.proc.Start()
    ipi.reader = ipi.proc.StandardOutput
    output = ipi.EatToPrompt()
    Assert('\r\r\n' not in output)
    Assert('\r\n' in output)

#############################################################################
# Remote console tests

from System.Diagnostics import Process

def get_process_ids(ipi):
    ipi.EnsureInteractiveRemote()
    ipi.proc.Refresh()
    consoleProcessId = ipi.proc.Id
    ipi.ExecuteLine("import System")
    remoteRuntimeProcessId = ipi.ExecuteLineRemote("System.Diagnostics.Process.GetCurrentProcess().Id")
    Assert(remoteRuntimeProcessId.isdigit(), "remoteRuntimeProcessId is '%s'" % remoteRuntimeProcessId)
    return consoleProcessId, int(remoteRuntimeProcessId)

def start_remote_console(args = ""):
    inputScript = testpath.test_inputs_dir + "\\RemoteConsole.py"
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs + " \"" + inputScript + "\" -X:ExceptionDetail " + args)
    AreEqual(ipi.Start(), True)
    return ipi

# Basic check that the remote console actually uses two processes
def test_remote_console_processes():
    # First check that a simple local console uses a single process
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)
    consoleProcessId, remoteRuntimeProcessId = get_process_ids(ipi)
    AreEqual(consoleProcessId, remoteRuntimeProcessId)
    ipi.End()

    # Now use the remote console
    ipi = start_remote_console()
    consoleProcessId, remoteRuntimeProcessId = get_process_ids(ipi)
    AreNotEqual(consoleProcessId, remoteRuntimeProcessId)
    ipi.End()

# The remote runtime should terminate when the console terminates
def test_remote_runtime_normal_exit():
    ipi = start_remote_console()
    consoleProcessId, remoteRuntimeProcessId = get_process_ids(ipi)
    runtimeProcess = Process.GetProcessById(remoteRuntimeProcessId)
    Assert(not runtimeProcess.HasExited)
    ipi.End()
    runtimeProcess.WaitForExit() # The test is that this wait succeeds

# Stress the input-output streams
def test_remote_io():
    ipi = start_remote_console()
    for i in range(100):
        AreEqual(ipi.ExecuteLineRemote("2+2"), "4")
    ipi.End()

# Kill the remote runtime and ensure that another process starts up again
def test_remote_server_restart():
    ipi = start_remote_console()
    consoleProcessId, remoteRuntimeProcessId = get_process_ids(ipi)
    runtimeProcess = Process.GetProcessById(remoteRuntimeProcessId)
    AreNotEqual(runtimeProcess, consoleProcessId)

    runtimeProcess.Kill()
    runtimeProcess.WaitForExit()
    # The Process.Exited event is fired asynchronously, and might take sometime to fire.
    # Hence, we need to block for a known marker
    ipi.EatToMarker("Remote runtime terminated")

    # We need to press Enter to nudge the old console out of the ReadLine...
    restartMessage = ipi.ExecuteLine("", True)
    ipi.ReadError()

    consoleProcessId2, remoteRuntimeProcessId2 = get_process_ids(ipi)
    AreEqual(consoleProcessId, consoleProcessId2)
    # This is technically not a 100% correct as there is a small chance the the process id might get reused
    AreNotEqual(remoteRuntimeProcessId, remoteRuntimeProcessId2)
    ipi.End()

# Check that an exception can be remoted back over the reverse channel
# Note that exceptions are not written to stdout by the remote process
def test_remote_console_exception():
    ipi = start_remote_console()
    zeroDivisionErrorOutput = ipi.ExecuteLine("1/0", True)
    AssertContains(zeroDivisionErrorOutput, "ZeroDivisionError")
    ipi.End()

def test_remote_startup_script():
    ipi = start_remote_console("-i " + testpath.test_inputs_dir + "\\simpleCommand.py")
    AreEqual(ipi.ExecuteLine("x"), "1")
    ipi.End()

def get_abort_command_output():
    ipi = start_remote_console()
    ipi.ExecuteLine("import System")

    ipi.ExecutePartialLine  ("def Hang():")
    ipi.ExecutePartialLine  ("    print 'ABORT ME!!!' # This string token should trigger an abort...")
    ipi.ExecutePartialLine  ("    infinite = System.Threading.Timeout.Infinite")
    ipi.ExecutePartialLine  ("    System.Threading.Thread.CurrentThread.Join(infinite)")
    ipi.ExecuteLine         ("")

    result = ipi.ExecuteLine("Hang()", True)
    ipi.End()
    return result

def test_remote_abort_command():
    for i in range(10):
        output = get_abort_command_output()
        if "KeyboardInterrupt" in output:
            AssertDoesNotContain(output, "Thread was being aborted.") # ThreadAbortException
            return
        else:
            # Rarely, under stress conditions, ThreadAbortException leaks through.
            # Keep retrying until we actually get KeyboardInterrupt
            AssertContains(output, "Thread was being aborted.") # ThreadAbortException
            continue
    Assert(False, "KeyboardInterrupt not thrown. Only KeyboardInterrupt was thrown")

def test_exception_slicing_warning():
    ipi = IronPythonInstance(executable, exec_prefix, '-c "print Exception(*range(2))[1]"')
    res = ipi.StartAndRunToCompletion()
    AreEqual(res[0], True)  # should have started
    AreEqual(res[1], '1\r\n')   # some std out
    AreEqual(res[2], '')    # no std err
    AreEqual(res[3], 0)     # should return 0

    ipi = IronPythonInstance(executable, exec_prefix,
        '-3 -c "import warnings;'
        'warnings.filters.reverse();'
        'warnings.filters.pop();'
        'print Exception(*range(2))[1]"')
    res = ipi.StartAndRunToCompletion()
    AreEqual(res[0], True)  # should have started
    AreEqual(res[1], '1\r\n')   # std out
    Assert(res[2].endswith('DeprecationWarning: __getitem__ not supported for exception classes in 3.x; use args attribute\r\n')) #std err
    AreEqual(res[3], 0)     # should return 0

#------------------------------------------------------------------------------

run_test(__name__)


text:
module UnifiedAttachmentAssociationMethods
  def generate_flavor(association_id)
    "#{self.name}_#{association_id.to_s}"
  end

  def has_one_unified_attachment(association_id, options = {})
    flavor = self.generate_flavor(association_id)
    default_options = {
      :as          => :uploadable,
      :class_name  => "UnifiedUpload",
      :foreign_key => "uploadable_id",
      :conditions  => {:flavor => flavor}
    }

    # gotta dupe before we merge conditions
    options = options.dup.symbolize_keys

    if options[:conditions]
      options[:conditions] = options[:conditions].dup.symbolize_keys
      options[:conditions].reverse_merge!(default_options[:conditions])
    end

    options.reverse_merge!(default_options)
    tmp = has_one(association_id, options)
    self.unify_has_one_attachments(association_id)
    tmp
  end

  def has_many_unified_attachments(association_id, options = {})
    flavor = self.generate_flavor(association_id)
    default_options = {
      :as          => :uploadable,
      :class_name  => "UnifiedUpload",
      :foreign_key => "uploadable_id",
      :conditions  => {:flavor => flavor},
      :before_add  => Proc.new {|parent, item| item.flavor = flavor }
    }

    # we want these to stack
    if options[:before_add] && options[:before_add].is_a?(Array)
      options[:before_add] << default_options[:before_add]
    elsif options[:before_add]
      options[:before_add] = [options[:before_add]]
      options[:before_add] << default_options[:before_add]
    end

    # gotta dupe before we merge conditions
    options = options.dup.symbolize_keys

    if options[:conditions]
      options[:conditions] = options[:conditions].dup.symbolize_keys
      options[:conditions].reverse_merge!(default_options[:conditions])
    end

    options.reverse_merge!(default_options)

    has_many(association_id, options)
  end

  def unify_has_one_attachments(association_id)
    flavor = self.generate_flavor(association_id)
    module_eval do
      alias :"ar_#{association_id}=" :"#{association_id}="
      alias :"ar_build_#{association_id}" :"build_#{association_id}"
    end

    define_method("#{association_id}=") do |*params|
      unless params.first.kind_of?(UnifiedUpload)
        params[0] = UnifiedUpload.new(:content => params[0])
      end
      params.first.flavor = flavor
      self.send("ar_#{association_id}=", *params)
    end

    define_method("build_#{association_id}") do |*params|
      params << {} unless params.first
      params.first[:flavor] = flavor
      self.send("ar_build_#{association_id}", *params)
    end

    define_method("create_#{association_id}") do |*params|
      params << {} unless params.first
      params.first[:flavor] = flavor
      self.send("ar_build_#{association_id}", *params)
    end
  end

end

ActiveRecord::Base.extend(UnifiedAttachmentAssociationMethods)


text:
from __future__ import absolute_import, division, print_function

import json
import netmiko
import mytools
import signal
import sys

signal.signal(signal.SIGPIPE, signal.SIG_DFL)  # IOError: Broken pipe
signal.signal(signal.SIGINT, signal.SIG_DFL)  # KeyboardInterrupt: Ctrl-C

if len(sys.argv) < 3:
    print('Usage: cmdrunner.py commands.txt devices.json')
    exit()

netmiko_exceptions = (netmiko.ssh_exception.NetMikoTimeoutException,
                      netmiko.ssh_exception.NetMikoAuthenticationException)

username, password = mytools.get_credentials()

with open(sys.argv[1]) as cmd_file:
    commands = cmd_file.readlines()

with open(sys.argv[2]) as dev_file:
     devices = json.load(dev_file)

for device in devices:
    device['username'] = username
    device['password'] = password
    try:
        print('~' * 79)
        print('Connecting to device:', device['ip'])
        connection = netmiko.ConnectHandler(**device)
        for command in commands:
            print('## Output of ' + command)
            print(connection.send_command(command))
            print()
        connection.disconnect()
    except netmiko_exceptions as e:
        print('Failed to ', device['ip'], e)


text:
If you liked this post, you can

  share it with your followers
or

  follow me on Twitter!


text:
require 'spec_helper'

describe Conversation do

  subject { build(:conversation) }

  let(:message) { build(:message) }

  it "is valid" do
    expect(subject).to be_valid
  end

  it "is not archived" do
    expect(subject).to_not be_archived
  end

  it "is reopened when new messages are added" do
    subject.archived = true
    subject.messages << message
    expect(subject).to_not be_archived
  end

  describe "#unarchive!" do
    before do
      subject.save
      subject.unarchive!
    end

    it "archives the conversation" do
      expect(subject).to_not be_archived
    end

    it "sets the flash notice" do
      expect(subject.flash_notice).to eq("The conversation has been moved to the inbox.")
    end
  end

  describe "#archive!" do
    before do
      subject.save
      subject.archive!
    end

    it "archives the conversation" do
      expect(subject).to be_archived
    end

    it "sets the flash notice" do
      expect(subject.flash_notice).to eq("The conversation has been archived.")
    end
  end

  describe "#respond_later!" do
    let!(:user) { create(:user) }

    before { subject.save }

    it "creates a respond later record" do
      subject.respond_later!(user)

      expect(subject.respond_laters).not_to be_empty
    end
  end

  describe "#mailbox_email" do
    before { subject.save }

    it "must return a valid email" do
      expect(subject.mailbox_email.address).to_not be_empty
    end

    it "must have the correct local part" do
      subject.save
      expect(subject.mailbox_email.local).to eq(subject.id)
    end

    it "must have the correct domain part" do
      subject.save
      expect(subject.mailbox_email.domain).to eq(Helpful.incoming_email_domain)
    end

    it "must have the correct display name" do
      subject.save
      expect(subject.mailbox_email.display_name).to eq(subject.account.name)
    end
  end

  describe ".match_mailbox" do

    it "matches a mailbox email to a conversation" do
      subject.save
      expect(described_class.match_mailbox(subject.mailbox_email.to_s)).to eq(subject)
    end

    it "raises an exception if a converstion is not found" do
      subject.save
      address = subject.mailbox_email.to_s
      subject.delete
      expect {
        described_class.match_mailbox!(address)
      }.to raise_error(ActiveRecord::RecordNotFound)
    end
  end

  describe "#most_recent_message" do
    it "returns the most recently updated message" do
      subject.save
      _old_message = create(:message, conversation: subject, updated_at: 10.minutes.ago)
      new_message = create(:message, conversation: subject, updated_at: 1.minute.ago)

      expect(subject.most_recent_message).to eq(new_message)
    end
  end

  describe "#last_activity_at" do
    it "returns the updated at timestamp of the most recent message" do
      most_recent_message = double("Message", updated_at: Time.utc(2014, 3, 24, 12, 0, 0))

      allow(subject).to receive(:most_recent_message) { most_recent_message }

      expect(subject.last_activity_at).to eq(Time.utc(2014, 3, 24, 12, 0, 0))
    end

    it "uses the conversation updated at timestamp if there are no messages" do
      allow(subject).to receive(:most_recent_message) { nil }
      allow(subject).to receive(:updated_at) { Time.utc(2014, 3, 24, 12, 0, 0) }

      expect(subject.last_activity_at).to eq(Time.utc(2014, 3, 24, 12, 0, 0))
    end
  end

  describe "#to_mailbox_hash" do

    before { subject.save }

    it "returns a hash containing the account_slug and the conversation_id" do
      expect(subject.to_mailbox_hash).to include(
        { account_slug: subject.account.slug },
        { conversation_number: subject.number }
      )
    end
  end

end


text:
class StoriesController < ApplicationController

  before_action :set_story, only: [:show, :update, :destroy]
  before_filter :admin_only, only: [:create, :update]

  def index
    stories = Story.all
    render json: stories, status: :ok
  end

  def show
    render json: @story, status: :ok
  end

  def create
    story = Story.create(story_params)
    if story.save
      render json: story, status: :created, location: story_url(story)
    else
      render json: {errors: story.errors.full_messages}, status: :unprocessable_entity
    end
  end

  def update
    if @story.update(story_params)
      render json: @story, status: :ok
    else
      render json: @story.errors, status: :unprocessable_entity
    end
  end

  def destroy
    @story.destroy
    head :no_content
  end

  def story_data
    render json: {
      number_ishmael_stories: Story.ishmaels_library.count,
      ishmael_listens: Story.listens_to_ishmaels_library,
      number_venue_stories: Story.all_venue_library.count,
      venue_listens: Story.listens_to_venue_library,
      number_postroll_stories: Story.postroll_library.count,
      postroll_listens: Story.listens_to_postrolls
    }.to_json, status: :ok
  end

  private

  def set_story
    @story = Story.find(params[:id])
  end

  def story_params
    params.require(:story).permit(:title, :url, :story_type, :author_last, :author_first, :listens, :percentage, :call_length, :common_title, :call_date, :spoiler_alert, :child_appropriate, :explicit, :gender, :rating, :transcript_url, :call_uuid)
  end

end


text:
from cmd_helpers import *
import time
import argparse
import sys
import os

AMI_IMAGE_ID = 'ami-84c33ae4'
SEC_GROUP_NAME = 'repro_rdd_secgroup'
INSTANCE_TYPE = 'm4.xlarge'
IS_AWS_RUNNING = False
MASTER = None
MASTER_ID = None
SLAVES = []
SLAVE_IDS = []

def main():
  parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,
      description="""Use EC2 to reproduce results from the Resilient Distributed Datasets (Spark) paper. Note: the created
instances are not designed to be secure, and it is not recommended to use them for anything else.""",
      epilog="""You can obtain your keys from https://console.aws.amazon.com/iam/home?region=us-west-2#security_credential
and http://docs.aws.amazon.com/general/latest/gr/managing-aws-access-keys.html contains more information.
AWS recommends creating IAM users, but if you trust this script you can just use your root account keys.""")
  parser.add_argument('access_key', metavar='YOUR_AWS_ACCESS_KEY', help='Your AWS access key ID')
  parser.add_argument('secret_key', metavar='YOUR_AWS_SECRET_KEY', help='Your AWS secret access key')
  args = parser.parse_args()

  set_cwd(__file__)
  import_boto3()
  ec2 = boto3.resource('ec2', region_name='us-west-2',  # us-west-2 has good pricing
      aws_access_key_id=args.access_key, aws_secret_access_key=args.secret_key)

  run(['chmod', '600', 'id_rsa'])
  create_secgroup(ec2, SEC_GROUP_NAME)
  get_or_launch_instances(ec2, 25, args, check_existing=True)
  run_instances(ec2)

  get_or_launch_instances(ec2, 100, args)
  run_instances(ec2)

  terminate(ec2)

def import_boto3():
  try:
    import boto3
  except ImportError:
    if not confirm('boto3 not installed. Do you want me to try and install it?'):
      abort()
    run(['pip', 'install', '--user', 'boto3'])
    import boto3
  globals()['boto3'] = __import__('boto3')

def create_secgroup(ec2, name):
  from botocore.exceptions import ClientError
  try:
    groups = list(ec2.security_groups.filter(GroupNames=[name]))
    if groups:
      highlight('Security group %s found, not recreating' % name)
      return
  except ClientError:
    pass

  highlight('Creating security group %s' % name)
  secgroup = ec2.create_security_group(GroupName=name, Description='Reproducing Spark results. Allows all TCP ingress/egress for simplicity.')
  secgroup.authorize_ingress(IpPermissions=[dict(IpProtocol='tcp',
      IpRanges=[dict(CidrIp='0.0.0.0/0')], FromPort=0, ToPort=65535)])
  secgroup.authorize_egress(IpPermissions=[dict(IpProtocol='tcp',
      IpRanges=[dict(CidrIp='0.0.0.0/0')], FromPort=0, ToPort=65535)])

def get_or_launch_instances(ec2, n, args, check_existing=False):
  global MASTER, MASTER_ID, SLAVES, SLAVE_IDS, IS_AWS_RUNNING
  running = []
  if check_existing:
    running = list(ec2.instances.filter(
          Filters=[{'Name': 'instance-state-name', 'Values': ['running']}]))
    if running:
      if not confirm('%d running instances found - do you want to use them? (If these instances have not been launched by this script, you should say "n".)' % len(running)):
        running = []

  if len(running) < n:
    running += launch_and_wait_instances(ec2, n - len(running), args)

  IS_AWS_RUNNING = True
  MASTER_ID = None
  if not MASTER:
    MASTER_ID = running[0].id
    MASTER = list(ec2.instances.filter(InstanceIds=[MASTER_ID]))[0].public_dns_name
    ec2.create_tags(Resources=[MASTER_ID], Tags=[dict(Key='Name', Value='repro_rdd master')])
    highlight('Master is ' + MASTER)

  slave_instances = filter(lambda i: i.id != MASTER_ID, running)
  ec2.create_tags(Resources=[instance.id for instance in slave_instances], Tags=[dict(Key='Name', Value='repro_rdd')])
  SLAVE_IDS += [instance.id for instance in slave_instances]
  slave_hosts = [instance.public_dns_name for instance in slave_instances]
  SLAVES += slave_hosts
  highlight('Added slaves are %r' % slave_hosts)

def launch_and_wait_instances(ec2, n, args):
  global IS_AWS_RUNNING
  if not confirm('About to launch %d instances. Proceed?' % n):
    sys.exit(1)

  instances = list(ec2.create_instances(ImageId=AMI_IMAGE_ID, MinCount=n, MaxCount=n,
      InstanceType=INSTANCE_TYPE, SecurityGroups=[SEC_GROUP_NAME]))
  IS_AWS_RUNNING = True
  highlight('Launched %r, waiting for initialization' % instances)

  while True:
    time.sleep(10)
    running = list(ec2.instances.filter(
        Filters=[{'Name': 'instance-state-name', 'Values': ['running']}]))
    print '%d instances running' % len(running)
    if len(running) == len(instances):
      break

  client = boto3.client('ec2', region_name='us-west-2',
      aws_access_key_id=args.access_key, aws_secret_access_key=args.secret_key)
  while True:
    statuses = client.describe_instance_status()
    if any([status['InstanceStatus']['Status'] != 'ok' for status in statuses['InstanceStatuses']]):
      print 'Waiting for instances to finish initializing'
      time.sleep(30)
    else:
      break

  highlight('All launched instances are running')
  return running

def run_instances(ec2):
  def write_core_site(fname, tmp_dir):
    with open(fname, 'w') as f:
      f.write("""<?xml version="1.0" encoding="UTF-8"?>
  <configuration>
   <property>
    <name>hadoop.tmp.dir</name>
    <value>%s</value>
    <description>A base for other temporary directories.</description>
   </property>

   <property>
    <name>fs.default.name</name>
    <value>hdfs://%s:54310</value>
    <description>The name of the default file system.  A URI whose
    scheme and authority determine the FileSystem implementation.  The
    uri's scheme determines the config property (fs.SCHEME.impl) naming
    the FileSystem implementation class.  The uri's authority is used to
    determine the host, port, etc. for a filesystem.</description>
   </property>
  </configuration>
  """ % (tmp_dir, MASTER))
  write_core_site('ec2/core-site.xml', '/home/ubuntu/hadoop_temp')

  with open('ec2/mapred-site.xml', 'w') as f:
    f.write("""<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
 <property>
  <name>mapred.job.tracker</name>
  <value>%s:54311</value>
  <description>The host and port that the MapReduce job tracker runs
  at.  If "local", then jobs are run in-process as a single map
  and reduce task.
  </description>
 </property>
</configuration>
""" % MASTER)
  with open('ec2/slaves', 'w') as f:
    f.write('\n'.join(SLAVES))
  with open('ec2/masters', 'w') as f:
    f.write(MASTER)

  highlight('Setting up machines')
  all_nodes = SLAVES + [MASTER]
  rsync_all(all_nodes, 'ec2/', '~/scripts')
  ssh_all(SLAVES, '~/scripts/setup.sh')
  ssh(MASTER, 'touch ~/scripts/is_master; ~/scripts/setup.sh')

  highlight('Generating data')
  ssh(MASTER, '~/scripts/gen_data.sh %d' % len(SLAVES))
  # Clear buffer caches
  ssh_all(all_nodes, 'sync; echo 3 | sudo tee /proc/sys/vm/drop_caches')

  highlight('Running experiments')
  # ssh(MASTER, '~/scripts/run_hadoopkmeans.sh')
  # ssh_all(all_nodes, 'sync; echo 3 | sudo tee /proc/sys/vm/drop_caches')
  ssh(MASTER, '~/scripts/run_hadooplr.sh')
  ssh_all(all_nodes, 'sync; echo 3 | sudo tee /proc/sys/vm/drop_caches')
  # ssh(MASTER, '~/scripts/run_sparkkmeans.sh')
  # ssh_all(all_nodes, 'sync; echo 3 | sudo tee /proc/sys/vm/drop_caches')
  ssh(MASTER, '~/scripts/run_sparklr.sh')

  highlight('Copying timing data')
  run(['mkdir', '-p', 'timings/%d' % len(all_nodes)])
  rsync_reverse(MASTER, '~/scripts/timings/', 'timings/%d' % len(all_nodes))

  highlight('Cleaning up')
  ssh(MASTER, '~/scripts/stop.sh')
  ssh_all(all_nodes, 'rm -r ~/hadoop_temp')

def terminate(ec2):
  global IS_AWS_RUNNING
  highlight('Terminating instances')
  ec2.instances.filter(InstanceIds=([MASTER_ID] + SLAVE_IDS))
  IS_AWS_RUNNING = False # TODO

if __name__ == '__main__':
  try:
    main()
  except KeyboardInterrupt:
    abort()
  finally:
    if IS_AWS_RUNNING:
      error('It seems an error occurred! Instances are likely STILL RUNNING. If '
            'you want to terminate them, you should go to the AWS console at '
            'https://us-west-2.console.aws.amazon.com/ec2/v2/home?region=us-west-2#Instances:sort=instanceState '
            'and terminate them manually.')