text:
define([
    'jquery',
    'base/js/namespace',
    'base/js/dialog',
    'base/js/utils'

], function ($, Jupyter, dialog, utils) {
    "use strict";

    var nbgrader_version = "0.8.0.dev";

    var ajax = utils.ajax || $.ajax;
    // Notebook v4.3.1 enabled xsrf so use notebooks ajax that includes the
    // xsrf token in the header data

    var checkNbGraderVersion = function (callback) {
        var settings = {
            cache : false,
            type : "GET",
            dataType : "json",
            data : {
                version: nbgrader_version
            },
            success : function (response) {
                if (!response['success']) {
                    var body = $("<div/>").text(response['message']);
                    dialog.modal({
                        title: "Version Mismatch",
                        body: body,
                        buttons: { OK: { class : "btn-primary" } }
                    });
                } else {
                    callback();
                }
            },
            error : utils.log_ajax_error,
        };
        var url = utils.url_path_join(Jupyter.notebook.base_url, 'nbgrader_version');
        ajax(url, settings);
    };

    var add_button = function () {
        var maintoolbar = $("#maintoolbar-container");
        var btn_group = $("<div />").attr("class", "btn-group")
        var btn = $("<button />").attr("class", "btn btn-default validate").text("Validate");
        btn_group.append(btn)
        maintoolbar.append(btn_group);

        btn.click(function (e) {
            checkNbGraderVersion(function () {
                var p = Jupyter.notebook.save_notebook();
                p.then(function () {
                    var settings = {
                        cache : false,
                        data : { path: Jupyter.notebook.notebook_path },
                        type : "POST",
                        dataType : "json",
                        success : function (data, status, xhr) {
                            btn.text('Validate');
                            btn.removeAttr('disabled');
                            validate(data, btn);
                        },
                        error : function (xhr, status, error) {
                            utils.log_ajax_error(xhr, status, error);
                        }
                    };
                    btn.text('Validating...');
                    btn.attr('disabled', 'disabled');
                    var url = utils.url_path_join(
                        Jupyter.notebook.base_url,
                        'assignments',
                        'validate'
                    );
                    ajax(url, settings);
                });
            });
        });
    };

    var validate = function (data, button) {
        var body = $('<div/>').attr("id", "validation-message");
        if (data.success === true) {
            if (typeof(data.value) === "string") {
                data = JSON.parse(data.value);
            } else {
                data = data.value;
            }
            if (data.type_changed !== undefined) {
                for (var i=0; i<data.type_changed.length; i++) {
                    body.append($('<div/>').append($('<p/>').text('The following ' + data.type_changed[i].old_type + ' cell has changed to a ' + data.type_changed[i].new_type + ' cell, but it should not have!')));
                    body.append($('<pre/>').text(data.type_changed[i].source));
                }
                body.addClass("validation-type-changed");

            } else if (data.changed !== undefined) {
                for (var i=0; i<data.changed.length; i++) {
                    body.append($('<div/>').append($('<p/>').text('The source of the following cell has changed, but it should not have!')));
                    body.append($('<pre/>').text(data.changed[i].source));
                }
                body.addClass("validation-changed");

            } else if (data.passed !== undefined) {
                for (var i=0; i<data.changed.length; i++) {
                    body.append($('<div/>').append($('<p/>').text('The following cell passed:')));
                    body.append($('<pre/>').text(data.passed[i].source));
                }
                body.addClass("validation-passed");

            } else if (data.failed !== undefined) {
                for (var i=0; i<data.failed.length; i++) {
                    body.append($('<div/>').append($('<p/>').text('The following cell failed:')));
                    body.append($('<pre/>').text(data.failed[i].source));
                    body.append($('<pre/>').html(data.failed[i].error));
                }
                body.addClass("validation-failed");

            } else {
                body.append($('<div/>').append($('<p/>').text('Success! Your notebook passes all the tests.')));
                body.addClass("validation-success");
            }

        } else {
            body.append($('<div/>').append($('<p/>').text('There was an error running the validate command:')));
            body.append($('<pre/>').text(data.value));
        }

        dialog.modal({
            title: "Validation Results",
            body: body,
            buttons: { OK: { class : "btn-primary" } }
        });
    };

    var load_extension = function () {
        add_button();
        console.log('nbgrader extension for validating notebooks loaded.');
    };

    return {
        'load_ipython_extension': load_extension
    };
});


text:
"""
================================================================================
Keyglove host control console demo application
2014-12-06 by Jeff Rowberg <jeff@rowberg.net>

Changelog:
    2014-12-06 - Initial release

================================================================================
Keyglove source code is placed under the MIT license
Copyright (c) 2014 Jeff Rowberg

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

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

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

================================================================================

"""

__author__ = "Jeff Rowberg"
__license__ = "MIT"
__version__ = "2014-12-06"
__email__ = "jeff@rowberg.net"

import sys, signal, time
import kglib

keyglove = None         # Keyglove device instance (see 'kglib.KeygloveDevice')
kgapi = kglib.KGAPI()   # API protocol parser instance (see 'kglib.KGAPI')

# ==============================================================================
# DEVICE CONNECTION MANAGEMENT EVENTS (triggered from KeygloveDevice object)
# ==============================================================================

def my_on_connected(sender, args):
    print("+++ Keyglove connected")

def my_on_disconnected(sender, args):
    print("--- Keyglove disconnected")

def my_on_unplugged(sender, args):
    print("!!! Keyglove device unplugged, no communication possible at this time")

def my_on_api_timeout(sender, args):
    print("??? API command timed out waiting for response, device may be disconnected")

# ==============================================================================
# API COMMUNICATION CALLBACKS (assigned in main(), triggered from KGAPI object)
# ==============================================================================

def my_kg_response(sender, args):
    friendly = kgapi.friendly_packet(args["raw"], True)
    if friendly:
        print("%.2f <-- %s { %s }" % (time.time(), friendly["name"], ', '.join([ ("%s: %s" % (x, friendly["payload"][x])) for x in friendly["payload"]])))
    else:
        print("%.2f <-- UNKNOWN RESPONSE: [ %s ]" % (time.time(), ' '.join(['%02X' % b for b in args['raw']])))

def my_kg_event(sender, args):
    friendly = kgapi.friendly_packet(args["raw"], True)
    if friendly:
        print("%.2f <-- %s { %s }" % (time.time(), friendly["name"], ', '.join([ ("%s: %s" % (x, friendly["payload"][x])) for x in friendly["payload"]])))
    else:
        print("%.2f <-- UNKNOWN EVENT: [ %s ]" % (time.time(), ' '.join(['%02X' % b for b in args['raw']])))

def my_kg_log(sender, args):
    print("%.2f <-- LOG (%d): %s" % (time.time(), args["level"], args["log"]))

def my_kg_evt_touch_status(sender, args):
    print("%.2f *** Touch update: %s" % (time.time(), ' '.join(['%02X' % b for b in args['status']])))

# ==============================================================================
# MAIN APPLICATION LOGIC
# ==============================================================================

