text:
define([
    "jwebkit",
    "jwebkit.ui",
    "jwebdesk",
], function(jwk, ui, jwebdesk) {

    // jwk.ui.Panel.Layout --------------------------------------------------------------------------
    jwebdesk.WindowManager = function (settings) {
        if (!settings) return;
        var def = {
            ui_type: "window-manager",
            namespace: "jwebdesk",
            layout: ["content"]
        };
        settings = jwk.extend(def, settings);
        jwk.ui.Component.call(this, settings);
        this.set("start", "row");
        this.set("layout", settings.layout, {no_parse:true});
        this.set("window", {}, { getter: "child" });
        this.on("render_start", function (n,e){
            e.component.restructure();
        });
    }

    jwebdesk.WindowManager.prototype = new jwk.ui.Component();
    jwebdesk.WindowManager.prototype.constructor = jwebdesk.WindowManager;

    jwebdesk.WindowManager.prototype.create_service = function () {
        var service = jwk.global.proxy();
        var win_man = this;
        win_man.service = service;

        service.register_function({
            create: win_man.create,
            min_mode: win_man.min_mode,
            list: win_man.list,
            select: win_man.select_window,
            minimize: win_man.minimize_window,
            maximize: win_man.maximize_window,
            restore: win_man.restore_window,
            close: win_man.close_window
        }, this);

        var handle_F5 = function () {
            console.log("handle_F5", arguments);
            var selected = win_man.get_selected();
            console.log(selected);
            if (selected) {
                selected.reload();
            } else {
                window.location.reload();
            }
        };

        // shortcut.add("F5", handle_F5);

        jwebdesk.register_service("window-manager", service);

    }

    function on_select_handler(n,e) {
        this.set("selected", this.window(e.window));
    }

    jwebdesk.WindowManager.prototype.get_selected = function () {
        return this.get("selected");
    }

    jwebdesk.WindowManager.prototype.select_hiest_window = function (win_id, params) {
        var z_best = -1;
        var win_best = null;
        var list = this.window().keys();
        for (var i=0; i<list.length; i++) {
            var id = list[i];
            var win =this.window(id);
            if (win.component && win.component.get("state") != "minimized" && win.component.target && win.component.target.css("z-index")) {
                if (parseInt(win.component.target.css("z-index")) > z_best) {
                    z_best = parseInt(win.component.target.css("z-index"));
                    win_best = win;
                }
            }
        }

        if (win_best) win_best.component.select();
    }

    jwebdesk.WindowManager.prototype.select_window = function (win_id, params) {
        this.window(win_id).component.select();
    }

    jwebdesk.WindowManager.prototype.minimize_window = function (win_id, params) {
        var manager = this;
        this.window(win_id).component.minimize().done(function () {
            manager.select_hiest_window();
        });
    }

    jwebdesk.WindowManager.prototype.maximize_window = function (win_id, params) {
        this.window(win_id).component.maximize();
    }

    jwebdesk.WindowManager.prototype.restore_window = function (win_id, params) {
        var win = this.window(win_id).component;
        var state = win.get("state");
        if (state == "minimized") {
            win.restore();
        } else if (state == "maximized") {
            win.normal();
        } else {
            console.error("ERROR: window.restore from state: ", win.state(), "not implemented", win, win_id);
        }
    }

    jwebdesk.WindowManager.prototype.close_window = function (win_id, params) {
        this.window(win_id).component.close();
        this.select_hiest_window();
    }

    jwebdesk.WindowManager.prototype.min_mode = function (win_id, params) {
        this.window(win_id).component.set("min_mode", params);
    }

    jwebdesk.WindowManager.prototype.list = function (win_id, params) {
        var list = [];
        this.window().each(function (w) {
            var win = w.valueOf();
            list.push({ window: win.id, title: win.title, icon: win.icon, category: win.setup.category });
        });
        return list;
    }

    jwebdesk.WindowManager.prototype.create = function (setup, restaure_settings) {
        if (setup instanceof jwebdesk.Setup) {
            var win = new jwebdesk.WindowManager.Window(setup, restaure_settings);
            // console.log("create ----", setup.valueOf(), win.id, win.valueOf());
            this.window(win.id, win);
            var event = { setup: setup.id, window: win.id, title: win.title, icon: win.icon };

            this.service.trigger("window:open", event);

            win.on("close",     function (n,e) {
                this.unset("selected");
                this.service.trigger("window:close",    event);
                this.window().unset(win.id);
                this.select_hiest_window();
            }, this);
            win.on("select", on_select_handler, this);
            win.component.on("minimize",  function (n,e) {
                this.service.trigger("window:minimize", event);
                this.select_hiest_window();
            }, this);
            win.component.on("maximize",  function (n,e) { this.service.trigger("window:maximize", event); }, this);
            win.component.on("restore",   function (n,e) { this.service.trigger("window:restore",  event); }, this);
            win.component.on("select",    function (n,e) { this.service.trigger("window:select",   event); }, this);

            if (!restaure_settings) {
                // Esto significa que la aplicación
                if (win.layer == "window") {
                    if (win.component.controllers.selectable) {
                        win.component.controllers.selectable.select();
                    }
                }
            }

            return win;
        } else {
            console.error(setup, "¿?");
        }
    }

    jwebdesk.WindowManager.prototype.structure_tree = function () {
        var root =  {
            "data": this,
            "name": "structure",
            "ui_type": "panel.placeholder",
            "children": {
                "desk": {
                    "start": this.get("start"),
                    "layout": this.get("layout"),
                    "class": "full",
                    "ui_type": "panel.layout",
                    "children": {
                        "west":       { "class":"expand window-manager-west",       "ui_type": "panel" },
                        "top":        { "class":"expand window-manager-top",        "ui_type": "panel" },
                        "left":       { "class":"expand window-manager-left",       "ui_type": "panel" },
                        "content":    {
                            "ui_type": "panel",
                            "disable_selection": true,
                            "class":"full window-manager-content",
                            "style": "position: absolute; left:0;right:0;"
                        },
                        "right":      { "class":"expand window-manager-right",      "ui_type": "panel" },
                        "bottom":     { "class":"expand window-manager-bottom",     "ui_type": "panel" },
                        "east":       { "class":"expand window-manager-east",       "ui_type": "panel" },
                    }
                }
            }
        }

        var containers = root.children.desk.children;
        var string = JSON.stringify(this.get("layout"));
        for (var name in containers) {
            if (string.indexOf(name) == -1) {
                delete containers[name];
            }
        }

        return root;
    }

    jwebdesk.WindowManager.prototype.hide = function (name) {
        console.error("ERROR: not jwebdesk.WindowManager.hide(name) not implemented yet");
    }

    jwebdesk.WindowManager.prototype.show = function (name) {
        var layout = this.get("layout");
        var level_1, level_2, level_3;
        level_1 = layout;
        for (var i in level_1) {
            if (Array.isArray(level_1[i])) level_2 = level_1[i];
        }
        if (!level_2) {
            level_3 = layout;
            level_2 = [level_3];
            level_1 = [level_2];
        } else {
            for (var i in level_2) {
                if (Array.isArray(level_2[i])) level_3 = level_2[i];
            }
            if (!level_3) {
                level_3 = level_2;
                level_2 = level_1;
                level_1 = [level_2];
            }
        }

        switch (name) {
            case "west":
                if (level_1[0] != name) level_1.splice(0,0,name); break;
            case "top":
                if (level_2[0] != name) level_2.splice(0,0,name); break;
            case "left":
                if (level_3[0] != name) level_3.splice(0,0,name); break;
            case "right":
                if (level_3[level_3-1] != name) level_3.splice(level_3-1,0,name); break;
            case "bottom":
                if (level_2[level_2-1] != name) level_2.splice(level_2-1,0,name); break;
            case "east":
                if (level_1[level_1-1] != name) level_1.splice(level_1-1,0,name); break;
        }

        var start;
        if (level_1.length > 1) {
            start = "row";
            layout = level_1;

        } else {
            if (level_2.length > 1) {
                start = "col";
                layout = level_2;
            } else {
                start = "row";
                layout = level_3;
            }
        }
        // if (this.get("structure")) this.get("structure").destroy();
        // this.unset("structure");
        this.set("start", start);
        this.set("layout", layout, {no_parse: true});

        this.paint();
    }

    jwebdesk.WindowManager.prototype.parent_for = function (name, index) {
        switch (name) {
            case "desk":
            case "structure":
                return {parent:this};
        }
        return {parent:this.get("structure").search("content")};
    }

    jwk.ui.component({
        ui_type: "window-manager",
        namespace: "jwebdesk",
        constructor: jwebdesk.WindowManager
    });

// -----------------------------------------------------------------------------------------------------------------------

    jwebdesk.WindowManager.Window = function (setup, restore_settings) {
        jwk.Node.call(this);
        this.set("setup", setup);
        var win = this;
        var windex;
        if (restore_settings && restore_settings.windex) {
            windex = restore_settings.windex;
        } else {
            windex = setup.windex();
        }
        win.windex = windex;

        // TODO: sele limina el theme y queda solo config.window
        // Puede que no estén todos los datos. Si algo falta setear valores por defecto
        // Si la posición y tamaño de la ventana no están presentes, generar un par adecuados sgun el estado actual de las ventanas.
        var window_config = setup.config["window_" + windex]
        if (!window_config) {
            window_config = setup.get("config.theme.window", {deep: true});
            if (window_config) {
                alert("ERROR: Hay que cambiar el path 'config.theme.window' del setup: "+ setup.get("id"));
                console.error("ERROR: Hay que cambiar el path 'config.theme.window' del setup: ", [setup.get("id"),setup]);
            }
        }
        if (!window_config) window_config = new jwk.Node();

        var settings = setup.get("settings");

        if (settings) settings = settings.valueOf();
        settings = jwk.extend({
            "layers": ["window"],
            "resizable": true,
            "draggable": true,
            "selectable": true
        }, settings);

        var layers = settings.layers;
        var layer = window_config.get("layer");
        if (!layers) {
            // console.error("ERROR: settings.layers not found:",[setup.get("id"), setup]);
            layers = ["window"];
        }
        console.assert(Array.isArray(layers) && layers.length > 0, "ERROR: layers must be an Array with at least one string indicating the possible layers");
        if (!layer) {
            layer = layers[0];
        }
        if (layers.indexOf(layer) == -1) {
            console.error("ERROR: layer (" +layer+ ") must be one of possible layers: ", layers);
            layer = layers[0];
        }

        this.layer = layer;
        window_config = jwk.extend(window_config.valueOf(), {layer: layer}, settings);

        switch (layer) {
            case "window":
                window_config.size = window_config.size || {
                    "width": "70%",
                    "height": "70%"
                }
                window_config.position = window_config.position || {
                    "my": "center center",
                    "at": "center center",
                    "of": "container"
                }

                // window-selection-group fix
                if (window_config.selectable == true) {
                    window_config.selectable = { group: "jwebdesk-window" }
                }
                var name = "window_" + jwk.nextId();
                var settings = jwk.extend({
                    path: name,
                    name: name,
                    parent: this.manager,
                    title: setup.get("title"),
                    icon: setup.getIcon(16)
                }, window_config);
                var spec = jwk.ui.component("jwk-ui", "window");
                this.component =  new spec.constructor(settings);
                this.component._win = win;
                this.component.init();
                this.component.paint();
                if (restore_settings && restore_settings.zindex) this.zindex(restore_settings.zindex);

                // TODO: Acá hay que ver como setear en el nuevo dato en las config de la aplicación
                this.component.on({
                    "resize": function (n,e) { win.trigger(n,jwk.extend({}, e, { window: win, component: e.window})); },
                    "move":   function (n,e) { win.trigger(n,jwk.extend({}, e, { window: win, component: e.window})); },
                    "state":  function (n,e) {
                        // console.log("win.state", arguments);
                        win.trigger(n,jwk.extend({}, e, { window: win, component: e.window}));
                    }
                }, this);
                break;
            case "west":
            case "top":
            case "left":
            case "right":
            case "bottom":
            case "east":
                this.manager.show(layer);
                this.component = this.manager.search(layer);
                break;
        }

        this.set("id", "win-"+jwk.nextId());
        this.set("title", setup.get("title") || "No title");
        this.set("icon", setup.getIcon(16));

        this.component.on("destroy", function (n,e){
            console.assert(this.component == e.component, this, this.component, e.component);
            // console.error("----------------",n,e);
            this.trigger_fast("close", {window: this.id});
        }, this);

        if (this.component.controllers.selectable) {
            this.component.controllers.selectable.on("select", function (n,e){
                console.assert(this.component == e.component, this, this.component, e.component);
                this.trigger_fast("select", {window: this.id});
            }, this);
        }

    }

    jwebdesk.WindowManager.Window.prototype = new jwk.Node();
    jwebdesk.WindowManager.Window.prototype.constructor = jwebdesk.WindowManager.Window;

    function add_packages(arr, packs){
        // console.log("add_packages", arguments);
        console.assert(Array.isArray(arr), arr);
        switch (typeof packs) {
            case "string":
                if (packs != "default-skin") {
                    arr.push(packs);
                }
                break;
            case "object":
                var list = packs.valueOf();
                if (Array.isArray(list)) {
                    for (var i in list) {
                        var obj = list[i];
                        if (typeof obj == "string") {
                            if (arr.indexOf(list[i]) == -1) {
                                arr.push(list[i]);
                            }
                        } else if (typeof obj == "object") {
                            // no se agrega porque se supone que el Setup lo va a saber interpretar como json y no como nombre de paquete
                        }
                    }
                }
                break;
            default:
                console.error("????", arguments);
        }
        return arr;

    }

    jwebdesk.WindowManager.Window.prototype.maximize = function () {
        console.assert(this.component, "ERROR: not component instantiated", [this]);
        this.component.maximize();
    }

    jwebdesk.WindowManager.Window.prototype.minimize = function () {
        console.assert(this.component, "ERROR: not component instantiated", [this]);
        this.component.minimize();
    }

    jwebdesk.WindowManager.Window.prototype.restore = function () {
        console.assert(this.component, "ERROR: not component instantiated", [this]);
        this.component.restore();
    }

    jwebdesk.WindowManager.Window.prototype.fullcanvas = function () {
        console.assert(this.component, "ERROR: not component instantiated", [this]);
        this.component.fullcanvas();
    }

    jwebdesk.WindowManager.Window.prototype.zindex = function (value) {
        var win = this;
        if (arguments.length == 1) {
             win.component.target.css("z-index", value);
        } else {
            return win.component.target.css("z-index");
        }
        return this.load();
    }

    jwebdesk.WindowManager.Window.prototype.reload = function () {
        var win = this;
        if (this.application) delete this.application;
        return this.load();
    }

    jwebdesk.WindowManager.Window.prototype.load = function (params) {
        var df = jwk.Deferred();
        var setup = this.get("setup");
        var component = this.component;
        var win = this;
        var title = setup.get("title");
        if (win.proxy) return df.resolve(win, win.proxy._proxy_id, setup.get("name")).promise();

        if (setup.category == "hud") {
            console.assert(setup.package, setup);
            var req_list = [];
            req_list.push(setup.package.id);
            if (setup.config.skin) req_list = add_packages(req_list, setup.config.skin);
            if (setup.config.plugins) req_list = add_packages(req_list, setup.config.plugins);

            jwebdesk.repository.require(req_list).done(function () {
                var ui_type =  setup.package.ui_type;
                var namespace = setup.package.namespace;
                win.application = jwk.ui.display_component({
                    "name": ui_type,
                    "parent": component,
                    "ui_type": ui_type,
                    "namespace": namespace
                });
                win.proxy = win.application.get_proxy();
                win.proxy.instance = win.application; // esto es temporal (tengo al lounchbar y sus  plugins agarrados de esto)
                df.resolve(win, win.proxy._proxy_id, setup.get("id"));
            });

            if (params && params.fullcanvas) console.error("ERROR: open_app fullcanvas only for 'app' category pacakes. " + setup.id + " is category 'hud'." );
        }

        if (setup.category == "app") {
            var req_list = [setup.get("packid")];
            if (setup.get("package.id", {deep: true})) {
                req_list.push(setup.package.id);
            }
            if (setup.config.skin) req_list = add_packages(req_list, setup.config.skin);
            if (setup.config.plugins) req_list = add_packages(req_list, setup.config.plugins);

            var app_url = setup.url_absolute();
            var url = jwebdesk.serverURL+"?package="+encodeURIComponent(JSON.stringify(req_list))
            if (params) {
                url += "&params="+encodeURIComponent(JSON.stringify(params));
            }

            if (app_url) {
                if (app_url.indexOf("/") == 0) {
                    app_url = jwebdesk.appsURL + app_url;
                }
                url = url + (url.indexOf("?") > 0 ? "&" : "?") + "url="+encodeURIComponent(app_url);
            }

            // TODO: habría que debugear esta parte:
            // Es posible que un setup tenga req_list no vacío y a la vez una url ? alguien hace un assert al respecto?
// console.log("jwebdesk.WindowManager.Window.prototype.load()", "jwk.global._listeners.iframe:", [jwk.global._listeners.iframe]);
            var iframe = component.search("iframe");
            if (iframe) {
                iframe.set("url", url, true);
            } else {
                iframe = jwk.ui.display_component({
                    "name": "iframe",
                    "url": url,
                    "parent": component,
                    "ui_type": "panel.iframe",
                    "namespace": "jwk-ui"
                });
            }

            component.onbeforeclose = function () {
                // console.log("onbeforeclose");
                if (iframe.proxy && typeof iframe.proxy.onbeforeclose == "function") {
                    return iframe.proxy.onbeforeclose();
                }
            };

            (function (fake_proxy) {
                iframe.on("change:proxy", function(n,e) {
                    var proxy = fake_proxy;
                    console.log("change_id() ------------------> APP: ", setup.packid, "fake_proxy:", fake_proxy._proxy_id, "iframe_proxy", e.value._proxy_id);
                    fake_proxy.change_id(e.value._proxy_id);
                    proxy.register_function({
                        close: function () {
                            component.onbeforeclose = null;
                            component.close();
                            return true;
                        }
                    });

                    var menubar = component.search("menubar");
                    proxy.register_function({
                        add_menu:               function () { menubar.add_menu.apply               (menubar, arguments); },
                        add_menu_item:          function () { menubar.add_menu_item.apply          (menubar, arguments); },
                        remove_menu:            function () { menubar.remove_menu.apply            (menubar, arguments); },
                        remove_menu_item:       function () { menubar.remove_menu_item.apply       (menubar, arguments); },
                        set_menu_title:         function () { menubar.set_menu_title.apply         (menubar, arguments); },
                        set_menu_item_shortcut: function () { menubar.set_menu_item_shortcut.apply (menubar, arguments); },
                        set_menu_item_state:    function () { menubar.set_menu_item_state.apply    (menubar, arguments); },
                        set_menu_item:          function () { menubar.set_menu_item.apply          (menubar, arguments); },
                    });

                    function propague_command_event(n,e){
                        proxy.trigger("command", {command: e.command});
                    }
                    menubar.off("command", propague_command_event, win);
                    menubar.on("command", propague_command_event, win);
                });
                df.resolve(win, fake_proxy._proxy_id, setup.get("name"));
            })(jwk.global.proxy());

            /*
            iframe.one("change:proxy", function(n,e) {
                console.log("CHAMGE_ID ", fake_proxy._proxy_id , "->", e.value._proxy_id);
                fake_proxy.change_id(e.value._proxy_id);
            });
            */

            /*
            if (params && params.fullcanvas) {
                win.wait_flag("rendered").done(function() {
                })
            }
            */
            /*
            if (app_url) {
                // the application may not be using jwk.global so iframe.one("change:proxy") event may never occur;
                setTimeout(function (){
                    if (df.state() == "pending") {
                        var fake_proxy = jwk.global.proxy();
                        iframe.one("change:proxy", function(n,e) {
                            // HACK:
                            // me pasó que al abrior el opfolders demora mucho el seteo del proxy y muere por timeout
                            fake_proxy.change_id(e.value._proxy_id);
                        });

                        df.resolve(win, fake_proxy._proxy_id, setup.get("name"));
                    }
                }, 2000);
            }*/

        }

        return df.promise();
    }

    jwebdesk.wait_flag("ready").done(function (){
        if (!jwebdesk.service("window-manager")) {

            var win_man = jwk.ui.create_component({
                "name": "window-manager",
                "ui_type": "window-manager",
                "namespace": "jwebdesk"
            });
            win_man.paint();

            jwebdesk.WindowManager.Window.prototype.manager = win_man;
            win_man.create_service();
            return win_man;
        }
    })

});

