text:
#include "rhodes/JNIRhodes.h"
#include "rhodes/JNIRhoRuby.h"

#include "rhodes/RhoClassFactory.h"

#include <ruby/ext/rho/rhoruby.h>

#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "Callbacks"

extern "C" void rho_webview_navigate(const char* url, int index);

RHO_GLOBAL void rho_map_location(char* query)
{
    rho::String url = "http://maps.google.com/?";
    url += query;
    rho_webview_navigate(url.c_str(), 0);
}

RHO_GLOBAL void rho_appmanager_load( void* /*httpContext*/, const char* /*szQuery*/)
{
    // Nothing
}

RHO_GLOBAL VALUE rho_sys_has_network()
{
    JNIEnv *env = jnienv();
    jclass cls = getJNIClass(RHODES_JAVA_CLASS_RHODES_SERVICE);
    if (!cls) return rho_ruby_create_boolean(0);
    jmethodID mid = getJNIClassStaticMethod(env, cls, "hasNetwork", "()Z");
    if (!mid) return rho_ruby_create_boolean(0);
    return rho_ruby_create_boolean(env->CallStaticBooleanMethod(cls, mid));
}

RHO_GLOBAL void rho_file_impl_delete_files_in_folder(const char *szFolderPath)
{
    JNIEnv *env = jnienv();
    jclass cls = getJNIClass(RHODES_JAVA_CLASS_RHODES_SERVICE);
    if (!cls) return;
    jmethodID mid = getJNIClassStaticMethod(env, cls, "deleteFilesInFolder", "(Ljava/lang/String;)V");
    if (!mid) return;
    jhstring objFolderPath = rho_cast<jhstring>(szFolderPath);
    env->CallStaticVoidMethod(cls, mid, objFolderPath.get());
}

RHO_GLOBAL void rho_file_impl_delete_folder(const char* szFolderPath) {
    /*
    JNIEnv *env = jnienv();
    jclass cls = getJNIClass(RHODES_JAVA_CLASS_RHODES_SERVICE);
    if (!cls) return;
    jmethodID mid = getJNIClassStaticMethod(env, cls, "deleteFolder", "(Ljava/lang/String;)V");
    if (!mid) return;
    jhstring objFolderPath = rho_cast<jhstring>(szFolderPath);
    env->CallStaticVoidMethod(cls, mid, objFolderPath.get());
     */

}

RHO_GLOBAL void rho_file_impl_copy_folders_content_to_another_folder(const char* szSrcFolderPath, const char* szDstFolderPath) {
    /*
    JNIEnv *env = jnienv();
    jclass cls = getJNIClass(RHODES_JAVA_CLASS_RHODES_SERVICE);
    if (!cls) return;
    jmethodID mid = getJNIClassStaticMethod(env, cls, "copyFoldersContentToAnotherFolder", "(Ljava/lang/String;Ljava/lang/String;)V");
    if (!mid) return;
    jhstring objSrcFolderPath = rho_cast<jhstring>(szSrcFolderPath);
    jhstring objDstFolderPath = rho_cast<jhstring>(szDstFolderPath);
    env->CallStaticVoidMethod(cls, mid, objSrcFolderPath.get(), objDstFolderPath.get());
     */
}

RHO_GLOBAL void rho_platform_restart_application() {

}

RHO_GLOBAL VALUE rho_sys_makephonecall(const char* callname, int nparams, char** param_names, char** param_values)
{
    // TODO:
    RHO_NOT_IMPLEMENTED;
    return 0;
}

RHO_GLOBAL void rho_net_impl_network_indicator(int enable)
{
    // No GUI indicator on Android
}

RHO_GLOBAL int rho_net_ping_network(const char* szHost)
{
    JNIEnv *env = jnienv();
    jclass cls = getJNIClass(RHODES_JAVA_CLASS_RHODES_SERVICE);
    if (!cls) return 0;
    jmethodID mid = getJNIClassStaticMethod(env, cls, "pingHost", "(Ljava/lang/String;)Z");
    if (!mid) return 0;
	return (int)env->CallStaticBooleanMethod(cls, mid, rho_cast<jhstring>(szHost).get());
}

rho::String rho_sysimpl_get_phone_id()
{
    JNIEnv *env = jnienv();

    jclass cls = getJNIClass(RHODES_JAVA_CLASS_RHODES_SERVICE);
    if (!cls) return 0;
    jmethodID mid = getJNIClassStaticMethod(env, cls, "getProperty", "(Ljava/lang/String;)Ljava/lang/Object;");
    if (!mid) return 0;

    jhstring propNameObj = rho_cast<jhstring>("phone_id");
    jhobject result = jhobject(env->CallStaticObjectMethod(cls, mid, propNameObj.get()));
    if (!result) return 0;

    jstring resStrObj = (jstring)result.get();
    return rho_cast<std::string>(resStrObj);
}

RHO_GLOBAL int rho_sysimpl_get_property(char* szPropName, VALUE* resValue)
{
    JNIEnv *env = jnienv();

    jclass cls = getJNIClass(RHODES_JAVA_CLASS_RHODES_SERVICE);
    if (!cls) return 0;
    jmethodID mid = getJNIClassStaticMethod(env, cls, "getProperty", "(Ljava/lang/String;)Ljava/lang/Object;");
    if (!mid) return 0;

    jhstring propNameObj = rho_cast<jhstring>(szPropName);
    jhobject result = jhobject(env->CallStaticObjectMethod(cls, mid, propNameObj.get()));
    if (!result) return 0;

    jclass clsBoolean = getJNIClass(RHODES_JAVA_CLASS_BOOLEAN);
    jclass clsInteger = getJNIClass(RHODES_JAVA_CLASS_INTEGER);
    jclass clsFloat = getJNIClass(RHODES_JAVA_CLASS_FLOAT);
    jclass clsDouble = getJNIClass(RHODES_JAVA_CLASS_DOUBLE);
    jclass clsString = getJNIClass(RHODES_JAVA_CLASS_STRING);

    if (env->IsInstanceOf(result.get(), clsBoolean)) {
        jmethodID midValue = getJNIClassMethod(env, clsBoolean, "booleanValue", "()Z");
        *resValue = rho_ruby_create_boolean((int)env->CallBooleanMethod(result.get(), midValue));
        return 1;
    }
    else if (env->IsInstanceOf(result.get(), clsInteger)) {
        jmethodID midValue = getJNIClassMethod(env, clsInteger, "intValue", "()I");
        *resValue = rho_ruby_create_integer((int)env->CallIntMethod(result.get(), midValue));
        return 1;
    }
    else if (env->IsInstanceOf(result.get(), clsFloat)) {
        jmethodID midValue = getJNIClassMethod(env, clsFloat, "floatValue", "()F");
        *resValue = rho_ruby_create_double((double)env->CallFloatMethod(result.get(), midValue));
        return 1;
    }
    else if (env->IsInstanceOf(result.get(), clsDouble)) {
        jmethodID midValue = getJNIClassMethod(env, clsDouble, "doubleValue", "()D");
        *resValue = rho_ruby_create_double((double)env->CallDoubleMethod(result.get(), midValue));
        return 1;
    }
    else if (env->IsInstanceOf(result.get(), clsString)) {
        jstring resStrObj = (jstring)result.get();
        *resValue = rho_ruby_create_string(rho_cast<std::string>(resStrObj).c_str());
        return 1;
    }

    return 0;
}

RHO_GLOBAL int rho_sys_set_sleeping(int sleeping) {
    JNIEnv *env = jnienv();
    jclass cls = getJNIClass(RHODES_JAVA_CLASS_RHODES_SERVICE);
    if (!cls) return 0;
    jmethodID mid = getJNIClassStaticMethod(env, cls, "rho_sys_set_sleeping", "(I)I");
    if (!mid) return 0;
    return env->CallStaticIntMethod(cls, mid, sleeping);
}

RHO_GLOBAL VALUE rho_sys_get_locale()
{
    VALUE res;
    if ( rho_sysimpl_get_property((char*)"locale", &res) )
        return res;

    return rho_ruby_get_NIL();
}

RHO_GLOBAL int rho_sys_get_screen_width()
{
    VALUE res;
    if ( rho_sysimpl_get_property((char*)"screen_width", &res) )
        return NUM2INT(res);

    return 0;
}

RHO_GLOBAL int rho_sys_get_screen_height()
{
    VALUE res;
    if ( rho_sysimpl_get_property((char*)"screen_height", &res) )
        return NUM2INT(res);

    return 0;
}

RHO_GLOBAL void rho_sys_app_exit()
{
    JNIEnv *env = jnienv();
    jclass cls = getJNIClass(RHODES_JAVA_CLASS_RHODES_SERVICE);
    if (!cls) return;
    jmethodID mid = getJNIClassStaticMethod(env, cls, "exit", "()V");
    if (!mid) return;
    env->CallStaticVoidMethod(cls, mid);
}

RHO_GLOBAL void rho_sys_run_app(const char *appname, VALUE params)
{
    JNIEnv *env = jnienv();
    jclass cls = getJNIClass(RHODES_JAVA_CLASS_RHODES_SERVICE);
    if (!cls) return;
    jmethodID mid = getJNIClassStaticMethod(env, cls, "runApplication", "(Ljava/lang/String;Ljava/lang/Object;)V");
    if (!mid) return;
    jhobject jhParams = rho_cast<jobject>(env, params);
    env->CallStaticVoidMethod(cls, mid, rho_cast<jhstring>(env, appname).get(), jhParams.get());
}

RHO_GLOBAL void rho_sys_bring_to_front()
{
    JNIEnv *env = jnienv();
    jclass cls = getJNIClass(RHODES_JAVA_CLASS_RHODES_SERVICE);
    if (!cls) return;
    jmethodID mid = getJNIClassStaticMethod(env, cls, "bringToFront", "()V");
    if (!mid) return;
    env->CallStaticVoidMethod(cls, mid);
}

RHO_GLOBAL void rho_sys_report_app_started()
{
    JNIEnv *env = jnienv();
    jclass cls = getJNIClass(RHODES_JAVA_CLASS_RHODES_SERVICE);
    if (!cls) return;
    jmethodID mid = getJNIClassStaticMethod(env, cls, "handleAppStarted", "()V");
    if (!mid) return;
    env->CallStaticVoidMethod(cls, mid);
}

RHO_GLOBAL void rho_sys_open_url(const char *url)
{
    JNIEnv *env = jnienv();
    jclass cls = getJNIClass(RHODES_JAVA_CLASS_RHODES_SERVICE);
    if (!cls) return;
    jmethodID mid = getJNIClassStaticMethod(env, cls, "openExternalUrl", "(Ljava/lang/String;)V");
    if (!mid) return;
    env->CallStaticVoidMethod(cls, mid, rho_cast<jhstring>(url).get());
}

RHO_GLOBAL int rho_sys_is_app_installed(const char *appname)
{
    JNIEnv *env = jnienv();
    jclass cls = getJNIClass(RHODES_JAVA_CLASS_RHODES_SERVICE);
    if (!cls) return 0;
    jmethodID mid = getJNIClassStaticMethod(env, cls, "isAppInstalled", "(Ljava/lang/String;)Z");
    if (!mid) return 0;
    return (int)env->CallStaticBooleanMethod(cls, mid, rho_cast<jhstring>(appname).get());
}