def main():
    global keyglove

    print("=================================")
    print("Keyglove Console Application Stub")
    print("=================================\n")

    # show available transports/backends
    print("USB options: %s" % kglib.usb_options)
    print("USB selected: %s" % kglib.usb_selected)
    print("Serial options: %s" % kglib.serial_options)
    print("Serial selected: %s\n" % kglib.serial_selected)

    # list all available devices
    print("Keyglove devices:")
    index = 0
    devices = list(kglib.get_devices())
    if len(devices) > 0:
        for device in devices:
            print("    #%d: %s @ %s" % (index, device.description, device.port))
            index = index + 1
        print("")
    else:
        # no devices available (no backends or nothing connected)
        print("    No devices found!")
        print("    Please make sure Keyglove is connected and")
        print("    PySerial, PyWinUSB, and/or PyUSB is available")
        exit(1)

    # attempt to connect and use Keyglove
    print("Connecting to first device in list...")
    keyglove = devices[0]
    try:
        # assign custom event handlers for connection/disconnection/unplug
        keyglove.on_connected += my_on_connected
        keyglove.on_disconnected += my_on_disconnected
        keyglove.on_unplugged += my_on_unplugged
        keyglove.on_api_timeout += my_on_api_timeout

        # assign custom generic handlers for responses, events, and log entries
        kgapi.kg_response += my_kg_response
        kgapi.kg_event += my_kg_event
        kgapi.kg_log += my_kg_log

        # assign custom event handler for kg_evt_touch_status() API event
        kgapi.kg_evt_touch_status += my_kg_evt_touch_status

        if keyglove.connect(kgapi):
            # repeatedly ping Keyglove device (SIGINT/Ctrl+C will break)
            while keyglove.connected:
                # build outgoing command packet
                cmd_packet = kgapi.kg_cmd_system_ping()

                # pass raw command to "friendly" interpreter in KGAPI object
                # (this is totally optional and mostly just helps debug output)
                friendly = kgapi.friendly_packet(cmd_packet, False)
                if friendly:
                    print("%.2f --> %s { %s }" % (time.time(), friendly["name"], ', '.join([ ("%s: %s" % (x, friendly["payload"][x])) for x in friendly["payload"]])))
                else:
                    print("%.2f --> UNKNOWN COMMAND: [ %s ]" % (time.time(), ' '.join(['%02X' % b for b in cmd_packet])))

                # send command and wait up to 1 second for response
                response = keyglove.send_and_return(cmd_packet, 1)

                # wait 5 seconds before repeating
                if keyglove.connected: time.sleep(5)

    except kglib.KeygloveError as e:
        print("Keyglove error (%s): %s" % (type(e), e))

# ==============================================================================
# PYTHON "__main__" ENTRY POINT DEFINITION
# ==============================================================================

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        if keyglove != None and keyglove.connected:
            print("Disconnecting from Keyglove...")
            if not keyglove.disconnect():
                print("Could not disconnect!")

        print("Goodbye!")
        sys.exit(0)

redpajama_set_name: RedPajamaGithub


text:
"""
Tests for catalyst.lib.adjustment
"""
from unittest import TestCase
from nose_parameterized import parameterized

from catalyst.lib import adjustment as adj
from catalyst.utils.numpy_utils import make_datetime64ns

class AdjustmentTestCase(TestCase):

    @parameterized.expand([
        ('add', adj.ADD),
        ('multiply', adj.MULTIPLY),
        ('overwrite', adj.OVERWRITE),
    ])
    def test_make_float_adjustment(self, name, adj_type):
        expected_types = {
            'add': adj.Float64Add,
            'multiply': adj.Float64Multiply,
            'overwrite': adj.Float64Overwrite,
        }
        result = adj.make_adjustment_from_indices(
            1, 2, 3, 4,
            adjustment_kind=adj_type,
            value=0.5,
        )
        expected = expected_types[name](
            first_row=1,
            last_row=2,
            first_col=3,
            last_col=4,
            value=0.5,
        )
        self.assertEqual(result, expected)

    def test_make_int_adjustment(self):
        result = adj.make_adjustment_from_indices(
            1, 2, 3, 4,
            adjustment_kind=adj.OVERWRITE,
            value=1,
        )
        expected = adj.Int64Overwrite(
            first_row=1,
            last_row=2,
            first_col=3,
            last_col=4,
            value=1,
        )
        self.assertEqual(result, expected)

    def test_make_datetime_adjustment(self):
        overwrite_dt = make_datetime64ns(0)
        result = adj.make_adjustment_from_indices(
            1, 2, 3, 4,
            adjustment_kind=adj.OVERWRITE,
            value=overwrite_dt,
        )
        expected = adj.Datetime64Overwrite(
            first_row=1,
            last_row=2,
            first_col=3,
            last_col=4,
            value=overwrite_dt,
        )
        self.assertEqual(result, expected)

    @parameterized.expand([("some text",), ("some text".encode(),), (None,)])
    def test_make_object_adjustment(self, value):
        result = adj.make_adjustment_from_indices(
            1, 2, 3, 4,
            adjustment_kind=adj.OVERWRITE,
            value=value,
        )

        expected = adj.ObjectOverwrite(
            first_row=1,
            last_row=2,
            first_col=3,
            last_col=4,
            value=value,
        )
        self.assertEqual(result, expected)

    def test_unsupported_type(self):
        class SomeClass(object):
            pass

        with self.assertRaises(TypeError) as e:
            adj.make_adjustment_from_indices(
                1, 2, 3, 4,
                adjustment_kind=adj.OVERWRITE,
                value=SomeClass(),
            )

        exc = e.exception
        expected_msg = (
            "Don't know how to make overwrite adjustments for values of type "
            "%r." % SomeClass
        )
        self.assertEqual(str(exc), expected_msg)


text:
#include <vr_core.h>

/*-----------------------------------------------------------------------------
 * List API
 *----------------------------------------------------------------------------*/

/* The function pushes an element to the specified list object 'subject',
 * at head or tail position as specified by 'where'.
 *
 * There is no need for the caller to increment the refcount of 'value' as
 * the function takes care of it if needed. */
void listTypePush(robj *subject, robj *value, int where) {
    if (subject->encoding == OBJ_ENCODING_QUICKLIST) {
        robj *value_new;
        int pos = (where == LIST_HEAD) ? QUICKLIST_HEAD : QUICKLIST_TAIL;
        value_new = getDecodedObject(value);
        size_t len = sdslen(value_new->ptr);
        quicklistPush(subject->ptr, value_new->ptr, len, pos);
        if (value_new != value) freeObject(value_new);
    } else {
        serverPanic("Unknown list encoding");
    }
}

void *listPopSaver(unsigned char *data, unsigned int sz) {
    return createStringObject((char*)data,sz);
}

robj *listTypePop(robj *subject, int where) {
    long long vlong;
    robj *value = NULL;

    int ql_where = where == LIST_HEAD ? QUICKLIST_HEAD : QUICKLIST_TAIL;
    if (subject->encoding == OBJ_ENCODING_QUICKLIST) {
        if (quicklistPopCustom(subject->ptr, ql_where, (unsigned char **)&value,
                               NULL, &vlong, listPopSaver)) {
            if (!value)
                value = createStringObjectFromLongLong(vlong);
        }
    } else {
        serverPanic("Unknown list encoding");
    }
    return value;
}

unsigned long listTypeLength(robj *subject) {
    if (subject->encoding == OBJ_ENCODING_QUICKLIST) {
        return quicklistCount(subject->ptr);
    } else {
        serverPanic("Unknown list encoding");
    }
}

/* Initialize an iterator at the specified index. */
listTypeIterator *listTypeInitIterator(robj *subject, long index,
                                       unsigned char direction) {
    listTypeIterator *li = dalloc(sizeof(listTypeIterator));
    li->subject = subject;
    li->encoding = subject->encoding;
    li->direction = direction;
    li->iter = NULL;
    /* LIST_HEAD means start at TAIL and move *towards* head.
     * LIST_TAIL means start at HEAD and move *towards tail. */
    int iter_direction =
        direction == LIST_HEAD ? AL_START_TAIL : AL_START_HEAD;
    if (li->encoding == OBJ_ENCODING_QUICKLIST) {
        li->iter = quicklistGetIteratorAtIdx(li->subject->ptr,
                                             iter_direction, index);
    } else {
        serverPanic("Unknown list encoding");
    }
    return li;
}

/* Clean up the iterator. */
void listTypeReleaseIterator(listTypeIterator *li) {
    dfree(li->iter);
    dfree(li);
}

/* Stores pointer to current the entry in the provided entry structure
 * and advances the position of the iterator. Returns 1 when the current
 * entry is in fact an entry, 0 otherwise. */
int listTypeNext(listTypeIterator *li, listTypeEntry *entry) {
    /* Protect from converting when iterating */
    ASSERT(li->subject->encoding == li->encoding);

    entry->li = li;
    if (li->encoding == OBJ_ENCODING_QUICKLIST) {
        return quicklistNext(li->iter, &entry->entry);
    } else {
        serverPanic("Unknown list encoding");
    }
    return 0;
}

/* Return entry or NULL at the current position of the iterator. */
robj *listTypeGet(listTypeEntry *entry) {
    robj *value = NULL;
    if (entry->li->encoding == OBJ_ENCODING_QUICKLIST) {
        if (entry->entry.value) {
            value = createStringObject((char *)entry->entry.value,
                                       entry->entry.sz);
        } else {
            value = createStringObjectFromLongLong(entry->entry.longval);
        }
    } else {
        serverPanic("Unknown list encoding");
    }
    return value;
}