//  requirejs(["apps/jwebdesk/hud/window-manager"]);


text:
namespace ash::multidevice {

namespace {

// Attributes of the default stub device.
const char kStubDeviceUserId[] = "example@gmail.com";
const char kStubDevicePiiFreeName[] = "no-pii device";
const char kStubDevicePSK[] = "remote device psk";
const int64_t kStubDeviceLastUpdateTimeMillis = 0L;
const char kBeaconSeedData[] = "beacon seed data";
const int64_t kBeaconSeedStartTimeMillis = 100L;
const int64_t kBeaconSeedEndTimeMillis = 200L;

}  // namespace

// Attributes of the default stub devices.
const char kStubHostPhoneName[] = "Fake Phone";
const char kStubClientComputerName[] = "Fake Computer";
const char kStubHostPhoneInstanceId[] = "1234";
const char kStubClientComputerInstanceId[] = "5678";
const char kStubHostPhonePublicKey[] = "public key phone";
const char kStubClientComputerPublicKey[] = "public key computer";
const char kStubDeviceBluetoothPublicAddress[] = "01:23:45:67:89:AB";

RemoteDevice CreateStubHostPhone() {
  static const base::NoDestructor<RemoteDevice> host_phone([] {
    // Stub host phone defaults to all host features enabled.
    std::map<SoftwareFeature, SoftwareFeatureState> software_features;
    software_features[SoftwareFeature::kBetterTogetherHost] =
        SoftwareFeatureState::kEnabled;
    software_features[SoftwareFeature::kSmartLockHost] =
        SoftwareFeatureState::kEnabled;
    software_features[SoftwareFeature::kInstantTetheringHost] =
        SoftwareFeatureState::kEnabled;
    software_features[SoftwareFeature::kMessagesForWebHost] =
        SoftwareFeatureState::kEnabled;
    software_features[SoftwareFeature::kPhoneHubHost] =
        SoftwareFeatureState::kEnabled;
    software_features[SoftwareFeature::kWifiSyncHost] =
        SoftwareFeatureState::kEnabled;
    software_features[SoftwareFeature::kEcheHost] =
        SoftwareFeatureState::kEnabled;
    software_features[SoftwareFeature::kPhoneHubCameraRollHost] =
        SoftwareFeatureState::kEnabled;

    std::vector<BeaconSeed> beacon_seeds = {multidevice::BeaconSeed(
        kBeaconSeedData, base::Time::FromJavaTime(kBeaconSeedStartTimeMillis),
        base::Time::FromJavaTime(kBeaconSeedEndTimeMillis))};

    return RemoteDevice(kStubDeviceUserId, kStubHostPhoneInstanceId,
                        kStubHostPhoneName, kStubDevicePiiFreeName,
                        kStubHostPhonePublicKey, kStubDevicePSK,
                        kStubDeviceLastUpdateTimeMillis, software_features,
                        beacon_seeds, kStubDeviceBluetoothPublicAddress);
  }());

  return *host_phone;
}

RemoteDevice CreateStubClientComputer() {
  static const base::NoDestructor<RemoteDevice> client_computer([] {
    // Stub client computer relies on flags.
    std::map<SoftwareFeature, SoftwareFeatureState> software_features;
    software_features[SoftwareFeature::kBetterTogetherClient] =
        SoftwareFeatureState::kSupported;
    software_features[SoftwareFeature::kSmartLockClient] =
        SoftwareFeatureState::kSupported;
    software_features[SoftwareFeature::kMessagesForWebClient] =
        SoftwareFeatureState::kSupported;

    software_features[SoftwareFeature::kInstantTetheringClient] =
        base::FeatureList::IsEnabled(features::kInstantTethering)
            ? SoftwareFeatureState::kSupported
            : SoftwareFeatureState::kNotSupported;

    software_features[SoftwareFeature::kPhoneHubClient] =
        features::IsPhoneHubEnabled() ? SoftwareFeatureState::kSupported
                                      : SoftwareFeatureState::kNotSupported;

    software_features[SoftwareFeature::kWifiSyncClient] =
        features::IsWifiSyncAndroidEnabled()
            ? SoftwareFeatureState::kSupported
            : SoftwareFeatureState::kNotSupported;

    software_features[SoftwareFeature::kEcheClient] =
        features::IsEcheSWAEnabled() ? SoftwareFeatureState::kSupported
                                     : SoftwareFeatureState::kNotSupported;

    software_features[SoftwareFeature::kPhoneHubCameraRollClient] =
        features::IsPhoneHubCameraRollEnabled()
            ? SoftwareFeatureState::kSupported
            : SoftwareFeatureState::kNotSupported;

    std::vector<BeaconSeed> beacon_seeds = {multidevice::BeaconSeed(
        kBeaconSeedData, base::Time::FromJavaTime(kBeaconSeedStartTimeMillis),
        base::Time::FromJavaTime(kBeaconSeedEndTimeMillis))};

    return RemoteDevice(kStubDeviceUserId, kStubClientComputerInstanceId,
                        kStubClientComputerName, kStubDevicePiiFreeName,
                        kStubClientComputerPublicKey, kStubDevicePSK,
                        kStubDeviceLastUpdateTimeMillis, software_features,
                        beacon_seeds, kStubDeviceBluetoothPublicAddress);
  }());

  return *client_computer;
}

bool ShouldUseMultideviceStubs() {
  // Should use multidevice stubs if running on Linux CrOS build which doesn't
  // support making authenticated network requests to the back-end.
  return !base::SysInfo::IsRunningOnChromeOS();
}

}  // namespace ash::multidevice

