text:
.class public Lcom/htc/weather/animations/compoundAlphaAnimation;
.super Landroid/view/animation/Animation;
.source "compoundAlphaAnimation.java"

# instance fields
.field mDuration:J

.field private mDurs:[J

.field private mFromAlpha:[F

.field private mSeg_no:I

.field private mToAlpha:[F

# direct methods
.method public constructor <init>(FF)V
    .locals 4
    .parameter "fromAlpha"
    .parameter "toAlpha"

    .prologue
    const/4 v1, 0x1

    const/4 v3, 0x0

    .line 21
    invoke-direct {p0}, Landroid/view/animation/Animation;-><init>()V

    .line 9
    iput v3, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mSeg_no:I

    .line 22
    iput v1, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mSeg_no:I

    .line 23
    new-array v0, v1, [F

    iput-object v0, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mFromAlpha:[F

    .line 24
    new-array v0, v1, [F

    iput-object v0, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mToAlpha:[F

    .line 25
    new-array v0, v1, [J

    iput-object v0, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mDurs:[J

    .line 26
    iget-object v0, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mFromAlpha:[F

    aput p1, v0, v3

    .line 27
    iget-object v0, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mToAlpha:[F

    aput p2, v0, v3

    .line 28
    iget-object v0, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mDurs:[J

    iget-wide v1, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mDuration:J

    aput-wide v1, v0, v3

    .line 29
    return-void
.end method

.method public constructor <init>(I[F[F)V
    .locals 1
    .parameter "n"
    .parameter "fromAlpha"
    .parameter "toAlpha"

    .prologue
    .line 39
    invoke-direct {p0}, Landroid/view/animation/Animation;-><init>()V

    .line 9
    const/4 v0, 0x0

    iput v0, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mSeg_no:I

    .line 40
    iput p1, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mSeg_no:I

    .line 41
    invoke-virtual {p2}, [F->clone()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, [F

    iput-object v0, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mFromAlpha:[F

    .line 42
    invoke-virtual {p3}, [F->clone()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, [F

    iput-object v0, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mToAlpha:[F

    .line 43
    new-array v0, p1, [J

    iput-object v0, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mDurs:[J

    .line 44
    return-void
.end method

.method public constructor <init>(Landroid/content/Context;Landroid/util/AttributeSet;)V
    .locals 1
    .parameter "context"
    .parameter "attrs"

    .prologue
    .line 16
    invoke-direct {p0, p1, p2}, Landroid/view/animation/Animation;-><init>(Landroid/content/Context;Landroid/util/AttributeSet;)V

    .line 9
    const/4 v0, 0x0

    iput v0, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mSeg_no:I

    .line 18
    return-void
.end method

# virtual methods
.method protected applyTransformation(FLandroid/view/animation/Transformation;)V
    .locals 12
    .parameter "interpolatedTime"
    .parameter "t"

    .prologue
    .line 98
    iget v5, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mSeg_no:I

    .line 99
    .local v5, n:I
    const-wide/16 v2, 0x0

    .line 100
    .local v2, dur:J
    iget-wide v8, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mDuration:J

    long-to-float v8, v8

    mul-float/2addr v8, p1

    float-to-long v6, v8

    .line 101
    .local v6, nNow:J
    iget-wide v8, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mDuration:J

    long-to-float v8, v8

    cmpl-float v8, p1, v8

    if-lez v8, :cond_1

    .line 102
    iget-object v8, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mToAlpha:[F

    add-int/lit8 v9, v5, -0x1

    aget v8, v8, v9

    invoke-virtual {p2, v8}, Landroid/view/animation/Transformation;->setAlpha(F)V

    .line 121
    :cond_0
    :goto_0
    return-void

    .line 105
    :cond_1
    const/4 v4, 0x0

    .local v4, i:I
    :goto_1
    if-ge v4, v5, :cond_0

    .line 106
    iget-object v8, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mDurs:[J

    aget-wide v8, v8, v4

    cmp-long v8, v6, v8

    if-lez v8, :cond_2

    .line 107
    iget-object v8, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mDurs:[J

    aget-wide v8, v8, v4

    sub-long/2addr v6, v8

    .line 105
    add-int/lit8 v4, v4, 0x1

    goto :goto_1

    .line 110
    :cond_2
    iget-object v8, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mFromAlpha:[F

    aget v1, v8, v4

    .line 111
    .local v1, alpha:F
    iget-object v8, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mDurs:[J

    aget-wide v8, v8, v4

    const-wide/16 v10, 0x0

    cmp-long v8, v8, v10

    if-eqz v8, :cond_3

    iget-object v8, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mToAlpha:[F

    aget v8, v8, v4

    cmpl-float v8, v1, v8

    if-nez v8, :cond_4

    .line 112
    :cond_3
    invoke-virtual {p2, v1}, Landroid/view/animation/Transformation;->setAlpha(F)V

    goto :goto_0

    .line 114
    :cond_4
    iget-object v8, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mToAlpha:[F

    aget v8, v8, v4

    sub-float/2addr v8, v1

    long-to-float v9, v6

    mul-float/2addr v8, v9

    iget-object v9, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mDurs:[J

    aget-wide v9, v9, v4

    long-to-float v9, v9

    div-float/2addr v8, v9

    add-float v0, v1, v8

    .line 115
    .local v0, a:F
    const/4 v8, 0x0

    cmpg-float v8, v0, v8

    if-gez v8, :cond_6

    const/4 v0, 0x0

    .line 117
    :cond_5
    :goto_2
    invoke-virtual {p2, v0}, Landroid/view/animation/Transformation;->setAlpha(F)V

    goto :goto_0

    .line 116
    :cond_6
    const/high16 v8, 0x3f80

    cmpl-float v8, v0, v8

    if-lez v8, :cond_5

    const/high16 v0, 0x3f80

    goto :goto_2
.end method

.method public setDuration(J)V
    .locals 4
    .parameter "durationMillis"

    .prologue
    .line 51
    const-wide/16 v1, 0x0

    cmp-long v1, p1, v1

    if-gez v1, :cond_0

    .line 52
    new-instance v1, Ljava/lang/IllegalArgumentException;

    const-string v2, "Animation duration cannot be negative"

    invoke-direct {v1, v2}, Ljava/lang/IllegalArgumentException;-><init>(Ljava/lang/String;)V

    throw v1

    .line 54
    :cond_0
    const/4 v0, 0x0

    .local v0, i:I
    :goto_0
    iget v1, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mSeg_no:I

    if-ge v0, v1, :cond_1

    .line 55
    iget-object v1, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mDurs:[J

    iget v2, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mSeg_no:I

    int-to-long v2, v2

    div-long v2, p1, v2

    aput-wide v2, v1, v0

    .line 54
    add-int/lit8 v0, v0, 0x1

    goto :goto_0

    .line 57
    :cond_1
    invoke-super {p0, p1, p2}, Landroid/view/animation/Animation;->setDuration(J)V

    .line 58
    return-void
.end method

.method public setDuration([J)V
    .locals 7
    .parameter "durationMillis"

    .prologue
    const-wide/16 v5, 0x0

    .line 69
    if-nez p1, :cond_0

    .line 70
    iput-wide v5, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mDuration:J

    .line 71
    new-instance v1, Ljava/lang/IllegalArgumentException;

    const-string v2, "Animation duration cannot be negative"

    invoke-direct {v1, v2}, Ljava/lang/IllegalArgumentException;-><init>(Ljava/lang/String;)V

    throw v1

    .line 73
    :cond_0
    iput-wide v5, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mDuration:J

    .line 74
    const/4 v0, 0x0

    .local v0, i:I
    :goto_0
    iget v1, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mSeg_no:I

    if-ge v0, v1, :cond_3

    .line 75
    array-length v1, p1

    if-ge v0, v1, :cond_2

    .line 76
    aget-wide v1, p1, v0

    cmp-long v1, v1, v5

    if-gez v1, :cond_1

    .line 77
    new-instance v1, Ljava/lang/IllegalArgumentException;

    const-string v2, "Animation duration cannot be negative"

    invoke-direct {v1, v2}, Ljava/lang/IllegalArgumentException;-><init>(Ljava/lang/String;)V

    throw v1

    .line 79
    :cond_1
    iget-object v1, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mDurs:[J

    aget-wide v2, p1, v0

    aput-wide v2, v1, v0

    .line 83
    :goto_1
    iget-wide v1, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mDuration:J

    iget-object v3, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mDurs:[J

    aget-wide v3, v3, v0

    add-long/2addr v1, v3

    iput-wide v1, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mDuration:J

    .line 74
    add-int/lit8 v0, v0, 0x1

    goto :goto_0

    .line 81
    :cond_2
    iget-object v1, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mDurs:[J

    aput-wide v5, v1, v0

    goto :goto_1

    .line 86
    :cond_3
    iget-wide v1, p0, Lcom/htc/weather/animations/compoundAlphaAnimation;->mDuration:J

    invoke-super {p0, v1, v2}, Landroid/view/animation/Animation;->setDuration(J)V

    .line 87
    return-void
.end method

.method public willChangeBounds()Z
    .locals 1

    .prologue
    .line 138
    const/4 v0, 0x0

    return v0
.end method

.method public willChangeTransformationMatrix()Z
    .locals 1

    .prologue
    .line 129
    const/4 v0, 0x0

    return v0
.end method


text:
exports.Box = Box;

/**
 * Abstract class that provides the basic attributes for each Box instance
 * @constructor Box
 * @param width {String|Number}
 * @param height {String|Number}
 * @param parent {HTMLElement|undefined}
 */
function Box(width, height, parent) {
    //mixin constructors
    ElementWrapper.call(this);
    ParentElementWrapper.call(this, parent);
    EventEmitter.call(this);
    BoxComponent.call(this);

    /**
     * id of the Box
     * @private
     * @type {Object}
     */
    this._id = Box.generateUniqueBoxId();

    /**
     * Optional custom name  for the box. Use the setter if you wish to use one.
     * @type {null}
     * @private
     */
    this._name = null;

    /**
     * @private
     * @type {Object}
     */
    this._children = {};

    /**
     * property for boxxer.view.View instance to serialize
     * @type {boxxer.view.ViewContainer|undefined}
     */
    this.view = undefined;

    /**
     * width of the Box
     * @type {b.render.Dimension}
     */
    this.width = new Dimension(width);

    /**
     * height of the Box
     * @type {b.render.Dimension}
     */
    this.height = new Dimension(height);

    /**
     * array of decorator names to apply after rendering
     * @private
     * @type {Array}
     */
    this._decoratorNames = [];

    /**
     * array of initialized decorators
     * @type {String}
     * @private
     */
    this._decorators = [];

    /**
     * the direction inside the Box
     * @private
     * @type {Object}
     */
    this._flowDirection = Box.FLOW_VERTICAL;

    /**
     * @private
     * @type {Boolean}
     */
    this.isRendered = false;

    //initialize Box
    this.addClass("boxxer-Box");
    this.setDataAttribute("box-id", this.getId());

    //registering Box
    Box._registry[this.getId()] = this;

    return this;
}

mix(Box, Adjustable);
mix(Box, ElementWrapper);
mix(Box, ParentElementWrapper);

mix(Box, Layout);
mix(Box, Serializer);
mix(Box, EventEmitter);
mix(Box, BoxComponent);

/**
 * adds the decorator specified to the Box instance
 * @param decoratorName {String}
 * @returns {Box}
 */
Box.prototype.addDecorator = function (decoratorName) {
    this._decoratorNames.push(decoratorName);
    return this;
};

/**
 * returns an array of decorator names registered for the Box instance
 * @returns {Array}
 */
Box.prototype.getDecoratorNames = function () {
    return this._decoratorNames;
};

/**
 * returns an array of decorators instances applied on the Box instance
 * @returns {Array}
 */
Box.prototype.getDecorators = function () {
    return this._decorators || [];
};

/**
 * return the flow direction of the box
 * @returns {Object}
 */
Box.prototype.getFlowDirection = function () {
    return this._flowDirection;
};

/**
 * Set the flow direction for the box
 * @param flowDirection {String}
 */
Box.prototype.setFlowDirection = function (flowDirection) {
    this._flowDirection = (flowDirection || Box.FLOW_VERTICAL);
    BoxComponent.reflow(this);
    return this;
};

/**
 * creates a new Dimension for width property
 * @param value {string|Number}
 */
Box.prototype.setWidthDimension = function (value) {
    this.width = new Dimension(value);
    return this;
};

/**
 * creates a new Dimension for width property
 * @param value {string|Number}
 */
Box.prototype.setHeightDimension = function (value) {
    this.height = new Dimension(value);
    return this;
};

/**
 * adds a new child to the current box instance
 * @param width {Number|String} width argument
 * @param height {Number|String} width argument
 * @param name {String} name of the new instance in the collection
 * @returns {Box}
 */
Box.prototype.addChild = function (width, height, name) {
    var box = new Box(width, height, this.getElement());
    this.addBox(box, name);
    return this;
};

/**
 * adds the given Box to the children
 * @param name {String} the child's name
 * @param box {Box} the child Box
 * @return {Box}
 */
Box.prototype.addBox = function (box, name) {
    if (!(box instanceof Box)) {
        throw new TypeError("Argument is not a Box!");
    }

    box.setParentElement(this.getElement());

    if (name) {
        this.setName(name);
    }

    this.getChildren()[box.getName() || box.getId()] = box;

    return this;
};

/**
 * Get the box custom name. Returns null if name was set.
 * @returns {null|String}
 */
Box.prototype.getName = function() {
    return this._name;
};

/**
 * Set a custom name for the Box and register it.
 * @param name {String}
 */
Box.prototype.setName = function(name) {
    if (Box._nameRegistry[name]) {
        throw "Box name already exists: " + name;
    }

    this._name = name;

    Box._nameRegistry[name] = this.getId();

    return this;
};

/**
 * returns the Box name
 * @return {String}
 */
Box.prototype.getId = function () {
    return this._id;
};

/**
 * returns a child from the BoxSet
 * @param name {String} the name of the child
 * @return {Box}
 */
Box.prototype.getChild = function (name) {
    return this.getChildren()[name];
};

/**
 * returns the children
 * @return {Object}
 */
Box.prototype.getChildren = function () {
    return this._children;
};

/**
 * returns the number of children the Box has
 * @return {Number}
 */
Box.prototype.getChildCount = function () {
    return Object.keys(this.getChildren()).length;
};

/**
 * removes a child Box
 * @param name {String} the name of the child
 */
Box.prototype.removeChild = function (name) {
    var children = this.getChildren();
    children[name].close();
    delete children[name];
    return this;
};

/**
 * Render the box and its children to the document
 */
Box.prototype.render = function (autoResize) {
    var parent = this.getParentElement();
    var boxId = parent.getAttribute("data-box-id");
    var parentBox = Box.getById(boxId);
    var eventType = EventEmitter.ON_RENDER;
    var flowDirection;

    if (parentBox instanceof Box) {
        flowDirection = parentBox.getFlowDirection();
    }

    BoxRenderer.render(this, parent, flowDirection);
    BoxComponent.render(this);

    if (this.isRendered) {
        eventType = EventEmitter.ON_UPDATE;
    } else {
        this.isRendered = true;
    }

    if (autoResize) {
        new DOMEvent(window).on("resize", function() {
            this.render();
        }.bind(this));
    }

    this.emit(eventType);

    return this;
};

/**
 * destroys and removes the Box
 */
Box.prototype.destroy = function () {
    delete Box._nameRegistry[this.getName()];
    delete Box._registry[this.getId()];
    BoxComponent.destroy(this);
    removeElement(this.getElement());
};

/**
 * @static
 * @type {Number}
 */
Box.MIN_DIMENSION = "10px";

/**
 * @static
 * @type {String}
 */
Box.FLOW_VERTICAL = "vertical";

/**
 * @static
 * @type {String}
 */
Box.FLOW_HORIZONTAL = "horizontal";

/**
 * @static
 * @type {Object}
 */
Box._registry = {};

/**
 * @static
 * @type {Object}
 */
Box._nameRegistry = {};

/**
 * static counter for Box ids
 * @static
 * @private
 * @type {Number}
 */
Box.REG_PREFIX = "bbox_";

/**
 * static counter for Box ids
 * @static
 * @private
 * @type {Number}
 */
Box._id = 0;

/**
 * static counter for zIndex
 * @static
 * @private
 * @returns {number}
 */
Box._zIndex = 666;

/**
 * @beta
 * Used by decorator to track which box is the current dropTarget
 * @type {null}
 * @private
 */
// TODO better solution?
Box.dropTarget = null;

/**
 * @beta
 * Used by decorator to track which box is the current dragTarget
 * @type {null}
 * @private
 */
// TODO better solution?
Box.dragTarget = null;

/**
 * Return the current zIndex and increase it
 * @returns {number}
 */
Box.getZIndex = function() {
    var zIndex = Box._zIndex;
    Box._zIndex++;
    return zIndex;
};

/**
 * generates a unique "box_[...]"id
 * @static
 * @return {String}
 */
Box.generateUniqueBoxId = function () {
    return Box.REG_PREFIX + Box._id++;
};

/**
 * removes a Box from the registry
 * @param id {String} id of the Box to remove
 */
Box.removeBox = function (id) {
    delete Box._registry[id];
};

/**
 * Move a box from one parent box to another
 * @param box
 * @param origin
 * @param destination
 */
Box.moveBox = function(box, origin, destination) {
    box.setParentElement(destination.getElement());
    destination.addBox(box);
    delete origin.getChildren()[box.getId()];
};

/**
 * returns a registered Box from the registry by id
 * @param id {String} the Box id
 * @return {Box}
 */
Box.getById = function (id) {
    return Box._registry[id];
};

/**
 * Returns a registered Box from the registry by name
 * @param name
 * @returns {*}
 */
Box.getByName = function(name) {
    var id = Box._nameRegistry[name];
    return id ? Box._registry[id] : null;
};

/**
 * cleans up the Box.s_oRegistry
 */
Box.clean = function () {
    Box._id = 0;
    Box._registry = {};
};

redpajama_set_name: RedPajamaGithub


text:
package org.apache.kafka.streams.state.internals;

import org.apache.kafka.common.metrics.Metrics;
import org.apache.kafka.common.serialization.Serde;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.Serializer;
import org.apache.kafka.common.utils.Bytes;
import org.apache.kafka.common.utils.LogContext;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.processor.internals.MockStreamsMetrics;
import org.apache.kafka.streams.state.KeyValueIterator;
import org.apache.kafka.test.MockProcessorContext;
import org.apache.kafka.test.NoOpRecordCollector;
import org.apache.kafka.test.TestUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

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

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertFalse;

public class ChangeLoggingKeyValueStoreTest {

    private MockProcessorContext context;
    private final InMemoryKeyValueStore<Bytes, byte[]> inner = new InMemoryKeyValueStore<>("kv", Serdes.Bytes(), Serdes.ByteArray());
    private final Serde<String> keySerde = Serdes.String();
    private final Serde<String> valueSerde = Serdes.String();
    private final ChangeLoggingKeyValueStore<String, String> store
            = new ChangeLoggingKeyValueStore<>(inner, keySerde, valueSerde);
    private final Map sent = new HashMap<>();
    private final String hi = "hi";
    private final Bytes hiBytes = Bytes.wrap(hi.getBytes());
    private final String there = "there";
    private final byte[] thereBytes = "there".getBytes();
    private final String hello = "hello";
    private final String world = "world";

    @Before
    public void before() {
        final NoOpRecordCollector collector = new NoOpRecordCollector() {
            @Override
            public <K, V> void send(final String topic,
                                    K key,
                                    V value,
                                    Integer partition,
                                    Long timestamp,
                                    Serializer<K> keySerializer,
                                    Serializer<V> valueSerializer) {
                sent.put(key, value);
            }
        };
        context = new MockProcessorContext(
            TestUtils.tempDirectory(),
            Serdes.String(),
            Serdes.Long(),
            collector,
            new ThreadCache(new LogContext("testCache "), 0, new MockStreamsMetrics(new Metrics())));
        context.setTime(0);
        store.init(context, store);
    }

    @After
    public void after() {
        context.close();
        store.close();
    }

    @Test
    public void shouldWriteKeyValueBytesToInnerStoreOnPut() {
        store.put(hi, there);
        assertThat(deserializedValueFromInner(hi), equalTo(there));
    }

    @Test
    public void shouldLogChangeOnPut() {
        store.put(hi, there);
        assertThat((byte[]) sent.get(hiBytes), equalTo(thereBytes));
    }

    @Test
    public void shouldWriteAllKeyValueToInnerStoreOnPutAll() {
        store.putAll(Arrays.asList(KeyValue.pair(hello, world),
                                   KeyValue.pair(hi, there)));
        assertThat(deserializedValueFromInner(hello), equalTo(world));
        assertThat(deserializedValueFromInner(hi), equalTo(there));
    }

    @Test
    public void shouldLogChangesOnPutAll() {
        store.putAll(Arrays.asList(KeyValue.pair(hi, there),
                                   KeyValue.pair(hello, world)));
        assertThat((byte[]) sent.get(hiBytes), equalTo(thereBytes));
        assertThat((byte[]) sent.get(Bytes.wrap(hello.getBytes())), equalTo(world.getBytes()));
    }

    @Test
    public void shouldPutNullOnDelete() {
        store.put(hi, there);
        store.delete(hi);
        assertThat(inner.get(hiBytes), nullValue());
    }

    @Test
    public void shouldReturnOldValueOnDelete() {
        store.put(hi, there);
        assertThat(store.delete(hi), equalTo(there));
    }

    @Test
    public void shouldReturnNullOnDeleteIfNoOldValue() {
        assertThat(store.delete(hi), is(nullValue()));
    }

    @Test
    public void shouldLogKeyNullOnDelete() {
        store.put(hi, there);
        store.delete(hi);
        assertThat(sent.get(hi), nullValue());
    }

    @Test
    public void shouldWriteToInnerOnPutIfAbsentNoPreviousValue() {
        store.putIfAbsent(hi, there);
        assertThat(inner.get(hiBytes), equalTo(thereBytes));
    }

    @Test
    public void shouldNotWriteToInnerOnPutIfAbsentWhenValueForKeyExists() {
        store.put(hi, there);
        store.putIfAbsent(hi, world);
        assertThat(inner.get(hiBytes), equalTo(thereBytes));
    }

    @Test
    public void shouldWriteToChangelogOnPutIfAbsentWhenNoPreviousValue() {
        store.putIfAbsent(hi, there);
        assertThat((byte[]) sent.get(hiBytes), equalTo(thereBytes));
    }

    @Test
    public void shouldNotWriteToChangeLogOnPutIfAbsentWhenValueForKeyExists() {
        store.put(hi, there);
        store.putIfAbsent(hi, world);
        assertThat((byte[]) sent.get(hiBytes), equalTo(thereBytes));
    }

    @Test
    public void shouldReturnCurrentValueOnPutIfAbsent() {
        store.put(hi, there);
        assertThat(store.putIfAbsent(hi, world), equalTo(there));
    }

    @Test
    public void shouldReturnNullOnPutIfAbsentWhenNoPreviousValue() {
        assertThat(store.putIfAbsent(hi, there), is(nullValue()));
    }

    @Test
    public void shouldQueryRange() {
        store.put(hello, world);
        store.put(hi, there);
        store.put("zooom", "home");
        final KeyValueIterator<String, String> range = store.range(hello, hi);
        assertThat(range.next(), equalTo(KeyValue.pair(hello, world)));
        assertThat(range.next(), equalTo(KeyValue.pair(hi, there)));
        assertFalse(range.hasNext());
    }

    @Test
    public void shouldReturnAllKeyValues() {
        store.put(hello, world);
        store.put(hi, there);
        final String zooom = "zooom";
        final String home = "home";
        store.put(zooom, home);
        final KeyValueIterator<String, String> all = store.all();
        assertThat(all.next(), equalTo(KeyValue.pair(hello, world)));
        assertThat(all.next(), equalTo(KeyValue.pair(hi, there)));
        assertThat(all.next(), equalTo(KeyValue.pair(zooom, home)));
        assertFalse(all.hasNext());
    }

    @Test
    public void shouldReturnValueOnGetWhenExists() {
        store.put(hello, world);
        assertThat(store.get(hello), equalTo(world));
    }

    @Test
    public void shouldReturnNullOnGetWhenDoesntExist() {
        assertThat(store.get(hello), is(nullValue()));
    }

    @Test
    public void shouldReturnInnerStoreName() {
        assertThat(store.name(), equalTo("kv"));
    }

    private String deserializedValueFromInner(final String key) {
        return valueSerde.deserializer().deserialize("blah", inner.get(Bytes.wrap(key.getBytes())));
    }
}


text:
layout: post
subheadline: "Support"
title: "A Year in Review: Annual Moore Progress Report"
teaser: ""
header:
  image_fullwidth: "light-blue-wood-texture.jpg"
categories:
  - blog
comments: true
show_meta: true
tags: ["Grants", "Funding", "Reports"]
authors: ["Tracy Teal"]
redirect_from: /blog/moore-report/
---

A year ago we were fortunate enough to receive a grant from the
[Gordon and Betty Moore Foundation](https://www.moore.org/article-detail?newsUrlName=the-gordon-and-betty-moore-foundation-selects-awardees-for-$21-million-in-grants-to-stimulate-data-driven-discovery)
Data-Driven Discovery initiative to support Data Carpentry to develop and deliver data skills training to researchers in the life and
physical sciences. [See our original proposal here.](https://figshare.com/articles/Data_Carpentry_Moore_Foundation_Grant_Proposal/1507552)
Thanks to the Moore Foundation, this support has allowed us as a community to run more workshops, develop new materials,
develop infrastructure and advocate for the importance of data skills training for more effective and reproducible research.

The work of the community has made this possible and we wanted to share our Moore annual report to highlight all the work that has been done in the last year!

- [Annual Report](https://github.com/datacarpentry/practices/blob/datacarpentry/datacarpentry/Moore_DataCarpentry_progress_report.pdf)
- [Output and Events - Excel file](https://github.com/datacarpentry/practices/blob/datacarpentry/datacarpentry/Data-Carpentry_Practices-Data-Collection.xlsx?raw=true)

### Some highlights from the last year

#### Workshops

- Since August, 2015 we have run 93 workshops in ten countries, serving approximately 1,700 learners
- We have over 600 completed surveys that show the demographics of our audience as well as workshop outcomes.
Workshop attendees are primarily graduate students (31%), but there is also research staff (25%) and postdoctoral researchers
(12%) and PIs (12%). Workshop attendees were primarily from the life sciences (45%), with other (21%) and social sciences and
library sciences (9%).
- Over 50% of learners were new to programming having never programmed or less than once per year.
- The vast majority (>90%) of those responding to our post-workshop survey say that participating in the
workshop was worth their time and led to improvements in their data management and data analysis skills.
- Gender balance in USA workshops (where demographic data is collected) was 51% female and 47% male.
- In the USA we are primarily reaching Caucasian (63%) and Asian/Pacific Islander (18%) participants. Black or African American
(3%), Hispanic (6%) and American or Alaskan Native (0.2%) are under-represented.

#### Instructors
- With Software Carpentry we have run over 30 instructor training events.
- We have over 350 officially badged Data Carpentry instructors.
- With Software Carpentry we were involved in forming a [Mentoring Subcommittee](http://software-carpentry.org/join/subcom/mentoring/)
who have developed and run [discussion sessions](http://pad.software-carpentry.org/instructor-discussion)

#### Curriculum
- With [CyVerse](http://www.cyverse.org/) and [SESYNC](https://www.sesync.org/) we developed a
[Genomics Data Carpentry](http://www.datacarpentry.org/genomics-workshop/) workshop, with a grant from Amazon AWS for cloud computing
resources
- With [NEON](http://www.neonscience.org/) we developed Geospatial Data Carpentry lessons on
[working with raster data](http://neondataskills.org/tutorial-series/raster-data-series/) and
[vector data](http://neondataskills.org/tutorial-series/vector-data-series/).

#### Strategic Planning, Sustainability, Communication and Advocacy
- Hired a Program Coordinator, [Associate Director](http://www.datacarpentry.org/blog/new-associate-director/)
and [Deputy Director of Assessment](http://www.datacarpentry.org/blog/new-assessment-director/).
- Developed a [Lesson Development Roadmap](http://www.datacarpentry.org/lessons-incubation/) to guide the development
of new curriculum
- Started a joint [Partnership](http://www.datacarpentry.org/partnerships/) program with Software Carpentry.
- Developed criteria for [requirements for Data Carpentry workshops](http://www.datacarpentry.org/workshops-host/) and
[Self-Organised](http://www.datacarpentry.org/self-organized-workshops/) workshops.
- Gave [presentations and wrote papers](https://www.zotero.org/groups/datacarpentry) on Data Carpentry and data skills for more
effective and reproducible research.

In year one the focus was on building the foundation to scale to run more workshops and train instructors, develop materials in new domains,
maintain existing lessons and support our instructor community. We also are working to establish Data Carpentry with Software Carpentry
as sustainable organizations. We'll continue these activities in year two and and also work on scaling to reach and engage with more learners and instructors throughout
the world!

As always, great thanks to all the volunteers who make all this work possible!


text:
Applying Database Migrations in Production on Kubernetes
########################################################

Unlike regular application code changes, database schema migrations in production require actual downtime.
We haven't built infrastructure to seamlessly switch between schemas in production.

Prerequisites
=============

- This procedure should only be followed for application updates that change DB schema and have an Alembic migration.
  See :doc:`dev-migrations` for information about creating migrations with Alembic.
- A new docker image with the DB change should be pushed to Docker Hub.
- Check if additional steps are needed to apply the migration, such as seeding new data into the DB.

Procedure
=========

1. Bring the deployment down:

   .. code-block:: bash

      kubectl delete deployment keeper-deployment

   Watch for the pods to be deleted with ``kubectl get pods``.

2. Deploy the maintenance pod.

   First update :file:`keeper-mgmt-pod.yaml` with the new uWSGI container's ``image`` name.
   Look for the lines:

   .. code-block:: yaml

      - name: uwsgi
        image: "lsstsqre/ltd-keeper:latest"  # update this

   Then deploy the pod:

   .. code-block:: yaml

      kubectl create -f keeper-mgmt-pod.yaml

3. Log into the maintenance pod and apply the migration:

   .. code-block:: bash

      kubectl exec keeper-mgmt -c uwsgi -i -t /bin/bash

   To apply the migration:

   .. code-block:: bash

      FLASK_APP=keeper flask db upgrade

   When the upgrade is complete, log out of the management pod's shell:

   .. code-block:: bash

      exit

4. Delete the management pod:

   .. code-block:: bash

      kubectl delete pod keeper-mgmt

5. Deploy the application.

   First update the uWSGI container's ``image`` name in :file:`keeper-deployment.yaml` to match the one used by the maintenance pod, and deploy it:

   .. code-block:: bash

      kubectl apply -f keeper-deployment.yaml

.. _gke-migrations-troubleshooting:

Troubleshooting
===============

Unexpected branched state
-------------------------

It's possible for Alembic to get into an unexpected branching state, producing an error message during a ``flask db upgrade`` like::

   alembic.util.exc.CommandError: Requested revision 1ba709663f26 overlaps with other requested revisions 0c0c70d73d4b

The ``flask db heads``, ``flask db branches``, and ``flask db current`` commands will show a normal, linear version history.
A true validation is to inspect the ``alembic_version`` table in the database.

Following :ref:`gke-cloudsql-connect`, log into the database and show the ``alembic_version`` table:

.. code-block:: sql

   use keeper;
   select * from alembic_version;

If more than one version row is present, then the table can be easily reset.
First, drop the ``alembic_version`` table:

.. code-block:: sql

   drop table alembic_version;

Then in the management pod, stamp the database version:

.. code-block:: bash

   FLASK_APP=keeper flask db stamp $VERSION

``$VERSION`` is the ID of the known current migration.
This creates a new ``alembic_version`` table with a single row specifying the current version.
Now the database upgrade can be retried.


text:
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Kamer extends CI_Controller {

    /**
     * Kamer controller
     * Verzorgt communicatie tussen model en view
     */
    public function __construct() {
        /**
         * standaard controller constructor
         * laadt helpers
         */
        parent::__construct();
        $this->load->helper('form');
        $this->load->helper('notation');
    }

    public function index() {
        /**
         * Laadt de pagina waarop je kamers kan beheren
         * geeft een array van kamer objecten mee
         */
        $data['title'] = 'Kamers beheren';
        $data['author'] = 'Laenen Nathalie';
        $data['user'] = $this->authex->getUserInfo();
        $user = $this->authex->getUserInfo();
        if ($user->soort == 3) {
            $this->load->model('kamer_model');
            $data['kamers'] = $this->kamer_model->getAll();

            $partials = array('navbar' => 'main_navbar', 'content' => 'admin/kamer/kamer_beheren', 'footer' => 'main_footer');
            $this->template->load('main_master', $partials, $data);
        } else {
            redirect("/home/index");
        }
    }

    public function haalKamer() {
        /**
         * Haalt een kamer object en alle kamertypes op
         */
        $kamerId = $this->input->get('kamerId');
        if ($kamerId < 0) {
            $data['kamer'] = $this->getEmptyKamer();
        } else {
            $this->load->model('kamer_model');
            $data['kamer'] = $this->kamer_model->getWithKamerType($kamerId);
        }
        $this->load->model('kamerType_model');
        $data['kamerTypes'] = $this->kamerType_model->getall();

        $this->load->view("admin/kamer/ajax_kamer", $data);
    }

    public function verwijderKamer() {
        /**
         * Verwijdert een kamer object als hieraan geen boekingen verbonden zijn
         */
        $id = $this->input->get('id');
        $this->load->model('kamerBoeking_model');
        $result = $this->kamerBoeking_model->getAllByKamer($id);
        $size = count($result);
        if ($size == 0) {
            $this->load->model('kamer_model');
            $this->kamer_model->delete($id);
            echo 0;
        } else {
            echo 1;
        }
    }

    function getEmptyKamer() {
        /**
         * Creërt een leeg kamer object
         * \return kamer een leeg kamer object
         */
        $kamer = new stdClass();

        $kamer->id = '0';
        $kamer->naam = '';
        $kamer->aantalPersonen = '';
        $kamer->kamerTypeId = '1';
        $kamer->beschikbaar = '0';

        return $kamer;
    }

    public function schrijfKamer() {
        /**
         * Haalt de waarden van het kamer object op en update of insert deze in de database
         */
        $object = new stdClass();
        $object->id = $this->input->post('id');
        $object->naam = ucfirst(strtolower($this->input->post('naam')));
        $object->aantalPersonen = $this->input->post('aantalPersonen');
        $object->kamerTypeId = $this->input->post('kamerType');
        $object->beschikbaar = $this->input->post('beschikbaar');

        $this->load->model('kamer_model');
        if ($object->id == 0) {
            $this->kamer_model->insert($object);
        } else {
            $this->kamer_model->update($object);
        }
        redirect('kamer/index');
    }

}


text:
#import "ObjcGeneratedModelDemoViewController.h"

#import <IGListKit/IGListKit.h>

#import "PersonModel.h"
#import "PersonSectionController.h"

@interface ObjcGeneratedModelDemoViewController () <IGListAdapterDataSource>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) IGListAdapter *adapter;
@property (nonatomic, strong) NSArray<PersonModel *> *persons;

@end

@implementation ObjcGeneratedModelDemoViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.persons = @[[[PersonModel alloc] initWithFirstName:@"Ryan" lastName:@"Nystrom" uniqueId:@"1"],
                     [[PersonModel alloc] initWithFirstName:@"Jesse" lastName:@"Squires" uniqueId:@"2"],
                     [[PersonModel alloc] initWithFirstName:@"Markus" lastName:@"Emrich" uniqueId:@"3"],
                     [[PersonModel alloc] initWithFirstName:@"James" lastName:@"Sherlock" uniqueId:@"4"],
                     [[PersonModel alloc] initWithFirstName:@"Bofei" lastName:@"Zhu" uniqueId:@"5"],
                     [[PersonModel alloc] initWithFirstName:@"Valeriy" lastName:@"Van" uniqueId:@"6"],
                     [[PersonModel alloc] initWithFirstName:@"Hesham" lastName:@"Salman" uniqueId:@"7"],
                     [[PersonModel alloc] initWithFirstName:@"Bas" lastName:@"Broek" uniqueId:@"8"],
                     [[PersonModel alloc] initWithFirstName:@"Andrew" lastName:@"Monshizadeh" uniqueId:@"9"],
                     [[PersonModel alloc] initWithFirstName:@"Adlai" lastName:@"Holler" uniqueId:@"10"],
                     [[PersonModel alloc] initWithFirstName:@"Ben" lastName:@"Asher" uniqueId:@"11"],
                     [[PersonModel alloc] initWithFirstName:@"Jake" lastName:@"Lin" uniqueId:@"12"],
                     [[PersonModel alloc] initWithFirstName:@"Jeff" lastName:@"Bailey" uniqueId:@"13"],
                     [[PersonModel alloc] initWithFirstName:@"Daniel" lastName:@"Alamo" uniqueId:@"14"],
                     [[PersonModel alloc] initWithFirstName:@"Viktor" lastName:@"Gardart" uniqueId:@"15"],
                     [[PersonModel alloc] initWithFirstName:@"Anton" lastName:@"Sotkov" uniqueId:@"16"],
                     [[PersonModel alloc] initWithFirstName:@"Guilherme" lastName:@"Rambo" uniqueId:@"17"],
                     [[PersonModel alloc] initWithFirstName:@"Rizwan" lastName:@"Ibrahim" uniqueId:@"18"],
                     [[PersonModel alloc] initWithFirstName:@"Ayush" lastName:@"Saraswat" uniqueId:@"19"],
                     [[PersonModel alloc] initWithFirstName:@"Dustin" lastName:@"Shahidehpour" uniqueId:@"20"],
                     ];

    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero
                                             collectionViewLayout:[UICollectionViewFlowLayout new]];
    [self.view addSubview:self.collectionView];
    self.adapter = [[IGListAdapter alloc] initWithUpdater:[[IGListAdapterUpdater alloc] init]
                                           viewController:self];

    self.adapter.collectionView = self.collectionView;
    self.adapter.dataSource = self;
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.collectionView.frame = self.view.bounds;
}

#pragma mark - IGListAdapterDataSource

- (NSArray<id<IGListDiffable>> *)objectsForListAdapter:(IGListAdapter *)listAdapter {
    return self.persons;
}

- (IGListSectionController *)listAdapter:(IGListAdapter *)listAdapter sectionControllerForObject:(id)object {
    return [PersonSectionController new];
}

- (UIView *)emptyViewForListAdapter:(IGListAdapter *)listAdapter {
    return nil;
}

@end


text:
package org.apache.geode.experimental.driver;

import java.io.IOException;
import java.util.List;

/**
 * This interface represents from the client-side the execution of a query on the server-side.
 *
 * @param <T> Type of result returned from the query. May differ from the key and value types
 *        of any involved regions.
 */
public interface Query<T> {
  /**
   * Executes this query with the specified parameters.
   *
   * @param bindParameters Optional list of bind parameters.
   * @return Possibly empty list of results from the query.
   * @throws IOException If an error occurred communicating with the distributed system.
   */
  List<T> execute(Object... bindParameters) throws IOException;
}


text:
require 'work_dir/base'

module WorkDir
  # A static website
  class Phantom < Base
    def capture_screenshot(url)
      return unless phantomjs?
      working_dir do
        script_path = File.expand_path('../screenshot.js', __FILE__).to_s
        phantomjs script_path, url
      end
    end

    # Is phantomJS installed?
    def phantomjs?
      cmd 'which', 'phantomjs'
      return true
    rescue
      return false
    end

    private

    def phantomjs(*args)
      cmd(*['phantomjs'] + args)
    end
  end
end


text:
@interface WebViewController : UIViewController

@property (nonatomic) NSURLRequest *request;

@property (nonatomic, readonly) UIWebView *webView;

@end


text:
package net.ros.common.steam;

public class CreativeSteamTank extends SteamTank
{
    public CreativeSteamTank()
    {
        super(100_000, 1);
        this.setSteam(100_000);
    }

    @Override
    public int drainSteam(final int amount, final boolean doDrain)
    {
        return amount;
    }

    @Override
    public int fillSteam(final int amount, final boolean doFill)
    {
        return 0;
    }
}


text:
import { ICorpse } from "creature/corpse/ICorpse";
import { ICreature } from "creature/ICreature";
import { IDoodad } from "doodad/IDoodad";
import { DoodadType, GrowingStage, IModdable, IRGB, ItemQuality, OverlayType, SfxType, SkillType, TerrainType } from "Enums";
import { IContainer } from "item/IItem";
import { INPC } from "npc/INPC";
import { ITileEvent } from "tile/ITileEvent";
import { IVector3 } from "utilities/math/IVector";
export interface ITerrainDescription extends IModdable {
    passable?: boolean;
    particles: IRGB;
    durability?: number;
    water?: boolean;
    regathered?: boolean;
    shallowWater?: boolean;
    freshWater?: boolean;
    gather?: boolean;
    noGfxSwitch?: boolean;
    noLos?: boolean;
    flammable?: boolean;
    gatherSkillUse?: SkillType;
    sound?: SfxType;
    leftOver?: TerrainType;
    baseTerrain?: TerrainType;
    terrainType?: TerrainType;
    doodad?: DoodadType;
    isMountain?: boolean;
    background?: TerrainType;
    noBackground?: boolean;
    isOre?: boolean;
    animated?: boolean;
    tillable?: boolean;
    hasMound?: boolean;
    deepWater?: boolean;
    reduceRest?: boolean;
    noResting?: boolean;
    wet?: boolean;
    tileOnConsume?: TerrainType;
}
export interface ITile extends Partial<ITileContainer> {
    corpses?: ICorpse[];
    creature?: ICreature;
    data: number;
    doodad?: IDoodad;
    events?: ITileEvent[];
    npc?: INPC;
    overlays?: IOverlayInfo[];
}
export interface ITileOld {
    event?: ITileEvent[];
}
export interface ITileArray {
    [index: number]: ITile;
}
export declare type ITileContainer = IContainer & IVector3;
export interface ITileData {
    type: TerrainType;
    minDur?: number;
    maxDur?: number;
    quality?: ItemQuality;
    gfx?: number;
    tilled?: boolean;
    step?: number;
}
export declare type ITileDataOld = Partial<ITileData> & {
    strength?: number;
};
export declare enum TileTemplateType {
    House = 0,
    Pond = 1,
    CavePond = 2,
    Desert = 3,
    Beach = 4,
    Boat = 5,
    Lava = 6
}
export interface ITemplate {
    terrainTypes: {
        [id: string]: TerrainType;
    };
    terrain: string[];
    doodadTypes?: {
        [id: string]: DoodadType | ITemplateDoodad;
    };
    doodad?: string[];
    tilled?: boolean;
    /**
     * A decimal value, 0 for no degradation, 1 for 100% degradation (basically as if there was no template)
     */
    degrade: number;
}
export interface ITemplateDoodad {
    type: DoodadType;
    growingStages: GrowingStage[];
}
export interface IOverlayInfo {
    type: OverlayType;
    size?: number;
    offsetX?: number;
    offsetY?: number;
    spriteOffsetX?: number;
    spriteOffsetY?: number;
    red?: number;
    green?: number;
    blue?: number;
    alpha?: number;
}


text:
FROM gcr.io/google_containers/nginx-slim:0.14

RUN DEBIAN_FRONTEND=noninteractive apt-get update && apt-get install -y \
  diffutils \
  --no-install-recommends \
  && rm -rf /var/lib/apt/lists/*

COPY . /

# https://blog.phusion.nl/2015/01/20/docker-and-the-pid-1-zombie-reaping-problem
RUN curl -sSL -o /sbin/dumb-init https://github.com/Yelp/dumb-init/releases/download/v1.2.0/dumb-init_1.2.0_amd64 && \
  chmod +x /sbin/dumb-init

ENTRYPOINT ["/sbin/dumb-init", "--"]

CMD ["/nginx-ingress-controller"]


text:
layout: post
comments: true
title: 'Review: Kung Fu Samurai on Giant Robot Island'
date: 2008-12-29 21:02:30 -07:00
categories:
- leisure
- tabletop
tags:
- B-movie
- cards
- games
- giant robot
- island
- kung fu
- review
- samurai

---
![Kung Fu Samurai on Giant Robot Island](/assets/kung-fu-samurai.jpeg)

[Kung Fu Samurai on Giant Robot Island](http://www.amazon.com/gp/product/B000JETGRU)
is a member of a family of card games by Z-Man Games, in which players play B movie producers whose competing versions of a movie battle it out to the death.

Each card in the deck has a buzz word from the genre. At the beginning of the game, players pick six cards and use as many of those words to form the title of the movie as possible. Ours was "Shaolin Ninja Black vs. Little Eagle Commando". Just the title of our movie gives you an idea what this game is like.

Players amass Character, Location, and Prop cards, which all have defense ratings. Players play Creature cards to attack other movies, and can replace Locations in other movies to spice things up. Another kind of card, the Special Effects card, change the balance of the game. Mayhem continues until someone plays the "Roll the Credits" card and ends the game.

The game is best enjoyed when one plays the cards as though they were narrating the movie. The results can be hilarious! I'd recommend their games. For added fun, you can mix the decks from their B-Movie games for a crossover catastrophe.


text:
package com.consol.citrus.dsl.junit;

import com.consol.citrus.Citrus;
import com.consol.citrus.TestCase;
import com.consol.citrus.annotations.CitrusAnnotations;
import com.consol.citrus.context.TestContext;
import com.consol.citrus.dsl.design.DefaultTestDesigner;
import com.consol.citrus.dsl.design.TestDesigner;
import com.consol.citrus.dsl.runner.DefaultTestRunner;
import com.consol.citrus.dsl.runner.TestRunner;
import com.consol.citrus.exceptions.CitrusRuntimeException;
import com.consol.citrus.junit.AbstractJUnit4CitrusTest;
import com.consol.citrus.junit.CitrusJUnit4Runner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;

/**
 * @author Christoph Deppisch
 * @since 2.5
 */
public class JUnit4CitrusTest extends AbstractJUnit4CitrusTest {
    /** Logger */
    protected final Logger log = LoggerFactory.getLogger(getClass());

    private static final String DESIGNER_ATTRIBUTE = "designer";
    private static final String RUNNER_ATTRIBUTE = "runner";

    @Override
    protected void run(CitrusJUnit4Runner.CitrusFrameworkMethod frameworkMethod) {
        TestDesigner testDesigner = null;
        TestRunner testRunner = null;

        try {
            if (citrus == null) {
                citrus = Citrus.newInstance(applicationContext);
            }

            TestContext ctx = prepareTestContext(citrus.createTestContext());

            if (isDesignerMethod(frameworkMethod.getMethod())) {
                testDesigner = createTestDesigner(frameworkMethod, ctx);
            } else if (isRunnerMethod(frameworkMethod.getMethod())) {
                testRunner = createTestRunner(frameworkMethod, ctx);
            } else {
                throw new CitrusRuntimeException("Missing designer or runner method parameter");
            }

            TestCase testCase = testDesigner != null ? testDesigner.getTestCase() : testRunner.getTestCase();

            CitrusAnnotations.injectAll(this, citrus, ctx);

            invokeTestMethod(frameworkMethod, testCase, ctx);
        } finally {
            if (testRunner != null) {
                testRunner.stop();
            }
        }
    }

    /**
     * Invokes test method based on designer or runner environment.
     * @param frameworkMethod
     * @param testCase
     * @param context
     */
    protected void invokeTestMethod(CitrusJUnit4Runner.CitrusFrameworkMethod frameworkMethod, TestCase testCase, TestContext context) {
        if (frameworkMethod.getAttribute(DESIGNER_ATTRIBUTE) != null) {
            ReflectionUtils.invokeMethod(frameworkMethod.getMethod(), this,
                    resolveParameter(frameworkMethod, testCase, context));

            citrus.run(testCase, context);
        } else if (frameworkMethod.getAttribute(RUNNER_ATTRIBUTE) != null) {
            TestRunner testRunner = (TestRunner) frameworkMethod.getAttribute(RUNNER_ATTRIBUTE);

            Object[] params = resolveParameter(frameworkMethod, testCase, context);
            testRunner.start();
            ReflectionUtils.invokeMethod(frameworkMethod.getMethod(), this, params);
        }
    }

    @Override
    protected Object resolveAnnotatedResource(CitrusJUnit4Runner.CitrusFrameworkMethod frameworkMethod, Class<?> parameterType, TestContext context) {
        if (TestDesigner.class.isAssignableFrom(parameterType)) {
            return frameworkMethod.getAttribute(DESIGNER_ATTRIBUTE);
        } else if (TestRunner.class.isAssignableFrom(parameterType)) {
            return frameworkMethod.getAttribute(RUNNER_ATTRIBUTE);
        }

        return super.resolveAnnotatedResource(frameworkMethod, parameterType, context);
    }

    /**
     * Creates new test designer instance for this test method.
     * @param frameworkMethod
     * @param context
     * @return
     */
    protected TestDesigner createTestDesigner(CitrusJUnit4Runner.CitrusFrameworkMethod frameworkMethod, TestContext context) {
        TestDesigner testDesigner = new DefaultTestDesigner(applicationContext, context);
        testDesigner.testClass(getClass());
        testDesigner.name(frameworkMethod.getTestName());
        testDesigner.packageName(frameworkMethod.getPackageName());

        frameworkMethod.setAttribute(DESIGNER_ATTRIBUTE, testDesigner);

        return testDesigner;
    }

    /**
     * Creates new test runner instance for this test method.
     * @param frameworkMethod
     * @param context
     * @return
     */
    protected TestRunner createTestRunner(CitrusJUnit4Runner.CitrusFrameworkMethod frameworkMethod, TestContext context) {
        TestRunner testRunner = new DefaultTestRunner(applicationContext, context);
        testRunner.testClass(getClass());
        testRunner.name(frameworkMethod.getTestName());
        testRunner.packageName(frameworkMethod.getPackageName());

        frameworkMethod.setAttribute(RUNNER_ATTRIBUTE, testRunner);

        return testRunner;
    }

    /**
     * Searches for method parameter of type test designer.
     * @param method
     * @return
     */
    protected boolean isDesignerMethod(Method method) {
        Class<?>[] parameterTypes = method.getParameterTypes();

        for (Class<?> parameterType : parameterTypes) {
            if (parameterType.isAssignableFrom(TestDesigner.class)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Searches for method parameter of type test runner.
     * @param method
     * @return
     */
    protected boolean isRunnerMethod(Method method) {
        Class<?>[] parameterTypes = method.getParameterTypes();

        for (Class<?> parameterType : parameterTypes) {
            if (parameterType.isAssignableFrom(TestRunner.class)) {
                return true;
            }
        }

        return false;
    }
}


text:
package com.vs.gofrodemoapp.model.forcastPojo;

import com.vs.gofrodemoapp.model.Coord;

/**
 * Created by Naveen on 26-08-2016.
 */
public class City
{
    private Coord coord;

    private String id;

    private Sys sys;

    private String name;

    private String population;

    private String country;

    public Coord getCoord ()
    {
        return coord;
    }

    public void setCoord (Coord coord)
    {
        this.coord = coord;
    }

    public String getId ()
    {
        return id;
    }

    public void setId (String id)
    {
        this.id = id;
    }

    public Sys getSys ()
    {
        return sys;
    }

    public void setSys (Sys sys)
    {
        this.sys = sys;
    }

    public String getName ()
    {
        return name;
    }

    public void setName (String name)
    {
        this.name = name;
    }

    public String getPopulation ()
    {
        return population;
    }

    public void setPopulation (String population)
    {
        this.population = population;
    }

    public String getCountry ()
    {
        return country;
    }

    public void setCountry (String country)
    {
        this.country = country;
    }

    @Override
    public String toString()
    {
        return "ClassPojo [coord = "+coord+", id = "+id+", sys = "+sys+", name = "+name+", population = "+population+", country = "+country+"]";
    }
}


text:
from zeit.cms.i18n import MessageFactory as _
import grokcore.component as grok
import logging
import zeit.cms.browser.interfaces
import zeit.cms.browser.menu
import zeit.cms.checkout.interfaces
import zeit.cms.content.interfaces
import zeit.cms.interfaces
import zeit.cms.repository.browser.delete
import zeit.cms.repository.interfaces
import zeit.cms.workingcopy.interfaces
import zope.cachedescriptors.property
import zope.component
import zope.viewlet.viewlet

log = logging.getLogger(__name__)

class Sidebar(zope.viewlet.viewlet.ViewletBase):
    """view class for navtree"""

    @property
    def workingcopy(self):
        return zeit.cms.workingcopy.interfaces.IWorkingcopy(
            self.request.principal)

    @zope.cachedescriptors.property.Lazy
    def content(self):
        result = []
        for obj in self.workingcopy.values():
            list_repr = zope.component.queryMultiAdapter(
                (obj, self.request),
                zeit.cms.browser.interfaces.IListRepresentation)
            if list_repr is None:
                log.warning("Could not adapt %r to IListRepresentation",
                            (obj, ))
                continue
            css_class = []
            if list_repr.type:
                css_class.append('type-' + list_repr.type)
            if zeit.cms.clipboard.interfaces.IObjectReference.providedBy(obj):
                css_class.append('reference')
            result.append(dict(
                css_class=' '.join(css_class),
                obj=obj,
                title=list_repr.title or list_repr.__name__,
                uniqueId=list_repr.uniqueId,
                url=list_repr.url,
            ))
        return result

@zope.component.adapter(
    zeit.cms.workingcopy.interfaces.ILocalContent,
    zeit.cms.content.interfaces.ICMSContentSource)
@zope.interface.implementer(
    zeit.cms.browser.interfaces.IDefaultBrowsingLocation)
def localcontent_default_browsing_location(context, schema):
    repository = zope.component.getUtility(
        zeit.cms.repository.interfaces.IRepository)

    # Get the object in the repository, potentially looking for the parent.
    object_in_repository = None
    unique_id = context.uniqueId
    while object_in_repository is None:
        try:
            object_in_repository = repository.getContent(unique_id)
        except KeyError:
            unique_id = unique_id.rsplit('/', 1)[0]

            # This is edge case number something-or-other. Steps to reproduce:
            # - create an object in the repository root folder
            # - check it out
            # - delete the object from the repository
            if unique_id + '/' == zeit.cms.interfaces.ID_NAMESPACE:
                object_in_repository = repository
        else:
            break

    return zope.component.queryMultiAdapter(
        (object_in_repository, schema),
        zeit.cms.browser.interfaces.IDefaultBrowsingLocation)

@grok.adapter(zeit.cms.workingcopy.interfaces.IWorkingcopyLocation)
@grok.implementer(zeit.cms.browser.interfaces.IAdditionalLayer)
def layer_for_workingcopy(context):
    return zeit.cms.browser.interfaces.IWorkingcopyLayer

class DeleteFromWorkingcopy(zeit.cms.repository.browser.delete.DeleteContent):

    def next_url(self, folder):
        unique_id = self.context.uniqueId
        target = None
        while target is None:
            target = zeit.cms.interfaces.ICMSContent(unique_id, None)
            unique_id = unique_id.rsplit('/', 1)[0]
            if unique_id + '/' == zeit.cms.interfaces.ID_NAMESPACE:
                break
        if target is None:
            target = folder
        return self.url(target)

    def _delete(self):
        zeit.cms.checkout.interfaces.ICheckinManager(self.context).delete()

class DeleteMenuItem(zeit.cms.browser.menu.LightboxActionMenuItem):
    """Delete menu item."""

    title = _('Cancel workingcopy')


text:
<?xml version="1.0" encoding="utf-8"?>
<openerp>
     <data>
        <!-- TODO:REMOVE this wizard is not used  -->
        <record id="account_payment_make_payment_view" model="ir.ui.view">
             <field name="name">account.payment.make.payment.form</field>
             <field name="model">account.payment.make.payment</field>
             <field name="arch" type="xml">
                <form string="Make Payment" version="7.0">
                    <separator string="Are you sure you want to make payment?"/>
                    <footer>
                        <button name="launch_wizard" string="Yes" type="object" default_focus="1" class="oe_highlight"/>
                        or
                        <button string="Cancel" class="oe_link" special="cancel"/>
                    </footer>
                </form>
            </field>
        </record>

        <record id="action_account_payment_make_payment" model="ir.actions.act_window">
            <field name="name">Make Payment</field>
            <field name="type">ir.actions.act_window</field>
            <field name="res_model">account.payment.make.payment</field>
            <field name="view_type">form</field>
            <field name="view_mode">form</field>
            <field name="view_id" ref="account_payment_make_payment_view"/>
            <field name="target">new</field>
        </record>

    </data>
</openerp>


text:
package com.yahoo.ycsb.db.solr;

import com.yahoo.ycsb.ByteIterator;
import com.yahoo.ycsb.DB;
import com.yahoo.ycsb.Status;
import com.yahoo.ycsb.StringByteIterator;
import com.yahoo.ycsb.workloads.CoreWorkload;
import org.apache.solr.client.solrj.embedded.JettyConfig;
import org.apache.solr.cloud.MiniSolrCloudCluster;
import org.apache.solr.common.util.NamedList;
import org.junit.*;

import java.io.File;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Properties;
import java.util.Set;
import java.util.Vector;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

public abstract class SolrClientBaseTest {

  protected static MiniSolrCloudCluster miniSolrCloudCluster;
  private DB instance;
  private final static HashMap<String, ByteIterator> MOCK_DATA;
  protected final static String MOCK_TABLE = "ycsb";
  private final static String MOCK_KEY0 = "0";
  private final static String MOCK_KEY1 = "1";
  private final static int NUM_RECORDS = 10;
  private final static String FIELD_PREFIX = CoreWorkload.FIELD_NAME_PREFIX_DEFAULT;

  static {
    MOCK_DATA = new HashMap<>(NUM_RECORDS);
    for (int i = 0; i < NUM_RECORDS; i++) {
      MOCK_DATA.put(FIELD_PREFIX + i, new StringByteIterator("value" + i));
    }
  }

  @BeforeClass
  public static void onlyOnce() throws Exception {
    Path miniSolrCloudClusterTempDirectory = Files.createTempDirectory("miniSolrCloudCluster");
    miniSolrCloudClusterTempDirectory.toFile().deleteOnExit();
    miniSolrCloudCluster = new MiniSolrCloudCluster(1, miniSolrCloudClusterTempDirectory, JettyConfig.builder().build());

    // Upload Solr configuration
    URL configDir = SolrClientBaseTest.class.getClassLoader().getResource("solr_config");
    assertNotNull(configDir);
    miniSolrCloudCluster.uploadConfigDir(new File(configDir.toURI()), MOCK_TABLE);
  }

  @AfterClass
  public static void destroy() throws Exception {
    if(miniSolrCloudCluster != null) {
      miniSolrCloudCluster.shutdown();
    }
  }

  @Before
  public void setup() throws Exception {
    NamedList<Object> namedList = miniSolrCloudCluster.createCollection(MOCK_TABLE, 1, 1, MOCK_TABLE, null);
    assertEquals(namedList.indexOf("success", 0), 1);
    Thread.sleep(1000);

    instance = getDB();
  }

  @After
  public void tearDown() throws Exception {
    if(miniSolrCloudCluster != null) {
      NamedList<Object> namedList = miniSolrCloudCluster.deleteCollection(MOCK_TABLE);
      assertEquals(namedList.indexOf("success", 0), 1);
      Thread.sleep(1000);
    }
  }

  @Test
  public void testInsert() throws Exception {
    Status result = instance.insert(MOCK_TABLE, MOCK_KEY0, MOCK_DATA);
    assertEquals(Status.OK, result);
  }

  @Test
  public void testDelete() throws Exception {
    Status result = instance.delete(MOCK_TABLE, MOCK_KEY1);
    assertEquals(Status.OK, result);
  }

  @Test
  public void testRead() throws Exception {
    Set<String> fields = MOCK_DATA.keySet();
    HashMap<String, ByteIterator> resultParam = new HashMap<>(NUM_RECORDS);
    Status result = instance.read(MOCK_TABLE, MOCK_KEY1, fields, resultParam);
    assertEquals(Status.OK, result);
  }

  @Test
  public void testUpdate() throws Exception {
    HashMap<String, ByteIterator> newValues = new HashMap<>(NUM_RECORDS);

    for (int i = 0; i < NUM_RECORDS; i++) {
      newValues.put(FIELD_PREFIX + i, new StringByteIterator("newvalue" + i));
    }

    Status result = instance.update(MOCK_TABLE, MOCK_KEY1, newValues);
    assertEquals(Status.OK, result);

    //validate that the values changed
    HashMap<String, ByteIterator> resultParam = new HashMap<>(NUM_RECORDS);
    instance.read(MOCK_TABLE, MOCK_KEY1, MOCK_DATA.keySet(), resultParam);

    for (int i = 0; i < NUM_RECORDS; i++) {
      assertEquals("newvalue" + i, resultParam.get(FIELD_PREFIX + i).toString());
    }
  }

  @Test
  public void testScan() throws Exception {
    Set<String> fields = MOCK_DATA.keySet();
    Vector<HashMap<String, ByteIterator>> resultParam = new Vector<>(NUM_RECORDS);
    Status result = instance.scan(MOCK_TABLE, MOCK_KEY1, NUM_RECORDS, fields, resultParam);
    assertEquals(Status.OK, result);
  }

  /**
   * Gets the test DB.
   *
   * @return The test DB.
   */
  protected DB getDB() {
    return getDB(new Properties());
  }

  /**
   * Gets the test DB.
   *
   * @param props
   *    Properties to pass to the client.
   * @return The test DB.
   */
  protected abstract DB getDB(Properties props);
}


text:
package com.jetbrains.python.refactoring.classes;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import javax.annotation.Nonnull;

import org.jetbrains.annotations.NonNls;

import javax.annotation.Nullable;
import com.google.common.collect.Collections2;
import com.intellij.lang.ASTNode;
import com.intellij.lang.injection.InjectedLanguageManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import consulo.util.dataholder.Key;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileSystemItem;
import com.intellij.psi.PsiNamedElement;
import com.intellij.psi.PsiReference;
import com.intellij.psi.PsiWhiteSpace;
import com.intellij.psi.ResolveResult;
import com.intellij.psi.impl.light.LightElement;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtilBase;
import com.intellij.psi.util.QualifiedName;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.ContainerUtil;
import com.jetbrains.NotNullPredicate;
import com.jetbrains.python.PyNames;
import com.jetbrains.python.codeInsight.PyCodeInsightSettings;
import com.jetbrains.python.codeInsight.imports.AddImportHelper;
import com.jetbrains.python.codeInsight.imports.PyImportOptimizer;
import com.jetbrains.python.psi.*;
import com.jetbrains.python.psi.impl.PyBuiltinCache;
import com.jetbrains.python.psi.impl.PyImportedModule;
import com.jetbrains.python.psi.impl.PyPsiUtils;
import com.jetbrains.python.psi.resolve.QualifiedNameFinder;

/**
 * @author Dennis.Ushakov
 */
public final class PyClassRefactoringUtil
{
	private static final Logger LOG = Logger.getInstance(PyClassRefactoringUtil.class.getName());
	private static final Key<PsiNamedElement> ENCODED_IMPORT = Key.create("PyEncodedImport");
	private static final Key<Boolean> ENCODED_USE_FROM_IMPORT = Key.create("PyEncodedUseFromImport");
	private static final Key<String> ENCODED_IMPORT_AS = Key.create("PyEncodedImportAs");

	private PyClassRefactoringUtil()
	{
	}

	/**
	 * Copies class field declarations to some other place
	 *
	 * @param assignmentStatements       list of class fields
	 * @param dequalifyIfDeclaredInClass If not null method will check if field declared in this class.
	 *                                   If declared -- qualifier will be removed.
	 *                                   For example: MyClass.Foo will become Foo it this param is MyClass.
	 * @return new (copied) fields
	 */
	@Nonnull
	public static List<PyAssignmentStatement> copyFieldDeclarationToStatement(@Nonnull final Collection<PyAssignmentStatement> assignmentStatements,
			@Nonnull final PyStatementList superClassStatement,
			@Nullable final PyClass dequalifyIfDeclaredInClass)
	{
		final List<PyAssignmentStatement> declarations = new ArrayList<>(assignmentStatements.size());
		Collections.sort(declarations, PyDependenciesComparator.INSTANCE);

		for(final PyAssignmentStatement pyAssignmentStatement : assignmentStatements)
		{
			final PyElement value = pyAssignmentStatement.getAssignedValue();
			final PyAssignmentStatement newDeclaration = (PyAssignmentStatement) pyAssignmentStatement.copy();

			if(value instanceof PyReferenceExpression && dequalifyIfDeclaredInClass != null)
			{
				final String newValue = getNewValueToAssign((PyReferenceExpression) value, dequalifyIfDeclaredInClass);

				setNewAssigneeValue(newDeclaration, newValue);

			}

			declarations.add(PyUtil.addElementToStatementList(newDeclaration, superClassStatement));
			PyPsiUtils.removeRedundantPass(superClassStatement);
		}
		return declarations;
	}

	/**
	 * Sets new value to assignment statement.
	 *
	 * @param assignmentStatement statement to change
	 * @param newValue            new value
	 */
	private static void setNewAssigneeValue(@Nonnull final PyAssignmentStatement assignmentStatement, @Nonnull final String newValue)
	{
		final PyExpression oldValue = assignmentStatement.getAssignedValue();
		final PyExpression newExpression = PyElementGenerator.getInstance(assignmentStatement.getProject()).createExpressionFromText(LanguageLevel.forElement(assignmentStatement), newValue);
		if(oldValue != null)
		{
			oldValue.replace(newExpression);
		}
		else
		{
			assignmentStatement.add(newExpression);
		}
	}

	/**
	 * Checks if current value declared in provided class and removes class qualifier if true
	 *
	 * @param currentValue               current value
	 * @param dequalifyIfDeclaredInClass class to check
	 * @return value as string
	 */
	@Nonnull
	private static String getNewValueToAssign(@Nonnull final PyReferenceExpression currentValue, @Nonnull final PyClass dequalifyIfDeclaredInClass)
	{
		final PyExpression qualifier = currentValue.getQualifier();
		if((qualifier instanceof PyReferenceExpression) && ((PyReferenceExpression) qualifier).getReference().isReferenceTo(dequalifyIfDeclaredInClass))
		{
			final String name = currentValue.getName();
			return ((name != null) ? name : currentValue.getText());
		}
		return currentValue.getText();
	}

	@Nonnull
	public static List<PyFunction> copyMethods(Collection<PyFunction> methods, PyClass superClass, boolean skipIfExist)
	{
		if(methods.isEmpty())
		{
			return Collections.emptyList();
		}
		for(final PsiElement e : methods)
		{
			rememberNamedReferences(e);
		}
		final PyFunction[] elements = methods.toArray(new PyFunction[methods.size()]);
		return addMethods(superClass, skipIfExist, elements);
	}

	/**
	 * Adds methods to class.
	 *
	 * @param destination where to add methods
	 * @param methods     methods
	 * @param skipIfExist do not add anything if method already exists
	 * @return newly added methods or existing one (if skipIfExists is true and method already exists)
	 */
	@Nonnull
	public static List<PyFunction> addMethods(@Nonnull final PyClass destination, final boolean skipIfExist, @Nonnull final PyFunction... methods)
	{

		final PyStatementList destStatementList = destination.getStatementList();
		final List<PyFunction> result = new ArrayList<>(methods.length);

		for(final PyFunction method : methods)
		{

			final PyFunction existingMethod = destination.findMethodByName(method.getName(), false, null);
			if((existingMethod != null) && skipIfExist)
			{
				result.add(existingMethod);
				continue; //We skip adding if class already has this method.
			}

			final PyFunction newMethod = insertMethodInProperPlace(destStatementList, method);
			result.add(newMethod);
			restoreNamedReferences(newMethod);
		}

		PyPsiUtils.removeRedundantPass(destStatementList);
		return result;
	}

	/**
	 * Adds init methods before all other methods (but after class vars and docs).
	 * Adds all other methods to the bottom
	 *
	 * @param destStatementList where to add methods
	 * @param method            method to add
	 * @return newlty added method
	 */
	@Nonnull
	private static PyFunction insertMethodInProperPlace(@Nonnull final PyStatementList destStatementList, @Nonnull final PyFunction method)
	{
		boolean methodIsInit = PyUtil.isInit(method);
		if(!methodIsInit)
		{
			//Not init method could be inserted in the bottom
			return (PyFunction) destStatementList.add(method);
		}

		//We should find appropriate place for init
		for(final PsiElement element : destStatementList.getChildren())
		{
			final boolean elementComment = element instanceof PyExpressionStatement;
			final boolean elementClassField = element instanceof PyAssignmentStatement;

			if(!(elementComment || elementClassField))
			{
				return (PyFunction) destStatementList.addBefore(method, element);
			}
		}
		return (PyFunction) destStatementList.add(method);
	}

	/**
	 * Restores references saved by {@link #rememberNamedReferences(com.intellij.psi.PsiElement, String...)}.
	 *
	 * @param element newly created element to restore references
	 * @see #rememberNamedReferences(com.intellij.psi.PsiElement, String...)
	 */
	public static void restoreNamedReferences(@Nonnull final PsiElement element)
	{
		restoreNamedReferences(element, null);
	}

	public static void restoreNamedReferences(@Nonnull final PsiElement newElement, @Nullable final PsiElement oldElement)
	{
		restoreNamedReferences(newElement, oldElement, PsiElement.EMPTY_ARRAY);
	}

	public static void restoreNamedReferences(@Nonnull final PsiElement newElement, @Nullable final PsiElement oldElement, @Nonnull final PsiElement[] otherMovedElements)
	{
		newElement.acceptChildren(new PyRecursiveElementVisitor()
		{
			@Override
			public void visitPyReferenceExpression(PyReferenceExpression node)
			{
				super.visitPyReferenceExpression(node);
				restoreReference(node, otherMovedElements);
			}

			@Override
			public void visitPyStringLiteralExpression(PyStringLiteralExpression node)
			{
				super.visitPyStringLiteralExpression(node);
				for(PsiReference ref : node.getReferences())
				{
					if(ref.isReferenceTo(oldElement))
					{
						ref.bindToElement(newElement);
					}
				}
			}
		});
	}

	private static void restoreReference(@Nonnull PyReferenceExpression node, @Nonnull PsiElement[] otherMovedElements)
	{
		try
		{
			PsiNamedElement target = node.getCopyableUserData(ENCODED_IMPORT);
			final String asName = node.getCopyableUserData(ENCODED_IMPORT_AS);
			final Boolean useFromImport = node.getCopyableUserData(ENCODED_USE_FROM_IMPORT);
			if(target instanceof PsiDirectory)
			{
				target = (PsiNamedElement) PyUtil.getPackageElement((PsiDirectory) target, node);
			}
			if(target instanceof PyFunction)
			{
				final PyFunction f = (PyFunction) target;
				final PyClass c = f.getContainingClass();
				if(c != null && c.findInitOrNew(false, null) == f)
				{
					target = c;
				}
			}
			if(target == null)
			{
				return;
			}
			if(PsiTreeUtil.isAncestor(node.getContainingFile(), target, false))
			{
				return;
			}
			if(ArrayUtil.contains(target, otherMovedElements))
			{
				return;
			}
			if(target instanceof PyFile || target instanceof PsiDirectory)
			{
				insertImport(node, target, asName, useFromImport != null ? useFromImport : true);
			}
			else
			{
				insertImport(node, target, asName, true);
			}
		}
		finally
		{
			node.putCopyableUserData(ENCODED_IMPORT, null);
			node.putCopyableUserData(ENCODED_IMPORT_AS, null);
			node.putCopyableUserData(ENCODED_USE_FROM_IMPORT, null);
		}
	}

	public static void insertImport(PsiElement anchor, Collection<PsiNamedElement> elements)
	{
		for(PsiNamedElement newClass : elements)
		{
			insertImport(anchor, newClass);
		}
	}

	public static boolean isValidQualifiedName(QualifiedName name)
	{
		if(name == null)
		{
			return false;
		}
		final Collection<String> components = name.getComponents();
		if(components.isEmpty())
		{
			return false;
		}
		for(String s : components)
		{
			if(!PyNames.isIdentifier(s) || PyNames.isReserved(s))
			{
				return false;
			}
		}
		return true;
	}

	public static boolean insertImport(@Nonnull PsiElement anchor, @Nonnull PsiNamedElement element)
	{
		return insertImport(anchor, element, null);
	}

	public static boolean insertImport(@Nonnull PsiElement anchor, @Nonnull PsiNamedElement element, @Nullable String asName)
	{
		return insertImport(anchor, element, asName, PyCodeInsightSettings.getInstance().PREFER_FROM_IMPORT);
	}

	public static boolean insertImport(@Nonnull PsiElement anchor, @Nonnull PsiNamedElement element, @Nullable String asName, boolean preferFromImport)
	{
		if(PyBuiltinCache.getInstance(element).isBuiltin(element))
		{
			return false;
		}
		final PsiFileSystemItem elementSource = element instanceof PsiDirectory ? (PsiFileSystemItem) element : element.getContainingFile();
		final PsiFile file = anchor.getContainingFile();
		if(elementSource == file)
		{
			return false;
		}
		final QualifiedName qname = QualifiedNameFinder.findCanonicalImportPath(element, anchor);
		if(qname == null || !isValidQualifiedName(qname))
		{
			return false;
		}
		final QualifiedName containingQName;
		final String importedName;
		final boolean importingModuleOrPackage = element instanceof PyFile || element instanceof PsiDirectory;
		if(importingModuleOrPackage)
		{
			containingQName = qname.removeLastComponent();
			importedName = qname.getLastComponent();
		}
		else
		{
			containingQName = qname;
			importedName = getOriginalName(element);
		}
		final AddImportHelper.ImportPriority priority = AddImportHelper.getImportPriority(anchor, elementSource);
		if(preferFromImport && !containingQName.getComponents().isEmpty() || !importingModuleOrPackage)
		{
			return AddImportHelper.addOrUpdateFromImportStatement(file, containingQName.toString(), importedName, asName, priority, anchor);
		}
		else
		{
			return AddImportHelper.addImportStatement(file, containingQName.append(importedName).toString(), asName, priority, anchor);
		}
	}

	/**
	 * Searches for references inside some element (like {@link com.jetbrains.python.psi.PyAssignmentStatement}, {@link com.jetbrains.python.psi.PyFunction} etc
	 * and stored them.
	 * After that you can add element to some new parent. Newly created element then should be processed via {@link #restoreNamedReferences(com.intellij.psi.PsiElement)}
	 * and all references would be restored.
	 *
	 * @param element     element to store references for
	 * @param namesToSkip if reference inside of element has one of this names, it will not be saved.
	 */
	public static void rememberNamedReferences(@Nonnull final PsiElement element, @Nonnull final String... namesToSkip)
	{
		element.acceptChildren(new PyRecursiveElementVisitor()
		{
			@Override
			public void visitPyReferenceExpression(PyReferenceExpression node)
			{
				super.visitPyReferenceExpression(node);
				if(PsiTreeUtil.getParentOfType(node, PyImportStatementBase.class) != null)
				{
					return;
				}
				final PyImportedNameDefiner importElement = getImportElement(node);
				if(importElement != null && PsiTreeUtil.isAncestor(element, importElement, false))
				{
					return;
				}
				if(!ArrayUtil.contains(node.getText(), namesToSkip))
				{ //Do not remember name if it should be skipped
					rememberReference(node, element);
				}
			}
		});
	}

	private static void rememberReference(@Nonnull PyReferenceExpression node, @Nonnull PsiElement element)
	{
		// We will remember reference in deepest node (except for references to PyImportedModules, as we need references to modules, not to
		// their packages)
		final PyExpression qualifier = node.getQualifier();
		if(qualifier != null && !(resolveExpression(qualifier) instanceof PyImportedModule))
		{
			return;
		}
		final List<PsiElement> allResolveResults = multiResolveExpression(node);
		PsiElement target = ContainerUtil.getFirstItem(allResolveResults);
		if(target instanceof PsiNamedElement && !PsiTreeUtil.isAncestor(element, target, false))
		{
			final PyImportedNameDefiner importElement = getImportElement(node);
			if(!PyUtil.inSameFile(element, target) && importElement == null && !(target instanceof PsiFileSystemItem))
			{
				return;
			}
			if(target instanceof PyTargetExpression && PyNames.ALL.equals(((PyTargetExpression) target).getName()))
			{
				for(PsiElement result : allResolveResults)
				{
					if(result instanceof PyImportElement)
					{
						final QualifiedName importedQName = ((PyImportElement) result).getImportedQName();
						if(importedQName != null)
						{
							target = new DynamicNamedElement(target.getContainingFile(), importedQName.toString());
							break;
						}
					}
				}
			}
			node.putCopyableUserData(ENCODED_IMPORT, (PsiNamedElement) target);
			if(importElement instanceof PyImportElement)
			{
				node.putCopyableUserData(ENCODED_IMPORT_AS, ((PyImportElement) importElement).getAsName());
			}
			node.putCopyableUserData(ENCODED_USE_FROM_IMPORT, qualifier == null);
		}
	}

	@Nullable
	private static PyImportedNameDefiner getImportElement(PyReferenceExpression expr)
	{
		for(ResolveResult result : expr.getReference().multiResolve(false))
		{
			final PsiElement e = result.getElement();
			if(e instanceof PyImportElement)
			{
				return (PyImportElement) e;
			}
			if(e instanceof PyStarImportElement)
			{
				return (PyStarImportElement) e;
			}
		}
		return null;
	}

	@Nullable
	private static PsiElement resolveExpression(@Nonnull PyExpression expr)
	{
		if(expr instanceof PyReferenceExpression)
		{
			return ((PyReferenceExpression) expr).getReference().resolve();
		}
		return null;
	}

	@Nonnull
	private static List<PsiElement> multiResolveExpression(@Nonnull PyReferenceExpression expr)
	{
		return ContainerUtil.mapNotNull(expr.getReference().multiResolve(false), result -> result.getElement());
	}

	/**
	 * Updates the import statement if the given PSI element has the same name as one of the import elements of that statement.
	 * It means that you should be careful it you actually want to update the source part of a "from import" statement, because in cases
	 * like {@code from foo import foo} this method may do not what you expect.
	 *
	 * @param importStatement parent import statement that contains reference to given element
	 * @param element         PSI element reference to which should be updated
	 * @return whether import statement was actually updated
	 */
	public static boolean updateUnqualifiedImportOfElement(@Nonnull PyImportStatementBase importStatement, @Nonnull PsiNamedElement element)
	{
		final String name = getOriginalName(element);
		if(name != null)
		{
			PyImportElement importElement = null;
			for(PyImportElement e : importStatement.getImportElements())
			{
				if(name.equals(getOriginalName(e)))
				{
					importElement = e;
				}
			}
			if(importElement != null)
			{
				final PsiFile file = importStatement.getContainingFile();
				final PsiFile newFile = element.getContainingFile();
				if(newFile == file || insertImport(importStatement, element, importElement.getAsName(), true))
				{
					if(importStatement.getImportElements().length == 1)
					{
						final boolean isInjected = InjectedLanguageManager.getInstance(importElement.getProject()).isInjectedFragment(importElement.getContainingFile());
						if(!isInjected)
						{
							importStatement.delete();
						}
						else
						{
							deleteImportStatementFromInjected(importStatement);
						}
					}
					else
					{
						importElement.delete();
					}
					return true;
				}
			}
		}
		return false;
	}

	private static void deleteImportStatementFromInjected(@Nonnull final PyImportStatementBase importStatement)
	{
		final PsiElement sibling = importStatement.getPrevSibling();
		importStatement.delete();
		if(sibling instanceof PsiWhiteSpace)
		{
			sibling.delete();
		}
	}

	@Nullable
	public static String getOriginalName(@Nonnull PsiNamedElement element)
	{
		if(element instanceof PyFile)
		{
			VirtualFile virtualFile = PsiUtilBase.asVirtualFile(PyUtil.turnInitIntoDir(element));
			if(virtualFile != null)
			{
				return virtualFile.getNameWithoutExtension();
			}
			return null;
		}
		return element.getName();
	}

	@Nullable
	private static String getOriginalName(PyImportElement element)
	{
		final QualifiedName qname = element.getImportedQName();
		if(qname != null && qname.getComponentCount() > 0)
		{
			return qname.getComponents().get(0);
		}
		return null;
	}

	/**
	 * Adds super classes to certain class.
	 *
	 * @param project      project where refactoring takes place
	 * @param clazz        destination
	 * @param superClasses classes to add
	 */
	public static void addSuperclasses(@Nonnull final Project project, @Nonnull final PyClass clazz, @Nonnull final PyClass... superClasses)
	{

		final Collection<String> superClassNames = new ArrayList<>();

		for(final PyClass superClass : Collections2.filter(Arrays.asList(superClasses), NotNullPredicate.INSTANCE))
		{
			if(superClass.getName() != null)
			{
				superClassNames.add(superClass.getName());
				insertImport(clazz, superClass);
			}
		}

		addSuperClassExpressions(project, clazz, superClassNames, null);
	}

	/**
	 * Adds expressions to superclass list
	 *
	 * @param project          project
	 * @param clazz            class to add expressions to superclass list
	 * @param paramExpressions param expressions. Like "object" or "MySuperClass". Will not add any param exp. if null.
	 * @param keywordArguments keyword args like "metaclass=ABCMeta". key-value pairs.  Will not add any keyword arg. if null.
	 */
	public static void addSuperClassExpressions(@Nonnull final Project project,
			@Nonnull final PyClass clazz,
			@Nullable final Collection<String> paramExpressions,
			@Nullable final Collection<Pair<String, String>> keywordArguments)
	{
		final PyElementGenerator generator = PyElementGenerator.getInstance(project);
		final LanguageLevel languageLevel = LanguageLevel.forElement(clazz);

		PyArgumentList superClassExpressionList = clazz.getSuperClassExpressionList();
		boolean addExpression = false;
		if(superClassExpressionList == null)
		{
			superClassExpressionList = generator.createFromText(languageLevel, PyClass.class, "class foo():pass").getSuperClassExpressionList();
			assert superClassExpressionList != null : "expression not created";
			addExpression = true;
		}

		generator.createFromText(LanguageLevel.PYTHON34, PyClass.class, "class foo(object, metaclass=Foo): pass").getSuperClassExpressionList();
		if(paramExpressions != null)
		{
			for(final String paramExpression : paramExpressions)
			{
				superClassExpressionList.addArgument(generator.createParameter(paramExpression));
			}
		}

		if(keywordArguments != null)
		{
			for(final Pair<String, String> keywordArgument : keywordArguments)
			{
				superClassExpressionList.addArgument(generator.createKeywordArgument(languageLevel, keywordArgument.first, keywordArgument.second));
			}
		}

		// If class has no expression list, then we need to add it manually.
		if(addExpression)
		{
			final ASTNode classNameNode = clazz.getNameNode(); // For nameless classes we simply add expression list directly to them
			final PsiElement elementToAddAfter = (classNameNode == null) ? clazz.getFirstChild() : classNameNode.getPsi();
			clazz.addAfter(superClassExpressionList, elementToAddAfter);
		}
	}

	/**
	 * Optimizes imports resorting them and removing unneeded
	 *
	 * @param file file to optimize imports
	 */
	public static void optimizeImports(@Nonnull final PsiFile file)
	{
		new PyImportOptimizer().processFile(file).run();
	}

	/**
	 * Adds class attributeName (field) if it does not exist. like __metaclass__ = ABCMeta. Or CLASS_FIELD = 42.
	 *
	 * @param aClass        where to add
	 * @param attributeName attribute's name. Like __metaclass__ or CLASS_FIELD
	 * @param value         it's value. Like ABCMeta or 42.
	 * @return newly inserted attribute
	 */
	@Nullable
	public static PsiElement addClassAttributeIfNotExist(@Nonnull final PyClass aClass, @Nonnull final String attributeName, @Nonnull final String value)
	{
		if(aClass.findClassAttribute(attributeName, false, null) != null)
		{
			return null; //Do not add any if exist already
		}
		final PyElementGenerator generator = PyElementGenerator.getInstance(aClass.getProject());
		final String text = String.format("%s = %s", attributeName, value);
		final LanguageLevel level = LanguageLevel.forElement(aClass);

		final PyAssignmentStatement assignmentStatement = generator.createFromText(level, PyAssignmentStatement.class, text);
		//TODO: Add metaclass to the top. Add others between last attributeName and first method
		return PyUtil.addElementToStatementList(assignmentStatement, aClass.getStatementList(), true);
	}

	private static class DynamicNamedElement extends LightElement implements PsiNamedElement
	{
		private final PsiFile myFile;
		private final String myName;

		public DynamicNamedElement(@Nonnull PsiFile file, @Nonnull String name)
		{
			super(file.getManager(), file.getLanguage());
			myName = name;
			myFile = file;
		}

		@Override
		public String toString()
		{
			return "DynamicNamedElement(file='" + getContainingFile().getName() + "', name='" + getName() + "')";
		}

		@Override
		public PsiFile getContainingFile()
		{
			return myFile;
		}

		@Override
		public PsiElement setName(@NonNls @Nonnull String name) throws IncorrectOperationException
		{
			return null;
		}

		@Override
		public String getName()
		{
			return myName;
		}
	}
}


text:
<!-- Collapsed Table of Content -->
<script src="website/jquery/jquery.min.js"></script>
<script src="website/jstree/jstree.min.js"></script>
<script src="website/toc.js"></script>

<!-- Adobe Analytics for Red Hat - DPAL (DTM Property Auto-Loader) - part 2/2 -->
<script type="text/javascript">
    if (("undefined" !== typeof _satellite) && ("function" === typeof _satellite.pageBottom)) {
        _satellite.pageBottom();
    }
+</script>


text:
<?xml version="1.0" encoding="UTF-8"?>
<array xmlns="http://www.w3.org/2013/XSL/json">
<null/>
<boolean>true</boolean>
<boolean>false</boolean>
<string>stringvalue</string>
<string>1</string>
<number>1</number>
<number>1.2</number>
<number>0.02</number>
<map>
<string key="a">1</string>
<string key="b">xyz</string>
</map>
<array>
<string>x</string>
<string>y</string>
</array>
</array>


text:
package com.thoughtworks.go.server.service;

import com.thoughtworks.go.config.CaseInsensitiveString;
import com.thoughtworks.go.config.StageConfig;
import com.thoughtworks.go.domain.PipelineInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StageOrderService {
    @Autowired private GoConfigService goConfigService;

    public StageConfig getNextStage(PipelineInfo pipeline, String stageName) {
        StageConfig nextStageFromHistory = nextStageFromHistory(pipeline, stageName);
        return nextStageFromHistory == null ? nextStageFromConfig(pipeline, stageName) : nextStageFromHistory;
    }

    private StageConfig nextStageFromHistory(PipelineInfo pipeline, String stageName) {
        String nextStageName = pipeline.nextStageName(stageName);
        return nextStageName == null ? null : goConfigService.stageConfigNamed(pipeline.getName(), nextStageName);
    }

    private StageConfig nextStageFromConfig(PipelineInfo pipeline, String stageName) {
        if (goConfigService.hasNextStage(pipeline.getName(), stageName)) {
            StageConfig nextStageConfig = goConfigService.nextStage(pipeline.getName(), stageName);
            return stageHasBeenRun(pipeline, nextStageConfig) ? null : nextStageConfig;
        }
        return null;
    }

    private boolean stageHasBeenRun(PipelineInfo currentPipeline, StageConfig nextStageConfig) {
        return currentPipeline.hasStageBeenRun(CaseInsensitiveString.str(nextStageConfig.name()));
    }
}