void listTypeInsert(listTypeEntry *entry, robj *value, int where) {
    if (entry->li->encoding == OBJ_ENCODING_QUICKLIST) {
        value = getDecodedObject(value);
        sds str = value->ptr;
        size_t len = sdslen(str);
        if (where == LIST_TAIL) {
            quicklistInsertAfter((quicklist *)entry->entry.quicklist,
                                 &entry->entry, str, len);
        } else if (where == LIST_HEAD) {
            quicklistInsertBefore((quicklist *)entry->entry.quicklist,
                                  &entry->entry, str, len);
        }
        decrRefCount(value);
    } else {
        serverPanic("Unknown list encoding");
    }
}

/* Compare the given object with the entry at the current position. */
int listTypeEqual(listTypeEntry *entry, robj *o) {
    if (entry->li->encoding == OBJ_ENCODING_QUICKLIST) {
        serverAssertWithInfo(NULL,o,sdsEncodedObject(o));
        return quicklistCompare(entry->entry.zi,o->ptr,sdslen(o->ptr));
    } else {
        serverPanic("Unknown list encoding");
    }
}

/* Delete the element pointed to. */
void listTypeDelete(listTypeIterator *iter, listTypeEntry *entry) {
    if (entry->li->encoding == OBJ_ENCODING_QUICKLIST) {
        quicklistDelEntry(iter->iter, &entry->entry);
    } else {
        serverPanic("Unknown list encoding");
    }
}

/* Create a quicklist from a single ziplist */
void listTypeConvert(robj *subject, int enc) {
    serverAssertWithInfo(NULL,subject,subject->type==OBJ_LIST);
    serverAssertWithInfo(NULL,subject,subject->encoding==OBJ_ENCODING_ZIPLIST);

    if (enc == OBJ_ENCODING_QUICKLIST) {
        size_t zlen = server.list_max_ziplist_size;
        int depth = server.list_compress_depth;
        subject->ptr = quicklistCreateFromZiplist(zlen, depth, subject->ptr);
        subject->encoding = OBJ_ENCODING_QUICKLIST;
    } else {
        serverPanic("Unsupported list conversion");
    }
}

/*-----------------------------------------------------------------------------
 * List Commands
 *----------------------------------------------------------------------------*/

void pushGenericCommand(client *c, int where) {
    int j, waiting = 0, pushed = 0;
    robj *lobj;
    int expired = 0;

    fetchInternalDbByKey(c, c->argv[1]);
    lockDbWrite(c->db);
    lobj = lookupKeyWrite(c->db,c->argv[1],&expired);
    if (lobj && lobj->type != OBJ_LIST) {
        unlockDb(c->db);
        if (expired) update_stats_add(c->vel->stats,expiredkeys,1);
        addReply(c,shared.wrongtypeerr);
        return;
    }

    for (j = 2; j < c->argc; j++) {
        c->argv[j] = tryObjectEncoding(c->argv[j]);
        if (!lobj) {
            lobj = createQuicklistObject();
            quicklistSetOptions(lobj->ptr, server.list_max_ziplist_size,
                                server.list_compress_depth);
            dbAdd(c->db,c->argv[1],lobj);
        }
        listTypePush(lobj,c->argv[j],where);
        pushed++;
    }
    addReplyLongLong(c, waiting + (lobj ? listTypeLength(lobj) : 0));
    if (pushed) {
        char *event = (where == LIST_HEAD) ? "lpush" : "rpush";

        signalModifiedKey(c->db,c->argv[1]);
        notifyKeyspaceEvent(NOTIFY_LIST,event,c->argv[1],c->db->id);
    }
    c->vel->dirty += pushed;

    unlockDb(c->db);
    if (expired) update_stats_add(c->vel->stats,expiredkeys,1);
}

void lpushCommand(client *c) {
    pushGenericCommand(c,LIST_HEAD);
}

void rpushCommand(client *c) {
    pushGenericCommand(c,LIST_TAIL);
}

void pushxGenericCommand(client *c, robj *refval, robj *val, int where) {
    robj *subject;
    listTypeIterator *iter;
    listTypeEntry entry;
    int inserted = 0;

    if ((subject = lookupKeyWriteOrReply(c,c->argv[1],shared.czero,NULL)) == NULL ||
        checkType(c,subject,OBJ_LIST)) return;

    if (refval != NULL) {
        /* Seek refval from head to tail */
        iter = listTypeInitIterator(subject,0,LIST_TAIL);
        while (listTypeNext(iter,&entry)) {
            if (listTypeEqual(&entry,refval)) {
                listTypeInsert(&entry,val,where);
                inserted = 1;
                break;
            }
        }
        listTypeReleaseIterator(iter);

        if (inserted) {
            signalModifiedKey(c->db,c->argv[1]);
            notifyKeyspaceEvent(NOTIFY_LIST,"linsert",
                                c->argv[1],c->db->id);
            server.dirty++;
        } else {
            /* Notify client of a failed insert */
            addReply(c,shared.cnegone);
            return;
        }
    } else {
        char *event = (where == LIST_HEAD) ? "lpush" : "rpush";

        listTypePush(subject,val,where);
        signalModifiedKey(c->db,c->argv[1]);
        notifyKeyspaceEvent(NOTIFY_LIST,event,c->argv[1],c->db->id);
        server.dirty++;
    }

    addReplyLongLong(c,listTypeLength(subject));
}

void lpushxCommand(client *c) {
    c->argv[2] = tryObjectEncoding(c->argv[2]);
    pushxGenericCommand(c,NULL,c->argv[2],LIST_HEAD);
}

void rpushxCommand(client *c) {
    c->argv[2] = tryObjectEncoding(c->argv[2]);
    pushxGenericCommand(c,NULL,c->argv[2],LIST_TAIL);
}

void linsertCommand(client *c) {
    c->argv[4] = tryObjectEncoding(c->argv[4]);
    if (strcasecmp(c->argv[2]->ptr,"after") == 0) {
        pushxGenericCommand(c,c->argv[3],c->argv[4],LIST_TAIL);
    } else if (strcasecmp(c->argv[2]->ptr,"before") == 0) {
        pushxGenericCommand(c,c->argv[3],c->argv[4],LIST_HEAD);
    } else {
        addReply(c,shared.syntaxerr);
    }
}

void llenCommand(client *c) {
    robj *o;

    fetchInternalDbByKey(c, c->argv[1]);
    lockDbRead(c->db);
    o = lookupKeyReadOrReply(c,c->argv[1],shared.czero);
    if (o == NULL) {
        unlockDb(c->db);
        update_stats_add(c->vel->stats, keyspace_misses, 1);
        return;
    } else if(checkType(c,o,OBJ_LIST)) {
        unlockDb(c->db);
        update_stats_add(c->vel->stats, keyspace_hits, 1);
        return;
    }

    addReplyLongLong(c,listTypeLength(o));
    unlockDb(c->db);
    update_stats_add(c->vel->stats, keyspace_hits, 1);
}

void lindexCommand(client *c) {
    robj *o;
    long index;
    robj *value = NULL;

    if ((getLongFromObjectOrReply(c, c->argv[2], &index, NULL) != VR_OK))
        return;

    fetchInternalDbByKey(c,c->argv[1]);
    lockDbRead(c->db);
    o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk);
    if (o == NULL) {
        unlockDb(c->db);
        update_stats_add(c->vel->stats, keyspace_misses, 1);
        return;
    } else if(checkType(c,o,OBJ_LIST)) {
        unlockDb(c->db);
        update_stats_add(c->vel->stats, keyspace_hits, 1);
        return;
    }
    if (o->encoding == OBJ_ENCODING_QUICKLIST) {
        quicklistEntry entry;
        if (quicklistIndex(o->ptr, index, &entry)) {
            if (entry.value) {
                value = createStringObject((char*)entry.value,entry.sz);
            } else {
                value = createStringObjectFromLongLong(entry.longval);
            }
            addReplyBulk(c,value);
            freeObject(value);
        } else {
            addReply(c,shared.nullbulk);
        }
    } else {
        serverPanic("Unknown list encoding");
    }
    unlockDb(c->db);
    update_stats_add(c->vel->stats, keyspace_hits, 1);
}