RHO_GLOBAL void rho_sys_app_install(const char *url)
{
    JNIEnv *env = jnienv();
    jclass cls = getJNIClass(RHODES_JAVA_CLASS_RHODES_SERVICE);
    if (!cls) return;
    jmethodID mid = getJNIClassStaticMethod(env, cls, "installApplication", "(Ljava/lang/String;)V");
    if (!mid) return;
    env->CallStaticVoidMethod(cls, mid, rho_cast<jhstring>(url).get());
}

RHO_GLOBAL void rho_sys_app_uninstall(const char *appname)
{
    JNIEnv *env = jnienv();
    jclass cls = getJNIClass(RHODES_JAVA_CLASS_RHODES_SERVICE);
    if (!cls) return;
    jmethodID mid = getJNIClassStaticMethod(env, cls, "uninstallApplication", "(Ljava/lang/String;)V");
    if (!mid) return;
    env->CallStaticVoidMethod(cls, mid, rho_cast<jhstring>(appname).get());
}

RHO_GLOBAL void rho_sys_set_application_icon_badge(int badge_number) {
    //unsupported on Android
}


text:
class GraphView:public QWidget{
    Q_OBJECT
public:
    GraphView(QWidget* parent, char * name);
public slots:
    void loadImage(Image im);
    void clearImage();

    void loadGraph(GraphDiscription);

    void resizeEvent(QResizeEvent* e);
    void paintEvent(QPaintEvent*);

    void getPoint(int& x, int &y, const Vert& vert) const;
    void setPoint(int x, int y, Vert& vert) const ;
    void setDiscription(GraphDiscription d);

    virtual void mousePressEvent ( QMouseEvent * me);
    virtual void mouseMoveEvent ( QMouseEvent * me);
    virtual void mouseReleaseEvent ( QMouseEvent * me);

signals:
    void pointChanged(int, double, double);

private:
    QImage image;
    QString fname;

    Image im;
    GraphDiscription disc;
    int sPoint;
    int mouseTrack;

};

#endif

redpajama_set_name: RedPajamaGithub


text:
const path = require('path')
module.exports = function (err, callingModule, t) {
  const moduleName = path.basename(callingModule.id, '.js')
  let errorTitle
  let errorMessage
  if (!err) {
    errorTitle = errorMessage = `Error missing: ${moduleName}`
  } else if (typeof err === 'string') {
    errorTitle = errorMessage = `${err}: ${moduleName}`
  } else {
    errorTitle = err.message
    errorMessage = `
    Module: ${moduleName}
    Name: ${err.name}
    Message: ${err.message}
    ${err.stack}\n
    `
  }

  console.error(errorMessage)
  console.error(err)
  t.fail(errorTitle)
  return errorMessage
}


text:
/**
 * Renders a chart for each workspace
 */
