text:
var ui = (function () {

var exports = {};

var actively_scrolling = false;

exports.have_scrolled_away_from_top = true;

exports.actively_scrolling = function () {
    return actively_scrolling;
};

// What, if anything, obscures the home tab?
exports.home_tab_obscured = function () {
    if ($('.modal:visible').length > 0) {
        return 'modal';
    }
    if (! $('#home').hasClass('active')) {
        return 'other_tab';
    }
    return false;
};

exports.change_tab_to = function (tabname) {
    $('#gear-menu a[href="' + tabname + '"]').tab('show');
};

exports.focus_on = function (field_id) {
    // Call after autocompleting on a field, to advance the focus to
    // the next input field.

    // Bootstrap's typeahead does not expose a callback for when an
    // autocomplete selection has been made, so we have to do this
    // manually.
    $("#" + field_id).focus();
};

exports.blur_active_element = function () {
    // this blurs anything that may perhaps be actively focused on.
    document.activeElement.blur();
};

function amount_to_paginate() {
    // Some day we might have separate versions of this function
    // for Page Up vs. Page Down, but for now it's the same
    // strategy in either direction.
    var info = viewport.message_viewport_info();
    var page_size = info.visible_height;

    // We don't want to page up a full page, because Zulip users
    // are especially worried about missing messages, so we want
    // a little bit of the old page to stay on the screen.  The
    // value chosen here is roughly 2 or 3 lines of text, but there
    // is nothing sacred about it, and somebody more anal than me
    // might wish to tie this to the size of some particular DOM
    // element.
    var overlap_amount = 55;

    var delta = page_size - overlap_amount;

    // If the user has shrunk their browser a whole lot, pagination
    // is not going to be very pleasant, but we can at least
    // ensure they go in the right direction.
    if (delta < 1) {
        delta = 1;
    }

    return delta;
}

exports.page_up_the_right_amount = function () {
    // This function's job is to scroll up the right amount,
    // after the user hits Page Up.  We do this ourselves
    // because we can't rely on the browser to account for certain
    // page elements, like the compose box, that sit in fixed
    // positions above the message pane.  For other scrolling
    // related adjustements, try to make those happen in the
    // scroll handlers, not here.
    var delta = amount_to_paginate();
    viewport.scrollTop(viewport.scrollTop() - delta);
};

exports.page_down_the_right_amount = function () {
    // see also: page_up_the_right_amount
    var delta = amount_to_paginate();
    viewport.scrollTop(viewport.scrollTop() + delta);
};

exports.replace_emoji_with_text = function (element) {
    element.find(".emoji").replaceWith(function () {
        return $(this).attr("alt");
    });
};

/* We use 'visibility' rather than 'display' and jQuery's show() / hide(),
   because we want to reserve space for the email address.  This avoids
   things jumping around slightly when the email address is shown. */

var current_message_hover;
function message_unhover() {
    if (current_message_hover === undefined) {
        return;
    }
    current_message_hover.find('span.edit_content').html("");
    current_message_hover.removeClass('message_hovered');
    current_message_hover = undefined;
}

function message_hover(message_row) {
    var message;

    var id = parseInt(message_row.attr("zid"), 10);
    if (current_message_hover && message_row && current_message_hover.attr("zid") === message_row.attr("zid")) {
        return;
    }
    // Don't allow on-hover editing for local-only messages
    if (message_row.hasClass('local')) {
        return;
    }
    message = current_msg_list.get(rows.id(message_row));
    message_unhover();
    message_row.addClass('message_hovered');
    current_message_hover = message_row;

    if (!message.sent_by_me) {
        // The actions and reactions icon hover logic is handled entirely by CSS
        return;
    }

    // But the message edit hover icon is determined by whether the message is still editablex
    if ((message_edit.get_editability(message) === message_edit.editability_types.FULL) &&
        !message.status_message) {
        message_row.find(".edit_content").html('');
    } else {
        message_row.find(".edit_content").html('');
    }
}

/* Arguments used in the report_* functions are,
   response- response that we want to display
   status_box- element being used to display the response
   cls- class that we want to add/remove to/from the status_box
   type- used to define more complex logic for special cases (currently being
         used only for subscriptions-status) */

exports.report_message = function (response, status_box, cls, type) {
    if (cls === undefined) {
        cls = 'alert';
    }

    if (type === undefined) {
        type = ' ';
    }

    if (type === 'subscriptions-status') {
        status_box.removeClass(status_classes).addClass(cls).children('#response')
              .text(response).stop(true).fadeTo(0, 1);
    } else {
        status_box.removeClass(status_classes).addClass(cls)
              .text(response).stop(true).fadeTo(0, 1);
    }

    status_box.show();
};

exports.report_error = function (response, xhr, status_box, type) {
    if (xhr && xhr.status.toString().charAt(0) === "4") {
        // Only display the error response for 4XX, where we've crafted
        // a nice response.
        response += ": " + JSON.parse(xhr.responseText).msg;
    }

    ui.report_message(response, status_box, 'alert-error', type);
};

exports.report_success = function (response, status_box, type) {
    ui.report_message(response, status_box, 'alert-success', type);
};

function update_message_in_all_views(message_id, callback) {
    _.each([message_list.all, home_msg_list, message_list.narrowed], function (list) {
        if (list === undefined) {
            return;
        }
        var row = list.get_row(message_id);
        if (row === undefined) {
            // The row may not exist, e.g. if you do an action on a message in
            // a narrowed view
            return;
        }
        callback(row);
    });
}

exports.find_message = function (message_id) {
    // Try to find the message object. It might be in the narrow list
    // (if it was loaded when narrowed), or only in the message_list.all
    // (if received from the server while in a different narrow)
    var message;
    _.each([message_list.all, home_msg_list, message_list.narrowed], function (msg_list) {
        if (msg_list !== undefined && message === undefined) {
            message = msg_list.get(message_id);
        }
    });
    return message;
};

exports.update_starred = function (message_id, starred) {
    // Update the message object pointed to by the various message
    // lists.
    var message = exports.find_message(message_id);

    // If it isn't cached in the browser, no need to do anything
    if (message === undefined) {
        return;
    }

    unread.mark_message_as_read(message);

    message.starred = starred;

    // Avoid a full re-render, but update the star in each message
    // table in which it is visible.
    update_message_in_all_views(message_id, function update_row(row) {
        var elt = row.find(".message_star");
        if (starred) {
            elt.addClass("icon-vector-star").removeClass("icon-vector-star-empty").removeClass("empty-star");
        } else {
            elt.removeClass("icon-vector-star").addClass("icon-vector-star-empty").addClass("empty-star");
        }
        var title_state = message.starred ? "Unstar" : "Star";
        elt.attr("title", title_state + " this message");
    });
};

var local_messages_to_show = [];
var show_message_timestamps = _.throttle(function () {
    _.each(local_messages_to_show, function (message_id) {
        update_message_in_all_views(message_id, function update_row(row) {
            row.find('.message_time').toggleClass('notvisible', false);
        });
    });
    local_messages_to_show = [];
}, 100);

exports.show_local_message_arrived = function (message_id) {
    local_messages_to_show.push(message_id);
    show_message_timestamps();
};

exports.show_message_failed = function (message_id, failed_msg) {
    // Failed to send message, so display inline retry/cancel
    update_message_in_all_views(message_id, function update_row(row) {
        var failed_div = row.find('.message_failed');
        failed_div.toggleClass('notvisible', false);
        failed_div.find('.failed_text').attr('title', failed_msg);
    });
};

exports.show_failed_message_success = function (message_id) {
    // Previously failed message succeeded
    update_message_in_all_views(message_id, function update_row(row) {
        row.find('.message_failed').toggleClass('notvisible', true);
    });
};

exports.lightbox = function (data) {
    switch (data.type) {
        case "photo":
            exports.lightbox_photo(data.image, data.user);
            break;
        case "youtube":
            exports.youtube_video(data.id);
            break;
        default:
            break;
    }

    $("#overlay").addClass("show");
    popovers.hide_all();
};

exports.lightbox_photo = function (image, user) {
    // image should be an Image Object in JavaScript.
    var url = $(image).attr("src");
    var title = $(image).parent().attr("title");

    $("#overlay .player-container").hide();
    $("#overlay .image-actions, .image-description, .download").show();

    var img = new Image();
    img.src = url;
    $("#overlay .image-preview").html("").show()
        .append(img);

    $(".image-description .title").text(title || "N/A");
    $(".image-description .user").text(user);

    $(".image-actions .open, .image-actions .download").attr("href", url);
};

exports.exit_lightbox_photo = function () {
    $("#overlay").removeClass("show");
    $(".player-container iframe").remove();
    document.activeElement.blur();
};

exports.youtube_video = function (id) {
    $("#overlay .image-preview, .image-description, .download").hide();

    var iframe = document.createElement("iframe");
    iframe.width = window.innerWidth;
    iframe.height = window.innerWidth * 0.5625;
    iframe.src = "https://www.youtube.com/embed/" + id;
    iframe.setAttribute("frameborder", 0);
    iframe.setAttribute("allowfullscreen", true);

    $("#overlay .player-container").html("").show().append(iframe);
    $(".image-actions .open").attr("href", "https://youtu.be/" + id);
};
// k3O01EfM5fU

var loading_more_messages_indicator_showing = false;
exports.show_loading_more_messages_indicator = function () {
    if (! loading_more_messages_indicator_showing) {
        loading.make_indicator($('#loading_more_messages_indicator'),
                                    {abs_positioned: true});
        loading_more_messages_indicator_showing = true;
        floating_recipient_bar.hide();
    }
};

exports.hide_loading_more_messages_indicator = function () {
    if (loading_more_messages_indicator_showing) {
        loading.destroy_indicator($("#loading_more_messages_indicator"));
        loading_more_messages_indicator_showing = false;
    }
};

/* EXPERIMENTS */

/* This method allows an advanced user to use the console
 * to switch the application to span full width of the browser.
 */
exports.switchToFullWidth = function () {
    $("#full-width-style").remove();
    $('head').append('');
    return ("Switched to full width");
};

/* END OF EXPERIMENTS */

$(function () {
    var throttled_mousewheelhandler = $.throttle(50, function (e, delta) {
        // Most of the mouse wheel's work will be handled by the
        // scroll handler, but when we're at the top or bottom of the
        // page, the pointer may still need to move.

        if (delta > 0) {
            if (viewport.at_top()) {
                navigate.up();
            }
        } else if (delta < 0) {
            if (viewport.at_bottom()) {
                navigate.down();
            }
        }

        viewport.last_movement_direction = delta;
    });

    viewport.message_pane.mousewheel(function (e) {
        // Ignore mousewheel events if a modal is visible.  It's weird if the
        // user can scroll the main view by wheeling over the grayed-out area.
        // Similarly, ignore events on settings page etc.
        //
        // We don't handle the compose box here, because it *should* work to
        // select the compose box and then wheel over the message stream.
        var obscured = exports.home_tab_obscured();
        if (!obscured) {
            throttled_mousewheelhandler(e, e.deltaY);
        } else if (obscured === 'modal') {
            // The modal itself has a handler invoked before this one (see below).
            // preventDefault here so that the tab behind the modal doesn't scroll.
            //
            // This needs to include the events that would be ignored by throttling.
            // That's why this code can't be moved into throttled_mousewheelhandler.
            e.preventDefault();
        }
        // If on another tab, we neither handle the event nor preventDefault, allowing
        // the tab to scroll normally.
    });

    $(window).resize($.throttle(50, resize.handler));

    // Scrolling in modals, input boxes, and other elements that
    // explicitly scroll should not scroll the main view.  Stop
    // propagation in all cases.  Also, ignore the event if the
    // element is already at the top or bottom.  Otherwise we get a
    // new scroll event on the parent (?).
    $('.modal-body, .scrolling_list, input, textarea').mousewheel(function (e) {
        var self = $(this);
        var scroll = self.scrollTop();

        // The -1 fudge factor is important here due to rounding errors.  Better
        // to err on the side of not scrolling.
        var max_scroll = this.scrollHeight - self.innerHeight() - 1;

        e.stopPropagation();
        if (   ((e.deltaY > 0) && (scroll <= 0))
            || ((e.deltaY < 0) && (scroll >= max_scroll))) {
            e.preventDefault();
        }
    });

    // Override the #compose mousewheel prevention below just for the emoji box
    $('.emoji_popover').mousewheel(function (e) {
        e.stopPropagation();
    });

    // Ignore wheel events in the compose area which weren't already handled above.
    $('#compose').mousewheel(function (e) {
        e.stopPropagation();
        e.preventDefault();
    });

    // A little hackish, because it doesn't seem to totally get us the
    // exact right width for the floating_recipient_bar and compose
    // box, but, close enough for now.
    resize.handler();

    if (!page_params.left_side_userlist) {
        $("#navbar-buttons").addClass("right-userlist");
    }

    $("#main_div").on("mouseover", ".message_row", function () {
        var row = $(this).closest(".message_row");
        message_hover(row);
    });

    $("#main_div").on("mouseleave", ".message_row", function () {
        message_unhover();
    });

    $("#main_div").on("mouseover", ".message_sender", function () {
        var row = $(this).closest(".message_row");
        row.addClass("sender_name_hovered");
    });

    $("#main_div").on("mouseout", ".message_sender", function () {
        var row = $(this).closest(".message_row");
        row.removeClass("sender_name_hovered");
    });

    $("#subscriptions_table").on("mouseover", ".subscription_header", function () {
        $(this).addClass("active");
    });

    $("#subscriptions_table").on("mouseout", ".subscription_header", function () {
        $(this).removeClass("active");
    });

    $("#stream").on('blur', function () { compose.decorate_stream_bar(this.value); });

    $(window).on('blur', function () {
        $(document.body).addClass('window_blurred');
    });

    $(window).on('focus', function () {
        $(document.body).removeClass('window_blurred');
    });

    $(document).on('message_selected.zulip', function (event) {
        if (current_msg_list !== event.msg_list) {
            return;
        }
        if (event.id === -1) {
            // If the message list is empty, don't do anything
            return;
        }
        var row = event.msg_list.get_row(event.id);
        $('.selected_message').removeClass('selected_message');
        row.addClass('selected_message');

        if (event.then_scroll) {
            if (row.length === 0) {
                var row_from_dom = current_msg_list.get_row(event.id);
                blueslip.debug("message_selected missing selected row", {
                    previously_selected: event.previously_selected,
                    selected_id: event.id,
                    selected_idx: event.msg_list.selected_idx(),
                    selected_idx_exact: event.msg_list._items.indexOf(event.msg_list.get(event.id)),
                    render_start: event.msg_list.view._render_win_start,
                    render_end: event.msg_list.view._render_win_end,
                    selected_id_from_idx: event.msg_list._items[event.msg_list.selected_idx()].id,
                    msg_list_sorted: _.isEqual(
                        _.pluck(event.msg_list._items, 'id'),
                        _.chain(current_msg_list._items).pluck('id').clone().value().sort()
                    ),
                    found_in_dom: row_from_dom.length,
                });
            }
            if (event.target_scroll_offset !== undefined) {
                viewport.set_message_offset(event.target_scroll_offset);
            } else {
                // Scroll to place the message within the current view;
                // but if this is the initial placement of the pointer,
                // just place it in the very center
                viewport.recenter_view(row, {from_scroll: event.from_scroll,
                                    force_center: event.previously_selected === -1});
            }
        }
    });

    $("#main_div").on("mouseenter", ".message_time", function (e) {
        var time_elem = $(e.target);
        var row = time_elem.closest(".message_row");
        var message = current_msg_list.get(rows.id(row));
        timerender.set_full_datetime(message, time_elem);
    });

    $('#streams_header h4').tooltip({ placement: 'right',
                                       animation: false });

    $('#streams_header i[data-toggle="tooltip"]').tooltip({ placement: 'left',
                                       animation: false });

    $('.message_failed i[data-toggle="tooltip"]').tooltip();

    if (!page_params.realm_allow_message_editing) {
        $("#edit-message-hotkey-help").hide();
    }

    if (page_params.presence_disabled) {
        $("#user-list").hide();
        $("#group-pm-list").hide();
    }

    if (feature_flags.full_width) {
        exports.switchToFullWidth();
    }

    // initialize other stuff
    reload.initialize();
    composebox_typeahead.initialize();
    search.initialize();
    tutorial.initialize();
    notifications.initialize();
    gear_menu.initialize();
    hashchange.initialize();
    invite.initialize();
    pointer.initialize();
    unread.initialize();
    activity.initialize();
    emoji.initialize();
});

function scroll_finished() {
    actively_scrolling = false;

    if ($('#home').hasClass('active')) {
        if (!pointer.suppress_scroll_pointer_update) {
            pointer.keep_pointer_in_view();
        } else {
            pointer.suppress_scroll_pointer_update = false;
        }
        floating_recipient_bar.update();
        if (viewport.scrollTop() === 0 &&
            ui.have_scrolled_away_from_top) {
            ui.have_scrolled_away_from_top = false;
            message_store.load_more_messages(current_msg_list);
        } else if (!ui.have_scrolled_away_from_top) {
            ui.have_scrolled_away_from_top = true;
        }
        // When the window scrolls, it may cause some messages to
        // enter the screen and become read.  Calling
        // unread.process_visible will update necessary
        // data structures and DOM elements.
        setTimeout(unread.process_visible, 0);
    }
}

var scroll_timer;
function scroll_finish() {
    actively_scrolling = true;
    clearTimeout(scroll_timer);
    scroll_timer = setTimeout(scroll_finished, 100);
}

// Save the compose content cursor position and restore when we
// shift-tab back in (see hotkey.js).
var saved_compose_cursor = 0;

$(function () {
    viewport.message_pane.scroll($.throttle(50, function () {
        unread.process_visible();
        scroll_finish();
    }));

    $('#new_message_content').blur(function () {
        saved_compose_cursor = $(this).caret();
    });
});

exports.restore_compose_cursor = function () {
    $('#new_message_content')
        .focus()
        .caret(saved_compose_cursor);
};

$(function () {
    if (window.bridge !== undefined) {
        // Disable "spellchecking" in our desktop app. The "spellchecking"
        // in our Mac app is actually autocorrect, and frustrates our
        // users.
        $("#new_message_content").attr('spellcheck', 'false');
        // Modify the zephyr mirroring error message in our desktop
        // app, since it doesn't work from the desktop version.
        $("#webathena_login_menu").hide();
        $("#normal-zephyr-mirror-error-text").addClass("notdisplayed");
        $("#desktop-zephyr-mirror-error-text").removeClass("notdisplayed");
    }
});

return exports;
}());