void lsetCommand(client *c) {
    robj *o;
    long index;
    robj *value = c->argv[3];
    int expired = 0;

    if ((getLongFromObjectOrReply(c, c->argv[2], &index, NULL) != VR_OK))
        return;

    fetchInternalDbByKey(c, c->argv[1]);
    lockDbWrite(c->db);
    o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr,&expired);
    if (o == NULL || checkType(c,o,OBJ_LIST)) {
        unlockDb(c->db);
        if (expired) update_stats_add(c->vel->stats,expiredkeys,1);
        return;
    }
    if (o->encoding == OBJ_ENCODING_QUICKLIST) {
        quicklist *ql = o->ptr;
        int replaced = quicklistReplaceAtIndex(ql, index,
                                               value->ptr, sdslen(value->ptr));
        if (!replaced) {
            addReply(c,shared.outofrangeerr);
        } else {
            addReply(c,shared.ok);
            signalModifiedKey(c->db,c->argv[1]);
            notifyKeyspaceEvent(NOTIFY_LIST,"lset",c->argv[1],c->db->id);
            c->vel->dirty++;
        }
    } else {
        serverPanic("Unknown list encoding");
    }

    unlockDb(c->db);
    if (expired) update_stats_add(c->vel->stats,expiredkeys,1);
}

void popGenericCommand(client *c, int where) {
    robj *o, *value;
    int expired = 0;

    fetchInternalDbByKey(c, c->argv[1]);
    lockDbWrite(c->db);
    o = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk,&expired);
    if (o == NULL || checkType(c,o,OBJ_LIST)) {
        unlockDb(c->db);
        if (expired) update_stats_add(c->vel->stats,expiredkeys,1);
        return;
    }

    value = listTypePop(o,where);
    if (value == NULL) {
        addReply(c,shared.nullbulk);
    } else {
        char *event = (where == LIST_HEAD) ? "lpop" : "rpop";

        addReplyBulk(c,value);
        freeObject(value);
        notifyKeyspaceEvent(NOTIFY_LIST,event,c->argv[1],c->db->id);
        if (listTypeLength(o) == 0) {
            notifyKeyspaceEvent(NOTIFY_GENERIC,"del",
                                c->argv[1],c->db->id);
            dbDelete(c->db,c->argv[1]);
        }
        signalModifiedKey(c->db,c->argv[1]);
        c->vel->dirty++;
    }
    unlockDb(c->db);
    if (expired) update_stats_add(c->vel->stats,expiredkeys,1);
}

void lpopCommand(client *c) {
    popGenericCommand(c,LIST_HEAD);
}

void rpopCommand(client *c) {
    popGenericCommand(c,LIST_TAIL);
}

void lrangeCommand(client *c) {
    robj *o;
    long start, end, llen, rangelen;

    if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != VR_OK) ||
        (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != VR_OK)) return;

    fetchInternalDbByKey(c, c->argv[1]);
    lockDbRead(c->db);
    if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL) {
        unlockDb(c->db);
        update_stats_add(c->vel->stats, keyspace_misses, 1);
        return;
    } else if (checkType(c,o,OBJ_LIST)) {
        unlockDb(c->db);
        update_stats_add(c->vel->stats, keyspace_hits, 1);
        return;
    }

    llen = listTypeLength(o);

    /* convert negative indexes */
    if (start < 0) start = llen+start;
    if (end < 0) end = llen+end;
    if (start < 0) start = 0;

    /* Invariant: start >= 0, so this test will be true when end < 0.
     * The range is empty when start > end or start >= length. */
    if (start > end || start >= llen) {
        unlockDb(c->db);
        update_stats_add(c->vel->stats, keyspace_hits, 1);
        addReply(c,shared.emptymultibulk);
        return;
    }
    if (end >= llen) end = llen-1;
    rangelen = (end-start)+1;

    /* Return the result in form of a multi-bulk reply */
    addReplyMultiBulkLen(c,rangelen);
    if (o->encoding == OBJ_ENCODING_QUICKLIST) {
        listTypeIterator *iter = listTypeInitIterator(o, start, LIST_TAIL);

        while(rangelen--) {
            listTypeEntry entry;
            listTypeNext(iter, &entry);
            quicklistEntry *qe = &entry.entry;
            if (qe->value) {
                addReplyBulkCBuffer(c,qe->value,qe->sz);
            } else {
                addReplyBulkLongLong(c,qe->longval);
            }
        }
        listTypeReleaseIterator(iter);
    } else {
        serverPanic("List encoding is not QUICKLIST!");
    }

    unlockDb(c->db);
    update_stats_add(c->vel->stats, keyspace_hits, 1);
}

void ltrimCommand(client *c) {
    robj *o;
    long start, end, llen, ltrim, rtrim;
    int expired = 0;

    if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != VR_OK) ||
        (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != VR_OK)) return;

    fetchInternalDbByKey(c, c->argv[1]);
    lockDbWrite(c->db);
    if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.ok,&expired)) == NULL ||
        checkType(c,o,OBJ_LIST)) {
        unlockDb(c->db);
        if (expired) update_stats_add(c->vel->stats, expiredkeys, 1);
        return;
    }
    llen = listTypeLength(o);

    /* convert negative indexes */
    if (start < 0) start = llen+start;
    if (end < 0) end = llen+end;
    if (start < 0) start = 0;

    /* Invariant: start >= 0, so this test will be true when end < 0.
     * The range is empty when start > end or start >= length. */
    if (start > end || start >= llen) {
        /* Out of range start or start > end result in empty list */
        ltrim = llen;
        rtrim = 0;
    } else {
        if (end >= llen) end = llen-1;
        ltrim = start;
        rtrim = llen-end-1;
    }

    /* Remove list elements to perform the trim */
    if (o->encoding == OBJ_ENCODING_QUICKLIST) {
        quicklistDelRange(o->ptr,0,ltrim);
        quicklistDelRange(o->ptr,-rtrim,rtrim);
    } else {
        serverPanic("Unknown list encoding");
    }

    notifyKeyspaceEvent(NOTIFY_LIST,"ltrim",c->argv[1],c->db->id);
    if (listTypeLength(o) == 0) {
        dbDelete(c->db,c->argv[1]);
        notifyKeyspaceEvent(NOTIFY_GENERIC,"del",c->argv[1],c->db->id);
    }
    signalModifiedKey(c->db,c->argv[1]);
    c->vel->dirty++;
    addReply(c,shared.ok);
    unlockDb(c->db);
    if (expired) update_stats_add(c->vel->stats, expiredkeys, 1);
}

void lremCommand(client *c) {
    robj *subject, *obj;
    obj = c->argv[3];
    long toremove;
    long removed = 0;
    int expired = 0;

    if ((getLongFromObjectOrReply(c, c->argv[2], &toremove, NULL) != VR_OK))
        return;

    fetchInternalDbByKey(c, c->argv[1]);
    lockDbWrite(c->db);
    subject = lookupKeyWriteOrReply(c,c->argv[1],shared.czero,&expired);
    if (subject == NULL || checkType(c,subject,OBJ_LIST)) {
        unlockDb(c->db);
        if (expired) update_stats_add(c->vel->stats, expiredkeys, 1);
        return;
    }
    listTypeIterator *li;
    if (toremove < 0) {
        toremove = -toremove;
        li = listTypeInitIterator(subject,-1,LIST_HEAD);
    } else {
        li = listTypeInitIterator(subject,0,LIST_TAIL);
    }

    listTypeEntry entry;
    while (listTypeNext(li,&entry)) {
        if (listTypeEqual(&entry,obj)) {
            listTypeDelete(li, &entry);
            c->vel->dirty++;
            removed++;
            if (toremove && removed == toremove) break;
        }
    }
    listTypeReleaseIterator(li);

    if (removed) {
        signalModifiedKey(c->db,c->argv[1]);
        notifyKeyspaceEvent(NOTIFY_GENERIC,"lrem",c->argv[1],c->db->id);
    }

    if (listTypeLength(subject) == 0) {
        dbDelete(c->db,c->argv[1]);
        notifyKeyspaceEvent(NOTIFY_GENERIC,"del",c->argv[1],c->db->id);
    }

    addReplyLongLong(c,removed);
    unlockDb(c->db);
    if (expired) update_stats_add(c->vel->stats, expiredkeys, 1);
}