var Chart = Backbone.View.extend({
    initialize: function(args) {
        this.workspace = args.workspace;

        // Create a unique ID for use as the CSS selector
        this.id = _.uniqueId("chart_");
        $(this.el).attr({ id: this.id });

        // Bind table rendering to query result event
        _.bindAll(this, "render", "receive_data", "process_data", "show",
            "setOptions");
        this.workspace.bind('query:result', this.receive_data);

        // Add chart button
        this.add_button();
        this.workspace.toolbar.chart = this.show;

        // Listen to adjust event and rerender chart
        this.workspace.bind('workspace:adjust', this.render);
        var chartoptions ="
" +
                "bar" +
                "stacked bar" +
                "line" +
                "pie" +
                "heatgrid";

        var exportoptions = "Export to: " +
                "PNG, " +
                "PDF, " +
                "TIFF, " +
                "SVG, " +
                "JPG" +
                "<form id='svgChartPseudoForm' action='/saiku/svg' method='POST'>" +
                "<input type='hidden' name='type' class='type'/>" +
                "<input type='hidden' name='svg' class='svg'/>" +
                "</form>";

        var chartnav = (Settings.PLUGIN) ? chartoptions + "
" : chartoptions + exportoptions + "
";

        // Create navigation
        this.nav = $(chartnav).css({
        		    'padding-bottom': '10px'
        		});
        this.nav.find('a.type').css({
                    color: '#666',
                    'margin-right': '5px',
                    'text-decoration': 'none',
                    'border': '1px solid #ccc',
                    padding: '5px'
                })
                .click(this.setOptions);
        this.nav.find('a.export').click(this.exportChart);

        // Append chart to workspace
        $(this.workspace.el).find('.workspace_results')
            .prepend($(this.el).hide())
            .prepend(this.nav.hide());
    },

    add_button: function() {
        var $chart_button =
            $('')
            .css({  'background-image': "url('js/saiku/plugins/Chart/chart.png')",
                    'background-repeat':'no-repeat',
                    'background-position':'50% 50%'
                });

        var $chart_li = $('

').append($chart_button);
        $(this.workspace.toolbar.el).find("ul").append($chart_li);

    },

    show: function(event, ui) {
        $(this.workspace.el).find('.workspace_results table').toggle();
        $(this.el).toggle();
        $(this.nav).toggle();
        $(event.target).toggleClass('on');

        if ($(event.target).hasClass('on')) {
            this.process_data({ data: this.workspace.query.result.lastresult() });
            this.render();
        }
    },

    setOptions: function(event) {
        var type = $(event.target).attr('href').replace('#', '');
        try {
            this[type]();
        } catch (e) { }

        return false;
    },

    exportChart: function(event) {
        var type = $(event.target).attr('href').replace('#', '');
        var svgContent = new XMLSerializer().serializeToString($('svg')[0]);
        var form = $('#svgChartPseudoForm');
        form.find('.type').val(type);
        form.find('.svg').val(svgContent);
        form.submit();
        return false;
    },

    stackedBar: function() {
        this.options.stacked = true;
        this.options.type = "BarChart";
        this.render();
    },

    bar: function() {
        this.options.stacked = false;
        this.options.type = "BarChart";
        this.render();
    },

    line: function() {
        this.options.stacked = false;
        this.options.type = "LineChart";
        this.render();
    },

    pie: function() {
        this.options.stacked = false;
        this.options.type = "PieChart";
        this.render();
    },

    heatgrid: function() {
        this.options.stacked = false;
        this.options.type = "HeatGridChart";
        this.render();
    },

    render: function() {
        if (! $(this.workspace.toolbar.el).find('.chart').hasClass('on')) {
            return;
        }

        var options = _.extend({
            canvas: this.id,
            width: $(this.workspace.el).find('.workspace_results').width() - 40,
            height: $(this.workspace.el).find('.workspace_results').height() - 40,
            yAxisSize: 70,
            orientation: 'vertical',
            stacked: false,
            animate: false,
            showValues: false,
            legend: true,
            legendPosition:"top",
            legendAlign: "right",
            colors: ["#4bb2c5", "#c5b47f", "#EAA228", "#579575", "#839557", "#958c12", "#953579", "#4b5de4", "#d8b83f", "#ff5800", "#0085cc"],
            type: 'BarChart'
        }, this.options);

        if (options.type == "HeatGridChart") {
            options = _.extend({
                    canvas: this.id,
                    width: $(this.workspace.el).find('.workspace_results').width() - 40,
                    height: $(this.workspace.el).find('.workspace_results').height() - 40,
                    animate: false,
                    clickable: false,
                    orientation: "horizontal",
                    showValues: false,
                    showXScale: true,
                    xAxisPosition: "bottom",
                    showYScale: true,
                    panelSizeRatio: 0.8,
                    yAxisPosition: "left",
                    yAxisSize: 150,
                    minColor: "#FFFFFF",
                    maxColor: "green",
                    extensionPoints: {
                        xAxisLabel_textAngle: -(Math.PI / 2),
                        xAxisLabel_textAlign: "right",
                        xAxisLabel_bottom: 10
                    }
            }, this.options);
        }
        if (this.data.resultset.length > 5 ) {
            options.extensionPoints = {
                xAxisLabel_textAngle: -(Math.PI / 2),
                xAxisLabel_textAlign: "right",
                xAxisLabel_bottom: 10
            };

            options.xAxisSize = 100;
        }

        this.chart = new pvc[options.type](options);

        this.chart.setData(this.data, {
            crosstabMode: true,
            seriesInRows: false
        });

        try {
            this.chart.render();
            Saiku.i18n.automatic_i18n();
        } catch (e) {
            $(this.el).text("Could not render chart");
        }
    },

    receive_data: function(args) {
        if (! $(this.workspace.toolbar.el).find('.chart').hasClass('on')) {
            return;
        }
        return _.delay(this.process_data, 0, args);
    },

    process_data: function(args) {
        this.data = {};
        this.data.resultset = [];
        this.data.metadata = [];
        this.data.height = 0;
        this.data.width = 0;

        var cellset = args.data.cellset;
        if (cellset && cellset.length > 0) {

            var lowest_level = 0;
            var data_start = 0;
            for (var row = 0; data_start == 0 && row < cellset.length; row++) {
                    this.data.metadata = [];
                    for (var field = 0; field < cellset[row].length; field++) {
                        var firstHeader = [];

                        while (cellset[row][field].type == "COLUMN_HEADER" && cellset[row][field].value == "null") {
                            row++;
                        }
                        if (cellset[row][field].type == "ROW_HEADER_HEADER") {

                            while(cellset[row][field].type == "ROW_HEADER_HEADER") {
                                firstHeader.push(cellset[row][field].value);
                                field++;
                            }

                            this.data.metadata.push({
                                colIndex: 0,
                                colType: "String",
                                colName: firstHeader.join('/')
                            });
                            lowest_level = field - 1;
                        }
                        if (cellset[row][field].type == "COLUMN_HEADER" && cellset[row][field].value != "null") {
                            var lowest_col_header = 0;
                            var colheader = [];
                            while(lowest_col_header <= row) {
                                colheader.push(cellset[lowest_col_header][field].value);
                                lowest_col_header++;
                            }
                            this.data.metadata.push({
                                colIndex: field - lowest_level + 1,
                                colType: "Numeric",
                                colName: colheader.join('/')
                            });

                            data_start = row+1;
                        }
                    }
            }
            var labelsSet = {};
            for (var row = data_start; row < cellset.length; row++) {
            if (cellset[row][0].value !== "") {
                    var record = [];
                    this.data.width = cellset[row].length - lowest_level + 1;
                    var label = "";
                    for (var labelCol = lowest_level; labelCol >= 0; labelCol--) {
                        var lastKnownUpperLevelRow = row;
                        while(cellset[lastKnownUpperLevelRow] && cellset[lastKnownUpperLevelRow][labelCol].value === 'null') {
                            --lastKnownUpperLevelRow;
                        }
                        if(cellset[lastKnownUpperLevelRow]) {
                            if (label == "") {
                                label = cellset[lastKnownUpperLevelRow][labelCol].value;
                            } else {
                                label = cellset[lastKnownUpperLevelRow][labelCol].value + " / " + label;
                            }
                        }
                    }
                    if(label in labelsSet) {
                        labelsSet[label] = labelsSet[label]+1;
                        label = label + ' [' + (labelsSet[label] + 1) + ']';
                    } else {
                        labelsSet[label] = 0;
                    }
                    record.push(label);

                    for (var col = lowest_level + 1; col < cellset[row].length; col++) {
                        var cell = cellset[row][col];
                        var value = cell.value || 0;
                        // check if the resultset contains the raw value, if not try to parse the given value
                        var raw = cell.properties.raw;
                        if (raw && raw !== "null") {
                            value = parseFloat(raw);
                        } else if (typeof(cell.value) !== "number" && parseFloat(cell.value.replace(/[^a-zA-Z 0-9.]+/g,''))) {
                            value = parseFloat(cell.value.replace(/[^a-zA-Z 0-9.]+/g,''));
                        }
                        record.push(value);
                    }
                    this.data.resultset.push(record);
                }
            }
            //makeSureUniqueLabels(this.data.resultset);
            this.data.height = this.data.resultset.length;
            this.render();
        } else {
            $(this.el).text("No results");
        }
    }
});

/**
 * Loads CCC and initializes chart plugin
 */
(function() {
    // Initialize CCC
    $.ajax({
        url: "js/saiku/plugins/Chart/ccc.js",
        dataType: "script",
        cache: true,
        success: function() {

            var initPlugin = function(session) {
                function new_workspace(args) {
                    // Add chart element
                    if (typeof args.workspace.chart == "undefined") {
                        args.workspace.chart = new Chart({ workspace: args.workspace });
                    }
                }

                function clear_workspace(args) {
                    if (typeof args.workspace.chart != "undefined") {
                        $(args.workspace.chart.nav).hide();
                        $(args.workspace.chart.el).hide();
                        $(args.workspace.chart.el).parents().find('.workspace_results table').show();
                    }
                }

                // Attach chart to existing tabs
                for(var i = 0; i < Saiku.tabs._tabs.length; i++) {
                    var tab = Saiku.tabs._tabs[i];
                    new_workspace({
                        workspace: tab.content
                    });
                };

                // Attach chart to future tabs
                session.bind("workspace:new", new_workspace);
                session.bind("workspace:clear", clear_workspace);
            };

            if (typeof Saiku.session == "undefined") {
                Saiku.events.bind('session:new', initPlugin);
            } else {
                initPlugin(Saiku.session);
            }
        }
    });
}());


text:
package jcuda.driver;

/**
 * Flags for mapping and unmapping interop resources
 */
public class CUgraphicsRegisterFlags
{
    public static final int CU_GRAPHICS_REGISTER_FLAGS_NONE  = 0x00;

    public static final int CU_GRAPHICS_REGISTER_FLAGS_READ_ONLY     = 0x01;

    public static final int CU_GRAPHICS_REGISTER_FLAGS_WRITE_DISCARD = 0x02;

    public static final int CU_GRAPHICS_REGISTER_FLAGS_SURFACE_LDST  = 0x04;

    public static final int CU_GRAPHICS_REGISTER_FLAGS_TEXTURE_GATHER = 0x08;

    /**
     * Returns the String identifying the given CUgraphicsRegisterFlags
     *
     * @param n The CUgraphicsRegisterFlags
     * @return The String identifying the given CUgraphicsRegisterFlags
     */
    public static String stringFor(int n)
    {
        if (n == 0)
        {
            return "CU_GRAPHICS_REGISTER_FLAGS_NONE";
        }
        String result = "";
        if ((n & CU_GRAPHICS_REGISTER_FLAGS_READ_ONLY    ) != 0) result += "CU_GRAPHICS_REGISTER_FLAGS_READ_ONLY ";
        if ((n & CU_GRAPHICS_REGISTER_FLAGS_WRITE_DISCARD) != 0) result += "CU_GRAPHICS_REGISTER_FLAGS_WRITE_DISCARD ";
        if ((n & CU_GRAPHICS_REGISTER_FLAGS_SURFACE_LDST ) != 0) result += "CU_GRAPHICS_REGISTER_FLAGS_SURFACE_LDST ";
        if ((n & CU_GRAPHICS_REGISTER_FLAGS_TEXTURE_GATHER ) != 0) result += "CU_GRAPHICS_REGISTER_FLAGS_TEXTURE_GATHER ";
        return result;
    }

    /**
     * Private constructor to prevent instantiation.
     */
    private CUgraphicsRegisterFlags()
    {
    }

}


text:
<?php
return array(

	// see https://msdn.microsoft.com/en-gb/library/ee825488%28v=cs.20%29.aspx for a full list of language cultures
	// this *is* case-sensitive and match the culture exactly for best interoperability with translating tools
	// this will be used as the defaul language culture
	// if this is set to empty, then it will default to en-GB from within the base maverick class itself, you should not specify the .utf8 ending for this!
	// finally, you can use either hyphens or the underscore here, as hyphens will be replaced by underscores internally
	'default' => 'en-GB',

	'active' => true,	// set this to true if you want to make use of i18n translation features in your application

	'pagination_first' => '↞',
	'pagination_last' => '↠',
	'pagination_prev' => '←',
	'pagination_next' => '→',
);


text:
"""
Authors:  Damien Irving (irving.damien@gmail.com)

Copyright 2015 CSIRO

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.

This module wraps a shell script that calculates the field correlation:
cwsl-ctools/statistics/cdo_fldcor.sh

Part of the CWSLab Model Analysis Service VisTrails plugin.

"""

from vistrails.core.modules import vistrails_module, basic_modules

from cwsl.configuration import configuration
from cwsl.core.constraint import Constraint
from cwsl.core.process_unit import ProcessUnit
from cwsl.core.pattern_generator import PatternGenerator

class FieldCorrelation(vistrails_module.Module):
    """Field correlation.

    Wraps the cwsl-ctools/statistics/cdo_fldcor.sh script.

    """

    _input_ports = [('in_dataset1', 'csiro.au.cwsl:VtDataSet',
                     {'labels': str(['Input dataset 1'])}),
                    ('in_dataset2', 'csiro.au.cwsl:VtDataSet',
                     {'labels': str(['Input dataset 2'])}),
                    ('merge_constraints', basic_modules.String,
                     {'labels': str(['Constraints to merge']),
                      'defaults': str([''])})]

    _output_ports = [('out_dataset', 'csiro.au.cwsl:VtDataSet')]

    _execution_options = {'required_modules': ['cdo', 'python/2.7.5', 'python-cdat-lite/6.0rc2-py2.7.5']}

    command = '${CWSL_CTOOLS}/statistics/cdo_fldcor.sh'

    def __init__(self):

        super(FieldCorrelation, self).__init__()
        self.out_pattern = PatternGenerator('user', 'default').pattern

    def compute(self):

        in_dataset1 = self.getInputFromPort('in_dataset1')
        in_dataset2 = self.getInputFromPort('in_dataset2')

        self.positional_args = []
        self.keyword_args = {}

        new_constraints_for_output = set([Constraint('extra_info', ['fldcor']),
                                          Constraint('suffix', ['nc'])])

        merge_val =  self.getInputFromPort('merge_constraints')
        if merge_val:
            extra_merge = [cons_name.strip() for cons_name in merge_val.split(',')]
        else:
            extra_merge = []

        this_process = ProcessUnit([in_dataset1, in_dataset2],
                                   self.out_pattern,
                                   self.command,
                                   new_constraints_for_output,
                                   execution_options=self._execution_options,
                                   positional_args=self.positional_args,
                                   cons_keywords=self.keyword_args,
                                   merge_output=extra_merge)

        try:
            this_process.execute(simulate=configuration.simulate_execution)
        except Exception as e:
            raise vistrails_module.ModuleError(self, repr(e))

        process_output = this_process.file_creator

        self.setResult('out_dataset', process_output)


text:
public class SequenceFeature {

    private String accession;
    private long end5;
    private long end3;

    private String organismName = null;
    private String moleculeName = null;

    // constructor
    public SequenceFeature (String accession, long end5, long end3) {

	this.accession = accession;
	this.end5 = end5;
	this.end3 = end3;

    }

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

    public String get_organismName () {
	return (this.organismName);
    }

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

    public String get_moleculeName () {
	return (this.moleculeName);
    }

    public String get_accession () {
	return (this.accession);
    }

    public long end5() {
	return (this.end5);
    }

    public long end3() {
	return (this.end3);
    }

    public long midPt() {
	return ( (this.end5 + this.end3)/2);
    }

    public String toString() {

	String text = moleculeName + "\t" + accession + "\t" + String.valueOf(end5) + "\t" + String.valueOf(end3);

	return (text);
    }
}


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

namespace WebSocket4Net.Common
{
    public interface ICommandInfo
    {
        string Key { get; }
    }

    public interface ICommandInfo<TCommandData> : ICommandInfo
    {
        TCommandData Data { get; }
    }
}


text:
require "openssl"
require "net/ldap"

module Velum
  # LDAPMock is a mock object to test LDAP connectors without a server
  class LDAPMock
    attr_accessor :host, :port, :start_tls, :cert, :anon_bind, :dn, :pass, :ldap_mock_cfg

    def initialize(ldap_params, auth_hash, tls_method)
      @host = ldap_params[:host].downcase
      @port       = ldap_params[:port]
      @start_tls  = ldap_params[:start_tls]
      @cert       = ldap_params[:cert].tr(" \t\r\n", "")
      @anon_bind  = ldap_params[:anon_bind]
      @dn         = ldap_params[:dn].downcase
      @pass       = ldap_params[:pass]
      @base_dn    = ldap_params[:base_dn].downcase
      @filter     = ldap_params[:filter]

      @auth_hash = auth_hash
      @tls_method = tls_method

      @ldap_mock_cfg = load_ldap_mock
      check_cert
    end

    # Compares certs with space/tab/return/newline removed
    def check_cert
      # :nocov:
      raise OpenSSL::X509::CertificateError if cert.tr(" \t\r\n", "") != \
          ldap_mock_cfg["cert"].tr(" \t\r\n", "")
      # :nocov:
    end

    # Loads mock object properties from ldap_mock.yml
    def load_ldap_mock
      YAML.load_file(::Rails.root.join("config", "ldap_mock.yml"))
    end

    # Replicates "net/ldap" method
    # rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity, Metrics/AbcSize
    def bind
      raise Net::LDAP::Error unless host == ldap_mock_cfg["host"].downcase

      if start_tls == "true"
        raise Net::LDAP::Error unless port == ldap_mock_cfg["start_tls_port"].to_s
      else
        raise Net::LDAP::Error unless port == ldap_mock_cfg["simple_tls_port"].to_s
      end

      if anon_bind == "true"
        raise Net::LDAP::Error if ldap_mock_cfg["anon_bind"] != true
        return true
      end

      dn == ldap_mock_cfg["dn"].downcase && pass == ldap_mock_cfg["pass"]
    end
    # rubocop:enable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity, Metrics/AbcSize

    # Replicates "net/ldap" method
    # rubocop:disable Naming/AccessorMethodName
    def get_operation_result
      os = OpenStruct.new
      os.message = "mock test message"
      os
    end
    # rubocop:enable Naming/AccessorMethodName

    # Replicates "net/ldap" method
    def search(base:, filter:, attributes:, return_result:)
      if base == ldap_mock_cfg["base_dn"].downcase &&
          filter == Net::LDAP::Filter.construct(ldap_mock_cfg["filter"])
        # attributes, return_result must be used to keep rubocop happy
        ["user0", "user1", attributes, return_result]
      else
        []
      end
    end
  end
end


text:
//  define null for compatibility with original Java source code.
#define null 0

#include <xercesc/dom/DOM.hpp>

XERCES_CPP_NAMESPACE_USE

XERCES_CPP_NAMESPACE_BEGIN
class XercesDOMParser;
XERCES_CPP_NAMESPACE_END

class TypeInfo {

public:
	TypeInfo();
	~TypeInfo();

    bool testInBuiltTypesOnElements();
    bool testInBuiltTypesOnAttributes(bool DTDPresent);
    bool testSimpleDerived();
    bool testComplexTypes();
    bool testUnions();
    bool testAnonymous();
    bool testXsiTypes();
    bool testInvaild();
    bool testAnys();
    bool testDTD();
    bool combinedTest();

    bool compareDOMTypeInfo(const DOMTypeInfo *info, const XMLCh* type, const XMLCh* uri);

	XercesDOMParser *parser;
    DOMDocument *doc;

private:

    DOMElement* findElement(const XMLCh *name) const ;

};


text:
'use strict'

var Readable = require('stream').Readable

module.exports = function (string, size) {
  var rs = new Readable()
  var start = 0
  var length = string.length
  var chunkSize = size || 4096
  var end = chunkSize
  var slice
  rs._read = function () {
    if (length <= chunkSize) {
      rs.push(string)
      return rs.push(null)
    }
    slice = string.slice(start, end)
    rs.push(slice)
    end += chunkSize
    start += chunkSize
    if (end > string.length) {
      slice = string.slice(start, string.length)
      rs.push(slice)
      rs.push(null)
    }
  }
  return rs
}


text:
package com.siyeh.ig.visibility;

import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.InspectionGadgetsFix;
import com.siyeh.ig.fixes.RenameFix;
import com.siyeh.ig.psiutils.ClassUtils;
import com.siyeh.ig.ui.MultipleCheckboxOptionsPanel;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;

public class LocalVariableHidingMemberVariableInspection
        extends BaseInspection {

    /** @noinspection PublicField*/
    public boolean m_ignoreInvisibleFields = true;
    /** @noinspection PublicField*/
    public boolean m_ignoreStaticMethods = true;

    @NotNull
    public String getID(){
        return "LocalVariableHidesMemberVariable";
    }

    @NotNull
    public String getDisplayName() {
        return InspectionGadgetsBundle.message(
                "local.variable.hides.member.variable.display.name");
    }

    protected InspectionGadgetsFix buildFix(Object... infos) {
        return new RenameFix();
    }

    protected boolean buildQuickFixesOnlyForOnTheFlyErrors() {
        return true;
    }

    @NotNull
    public String buildErrorString(Object... infos) {
        return InspectionGadgetsBundle.message(
                "local.variable.hides.member.variable.problem.descriptor");
    }

    public JComponent createOptionsPanel() {
        final MultipleCheckboxOptionsPanel optionsPanel =
                new MultipleCheckboxOptionsPanel(this);
        optionsPanel.addCheckbox(InspectionGadgetsBundle.message(
                "field.name.hides.in.superclass.ignore.option"),
                "m_ignoreInvisibleFields");
        optionsPanel.addCheckbox(InspectionGadgetsBundle.message(
                "local.variable.hides.member.variable.ignore.option"),
                "m_ignoreStaticMethods");
        return optionsPanel;
    }

    public BaseInspectionVisitor buildVisitor() {
        return new LocalVariableHidingMemberVariableVisitor();
    }

    private class LocalVariableHidingMemberVariableVisitor
            extends BaseInspectionVisitor {

        @Override public void visitLocalVariable(@NotNull PsiLocalVariable variable) {
            super.visitLocalVariable(variable);
            if (m_ignoreStaticMethods) {
                final PsiMethod aMethod =
                        PsiTreeUtil.getParentOfType(variable,
                                PsiMethod.class);
                if (aMethod == null) {
                    return;
                }
                if (aMethod.hasModifierProperty(PsiModifier.STATIC)) {
                    return;
                }
            }
            final PsiClass aClass =
                    ClassUtils.getContainingClass(variable);
            if (aClass == null) {
                return;
            }
            final String variableName = variable.getName();
            final PsiField[] fields = aClass.getAllFields();
            for(final PsiField field : fields){
                if(checkFieldName(field, variableName, aClass)){
                    registerVariableError(variable);
                }
            }
        }

        @Override public void visitParameter(@NotNull PsiParameter variable) {
            super.visitParameter(variable);
            if (!(variable.getDeclarationScope() instanceof PsiCatchSection)) {
                return;
            }
            final PsiClass aClass =
                    ClassUtils.getContainingClass(variable);
            if (aClass == null) {
                return;
            }
            final String variableName = variable.getName();
            final PsiField[] fields = aClass.getAllFields();
            for(final PsiField field : fields){
                if(checkFieldName(field, variableName, aClass)){
                    registerVariableError(variable);
                }
            }
        }

        private boolean checkFieldName(PsiField field, String variableName,
                                       PsiClass aClass) {
            if (field == null) {
                return false;
            }
            final String fieldName = field.getName();
            if (fieldName == null) {
                return false;
            }
            if (!fieldName.equals(variableName)) {
                return false;
            }
            return !m_ignoreInvisibleFields ||
                    ClassUtils.isFieldVisible(field, aClass);
        }
    }
}


text:
from google.cloud import automl_v1

def sample_create_model():
    # Create a client
    client = automl_v1.AutoMlClient()

    # Initialize request argument(s)
    request = automl_v1.CreateModelRequest(
        parent="parent_value",
    )

    # Make the request
    operation = client.create_model(request=request)

    print("Waiting for operation to complete...")

    response = operation.result()

    # Handle the response
    print(response)

# [END automl_v1_generated_AutoMl_CreateModel_sync]


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Build.BuildEngine;
using System.Collections;

namespace ProjectFileParser.platform_helpers
{
    internal class MonoPlatform : PlatformProjectHelper
    {
        public override void AddNewItem(Project project, string name, string include)
        {
            project.AddNewItemGroup().AddNewItem(name, include);
        }

        public override IEnumerable<Tuple<string, IEnumerable<BuildItem>>> GetEvaluatedItemsByName(Project project, bool ignoreCondition)
        {
            var dic = Reflection.GetProperty<IDictionary<string, BuildItemGroup>, Project>(project, ignoreCondition ? "EvaluatedItemsByNameIgnoringCondition" : "EvaluatedItemsByName");
            return dic.Select(e => Tuple.Create(e.Key, e.Value.Cast<BuildItem>()));
        }

        public override IEnumerable<Tuple<string, string>> GetEvaluatedMetadata(BuildItem proj)
        {
            var dic = Reflection.GetField<IDictionary, BuildItem>(proj, "evaluatedMetadata");
            return dic.Cast<DictionaryEntry>().Select(e => Tuple.Create((string)e.Key, (string)e.Value));
        }
    }
}


text:
namespace clusters {

}


text:
require "fast_spec_helper"
require "attr_extras"
require "lib/github_api"
require "json"
require "app/models/github_user"

describe GithubApi do
  let(:user_token) { "usergithubtoken" }
  let(:api) { GithubApi.new(user_token) }

  describe "#add_user_to_repo" do
    let(:username) { "testuser" }
    let(:organization) { "testing" }
    let(:repo_name) { "#{organization}/repo" }
    let(:team_id) { 4567 }

    context "when repo is part of an organization" do
      context "when repo is part of a team" do
        context "when request succeeds" do
          it "adds Hound user to first repo team with admin access and return true" do
            stub_common_requests(user_token)
            add_user_request =
              stub_add_user_to_team_request(username, team_id, user_token)

            expect(api.add_user_to_repo(username, repo_name)).to be_truthy
            expect(add_user_request).to have_been_requested
          end
        end

        context "when request fails" do
          it "tries to add Hound user to first repo team with admin access and returns false" do
            stub_common_requests(user_token)
            add_user_request = stub_failed_add_user_to_team_request(
              username,
              team_id,
              user_token
            )

            expect(api.add_user_to_repo(username, repo_name)).to be_falsy
            expect(add_user_request).to have_been_requested
          end
        end

        def stub_common_requests(token)
          stub_repo_with_org_request(repo_name, token)
          stub_repo_teams_request(repo_name, token)
          stub_user_teams_request(token)
        end
      end

      context "when repo is not part of a team" do
        context "when Services team does not exist" do
          it "creates a Services team and adds user to the new team" do
            team_id = 1234 # from fixture
            stub_repo_with_org_request(repo_name, user_token)
            stub_empty_repo_teams_request(repo_name, user_token)
            stub_team_creation_request(organization, repo_name, user_token)
            stub_org_teams_request(organization, user_token)
            add_user_request =
              stub_add_user_to_team_request(username, team_id, user_token)

            expect(api.add_user_to_repo(username, repo_name)).to be_truthy
            expect(add_user_request).to have_been_requested
          end
        end

        context "when team creation raises a validation error" do
          it "adds user to Services team" do
            stub_repo_with_org_request(repo_name, user_token)
            stub_empty_repo_teams_request(repo_name, user_token)
            stub_chained_org_teams_request(organization, user_token)
            stub_failed_team_creation_request(
              organization,
              repo_name,
              user_token
            )
            add_user_request =
              stub_add_user_to_team_request(username, team_id, user_token)

            api.add_user_to_repo(username, repo_name)

            expect(add_user_request).to have_been_requested
          end
        end

        context "when 'Services' team exists" do
          context "when Services team is not on the first page of results" do
            it "adds user to Services team" do
              stub_repo_with_org_request(repo_name, user_token)
              stub_empty_repo_teams_request(repo_name, user_token)
              stub_paginated_org_teams_request(organization, user_token)
              add_repo_request =
                stub_add_repo_to_team_request(repo_name, team_id, user_token)
              add_user_request =
                stub_add_user_to_team_request(username, team_id, user_token)

              api.add_user_to_repo(username, repo_name)

              expect(add_user_request).to have_been_requested
              expect(add_repo_request).to have_been_requested
            end
          end

          it "adds user to 'Services' team" do
            stub_repo_with_org_request(repo_name, user_token)
            stub_empty_repo_teams_request(repo_name, user_token)
            stub_org_teams_with_services_request(organization, user_token)
            add_repo_request =
              stub_add_repo_to_team_request(repo_name, team_id, user_token)
            add_user_request =
              stub_add_user_to_team_request(username, team_id, user_token)

            api.add_user_to_repo(username, repo_name)

            expect(add_user_request).to have_been_requested
            expect(add_repo_request).to have_been_requested
          end
        end

        context "when 'services' team exists" do
          it "adds user to 'services' team" do
            stub_repo_with_org_request(repo_name, user_token)
            stub_empty_repo_teams_request(repo_name, user_token)
            stub_org_teams_with_lowercase_services_request(
              organization,
              user_token
            )
            add_repo_request =
              stub_add_repo_to_team_request(repo_name, team_id, user_token)
            add_user_request =
              stub_add_user_to_team_request(username, team_id, user_token)

            api.add_user_to_repo(username, repo_name)

            expect(add_user_request).to have_been_requested
            expect(add_repo_request).to have_been_requested
          end
        end
      end
    end

    context "when repo is not part of an organization" do
      it "adds user as collaborator" do
        stub_repo_request(repo_name, user_token)
        add_user_request =
          stub_add_user_to_repo_request(username, repo_name, user_token)

        expect(api.add_user_to_repo(username, repo_name)).to be_truthy
        expect(add_user_request).to have_been_requested
      end
    end
  end

  describe "#repos" do
    it "fetches all repos from Github" do
      stub_repo_requests(user_token)

      repos = api.repos

      expect(repos.size).to eq 4
    end
  end

  describe "#create_hook" do
    context "when hook does not exist" do
      it "creates pull request web hook" do
        full_repo_name = "jimtom/repo"
        callback_endpoint = "http://example.com"
        request = stub_hook_creation_request(
          full_repo_name,
          callback_endpoint,
          user_token
        )

        api.create_hook(full_repo_name, callback_endpoint)

        expect(request).to have_been_requested
      end

      it "yields hook" do
        full_repo_name = "jimtom/repo"
        callback_endpoint = "http://example.com"
        request = stub_hook_creation_request(
          full_repo_name,
          callback_endpoint,
          user_token
        )
        yielded = false

        api.create_hook(full_repo_name, callback_endpoint) do |hook|
          yielded = true
        end

        expect(request).to have_been_requested
        expect(yielded).to be_truthy
      end
    end

    context "when hook already exists" do
      it "does not raise" do
        full_repo_name = "jimtom/repo"
        callback_endpoint = "http://example.com"
        stub_failed_hook_creation_request(full_repo_name, callback_endpoint)
        api = GithubApi.new

        expect do
          api.create_hook(full_repo_name, callback_endpoint)
        end.not_to raise_error
      end

      it "returns true" do
        full_repo_name = "jimtom/repo"
        callback_endpoint = "http://example.com"
        stub_failed_hook_creation_request(full_repo_name, callback_endpoint)
        api = GithubApi.new

        expect(api.create_hook(full_repo_name, callback_endpoint)).
          to eq true
      end
    end
  end

  describe "#remove_hook" do
    it "removes pull request web hook" do
      repo_name = "test-user/repo"
      hook_id = "123"
      stub_hook_removal_request(repo_name, hook_id)
      api = GithubApi.new

      response = api.remove_hook(repo_name, hook_id)

      expect(response).to be_truthy
    end

    it "yields given block" do
      repo_name = "test-user/repo"
      hook_id = "123"
      stub_hook_removal_request(repo_name, hook_id)
      api = GithubApi.new
      yielded = false

      api.remove_hook(repo_name, hook_id) do
        yielded = true
      end

      expect(yielded).to eq true
    end
  end

  describe "#pull_request_files" do
    it "returns changed files in a pull request" do
      api = GithubApi.new
      pull_request = double(:pull_request, full_repo_name: "thoughtbot/hound")
      pr_number = 123
      commit_sha = "abc123"
      stub_pull_request_files_request(pull_request.full_repo_name, pr_number)
      stub_contents_request(
        repo_name: pull_request.full_repo_name,
        sha: commit_sha
      )

      files = api.pull_request_files(pull_request.full_repo_name, pr_number)

      expect(files.size).to eq(1)
      expect(files.first.filename).to eq "config/unicorn.rb"
    end
  end

  describe "#add_pull_request_comment" do
    it "adds comment to GitHub pull request" do
      api = GithubApi.new("authtoken")
      repo_name = "test/repo"
      pull_request_number = 2
      comment = "test comment"
      commit_sha = "commitsha"
      file = "test.rb"
      patch_position = 123
      commit = double(:commit, repo_name: repo_name, sha: commit_sha)
      request = stub_comment_request(
        repo_name,
        pull_request_number,
        comment,
        commit_sha,
        file,
        patch_position
      )

      api.add_pull_request_comment(
        pull_request_number: pull_request_number,
        commit: commit,
        comment: "test comment",
        filename: file,
        patch_position: patch_position
      )

      expect(request).to have_been_requested
    end

    describe "#pull_request_comments" do
      it "returns comments added to pull request" do
        api = GithubApi.new
        pull_request = double(:pull_request, full_repo_name: "thoughtbot/hound")
        pull_request_id = 253
        commit_sha = "abc253"
        expected_comment = "inline if's and while's are not violations?"
        stub_pull_request_comments_request(
          pull_request.full_repo_name,
          pull_request_id
        )
        stub_contents_request(
          repo_name: pull_request.full_repo_name,
          sha: commit_sha
        )

        comments = api.pull_request_comments(
          pull_request.full_repo_name,
          pull_request_id
        )

        expect(comments.size).to eq(4)
        expect(comments.first.body).to eq expected_comment
      end
    end

    describe "#accept_pending_invitations" do
      it "finds and accepts pending org invitations" do
        api = GithubApi.new
        memberships_request = stub_memberships_request
        membership_update_request = stub_membership_update_request

        api.accept_pending_invitations

        expect(memberships_request).to have_been_requested
        expect(membership_update_request).to have_been_requested
      end
    end

    it "returns user's teams" do
      teams = ["thoughtbot"]
      client = double(user_teams: teams)
      allow(Octokit::Client).to receive(:new).and_return(client)
      api = GithubApi.new

      user_teams = api.user_teams

      expect(user_teams).to eq teams
    end
  end
end


text:
package com.novoda.downloadmanager.lib;

import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.NetworkInfo;

interface SystemFacade {
    /**
     * @see System#currentTimeMillis()
     */
    long currentTimeMillis();

    /**
     * @return Currently active network, or null if there's no active
     * connection.
     */
    NetworkInfo getActiveNetworkInfo(int uid);

    /**
     * @return Currently active network, or null if there's no active
     * connection.
     */
    NetworkInfo getActiveNetworkInfo();

    boolean isActiveNetworkMetered();

    /**
     * @see android.telephony.TelephonyManager#isNetworkRoaming
     */
    boolean isNetworkRoaming();

    /**
     * @return maximum size, in bytes, of downloads that may go over a mobile connection; or null if
     * there's no limit
     */
    Long getMaxBytesOverMobile();

    /**
     * @return recommended maximum size, in bytes, of downloads that may go over a mobile
     * connection; or null if there's no recommended limit.  The user will have the option to bypass
     * this limit.
     */
    Long getRecommendedMaxBytesOverMobile();

    /**
     * Send a broadcast intent.
     */
    void sendBroadcast(Intent intent);

    /**
     * Returns true if the specified UID owns the specified package name.
     */
    boolean userOwnsPackage(int uid, String pckg) throws NameNotFoundException;
}


text:
package com.example.dell.weather;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
 * Created by Dell on 27-04-2016.
 */
public class CheckConnectivity {
    ConnectivityManager mConnectivityManager;
    NetworkInfo wifiInfo, mobileInfo;

    public Boolean checkNow(Context con){

        try{
            mConnectivityManager = (ConnectivityManager)con.getSystemService((Context.CONNECTIVITY_SERVICE));
            wifiInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            mobileInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

            if(wifiInfo.isConnected() || mobileInfo.isConnected()){
                return true;
            }

        }
        catch(Exception e){
            System.out.println("CheckConnectivity Exception: " + e.getMessage());
        }

        return false;
    }
}


text:
package org.optaplanner.persistence.jpa.api.score.buildin.bendablebigdecimal;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

import org.optaplanner.core.api.score.buildin.bendablebigdecimal.BendableBigDecimalScore;

@Converter
public class BendableBigDecimalScoreConverter implements AttributeConverter<BendableBigDecimalScore, String> {

    @Override
    public String convertToDatabaseColumn(BendableBigDecimalScore score) {
        if (score == null) {
            return null;
        }

        return score.toString();
    }

    @Override
    public BendableBigDecimalScore convertToEntityAttribute(String scoreString) {
        if (scoreString == null) {
            return null;
        }

        return BendableBigDecimalScore.parseScore(scoreString);
    }
}


text:
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>{{ with .Title }}{{.}} on {{ end }}{{ .Site.Title }}</title>
    <link>{{ .Permalink }}</link>
    <description>Recent content {{ with .Title }}in {{.}} {{ end }}on {{ .Site.Title }}</description>
    <generator>StashOurCode by gohugo.io</generator>{{ with .Site.LanguageCode }}
    <language>{{.}}</language>{{end}}{{ with .Site.Author.email }}
    <managingEditor>{{.}}{{ with $.Site.Author.name }} ({{.}}){{end}}</managingEditor>{{end}}{{ with .Site.Author.email }}
    <webMaster>{{.}}{{ with $.Site.Author.name }} ({{.}}){{end}}</webMaster>{{end}}{{ with .Site.Copyright }}
    <copyright>{{.}}</copyright>{{end}}{{ if not .Date.IsZero }}
    <lastBuildDate>{{ .Date.Format "Mon, 02 Jan 2006 15:04:05 -0700" | safeHTML }}</lastBuildDate>{{ end }}
    <atom:link href="{{.URL}}" rel="self" type="application/rss+xml" />
    {{ range first 15 .Data.Pages }}
    <item>
      <title>{{ .Title }}</title>
      <link>{{ .Permalink }}</link>
      <pubDate>{{ .Date.Format "Mon, 02 Jan 2006 15:04:05 -0700" | safeHTML }}</pubDate>
      {{ with .Params.author }}<author>{{.}}</author>{{end}}
      <guid>{{ .Permalink }}</guid>
      <description>{{ .Content | html }}</description>
    </item>
    {{ end }}
  </channel>
</rss>


text:
import {Provider} from '@angular/core';
import {NgClass} from './ng_class';
import {NgComponentOutlet} from './ng_component_outlet';
import {NgForOf, NgForOfContext} from './ng_for_of';
import {NgIf, NgIfContext} from './ng_if';
import {NgPlural, NgPluralCase} from './ng_plural';
import {NgStyle} from './ng_style';
import {NgSwitch, NgSwitchCase, NgSwitchDefault} from './ng_switch';
import {NgTemplateOutlet} from './ng_template_outlet';

export {
  NgClass,
  NgComponentOutlet,
  NgForOf,
  NgForOfContext,
  NgIf,
  NgIfContext,
  NgPlural,
  NgPluralCase,
  NgStyle,
  NgSwitch,
  NgSwitchCase,
  NgSwitchDefault,
  NgTemplateOutlet,
};

/**
 * A collection of Angular directives that are likely to be used in each and every Angular
 * application.
 */
export const COMMON_DIRECTIVES: Provider[] = [
  NgClass,
  NgComponentOutlet,
  NgForOf,
  NgIf,
  NgTemplateOutlet,
  NgStyle,
  NgSwitch,
  NgSwitchCase,
  NgSwitchDefault,
  NgPlural,
  NgPluralCase,
];


text:
$:.unshift 'lib'

# require all our gems here

ENV['RACK_ENV'] = 'test'

require 'bundler'
Bundler.require(:default, :test)

# require our application here

require 'blix/rest'

# configure rspec

RSpec.configure do  |c|

  c.expect_with :rspec do |oc|
    oc.syntax = [:should, :expect]
  end

  c.before(:all) do
    #Blix::WebFrame::Database.configure(:host=>'localhost', :database=>'webframe_test')
    @_app = Blix::Rest::Server.new
    @_srv = Rack::MockRequest.new(@_app)
  end
  c.before(:each) do
    Blix::Rest::RequestMapper.set_path_root(nil)
  end
end

# add some test helpers
TYPE_JSON = "application/json"

class DummyResponse
  attr_accessor :body
  attr_accessor :code
  attr_accessor :code_type
  attr_accessor :content_type
  attr_accessor :message
  def initialize(code,body=nil)
    @code = code
    @body = body
    @code_type =  Net::HTTPResponse::CODE_TO_OBJ[code.to_s]
    @content_type = "application/json"
  end

  def status
    code
  end

  def reason
    message
  end
end

module RequestHelpers

  class Response

    def initialize(resp)
      @resp = resp
      @h  = MultiJson.load(@resp.body) || {}
    end

    def [](k)
      @h[k]
    end

    def data
      @h["data"]
    end

    def error
      @h["error"]
    end

    def status
      @resp.status.to_i
    end

    def header
      @resp.header || {}
    end

    def content_type
      header["Content-Type"]
    end

    def inspect
      @resp.inspect
    end

  end

  def server_get path,params={}
    resp = @_srv.get(path, params)
    return Response.new(resp)
  end

end


text:
#ifndef __EVENTRPC_RPC_CONNECTION_H__
#define __EVENTRPC_RPC_CONNECTION_H__
#include <arpa/inet.h>
namespace eventrpc {
class RpcMethodManager;
class RpcConnectionManager;
class Dispatcher;
class Event;
class RpcConnection {
 public:
  RpcConnection();

  ~RpcConnection();

  void set_fd(int fd);

  void set_client_address(struct sockaddr_in address);

  void set_rpc_method_manager(RpcMethodManager *rpc_method_manager);

  void set_rpc_connection_manager(
      RpcConnectionManager *rpc_connection_manager);

  void set_dispacher(Dispatcher *dispatcher);

  Event* event();

  void Close();

  struct Impl;
 private:
  struct Impl *impl_;
};
};
#endif  // __EVENTRPC_RPC_CONNECTION_H__


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
     Copyright (C) 2014 The Android Open Source Project

     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.
-->

<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?attr/listPreferredItemHeightSmall"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:textColor="?attr/textColorAlertDialogListItem"
    android:gravity="center_vertical"
    android:paddingLeft="?attr/dialogPreferredPadding"
    android:paddingRight="?attr/dialogPreferredPadding"
    android:checkMark="?android:attr/listChoiceIndicatorSingle"
    android:ellipsize="marquee" />
<!-- From: file:/usr/local/google/buildbot/repo_clients/https___googleplex-android.googlesource.com_a_platform_manifest.git/lmp-mr1-supportlib-release/frameworks/support/v7/appcompat/res/layout/select_dialog_singlechoice_material.xml --><!-- From: file:/home/armando/Projects/Android-Studio/Hubifier/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/22.2.0/res/layout/select_dialog_singlechoice_material.xml -->


text:
package com.graphicsfuzz.common.ast.expr;

import com.graphicsfuzz.common.ast.IAstNode;
import com.graphicsfuzz.common.ast.visitors.IAstVisitor;
import java.util.Collections;

public class LengthExpr extends Expr {

  private Expr receiver;

  public LengthExpr(Expr receiver) {
    setReceiver(receiver);
  }

  public Expr getReceiver() {
    return receiver;
  }

  public void setReceiver(Expr receiver) {
    checkNoTopLevelCommaExpression(Collections.singletonList(receiver));
    if (receiver == null) {
      throw new IllegalArgumentException("Length expression cannot have null receiver");
    }
    this.receiver = receiver;
  }

  @Override
  public void accept(IAstVisitor visitor) {
    visitor.visitLengthExpr(this);
  }

  @Override
  public LengthExpr clone() {
    return new LengthExpr(receiver.clone());
  }

  @Override
  public Expr getChild(int index) {
    if (index == 0) {
      return receiver;
    }
    throw new IndexOutOfBoundsException("Index for LengthExpr must be 0");
  }

  @Override
  public void setChild(int index, Expr expr) {
    if (index == 0) {
      setReceiver(expr);
      return;
    }
    throw new IndexOutOfBoundsException("Index for LengthExpr must be 0");
  }

  @Override
  public int getNumChildren() {
    return 1;
  }

  @Override
  public boolean hasChild(IAstNode candidateChild) {
    return receiver == candidateChild;
  }
}


text:
<ion-view view-title="Debts">
    <ion-content>
        <ion-refresher pulling-text="Pull to refresh..."
                       on-refresh="vm.refresh()">
        </ion-refresher>
        <ion-list>
            <ion-item ng-repeat="debt in vm.debts">
                {{debt.gives}}
                owes
                {{debt.recieves}}
                {{debt.amount}}

                    (settled)

                <ion-option-button class="button-balanced"
                            ng-show="!debt.settled"
                            ng-click="vm.toggleDebt(debt)">
                    Resolve
                </ion-option-button>
                <ion-option-button class="button-assertive"
                            ng-show="debt.settled"
                            ng-click="vm.toggleDebt(debt)">
                    Undo
                </ion-option-button>
            </ion-item>
            <ion-item class="list-message" ng-hide="vm.debts.length">
                Nothing to display!
            </ion-item>
        </ion-list>
    </ion-content>
</ion-view >


text:
package tool;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.program.gyf.jianji.R;

/**
 * Created by Administrator on 2017/2/28.
 */

public class WonderfulDialog extends Dialog
{

    private Context context;
    private int resId;
    private int layoutId;
    private String title=null;
    private int height;
    private int width;
    public WonderfulDialog(Context context)
    {
        super(context);
        this.context = context;

    }

    public WonderfulDialog(Context context, int themeResId)
    {
        super(context, themeResId);
        this.context = context;
        resId = themeResId;
    }

    public WonderfulDialog(Context context, int  themeResId, int  layoutId,int height,int width)
    {
        super(context, themeResId);
        this.layoutId = layoutId;
        this.context = context;
        this.height = height;
        this.width = width;

    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        View view = View.inflate(context, layoutId, null);
        TextView titleText = (TextView) view.findViewById(R.id.title);
        if(title!=null)
        {
            titleText.setText(title);
        }
        setContentView(view);
        initSize();
    }

    private void initSize()
    {
        Window window = getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.gravity = Gravity.CENTER;
        lp.width = DensityUtils.dp2px(context, width);
        lp.height = DensityUtils.dp2px(context, height);
        window.setAttributes(lp);
    }

    public void setMyTitle(String title)
    {

        this.title = title;
        View view = View.inflate(context, layoutId, null);
        TextView titleText = (TextView) view.findViewById(R.id.title);
        titleText.setText(title);

    }
}


text:
Decouple your models from forms. Reform gives you a form object with validations and nested setup of models. It is completely framework-agnostic and doesn't care about your database.

## Installation

Add this line to your Gemfile:

```ruby
gem 'reform'
```

## Defining Forms

Say you need a form for song requests on a radio station. Internally, this would imply associating `songs` table and the `artists` table. You don't wanna reflect that in your web form, do you?

```ruby
class SongRequestForm < Reform::Form
  include DSL

  property :title,  on: :song
  property :name,   on: :artist

  validates :name, :title, presence: true
end
```

The `::property` method allows defining the fields of the form. Using `:on` delegates this field to a nested object in your form.

__Note__: There is a convenience method `::properties` that allows you to pass an array of fields at one time.

## Using Forms

In your controller you'd create a form instance and pass in the models you wanna work on.

```ruby
def new
  @form = SongRequestForm.new(song: Song.new, artist: Artist.new)
end
```

You can also setup the form for editing existing items.

```ruby
def edit
  @form = SongRequestForm.new(song: Song.find(1), artist: Artist.find(2))
end
```

## Rendering Forms

Your `@form` is now ready to be rendered, either do it yourself or use something like `simple_form`.

```haml
= simple_form_for @form do |f|

  = f.input :name
  = f.input :title
```

## Validating Forms

After a form submission, you wanna validate the input.

```ruby
def create
  @form = SongRequestForm.new(song: Song.new, artist: Artist.new)

  #=> params: {song_request: {title: "Rio", name: "Duran Duran"}}

  if @form.validate(params[:song_request])
```

`Reform` uses the validations you provided in the form - and nothing else.

## Saving Forms

We provide a bullet-proof way to save your form data: by letting _you_ do it!

```ruby
  if @form.validate(params[:song_request])

    @form.save do |data, nested|
      #=> data:   <title: "Rio", name: "Duran Duran">
      #
      #   nested: {song:   {title: "Rio"},
      #            artist: {name: "Duran Duran"}}

      SongRequest.new(nested[:song][:title])
    end
```

While `data` gives you an object exposing the form property readers, `nested` already reflects the nesting you defined in your form earlier.

To push the incoming data to the models directly, call `#save` without the block.

```ruby
    @form.save  #=> populates song and artist with incoming data
                #   by calling @form.song.name= and @form.artist.title=.
```

## Rails Integration

[A sample Rails app using Reform.](https://github.com/gogogarrett/reform_example)

Reform offers ActiveRecord support to easily make this accessible in Rails based projects. You simply `include Reform::Form::ActiveRecord` in your form object and the Rails specific code will be handled for you. This happens by adding behaviour to make the form ActiveModel-compliant. Note that this module will also work with other ORMs like Datamapper.

### Simple Integration
#### Form Class

You have to include a call to `model` to specify which is the main object of the form.

```ruby
require 'reform/rails'

class UserProfileForm < Reform::Form
  include DSL
  include Reform::Form::ActiveRecord

  property :email,        on: :user
  properties [:gender, :age],   on: :profile

  model :user

  validates :email, :gender, presence: true
  validates :age, numericality: true
  validates_uniqueness_of :email
end
```

Basically, `model :user` tells Reform to use the `:user` object in the composition as the form main object while using `"user"` as the form name (needed for URL computation). If you want to change the form name let Reform know.

```ruby
  model :singer, :on => :user # form name is "singer" whereas main object is `:user` in composition.
```

#### View Form

The form becomes __very__ dumb as it knows nothing about the backend assocations or data binding to the database layer.  This simply takes input and passes it along to the controller as it should.

```erb
<%= form_for @form do |f| %>
  <%= f.email_field :email %>
  <%= f.input :gender %>
  <%= f.number_field :age %>
  <%= f.submit %>
<% end %>
```

#### Controller

In the controller you can easily create helpers to build these form objects for you.  In the create and update actions Reform allows you total control of what to do with the data being passed via the form. How you interact with the data is entirely up to you.

```ruby
class UsersController < ApplicationController

  def create
    @form = create_new_form
    if @form.validate(params[:user])
      @form.save do |data, map|
        new_user = User.new(map[:user])
        new_user.build_user_profile(map[:profile])
        new_user.save!
      end
    end
  end

  private
  def create_new_form
    UserProfileForm.new(user: User.new, profile: UserProfile.new)
  end
end
```

__Note__: this can also be used for the update action as well.

## Using Your Models In Validations

Sometimes you want to access your database in a validation. You can access the models using the `#model` accessor in the form.

```ruby
class ArtistForm < Reform::Form
  property :name

  validate "name_correct?"

  def name_correct?
    errors.add :name, "#{name} is stupid!" if model.artist.stupid_name?(name)
  end
end
```

## Security

By explicitely defining the form layout using `::property` there is no more need for protecting from unwanted input. `strong_parameter` or `attr_accessible` become obsolete. Reform will simply ignore undefined incoming parameters.


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>ru.job4j.chapter_008.jdbc.optimisation</groupId>
    <artifactId>optimisation</artifactId>
    <version>2.0</version>
    <packaging>pom</packaging>
    <parent>
        <groupId>ru.job4j.chapter_008.jdbc</groupId>
        <artifactId>jdbc</artifactId>
        <version>2.0</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.xerial</groupId>
            <artifactId>sqlite-jdbc</artifactId>
            <version>3.21.0.1</version>
        </dependency>
    </dependencies>
</project>


text:
/*
 * Partners Messages
 *
 * This contains all the text for the Partners component.
 */
import { defineMessages } from 'react-intl';

export default defineMessages({
  header: {
    id: 'app.containers.Partners.header',
    defaultMessage: 'Partners',
  },
  text: {
    id: 'app.containers.Partners.text',
    defaultMessage: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum',
  },
});


text:
package com.njit.ece.senior_project.medical_sensor.data.DataProvider;

/**
 * Listens for raw data, which is provided immediately as it is recieved (no buffer)
 */
public interface RawDataListener {

    void onRawDataChanged(DataEvent event);

}


text:
require 'test_helper'
require 'gds_api/test_helpers/imminence'

class SmartdownScenariosTest < ActiveSupport::TestCase
  include GdsApi::TestHelpers::Imminence

  setup do
    imminence_has_areas_for_postcode("WC2B%206SE", [])
    imminence_has_areas_for_postcode("B1%201PW", [{ slug: "birmingham-city-council" }])
  end

  smartdown_flow_to_test = ENV['SMARTDOWN_FLOW_TO_TEST']
  run_all_tests = smartdown_flow_to_test.nil?

  flow_registry_options = {
    preload_flows: true,
    show_drafts: true,
    show_transitions: true,
  }
  SmartdownAdapter::Registry.reset_instance
  smartdown_flows = SmartdownAdapter::Registry.instance(flow_registry_options).flows
  smartdown_flows.each do |smartdown_flow|
    next unless run_all_tests || smartdown_flow.name == smartdown_flow_to_test

    smartdown_flow.scenario_sets.each do |scenario_set|
      scenario_set.scenarios.each_with_index do |scenario, scenario_index|
        description = scenario.description.empty? ? scenario_index + 1 : scenario.description
        test "scenario #{description} in set #{scenario_set.name} for flow #{smartdown_flow.name}" do
          scenario.question_groups.each_with_index do |question_group, question_index|
            answers = scenario.question_groups.take(question_index).flatten.map(&:answer)
            question_names = question_group.map(&:name)
            questions_are_asked(smartdown_flow, answers, question_names)
          end
          answers = scenario.question_groups.flatten.map(&:answer)
          outcome_is_reached(smartdown_flow, answers, scenario.outcome)
          markers_are_included(smartdown_flow, answers, scenario.markers)
          exact_markers_are_included(smartdown_flow, answers, scenario.exact_markers) if scenario.exact_markers.any?
        end
      end
    end
  end
  SmartdownAdapter::Registry.reset_instance

  def questions_are_asked(flow, answers, question_names)
    assert_nothing_raised("Exception was thrown when running flow #{flow.name} with answers #{answers}") do
      state  = flow.state(true, answers)
      assert (state.current_node.is_a? Smartdown::Api::QuestionPage),
             "Expected a question when running flow #{flow.name} with answers #{answers}"
      current_question_names = state.current_node.questions.map(&:name).map(&:to_s)
      question_names.each do |question_name|
        assert current_question_names.include?(question_name),
               "In flow #{flow.name} with answers #{answers}, questions #{current_question_names} were reached but not #{question_name}"
      end
    end
  end

  def outcome_is_reached(flow, answers, outcome)
    assert_nothing_raised("Exception was thrown when running flow #{flow.name} with answers #{answers}") do
      state  = flow.state(true, answers)
      assert (state.current_node.is_a? Smartdown::Api::Outcome),
             "Expected an outcome when running flow #{flow.name} with answers #{answers}"
      assert_equal outcome,
                   state.current_node.name,
                   "In flow #{flow.name} with answers #{answers}, outcome #{state.current_node.name} was reached and not #{outcome}"
    end
  end

  def markers_are_included(flow, answers, expected_markers)
    state  = flow.state(true, answers)
    actual_markers = state.current_node.markers.map(&:marker_name)
    assert_empty (expected_markers - actual_markers),
      "In flow #{flow.name} with answers #{answers} markers #{expected_markers} were expected but #{actual_markers} was received"
  end

  def exact_markers_are_included(flow, answers, expected_markers)
    state  = flow.state(true, answers)
    actual_markers = state.current_node.markers.map(&:marker_name)
    assert_empty ((expected_markers - actual_markers) + (actual_markers - expected_markers)),
      "In flow #{flow.name} with answers #{answers} markers #{expected_markers} were expected but #{actual_markers} was received"
  end
end


text:
===================================
VNF version upgrading from v1 to v2
===================================

Overview
--------
Tacker supports multi-version APIs: v1 API based on `NFV-SOL003 v2.6.1`_
and v2 API based on `NFV-SOL003 v3.3.1`_.
Because of the lack of compatibility between those versions,
version upgrading usually requires re-instantiation of the VNFs.

However, by using the :command:`tacker-db-manage` command,
the information on the v1 API table can be migrated to the v2 API table,
which allows VNF version upgrades without re-instantiation.

This document describes how to upgrade VNF using
the :command:`tacker-db-manage` command.

Target tables of migration
--------------------------

Target tables to be migrated:

* VnfInstanceV2
* VnfLcmOpOccV2

Source tables to be migrated:

* vnf
* vnf_attribute
* vnf_instances
* vnf_instantiated_info
* vnf_lcm_op_occs

Pre-requisites
--------------

There is a process to retrieve information about the VIM
associated with the VNF in the migration.
The authentication information of the keystone needed for this process
must be provided from the environment variables.
The required environment variables are shown below.

* OS_AUTH_URL
* OS_PASSWORD
* OS_PROJECT_DOMAIN_ID
* OS_PROJECT_DOMAIN_NAME
* OS_PROJECT_NAME
* OS_USER_DOMAIN_ID
* OS_USER_DOMAIN_NAME
* OS_USERNAME

The method of migration
-----------------------

The following command can be used to upgrade a specified VNF from v1 to v2,
without leaving any records related to the VNF on the existing v1 table.

.. code-block:: console

        $ tacker-db-manage --config-file /path/to/tacker.conf \
        --config-file /path/to/plugin/config.ini migrate-to-v2 --vnf-id <uuid_of_target_vnf>

The following command can be used to upgrade a specified VNF from v1 to v2,
leaving records related to the VNF on the existing v1 table.

.. code-block:: console

        $ tacker-db-manage --config-file /path/to/tacker.conf \
        --config-file /path/to/plugin/config.ini migrate-to-v2 --vnf-id <uuid_of_target_vnf> --keep-orig

The following command can be used to upgrade all VNFs from v1 to v2,
without leaving any records related to the VNF on the existing v1 table.

.. code-block:: console

        $ tacker-db-manage --config-file /path/to/tacker.conf \
        --config-file /path/to/plugin/config.ini migrate-to-v2 --all

The following command can be used to upgrade all VNFs from v1 to v2,
leaving records related to the VNF on the existing v1 table.

.. code-block:: console

        $ tacker-db-manage --config-file /path/to/tacker.conf \
        --config-file /path/to/plugin/config.ini migrate-to-v2 --all --keep-orig

To complete the migration after using the ``--keep-orig`` option,
the following command can be used.
This command deletes the records for a specified VNF
left on the existing v1 table.

.. code-block:: console

        $ tacker-db-manage --config-file /path/to/tacker.conf \
        --config-file /path/to/plugin/config.ini migrate-to-v2 --vnf-id <uuid_of_target_vnf> \
        --mark-delete --api-ver v1

.. note::

       This command just updates the value of the "deleted" field to 1.
       You can delete records completely by executing the
       :command:`tacker-db-manage` command with subcommand of purge_deleted.

To rollback the migration after using the ``--keep-orig`` option,
the following command can be used.
This command deletes the records for a specified VNF on the v2 table.

.. code-block:: console

        $ tacker-db-manage --config-file /path/to/tacker.conf \
        --config-file /path/to/plugin/config.ini migrate-to-v2 --vnf-id <uuid_of_target_vnf> \
        --mark-delete --api-ver v2

.. note::

       There are no "deleted" flag in v2 tables.
       Therefore this command deletes records in v2 tables completely.

Examples of migration
---------------------

Below shows the flow of upgrading a specified VNF as an example.

Confirm the existence of instantiated VNFs on v1 API:

.. code-block:: console

        $ openstack vnflcm list
        +--------------------------------------+-----------------------+---------------------+--------------+----------------------+------------------+--------------------------------------+
        | ID                                   | VNF Instance Name     | Instantiation State | VNF Provider | VNF Software Version | VNF Product Name | VNFD ID                              |
        +--------------------------------------+-----------------------+---------------------+--------------+----------------------+------------------+--------------------------------------+
        | ab358004-739b-4aa9-8d27-734208f7c625 | test_vnf              | INSTANTIATED        | Sample       | 1.0                  | Sample           | 116aaf63-0b7c-4b1d-a2d4-af73df86787d |
        +--------------------------------------+-----------------------+---------------------+--------------+----------------------+------------------+--------------------------------------+

Read the environment variables:

.. code-block:: console

        $ source sample.rc

Execute the migration command:

.. code-block:: console

        $ tacker-db-manage --config-file /etc/tacker/tacker.conf --config-file /etc/tacker/api-paste.ini migrate-to-v2 --vnf-id ab358004-739b-4aa9-8d27-734208f7c625

.. note::

        Verify that the prompt is returned.

Confirm that there is no VNF on v1 API:

.. code-block:: console

        $ openstack vnflcm list

.. note::

        Verify that no VNF is displayed.

Confirm the existence of VNFs on v2 API:

.. code-block:: console

        $ openstack vnflcm list --os-tacker-api-version 2
        +--------------------------------------+-----------------------+---------------------+--------------+----------------------+------------------+--------------------------------------+
        | ID                                   | VNF Instance Name     | Instantiation State | VNF Provider | VNF Software Version | VNF Product Name | VNFD ID                              |
        +--------------------------------------+-----------------------+---------------------+--------------+----------------------+------------------+--------------------------------------+
        | ab358004-739b-4aa9-8d27-734208f7c625 | test_vnf              | INSTANTIATED        | Sample       | 1.0                  | Sample           | 116aaf63-0b7c-4b1d-a2d4-af73df86787d |
        +--------------------------------------+-----------------------+---------------------+--------------+----------------------+------------------+--------------------------------------+

.. _NFV-SOL003 v2.6.1: https://www.etsi.org/deliver/etsi_gs/NFV-SOL/001_099/003/02.06.01_60/gs_nfv-sol003v020601p.pdf
.. _NFV-SOL003 v3.3.1: https://www.etsi.org/deliver/etsi_gs/NFV-SOL/001_099/003/03.03.01_60/gs_nfv-sol003v030301p.pdf


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package mymiddleware;

/**A userAgent is a type of metaagent that represents a system.
 * Attach them to portals to sent messages between them.
 *
 * @author Adam
 */
public class UserAgent extends MetaAgent implements Runnable{

    /**The portal that the agent is attached to.*/
    private Portal portal;

    /**UserAgent(nameIn) - A constructor for a useragent.
     *
     * @param nameIn - The name to give to the useragent
     */
    public UserAgent(String nameIn) {
        setName(nameIn);
        this.start();
    }

    /**sendMessage(destination,message) - Creates a usermessage to sent to
     * another agent.
     *
     * @param destination - The messages destination
     * @param message - The message.
     */
    public synchronized void sendMessage(String destination, String message)
    {
        portal.offer(new UserMessage(destination,getName(),message));
        portal.start();
        System.out.println(getName() + " has added a message to the queue of " + portal.getName() + ".");
        System.out.println("");
    }

    /**isAttached - whether the useragent is attached to a portal.
     *
     * @return - Whether the useragent is attached to a portal.
     */
    public boolean isAttached()
    {
        return portal != null;
    }

    /**attach(portalIn) - For attaching a useragent to a portal so it can send
     * messages. Note a useragent can only be attached to one portal.
     *
     * @param portalIn - The portal to attach it to.
     * @return - Whether it was succesful.
     */
    public boolean attach(Portal portalIn)
    {
        if(portalIn != null)
        {
            portal = portalIn;
            portalIn.attachUserAgent(this);
            return true;
        }
        return false;
    }

    /**detach() - Detach the useragent from a portal to move it to another one,
     * or to remove it from the system.
     *
     * @return Whether it was able to be detached.
     */
    public boolean detach()
    {
        if(portal != null)
        {
            portal.removeAgent(this);
            portal = null;
            return true;
        }
        return false;
    }

    /**getPortal() - Gets the portal that the agent is attached to.
     *
     * @return - The attached portal object.
     */
    public Portal getPortal()
    {
        return portal;
    }
}


text:
<project
  xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <groupId>org.codehaus.mojo.appassembler-maven-plugin.it</groupId>
  <artifactId>asterikClassPathWrongConfiguration-test</artifactId>

  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>appassembler-maven-plugin asterikClassPathTest</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <!--  This dependency is only added to get the version in the verify.groovy scropt
  of the current build artifacts. -->
  <dependencies>
    <dependency>
      <groupId>org.codehaus.mojo.appassembler</groupId>
      <artifactId>appassembler-model</artifactId>
      <version>@project.version@</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>@project.groupId@</groupId>
        <artifactId>@project.artifactId@</artifactId>
        <version>@project.version@</version>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>assemble</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <includeConfigurationDirectoryInClasspath>true</includeConfigurationDirectoryInClasspath>
          <!--  This configuration must fail, cause the repositoryLayout has not been set to flat. -->
          <useWildcardClassPath>true</useWildcardClassPath>
          <assembleDirectory>${project.build.directory}/appassembler</assembleDirectory>
          <configurationDirectory>config</configurationDirectory>
          <extraJvmArguments>-Xms16m</extraJvmArguments>
          <platforms>
            <platform>windows</platform>
            <platform>unix</platform>
          </platforms>
          <programs>
            <program>
              <mainClass>org.codehaus.mojo.appassembler.example.helloworld.HelloWorld</mainClass>
              <name>basic-test</name>
            </program>
          </programs>
        </configuration>
      </plugin>
    </plugins>

  </build>

</project>


text:
import * as DeprecatedAnalyticsSchema from "@artsy/cohesion/dist/DeprecatedSchema"
import { useTracking } from "react-tracking"
import { useContext } from "react"
import * as React from "react"
import { createFragmentContainer, graphql } from "react-relay"
import { SystemContext } from "System"
import { NavBarNotificationsQuery } from "__generated__/NavBarNotificationsQuery.graphql"
import {
  Box,
  Flex,
  Image,
  Separator,
  Skeleton,
  SkeletonBox,
  SkeletonText,
  Text,
} from "@artsy/palette"
import { SystemQueryRenderer } from "System/Relay/SystemQueryRenderer"
import { NavBarMenuItemLink } from "./NavBarMenuItem"
import { extractNodes } from "Utils/extractNodes"
import { NavBarNotifications_me$data } from "__generated__/NavBarNotifications_me.graphql"

interface NavBarNotificationsItemContentProps {
  image: JSX.Element
  summary: JSX.Element
  artists: JSX.Element
}

const NavBarNotificationsItemContent: React.FC<NavBarNotificationsItemContentProps> = ({
  image,
  summary,
  artists,
}) => {
  return (
    <Flex alignItems="center">
      <Box width={40} height={40} bg="black5" mr={1}>
        {image}
      </Box>

      <Box>
        {summary}
        {artists}
      </Box>
    </Flex>
  )
}

const NavBarNotificationsItemPlaceholder = () => {
  return (
    <Skeleton px={2} py={1}>
      <NavBarNotificationsItemContent
        image={<SkeletonBox width="100%" height="100%" />}
        summary={<SkeletonText variant="xs">N works added</SkeletonText>}
        artists={<SkeletonText variant="xs">Pending artists</SkeletonText>}
      />
    </Skeleton>
  )
}

interface NavBarNotificationsProps {
  me: NavBarNotifications_me$data
}

export const NavBarNotifications: React.FC<NavBarNotificationsProps> = ({
  me,
}) => {
  const notifications = extractNodes(me?.followsAndSaves?.notifications)

  const { trackEvent } = useTracking()

  const handleClick = (href: string, subject: string) => {
    trackEvent({
      action_type: DeprecatedAnalyticsSchema.ActionType.Click,
      context_module:
        DeprecatedAnalyticsSchema.ContextModule.HeaderActivityDropdown,
      destination_path: href,
      subject,
    })
  }

  return (
    <>
      {notifications.map(({ artists, href, image, summary }, index) => {
        return (
          <NavBarMenuItemLink
            to={`${href}/works-for-sale`}
            key={index}
            aria-label={`${summary} by ${artists}`}
            onClick={() => {
              handleClick(href!, DeprecatedAnalyticsSchema.Subject.Notification)
            }}
          >
            <NavBarNotificationsItemContent
              aria-hidden="true"
              image={
                <Image
                  src={image?.thumb?.url}
                  width={40}
                  height={40}
                  alt=""
                  lazyLoad
                />
              }
              summary={<Text variant="xs">{summary}</Text>}
              artists={<Text variant="xs">{artists}</Text>}
            />
          </NavBarMenuItemLink>
        )
      })}

      {notifications.length === 0 && (
        <Text variant="sm" px={2} py={1} color="black60">
          No new works
        </Text>
      )}

      <Separator my={1} />

      <NavBarMenuItemLink
        aria-label="View all notifications"
        to="/works-for-you"
        onClick={() => {
          handleClick(
            "/works-for-you",
            DeprecatedAnalyticsSchema.Subject.ViewAll
          )
        }}
      >
        <Text variant="sm" m="auto">
          View all
        </Text>
      </NavBarMenuItemLink>
    </>
  )
}

const NavBarNotificationsFragmentContainer = createFragmentContainer(
  NavBarNotifications,
  {
    me: graphql`
      fragment NavBarNotifications_me on Me {
        unreadNotificationsCount
        followsAndSaves {
          notifications: bundledArtworksByArtistConnection(
            sort: PUBLISHED_AT_DESC
            first: 10
          ) @connection(key: "NavBarNotifications_notifications") {
            edges {
              node {
                href
                summary
                artists
                published_at: publishedAt(format: "MMM DD")
                image {
                  thumb: cropped(height: 80, width: 80) {
                    url
                  }
                }
              }
            }
          }
        }
      }
    `,
  }
)

const NavBarNotificationsPlaceholder: React.FC = () => {
  return (
    <>
      <NavBarNotificationsItemPlaceholder />
      <NavBarNotificationsItemPlaceholder />

      <Separator my={1} />

      <SkeletonText variant="sm" textAlign="center" px={2} py={1}>
        View all
      </SkeletonText>
    </>
  )
}

/**
 * The <Menu /> component renders a QueryRenderer inside of it, which fetches
 * individual MenuItems for display. During fetch there is a custom placeholder
 */
export const NavBarNotificationsQueryRenderer: React.FC = () => {
  const { relayEnvironment } = useContext(SystemContext)

  return (
    <Flex width={230} py={1} flexDirection="column" aria-live="assertive">
      <Text variant="sm" px={2} py={1}>
        Activity
      </Text>

      <Separator my={1} />

      <SystemQueryRenderer<NavBarNotificationsQuery>
        environment={relayEnvironment}
        query={graphql`
          query NavBarNotificationsQuery {
            me {
              ...NavBarNotifications_me
            }
          }
        `}
        render={({ error, props }) => {
          if (error) {
            return (
              <Flex justifyContent="center">
                <Text variant="xs" color="red100">
                  {error.message}
                </Text>
              </Flex>
            )
          }

          if (!props || !props.me) {
            return <NavBarNotificationsPlaceholder />
          }

          return <NavBarNotificationsFragmentContainer me={props.me} />
        }}
      />
    </Flex>
  )
}


text:
/opt/docker-solr/scripts/precreate-core development
cp /docker-entrypoint-initdb.d/conf/* /var/solr/data/development/conf

/opt/docker-solr/scripts/precreate-core test
cp /docker-entrypoint-initdb.d/conf/* /var/solr/data/test/conf


text:
<title>jsChemistry</title>

<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">

<canvas id="myCanvas"></canvas>

<button type="button" onclick="pause = !pause;">Pause/Play</button>
<button type="button" onclick="speed = fastSpeed;">Fast</button>
<button type="button" onclick="speed = mediumSpeed;">Medium</button>
<button type="button" onclick="speed = slowSpeed;">Slow</button>

<button type="button" onclick="show_unbonded_atoms = !show_unbonded_atoms;">Show/hide the bath</button>
<button type="button" onclick="withTemperatureGradient = !withTemperatureGradient;">Temperature gradient on/off</button>
<button type="button" onclick="updateReactionList();">Update Reaction Graph</button>

Estimated energy usage:

What's going on?

There are two template-replicating polymers present from the start. Hide the bath to see them better. The two are: eacbdf (purple-red-green-blue-yellow-cyan) and ebdbdf (purple-green-yellow-green-yellow-cyan).
They replicate by pulling in matching atoms from the surrounding bath.

The colors (abcdef) of the atoms never change. The numbers/letters you see (01233456789ABCDEFHI) are their states. We use the states to direct the replication process. Replication works like this:

eabcdf --> eabcdffcdbae --> eabcdf + fcdbae

Reactions happen between pairs of atoms, and can bond or unbond them and change their states. All reactions are reversible with equal probability. Bonding reactions are energetically downhill, unbonding reactions are uphill.

The reactions in our system are listed below. They are designed to let any sequence e{abcd}*f replicate. Credit to Dave Mann for inventing this form of template-replication (see the Organic Builder paper).

<tt>
    x1yD    -> xDy1    // message-passing
    x2yD    -> xDy2
    x3yD    -> xDy3
    x4yD    -> xDy4
    x5yD    -> xDy5
    x6yD    -> xDy6
    x7 + a0 -> xDaE    // bond the appropriate type
    x8 + b0 -> xDbE
    x9 + c0 -> xDcE
    xA + d0 -> xDdE
    xB + e0 -> xDeF    // (if bonded an 'e' then we start reset1 (F) )
    xC + f0 -> xDfE
    x1yE    -> xDy7    // activate for the next one to be bonded
    x2yE    -> xDy8
    x3yE    -> xDy9
    x4yE    -> xDyA
    x5yE    -> xDyB
    aFxD    -> a1xF    // reset1 passes over a base 'a', setting its state to 1
    bFxD    -> b2xF
    cFxD    -> c3xF
    dFxD    -> d4xF
    eFxD    -> e5xF
    fFfD    -> fC + fG  // unbonds when reset1 passes over the central f-f
    fGxD    -> fGxH    // reset2 (G) starts moving
    aHxD    -> aGxH    // reset2 passes over a base
    bHxD    -> bGxH
    cHxD    -> cGxH
    dHxD    -> dGxH
    eHxG    -> e5xI    // reset2 ends, starts reset3 (I)
    aIxG    -> a1xI    // reset3 passes over a base
    bIxG    -> b2xI
    cIxG    -> c3xI
    dIxG    -> d4xI
    fIa1    -> fCa1   // reset3 gets to the end
    fIb2    -> fCb2
    fIc3    -> fCc3
    fId4    -> fCd4
    fIe5    -> fCe5
</tt>

This is a bit complicated, which is annoying. Here are some notes:

states 1-6: passive message saying we would like to bond a-f respectively
states 7-C: active end of the growing molecule, ready to bond the next atom (of type a-f respectively)
state D: empty space in message-passing
state E: active end ready to be told what the next atom to be bonded is
states FGHI: resets 1,2,3,4

The simplest possible replicator is e5fC.