redpajama_set_name: RedPajamaGithub


text:
USE biblioteca;

CREATE TABLE IF NOT EXISTS `AreaConhecimento` (
  `idAreaConhecimento` INT NOT NULL,
  `nomeArea` VARCHAR(45) NULL,
  PRIMARY KEY (`idAreaConhecimento`))
ENGINE = InnoDB


text:
package com.intellij.packaging.impl.artifacts;

import com.intellij.icons.AllIcons;
import com.intellij.packaging.artifacts.ArtifactType;
import com.intellij.packaging.elements.CompositePackagingElement;
import com.intellij.packaging.elements.PackagingElementOutputKind;
import com.intellij.packaging.impl.elements.ZipArchivePackagingElement;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;

/**
 * @author VISTALL
 * @since 15:59/18.06.13
 */
public class ZipArtifactType extends ArtifactType {
  protected ZipArtifactType() {
    super("zip", "Zip");
  }

  @NotNull
  @Override
  public Icon getIcon() {
    return AllIcons.Nodes.Artifact;
  }

  @Override
  public String getDefaultPathFor(@NotNull PackagingElementOutputKind kind) {
    return "/";
  }

  @NotNull
  @Override
  public CompositePackagingElement<?> createRootElement(@NotNull String artifactName) {
    return new ZipArchivePackagingElement(ArtifactUtil.suggestArtifactFileName(artifactName) + ".zip");
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

Tests that shadow roots are displayed correctly in breadcrumbs.

<input type="text">

<template id="tmpl">

inner

</template>


text:
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.commands;

import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.io.URLUtil;
import com.intellij.util.net.HttpConfigurable;
import git4idea.config.GitVcsSettings;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.git4idea.http.GitAskPassXmlRpcHandler;
import org.jetbrains.git4idea.ssh.GitSSHHandler;
import org.jetbrains.git4idea.ssh.GitXmlRpcSshService;

import java.io.IOException;
import java.util.Collection;
import java.util.UUID;

/**
 * Manager for Git remotes authentication.
 * Provides necessary handlers and watcher for http auth failure.
 */
public class GitHandlerAuthenticationManager implements AutoCloseable {
  private static final Logger LOG = Logger.getInstance(GitHandlerAuthenticationManager.class);

  @NotNull private final GitLineHandler myHandler;
  @NotNull private final Project myProject;

  @Nullable private UUID myHttpHandler;
  private volatile boolean myHttpAuthFailed;

  @Nullable private UUID mySshHandler;

  private GitHandlerAuthenticationManager(@NotNull Project project, @NotNull GitLineHandler handler) {
    myProject = project;
    myHandler = handler;
  }

  @NotNull
  public static GitHandlerAuthenticationManager prepare(@NotNull Project project, @NotNull GitLineHandler handler) throws IOException {
    GitHandlerAuthenticationManager manager = new GitHandlerAuthenticationManager(project, handler);
    manager.prepareHttpAuth();
    if (GitVcsSettings.getInstance(project).isIdeaSsh()) manager.prepareSshAuth();
    return manager;
  }

  @Override
  public void close() {
    cleanupHttpAuth();
    cleanupSshAuth();
  }

  private void prepareHttpAuth() throws IOException {
    GitHttpAuthService service = ServiceManager.getService(GitHttpAuthService.class);
    myHandler.addCustomEnvironmentVariable(GitAskPassXmlRpcHandler.GIT_ASK_PASS_ENV, service.getScriptPath().getPath());
    GitHttpAuthenticator httpAuthenticator =
      service.createAuthenticator(myProject, myHandler.getUrls(), myHandler.isIgnoreAuthenticationRequest());
    myHttpHandler = service.registerHandler(httpAuthenticator, myProject);
    myHandler.addCustomEnvironmentVariable(GitAskPassXmlRpcHandler.GIT_ASK_PASS_HANDLER_ENV, myHttpHandler.toString());
    int port = service.getXmlRcpPort();
    myHandler.addCustomEnvironmentVariable(GitAskPassXmlRpcHandler.GIT_ASK_PASS_PORT_ENV, Integer.toString(port));
    LOG.debug(String.format("myHandler=%s, port=%s", myHttpHandler, port));

    myHandler.addLineListener(new GitLineHandlerListener() {
      @Override
      public void onLineAvailable(@NonNls String line, Key outputType) {
        String lowerCaseLine = line.toLowerCase();
        if (lowerCaseLine.contains("authentication failed") ||
            lowerCaseLine.contains("403 forbidden") ||
            lowerCaseLine.contains("error: 400") ||
            (lowerCaseLine.contains("fatal: repository") && lowerCaseLine.contains("not found")) ||
            (lowerCaseLine.contains("fatal: unable to access") && lowerCaseLine.contains("the requested url returned error: 403")) ||
            lowerCaseLine.contains("[remote rejected] (permission denied)")) {
          LOG.debug("auth listener: auth failure detected: " + line);
          myHttpAuthFailed = true;
        }
      }

      @Override
      public void processTerminated(int exitCode) {
        LOG.debug("auth listener: process terminated. auth failed=" + myHttpAuthFailed + ", cancelled=" + httpAuthenticator.wasCancelled());
        if (!httpAuthenticator.wasCancelled()) {
          if (myHttpAuthFailed) {
            httpAuthenticator.forgetPassword();
          }
          else {
            httpAuthenticator.saveAuthData();
          }
        }
        else {
          myHttpAuthFailed = false;
        }
      }
    });
  }

  private void cleanupHttpAuth() {
    if (myHttpHandler != null) {
      ServiceManager.getService(GitHttpAuthService.class).unregisterHandler(myHttpHandler);
      myHttpHandler = null;
    }
  }

  public boolean isHttpAuthFailed() {
    return myHttpAuthFailed;
  }

  private void prepareSshAuth() throws IOException {
    GitXmlRpcSshService ssh = ServiceManager.getService(GitXmlRpcSshService.class);
    myHandler.addCustomEnvironmentVariable(GitSSHHandler.GIT_SSH_ENV, ssh.getScriptPath().getPath());
    myHandler.addCustomEnvironmentVariable(GitSSHHandler.GIT_SSH_VAR, "ssh");
    mySshHandler = ssh.registerHandler(new GitSSHGUIHandler(myProject, myHandler.isIgnoreAuthenticationRequest()), myProject);
    myHandler.addCustomEnvironmentVariable(GitSSHHandler.SSH_HANDLER_ENV, mySshHandler.toString());
    int port = ssh.getXmlRcpPort();
    myHandler.addCustomEnvironmentVariable(GitSSHHandler.SSH_PORT_ENV, Integer.toString(port));
    LOG.debug(String.format("myHandler=%s, port=%s", mySshHandler, port));

    final HttpConfigurable httpConfigurable = HttpConfigurable.getInstance();
    boolean useHttpProxy =
      httpConfigurable.USE_HTTP_PROXY && !isSshUrlExcluded(httpConfigurable, myHandler.getUrls());
    myHandler.addCustomEnvironmentVariable(GitSSHHandler.SSH_USE_PROXY_ENV, String.valueOf(useHttpProxy));

    if (useHttpProxy) {
      myHandler.addCustomEnvironmentVariable(GitSSHHandler.SSH_PROXY_HOST_ENV, StringUtil.notNullize(httpConfigurable.PROXY_HOST));
      myHandler.addCustomEnvironmentVariable(GitSSHHandler.SSH_PROXY_PORT_ENV, String.valueOf(httpConfigurable.PROXY_PORT));
      boolean proxyAuthentication = httpConfigurable.PROXY_AUTHENTICATION;
      myHandler.addCustomEnvironmentVariable(GitSSHHandler.SSH_PROXY_AUTHENTICATION_ENV, String.valueOf(proxyAuthentication));

      if (proxyAuthentication) {
        myHandler.addCustomEnvironmentVariable(GitSSHHandler.SSH_PROXY_USER_ENV, StringUtil.notNullize(httpConfigurable.getProxyLogin()));
        myHandler.addCustomEnvironmentVariable(GitSSHHandler.SSH_PROXY_PASSWORD_ENV,
                                               StringUtil.notNullize(httpConfigurable.getPlainProxyPassword()));
      }
    }
  }

  private void cleanupSshAuth() {
    if (mySshHandler != null) {
      ServiceManager.getService(GitXmlRpcSshService.class).unregisterHandler(mySshHandler);
      mySshHandler = null;
    }
  }

  private static boolean isSshUrlExcluded(@NotNull HttpConfigurable httpConfigurable, @NotNull Collection<String> urls) {
    return ContainerUtil.exists(urls, url -> {
      String host = URLUtil.parseHostFromSshUrl(url);
      return httpConfigurable.isProxyException(host);
    });
  }
}


text:
from model.group import Group

class GroupHelper:

    def __init__(self, app):
        self.app = app

    def open_groups_page(self):
        wd = self.app.wd
        if not(wd.current_url.endswith("/group.php") and len(wd.find_elements_by_name("new")) > 0):
            wd.find_element_by_link_text("groups").click()

    def create(self, group):
        wd = self.app.wd
        self.open_groups_page()
        wd.find_element_by_name("new").click()
        self.fill_group_form(group)
        wd.find_element_by_name("submit").click()
        self.return_to_group_page()
        self.group_cache = None

    def fill_group_form(self, group):
        wd = self.app.wd
        self.change_field_value("group_name", group.name)
        self.change_field_value("group_header", group.header)
        self.change_field_value("group_footer", group.footer)

    def change_field_value(self, field_name, text):
        wd = self.app.wd
        if text is not None:
            wd.find_element_by_name(field_name).click()
            wd.find_element_by_name(field_name).clear()
            wd.find_element_by_name(field_name).send_keys(text)

    def delete_group_by_index(self, index):
        wd = self.app.wd
        self.open_groups_page()
        wd.find_elements_by_name("selected[]")[index].click()
        wd.find_element_by_name("delete").click()
        self.return_to_group_page()
        self.group_cache = None

    def delete_group_by_id(self, id):
        wd = self.app.wd
        self.open_groups_page()
        self.select_group_by_id(id)
        wd.find_element_by_name("delete").click()
        self.return_to_group_page()
        self.group_cache = None

    def delete_first_group(self):
        self.delete_group_by_index(0)

    def select_group_by_id(self, id):
        wd = self.app.wd
        wd.find_element_by_css_selector("input[value='%s']" % id).click()

    def select_group_by_index(self, index):
         wd = self.app.wd
         wd.find_elements_by_name("selected[]")[index].click()

    def modify_group_by_index(self, new_group_data, index):
        wd = self.app.wd
        self.open_groups_page()
        self.select_group_by_index(index)
        wd.find_element_by_name("edit").click()
        self.fill_group_form(new_group_data)
        wd.find_element_by_name("update").click()
        self.return_to_group_page()
        self.group_cache = None

    def modify_group_by_id(self, new_group_data, id):
        wd = self.app.wd
        self.open_groups_page()
        self.select_group_by_id(id)
        wd.find_element_by_name("edit").click()
        self.fill_group_form(new_group_data)
        wd.find_element_by_name("update").click()
        self.return_to_group_page()
        self.group_cache = None

    def modify_first_group(self, new_group_data):
        self.modify_group_by_index(new_group_data, 0)

    def return_to_group_page(self):
        wd = self.app.wd
        wd.find_element_by_link_text("group page").click()

    def count(self):
        wd = self.app.wd
        self.open_groups_page()
        return len(wd.find_elements_by_name("selected[]"))

    group_cache = None

    def get_group_list(self):
        if self.group_cache is None:
            wd = self.app.wd
            self.open_groups_page()
            self.group_cache = []
            for element in wd.find_elements_by_css_selector("span.group"):
                text = element.text
                id=element.find_element_by_name("selected[]").get_attribute("value")
                self.group_cache.append(Group(name=text, id=id))
        return list(self.group_cache)

    def clean(group):
        return Group(id=group.id, name=group.name.strip())


text:
package com.intellij.openapi.application;

import com.intellij.ExtensionPoints;
import com.intellij.openapi.extensions.ExtensionPointName;
import org.jetbrains.annotations.NonNls;

/**
 * Implementors of this interface declared via {@link com.intellij.ExtensionPoints#APPLICATION_STARTER} contribute a
 * command line application based on IDEA platform.
 *
 * @author max
 * @see ApplicationStarterEx
 */
public interface ApplicationStarter {
  ExtensionPointName<ApplicationStarter> EP_NAME = ExtensionPointName.create(ExtensionPoints.APPLICATION_STARTER);

  /**
   * Command line switch to start with this runner. For example return "inspect" if you'd like to start app with
   * idea.exe inspect cmdline.
   * @return command line selector.
   */
  @NonNls
  String getCommandName();

  /**
   * Called before application initialization. Invoked in awt dispatch thread.
   * @param args cmdline arguments including declared selector. For example "idea.exe inspect myproject.ipr"
   * will pass {"inspect", "myproject.ipr"}
   */
  void premain(String[] args);

  /**
   * Called when application have been initialized. Invoked in awt dispatch thread. An application starter should take care terminating
   * JVM itself when appropriate by calling {@link java.lang.System#exit}(0);
   * @param args cmdline arguments including declared selector. For example "idea.exe inspect myproject.ipr"
   * will pass {"inspect", "myproject.ipr"}
   */
  void main(String[] args);
}


text:
package com.bazaarvoice.jolt.common.pathelement;

import com.bazaarvoice.jolt.common.tree.MatchedElement;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class StarRegexPathElementTest {

    @DataProvider
    public Object[][] getStarPatternTests() {
        return new Object[][] {
                {"easy star test",                "rating-*-*",               "rating-tuna-marlin",                         "tuna",      "marlin"},
                {"easy facet usage",              "terms--config--*--*--cdv", "terms--config--Expertise--12345--cdv",       "Expertise", "12345"},
                {"degenerate ProductId in facet", "terms--config--*--*--cdv", "terms--config--Expertise--12345--6789--cdv", "Expertise", "12345--6789"},
                {"multi metachar test",           "rating.$.*.*",               "rating.$.marlin$.test.",                   "marlin$",   "test."},
        };
    }

    @Test( dataProvider = "getStarPatternTests")
    public void starPatternTest( String testName, String spec, String dataKey, String expected1, String expected2 ) {

        StarPathElement star = new StarRegexPathElement( spec );

        MatchedElement lpe = star.match( dataKey, null );

        Assert.assertEquals( 3, lpe.getSubKeyCount() );
        Assert.assertEquals( dataKey,   lpe.getSubKeyRef( 0 ) );
        Assert.assertEquals( expected1, lpe.getSubKeyRef( 1 ) );
        Assert.assertEquals( expected2, lpe.getSubKeyRef( 2 ) );
    }

    @Test
    public void mustMatchSomethingTest() {

        StarPathElement star = new StarRegexPathElement( "tuna-*-*");

        Assert.assertNull( star.match( "tuna--", null ) );
        Assert.assertNull( star.match( "tuna-bob-", null ) );
        Assert.assertNull( star.match( "tuna--bob", null ) );

        StarPathElement multiMetacharStarpathelement = new StarRegexPathElement( "rating-$-*-*");

        Assert.assertNull( multiMetacharStarpathelement.match( "rating-capGrp1-capGrp2", null ) );
        Assert.assertNull( multiMetacharStarpathelement.match( "rating-$capGrp1-capGrp2", null ) );
        Assert.assertNotNull(multiMetacharStarpathelement.match( "rating-$-capGrp1-capGrp2",null) );
    }
}


text:
import json
import argparse
import map_json_common as mjc
import sys

def generate_out_filename(infileName, startInd, endInd):
    dotInd= infileName.rfind(".")
    slashInd= infileName.rfind("/")
    suffix= "_trunc" + str(startInd) + "-" + str(endInd)
    outFName= infileName + suffix if dotInd < 0 or (slashInd > 0 and dotInd < slashInd) else \
            infileName[:dotInd] + suffix + infileName[dotInd:]
    return outFName
#### End of function generate_out_filename

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Takes a start and end index" +
    " and truncates the samples in a JSON file to contain only the given" +
    " samples.")