/* This is the semantic of this command:
 *  RPOPLPUSH srclist dstlist:
 *    IF LLEN(srclist) > 0
 *      element = RPOP srclist
 *      LPUSH dstlist element
 *      RETURN element
 *    ELSE
 *      RETURN nil
 *    END
 *  END
 *
 * The idea is to be able to get an element from a list in a reliable way
 * since the element is not just returned but pushed against another list
 * as well. This command was originally proposed by Ezra Zygmuntowicz.
 */

void rpoplpushHandlePush(client *c, robj *dstkey, robj *dstobj, robj *value) {
    /* Create the list if the key does not exist */
    if (!dstobj) {
        dstobj = createQuicklistObject();
        quicklistSetOptions(dstobj->ptr, server.list_max_ziplist_size,
                            server.list_compress_depth);
        dbAdd(c->db,dstkey,dstobj);
    }
    signalModifiedKey(c->db,dstkey);
    listTypePush(dstobj,value,LIST_HEAD);
    notifyKeyspaceEvent(NOTIFY_LIST,"lpush",dstkey,c->db->id);
    /* Always send the pushed value to the client. */
    addReplyBulk(c,value);
}

void rpoplpushCommand(client *c) {
    robj *sobj, *value;
    if ((sobj = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk,NULL)) == NULL ||
        checkType(c,sobj,OBJ_LIST)) return;

    if (listTypeLength(sobj) == 0) {
        /* This may only happen after loading very old RDB files. Recent
         * versions of Redis delete keys of empty lists. */
        addReply(c,shared.nullbulk);
    } else {
        robj *dobj = lookupKeyWrite(c->db,c->argv[2],NULL);
        robj *touchedkey = c->argv[1];

        if (dobj && checkType(c,dobj,OBJ_LIST)) return;
        value = listTypePop(sobj,LIST_TAIL);
        /* We saved touched key, and protect it, since rpoplpushHandlePush
         * may change the client command argument vector (it does not
         * currently). */
        incrRefCount(touchedkey);
        rpoplpushHandlePush(c,c->argv[2],dobj,value);

        /* listTypePop returns an object with its refcount incremented */
        decrRefCount(value);

        /* Delete the source list when it is empty */
        notifyKeyspaceEvent(NOTIFY_LIST,"rpop",touchedkey,c->db->id);
        if (listTypeLength(sobj) == 0) {
            dbDelete(c->db,touchedkey);
            notifyKeyspaceEvent(NOTIFY_GENERIC,"del",
                                touchedkey,c->db->id);
        }
        signalModifiedKey(c->db,touchedkey);
        decrRefCount(touchedkey);
        server.dirty++;
    }
}

/*-----------------------------------------------------------------------------
 * Blocking POP operations
 *----------------------------------------------------------------------------*/

/* This is how the current blocking POP works, we use BLPOP as example:
 * - If the user calls BLPOP and the key exists and contains a non empty list
 *   then LPOP is called instead. So BLPOP is semantically the same as LPOP
 *   if blocking is not required.
 * - If instead BLPOP is called and the key does not exists or the list is
 *   empty we need to block. In order to do so we remove the notification for
 *   new data to read in the client socket (so that we'll not serve new
 *   requests if the blocking request is not served). Also we put the client
 *   in a dictionary (db->blocking_keys) mapping keys to a list of clients
 *   blocking for this keys.
 * - If a PUSH operation against a key with blocked clients waiting is
 *   performed, we mark this key as "ready", and after the current command,
 *   MULTI/EXEC block, or script, is executed, we serve all the clients waiting
 *   for this list, from the one that blocked first, to the last, accordingly
 *   to the number of elements we have in the ready list.
 */

/* Set a client in blocking mode for the specified key, with the specified
 * timeout */
void blockForKeys(client *c, robj **keys, int numkeys, mstime_t timeout, robj *target) {
    dictEntry *de;
    dlist *l;
    int j;

    c->bpop.timeout = timeout;
    c->bpop.target = target;

    if (target != NULL) incrRefCount(target);

    for (j = 0; j < numkeys; j++) {
        /* If the key already exists in the dict ignore it. */
        if (dictAdd(c->bpop.keys,keys[j],NULL) != DICT_OK) continue;
        incrRefCount(keys[j]);

        /* And in the other "side", to map keys -> clients */
        de = dictFind(c->db->blocking_keys,keys[j]);
        if (de == NULL) {
            int retval;

            /* For every key we take a list of clients blocked for it */
            l = dlistCreate();
            retval = dictAdd(c->db->blocking_keys,keys[j],l);
            incrRefCount(keys[j]);
            serverAssertWithInfo(c,keys[j],retval == DICT_OK);
        } else {
            l = dictGetVal(de);
        }
        dlistAddNodeTail(l,c);
    }
    blockClient(c,BLOCKED_LIST);
}

/* Unblock a client that's waiting in a blocking operation such as BLPOP.
 * You should never call this function directly, but unblockClient() instead. */
void unblockClientWaitingData(client *c) {
    dictEntry *de;
    dictIterator *di;
    dlist *l;

    serverAssertWithInfo(c,NULL,dictSize(c->bpop.keys) != 0);
    di = dictGetIterator(c->bpop.keys);
    /* The client may wait for multiple keys, so unblock it for every key. */
    while((de = dictNext(di)) != NULL) {
        robj *key = dictGetKey(de);

        /* Remove this client from the list of clients waiting for this key. */
        l = dictFetchValue(c->db->blocking_keys,key);
        serverAssertWithInfo(c,key,l != NULL);
        dlistDelNode(l,dlistSearchKey(l,c));
        /* If the list is empty we need to remove it to avoid wasting memory */
        if (dlistLength(l) == 0)
            dictDelete(c->db->blocking_keys,key);
    }
    dictReleaseIterator(di);

    /* Cleanup the client structure */
    dictEmpty(c->bpop.keys,NULL);
    if (c->bpop.target) {
        decrRefCount(c->bpop.target);
        c->bpop.target = NULL;
    }
}

/* If the specified key has clients blocked waiting for list pushes, this
 * function will put the key reference into the server.ready_keys list.
 * Note that db->ready_keys is a hash table that allows us to avoid putting
 * the same key again and again in the list in case of multiple pushes
 * made by a script or in the context of MULTI/EXEC.
 *
 * The list will be finally processed by handleClientsBlockedOnLists() */
void signalListAsReady(redisDb *db, robj *key) {
    int ret;
    readyList *rl;

    /* No clients blocking for this key? No need to queue it. */
    if (dictFind(db->blocking_keys,key) == NULL) return;

    /* Key was already signaled? No need to queue it again. */
    if (dictFind(db->ready_keys,key) != NULL) return;

    /* Ok, we need to queue this key into server.ready_keys. */
    rl = dalloc(sizeof(*rl));
    rl->key = key;
    rl->db = db;
    incrRefCount(key);
    dlistAddNodeTail(server.ready_keys,rl);

    /* We also add the key in the db->ready_keys dictionary in order
     * to avoid adding it multiple times into a list with a simple O(1)
     * check. */
    incrRefCount(key);
    ret = dictAdd(db->ready_keys,key,NULL);
    ASSERT(ret == DICT_OK);
}

/* This is a helper function for handleClientsBlockedOnLists(). It's work
 * is to serve a specific client (receiver) that is blocked on 'key'
 * in the context of the specified 'db', doing the following:
 *
 * 1) Provide the client with the 'value' element.
 * 2) If the dstkey is not NULL (we are serving a BRPOPLPUSH) also push the
 *    'value' element on the destination list (the LPUSH side of the command).
 * 3) Propagate the resulting BRPOP, BLPOP and additional LPUSH if any into
 *    the AOF and replication channel.
 *
 * The argument 'where' is LIST_TAIL or LIST_HEAD, and indicates if the
 * 'value' element was popped fron the head (BLPOP) or tail (BRPOP) so that
 * we can propagate the command properly.
 *
 * The function returns VR_OK if we are able to serve the client, otherwise
 * VR_ERROR is returned to signal the caller that the list POP operation
 * should be undone as the client was not served: This only happens for
 * BRPOPLPUSH that fails to push the value to the destination key as it is
 * of the wrong type. */