if (typeof module !== 'undefined') {
    module.exports = ui;
}


text:
"""
This module contains classes which help you work with Redis queues.
"""

from logutils.queue import QueueHandler, QueueListener
try:
    import cPickle as pickle
except ImportError:
    import pickle

class RedisQueueHandler(QueueHandler):
    """
    A QueueHandler implementation which pushes pickled
    records to a Redis queue using a specified key.

    :param key: The key to use for the queue. Defaults to
                "python.logging".
    :param redis: If specified, this instance is used to
                  communicate with a Redis instance.
    :param limit: If specified, the queue is restricted to
                  have only this many elements.
    """
    def __init__(self, key='python.logging', redis=None, limit=0):
        if redis is None:
            from redis import Redis
            redis = Redis()
        self.key = key
        assert limit >= 0
        self.limit = limit
        QueueHandler.__init__(self, redis)

    def enqueue(self, record):
        s = pickle.dumps(vars(record))
        self.queue.rpush(self.key, s)
        if self.limit:
            self.queue.ltrim(self.key, -self.limit, -1)

class RedisQueueListener(QueueListener):
    """
    A QueueListener implementation which fetches pickled
    records from a Redis queue using a specified key.

    :param key: The key to use for the queue. Defaults to
                "python.logging".
    :param redis: If specified, this instance is used to
                  communicate with a Redis instance.
    """
    def __init__(self, *handlers, **kwargs):
        redis = kwargs.get('redis')
        if redis is None:
            from redis import Redis
            redis = Redis()
        self.key = kwargs.get('key', 'python.logging')
        QueueListener.__init__(self, redis, *handlers)

    def dequeue(self, block):
        """
        Dequeue and return a record.
        """
        if block:
            s = self.queue.blpop(self.key)[1]
        else:
            s = self.queue.lpop(self.key)
        if not s:
            record = None
        else:
            record = pickle.loads(s)
        return record

    def enqueue_sentinel(self):
        self.queue.rpush(self.key, '')

redpajama_set_name: RedPajamaGithub


text:
package org.c4sg.service;

import java.util.List;
import org.c4sg.dto.SkillDTO;

public interface SkillService {
    List<SkillDTO> findSkills();
    List<SkillDTO> findSkillsbyCount();
    List<String> findSkillsForUser(Integer id);
    List<String> findSkillsForProject(Integer id);
    void saveSkillsForUser(Integer id, List<String> skillsList);
    void saveSkillsForProject(Integer id, List<String> skillsList);
}


text:
\hypertarget{classSDDistributed}{}\section{S\+D\+Distributed Class Reference}
\label{classSDDistributed}\index{S\+D\+Distributed@{S\+D\+Distributed}}

Subdomain on distributed memory (S\+DD)