    # Add a file to read input from
    parser.add_argument("infile", help="JSON format file which has been " +
            "exported from an Arm MAP file")
    # Add a file to read metrics from
    parser.add_argument("startInd", help="Zero based index of the sample number" +
            " from which to start (inclusive)", type=int, default=0)
    parser.add_argument("endInd", help="Zero based index of the sample number" +
            " at which to end (inclusive)", type=int, default=-1)

    # Parse the arguments
    args = parser.parse_args()

    # Open the JSON file for reading
    with open(args.infile, "r") as f:
        profileDict = json.load(f)

    # Ensure that the number of samples we want to obtain are in the right range
    if (args.startInd < 0 or args.startInd >= args.endInd or
        args.endInd >= mjc.get_sample_count(profileDict)):
        print("Invalid index range [" + str(args.startInd) + ", " + str(args.endInd) + "]")
        sys.exit(1)

    mjc.truncate_profile(profileDict, args.startInd, args.endInd)

    outFileName= generate_out_filename(args.infile, args.startInd, args.endInd)
    with open(outFileName, "w") as f:
        json.dump(profileDict, f, sort_keys=True, indent=4)
    print("Truncated JSON samples written to " + outFileName)
#### End of main function


text:
class ClientApplication
  attr_accessor :key

  def self.find_by_key(key)
    ClientApplication.new(key)
  end

  def initialize(key)
    @key = key
  end

  def tokens
    @tokens||=[]
  end

  def secret
    "secret"
  end
end

class OauthToken
  attr_accessor :token, :refresh_token

  def self.where(q, p)
    case p
    when "not_authorized", "invalidated"
      []
    else
      [OauthToken.new(p)]
    end
  end

  def initialize(token)
    @token = token
  end

  def secret
    "secret"
  end
end

class Oauth2Token < OauthToken ; end
class Oauth2Verifier < OauthToken ; end
class AccessToken < OauthToken ; end
class RequestToken < OauthToken ; end

class OauthNonce
  # Always remember
  def self.remember(nonce,timestamp)
    true
  end
end


text:
package org.scribe.model;

import java.io.*;

/**
 * Parameter object that groups OAuth config values
 *
 * @author Pablo Fernandez
 */
public class OAuthConfig
{
  private final String apiKey;
  private final String apiSecret;
  private final String callback;
  private final SignatureType signatureType;
  private final String scope;
  private final OutputStream debugStream;
  private final boolean offline;

  public OAuthConfig(String key, String secret)
  {
    this(key, secret, null, null, null, null);
  }

  public OAuthConfig(String key, String secret, String callback, SignatureType type, String scope, OutputStream stream)
  {
      this(key, secret, callback, type, scope, stream, true);
  }

  public OAuthConfig(String key, String secret, String callback, SignatureType type, String scope, OutputStream stream, boolean offline)
  {
    this.apiKey = key;
    this.apiSecret = secret;
    this.callback = callback;
    this.signatureType = type;
    this.scope = scope;
    this.debugStream = stream;
    this.offline = offline;
  }

  public String getApiKey()
  {
    return apiKey;
  }

  public String getApiSecret()
  {
    return apiSecret;
  }

  public String getCallback()
  {
    return callback;
  }

  public SignatureType getSignatureType()
  {
    return signatureType;
  }

  public String getScope()
  {
    return scope;
  }

  public boolean hasScope()
  {
    return scope != null;
  }

  public boolean isOffline()
  {
      return offline;
  }

  public void log(String message)
  {
    if (debugStream != null)
    {
      message = message + "\n";
      try
      {
        debugStream.write(message.getBytes("UTF8"));
      }
      catch (Exception e)
      {
        throw new RuntimeException("there were problems while writing to the debug stream", e);
      }
    }
  }
}


text:
var passport = require('passport'),
  LocalStrategy = require('passport-local').Strategy,
  bcrypt = require('bcrypt'),
  BearerStrategy = require('passport-http-bearer').Strategy;

function findByUsername(u, fn) {
  User.findOne({
    username: u
  }).exec(function (err, user) {
    // Error handling
    if (err) return fn(null, null);
    else return fn(null, user);
  });
}
function findByToken(token, fn) {
  User.findOne({access_token: token}).exec(function(err, user) {
    if (err) return fn(null, null);
    else return fn(null, user);
  });
}

function findById(id, fn) {
  User.findOne(id).exec(function (err, user) {
    if (err) return fn(null, null);
    else return fn(null, user);
  });
}

passport.serializeUser(function (user, done) {
  done(null, user.id);
});

passport.deserializeUser(function (id, done) {
  findById(id, function (err, user) {
    done(err, user);
  });
});

// Use the LocalStrategy within Passport.
passport.use('local', new LocalStrategy(
  function (username, password, done) {
    // asynchronous verification, for effect...
    process.nextTick(function () {
      // Find the user by username. If there is no user with the given
      // username, or the password is not correct, set the user to `false` to
      // indicate failure and set a flash message. Otherwise, return the
      // authenticated `user`.
      findByUsername(username, function (err, user) {
        if (err)
          return done(null, err);
        if (!user) {
          return done(null, false, {
            message: 'Unknown user ' + username
          });
        }
        bcrypt.compare(password, user.password, function (err, res) {
          if (!res)
            return done(null, false, {
              message: 'Invalid Password'
            });
          var returnUser = {
            username: user.username,
            createdAt: user.createdAt,
            id: user.id
          };
          return done(null, returnUser, {
            message: 'Logged In Successfully'
          });
        });
      })
    });
  }
));

passport.use('bearer', new BearerStrategy(
  function(token, done) {
    // asynchronous validation, for effect...
    process.nextTick(function () {
      // Find the user by token. If there is no user with the given token, set
      // the user to `false` to indicate failure. Otherwise, return the
      // authenticated `user`.
      findByToken(token, function(err, user) {
        if (err) { return done(err); }
        if (!user) { return done(null, false); }
        return done(null, user);
      })
    });
  }
));


text:
package org.jboss.pnc.core.builder.datastore;

import org.jboss.logging.Logger;
import org.jboss.pnc.core.BuildCoordinationException;
import org.jboss.pnc.core.builder.coordinator.BuildTask;
import org.jboss.pnc.model.Artifact;
import org.jboss.pnc.model.BuildConfigSetRecord;
import org.jboss.pnc.model.BuildConfiguration;
import org.jboss.pnc.model.BuildConfigurationAudited;
import org.jboss.pnc.model.BuildRecord;
import org.jboss.pnc.spi.BuildResult;
import org.jboss.pnc.spi.builddriver.BuildDriverResult;
import org.jboss.pnc.spi.datastore.Datastore;
import org.jboss.pnc.spi.datastore.DatastoreException;
import org.jboss.pnc.spi.executor.BuildExecutionConfiguration;
import org.jboss.pnc.spi.repositorymanager.RepositoryManagerResult;

import javax.inject.Inject;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
import java.util.Optional;

import static org.jboss.pnc.model.BuildStatus.SYSTEM_ERROR;

/**
 * Created by Matej Lazar on 2014-12-15.
 */
public class DatastoreAdapter {