int serveClientBlockedOnList(client *receiver, robj *key, robj *dstkey, redisDb *db, robj *value, int where)
{
    robj *argv[3];

    if (dstkey == NULL) {
        /* Propagate the [LR]POP operation. */
        argv[0] = (where == LIST_HEAD) ? shared.lpop :
                                          shared.rpop;
        argv[1] = key;
        propagate((where == LIST_HEAD) ?
            server.lpopCommand : server.rpopCommand,
            db->id,argv,2,PROPAGATE_AOF|PROPAGATE_REPL);

        /* BRPOP/BLPOP */
        addReplyMultiBulkLen(receiver,2);
        addReplyBulk(receiver,key);
        addReplyBulk(receiver,value);
    } else {
        /* BRPOPLPUSH */
        robj *dstobj =
            lookupKeyWrite(receiver->db,dstkey,NULL);
        if (!(dstobj &&
             checkType(receiver,dstobj,OBJ_LIST)))
        {
            /* Propagate the RPOP operation. */
            argv[0] = shared.rpop;
            argv[1] = key;
            propagate(server.rpopCommand,
                db->id,argv,2,
                PROPAGATE_AOF|
                PROPAGATE_REPL);
            rpoplpushHandlePush(receiver,dstkey,dstobj,
                value);
            /* Propagate the LPUSH operation. */
            argv[0] = shared.lpush;
            argv[1] = dstkey;
            argv[2] = value;
            propagate(server.lpushCommand,
                db->id,argv,3,
                PROPAGATE_AOF|
                PROPAGATE_REPL);
        } else {
            /* BRPOPLPUSH failed because of wrong
             * destination type. */
            return VR_ERROR;
        }
    }
    return VR_OK;
}

/* This function should be called by Redis every time a single command,
 * a MULTI/EXEC block, or a Lua script, terminated its execution after
 * being called by a client.
 *
 * All the keys with at least one client blocked that received at least
 * one new element via some PUSH operation are accumulated into
 * the server.ready_keys list. This function will run the list and will
 * serve clients accordingly. Note that the function will iterate again and
 * again as a result of serving BRPOPLPUSH we can have new blocking clients
 * to serve because of the PUSH side of BRPOPLPUSH. */
void handleClientsBlockedOnLists(void) {
    while(dlistLength(server.ready_keys) != 0) {
        dlist *l;

        /* Point server.ready_keys to a fresh list and save the current one
         * locally. This way as we run the old list we are free to call
         * signalListAsReady() that may push new elements in server.ready_keys
         * when handling clients blocked into BRPOPLPUSH. */
        l = server.ready_keys;
        server.ready_keys = dlistCreate();

        while(dlistLength(l) != 0) {
            dlistNode *ln = dlistFirst(l);
            readyList *rl = ln->value;

            /* First of all remove this key from db->ready_keys so that
             * we can safely call signalListAsReady() against this key. */
            dictDelete(rl->db->ready_keys,rl->key);

            /* If the key exists and it's a list, serve blocked clients
             * with data. */
            robj *o = lookupKeyWrite(rl->db,rl->key,NULL);
            if (o != NULL && o->type == OBJ_LIST) {
                dictEntry *de;

                /* We serve clients in the same order they blocked for
                 * this key, from the first blocked to the last. */
                de = dictFind(rl->db->blocking_keys,rl->key);
                if (de) {
                    dlist *clients = dictGetVal(de);
                    int numclients = dlistLength(clients);

                    while(numclients--) {
                        dlistNode *clientnode = dlistFirst(clients);
                        client *receiver = clientnode->value;
                        robj *dstkey = receiver->bpop.target;
                        int where = (receiver->lastcmd &&
                                     receiver->lastcmd->proc == blpopCommand) ?
                                    LIST_HEAD : LIST_TAIL;
                        robj *value = listTypePop(o,where);

                        if (value) {
                            /* Protect receiver->bpop.target, that will be
                             * freed by the next unblockClient()
                             * call. */
                            if (dstkey) incrRefCount(dstkey);
                            unblockClient(receiver);

                            if (serveClientBlockedOnList(receiver,
                                rl->key,dstkey,rl->db,value,
                                where) == VR_ERROR)
                            {
                                /* If we failed serving the client we need
                                 * to also undo the POP operation. */
                                    listTypePush(o,value,where);
                            }

                            if (dstkey) decrRefCount(dstkey);
                            decrRefCount(value);
                        } else {
                            break;
                        }
                    }
                }

                if (listTypeLength(o) == 0) {
                    dbDelete(rl->db,rl->key);
                }
                /* We don't call signalModifiedKey() as it was already called
                 * when an element was pushed on the list. */
            }

            /* Free this item. */
            decrRefCount(rl->key);
            dfree(rl);
            dlistDelNode(l,ln);
        }
        dlistRelease(l); /* We have the new list on place at this point. */
    }
}

/* Blocking RPOP/LPOP */
void blockingPopGenericCommand(client *c, int where) {
    robj *o;
    mstime_t timeout;
    int j;

    if (getTimeoutFromObjectOrReply(c,c->argv[c->argc-1],&timeout,UNIT_SECONDS)
        != VR_OK) return;

    for (j = 1; j < c->argc-1; j++) {
        o = lookupKeyWrite(c->db,c->argv[j],NULL);
        if (o != NULL) {
            if (o->type != OBJ_LIST) {
                addReply(c,shared.wrongtypeerr);
                return;
            } else {
                if (listTypeLength(o) != 0) {
                    /* Non empty list, this is like a non normal [LR]POP. */
                    char *event = (where == LIST_HEAD) ? "lpop" : "rpop";
                    robj *value = listTypePop(o,where);
                    ASSERT(value != NULL);

                    addReplyMultiBulkLen(c,2);
                    addReplyBulk(c,c->argv[j]);
                    addReplyBulk(c,value);
                    decrRefCount(value);
                    notifyKeyspaceEvent(NOTIFY_LIST,event,
                                        c->argv[j],c->db->id);
                    if (listTypeLength(o) == 0) {
                        dbDelete(c->db,c->argv[j]);
                        notifyKeyspaceEvent(NOTIFY_GENERIC,"del",
                                            c->argv[j],c->db->id);
                    }
                    signalModifiedKey(c->db,c->argv[j]);
                    server.dirty++;

                    /* Replicate it as an [LR]POP instead of B[LR]POP. */
                    rewriteClientCommandVector(c,2,
                        (where == LIST_HEAD) ? shared.lpop : shared.rpop,
                        c->argv[j]);
                    return;
                }
            }
        }
    }

    /* If we are inside a MULTI/EXEC and the list is empty the only thing
     * we can do is treating it as a timeout (even with timeout 0). */
    if (c->flags & CLIENT_MULTI) {
        addReply(c,shared.nullmultibulk);
        return;
    }

    /* If the list is empty or the key does not exists we must block */
    blockForKeys(c, c->argv + 1, c->argc - 2, timeout, NULL);
}

void blpopCommand(client *c) {
    blockingPopGenericCommand(c,LIST_HEAD);
}

void brpopCommand(client *c) {
    blockingPopGenericCommand(c,LIST_TAIL);
}

void brpoplpushCommand(client *c) {
    mstime_t timeout;

    if (getTimeoutFromObjectOrReply(c,c->argv[3],&timeout,UNIT_SECONDS)
        != VR_OK) return;

    robj *key = lookupKeyWrite(c->db, c->argv[1],NULL);

    if (key == NULL) {
        if (c->flags & CLIENT_MULTI) {
            /* Blocking against an empty list in a multi state
             * returns immediately. */
            addReply(c, shared.nullbulk);
        } else {
            /* The list is empty and the client blocks. */
            blockForKeys(c, c->argv + 1, 1, timeout, c->argv[2]);
        }
    } else {
        if (key->type != OBJ_LIST) {
            addReply(c, shared.wrongtypeerr);
        } else {
            /* The list exists and has elements, so
             * the regular rpoplpushCommand is executed. */
            serverAssertWithInfo(c,key,listTypeLength(key) > 0);
            rpoplpushCommand(c);
        }
    }
}


text:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

using Iwana.View;
using Iwana.Events;