{\ttfamily \#include $<$S\+D\+Distributed.\+hpp$>$}

\subsection*{Public Member Functions}
\begin{DoxyCompactItemize}
\item
\mbox{\hyperlink{classSDDistributed_a07332d418da104a969360c6c671feef4}{S\+D\+Distributed}} (unsigned int sizeX, unsigned int sizeY, int B\+L\+\_\+X, int B\+L\+\_\+Y, unsigned int boundary\+Thickness, unsigned int neighbour\+Hood, unsigned int id, unsigned int n\+S\+DD)
\begin{DoxyCompactList}\small\item\em Constructor. \end{DoxyCompactList}\item
\mbox{\Hypertarget{classSDDistributed_a1af9779279416a7bd519747e3b029124}\label{classSDDistributed_a1af9779279416a7bd519747e3b029124}}
\mbox{\hyperlink{classSDDistributed_a1af9779279416a7bd519747e3b029124}{$\sim$\+S\+D\+Distributed}} ()
\begin{DoxyCompactList}\small\item\em Destructor. \end{DoxyCompactList}\item
\mbox{\Hypertarget{classSDDistributed_a3617b83f6f2a6368b1f17c938d921e0a}\label{classSDDistributed_a3617b83f6f2a6368b1f17c938d921e0a}}
std\+::map$<$ std\+::pair$<$ int, int $>$, std\+::pair$<$ int, std\+::pair$<$ int, int $>$ $>$ $>$ \mbox{\hyperlink{classSDDistributed_a3617b83f6f2a6368b1f17c938d921e0a}{get\+Boundary\+Map}} ()
\begin{DoxyCompactList}\small\item\em Returns map between coords on S\+DD and \char`\"{}real cell\char`\"{} on neighbour S\+DD / boundary side. \end{DoxyCompactList}\item
\mbox{\hyperlink{classQuantity}{Quantity}}$<$ real $>$ $\ast$ \mbox{\hyperlink{classSDDistributed_a14f296606ff1afa1e4878fa6c4928afc}{get\+Quantity}} (std\+::string name)
\begin{DoxyCompactList}\small\item\em Gets physical quantity previously added with method add\+Quantity. \end{DoxyCompactList}\item
const std\+::vector$<$ \mbox{\hyperlink{classSDShared}{S\+D\+Shared}} $>$ \& \mbox{\hyperlink{classSDDistributed_a9afba0607b6012a0e446b95251559f5d}{get\+S\+DS}} () const
\begin{DoxyCompactList}\small\item\em Gets all S\+DS on S\+DD for a read-\/only access. \end{DoxyCompactList}\item
unsigned int \mbox{\hyperlink{classSDDistributed_a567b9535558271515166ce7ebd3f6c29}{get\+SizeX}} () const
\begin{DoxyCompactList}\small\item\em Gets width of S\+DD, excluding boundary thickness. \end{DoxyCompactList}\item
unsigned int \mbox{\hyperlink{classSDDistributed_a9bf0049f4c95513b4d9c9a9bac0f6eb4}{get\+SizeY}} () const
\begin{DoxyCompactList}\small\item\em Gets height of S\+DD, excluding boundary thickness. \end{DoxyCompactList}\item
unsigned int \mbox{\hyperlink{classSDDistributed_a0ab71d942dca319b739390055942a96a}{get\+Id}} () const
\begin{DoxyCompactList}\small\item\em Gets unique id of S\+DD. \end{DoxyCompactList}\item
\mbox{\Hypertarget{classSDDistributed_a8a7bf55ebead74e2c234fe21ebc02475}\label{classSDDistributed_a8a7bf55ebead74e2c234fe21ebc02475}}
unsigned int {\bfseries get\+Number\+Neighbour\+S\+D\+Ds} () const
\item
\mbox{\Hypertarget{classSDDistributed_a9fe968b07308e670e2bc53597d2d139f}\label{classSDDistributed_a9fe968b07308e670e2bc53597d2d139f}}
unsigned int {\bfseries get\+Number\+Overlap\+Cells} () const
\item
\mbox{\Hypertarget{classSDDistributed_ad8247f4958820ef02d97e22059ee7f94}\label{classSDDistributed_ad8247f4958820ef02d97e22059ee7f94}}
unsigned int {\bfseries get\+Number\+Boundary\+Cells} () const
\item
const std\+::map$<$ std\+::pair$<$ int, int $>$, std\+::pair$<$ int, std\+::pair$<$ int, int $>$ $>$ $>$ \& \mbox{\hyperlink{classSDDistributed_a2a2e744edad326561e3555a352ce4a0a}{get\+Overlap\+Cell\+Map}} () const
\begin{DoxyCompactList}\small\item\em Returns mapping between overlap cells and corresponding \char`\"{}real cells\char`\"{} on other S\+D\+Ds. \end{DoxyCompactList}\item
void \mbox{\hyperlink{classSDDistributed_ae9d8db949ba9da0a95407e1066df17b9}{set\+Value}} (std\+::string quantity\+Name, int coordX, int coordY, real value)
\begin{DoxyCompactList}\small\item\em Manually set the value on a coordinate, without having to get the quantity. \end{DoxyCompactList}\item
real \mbox{\hyperlink{classSDDistributed_a1db6a1bf2f8781b9e4b12be99b4bf9c4}{get\+Value}} (std\+::string quantity\+Name, int coordX, int coordY) const
\begin{DoxyCompactList}\small\item\em Manually set the value on a coordinate, without having to get the quantity. \end{DoxyCompactList}\item
void \mbox{\hyperlink{classSDDistributed_a32d97f1dcac80c2f61124460149fb0fb}{build\+Send\+Map}} ()
\begin{DoxyCompactList}\small\item\em Builds map of cells to send from this S\+DD to other S\+D\+Ds. \end{DoxyCompactList}\item
void \mbox{\hyperlink{classSDDistributed_a55650dabf89c711ac07e5795e1b87b17}{build\+Recv\+Map}} (const \mbox{\hyperlink{classDomain}{Domain}} \&domain, std\+::map$<$ std\+::pair$<$ int, int $>$, real $>$ \&dirichlet\+Cell\+Map, std\+::map$<$ std\+::pair$<$ int, int $>$, std\+::pair$<$ int, int $>$ $>$ \&neumann\+Cell\+Map)
\begin{DoxyCompactList}\small\item\em Builds map between coords on S\+DD and \char`\"{}real cell\char`\"{} on neighbour S\+DD / boundary side. \end{DoxyCompactList}\item
{\footnotesize template$<$typename T $>$ }\\void \mbox{\hyperlink{classSDDistributed_a82b5a390e964051d1952c683b4fa5f05}{add\+Quantity}} (std\+::string name)
\begin{DoxyCompactList}\small\item\em Adds physical quantity (and thus data) used in the scheme. \end{DoxyCompactList}\item
void \mbox{\hyperlink{classSDDistributed_a3dbacea02c2d4f36310c81f87f90fe5a}{build\+All\+S\+DS}} (unsigned int n\+S\+DS, std\+::string geom\+Type)
\begin{DoxyCompactList}\small\item\em Build subdomains on shared memory based on geometry type. \end{DoxyCompactList}\item
\mbox{\Hypertarget{classSDDistributed_aa7301877492714e144dc056b133d0a54}\label{classSDDistributed_aa7301877492714e144dc056b133d0a54}}
void \mbox{\hyperlink{classSDDistributed_aa7301877492714e144dc056b133d0a54}{dispatch\+Boundary\+Cell}} (const std\+::map$<$ std\+::pair$<$ int, int $>$, real $>$ \&dirichlet\+Cell\+Map, const std\+::map$<$ std\+::pair$<$ int, int $>$, std\+::pair$<$ int, int $>$ $>$ \&neumann\+Cell\+Map)
\begin{DoxyCompactList}\small\item\em Dispatch the boundary cells among the sds. \end{DoxyCompactList}\item
\mbox{\Hypertarget{classSDDistributed_a4cd7f5aea74376a9a40604459bcc9630}\label{classSDDistributed_a4cd7f5aea74376a9a40604459bcc9630}}
void \mbox{\hyperlink{classSDDistributed_a4cd7f5aea74376a9a40604459bcc9630}{dispatch\+Overlap\+Cell}} ()
\begin{DoxyCompactList}\small\item\em Dispatch the overlap cells among the sds. \end{DoxyCompactList}\item
\mbox{\Hypertarget{classSDDistributed_afd7366e358e454a2fe2eae2b2c870cf1}\label{classSDDistributed_afd7366e358e454a2fe2eae2b2c870cf1}}
void \mbox{\hyperlink{classSDDistributed_afd7366e358e454a2fe2eae2b2c870cf1}{update\+Overlap\+Cells}} ()
\begin{DoxyCompactList}\small\item\em Updates overlap cells by communicating through M\+PI with other S\+D\+Ds. \end{DoxyCompactList}\item
\mbox{\Hypertarget{classSDDistributed_a7a3029d43d4961a3ef5c2144e1f28b8f}\label{classSDDistributed_a7a3029d43d4961a3ef5c2144e1f28b8f}}
void {\bfseries copy\+Overlap\+Cell} ()
\item
\mbox{\Hypertarget{classSDDistributed_ae58e58e9240e953bc78d94af62d12723}\label{classSDDistributed_ae58e58e9240e953bc78d94af62d12723}}
void {\bfseries send\+Overlap\+Cell} ()
\item
\mbox{\Hypertarget{classSDDistributed_a97f1d4d864845aab5cf910eccf2e0e62}\label{classSDDistributed_a97f1d4d864845aab5cf910eccf2e0e62}}
void {\bfseries wait\+Overlap\+Cell} ()
\item
\mbox{\Hypertarget{classSDDistributed_aac3708e2ca754bdb3ea192cae5341d84}\label{classSDDistributed_aac3708e2ca754bdb3ea192cae5341d84}}
void {\bfseries parse\+Overlap\+Cell} ()
\item
void \mbox{\hyperlink{classSDDistributed_a0974e2cce9bfcddfd0acccd1105d980f}{add\+Equation}} (std\+::string eq\+Name, eq\+Type eq\+Func)
\begin{DoxyCompactList}\small\item\em Adds an equation to the stack of equations to be computed by the scheme. \end{DoxyCompactList}\item
\mbox{\Hypertarget{classSDDistributed_a00a539076c306457a4dd1aef2c4f2039}\label{classSDDistributed_a00a539076c306457a4dd1aef2c4f2039}}
void \mbox{\hyperlink{classSDDistributed_a00a539076c306457a4dd1aef2c4f2039}{exec\+Equation}} (std\+::string eq\+Name)
\begin{DoxyCompactList}\small\item\em Computes equation in the order they were added to the task stack. \end{DoxyCompactList}\item
void \mbox{\hyperlink{classSDDistributed_a64669d8f5e7b0d660fbe3b5407d46d46}{init\+Thread\+Pool}} (unsigned int n\+Threads, unsigned int n\+Common\+S\+DS)
\begin{DoxyCompactList}\small\item\em Builds thread pool given an amount of threads to build. \end{DoxyCompactList}\end{DoxyCompactItemize}

\subsection{Detailed Description}
Subdomain on distributed memory (S\+DD)

Defines a subdomain on distributed memory. It represents a part of a domain available as a single block of memory, hence its definition as a rectangle. It will then be sliced on geometric subdomains on this block of shared memory (\mbox{\hyperlink{classSDShared}{S\+D\+Shared}}).

\subsection{Constructor \& Destructor Documentation}
\mbox{\Hypertarget{classSDDistributed_a07332d418da104a969360c6c671feef4}\label{classSDDistributed_a07332d418da104a969360c6c671feef4}}
\index{S\+D\+Distributed@{S\+D\+Distributed}!S\+D\+Distributed@{S\+D\+Distributed}}
\index{S\+D\+Distributed@{S\+D\+Distributed}!S\+D\+Distributed@{S\+D\+Distributed}}
\subsubsection{\texorpdfstring{S\+D\+Distributed()}{SDDistributed()}}
{\footnotesize\ttfamily S\+D\+Distributed\+::\+S\+D\+Distributed (\begin{DoxyParamCaption}\item[{unsigned int}]{sizeX,  }\item[{unsigned int}]{sizeY,  }\item[{int}]{B\+L\+\_\+X,  }\item[{int}]{B\+L\+\_\+Y,  }\item[{unsigned int}]{boundary\+Thickness,  }\item[{unsigned int}]{neighbour\+Hood,  }\item[{unsigned int}]{id,  }\item[{unsigned int}]{n\+S\+DD }\end{DoxyParamCaption})}

Constructor.

\begin{DoxyParams}{Parameters}
{\em sizeX} & number of cells of subdomain on the X-\/axis \\
\hline
{\em sizeY} & number of cells of subdomain on the Y-\/axis \\
\hline
\end{DoxyParams}

\subsection{Member Function Documentation}
\mbox{\Hypertarget{classSDDistributed_a0974e2cce9bfcddfd0acccd1105d980f}\label{classSDDistributed_a0974e2cce9bfcddfd0acccd1105d980f}}
\index{S\+D\+Distributed@{S\+D\+Distributed}!add\+Equation@{add\+Equation}}
\index{add\+Equation@{add\+Equation}!S\+D\+Distributed@{S\+D\+Distributed}}
\subsubsection{\texorpdfstring{add\+Equation()}{addEquation()}}
{\footnotesize\ttfamily void S\+D\+Distributed\+::add\+Equation (\begin{DoxyParamCaption}\item[{std\+::string}]{eq\+Name,  }\item[{eq\+Type}]{eq\+Func }\end{DoxyParamCaption})}

Adds an equation to the stack of equations to be computed by the scheme.

\begin{DoxyParams}{Parameters}
{\em eq\+Func} & function to be added to the task \\
\hline
\end{DoxyParams}
\mbox{\Hypertarget{classSDDistributed_a82b5a390e964051d1952c683b4fa5f05}\label{classSDDistributed_a82b5a390e964051d1952c683b4fa5f05}}
\index{S\+D\+Distributed@{S\+D\+Distributed}!add\+Quantity@{add\+Quantity}}
\index{add\+Quantity@{add\+Quantity}!S\+D\+Distributed@{S\+D\+Distributed}}
\subsubsection{\texorpdfstring{add\+Quantity()}{addQuantity()}}
{\footnotesize\ttfamily template$<$typename T $>$ \\
void S\+D\+Distributed\+::add\+Quantity (\begin{DoxyParamCaption}\item[{std\+::string}]{name }\end{DoxyParamCaption})}

Adds physical quantity (and thus data) used in the scheme.

\begin{DoxyParams}{Parameters}
{\em name} & name of the quantity to add, used as reference when getting and setting a value, or when getting the whole quantity data \\
\hline
\end{DoxyParams}
\mbox{\Hypertarget{classSDDistributed_a3dbacea02c2d4f36310c81f87f90fe5a}\label{classSDDistributed_a3dbacea02c2d4f36310c81f87f90fe5a}}
\index{S\+D\+Distributed@{S\+D\+Distributed}!build\+All\+S\+DS@{build\+All\+S\+DS}}
\index{build\+All\+S\+DS@{build\+All\+S\+DS}!S\+D\+Distributed@{S\+D\+Distributed}}
\subsubsection{\texorpdfstring{build\+All\+S\+D\+S()}{buildAllSDS()}}
{\footnotesize\ttfamily void S\+D\+Distributed\+::build\+All\+S\+DS (\begin{DoxyParamCaption}\item[{unsigned int}]{n\+S\+DS,  }\item[{std\+::string}]{geom\+Type }\end{DoxyParamCaption})}

Build subdomains on shared memory based on geometry type.

\begin{DoxyParams}{Parameters}
{\em n\+S\+DS} & number of subdomains to be built \\
\hline
{\em geom\+Type} & geometry type of subdomain (see the \mbox{\hyperlink{classGeometry}{Geometry}} class for possible values) \\
\hline
\end{DoxyParams}
Shuffling S\+DS List \mbox{\Hypertarget{classSDDistributed_a55650dabf89c711ac07e5795e1b87b17}\label{classSDDistributed_a55650dabf89c711ac07e5795e1b87b17}}
\index{S\+D\+Distributed@{S\+D\+Distributed}!build\+Recv\+Map@{build\+Recv\+Map}}
\index{build\+Recv\+Map@{build\+Recv\+Map}!S\+D\+Distributed@{S\+D\+Distributed}}
\subsubsection{\texorpdfstring{build\+Recv\+Map()}{buildRecvMap()}}
{\footnotesize\ttfamily void S\+D\+Distributed\+::build\+Recv\+Map (\begin{DoxyParamCaption}\item[{const \mbox{\hyperlink{classDomain}{Domain}} \&}]{domain,  }\item[{std\+::map$<$ std\+::pair$<$ int, int $>$, real $>$ \&}]{dirichlet\+Cell\+Map,  }\item[{std\+::map$<$ std\+::pair$<$ int, int $>$, std\+::pair$<$ int, int $>$ $>$ \&}]{neumann\+Cell\+Map }\end{DoxyParamCaption})}

Builds map between coords on S\+DD and \char`\"{}real cell\char`\"{} on neighbour S\+DD / boundary side.

\begin{DoxyParams}{Parameters}
{\em domain} & parent domain of the S\+DD \\
\hline
\end{DoxyParams}
\mbox{\Hypertarget{classSDDistributed_a32d97f1dcac80c2f61124460149fb0fb}\label{classSDDistributed_a32d97f1dcac80c2f61124460149fb0fb}}
\index{S\+D\+Distributed@{S\+D\+Distributed}!build\+Send\+Map@{build\+Send\+Map}}
\index{build\+Send\+Map@{build\+Send\+Map}!S\+D\+Distributed@{S\+D\+Distributed}}
\subsubsection{\texorpdfstring{build\+Send\+Map()}{buildSendMap()}}
{\footnotesize\ttfamily void S\+D\+Distributed\+::build\+Send\+Map (\begin{DoxyParamCaption}{ }\end{DoxyParamCaption})}

Builds map of cells to send from this S\+DD to other S\+D\+Ds.

\begin{DoxyParams}{Parameters}
{\em domain} & parent domain of the S\+DD \\
\hline
\end{DoxyParams}
\mbox{\Hypertarget{classSDDistributed_a0ab71d942dca319b739390055942a96a}\label{classSDDistributed_a0ab71d942dca319b739390055942a96a}}
\index{S\+D\+Distributed@{S\+D\+Distributed}!get\+Id@{get\+Id}}
\index{get\+Id@{get\+Id}!S\+D\+Distributed@{S\+D\+Distributed}}
\subsubsection{\texorpdfstring{get\+Id()}{getId()}}
{\footnotesize\ttfamily unsigned int S\+D\+Distributed\+::get\+Id (\begin{DoxyParamCaption}{ }\end{DoxyParamCaption}) const}

Gets unique id of S\+DD.

\begin{DoxyReturn}{Returns}
id of S\+DD
\end{DoxyReturn}
\mbox{\Hypertarget{classSDDistributed_a2a2e744edad326561e3555a352ce4a0a}\label{classSDDistributed_a2a2e744edad326561e3555a352ce4a0a}}
\index{S\+D\+Distributed@{S\+D\+Distributed}!get\+Overlap\+Cell\+Map@{get\+Overlap\+Cell\+Map}}
\index{get\+Overlap\+Cell\+Map@{get\+Overlap\+Cell\+Map}!S\+D\+Distributed@{S\+D\+Distributed}}
\subsubsection{\texorpdfstring{get\+Overlap\+Cell\+Map()}{getOverlapCellMap()}}
{\footnotesize\ttfamily const std\+::map$<$ std\+::pair$<$int, int$>$, std\+::pair$<$ int, std\+::pair$<$int, int$>$ $>$ $>$\& S\+D\+Distributed\+::get\+Overlap\+Cell\+Map (\begin{DoxyParamCaption}{ }\end{DoxyParamCaption}) const}

Returns mapping between overlap cells and corresponding \char`\"{}real cells\char`\"{} on other S\+D\+Ds.

Used by the domain to communicate between S\+D\+Ds when updating overlap cells \mbox{\Hypertarget{classSDDistributed_a14f296606ff1afa1e4878fa6c4928afc}\label{classSDDistributed_a14f296606ff1afa1e4878fa6c4928afc}}
\index{S\+D\+Distributed@{S\+D\+Distributed}!get\+Quantity@{get\+Quantity}}
\index{get\+Quantity@{get\+Quantity}!S\+D\+Distributed@{S\+D\+Distributed}}
\subsubsection{\texorpdfstring{get\+Quantity()}{getQuantity()}}
{\footnotesize\ttfamily \mbox{\hyperlink{classQuantity}{Quantity}}$<$ real $>$ $\ast$ S\+D\+Distributed\+::get\+Quantity (\begin{DoxyParamCaption}\item[{std\+::string}]{name }\end{DoxyParamCaption})}

Gets physical quantity previously added with method add\+Quantity.

\begin{DoxyParams}{Parameters}
{\em name} & name of the quantity to get \\
\hline
\end{DoxyParams}
\mbox{\Hypertarget{classSDDistributed_a9afba0607b6012a0e446b95251559f5d}\label{classSDDistributed_a9afba0607b6012a0e446b95251559f5d}}
\index{S\+D\+Distributed@{S\+D\+Distributed}!get\+S\+DS@{get\+S\+DS}}
\index{get\+S\+DS@{get\+S\+DS}!S\+D\+Distributed@{S\+D\+Distributed}}
\subsubsection{\texorpdfstring{get\+S\+D\+S()}{getSDS()}}
{\footnotesize\ttfamily const std\+::vector$<$ \mbox{\hyperlink{classSDShared}{S\+D\+Shared}} $>$ \& S\+D\+Distributed\+::get\+S\+DS (\begin{DoxyParamCaption}{ }\end{DoxyParamCaption}) const}

Gets all S\+DS on S\+DD for a read-\/only access.

\begin{DoxyReturn}{Returns}
const reference to the array of all subdomains on S\+DD
\end{DoxyReturn}
\mbox{\Hypertarget{classSDDistributed_a567b9535558271515166ce7ebd3f6c29}\label{classSDDistributed_a567b9535558271515166ce7ebd3f6c29}}
\index{S\+D\+Distributed@{S\+D\+Distributed}!get\+SizeX@{get\+SizeX}}
\index{get\+SizeX@{get\+SizeX}!S\+D\+Distributed@{S\+D\+Distributed}}
\subsubsection{\texorpdfstring{get\+Size\+X()}{getSizeX()}}
{\footnotesize\ttfamily unsigned int S\+D\+Distributed\+::get\+SizeX (\begin{DoxyParamCaption}{ }\end{DoxyParamCaption}) const}

Gets width of S\+DD, excluding boundary thickness.

\begin{DoxyReturn}{Returns}
width of S\+DD
\end{DoxyReturn}
\mbox{\Hypertarget{classSDDistributed_a9bf0049f4c95513b4d9c9a9bac0f6eb4}\label{classSDDistributed_a9bf0049f4c95513b4d9c9a9bac0f6eb4}}
\index{S\+D\+Distributed@{S\+D\+Distributed}!get\+SizeY@{get\+SizeY}}
\index{get\+SizeY@{get\+SizeY}!S\+D\+Distributed@{S\+D\+Distributed}}
\subsubsection{\texorpdfstring{get\+Size\+Y()}{getSizeY()}}
{\footnotesize\ttfamily unsigned int S\+D\+Distributed\+::get\+SizeY (\begin{DoxyParamCaption}{ }\end{DoxyParamCaption}) const}

Gets height of S\+DD, excluding boundary thickness.

\begin{DoxyReturn}{Returns}
height of S\+DD
\end{DoxyReturn}
\mbox{\Hypertarget{classSDDistributed_a1db6a1bf2f8781b9e4b12be99b4bf9c4}\label{classSDDistributed_a1db6a1bf2f8781b9e4b12be99b4bf9c4}}
\index{S\+D\+Distributed@{S\+D\+Distributed}!get\+Value@{get\+Value}}
\index{get\+Value@{get\+Value}!S\+D\+Distributed@{S\+D\+Distributed}}
\subsubsection{\texorpdfstring{get\+Value()}{getValue()}}
{\footnotesize\ttfamily real S\+D\+Distributed\+::get\+Value (\begin{DoxyParamCaption}\item[{std\+::string}]{quantity\+Name,  }\item[{int}]{coordX,  }\item[{int}]{coordY }\end{DoxyParamCaption}) const}

Manually set the value on a coordinate, without having to get the quantity.

\begin{DoxyParams}{Parameters}
{\em quantity\+Name} & name of quantity to update \\
\hline
{\em coordX} & coordinate on X-\/axis of cell to update \\
\hline
{\em coordY} & coordinate on Y-\/axis of cell to update \\
\hline
{\em value} & value to set on the desired cell for the desired quantity \\
\hline
\end{DoxyParams}
\mbox{\Hypertarget{classSDDistributed_a64669d8f5e7b0d660fbe3b5407d46d46}\label{classSDDistributed_a64669d8f5e7b0d660fbe3b5407d46d46}}
\index{S\+D\+Distributed@{S\+D\+Distributed}!init\+Thread\+Pool@{init\+Thread\+Pool}}
\index{init\+Thread\+Pool@{init\+Thread\+Pool}!S\+D\+Distributed@{S\+D\+Distributed}}
\subsubsection{\texorpdfstring{init\+Thread\+Pool()}{initThreadPool()}}
{\footnotesize\ttfamily void S\+D\+Distributed\+::init\+Thread\+Pool (\begin{DoxyParamCaption}\item[{unsigned int}]{n\+Threads,  }\item[{unsigned int}]{n\+Common\+S\+DS }\end{DoxyParamCaption})}

Builds thread pool given an amount of threads to build.

\begin{DoxyParams}{Parameters}
{\em n\+Threads} & number of threads to build \\
\hline
{\em n\+Common\+S\+DS} & number of work to share among the threads \\
\hline
\end{DoxyParams}
\mbox{\Hypertarget{classSDDistributed_ae9d8db949ba9da0a95407e1066df17b9}\label{classSDDistributed_ae9d8db949ba9da0a95407e1066df17b9}}
\index{S\+D\+Distributed@{S\+D\+Distributed}!set\+Value@{set\+Value}}
\index{set\+Value@{set\+Value}!S\+D\+Distributed@{S\+D\+Distributed}}
\subsubsection{\texorpdfstring{set\+Value()}{setValue()}}
{\footnotesize\ttfamily void S\+D\+Distributed\+::set\+Value (\begin{DoxyParamCaption}\item[{std\+::string}]{quantity\+Name,  }\item[{int}]{coordX,  }\item[{int}]{coordY,  }\item[{real}]{value }\end{DoxyParamCaption})}

Manually set the value on a coordinate, without having to get the quantity.

\begin{DoxyParams}{Parameters}
{\em quantity\+Name} & name of quantity to update \\
\hline
{\em coordX} & coordinate on X-\/axis of cell to update \\
\hline
{\em coordY} & coordinate on Y-\/axis of cell to update \\
\hline
{\em value} & value to set on the desired cell for the desired quantity \\
\hline
\end{DoxyParams}

The documentation for this class was generated from the following files\+:\begin{DoxyCompactItemize}
\item
source/subdomain/\mbox{\hyperlink{SDDistributed_8hpp}{S\+D\+Distributed.\+hpp}}\item
source/subdomain/Domain.\+cpp\item
source/subdomain/S\+D\+Distributed.\+cpp\end{DoxyCompactItemize}


text:
"""Implementation of Inspector abstraction for Hyper-V"""

import collections
import functools
import sys

from os_win import exceptions as os_win_exc
from os_win import utilsfactory
from oslo_utils import units
import six

from ceilometer.compute.pollsters import util
from ceilometer.compute.virt import inspector as virt_inspector

def convert_exceptions(function, exception_map):
    expected_exceptions = tuple(exception_map.keys())

    @functools.wraps(function)
    def wrapper(*args, **kwargs):
        try:
            return function(*args, **kwargs)
        except expected_exceptions as ex:
            # exception might be a subclass of an expected exception.
            for expected in expected_exceptions:
                if isinstance(ex, expected):
                    raised_exception = exception_map[expected]
                    break

            exc_info = sys.exc_info()
            # NOTE(claudiub): Python 3 raises the exception object given as
            # the second argument in six.reraise.
            # The original message will be maintained by passing the original
            # exception.
            exc = raised_exception(six.text_type(exc_info[1]))
            six.reraise(raised_exception, exc, exc_info[2])
    return wrapper

def decorate_all_methods(decorator, *args, **kwargs):
    def decorate(cls):
        for attr in cls.__dict__:
            class_member = getattr(cls, attr)
            if callable(class_member):
                setattr(cls, attr, decorator(class_member, *args, **kwargs))
        return cls

    return decorate

exception_conversion_map = collections.OrderedDict([
    # NOTE(claudiub): order should be from the most specialized exception type
    # to the most generic exception type.
    # (expected_exception, converted_exception)
    (os_win_exc.NotFound, virt_inspector.InstanceNotFoundException),
    (os_win_exc.OSWinException, virt_inspector.InspectorException),
])

# NOTE(claudiub): the purpose of the decorator below is to prevent any
# os_win exceptions (subclasses of OSWinException) to leak outside of the
# HyperVInspector.

@decorate_all_methods(convert_exceptions, exception_conversion_map)
class HyperVInspector(virt_inspector.Inspector):

    def __init__(self):
        super(HyperVInspector, self).__init__()
        self._utils = utilsfactory.get_metricsutils()
        self._host_max_cpu_clock = self._compute_host_max_cpu_clock()

    def _compute_host_max_cpu_clock(self):
        hostutils = utilsfactory.get_hostutils()
        # host's number of CPUs and CPU clock speed will not change.
        cpu_info = hostutils.get_cpus_info()
        host_cpu_count = len(cpu_info)
        host_cpu_clock = cpu_info[0]['MaxClockSpeed']

        return float(host_cpu_clock * host_cpu_count)

    def inspect_cpus(self, instance):
        instance_name = util.instance_name(instance)
        (cpu_clock_used,
         cpu_count, uptime) = self._utils.get_cpu_metrics(instance_name)

        cpu_percent_used = cpu_clock_used / self._host_max_cpu_clock

        # Nanoseconds
        cpu_time = (int(uptime * cpu_percent_used) * units.k)

        return virt_inspector.CPUStats(number=cpu_count, time=cpu_time)

    def inspect_memory_usage(self, instance, duration=None):
        instance_name = util.instance_name(instance)
        usage = self._utils.get_memory_metrics(instance_name)
        return virt_inspector.MemoryUsageStats(usage=usage)

    def inspect_vnics(self, instance):
        instance_name = util.instance_name(instance)
        for vnic_metrics in self._utils.get_vnic_metrics(instance_name):
            interface = virt_inspector.Interface(
                name=vnic_metrics["element_name"],
                mac=vnic_metrics["address"],
                fref=None,
                parameters=None)

            stats = virt_inspector.InterfaceStats(
                rx_bytes=vnic_metrics['rx_mb'] * units.Mi,
                rx_packets=0,
                tx_bytes=vnic_metrics['tx_mb'] * units.Mi,
                tx_packets=0)

            yield (interface, stats)

    def inspect_disks(self, instance):
        instance_name = util.instance_name(instance)
        for disk_metrics in self._utils.get_disk_metrics(instance_name):
            disk = virt_inspector.Disk(device=disk_metrics['instance_id'])
            stats = virt_inspector.DiskStats(
                read_requests=0,
                # Return bytes
                read_bytes=disk_metrics['read_mb'] * units.Mi,
                write_requests=0,
                write_bytes=disk_metrics['write_mb'] * units.Mi,
                errors=0)

            yield (disk, stats)

    def inspect_disk_latency(self, instance):
        instance_name = util.instance_name(instance)
        for disk_metrics in self._utils.get_disk_latency_metrics(
                instance_name):
            disk = virt_inspector.Disk(device=disk_metrics['instance_id'])
            stats = virt_inspector.DiskLatencyStats(
                disk_latency=disk_metrics['disk_latency'])

            yield (disk, stats)

    def inspect_disk_iops(self, instance):
        instance_name = util.instance_name(instance)
        for disk_metrics in self._utils.get_disk_iops_count(instance_name):
            disk = virt_inspector.Disk(device=disk_metrics['instance_id'])
            stats = virt_inspector.DiskIOPSStats(
                iops_count=disk_metrics['iops_count'])

            yield (disk, stats)


text:
package com.consol.citrus.http.message;

import com.consol.citrus.context.TestContext;

import javax.servlet.http.Cookie;
import java.util.LinkedList;
import java.util.List;

/**
 * The cookie enricher is capable of adding information from a test context to a given list of cookies.
 */
class CookieEnricher {

    /**
     * Replaces the dynamic content in the given list of cookies
     * @param cookies The list of Cookies to
     * @param context The context to replace the variables with
     */
    List<Cookie> enrich(List<Cookie> cookies, final TestContext context) {

        final List<Cookie> enrichedCookies = new LinkedList<>();

        for (final Cookie cookie : cookies) {
            final Cookie enrichedCookie = new Cookie(cookie.getName(), cookie.getValue());

            if (cookie.getValue() != null) {
                enrichedCookie.setValue(context.replaceDynamicContentInString(cookie.getValue()));
            }

            if (cookie.getComment() != null) {
                enrichedCookie.setComment(context.replaceDynamicContentInString(cookie.getComment()));
            }

            if (cookie.getPath() != null) {
                enrichedCookie.setPath(context.replaceDynamicContentInString(cookie.getPath()));
            }

            if (cookie.getDomain() != null) {
                enrichedCookie.setDomain(context.replaceDynamicContentInString(cookie.getDomain()));
            }

            enrichedCookie.setMaxAge(cookie.getMaxAge());
            enrichedCookie.setVersion(cookie.getVersion());
            enrichedCookie.setHttpOnly(cookie.isHttpOnly());
            enrichedCookie.setSecure(cookie.getSecure());

            enrichedCookies.add(enrichedCookie);
        }

        return enrichedCookies;
    }

}


text:
/* global setTimeout, clearTimeout */

import React from 'react';

export const POSITION_LEFT = 0;
export const POSITION_RIGHT = 100;
export const BOUNCE_INTERVAL = 1200;

/**
 * Describes a globally-positioned loading bar animation.
 */
export default class LoadingBar extends React.Component {
  static propTypes = {
    show: React.PropTypes.bool
  };
  static defaultProps = {
    show: true
  };

  constructor(props) {
    super(props);

    this.state = {
      // Describes the horizontal position of the loading bar
      position: POSITION_LEFT
    };
  }

  componentDidMount() {
    // When the component mounts, we want to immediately start the animation from left to right.
    // However, to avoid a race condition whereby we update the state while the component is mounting,
    // we will queue this event to occur as soon as possible *after* the component is mounted. It
    // is also necessary to record the interval as a class property to that it can be canceled promptly
    // if the component is immediately unmounted.
    this.interval = this.props.show && setTimeout(() => this.tick(), 1);
  }

  componentWillUnmount() {
    clearTimeout(this.interval);
  }

  tick() {
    // On every tick, we'll update the position to the other boundary.
    // Additionally, we'll schedule another tick for BOUNCE_INTERVAL ms from now.
    this.setState({
      position: this.state.position === POSITION_LEFT ? POSITION_RIGHT : POSITION_LEFT
    });
    this.interval = setTimeout(() => this.tick(), BOUNCE_INTERVAL);
  }

  render() {
    const {show} = this.props;
    const {position} = this.state;
    const offset = position === POSITION_LEFT ? -POSITION_RIGHT : POSITION_LEFT;

    return show && (

        <div className="loading-bar" style={{
          marginLeft: `calc(${position}% + ${offset}px)`
        }} />

    );
  }
}


text:
import _ from 'lodash';
import React from 'react';
import PropTypes from 'prop-types';
import {List} from 'immutable';
import {getForm} from 'elza-core';

export default function(Component) {
  return class withErrors extends React.Component {
    static displayName = 'withErrors(' + Component + ')';
    static propTypes = {
      className: PropTypes.string,
      htmlFor: PropTypes.string,
      name: PropTypes.string,
    };

    static defaultProps = {
      className: '',
    };

    /**
     * @constructor
     * @param  {Object} props
     */
    constructor(props) {
      super(props);
      this.form = null;
      this.state = {errors: new List()};
      _.bindAll(this, 'receiveErrors', 'formName', 'fieldName');
    }

    formName() {
      const name = this.fieldName();
      return name.substr(0, name.indexOf('.'));
    }

    fieldName() {
      let name = this.props.htmlFor;
      if (_.isNil(name)) name = this.props.name;
      return name;
    }

    receiveErrors(formData) {
      if (!formData.errors.any() && this.state.errors.size === 0) return;
      const fieldName = this.fieldName();
      console.log('fieldName = ', fieldName);
      const errors = _.get(formData.errors, 'errors.' + fieldName, []);
      // Be sure error list is immutable
      this.setState({errors: new List(errors)});
    }

    componentDidMount() {
      // Explode the form name
      const formName = this.formName();
      this.form = getForm(formName);
      // Client side errors
      this.form.onChange(this.receiveErrors);
      this.form.onAfter('validation', this.receiveErrors);
      this.form.onAfter('submit', this.receiveErrors);
    }

    /**
     * @override
     */
    render() {
      let {className, ...otherProps} = this.props;
      if (this.state.errors.size > 0) className += ' has-errors';
      return (
        <Component
          className={className}
          errors={this.state.errors}
          formName={this.formName()}
          fieldName={this.fieldName()}
          {...otherProps}
        />
      );
    }
  };
}


text:
require 'base_test'
require 'methadone'
require 'stringio'

class TestCLILogger < BaseTest
  include Methadone

  def setup
    @blank_format = proc { |severity,datetime,progname,msg|
      msg + "\n"
    }
    @real_stderr = $stderr
    @real_stdout = $stdout
    $stderr = StringIO.new
    $stdout = StringIO.new
  end

  def teardown
    $stderr = @real_stderr
    $stdout = @real_stdout
  end

  test_that "when both stderr and stdin are ttys, split the log messages between them and don't format" do
    Given {
      class << $stderr
        def tty?; true; end
      end
      class << $stdout
        def tty?; true; end
      end

      @logger = CLILogger.new
      @logger.level = Logger::DEBUG
    }

    When log_all_levels

    Then {
      $stdout.string.should == "debug\ninfo\n"
      $stderr.string.should == "warn\nerror\nfatal\n"
    }
  end

  test_that "when both stderr and stdin are ttys, setting the level higher than WARN should affect the error logger" do
    Given {
      class << $stderr
        def tty?; true; end
      end
      class << $stdout
        def tty?; true; end
      end

      @logger = CLILogger.new
      @logger.level = Logger::ERROR
    }

    When log_all_levels

    Then {
      $stdout.string.should == ""
      $stderr.string.should == "error\nfatal\n"
    }
  end

  test_that "logger sends debug and info to stdout, and warns, errors, and fatals to stderr" do
    Given a_logger_with_blank_format
    When log_all_levels

    Then stdout_should_have_everything
    And {
      $stderr.string.should == "warn\nerror\nfatal\n"
    }
  end

  test_that "we can control what goes to stderr" do
    Given a_logger_with_blank_format :at_error_level => Logger::Severity::FATAL

    When log_all_levels

    Then stdout_should_have_everything
    And {
      $stderr.string.should == "fatal\n"
    }
  end

  test_that "we can log to alternate devices easily" do
    Given {
      @out = StringIO.new
      @err = StringIO.new

      @logger = CLILogger.new(@out,@err)
      @logger.level = Logger::DEBUG
      @logger.formatter = @blank_format
    }

    When log_all_levels

    Then {
      @out.string.should == "debug\ninfo\nwarn\nerror\nfatal\n"
      @err.string.should == "warn\nerror\nfatal\n"
    }
  end

  test_that "error logger ignores the log level" do
    Given a_logger_with_blank_format :at_level => Logger::Severity::FATAL
    When log_all_levels

    Then {
      $stdout.string.should == "fatal\n"
      $stderr.string.should == "warn\nerror\nfatal\n"
    }
  end

  test_that "both loggers use the same date format" do
    Given {
    @logger = CLILogger.new
    @logger.level = Logger::DEBUG
    @logger.datetime_format = "the time"
    }

    When {
      @logger.debug("debug")
      @logger.error("error")
    }

    Then {
      $stdout.string.should match /the time.*DEBUG.*debug/
      $stderr.string.should match /the time.*ERROR.*error/
    }
  end

  test_that "error logger does not get <<" do
    Given a_logger_with_blank_format
    When {
      @logger << "foo"
    }
    Then {
      $stdout.string.should == "foo"
      $stderr.string.should == ""
    }
  end

  test_that "error logger can have a different format" do
    Given {
      @logger = logger_with_blank_format
      @logger.error_formatter = proc do |severity,datetime,progname,msg|
        "ERROR_LOGGER: #{msg}\n"
      end
    }
    When {
      @logger.debug("debug")
      @logger.error("error")
    }
    Then {
      $stdout.string.should == "debug\nerror\n"
      $stderr.string.should == "ERROR_LOGGER: error\n"
    }
  end

  private

  def log_all_levels
    proc do
      @logger.debug("debug")
      @logger.info("info")
      @logger.warn("warn")
      @logger.error("error")
      @logger.fatal("fatal")
    end
  end

  def logger_with_blank_format
    logger = CLILogger.new
    logger.formatter = @blank_format
    logger.level = Logger::Severity::DEBUG
    logger
  end

  # options - :at_level - level to set the logger
  def a_logger_with_blank_format(options = {})
    proc do
      @logger = logger_with_blank_format
      @logger.level = options[:at_level] if options[:at_level]
      @logger.error_level = options[:at_error_level] if options[:at_error_level]
    end
  end

  def stdout_should_have_everything
    proc do
      $stdout.string.should == "debug\ninfo\nwarn\nerror\nfatal\n"
    end
  end

end


text:
// Wraps Tizen interface "CalendarEvent" that resides in Tizen module "Calendar".

define(['Ti/_/declare', 'Tizen/_/Calendar/CalendarItem', 'Tizen/_/Calendar/helper'], function(declare, CalendarItem, helper) {

	function onError (e, callback) {
		callback({
			code: e.code,
			success: false,
			error: e.type + ': ' + e.message
		});
	}

	var calendarEvent = declare(CalendarItem, {

		constructor: function(args, nativeObj) {
			if (nativeObj) {
				// nativeObj is a native Tizen object; simply wrap it (take ownership of it)
				this._obj = nativeObj;
			} else {
				// args is a dictionary that the user of the wrapper module passed to the creator function.
				// There are several Tizen constructors for this object.
				// Deduce the correct parameters to the corresponding Tizen constructor, based on the types of
				// the members of args, and invoke the constructor.
				//
				// Note that Tizen calls distinguish between passing an undefined parameter and not passing
				// any parameter at all, so the count of the parameters must also be correct.

				if ('stringRepresentation' in args && 'format' in args) {
					this._obj = new tizen.CalendarEvent(args.stringRepresentation, args.format);
				} else {
					var eventInitDict = args,
						startDate = args.startDate,
						endDate = args.endDate,
						duration = args.duration;

					startDate && (eventInitDict.startDate = helper.createTZDate(startDate));
					endDate && (eventInitDict.endDate = helper.createTZDate(endDate));
					duration && (eventInitDict.duration = helper.createTimeDuration(duration));
					this._obj = new tizen.CalendarEvent(eventInitDict);
				}
			}
		},

		expandRecurrence: function(startDate /*Date*/, endDate /*Date*/, callback) {
			this._obj.expandRecurrence(helper.createTZDate(startDate), helper.createTZDate(endDate), callback && function(events) {
				var i = 0,
					eventsCount = events.length,
					eventsItems = [];

				for (; i < eventsCount; i++) {
					eventsItems.push(new calendarEvent(void 0, events[i]));
				}
				callback({
					code: 0,
					success: true,
					events: eventsItems
				});
			}, callback && function(e) {
					onError(e, callback);
			});
		},

		constants: {
			isDetached: {
				get: function() {
					return this._obj.isDetached;
				}
			}
		},

		properties: {
			endDate: {
				get: function() {
					var endDate = this._obj.endDate;
					return helper.createDate(endDate);
				},
				set: function(value) {
					this._obj.endDate = helper.createTZDate(value);
				}
			},
			availability: {
				get: function() {
					return this._obj.availability;
				},
				set: function(value) {
					this._obj.availability = value;
				}
			},
			recurrenceRule: {
				get: function() {
					return this._obj.recurrenceRule;
				},
				set: function(value) {
					this._obj.recurrenceRule = value;
				}
			}
		}

	});

	// Initialize declaredClass, so that toString() works properly on such objects.
	// Correct operation of toString() is required for proper wrapping and automated testing.
	calendarEvent.prototype.declaredClass = 'Tizen.Calendar.CalendarEvent';
	return calendarEvent;
});


text:
package com.databricks.spark.csv.util

import java.math.BigDecimal
import java.sql.{Date, Timestamp}
import java.text.NumberFormat
import java.util.Locale

import org.apache.spark.sql.types._

import scala.util.Try

/**
 * Utility functions for type casting
 */
object TypeCast {

  /**
   * Casts given string datum to specified type.
   * Currently we do not support complex types (ArrayType, MapType, StructType).
   *
   * For string types, this is simply the datum. For other types.
   * For other nullable types, this is null if the string datum is empty.
   *
   * @param datum string value
   * @param castType SparkSQL type
   */
  private[csv] def castTo(
      datum: String,
      castType: DataType,
      nullable: Boolean = true,
      treatEmptyValuesAsNulls: Boolean = false): Any = {
    if (datum == "" && nullable && (!castType.isInstanceOf[StringType] || treatEmptyValuesAsNulls)){
      null
    } else {
      castType match {
        case _: ByteType => datum.toByte
        case _: ShortType => datum.toShort
        case _: IntegerType => datum.toInt
        case _: LongType => datum.toLong
        case _: FloatType => Try(datum.toFloat)
          .getOrElse(NumberFormat.getInstance(Locale.getDefault).parse(datum).floatValue())
        case _: DoubleType => Try(datum.toDouble)
          .getOrElse(NumberFormat.getInstance(Locale.getDefault).parse(datum).doubleValue())
        case _: BooleanType => datum.toBoolean
        case _: DecimalType => new BigDecimal(datum.replaceAll(",", ""))
        // TODO(hossein): would be good to support other common timestamp formats
        case _: TimestampType => Timestamp.valueOf(datum)
        // TODO(hossein): would be good to support other common date formats
        case _: DateType => Date.valueOf(datum)
        case _: StringType => datum
        case _ => throw new RuntimeException(s"Unsupported type: ${castType.typeName}")
      }
    }
  }

  /**
   * Helper method that converts string representation of a character to actual character.
   * It handles some Java escaped strings and throws exception if given string is longer than one
   * character.
   *
   */
  @throws[IllegalArgumentException]
  private[csv] def toChar(str: String): Char = {
    if (str.charAt(0) == '\\') {
      str.charAt(1)
      match {
        case 't' => '\t'
        case 'r' => '\r'
        case 'b' => '\b'
        case 'f' => '\f'
        case '\"' => '\"' // In case user changes quote char and uses \" as delimiter in options
        case '\'' => '\''
        case 'u' if str == """\u0000""" => '\u0000'
        case _ =>
          throw new IllegalArgumentException(s"Unsupported special character for delimiter: $str")
      }
    } else if (str.length == 1) {
      str.charAt(0)
    } else {
      throw new IllegalArgumentException(s"Delimiter cannot be more than one character: $str")
    }
  }
}


text:
/* global __stack */

Object.defineProperty(global, '__stack', {
  get: function() {
    var orig = Error.prepareStackTrace;
    Error.prepareStackTrace = function(_, stack) {
      return stack;
    };
    var err = new Error;
    Error.captureStackTrace(err, arguments.callee);
    var stack = err.stack;
    Error.prepareStackTrace = orig;
    return stack;
  }
});

Object.defineProperty(global, '__line', {
  get: function() {
    return __stack[1].getLineNumber();
  }
});

Object.defineProperty(global, '__function', {
  get: function() {
    return __stack[1].getFunctionName();
  }
});


text:
/*
 * Test driver for AEAD entry points.
 */
/*  Copyright The Mbed TLS Contributors
 *  SPDX-License-Identifier: Apache-2.0
 *
 *  Licensed under the Apache License, Version 2.0 (the "License"); you may
 *  not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

#include <test/helpers.h>

#if defined(MBEDTLS_PSA_CRYPTO_DRIVERS) && defined(PSA_CRYPTO_DRIVER_TEST)
#include "psa_crypto_aead.h"
#include "psa_crypto_core.h"

#include "test/drivers/aead.h"

mbedtls_test_driver_aead_hooks_t
    mbedtls_test_driver_aead_hooks = MBEDTLS_TEST_DRIVER_AEAD_INIT;

psa_status_t mbedtls_test_transparent_aead_encrypt(
    const psa_key_attributes_t *attributes,
    const uint8_t *key_buffer, size_t key_buffer_size,
    psa_algorithm_t alg,
    const uint8_t *nonce, size_t nonce_length,
    const uint8_t *additional_data, size_t additional_data_length,
    const uint8_t *plaintext, size_t plaintext_length,
    uint8_t *ciphertext, size_t ciphertext_size, size_t *ciphertext_length )
{
    mbedtls_test_driver_aead_hooks.hits_encrypt++;

    if( mbedtls_test_driver_aead_hooks.forced_status != PSA_SUCCESS )
    {
         mbedtls_test_driver_aead_hooks.driver_status =
             mbedtls_test_driver_aead_hooks.forced_status;
    }
    else
    {
#if defined(MBEDTLS_PSA_BUILTIN_AEAD)
        mbedtls_test_driver_aead_hooks.driver_status =
            mbedtls_psa_aead_encrypt(
                attributes, key_buffer, key_buffer_size,
                alg,
                nonce, nonce_length,
                additional_data, additional_data_length,
                plaintext, plaintext_length,
                ciphertext, ciphertext_size, ciphertext_length );
#else
        (void) attributes;
        (void) key_buffer;
        (void) key_buffer_size;
        (void) alg;
        (void) nonce;
        (void) nonce_length;
        (void) additional_data;
        (void) additional_data_length;
        (void) plaintext;
        (void) plaintext_length;
        (void) ciphertext;
        (void) ciphertext_size;
        (void) ciphertext_length;
        mbedtls_test_driver_aead_hooks.driver_status = PSA_ERROR_NOT_SUPPORTED;
#endif
    }

    return( mbedtls_test_driver_aead_hooks.driver_status );
}

psa_status_t mbedtls_test_transparent_aead_decrypt(
    const psa_key_attributes_t *attributes,
    const uint8_t *key_buffer, size_t key_buffer_size,
    psa_algorithm_t alg,
    const uint8_t *nonce, size_t nonce_length,
    const uint8_t *additional_data, size_t additional_data_length,
    const uint8_t *ciphertext, size_t ciphertext_length,
    uint8_t *plaintext, size_t plaintext_size, size_t *plaintext_length )
{
    mbedtls_test_driver_aead_hooks.hits_decrypt++;

    if( mbedtls_test_driver_aead_hooks.forced_status != PSA_SUCCESS )
    {
         mbedtls_test_driver_aead_hooks.driver_status =
             mbedtls_test_driver_aead_hooks.forced_status;
    }
    else
    {
#if defined(MBEDTLS_PSA_BUILTIN_AEAD)
        mbedtls_test_driver_aead_hooks.driver_status =
            mbedtls_psa_aead_decrypt(
                attributes, key_buffer, key_buffer_size,
                alg,
                nonce, nonce_length,
                additional_data, additional_data_length,
                ciphertext, ciphertext_length,
                plaintext, plaintext_size, plaintext_length );
#else
        (void) attributes;
        (void) key_buffer;
        (void) key_buffer_size;
        (void) alg;
        (void) nonce;
        (void) nonce_length;
        (void) additional_data;
        (void) additional_data_length;
        (void) ciphertext;
        (void) ciphertext_length;
        (void) plaintext;
        (void) plaintext_size;
        (void) plaintext_length;
        mbedtls_test_driver_aead_hooks.driver_status = PSA_ERROR_NOT_SUPPORTED;
#endif
    }

    return( mbedtls_test_driver_aead_hooks.driver_status );
}

psa_status_t mbedtls_test_transparent_aead_encrypt_setup(
    mbedtls_transparent_test_driver_aead_operation_t *operation,
    const psa_key_attributes_t *attributes,
    const uint8_t *key_buffer, size_t key_buffer_size,
    psa_algorithm_t alg )
{
    mbedtls_test_driver_aead_hooks.hits_encrypt_setup++;

    if( mbedtls_test_driver_aead_hooks.forced_status != PSA_SUCCESS )
    {
         mbedtls_test_driver_aead_hooks.driver_status =
             mbedtls_test_driver_aead_hooks.forced_status;
    }
    else
    {
#if defined(MBEDTLS_PSA_BUILTIN_AEAD)
        mbedtls_test_driver_aead_hooks.driver_status =
            mbedtls_psa_aead_encrypt_setup( operation, attributes, key_buffer,
                                            key_buffer_size, alg );
#else
        (void) operation;
        (void) attributes;
        (void) key_buffer;
        (void) key_buffer_size;
        (void) alg;
        mbedtls_test_driver_aead_hooks.driver_status = PSA_ERROR_NOT_SUPPORTED;
#endif
    }

    return( mbedtls_test_driver_aead_hooks.driver_status );
}

psa_status_t mbedtls_test_transparent_aead_decrypt_setup(
    mbedtls_transparent_test_driver_aead_operation_t *operation,
    const psa_key_attributes_t *attributes,
    const uint8_t *key_buffer, size_t key_buffer_size,
    psa_algorithm_t alg )
{
    mbedtls_test_driver_aead_hooks.hits_decrypt_setup++;

    if( mbedtls_test_driver_aead_hooks.forced_status != PSA_SUCCESS )
    {
         mbedtls_test_driver_aead_hooks.driver_status =
             mbedtls_test_driver_aead_hooks.forced_status;
    }
    else
    {
#if defined(MBEDTLS_PSA_BUILTIN_AEAD)
        mbedtls_test_driver_aead_hooks.driver_status =
            mbedtls_psa_aead_decrypt_setup( operation, attributes, key_buffer,
                                            key_buffer_size, alg );
#else
        (void) operation;
        (void) attributes;
        (void) key_buffer;
        (void) key_buffer_size;
        (void) alg;
        mbedtls_test_driver_aead_hooks.driver_status = PSA_ERROR_NOT_SUPPORTED;
#endif
    }

    return( mbedtls_test_driver_aead_hooks.driver_status );
}

psa_status_t mbedtls_test_transparent_aead_set_nonce(
    mbedtls_transparent_test_driver_aead_operation_t *operation,
    const uint8_t *nonce,
    size_t nonce_length )
{
    mbedtls_test_driver_aead_hooks.hits_set_nonce++;

    if( mbedtls_test_driver_aead_hooks.forced_status != PSA_SUCCESS )
    {
         mbedtls_test_driver_aead_hooks.driver_status =
             mbedtls_test_driver_aead_hooks.forced_status;
    }
    else
    {
#if defined(MBEDTLS_PSA_BUILTIN_AEAD)
        mbedtls_test_driver_aead_hooks.driver_status =
            mbedtls_psa_aead_set_nonce( operation, nonce, nonce_length );
#else
        (void) operation;
        (void) nonce;
        (void) nonce_length;
        mbedtls_test_driver_aead_hooks.driver_status = PSA_ERROR_NOT_SUPPORTED;
#endif
    }

    return( mbedtls_test_driver_aead_hooks.driver_status );
}

psa_status_t mbedtls_test_transparent_aead_set_lengths(
    mbedtls_transparent_test_driver_aead_operation_t *operation,
    size_t ad_length,
    size_t plaintext_length )
{
    mbedtls_test_driver_aead_hooks.hits_set_lengths++;

    if( mbedtls_test_driver_aead_hooks.forced_status != PSA_SUCCESS )
    {
         mbedtls_test_driver_aead_hooks.driver_status =
             mbedtls_test_driver_aead_hooks.forced_status;
    }
    else
    {
#if defined(MBEDTLS_PSA_BUILTIN_AEAD)
        mbedtls_test_driver_aead_hooks.driver_status =
            mbedtls_psa_aead_set_lengths( operation, ad_length,
                                          plaintext_length );
#else
        (void) operation;
        (void) ad_length;
        (void) plaintext_length;
        mbedtls_test_driver_aead_hooks.driver_status = PSA_ERROR_NOT_SUPPORTED;
#endif
    }

    return( mbedtls_test_driver_aead_hooks.driver_status );
}

psa_status_t mbedtls_test_transparent_aead_update_ad(
    mbedtls_transparent_test_driver_aead_operation_t *operation,
    const uint8_t *input,
    size_t input_length )
{
    mbedtls_test_driver_aead_hooks.hits_update_ad++;

    if( mbedtls_test_driver_aead_hooks.forced_status != PSA_SUCCESS )
    {
         mbedtls_test_driver_aead_hooks.driver_status =
             mbedtls_test_driver_aead_hooks.forced_status;
    }
    else
    {
#if defined(MBEDTLS_PSA_BUILTIN_AEAD)
        mbedtls_test_driver_aead_hooks.driver_status =
            mbedtls_psa_aead_update_ad( operation, input, input_length );
#else
        (void) operation;
        (void) input;
        (void) input_length;
        mbedtls_test_driver_aead_hooks.driver_status = PSA_ERROR_NOT_SUPPORTED;
#endif
    }

    return( mbedtls_test_driver_aead_hooks.driver_status );
}

psa_status_t mbedtls_test_transparent_aead_update(
   mbedtls_transparent_test_driver_aead_operation_t *operation,
   const uint8_t *input,
   size_t input_length,
   uint8_t *output,
   size_t output_size,
   size_t *output_length )
{
    mbedtls_test_driver_aead_hooks.hits_update++;

    if( mbedtls_test_driver_aead_hooks.forced_status != PSA_SUCCESS )
    {
         mbedtls_test_driver_aead_hooks.driver_status =
             mbedtls_test_driver_aead_hooks.forced_status;
    }
    else
    {
#if defined(MBEDTLS_PSA_BUILTIN_AEAD)
        mbedtls_test_driver_aead_hooks.driver_status =
            mbedtls_psa_aead_update( operation, input, input_length, output,
                                    output_size, output_length );
#else
        (void) operation;
        (void) input;
        (void) input_length;
        (void) output;
        (void) output_size;
        (void) output_length;
        mbedtls_test_driver_aead_hooks.driver_status = PSA_ERROR_NOT_SUPPORTED;
#endif
    }

    return( mbedtls_test_driver_aead_hooks.driver_status );
}

psa_status_t mbedtls_test_transparent_aead_finish(
   mbedtls_transparent_test_driver_aead_operation_t *operation,
   uint8_t *ciphertext,
   size_t ciphertext_size,
   size_t *ciphertext_length,
   uint8_t *tag,
   size_t tag_size,
   size_t *tag_length )
{
   mbedtls_test_driver_aead_hooks.hits_finish++;

    if( mbedtls_test_driver_aead_hooks.forced_status != PSA_SUCCESS )
    {
         mbedtls_test_driver_aead_hooks.driver_status =
             mbedtls_test_driver_aead_hooks.forced_status;
    }
    else
    {
#if defined(MBEDTLS_PSA_BUILTIN_AEAD)
        mbedtls_test_driver_aead_hooks.driver_status =
            mbedtls_psa_aead_finish( operation, ciphertext, ciphertext_size,
                                     ciphertext_length, tag, tag_size,
                                     tag_length );
#else
        (void) operation;
        (void) ciphertext;
        (void) ciphertext_size;
        (void) ciphertext_length;
        (void) tag;
        (void) tag_size;
        (void) tag_length;
        mbedtls_test_driver_aead_hooks.driver_status = PSA_ERROR_NOT_SUPPORTED;
#endif
    }

    return( mbedtls_test_driver_aead_hooks.driver_status );
}

psa_status_t mbedtls_test_transparent_aead_verify(
   mbedtls_transparent_test_driver_aead_operation_t *operation,
   uint8_t *plaintext,
   size_t plaintext_size,
   size_t *plaintext_length,
   const uint8_t *tag,
   size_t tag_length )
{
   mbedtls_test_driver_aead_hooks.hits_verify++;

    if( mbedtls_test_driver_aead_hooks.forced_status != PSA_SUCCESS )
    {
         mbedtls_test_driver_aead_hooks.driver_status =
             mbedtls_test_driver_aead_hooks.forced_status;
    }
    else
    {
       uint8_t check_tag[PSA_AEAD_TAG_MAX_SIZE];
       size_t check_tag_length;

#if defined(MBEDTLS_PSA_BUILTIN_AEAD)
       mbedtls_test_driver_aead_hooks.driver_status =
          mbedtls_psa_aead_finish( operation,
                                   plaintext,
                                   plaintext_size,
                                   plaintext_length,
                                   check_tag,
                                   sizeof( check_tag ),
                                   &check_tag_length );
#else
        (void) operation;
        (void) plaintext;
        (void) plaintext_size;
        (void) plaintext_length;
        mbedtls_test_driver_aead_hooks.driver_status = PSA_ERROR_NOT_SUPPORTED;
#endif

       if( mbedtls_test_driver_aead_hooks.driver_status == PSA_SUCCESS )
       {
          if( tag_length != check_tag_length ||
              mbedtls_psa_safer_memcmp( tag, check_tag, tag_length )
              != 0 )
             mbedtls_test_driver_aead_hooks.driver_status =
                                                    PSA_ERROR_INVALID_SIGNATURE;
       }

       mbedtls_platform_zeroize( check_tag, sizeof( check_tag ) );
    }

    return( mbedtls_test_driver_aead_hooks.driver_status );
}

psa_status_t mbedtls_test_transparent_aead_abort(
   mbedtls_transparent_test_driver_aead_operation_t *operation )
{
   mbedtls_test_driver_aead_hooks.hits_abort++;

    if( mbedtls_test_driver_aead_hooks.forced_status != PSA_SUCCESS )
    {
         mbedtls_test_driver_aead_hooks.driver_status =
             mbedtls_test_driver_aead_hooks.forced_status;
    }
    else
    {
#if defined(MBEDTLS_PSA_BUILTIN_AEAD)
        mbedtls_test_driver_aead_hooks.driver_status =
            mbedtls_psa_aead_abort( operation );
#else
        (void) operation;
        mbedtls_test_driver_aead_hooks.driver_status = PSA_ERROR_NOT_SUPPORTED;
#endif
    }

    return( mbedtls_test_driver_aead_hooks.driver_status );
}

#endif /* MBEDTLS_PSA_CRYPTO_DRIVERS && PSA_CRYPTO_DRIVER_TEST */


text:
module Quality
  module Tools
    # Adds 'rubocop' tool support to quality gem
    class RailsBestPractices < Tool
      def quality_rails_best_practices
        ratchet_quality_cmd('rails_best_practices',
                            gives_error_code_on_violations: true) do |line|
          self.class.count_rails_best_practices_violations(line)
        end
      end

      # See Rubocop.included
      def self.count_rails_best_practices_violations(line)
        if line =~ /.*:[0-9]* - /
          1
        else
          0
        end
      end
    end
  end
end


text:
{% extends 'notifications/base_notifications.html' %}

{% block notifications_content %}

Your Notifications

	{% for notification in notifications %}
		{% ifchanged notification.created|date:"d/m/y" %}

{{ notification.created|date:"F d" }}

		{% endifchanged %}
		{% include notification.template %}
	{% endfor %}
{% endblock notifications_content %}


text:
define(['./filter'], function (filter) {

    /**
     * Remove all null/undefined items from array.
     */
    function compact(arr) {
        return filter(arr, function (val) {
            return (val != null);
        });
    }

    return compact;
});


text:
const request = require('supertest');
const dbConfig = require('../../db/connection');
const r = require('rethinkdbdash')({ ...dbConfig, silent: true });

const server = require('../../app').listen();

const BASE_URL = `/api/v1/quotes`;

beforeEach(async () => {
  await r.tableCreate('quotes');
  await r
    .table('quotes')
    .insert([
      { author: 'test1', content: 'content1' },
      { author: 'test2', content: 'content2' },
      { author: 'test3', content: 'content3' },
    ]);
});

afterEach(async () => {
  await r.tableDrop('quotes');
});

describe('api/index/quotes', () => {
  describe('GET /', () => {
    test('get all', async () => {
      const response = await request(server).get(BASE_URL);

      expect(response.status).toEqual(200);
      expect(response.type).toEqual('application/json');
      expect(response.body.data.length).toEqual(3);
    });
  });

  describe('GET /:id', () => {
    test('get single by id', async () => {
      const response = await request(server).get(BASE_URL);
      const quote = response.body.data[0];
      const fetchedQuote = await request(server).get(`${BASE_URL}/${quote.id}`);

      expect(response.status).toEqual(200);
      expect(response.type).toEqual('application/json');
      expect(fetchedQuote.body.data[0]).toEqual(quote);
    });

    test('get single 404', async () => {
      const response = await request(server).get(`${BASE_URL}/0`);

      expect(response.status).toEqual(404);
      expect(response.type).toEqual('application/json');
    });
  });

  describe('POST /:id', () => {
    test('create', async () => {
      const quote = {
        author: 'test-1',
        content: 'content-1',
      };
      const response = await request(server)
        .post(BASE_URL)
        .send(quote);
      const createdQuote = response.body.data[0];

      expect(response.status).toEqual(201);
      expect(response.type).toEqual('application/json');
      expect(createdQuote.author).toEqual(quote.author);
      expect(createdQuote.content).toEqual(createdQuote.content);
    });

    test('create 400', async () => {
      const response = await request(server).post(BASE_URL);

      expect(response.status).toEqual(400);
      expect(response.type).toEqual('application/json');
    });
  });

  describe('PUT /', () => {
    test('update by id', async () => {
      const quote = {
        author: 'test-2',
        content: 'content-2',
      };
      const quoteUpdate = {
        author: 'test-3',
        content: 'content-3',
      };
      const response = await request(server)
        .post(BASE_URL)
        .send(quote);
      const createdQuote = response.body.data[0];
      const updatedResponse = await request(server)
        .put(`${BASE_URL}/${createdQuote.id}`)
        .send(quoteUpdate);
      const updatedQuote = updatedResponse.body.data[0];

      expect(updatedResponse.status).toEqual(200);
      expect(updatedResponse.type).toEqual('application/json');
      expect(updatedQuote.author).toEqual(quoteUpdate.author);
      expect(updatedQuote.content).toEqual(quoteUpdate.content);
    });

    test('update 404', async () => {
      const quoteUpdate = {
        author: 'test-4',
        content: 'content-4',
      };
      const response = await request(server)
        .put(`${BASE_URL}/0`)
        .send(quoteUpdate);

      expect(response.status).toEqual(404);
      expect(response.type).toEqual('application/json');
    });
  });

  describe('DELETE /:id', () => {
    test('delete by id', async () => {
      const quote = {
        author: 'test-5',
        content: 'content-5',
      };
      const response = await request(server)
        .post(BASE_URL)
        .send(quote);
      const createdQuote = response.body.data[0];
      const deletedResponse = await request(server).delete(
        `${BASE_URL}/${createdQuote.id}`
      );

      const deletedQuote = deletedResponse.body.data[0];

      expect(deletedResponse.status).toEqual(200);
      expect(deletedResponse.type).toEqual('application/json');
      expect(deletedQuote.author).toEqual(createdQuote.author);
      expect(deletedQuote.content).toEqual(createdQuote.content);
    });

    test('delete 404', async () => {
      const response = await request(server).delete(`${BASE_URL}/0`);

      expect(response.status).toEqual(404);
      expect(response.type).toEqual('application/json');
    });
  });
});


text:
package gossip

import (
	"fmt"
	"math"
	"math/rand"
	"time"

	"github.com/weaveworks/mesh"

	"github.com/weaveworks/weave/common"
)

// Router to convey gossip from one gossiper to another, for testing
type unicastMessage struct {
	sender mesh.PeerName
	buf    []byte
}
type broadcastMessage struct {
	sender mesh.PeerName
	data   mesh.GossipData
}
type gossipMessage struct {
	sender mesh.PeerName
	data   mesh.GossipData
}
type exitMessage struct {
	exitChan chan struct{}
}
type flushMessage struct {
	flushChan chan struct{}
}

type TestRouter struct {
	gossipChans map[mesh.PeerName]chan interface{}
	loss        float32 // 0.0 means no loss
}

func NewTestRouter(loss float32) *TestRouter {
	return &TestRouter{make(map[mesh.PeerName]chan interface{}, 100), loss}
}

func (grouter *TestRouter) Stop() {
	for peer := range grouter.gossipChans {
		grouter.RemovePeer(peer)
	}
}

func (grouter *TestRouter) gossipBroadcast(sender mesh.PeerName, update mesh.GossipData) {
	for _, gossipChan := range grouter.gossipChans {
		select {
		case gossipChan <- broadcastMessage{sender: sender, data: update}:
		default: // drop the message if we cannot send it
			common.Log.Errorf("Dropping message")
		}
	}
}

func (grouter *TestRouter) gossip(sender mesh.PeerName, update mesh.GossipData) error {
	count := int(math.Log2(float64(len(grouter.gossipChans))))
	for dest, gossipChan := range grouter.gossipChans {
		if dest == sender {
			continue
		}
		select {
		case gossipChan <- gossipMessage{sender: sender, data: update}:
		default: // drop the message if we cannot send it
			common.Log.Errorf("Dropping message")
		}
		count--
		if count <= 0 {
			break
		}
	}
	return nil
}

func (grouter *TestRouter) Flush() {
	for _, gossipChan := range grouter.gossipChans {
		flushChan := make(chan struct{})
		gossipChan <- flushMessage{flushChan: flushChan}
		<-flushChan
	}
}

func (grouter *TestRouter) RemovePeer(peer mesh.PeerName) {
	gossipChan := grouter.gossipChans[peer]
	resultChan := make(chan struct{})
	gossipChan <- exitMessage{exitChan: resultChan}
	<-resultChan
	delete(grouter.gossipChans, peer)
}

type TestRouterClient struct {
	router *TestRouter
	sender mesh.PeerName
}

func (grouter *TestRouter) run(sender mesh.PeerName, gossiper mesh.Gossiper, gossipChan chan interface{}) {
	gossipTimer := time.Tick(2 * time.Second)
	for {
		select {
		case gossip := <-gossipChan:
			switch message := gossip.(type) {
			case exitMessage:
				close(message.exitChan)
				return

			case flushMessage:
				close(message.flushChan)

			case unicastMessage:
				if rand.Float32() > (1.0 - grouter.loss) {
					continue
				}
				if err := gossiper.OnGossipUnicast(message.sender, message.buf); err != nil {
					panic(fmt.Sprintf("Error doing gossip unicast to %s: %s", message.sender, err))
				}

			case broadcastMessage:
				if rand.Float32() > (1.0 - grouter.loss) {
					continue
				}
				for _, msg := range message.data.Encode() {
					if _, err := gossiper.OnGossipBroadcast(message.sender, msg); err != nil {
						panic(fmt.Sprintf("Error doing gossip broadcast: %s", err))
					}
				}
			case gossipMessage:
				if rand.Float32() > (1.0 - grouter.loss) {
					continue
				}
				for _, msg := range message.data.Encode() {
					diff, err := gossiper.OnGossip(msg)
					if err != nil {
						panic(fmt.Sprintf("Error doing gossip: %s", err))
					}
					if diff == nil {
						continue
					}
					// Sanity check - reconsuming the diff should yield nil
					for _, diffMsg := range diff.Encode() {
						if nextDiff, err := gossiper.OnGossip(diffMsg); err != nil {
							panic(fmt.Sprintf("Error doing gossip: %s", err))
						} else if nextDiff != nil {
							panic(fmt.Sprintf("Breach of gossip interface: %v != nil", nextDiff))
						}
					}
					grouter.gossip(message.sender, diff)
				}
			}
		case <-gossipTimer:
			grouter.gossip(sender, gossiper.Gossip())
		}
	}
}

func (grouter *TestRouter) Connect(sender mesh.PeerName, gossiper mesh.Gossiper) mesh.Gossip {
	gossipChan := make(chan interface{}, 100)

	go grouter.run(sender, gossiper, gossipChan)

	grouter.gossipChans[sender] = gossipChan
	return TestRouterClient{grouter, sender}
}

func (client TestRouterClient) GossipUnicast(dstPeerName mesh.PeerName, buf []byte) error {
	select {
	case client.router.gossipChans[dstPeerName] <- unicastMessage{sender: client.sender, buf: buf}:
	default: // drop the message if we cannot send it
		common.Log.Errorf("Dropping message")
	}
	return nil
}

func (client TestRouterClient) GossipBroadcast(update mesh.GossipData) {
	client.router.gossipBroadcast(client.sender, update)
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycotaxon 91: 229 (2005)

#### Original name
Sporisorium panicicola Vánky

### Remarks
null


text:
const double FACTOR = 0.0001;

InvKinBox::InvKinBox(
	const boost::shared_ptr< rbdl_parser::URDF_RBDL_Model >& model,
	const std::string& tip,
	const std::vector< std::string >& modelJointList, QWidget* parent)
 : QWidget(parent)
 , m_model(model)
 , m_jointList(modelJointList)
{
	m_bodyIdx = model->GetBodyId(tip.c_str());

	m_leg_ik = new LegIK(model, tip);

	m_ui = new Ui::InvKinBox;

	m_ui->setupUi(this);

	connect(m_ui->xSlider, SIGNAL(valueChanged(int)), SLOT(updateIK()));
	connect(m_ui->ySlider, SIGNAL(valueChanged(int)), SLOT(updateIK()));
	connect(m_ui->zSlider, SIGNAL(valueChanged(int)), SLOT(updateIK()));
	connect(m_ui->rollSlider, SIGNAL(valueChanged(int)), SLOT(updateIK()));
	connect(m_ui->pitchSlider, SIGNAL(valueChanged(int)), SLOT(updateIK()));
	connect(m_ui->yawSlider, SIGNAL(valueChanged(int)), SLOT(updateIK()));

	connect(m_ui->xSlider, SIGNAL(valueChanged(int)), SLOT(updateSpinboxes()));
	connect(m_ui->ySlider, SIGNAL(valueChanged(int)), SLOT(updateSpinboxes()));
	connect(m_ui->zSlider, SIGNAL(valueChanged(int)), SLOT(updateSpinboxes()));
	connect(m_ui->rollSlider, SIGNAL(valueChanged(int)), SLOT(updateSpinboxes()));
	connect(m_ui->pitchSlider, SIGNAL(valueChanged(int)), SLOT(updateSpinboxes()));
	connect(m_ui->yawSlider, SIGNAL(valueChanged(int)), SLOT(updateSpinboxes()));

	connect(m_ui->xBox, SIGNAL(valueChanged(double)), SLOT(updateSlider()));
	connect(m_ui->yBox, SIGNAL(valueChanged(double)), SLOT(updateSlider()));
	connect(m_ui->zBox, SIGNAL(valueChanged(double)), SLOT(updateSlider()));
	connect(m_ui->rollBox, SIGNAL(valueChanged(double)), SLOT(updateSlider()));
	connect(m_ui->pitchBox, SIGNAL(valueChanged(double)), SLOT(updateSlider()));
	connect(m_ui->yawBox, SIGNAL(valueChanged(double)), SLOT(updateSlider()));

	connect(m_ui->xBox, SIGNAL(valueChanged(double)), SLOT(updateIK()));
	connect(m_ui->yBox, SIGNAL(valueChanged(double)), SLOT(updateIK()));
	connect(m_ui->zBox, SIGNAL(valueChanged(double)), SLOT(updateIK()));
	connect(m_ui->rollBox, SIGNAL(valueChanged(double)), SLOT(updateIK()));
	connect(m_ui->pitchBox, SIGNAL(valueChanged(double)), SLOT(updateIK()));
	connect(m_ui->yawBox, SIGNAL(valueChanged(double)), SLOT(updateIK()));

}

void InvKinBox::updateSlider()
{
	m_ui->xSlider->blockSignals(true);
	m_ui->ySlider->blockSignals(true);
	m_ui->zSlider->blockSignals(true);
	m_ui->rollSlider->blockSignals(true);
	m_ui->pitchSlider->blockSignals(true);
	m_ui->yawSlider->blockSignals(true);

	m_ui->xSlider->setValue((m_ui->xBox->value() / FACTOR));
	m_ui->ySlider->setValue((m_ui->yBox->value() / FACTOR));
	m_ui->zSlider->setValue((m_ui->zBox->value() / FACTOR));
	m_ui->rollSlider->setValue((m_ui->rollBox->value() / FACTOR));
	m_ui->pitchSlider->setValue((m_ui->pitchBox->value() / FACTOR));
	m_ui->yawSlider->setValue((m_ui->yawBox->value() / FACTOR));

	m_ui->xSlider->blockSignals(false);
	m_ui->ySlider->blockSignals(false);
	m_ui->zSlider->blockSignals(false);
	m_ui->rollSlider->blockSignals(false);
	m_ui->pitchSlider->blockSignals(false);
	m_ui->yawSlider->blockSignals(false);
}

void InvKinBox::updateSpinboxes()
{
	m_ui->xBox->blockSignals(true);
	m_ui->yBox->blockSignals(true);
	m_ui->zBox->blockSignals(true);
	m_ui->rollBox->blockSignals(true);
	m_ui->pitchBox->blockSignals(true);
	m_ui->yawBox->blockSignals(true);

	m_ui->xBox->setValue((m_ui->xSlider->value() * FACTOR));
	m_ui->yBox->setValue((m_ui->ySlider->value() * FACTOR));
	m_ui->zBox->setValue((m_ui->zSlider->value() * FACTOR));
	m_ui->rollBox->setValue((m_ui->rollSlider->value() * FACTOR));
	m_ui->pitchBox->setValue((m_ui->pitchSlider->value() * FACTOR));
	m_ui->yawBox->setValue((m_ui->yawSlider->value() * FACTOR));

	m_ui->xBox->blockSignals(false);
	m_ui->yBox->blockSignals(false);
	m_ui->zBox->blockSignals(false);
	m_ui->rollBox->blockSignals(false);
	m_ui->pitchBox->blockSignals(false);
	m_ui->yawBox->blockSignals(false);
}

InvKinBox::~InvKinBox()
{
}

void InvKinBox::updateJointList(const std::vector< std::string >& list)
{
	m_jointList = list;
}

void InvKinBox::updateIK()
{
	Eigen::Vector3d pos(
		FACTOR * m_ui->xSlider->value(),
		FACTOR * m_ui->ySlider->value(),
		FACTOR * m_ui->zSlider->value()
	);

	Eigen::Matrix3d rot;
	rot =
		Eigen::AngleAxisd(FACTOR * m_ui->yawSlider->value(), Eigen::Vector3d(0, 0, 1)) *
		Eigen::AngleAxisd(FACTOR * m_ui->pitchSlider->value(), Eigen::Vector3d(0, 1, 0)) *
		Eigen::AngleAxisd(FACTOR * m_ui->rollSlider->value(), Eigen::Vector3d(1, 0, 0))
	;

	if(!m_leg_ik->doIK(boost::bind(&InvKinBox::ikCB, this, _1, _2), pos, rot))
	{
		ROS_WARN("no IK solution");
	}

	ROS_WARN("changed");
	changed();
}

void InvKinBox::setFrame(const InvKinBox::KeyframePtr& ptr)
{
	m_kf = ptr;
	updateFromMotionFile();
}

void InvKinBox::ikCB(int idx, double angle)
{
	if(m_kf)
	{
		std::vector<std::string>::iterator it = std::find(m_jointList.begin(), m_jointList.end(), m_model->jointName(idx+1));
		if(it == m_jointList.end())
		{
			ROS_WARN("Can't find joint '%s'", m_model->jointName(idx+1).c_str());
			return;
		}

		int kf_idx = it - m_jointList.begin();

		ROS_WARN("Joint %s maps to %d", m_model->jointName(idx+1).c_str(), kf_idx);

		motionfile::FrameJoint* j = &m_kf->joints[kf_idx];

		j->position = angle;
	}
	else
	{
		ROS_WARN("No kf loaded");
	}
}

void InvKinBox::updateFromMotionFile()
{
	if(!m_kf)
		return;

	Math::VectorNd zero = Math::VectorNd::Constant(m_model->dof_count, 0);
	Math::VectorNd q = zero;

	for(size_t i = 0; i < m_jointList.size(); ++i)
	{
		double angle = m_kf->joints[i].position;
		const std::string& name = m_jointList[i];

		if(m_jointList[i].empty())
			continue;

		int idx = m_model->jointIndex(name)-1;
		if(idx >= (int)m_model->dof_count)
		{
			ROS_ERROR("idx");
			abort();
		}

		q[idx] = angle;
	}

	RigidBodyDynamics::UpdateKinematics(*m_model, q, zero, zero);

	if(m_bodyIdx >= (int)m_model->X_base.size())
	{
		ROS_ERROR("bodyIDx");
		abort();
	}
	Math::SpatialTransform X = m_model->X_base[m_bodyIdx];

	m_ui->xSlider->blockSignals(true);
	m_ui->ySlider->blockSignals(true);
	m_ui->zSlider->blockSignals(true);
	m_ui->pitchSlider->blockSignals(true);
	m_ui->rollSlider->blockSignals(true);
	m_ui->yawSlider->blockSignals(true);

	m_ui->xBox->blockSignals(true);
	m_ui->yBox->blockSignals(true);
	m_ui->zBox->blockSignals(true);
	m_ui->rollBox->blockSignals(true);
	m_ui->pitchBox->blockSignals(true);
	m_ui->yawBox->blockSignals(true);

	m_ui->xSlider->setValue(X.r.x() / FACTOR);
	m_ui->ySlider->setValue(X.r.y() / FACTOR);
	m_ui->zSlider->setValue(X.r.z() / FACTOR);

	m_ui->xBox->setValue(X.r.x());
	m_ui->yBox->setValue(X.r.y());
	m_ui->zBox->setValue(X.r.z());

	Eigen::Vector3d euler = X.E.transpose().eulerAngles(2, 1, 0);

	m_ui->pitchBox->setValue(euler.y());
	m_ui->rollBox->setValue(euler.z());
	m_ui->yawBox->setValue(euler.x());

	m_ui->pitchSlider->setValue(euler.y() / FACTOR);
	m_ui->rollSlider->setValue(euler.z() / FACTOR);
	m_ui->yawSlider->setValue(euler.x() / FACTOR);

	m_ui->xSlider->blockSignals(false);
	m_ui->ySlider->blockSignals(false);
	m_ui->zSlider->blockSignals(false);
	m_ui->pitchSlider->blockSignals(false);
	m_ui->rollSlider->blockSignals(false);
	m_ui->yawSlider->blockSignals(false);

	m_ui->xBox->blockSignals(false);
	m_ui->yBox->blockSignals(false);
	m_ui->zBox->blockSignals(false);
	m_ui->rollBox->blockSignals(false);
	m_ui->pitchBox->blockSignals(false);
	m_ui->yawBox->blockSignals(false);
}


text:
var sys = require('sys'),
    exec = require('child_process').exec,
    path = require('path'),
    colors = require('colors'),
    isVerbose = process.argv[2] == '--verbose',
    _ = require('lodash');

var files = [
  "spec/integration_it.js",
  "spec/integration_it_async.js",
  "spec/integration_describe.js",
  "spec/integration_root.js"
];

_.each(files, function(file) {
  var filePath = path.join(process.cwd(), file);

  exec("node " + filePath, function(err, stdout, stderr) {
    if(err === null) {

      if(isVerbose) {
        console.log(stdout);
      }

      console.log(("Tested " + filePath).green);
    } else {
      console.log(("Failure in " + filePath).red + "\n");
      console.log(err.toString());

      process.exit(1);
    }
  });

});