    private Datastore datastore;

    private static final Logger log = Logger.getLogger(DatastoreAdapter.class);

    // needed for EJB/CDI
    @Deprecated
    public DatastoreAdapter() {
    }

    @Inject
    public DatastoreAdapter(Datastore datastore) {
        this.datastore = datastore;
    }

    public BuildConfigSetRecord saveBuildConfigSetRecord(BuildConfigSetRecord buildConfigSetRecord) throws DatastoreException {
        return datastore.saveBuildConfigSetRecord(buildConfigSetRecord);
    }

    /**
     * Get the latest audited revision for the given build configuration ID
     *
     * @param buildConfigurationId
     * @return The latest revision of the given build configuration
     */
    public BuildConfigurationAudited getLatestBuildConfigurationAudited(Integer buildConfigurationId) {
        return datastore.getLatestBuildConfigurationAudited(buildConfigurationId);
    }

    public void storeResult(BuildTask buildTask, BuildResult buildResult) throws DatastoreException {
        try {
            if (!buildResult.getBuildDriverResult().isPresent()) {
                storeResult(buildTask, new BuildCoordinationException("Trying to store success build with incomplete result. Missing BuildDriverResult."));
                return;
            }

            if (!buildResult.getRepositoryManagerResult().isPresent()) {
                storeResult(buildTask, new BuildCoordinationException("Trying to store success build with incomplete result. Missing RepositoryManagerResult."));
                return;
            }

            BuildDriverResult buildDriverResult = buildResult.getBuildDriverResult().get();
            RepositoryManagerResult repositoryManagerResult = buildResult.getRepositoryManagerResult().get();

            BuildRecord.Builder buildRecordBuilder = createBuildRecord(buildTask, Optional.of(repositoryManagerResult.getBuildContentId()));

            BuildExecutionConfiguration buildExecutionConfig = buildResult.getBuildExecutionConfiguration().get();
            buildRecordBuilder.scmRepoURL(buildExecutionConfig.getScmRepoURL());
            buildRecordBuilder.scmRevision(buildExecutionConfig.getScmRevision());

            // Build driver results
            buildRecordBuilder.buildLog(buildDriverResult.getBuildLog());
            buildRecordBuilder.status(buildDriverResult.getBuildDriverStatus().toBuildStatus());

            BuildRecord buildRecord = buildRecordBuilder.build();
            linkArtifactsWithBuildRecord(repositoryManagerResult.getBuiltArtifacts(), buildRecord);
            buildRecord.setBuiltArtifacts(repositoryManagerResult.getBuiltArtifacts());
            linkArtifactsWithBuildRecord(repositoryManagerResult.getDependencies(), buildRecord);
            buildRecord.setDependencies(repositoryManagerResult.getDependencies());

            log.debugf("Storing results of buildTask [%s] to datastore.", buildTask.getId());
            datastore.storeCompletedBuild(buildRecord, buildTask.getBuildRecordSetIds());
        } catch (Exception e) {
            throw new DatastoreException("Error storing the result to datastore.", e);
        }
    }

    public void storeResult(BuildTask buildTask, Throwable e) throws DatastoreException {
        BuildRecord.Builder buildRecordBuilder = createBuildRecord(buildTask, Optional.<String>empty());
        StringWriter stackTraceWriter = new StringWriter();
        PrintWriter stackTracePrinter = new PrintWriter(stackTraceWriter);
        e.printStackTrace(stackTracePrinter);
        buildRecordBuilder.status(SYSTEM_ERROR);

        String errorMessage = "Last build status: " + buildTask.getStatus().toString() + "\n";
        errorMessage += "Caught exception: " + stackTraceWriter.toString();
        buildRecordBuilder.buildLog(errorMessage);

        log.debugf("Storing ERROR result of %s to datastore. Error: %s", buildTask.getBuildConfigurationAudited().getName() + "\n\n\n Exception: " + errorMessage, e);
        datastore.storeCompletedBuild(buildRecordBuilder.build(), buildTask.getBuildRecordSetIds());
    }

    /**
     * Initialize a new BuildRecord based on the data contained in the BuildTask.
     * Note, this must be done inside a transaction because it fetches the BuildRecordSet entities from
     * the database.
     *
     * @return The initialized build record builder
     */
    private BuildRecord.Builder createBuildRecord(BuildTask buildTask, Optional<String> buildContentId) {
        BuildRecord.Builder builder = BuildRecord.Builder.newBuilder().id(buildTask.getId())
                .buildConfigurationAudited(buildTask.getBuildConfigurationAudited())
                .user(buildTask.getUser())
                .submitTime(buildTask.getSubmitTime())
                .startTime(buildTask.getStartTime())
                .endTime(buildTask.getEndTime());

        buildContentId.ifPresent((id) -> builder.buildContentId(id));

        builder.latestBuildConfiguration(buildTask.getBuildConfiguration());
        if (buildTask.getBuildConfigSetRecordId() != null) {
            BuildConfigSetRecord buildConfigSetRecord = datastore.getBuildConfigSetRecordById(buildTask.getBuildConfigSetRecordId());
            builder.buildConfigSetRecord(buildConfigSetRecord);
        }

        return builder;
    }

    public Integer getNextBuildRecordId() {
        return datastore.getNextBuildRecordId();
    }

    private void linkArtifactsWithBuildRecord(List<Artifact> artifacts, BuildRecord buildRecord) {
        artifacts.forEach(a -> a.setBuildRecord(buildRecord));
    }