public class IwPlayerView : MonoBehaviour, IIwView
{
	private IwEventDispatcher _dispatcher = null;
	public const string PLAYER_WRONG = "player_wrong";
	public const string PLAYER_IS_SAFE = "player_is_safe";
	public const string PLAYER_LOSES_LIFE = "player_loses_life";

	// Use this for initialization
	void Start ()
	{
		IwGameDemo.Instance.addView (this);
	}

	// Update is called once per frame
	void Update ()
	{
		if ( Input.GetKeyDown ( KeyCode.A ) )
		{
			// event dispatched when the player is in danger.
			_dispatcher.triggerEvent ( new IwEvent ( PLAYER_WRONG ) );
		}
		else if ( Input.GetKeyDown ( KeyCode.X ) )
		{
			// event dispatched when the player is safe.
			_dispatcher.triggerEvent ( new IwEvent ( PLAYER_IS_SAFE ) );
		}
		else if ( Input.GetKeyDown ( KeyCode.E ) )
		{
			// event dispatched when the player loses 1 life.
			_dispatcher.triggerEvent ( new IwEvent ( PLAYER_LOSES_LIFE ) );
		}
	}

	public void	initialize ()
	{}

	public void dispose ()
	{}

	public void notify ( IIwEvent evt )
	{}

	public string name
	{
		set { gameObject.name = value;}
		get { return gameObject.name; }
	}

	public IwEventDispatcher dispatcher { set { _dispatcher = value; } get { return _dispatcher; } }
	public List<string>  eventsToHand { get { return null; } }
}


text:
FROM python:3.6.2-alpine3.6

ENV PYTHONUNBUFFERED 1

ADD . /var/src
WORKDIR /var/src

ADD requirements.txt /tmp/requirements.txt
RUN pip3 install --no-cache-dir -r /tmp/requirements.txt

EXPOSE 8000

CMD ["python3", "manage.py", "migrate"]
CMD ["python3", "manage.py", "runserver", "0.0.0.0:8000"]


text:
"""Manipulate a TM1637 7-segment display."""

import math
import threading
from time import localtime, sleep

from . import config as cg
from .context import IO

IO.setwarnings(False)
IO.setmode(IO.BCM)

HexDigits = [0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d,
             0x07, 0x7f, 0x6f, 0x77, 0x7c, 0x39, 0x5e, 0x79, 0x71]

ADDR_AUTO = 0x40
ADDR_FIXED = 0x44
STARTADDR = 0xC0

class TM1637(object):
    """TM1637 7-Segment Display."""

    def __init__(self, clk, dio, brightness=1.0):
        """Initializer."""
        self.CLK = clk
        self.DIO = dio
        self.brightness = brightness

        self.double_point = False
        self.current_values = [0, 0, 0, 0]

        IO.setup(self.CLK, IO.OUT)
        IO.setup(self.DIO, IO.OUT)

    def cleanup(self):
        """Stop updating clock, turn off display, and cleanup GPIO."""
        self.stop_clock()
        self.clear()
        IO.cleanup()

    def clear(self):
        """Clear display."""
        b = self.brightness
        point = self.double_point
        self.brightness = 0
        self.double_point = False
        data = [0x7F, 0x7F, 0x7F, 0x7F]
        self.show(data)
        # Restore previous settings:
        self.brightness = b
        self.double_point = point

    def show(self, data):
        """Show data on display."""
        for i in range(0, 4):
            self.current_values[i] = data[i]

        self.start()
        self.write_byte(ADDR_AUTO)
        self.br()
        self.write_byte(STARTADDR)
        for i in range(0, 4):
            self.write_byte(self.coding(data[i]))
        self.br()
        self.write_byte(0x88 + int(self.brightness))
        self.stop()

    def set_digit(self, idx, data):
        """Set 7-segment digit by index [0, 3]."""
        assert not (idx < 0 or idx > 3), 'Index must be in (0,3). Args: ({},{})'.format(idx, data)

        self.current_values[idx] = data

        self.start()
        self.write_byte(ADDR_FIXED)
        self.br()
        self.write_byte(STARTADDR | idx)
        self.write_byte(self.coding(data))
        self.br()
        self.write_byte(0x88 + int(self.brightness))
        self.stop()

    def set_brightness(self, percent):
        """Set brightness in range 0-1."""
        max_brightness = 7.0
        brightness = math.ceil(max_brightness * percent)
        if (brightness < 0):
            brightness = 0
        if (self.brightness != brightness):
            self.brightness = brightness
            self.show(self.current_values)

    def show_colon(self, on):
        """Show or hide double point divider."""
        if (self.double_point != on):
            self.double_point = on
            self.show(self.current_values)

    def write_byte(self, data):
        """Write byte to display."""
        for i in range(0, 8):
            IO.output(self.CLK, IO.LOW)
            if (data & 0x01):
                IO.output(self.DIO, IO.HIGH)
            else:
                IO.output(self.DIO, IO.LOW)
            data = data >> 1
            IO.output(self.CLK, IO.HIGH)

        # Wait for ACK
        IO.output(self.CLK, IO.LOW)
        IO.output(self.DIO, IO.HIGH)
        IO.output(self.CLK, IO.HIGH)
        IO.setup(self.DIO, IO.IN)

        while IO.input(self.DIO):
            sleep(0.001)
            if (IO.input(self.DIO)):
                IO.setup(self.DIO, IO.OUT)
                IO.output(self.DIO, IO.LOW)
                IO.setup(self.DIO, IO.IN)
        IO.setup(self.DIO, IO.OUT)

    def start(self):
        """Send start signal to TM1637."""
        IO.output(self.CLK, IO.HIGH)
        IO.output(self.DIO, IO.HIGH)
        IO.output(self.DIO, IO.LOW)
        IO.output(self.CLK, IO.LOW)

    def stop(self):
        """Stop clock."""
        IO.output(self.CLK, IO.LOW)
        IO.output(self.DIO, IO.LOW)
        IO.output(self.CLK, IO.HIGH)
        IO.output(self.DIO, IO.HIGH)

    def br(self):
        """Terse break."""
        self.stop()
        self.start()

    def coding(self, data):
        """Set coding of display."""
        point_data = 0x80 if self.double_point else 0
        return 0 if data == 0x7F else HexDigits[data] + point_data

    def clock(self, military_time):
        """Clock thread script."""
        # Based on: https://github.com/johnlr/raspberrypi-tm1637
        self.show_colon(True)
        while (not self.__stop_event.is_set()):
            t = localtime()
            hour = t.tm_hour
            if not military_time:
                hour = 12 if (t.tm_hour % 12) == 0 else t.tm_hour % 12
            d0 = hour // 10 if hour // 10 else 0
            d1 = hour % 10
            d2 = t.tm_min // 10
            d3 = t.tm_min % 10
            digits = [d0, d1, d2, d3]
            self.show(digits)
            # # Optional visual feedback of running alarm:
            # print digits
            # for i in tqdm(range(60 - t.tm_sec)):
            for i in range(60 - t.tm_sec):
                if (not self.__stop_event.is_set()):
                    sleep(1)

    def start_clock(self, military_time=True):
        """Start clock thread."""
        # Stop event based on: http://stackoverflow.com/a/6524542/3219667
        self.__stop_event = threading.Event()
        self.__clock_thread = threading.Thread(target=self.clock, args=(military_time,))
        self.__clock_thread.daemon = True  # stops w/ main thread
        self.__clock_thread.start()

    def stop_clock(self):
        """Stop clock thread."""
        try:
            print('Attempting to stop live clock')
            self.__stop_event.set()
            self.clear()
        except AttributeError:
            print('No clock to close')

if __name__ == '__main__':
    """Confirm the display operation"""

    # Initialize the clock (GND, VCC=3.3V, Example Pins are DIO=20 and CLK=21)
    clock = cg.get_pin('7Segment', 'clk')
    digital = cg.get_pin('7Segment', 'dio')
    display = TM1637(CLK=clock, DIO=digital, brightness=1.0)
    print('clock', clock)
    print('digital', digital)

    display.clear()

    digits = [1, 2, 3, 4]
    display.show(digits)
    input('1234  - Working? (Press Key)')

    print('Updating one digit at a time:')
    display.clear()
    display.set_digit(1, 3)
    sleep(0.5)
    display.set_digit(2, 2)
    sleep(0.5)
    display.set_digit(3, 1)
    sleep(0.5)
    display.set_digit(0, 4)
    input('4321  - (Press Key)')

    print('Add double point\n')
    display.show_colon(True)
    sleep(0.2)
    print('Brightness Off')
    display.set_brightness(0)
    sleep(0.5)
    print('Full Brightness')
    display.set_brightness(1)
    sleep(0.5)
    print('30% Brightness')
    display.set_brightness(0.3)
    sleep(0.3)
    input('Start the clock?')

    display.start_clock(military_time=True)
    input('Stop the clock?')

    display.stop_clock()


text:
import React, {Component} from 'react';
import {connect} from 'react-redux';
import FbLogin from '../../components/shared/FbLogin';
import './NewPlPage.scss';
import * as LoginActions from '../../redux/loggedInUser';
import {get} from 'lodash';
import Spinner from '../../components/shared/Spinner';
import PlaylistForm from './playlistForm';
import PlaylistPreview from './playlistPreview';
class NewPlPage extends Component {

  constructor() {
    super()
    this.state = {};
    this.loadPreview = this.loadPreview.bind(this);
  }

  componentWillMount() {
    this.props.LoginRequest();
  }

  loadPreview(previewVideoId) {
    this.setState(Object.assign({}, this.state, { previewVideoId }))
  }

  render() {
    const {loggedInUser, loginPending} = this.props;
    const loginButton = (<FbLogin
          callback={response => this
          .props
          .LoginSuccess(response)}/>)
    const isReady = loggedInUser;
    return (

        {!loggedInUser && !loginPending && loginButton }
        {this.props.loginPending && <Spinner/>}
        {
          isReady &&

            <PlaylistForm onLoadPreview={ this.loadPreview } />
            <PlaylistPreview previewVideoId={this.state.previewVideoId} />

        }

    )
  }
}

const mapStateToProps = ({loggedInUser}) => ({
  loginPending: get(loggedInUser, 'pending'),
  loggedInUser: get(loggedInUser, 'data')
});

export default connect(mapStateToProps, LoginActions)(NewPlPage);


text:
package org.apache.ambari.server.stack.upgrade.orchestrate;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.ambari.server.stack.HostsType;
import org.apache.ambari.server.stack.upgrade.ExecuteHostType;
import org.apache.ambari.server.stack.upgrade.ExecuteTask;
import org.apache.ambari.server.stack.upgrade.Task;
import org.apache.ambari.server.utils.StageUtils;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Generates a collection of tasks that need to run on a set of hosts during an upgarde.
 */
public class TaskWrapperBuilder {

  private static final Logger LOG = LoggerFactory.getLogger(TaskWrapperBuilder.class);

  /**
   * Creates a collection of task wrappers based on the set of hosts they are allowed to run on
   * by analyzing the "hosts" attribute of any ExecuteTask objects.
   *
   * @param service the service name for the tasks
   * @param component the component name for the tasks
   * @param hostsType the collection of sets along with their status
   * @param tasks collection of tasks
   * @param params additional parameters
   *
   * @return the task wrappers, one for each task that is passed with {@code tasks}
   */
  public static List<TaskWrapper> getTaskList(String service, String component, HostsType hostsType, List<Task> tasks, Map<String, String> params) {
    // Ok if Ambari Server is not part of the cluster hosts since this is only used in the calculation of how many batches
    // to create.
    String ambariServerHostname = StageUtils.getHostName();

    List<TaskWrapper> collection = new ArrayList<>();
    for (Task t : tasks) {

      // only add the server-side task if there are actual hosts for the service/component
      if (t.getType().isServerAction() && CollectionUtils.isNotEmpty(hostsType.getHosts())) {
        collection.add(new TaskWrapper(service, component, Collections.singleton(ambariServerHostname), params, t));
        continue;
      }

      if (t.getType().equals(Task.Type.EXECUTE)) {
        ExecuteTask et = (ExecuteTask) t;
        if (et.hosts == ExecuteHostType.MASTER) {
          if (hostsType.hasMasters()) {
            collection.add(new TaskWrapper(service, component, hostsType.getMasters(), params, t));
            continue;
          } else {
            LOG.error(MessageFormat.format("Found an Execute task for {0} and {1} meant to run on a master but could not find any masters to run on. Skipping this task.", service, component));
            continue;
          }
        }
        // Pick a random host.
        if (et.hosts == ExecuteHostType.ANY) {
          if (!hostsType.getHosts().isEmpty()) {
            collection.add(new TaskWrapper(service, component, Collections.singleton(hostsType.getHosts().iterator().next()), params, t));
            continue;
          } else {
            LOG.error(MessageFormat.format("Found an Execute task for {0} and {1} meant to run on any host but could not find host to run on. Skipping this task.", service, component));
            continue;
          }
        }

        // Pick the first host sorted alphabetically (case insensitive).
        if (et.hosts == ExecuteHostType.FIRST) {
          if (!hostsType.getHosts().isEmpty()) {
            List<String> sortedHosts = new ArrayList<>(hostsType.getHosts());
            Collections.sort(sortedHosts, String.CASE_INSENSITIVE_ORDER);
            collection.add(new TaskWrapper(service, component, Collections.singleton(sortedHosts.get(0)), params, t));
            continue;
          } else {
            LOG.error(MessageFormat.format("Found an Execute task for {0} and {1} meant to run on the first host sorted alphabetically but could not find host to run on. Skipping this task.", service, component));
            continue;
          }
        }
        // Otherwise, meant to run on ALL hosts.
      }

      collection.add(new TaskWrapper(service, component, hostsType.getHosts(), params, t));
    }

    return collection;
  }

  /**
   * Given a collection of tasks, get the union of the hosts.
   * @param tasks Collection of tasks
   * @return Returns the union of the hosts scheduled to perform the tasks.
   */
  public static Set<String> getEffectiveHosts(List<TaskWrapper> tasks) {
    Set<String> effectiveHosts = new HashSet<>();
    for(TaskWrapper t : tasks) {
      effectiveHosts.addAll(t.getHosts());
    }
    return effectiveHosts;
  }
}


text:
import {
  HOME_SHOW_DEMO_ALERT,
} from './constants';

export function showDemoAlert() {
  return {
    type: HOME_SHOW_DEMO_ALERT,
  };
}

export function reducer(state, action) {
  switch (action.type) {
    case HOME_SHOW_DEMO_ALERT:
      return {
        ...state,
        demoAlertVisible: true,
      };

    default:
      return state;
  }
}


text:
package org.misumirize.hackernews.app;

import com.squareup.okhttp.OkHttpClient;
import dagger.Module;
import dagger.Provides;
import retrofit.client.Client;
import retrofit.client.OkClient;

@Module
public class AppModule {

    @Provides
    OkHttpClient provideHttpClient() {
        return new OkHttpClient();
    }

    @Provides
    Client provideRetrofitClient(OkHttpClient httpClient) {
        return new OkClient(httpClient);
    }

    @Provides
    HackerNewsService provideHackerNewsService(Client client) {
        return new HackerNewsService(client);
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Usnea 2: 436 (1937)

#### Original name
Usnea contexta Motyka

### Remarks
null


text:
import { moduleForModel, test } from 'ember-qunit';

moduleForModel('ticket', 'Unit | Model | ticket', {
  needs: ['model:event']
});

test('it exists', function(assert) {
  let model = this.subject();
  assert.ok(!!model);
});


text:
from azure.identity import DefaultAzureCredential
from azure.mgmt.vmwarecloudsimple import VMwareCloudSimple

"""
# PREREQUISITES
    pip install azure-identity
    pip install azure-mgmt-vmwarecloudsimple
# USAGE
    python list_rg_dedicated_cloud_services.py

    Before run the sample, please set the values of the client ID, tenant ID and client secret
    of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
    AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
    https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""

def main():
    client = VMwareCloudSimple(
        credential=DefaultAzureCredential(),
        subscription_id="{subscription-id}",
    )

    response = client.dedicated_cloud_services.list_by_resource_group(
        resource_group_name="myResourceGroup",
    )
    for item in response:
        print(item)

# x-ms-original-file: specification/vmwarecloudsimple/resource-manager/Microsoft.VMwareCloudSimple/stable/2019-04-01/examples/ListRGDedicatedCloudServices.json
if __name__ == "__main__":
    main()