    public boolean hasSuccessfulBuildRecord(BuildConfiguration buildConfiguration) {
        return datastore.hasSuccessfulBuildRecord(buildConfiguration);
    }
}


text:
namespace AllReady.Security
{
    public interface IAuthorizableEventIdContainer
    {
        int CampaignId { get; }
        int EventId { get; }
        int OrganizationId { get; }
    }
}


text:
CodeHS Provider
The Top Coding Education Platform for Schools

## Implementation Details

- Provider
Name: CodeHS
- Documentation: NONE
- HTTPS support: YES
- Fake Response: NO
- Oembed Params: maxwidth , maxheight
- Supported Hosts: codehs.com
- Responsive response: NO
- Collections: DefaultProviderCollection


text:
/*
 * FreeBSD port by Stephen Montgomery-Smith <stephen@math.missouri.edu>
 *
 * Redone by John Fay 2/4/04 with another look from the PLIB "js" library.
 *  Many thanks for Steve Baker for permission to pull from that library.
 */

#include <GL/freeglut.h>
#include "fg_internal.h"
#ifdef HAVE_SYS_PARAM_H
#    include <sys/param.h>
#endif

#define JS_TRUE  1
#define JS_FALSE 0

/*
 * Functions associated with the "jsJoystick" class in PLIB
 */
#if TARGET_HOST_MAC_OSX
#define K_NUM_DEVICES   32
int numDevices;
io_object_t ioDevices[K_NUM_DEVICES];

static void fghJoystickFindDevices ( SFG_Joystick* joy, mach_port_t );
static CFDictionaryRef fghJoystickGetCFProperties ( SFG_Joystick* joy, io_object_t );

static void fghJoystickEnumerateElements ( SFG_Joystick* joy, CFTypeRef element );
/* callback for CFArrayApply */
static void fghJoystickElementEnumerator ( SFG_Joystick* joy, void *element, void* vjs );

static void fghJoystickAddAxisElement ( SFG_Joystick* joy, CFDictionaryRef axis );
static void fghJoystickAddButtonElement ( SFG_Joystick* joy, CFDictionaryRef button );
static void fghJoystickAddHatElement ( SFG_Joystick* joy, CFDictionaryRef hat );
#endif

/* External function declarations (mostly platform-specific) */
extern void fgPlatformJoystickRawRead( SFG_Joystick* joy, int* buttons, float* axes );
extern void fgPlatformJoystickOpen( SFG_Joystick* joy );
extern void fgPlatformJoystickInit( SFG_Joystick *fgJoystick[], int ident );
extern void fgPlatformJoystickClose ( int ident );

/*
 * The static joystick structure pointer
 */
#define MAX_NUM_JOYSTICKS  2
SFG_Joystick *fgJoystick [ MAX_NUM_JOYSTICKS ];

/*
 * Read the raw joystick data
 */
static void fghJoystickRawRead( SFG_Joystick* joy, int* buttons, float* axes )
{
    int i;

    /* Defaults */
    if( buttons )
        *buttons = 0;

    if( axes )
        for( i = 0; i < joy->num_axes; i++ )
            axes[ i ] = 1500.0f;

    if( joy->error )
        return;

    fgPlatformJoystickRawRead ( joy, buttons, axes );
}

/*
 * Correct the joystick axis data
 */
static float fghJoystickFudgeAxis( SFG_Joystick* joy, float value, int axis )
{
    if( value < joy->center[ axis ] )
    {
        float xx = ( value - joy->center[ axis ] ) / ( joy->center[ axis ] -
                                                       joy->min[ axis ] );

        if( xx < -joy->saturate[ axis ] )
            return -1.0f;

        if( xx > -joy->dead_band [ axis ] )
            return 0.0f;

        xx = ( xx + joy->dead_band[ axis ] ) / ( joy->saturate[ axis ] -
                                                 joy->dead_band[ axis ] );

        return ( xx < -1.0f ) ? -1.0f : xx;
    }
    else
    {
        float xx = ( value - joy->center [ axis ] ) / ( joy->max[ axis ] -
                                                        joy->center[ axis ] );

        if( xx > joy->saturate[ axis ] )
            return 1.0f;

        if( xx < joy->dead_band[ axis ] )
            return 0.0f;

        xx = ( xx - joy->dead_band[ axis ] ) / ( joy->saturate[ axis ] -
                                                 joy->dead_band[ axis ] );

        return ( xx > 1.0f ) ? 1.0f : xx;
    }
}

/*
 * Read the corrected joystick data
 */
static void fghJoystickRead( SFG_Joystick* joy, int* buttons, float* axes )
{
    float raw_axes[ _JS_MAX_AXES ];
    int  i;

    if( joy->error )
    {
        if( buttons )
            *buttons = 0;

        if( axes )
            for ( i=0; i<joy->num_axes; i++ )
                axes[ i ] = 0.0f;
    }

    fghJoystickRawRead( joy, buttons, raw_axes );

    if( axes )
        for( i=0; i<joy->num_axes; i++ )
            axes[ i ] = fghJoystickFudgeAxis( joy, raw_axes[ i ], i );
}

/*
 * Happy happy happy joy joy joy (happy new year toudi :D)
 */

#if TARGET_HOST_MAC_OSX
/** open the IOKit connection, enumerate all the HID devices, add their
interface references to the static array. We then use the array index
as the device number when we come to open() the joystick. */
static int fghJoystickFindDevices ( SFG_Joystick *joy, mach_port_t masterPort )
{
    CFMutableDictionaryRef hidMatch = NULL;
    IOReturn rv = kIOReturnSuccess;

    io_iterator_t hidIterator;
    io_object_t ioDev;

    /* build a dictionary matching HID devices */
    hidMatch = IOServiceMatching(kIOHIDDeviceKey);

    rv = IOServiceGetMatchingServices(masterPort, hidMatch, &hidIterator);
    if (rv != kIOReturnSuccess || !hidIterator) {
      fgWarning( "no joystick (HID) devices found" );
      return;
    }

    /* iterate */
    while ((ioDev = IOIteratorNext(hidIterator))) {
        /* filter out keyboard and mouse devices */
        CFDictionaryRef properties = getCFProperties(ioDev);
        long usage, page;

        CFTypeRef refPage = CFDictionaryGetValue (properties, CFSTR(kIOHIDPrimaryUsagePageKey));
        CFTypeRef refUsage = CFDictionaryGetValue (properties, CFSTR(kIOHIDPrimaryUsageKey));
        CFNumberGetValue((CFNumberRef) refUsage, kCFNumberLongType, &usage);
        CFNumberGetValue((CFNumberRef) refPage, kCFNumberLongType, &page);

        /* keep only joystick devices */
        if ( ( page == kHIDPage_GenericDesktop ) && (
                            (usage == kHIDUsage_GD_Joystick)
                         || (usage == kHIDUsage_GD_GamePad)
                         || (usage == kHIDUsage_GD_MultiAxisController)
                         || (usage == kHIDUsage_GD_Hatswitch) /* last two necessary ? */
            /* add it to the array */
            ioDevices[numDevices++] = ioDev;
    }

    IOObjectRelease(hidIterator);
}

static CFDictionaryRef fghJoystickGetCFProperties ( SFG_Joystick *joy, io_object_t ioDev )
{
    IOReturn rv;
    CFMutableDictionaryRef cfProperties;

#if 0
    /* comment copied from darwin/SDL_sysjoystick.c */
    /* Mac OS X currently is not mirroring all USB properties to HID page so need to look at USB device page also
     * get dictionary for usb properties: step up two levels and get CF dictionary for USB properties
     */

    io_registry_entry_t parent1, parent2;

    rv = IORegistryEntryGetParentEntry (ioDev, kIOServicePlane, &parent1);
    if (rv != kIOReturnSuccess) {
        fgWarning ( "error getting device entry parent");
        return NULL;
    }

    rv = IORegistryEntryGetParentEntry (parent1, kIOServicePlane, &parent2);
    if (rv != kIOReturnSuccess) {
        fgWarning ( "error getting device entry parent 2");
        return NULL;
    }
#endif

    rv = IORegistryEntryCreateCFProperties( ioDev /*parent2*/,
        &cfProperties, kCFAllocatorDefault, kNilOptions);
    if (rv != kIOReturnSuccess || !cfProperties) {
        fgWarning ( "error getting device properties");
        return NULL;
    }

    return cfProperties;
}

static void fghJoystickElementEnumerator ( SFG_Joystick *joy, void *element, void* vjs )
{
      if (CFGetTypeID((CFTypeRef) element) != CFDictionaryGetTypeID()) {
            fgError ( "%s", "element enumerator passed non-dictionary value");
            return;
    }

      static_cast<jsJoystick*>(vjs)->parseElement ( (CFDictionaryRef) element );
}

/** element enumerator function : pass NULL for top-level*/
static void fghJoystickEnumerateElements ( SFG_Joystick *joy, CFTypeRef element )
{
      FREEGLUT_INTERNAL_ERROR_EXIT( (CFGetTypeID(element) == CFArrayGetTypeID(),
                                    "Joystick element type mismatch",
                                    "fghJoystickEnumerateElements" );

      CFRange range = {0, CFArrayGetCount ((CFArrayRef)element)};
      CFArrayApplyFunction((CFArrayRef) element, range,
            &fghJoystickElementEnumerator, joy );
}

static void fghJoystickAddAxisElement ( SFG_Joystick *joy, CFDictionaryRef axis )
{
    long cookie, lmin, lmax;
    int index = joy->num_axes++;

    CFNumberGetValue ((CFNumberRef)
        CFDictionaryGetValue ( axis, CFSTR(kIOHIDElementCookieKey) ),
        kCFNumberLongType, &cookie);

    joy->pJoystick.axisCookies[index] = (IOHIDElementCookie) cookie;

    CFNumberGetValue ((CFNumberRef)
        CFDictionaryGetValue ( axis, CFSTR(kIOHIDElementMinKey) ),
        kCFNumberLongType, &lmin);

    CFNumberGetValue ((CFNumberRef)
        CFDictionaryGetValue ( axis, CFSTR(kIOHIDElementMaxKey) ),
        kCFNumberLongType, &lmax);

    joy->min[index] = lmin;
    joy->max[index] = lmax;
    joy->dead_band[index] = 0.0;
    joy->saturate[index] = 1.0;
    joy->center[index] = (lmax + lmin) * 0.5;
}

static void fghJoystickAddButtonElement ( SFG_Joystick *joy, CFDictionaryRef button )
{
    long cookie;
    CFNumberGetValue ((CFNumberRef)
            CFDictionaryGetValue ( button, CFSTR(kIOHIDElementCookieKey) ),
            kCFNumberLongType, &cookie);

    joy->pJoystick.buttonCookies[num_buttons++] = (IOHIDElementCookie) cookie;
    /* anything else for buttons? */
}

static void fghJoystickAddHatElement ( SFG_Joystick *joy, CFDictionaryRef button )
{
    /* hatCookies[num_hats++] = (IOHIDElementCookie) cookie; */
    /* do we map hats to axes or buttons? */
}
#endif

/*
 *  Platform-Specific Code
 */

#if TARGET_HOST_MACINTOSH
void fgPlatformJoystickRawRead( SFG_Joystick* joy, int* buttons, float* axes )
{
    int i;

    if ( buttons )
    {
        *buttons = 0;

        for ( i = 0; i < joy->num_buttons; i++ )
        {
            UInt32 state;
            int err = ISpElement_GetSimpleState ( joy->pJoystick.isp_elem [ i + ISP_NUM_AXIS ], &state);
            ISP_CHECK_ERR(err)

            *buttons |= state << i;
        }
    }

    if ( axes )
    {
        for ( i = 0; i < joy->num_axes; i++ )
        {
            UInt32 state;
            int err = ISpElement_GetSimpleState ( joy->pJoystick.isp_elem [ i ], &state );
            ISP_CHECK_ERR(err)

            axes [i] = (float) state;
        }
    }
}

void fgPlatformJoystickOpen( SFG_Joystick* joy )
{
    int i = 0;
    OSStatus err;

    /* XXX FIXME: get joystick name in Mac */

    err = ISpStartup( );

    if( err == noErr )
    {
#define ISP_CHECK_ERR(x) if( x != noErr ) { joy->error = GL_TRUE; return; }

        joy->error = GL_TRUE;

        /* initialize the needs structure */
        ISpNeed temp_isp_needs[ ISP_NUM_NEEDS ] =
        {
          { "\pX-Axis",  128, 0, 0, kISpElementKind_Axis,   kISpElementLabel_None, 0, 0, 0, 0 },
          { "\pY-Axis",  128, 0, 0, kISpElementKind_Axis,   kISpElementLabel_None, 0, 0, 0, 0 },
          { "\pZ-Axis",    128, 0, 0, kISpElementKind_Axis,   kISpElementLabel_None, 0, 0, 0, 0 },
          { "\pR-Axis",    128, 0, 0, kISpElementKind_Axis,   kISpElementLabel_None, 0, 0, 0, 0 },
          { "\pAxis   4",  128, 0, 0, kISpElementKind_Axis,   kISpElementLabel_None, 0, 0, 0, 0 },
          { "\pAxis   5",  128, 0, 0, kISpElementKind_Axis,   kISpElementLabel_None, 0, 0, 0, 0 },
          { "\pAxis   6",  128, 0, 0, kISpElementKind_Axis,   kISpElementLabel_None, 0, 0, 0, 0 },
          { "\pAxis   7",  128, 0, 0, kISpElementKind_Axis,   kISpElementLabel_None, 0, 0, 0, 0 },
          { "\pAxis   8",  128, 0, 0, kISpElementKind_Axis,   kISpElementLabel_None, 0, 0, 0, 0 },

          { "\pButton 0",  128, 0, 0, kISpElementKind_Button, kISpElementLabel_Btn_Select, 0, 0, 0, 0 },
          { "\pButton 1",  128, 0, 0, kISpElementKind_Button, kISpElementLabel_Btn_Select, 0, 0, 0, 0 },
          { "\pButton 2",  128, 0, 0, kISpElementKind_Button, kISpElementLabel_Btn_Select, 0, 0, 0, 0 },
          { "\pButton 3",  128, 0, 0, kISpElementKind_Button, kISpElementLabel_Btn_Select, 0, 0, 0, 0 },
          { "\pButton 4",  128, 0, 0, kISpElementKind_Button, kISpElementLabel_Btn_Select, 0, 0, 0, 0 },
          { "\pButton 5",  128, 0, 0, kISpElementKind_Button, kISpElementLabel_Btn_Select, 0, 0, 0, 0 },
          { "\pButton 6",  128, 0, 0, kISpElementKind_Button, kISpElementLabel_Btn_Select, 0, 0, 0, 0 },
          { "\pButton 7",  128, 0, 0, kISpElementKind_Button, kISpElementLabel_Btn_Select, 0, 0, 0, 0 },
          { "\pButton 8",  128, 0, 0, kISpElementKind_Button, kISpElementLabel_Btn_Select, 0, 0, 0, 0 },
          { "\pButton 9",  128, 0, 0, kISpElementKind_Button, kISpElementLabel_Btn_Select, 0, 0, 0, 0 },
          { "\pButton 10", 128, 0, 0, kISpElementKind_Button, kISpElementLabel_Btn_Select, 0, 0, 0, 0 },
          { "\pButton 11", 128, 0, 0, kISpElementKind_Button, kISpElementLabel_Btn_Select, 0, 0, 0, 0 },
          { "\pButton 12", 128, 0, 0, kISpElementKind_Button, kISpElementLabel_Btn_Select, 0, 0, 0, 0 },
          { "\pButton 13", 128, 0, 0, kISpElementKind_Button, kISpElementLabel_Btn_Select, 0, 0, 0, 0 },
          { "\pButton 14", 128, 0, 0, kISpElementKind_Button, kISpElementLabel_Btn_Select, 0, 0, 0, 0 },
          { "\pButton 15", 128, 0, 0, kISpElementKind_Button, kISpElementLabel_Btn_Select, 0, 0, 0, 0 },
          { "\pButton 16", 128, 0, 0, kISpElementKind_Button, kISpElementLabel_Btn_Select, 0, 0, 0, 0 },
          { "\pButton 17", 128, 0, 0, kISpElementKind_Button, kISpElementLabel_Btn_Select, 0, 0, 0, 0 },
          { "\pButton 18", 128, 0, 0, kISpElementKind_Button, kISpElementLabel_Btn_Select, 0, 0, 0, 0 },
          { "\pButton 19", 128, 0, 0, kISpElementKind_Button, kISpElementLabel_Btn_Select, 0, 0, 0, 0 },
          { "\pButton 20", 128, 0, 0, kISpElementKind_Button, kISpElementLabel_Btn_Select, 0, 0, 0, 0 },
          { "\pButton 21", 128, 0, 0, kISpElementKind_Button, kISpElementLabel_Btn_Select, 0, 0, 0, 0 },
          { "\pButton 22", 128, 0, 0, kISpElementKind_Button, kISpElementLabel_Btn_Select, 0, 0, 0, 0 },
          { "\pButton 23", 128, 0, 0, kISpElementKind_Button, kISpElementLabel_Btn_Select, 0, 0, 0, 0 },
          { "\pButton 24", 128, 0, 0, kISpElementKind_Button, kISpElementLabel_Btn_Select, 0, 0, 0, 0 },
          { "\pButton 25", 128, 0, 0, kISpElementKind_Button, kISpElementLabel_Btn_Select, 0, 0, 0, 0 },
          { "\pButton 26", 128, 0, 0, kISpElementKind_Button, kISpElementLabel_Btn_Select, 0, 0, 0, 0 },
          { "\pButton 27", 128, 0, 0, kISpElementKind_Button, kISpElementLabel_Btn_Select, 0, 0, 0, 0 },
          { "\pButton 28", 128, 0, 0, kISpElementKind_Button, kISpElementLabel_Btn_Select, 0, 0, 0, 0 },
          { "\pButton 29", 128, 0, 0, kISpElementKind_Button, kISpElementLabel_Btn_Select, 0, 0, 0, 0 },
          { "\pButton 30", 128, 0, 0, kISpElementKind_Button, kISpElementLabel_Btn_Select, 0, 0, 0, 0 },
          { "\pButton 31", 128, 0, 0, kISpElementKind_Button, kISpElementLabel_Btn_Select, 0, 0, 0, 0 },
        };

        memcpy( joy->pJoystick.isp_needs, temp_isp_needs, sizeof (temp_isp_needs ) );

        /* next two calls allow keyboard and mouse to emulate other input
         * devices (gamepads, joysticks, etc)
         */
        /*
          err = ISpDevices_ActivateClass ( kISpDeviceClass_Keyboard );
          ISP_CHECK_ERR(err)

          err = ISpDevices_ActivateClass ( kISpDeviceClass_Mouse );
          ISP_CHECK_ERR(err)
        */

        err = ISpElement_NewVirtualFromNeeds( ISP_NUM_NEEDS,
                                              joy->pJoystick.isp_needs, joy->pJoystick.isp_elem,
                                              0 );
        ISP_CHECK_ERR( err )

        err = ISpInit( ISP_NUM_NEEDS, joy->pJoystick.isp_needs, joy->pJoystick.isp_elem,
                       'freeglut', nil, 0, 128, 0 );
        ISP_CHECK_ERR( err )

        joy->num_buttons = ISP_NUM_NEEDS - ISP_NUM_AXIS;
        joy->num_axes    = ISP_NUM_AXIS;

        for( i = 0; i < joy->num_axes; i++ )
        {
            joy->dead_band[ i ] = 0;
            joy->saturate [ i ] = 1;
            joy->center   [ i ] = kISpAxisMiddle;
            joy->max      [ i ] = kISpAxisMaximum;
            joy->min      [ i ] = kISpAxisMinimum;
        }

        joy->error = GL_FALSE;
    }
    else
        joy->num_buttons = joy->num_axes = 0;
}

void fgPlatformJoystickInit( SFG_Joystick *fgJoystick[], int ident )
{
    fgJoystick[ ident ]->id = ident;
    snprintf( fgJoystick[ ident ]->pJoystick.fname, sizeof(fgJoystick[ ident ]->pJoystick.fname), "/dev/js%d", ident ); /* FIXME */
    fgJoystick[ ident ]->error = GL_FALSE;
}

void fgPlatformJoystickClose ( int ident )
{
    ISpSuspend( );
    ISpStop( );
    ISpShutdown( );
}
#endif

#if TARGET_HOST_MAC_OSX
void fgPlatformJoystickRawRead( SFG_Joystick* joy, int* buttons, float* axes )
{
    int i;

    if ( buttons != NULL )
    {
        *buttons = 0;

        for ( i = 0; i < joy->num_buttons; i++ )
        {
            IOHIDEventStruct hidEvent;
            (*(joy->pJoystick.hidDev))->getElementValue ( joy->pJoystick.hidDev, joy->pJoystick.buttonCookies[i], &hidEvent );
            if ( hidEvent.value )
                *buttons |= 1 << i;
        }
    }

    if ( axes != NULL )
    {
        for ( i = 0; i < joy->num_axes; i++ )
        {
            IOHIDEventStruct hidEvent;
            (*(joy->pJoystick.hidDev))->getElementValue ( joy->pJoystick.hidDev, joy->pJoystick.axisCookies[i], &hidEvent );
            axes[i] = hidEvent.value;
        }
    }
}

void fgPlatformJoystickOpen( SFG_Joystick* joy )
{
    IOReturn rv;
    SInt32 score;
    IOCFPlugInInterface **plugin;

    HRESULT pluginResult;

    CFDictionaryRef props;
    CFTypeRef topLevelElement;

    if( joy->id >= numDevices )
    {
        fgWarning( "device index out of range in fgJoystickOpen()" );
        return;
    }

    /* create device interface */
    rv = IOCreatePlugInInterfaceForService( ioDevices[ joy->id ],
                                            kIOHIDDeviceUserClientTypeID,
                                            kIOCFPlugInInterfaceID,
                                            &plugin, &score );

    if( rv != kIOReturnSuccess )
    {
        fgWarning( "error creating plugin for io device" );
        return;
    }

    pluginResult = ( *plugin )->QueryInterface(
        plugin,
        CFUUIDGetUUIDBytes(kIOHIDDeviceInterfaceID),
        &( LPVOID )joy->pJoystick.hidDev
    );

    if( pluginResult != S_OK )
        fgWarning ( "QI-ing IO plugin to HID Device interface failed" );

    ( *plugin )->Release( plugin ); /* don't leak a ref */
    if( joy->pJoystick.hidDev == NULL )
        return;

    /* store the interface in this instance */
    rv = ( *( joy->pJoystick.hidDev ) )->open( joy->pJoystick.hidDev, 0 );
    if( rv != kIOReturnSuccess )
    {
        fgWarning( "error opening device interface");
        return;
    }

    props = getCFProperties( ioDevices[ joy->id ] );

    /* recursively enumerate all the bits */
    CFTypeRef topLevelElement =
        CFDictionaryGetValue( props, CFSTR( kIOHIDElementKey ) );
    enumerateElements( topLevelElement );

    CFRelease( props );
}

void fgPlatformJoystickInit( SFG_Joystick *fgJoystick[], int ident )
{
    fgJoystick[ ident ]->id = ident;
    fgJoystick[ ident ]->error = GL_FALSE;
    fgJoystick[ ident ]->num_axes = 0;
    fgJoystick[ ident ]->num_buttons = 0;

    if( numDevices < 0 )
    {
        /* do first-time init (since we can't over-ride jsInit, hmm */
        numDevices = 0;

        mach_port_t masterPort;
        IOReturn rv = IOMasterPort( bootstrap_port, &masterPort );
        if( rv != kIOReturnSuccess )
        {
            fgWarning( "error getting master Mach port" );
            return;
        }
        fghJoystickFindDevices( masterPort );
    }

    if ( ident >= numDevices )
    {
        fgJoystick[ ident ]->error = GL_TRUE;
        return;
    }

    /* get the name now too */
    CFDictionaryRef properties = getCFProperties( ioDevices[ ident ] );
    CFTypeRef ref = CFDictionaryGetValue( properties,
                                          CFSTR( kIOHIDProductKey ) );
    if (!ref)
        ref = CFDictionaryGetValue(properties, CFSTR( "USB Product Name" ) );

    if( !ref ||
        !CFStringGetCString( ( CFStringRef )ref, name, 128,
                             CFStringGetSystemEncoding( ) ) )
    {
        fgWarning( "error getting device name" );
        name[ 0 ] = '\0';
    }
}

void fgPlatformJoystickClose ( int ident )
{
    ( *( fgJoystick[ ident ]->pJoystick.hidDev ) )->
        close( fgJoystick[ ident ]->pJoystick.hidDev );
}
#endif

static void fghJoystickOpen( SFG_Joystick* joy )
{
    /*
     * Default values (for no joystick -- each conditional will reset the
     * error flag)
     */
    joy->error = TRUE;
    joy->num_axes = joy->num_buttons = 0;
    joy->name[ 0 ] = '\0';

    fgPlatformJoystickOpen ( joy );

}

/*
 * This function replaces the constructor method in the JS library.
 */
static void fghJoystickInit( int ident )
{
    if( ident >= MAX_NUM_JOYSTICKS )
      fgError( "Too large a joystick number: %d", ident );

    if( fgJoystick[ ident ] )
        fgError( "illegal attempt to initialize joystick device again" );

    fgJoystick[ ident ] =
        ( SFG_Joystick * )calloc( sizeof( SFG_Joystick ), 1 );

    /* Set defaults */
    fgJoystick[ ident ]->num_axes = fgJoystick[ ident ]->num_buttons = 0;
    fgJoystick[ ident ]->error = GL_TRUE;

    fgPlatformJoystickInit( fgJoystick, ident );

    fghJoystickOpen( fgJoystick[ ident  ] );
}

/*
 * Try initializing all the joysticks (well, both of them)
 */
void fgInitialiseJoysticks ( void )
{
    if( !fgState.JoysticksInitialised )
    {
        int ident ;
        for ( ident = 0; ident < MAX_NUM_JOYSTICKS; ident++ )
            fghJoystickInit( ident );

        fgState.JoysticksInitialised = GL_TRUE;
    }
}

void fgJoystickClose( void )
{
    int ident ;
    for( ident = 0; ident < MAX_NUM_JOYSTICKS; ident++ )
    {
        if( fgJoystick[ ident ] )
        {
            fgPlatformJoystickClose ( ident );

            free( fgJoystick[ ident ] );
            fgJoystick[ ident ] = NULL;
            /* show joystick has been deinitialized */
        }
    }
}

/*
 * Polls the joystick and executes the joystick callback hooked to the
 * window specified in the function's parameter:
 */
void fgJoystickPollWindow( SFG_Window* window )
{
    float axes[ _JS_MAX_AXES ];
    int buttons;
    int ident;

    freeglut_return_if_fail( window );
    freeglut_return_if_fail( FETCH_WCB( *window, Joystick ) );

    for( ident = 0; ident < MAX_NUM_JOYSTICKS; ident++ )
    {
        if( fgJoystick[ident] )
        {
            fghJoystickRead( fgJoystick[ident], &buttons, axes );

            if( !fgJoystick[ident]->error )
                INVOKE_WCB( *window, Joystick,
                            ( buttons,
                              (int) ( axes[ 0 ] * 1000.0f ),
                              (int) ( axes[ 1 ] * 1000.0f ),
                              (int) ( axes[ 2 ] * 1000.0f ) )
                );
        }
    }
}

/*
 * Implementation for glutDeviceGet(GLUT_HAS_JOYSTICK)
 */
int fgJoystickDetect( void )
{
    int ident;

    fgInitialiseJoysticks ();

    if ( !fgState.JoysticksInitialised )
        return 0;

    for( ident=0; ident<MAX_NUM_JOYSTICKS; ident++ )
        if( fgJoystick[ident] && !fgJoystick[ident]->error )
            return 1;

    return 0;
}

/*
 * Joystick information, setup and execution functions
 */

/*
 * Forces the joystick callback to be executed
 */
void FGAPIENTRY glutForceJoystickFunc( void )
{
    FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutForceJoystickFunc" );
#if !defined(_WIN32_WCE)
    freeglut_return_if_fail( fgStructure.CurrentWindow != NULL );
    freeglut_return_if_fail( FETCH_WCB( *( fgStructure.CurrentWindow ), Joystick ) );
    fgJoystickPollWindow( fgStructure.CurrentWindow );
#endif /* !defined(_WIN32_WCE) */
}
int  glutJoystickGetNumAxes( int ident )
{
    FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutJoystickGetNumAxes" );
    return fgJoystick[ ident ]->num_axes;
}
int  glutJoystickGetNumButtons( int ident )
{
    FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutJoystickGetNumButtons" );
    return fgJoystick[ ident ]->num_buttons;
}
int  glutJoystickNotWorking( int ident )
{
    FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutJoystickNotWorking" );
    return fgJoystick[ ident ]->error;
}

float glutJoystickGetDeadBand( int ident, int axis )
{
    FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutJoystickGetDeadBand" );
    return fgJoystick[ ident ]->dead_band [ axis ];
}
void  glutJoystickSetDeadBand( int ident, int axis, float db )
{
    FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutJoystickSetDeadBand" );
    fgJoystick[ ident ]->dead_band[ axis ] = db;
}

float glutJoystickGetSaturation( int ident, int axis )
{
    FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutJoystickGetSaturation" );
    return fgJoystick[ ident ]->saturate[ axis ];
}
void  glutJoystickSetSaturation( int ident, int axis, float st )
{
    FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutJoystickSetSaturation" );
    fgJoystick[ ident ]->saturate [ axis ] = st;
}

void glutJoystickSetMinRange( int ident, float *axes )
{
    FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutJoystickSetMinRange" );
    memcpy( fgJoystick[ ident ]->min, axes,
            fgJoystick[ ident ]->num_axes * sizeof( float ) );
}
void glutJoystickSetMaxRange( int ident, float *axes )
{
    FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutJoystickSetMaxRange" );
    memcpy( fgJoystick[ ident ]->max, axes,
            fgJoystick[ ident ]->num_axes * sizeof( float ) );
}
void glutJoystickSetCenter( int ident, float *axes )
{
    FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutJoystickSetCenter" );
    memcpy( fgJoystick[ ident ]->center, axes,
            fgJoystick[ ident ]->num_axes * sizeof( float ) );
}

void glutJoystickGetMinRange( int ident, float *axes )
{
    FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutJoystickGetMinRange" );
    memcpy( axes, fgJoystick[ ident ]->min,
            fgJoystick[ ident ]->num_axes * sizeof( float ) );
}
void glutJoystickGetMaxRange( int ident, float *axes )
{
    FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutJoystickGetMaxRange" );
    memcpy( axes, fgJoystick[ ident ]->max,
            fgJoystick[ ident ]->num_axes * sizeof( float ) );
}
void glutJoystickGetCenter( int ident, float *axes )
{
    FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutJoystickGetCenter" );
    memcpy( axes, fgJoystick[ ident ]->center,
            fgJoystick[ ident ]->num_axes * sizeof( float ) );
}

/*** END OF FILE ***/


text:
package it.sad.sii.transit.sdk.model;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import it.bz.sii.common.DateUtils;
import it.bz.sii.common.conversions.DateTimeDeserializer;
import it.bz.sii.common.conversions.DateTimeSerializer;
import org.joda.time.DateTime;

import java.io.Serializable;

/**
 * Created by lconcli on 10/11/15.
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class Passage implements Serializable {
    private static final long serialVersionUID = 1L;

    public Passage() {
    }

    public Passage(String lineId, String runId, String comCode, String waypointId,
                   DateTime scheduledTime, DateTime estimatedTime,
                   Integer dueIn, String delay, Integer delayInSeconds,
                   String destinationDE, String destinationIT,
                   Long lastTxTime, String lastTxPoint) {
        this.lineId = lineId;
        this.runId = runId;
        this.comCode = comCode;
        this.waypointId = waypointId;
        this.scheduledTime = scheduledTime;
        this.estimatedTime = estimatedTime;
        this.dueIn = dueIn;
        this.delay = delay;
        this.delayInSeconds = delayInSeconds;
        this.destinationIT = destinationIT;
        this.destinationDE = destinationDE;
        this.lastTxTime = lastTxTime;
        this.lastTxPoint = lastTxPoint;
    }

    private String lineId;
    private String runId;
    private DateTime scheduledTime;
    private String waypointId;
    private String comCode;
    private DateTime estimatedTime;
    protected Integer delayInSeconds;
    private Integer dueIn;
    private String destinationDE;
    private String destinationIT;
    private long lastTxTime;
    private String lastTxPoint;
    private String delay;

    public String getKey() {
        return String.format("W%s-L%s-R%s-%d", waypointId, lineId, runId, scheduledTime.getSecondOfDay());
    }

    public String getLineId() {
        return lineId;
    }

    public String getRunId() {
        return runId;
    }

    @JsonSerialize(using = DateTimeSerializer.class)
    @JsonDeserialize(using = DateTimeDeserializer.class)
    public DateTime getScheduledTime() {
        return scheduledTime;
    }

    public String getWaypointId() {
        return waypointId;
    }

    public String getComCode() {
        return comCode;
    }

    @JsonSerialize(using = DateTimeSerializer.class)
    @JsonDeserialize(using = DateTimeDeserializer.class)
    public DateTime getEstimatedTime() {
        return estimatedTime;
    }

    public Integer getDelayInSeconds() {
        return delayInSeconds;
    }

    public Integer getDueIn() {
        return dueIn;
    }

    public String getDestinationDE() {
        return destinationDE;
    }

    public String getDestinationIT() {
        return destinationIT;
    }

    public long getLastTxTime() {
        return lastTxTime;
    }

    public String getLastTxPoint() {
        return lastTxPoint;
    }

    public String getDelay() {
        return delay;
    }

    @Override
    public String toString() {
        return "Transit{lineId=" + lineId + ", runId=" + runId + ", scheduledTime=" +
                DateUtils.printDateTime(getScheduledTime()) + ", " + "comCode=" + comCode + ", waypointId=" + waypointId +
                ", estimatedTime=" + DateUtils.printDateTime(getEstimatedTime()) + ", destinationDE=" + destinationDE +
                ", destinationIT=" + destinationIT + "}";
    }
}


text:
<?php

namespace PhpConsole\Silex;

use Silex\Application;
use Silex\ServiceProviderInterface;
use PhpConsole\Connector;
use PhpConsole\Helper;
use PhpConsole\Storage;
use PhpConsole\Handler;

/**
 * PHP Console Provider.
 */
class ServiceProvider implements ServiceProviderInterface {

	protected static $isInitialized;

	/** @var bool Is PHP Console server enabled */
	protected $isEnabled = true;
	/** @var string Path to PhpConsole classes directory */
	protected $phpConsolePathAlias = 'application.vendors.PhpConsole.src.PhpConsole';
	/** @var string Base path of all project sources to strip in errors source paths */
	protected $sourcesBasePath;
	/** @var string|null Server internal encoding */
	protected $serverEncoding;
	/** @var int|null Set headers size limit for your web-server. You can detect headers size limit by /PhpConsole/examples/utils/detect_headers_limit.php */
	protected $headersLimit;
	/** @var string|null Protect PHP Console connection by password */
	protected $password;
	/** @var bool Force connection by SSL for clients with PHP Console installed */
	protected $enableSslOnlyMode = false;
	/** @var array Set IP masks of clients that will be allowed to connect to PHP Console lie: array('192.168.*.*', '10.2.12*.*', '127.0.0.1') */
	protected $ipMasks = array();

	/** @var bool Enable errors handling */
	protected $handleErrors = true;
	/** @var bool Enable exceptions handling */
	protected $handleExceptions = true;

	/** @var int Maximum dumped vars array or object nested dump level */
	protected $dumperLevelLimit = 5;
	/** @var int Maximum dumped var same level array items or object properties number */
	protected $dumperItemsCountLimit = 100;
	/** @var int Maximum length of any string or dumped array item */
	protected $dumperItemSizeLimit = 50000;
	/** @var int Maximum approximate size of dumped vars result formatted in JSON */
	protected $dumperDumpSizeLimit = 500000;
	/** @var bool Convert callback items in dumper vars to (callback SomeClass::someMethod) strings */
	protected $dumperDetectCallbacks = true;
	/** @var bool Autodetect and append trace data to debug */
	protected $detectDumpTraceAndSource = false;

	/**
	 * @var bool Enable eval request to be handled by eval dispatcher. Must be called after all Connector configurations.
	 * $this->password is required to be set
	 * use $this->ipMasks & $this->enableSslOnlyMode for additional protection
	 */
	public $isEvalEnabled = false;

	/**
	 * Initializing errors handler as soon as possible
	 * @param Application $app
	 * @param Storage $storage Postponed response storage(except PhpConsole\Storage\Session)
	 * @param bool $handleErrors Enable errors handling
	 * @param bool $handleExceptions Enable exceptions handling
	 */
	public function __construct(Application $app, Storage $storage, $handleErrors = true, $handleExceptions = true) {
		$this->initPostponeStorage($storage);
		$this->initHandler($app, $handleErrors, $handleExceptions);
	}

	/**
	 * @return Connector
	 */
	public function getConnector() {
		return Connector::getInstance();
	}

	/**
	 * @return Handler
	 */
	public function getHandler() {
		return Handler::getInstance();
	}

	public function initHandler(Application $app, $handleErrors, $handleExceptions) {
		$handler = $this->getHandler();
		$handler->setHandleErrors($handleErrors);
		$handler->setHandleExceptions($handleExceptions);
		$handler->start();
		if($handleExceptions) {
			$app->error(function (\Exception $exception) use ($handler) {
				$handler->handleException($exception);
			});
		}
	}

	protected function initPostponeStorage(Storage $storage = null) {
		if($storage instanceof \PhpConsole\Storage\Session) {
			throw new \Exception('Unable to use PhpConsole\Storage\Session as PhpConsole storage interface because of problems with overridden $_SESSION handler in Silex');
		}
		Connector::setPostponeStorage($storage);
	}

	/**
	 * Registers services on the given app.
	 *
	 * This method should only be used to configure services and parameters.
	 * It should not get services.
	 *
	 * @param Application $app An Application instance
	 */
	public function register(Application $app) {
		$connector = $this->getConnector();
		$handler = $this->getHandler();

		Helper::register($connector, $handler);

		$app['php-console.connector'] = $connector;
		$app['php-console.handler'] = $handler;
		$app->error(function (\Exception $exception) {
		});
	}

	public function boot(Application $app) {
		if($app['php-console.settings']) {
			foreach($app['php-console.settings'] as $option => $value) {
				$this->setOption($option, $value);
			}
		}
		if($this->isEnabled && $this->getConnector()->isActiveClient()) {
			$this->initConnectorSettings();
		}
		self::$isInitialized = true;
	}

	public function setOption($property, $value) {
		if(self::$isInitialized) {
			throw new \Exception('Unable to set option. Service provider already booted.');
		}
		if(!property_exists($this, $property)) {
			throw new \Exception('Unknown property "' . $property . '" in php-console settings list. See ' . __CLASS__ . ' properties for list of available settings');
		}
		$this->$property = $value;
	}

	/**
	 * @throws \Exception
	 */
	protected function initConnectorSettings() {
		$connector = $this->getConnector();

		if($this->sourcesBasePath) {
			$connector->setSourcesBasePath($this->sourcesBasePath);
		}
		if($this->serverEncoding) {
			$connector->setServerEncoding($this->serverEncoding);
		}
		if($this->password) {
			$connector->setPassword($this->password);
		}
		if($this->enableSslOnlyMode) {
			$connector->enableSslOnlyMode();
		}
		if($this->ipMasks) {
			$connector->setAllowedIpMasks($this->ipMasks);
		}
		if($this->headersLimit) {
			$connector->setHeadersLimit($this->headersLimit);
		}

		if($this->detectDumpTraceAndSource) {
			$connector->getDebugDispatcher()->detectTraceAndSource = true;
		}

		$dumper = $connector->getDumper();
		$dumper->levelLimit = $this->dumperLevelLimit;
		$dumper->itemsCountLimit = $this->dumperItemsCountLimit;
		$dumper->itemSizeLimit = $this->dumperItemSizeLimit;
		$dumper->dumpSizeLimit = $this->dumperDumpSizeLimit;
		$dumper->detectCallbacks = $this->dumperDetectCallbacks;

		if($this->isEvalEnabled) {
			$connector->startEvalRequestsListener();
		}
	}
}


text:
Transductive Learning over the Product Graph

## Description
This piece of code implements the content-aware link prediction algorithm described in

> Liu, Hanxiao, and Yiming Yang. "Bipartite Edge Prediction via Transductive Learning over Product Graphs." Proceedings of the 32nd International Conference on Machine Learning (ICML). 2015.

The program is going to carry out transductive learning over the Cartesian product graph with the heat diffusion kernel, which gives the best average empirical performace.

## Usage
The program takes four files as its input:

A sparse graph G on the left and a sparse graph H on the right in the following format
```
vertexIn_G anotherVertexIn_G edgeStrength
```
Cross-graph links for training and testing
```
vertexIn_G vertexIn_H linkStrength
```
For example,
G could be the social network among the users
and H could be the graph of movie-movie similarity induced from the movie genres.
In this case, cross-graph links may correspond to user-movie ratings.

The program reads configurations specified in `*.ini`. The provided configuration file should be self-explanatory. Here is a sample pipeline for execution and evaluation:
```
make && ./train cfg.ini && python eval.py data/cmu/link.test.txt predict.txt
```

## Author
Hanxiao Liu, Carnegie Mellon University


text:
#include <stdio.h>
#include <stdlib.h>

unsigned int knapsack(int* weights, unsigned int* values, unsigned int num_items,
              int capacity, unsigned int cur_value);

void readFile(const char* file_name, int** weights, unsigned int** values, unsigned int* num_items, int* capacity){
	/*
		File is strucured as:
		capacity
		num_items
		weight1 value1
		weight2 value2
		weight3 value3
		...
	*/
	FILE* fptr;
	unsigned int i;

	fptr = fopen(file_name, "r");

	fscanf(fptr,"%d", capacity); //read capacity
	fscanf(fptr,"%d", num_items); //read capacity

	//make space
	*weights = (int*) malloc(*num_items * sizeof(int));
	*values = (unsigned int*) malloc(*num_items * sizeof(unsigned int));

	//read weights and values
	for(i = 0; i < *num_items; i++){
		fscanf(fptr, "%d", *weights + i);
		fscanf(fptr, "%u", *values + i);
	}

	//close file
	fclose(fptr);

}

int main(int argc, char **argv){
  int* weights;
  unsigned int* values;
  unsigned int num_items;
  int capacity;
  unsigned int max_value;

  if(argc == 2){
  	//readFile
  	readFile(argv[1], &weights, &values, &num_items, &capacity);

  	//find the max that we can carry
  	max_value = knapsack(weights, values, num_items, capacity, 0);
  	printf("%u\n", max_value); //display result

  	//free space malloced
  	free(weights);
  	free(values);
  } else{
  	printf("Usage: knapsack.out arg_file\n");
  }

  return 0;

 }//main