<commit_before>define([
	'jquery',
	'underscore',
	'backbone',
	'models/amf_base',
], function($, _, Backbone, AmfBaseModel) {

	return AmfBaseModel.extend({
		idAttribute: 'quest_id',

		amfphp_url_templates: {
			read:   "quests.getQuest",
			update: "quests.updateQuest",
			create: "quests.createQuest",
			delete: "quests.deleteQuest"
		},

		amfphp_url_attributes: [
			"game_id",
			"quest_id",
			"name",
			"description",
			"text_when_complete",
			"description_notification",
			"text_when_complete_notification",
			"active_media_id",
			"complete_media_id",
			"active_icon_media_id",
			"complete_icon_media_id",
			"go_function",
			"complete_go_function",
			"notif_go_function",
			"complete_notif_go_function",
			"full_screen_notify",
			"complete_full_screen_notify",
			"active_notif_show_dismiss",
			"complete_notif_show_dismiss",
			"sort_index"
		],

		defaults: {
			active_icon_media_id: 0
			active_media_id: 0
			active_notif_show_dismiss: 1
			active_notification_media_id: 0
			complete_full_screen_notify: 1
			complete_go_function: "NONE"
			complete_icon_media_id: 0
			complete_media_id: 0
			complete_notif_go_function: "NONE"
			complete_notif_show_dismiss: "1"
			complete_notification_media_id: 0
			description: ""
			description_notification: ""
			full_screen_notify: 1
			go_function: "NONE"
			name: "New Quest"
			notif_go_function: "NONE"
			sort_index: 0
			text_when_complete: ""
			text_when_complete_notification: ""
		}
	});
});
<commit_msg>Fixed syntax<commit_after>define([
	'jquery',
	'underscore',
	'backbone',
	'models/amf_base',
], function($, _, Backbone, AmfBaseModel) {

	return AmfBaseModel.extend({
		idAttribute: 'quest_id',

		amfphp_url_templates: {
			read:   "quests.getQuest",
			update: "quests.updateQuest",
			create: "quests.createQuest",
			delete: "quests.deleteQuest"
		},

		amfphp_url_attributes: [
			"game_id",
			"quest_id",
			"name",
			"description",
			"text_when_complete",
			"description_notification",
			"text_when_complete_notification",
			"active_media_id",
			"complete_media_id",
			"active_icon_media_id",
			"complete_icon_media_id",
			"go_function",
			"complete_go_function",
			"notif_go_function",
			"complete_notif_go_function",
			"full_screen_notify",
			"complete_full_screen_notify",
			"active_notif_show_dismiss",
			"complete_notif_show_dismiss",
			"sort_index"
		],

		defaults: {
			active_icon_media_id: 0,
			active_media_id: 0,
			active_notif_show_dismiss: 1,
			active_notification_media_id: 0,
			complete_full_screen_notify: 1,
			complete_go_function: "NONE",
			complete_icon_media_id: 0,
			complete_media_id: 0,
			complete_notif_go_function: "NONE",
			complete_notif_show_dismiss: "1",
			complete_notification_media_id: 0,
			description: "",
			description_notification: "",
			full_screen_notify: 1,
			go_function: "NONE",
			name: "New Quest",
			notif_go_function: "NONE",
			sort_index: 0,
			text_when_complete: "",
			text_when_complete_notification: ""
		}
	});
});
<|endoftext|>


<commit_before>graphOutputBinding = new Shiny.OutputBinding();
graphOutputBinding.find = function(scope) {
    return $(scope).find(".graph-output");
};

graphOutputBinding.renderValue = function(el, data) {
    initContainer(el);
    loadGraph(el, data);
}

Shiny.outputBindings.register(graphOutputBinding, "alserg.graphOutputBinding");

jsOutputBinding = new Shiny.OutputBinding();
jsOutputBinding.find = function(scope) {
    return $(scope).find(".js-output");
};

jsOutputBinding.renderValue = function(el, data) {
    eval(data);
}

Shiny.outputBindings.register(jsOutputBinding, "alserg.jsOutputBinding");

positiveFCScale = d3.scale.linear().clamp(true).domain([0,2]).range(["#cccccc","#ff0000"]);
negativeFCScale = d3.scale.linear().clamp(true).domain([0,-2]).range(["#cccccc","#00ff00"]);
function getColor(d) {
    if (d.log2FC === parseFloat(d.log2FC)) {
        if (d.log2FC >= 0) {
            return positiveFCScale(d.log2FC);
        } else {
            return negativeFCScale(d.log2FC);
        }
    }
    return "#00acad";
}

pvalScale = d3.scale.linear().clamp(true).domain([0, -100]).range([8, 20]);
function getSize(d) {
    if (d.logPval === parseFloat(d.logPval)) {
        return pvalScale(d.logPval);
    }
    return pvalScale(0);
}

function initContainer(container) {
    container.innerHTML = "";
    var width = $(container).width(),
        height = $(window).height();

    container.svg = d3.select(container).append("svg")
        .append("g");

    container.svg
        .append("rect")
        .attr("class", "overlay")
        .attr("width", "1000")
        .attr("height", "1000");

    function sizeChange() {
        var width = container.width(),
            height = width.height();
        d3.select("svg")
            .attr("width", width)
            .attr("height", height);
        d3.select("rect")
            .attr("width", width)
            .attr("height", height);
    }
    // $(container).resize(sizeChange);

    function zoomed() {
        container.svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
    }

    container.zoom = d3.behavior.zoom().scaleExtent([1/8, 8]).on("zoom", zoomed);

    container.svg = container.svg.call(container.zoom)
      .append("g");

}

$(".graph-output").each(function(i) {
    this.onload = function() {
        initContainer(this);
    };
})

if (typeof String.prototype.startsWith != 'function') {
  String.prototype.startsWith = function (str){
    return this.slice(0, str.length) == str;
  };
}

homeTab = "work"

$(document).ready(function() {
    var hash = document.location.hash;
    var prefix="#tab-";
    if (hash) {
        if (hash.startsWith(prefix)) {
            hash = hash.replace(prefix, "#");
        }
    } else {
        hash = "#" + homeTab;
    }
    document.location.hash = hash;
    $('.nav-tabs a[href='+hash.replace("#", prefix)+']').tab('show') ;

    // Change hash for page-reload
    $('.nav-tabs a').on('shown', function (e) {
        window.location.hash = e.target.hash.replace(prefix, "#");
    })
})

$(window).on("popstate", function() {
    var hash = document.location.hash;
    var prefix="#tab-";
    if (hash) {
        if (hash.startsWith(prefix)) {
            hash = hash.replace(prefix, "#");
        }
        $('.nav-tabs a[href='+hash.replace("#", prefix)+']').tab('show') ;
    } else {
        $('.nav-tabs a[href="#tab-'+homeTab+'"]').tab('show') ;

    }
})

window.onload = function() {

    // d3.select(window).on("resize", sizeChange);

    // sizeChange();

    $(".graph-output").each(function(i) { initContainer(this) })
    // initContainer($(container));

    // $('.help-popover').popover();
    $('.help-tooltip').tooltip({
        placement: "right",
        delay: { show: 0, hide: 0 }
    });
    $("#metMinusLogFDR").slider({
        from: 0,
        to: 12 * 4,
        step: 1,
        limits: false,
        scale: [ "1e-1", "1e-5", "1e-9", "1e-13" ],
        calculate: function(value) {
            return Math.pow(10, -1 - value / 4.).toExponential(2);
        },

        multiple: false,
        onstatechange: function(value) {
            $("#metFDR")[0].value = Math.pow(10, -value);
        },
        smooth: false
    });
    $("#geneMinusLogFDR").slider({
        from: 0,
        to: 12 * 4,
        step: 1,
        limits: false,
        scale: [ "1e-1", "1e-5", "1e-9", "1e-13" ],
        calculate: function(value) {
            return Math.pow(10, -1 - value / 4.).toExponential(2);
        },

        multiple: false,
        onstatechange: function(value) {
            $("#geneFDR")[0].value = Math.pow(10, -value);
        },
        smooth: false
    });

}

function loadGraph(container, graph) {

    var width = $(container).width(),
        height = $(container).height();

    container.zoo

    container.force = d3.layout.force()
        .nodes(graph.nodes)
        .links(graph.edges)
        .charge(-300)
        .linkDistance(100)
        .size([width, height])
        .start();

    container.drag = container.force.drag()
        .on("dragstart", function(d) { d3.event.sourceEvent.stopPropagation(); } );

    container.svg.text(null);

    var svg = container.svg;

    var link = svg.selectAll(".link")
        .data(graph.edges)
        .enter().append("line")
        .attr("class", "link")
        .style("stroke", getColor)
        .style("stroke-width", getSize)
        .style("stroke-dasharray", function(d) { if (d.rptype == "trans") return "5,5"; else return ""; });

    var edgepaths = svg.selectAll(".edgepath")
        .data(graph.edges)
        .enter()
        .append('path')
        .attr({'d': function(d) {return 'M '+d.source.x+' '+d.source.y+' L '+ d.target.x +' '+d.target.y},
               'class':'edgepath',
               'fill-opacity':0,
               'stroke-opacity':0,
               'fill':'blue',
               'stroke':'red',
               'id':function(d,i) {return 'edgepath'+i}})
        .style("pointer-events", "none");

    var edgelabels = svg.selectAll(".edgelabel")
        .data(graph.edges)
        .enter()
        .append('text')
        .style("pointer-events", "none")
        .attr('class', 'edgelabel')
        .style('fill', 'black')
        .style("font-size", getSize);

    edgelabels.append('textPath')
        .attr('xlink:href',function(d,i) {return '#edgepath'+i})
        .style("pointer-events", "none")
        .attr('text-anchor', 'middle')
        .attr('startOffset', '50%')
        .attr('alignment-baseline', 'central')
        .text(function(d,i){return d.label});

    var node = svg.selectAll(".node")
        .data(graph.nodes)
        .enter()
        .append("g")
        .attr("class", "node")
        .call(container.drag);

    node.append("circle")
        .attr("cx", 0)
        .attr("cy", 0)
        .attr("r", getSize)
        .style("fill", getColor);

    node.append("text")
        .attr("x", 0)
        .attr("dy", ".35em")
        .attr("text-anchor", "middle")
        .style("font-size", getSize)
        .text(function(d) { return d.label });

    container.force.on("tick", function() {
        link.attr("x1", function(d) { return d.source.x; })
            .attr("y1", function(d) { return d.source.y; })
            .attr("x2", function(d) { return d.target.x; })
            .attr("y2", function(d) { return d.target.y; });

        node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });

        edgepaths.attr('d', function(d) { var path='M '+d.source.x+' '+d.source.y+' L '+ d.target.x +' '+d.target.y;
                                           //console.log(d)
                                           return path});

        edgelabels.attr('transform',function(d,i){
            if (d.target.x<d.source.x){
                bbox = this.getBBox();
                rx = bbox.x+bbox.width/2;
                ry = bbox.y+bbox.height/2;
                return 'rotate(180 '+rx+' '+ry+')';
                }
            else {
                return 'rotate(0)';
                }
        });
    });
}

function showFastHeinzAndMWCS(shouldShow) {
    if (shouldShow) {
        $("option[value='fastHeinz']").removeAttr("disabled");
        $("option[value='mwcs']").removeAttr("disabled");
    } else {
        $("option[value='fastHeinz']").attr("disabled", "disabled");
        $("option[value='mwcs']").attr("disabled", "disabled");
        if ($("#solver").val() == "fastHeinz" ||
            $("#solver").val() == "mwcs") {
            $("#solver").val("heinz");
        }
    }
}

<commit_msg>fixed problem with height of the svg in firefox<commit_after>graphOutputBinding = new Shiny.OutputBinding();
graphOutputBinding.find = function(scope) {
    return $(scope).find(".graph-output");
};

graphOutputBinding.renderValue = function(el, data) {
    initContainer(el);
    loadGraph(el, data);
}

Shiny.outputBindings.register(graphOutputBinding, "alserg.graphOutputBinding");

jsOutputBinding = new Shiny.OutputBinding();
jsOutputBinding.find = function(scope) {
    return $(scope).find(".js-output");
};

jsOutputBinding.renderValue = function(el, data) {
    eval(data);
}

Shiny.outputBindings.register(jsOutputBinding, "alserg.jsOutputBinding");

positiveFCScale = d3.scale.linear().clamp(true).domain([0,2]).range(["#cccccc","#ff0000"]);
negativeFCScale = d3.scale.linear().clamp(true).domain([0,-2]).range(["#cccccc","#00ff00"]);
function getColor(d) {
    if (d.log2FC === parseFloat(d.log2FC)) {
        if (d.log2FC >= 0) {
            return positiveFCScale(d.log2FC);
        } else {
            return negativeFCScale(d.log2FC);
        }
    }
    return "#00acad";
}

pvalScale = d3.scale.linear().clamp(true).domain([0, -100]).range([8, 20]);
function getSize(d) {
    if (d.logPval === parseFloat(d.logPval)) {
        return pvalScale(d.logPval);
    }
    return pvalScale(0);
}

function initContainer(container) {
    container.innerHTML = "";
    var width = $(container).width(),
        height = $(window).height();

    container.svg = d3.select(container).append("svg")
        .attr("width", width)
        .attr("height", height)
        .append("g");

    container.svg
        .append("rect")
        .attr("class", "overlay")
        .attr("width", "1000")
        .attr("height", "1000");

    function sizeChange() {
        var width = container.width(),
            height = width.height();
        d3.select("svg")
            .attr("width", width)
            .attr("height", height);
        d3.select("rect")
            .attr("width", width)
            .attr("height", height);
    }
    // $(container).resize(sizeChange);

    function zoomed() {
        container.svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
    }

    container.zoom = d3.behavior.zoom().scaleExtent([1/8, 8]).on("zoom", zoomed);

    container.svg = container.svg.call(container.zoom)
      .append("g");

}

$(".graph-output").each(function(i) {
    this.onload = function() {
        initContainer(this);
    };
})

if (typeof String.prototype.startsWith != 'function') {
  String.prototype.startsWith = function (str){
    return this.slice(0, str.length) == str;
  };
}

homeTab = "work"

$(document).ready(function() {
    var hash = document.location.hash;
    var prefix="#tab-";
    if (hash) {
        if (hash.startsWith(prefix)) {
            hash = hash.replace(prefix, "#");
        }
    } else {
        hash = "#" + homeTab;
    }
    document.location.hash = hash;
    $('.nav-tabs a[href='+hash.replace("#", prefix)+']').tab('show') ;

    // Change hash for page-reload
    $('.nav-tabs a').on('shown', function (e) {
        window.location.hash = e.target.hash.replace(prefix, "#");
    })
})

$(window).on("popstate", function() {
    var hash = document.location.hash;
    var prefix="#tab-";
    if (hash) {
        if (hash.startsWith(prefix)) {
            hash = hash.replace(prefix, "#");
        }
        $('.nav-tabs a[href='+hash.replace("#", prefix)+']').tab('show') ;
    } else {
        $('.nav-tabs a[href="#tab-'+homeTab+'"]').tab('show') ;

    }
})

window.onload = function() {

    // d3.select(window).on("resize", sizeChange);

    // sizeChange();

    $(".graph-output").each(function(i) { initContainer(this) })
    // initContainer($(container));

    // $('.help-popover').popover();
    $('.help-tooltip').tooltip({
        placement: "right",
        delay: { show: 0, hide: 0 }
    });
    $("#metMinusLogFDR").slider({
        from: 0,
        to: 12 * 4,
        step: 1,
        limits: false,
        scale: [ "1e-1", "1e-5", "1e-9", "1e-13" ],
        calculate: function(value) {
            return Math.pow(10, -1 - value / 4.).toExponential(2);
        },

        multiple: false,
        onstatechange: function(value) {
            $("#metFDR")[0].value = Math.pow(10, -value);
        },
        smooth: false
    });
    $("#geneMinusLogFDR").slider({
        from: 0,
        to: 12 * 4,
        step: 1,
        limits: false,
        scale: [ "1e-1", "1e-5", "1e-9", "1e-13" ],
        calculate: function(value) {
            return Math.pow(10, -1 - value / 4.).toExponential(2);
        },

        multiple: false,
        onstatechange: function(value) {
            $("#geneFDR")[0].value = Math.pow(10, -value);
        },
        smooth: false
    });

}

function loadGraph(container, graph) {
    if (!("nodes" in graph) || !("edges" in graph)) {
        return;
    }

    var width = $(container).width(),
        height = $(container).height();

    container.zoo

    container.force = d3.layout.force()
        .nodes(graph.nodes)
        .links(graph.edges)
        .charge(-300)
        .linkDistance(100)
        .size([width, height])
        .start();

    container.drag = container.force.drag()
        .on("dragstart", function(d) { d3.event.sourceEvent.stopPropagation(); } );

    container.svg.text(null);

    var svg = container.svg;

    var link = svg.selectAll(".link")
        .data(graph.edges)
        .enter().append("line")
        .attr("class", "link")
        .style("stroke", getColor)
        .style("stroke-width", getSize)
        .style("stroke-dasharray", function(d) { if (d.rptype == "trans") return "5,5"; else return ""; });

    var edgepaths = svg.selectAll(".edgepath")
        .data(graph.edges)
        .enter()
        .append('path')
        .attr({'d': function(d) {return 'M '+d.source.x+' '+d.source.y+' L '+ d.target.x +' '+d.target.y},
               'class':'edgepath',
               'fill-opacity':0,
               'stroke-opacity':0,
               'fill':'blue',
               'stroke':'red',
               'id':function(d,i) {return 'edgepath'+i}})
        .style("pointer-events", "none");

    var edgelabels = svg.selectAll(".edgelabel")
        .data(graph.edges)
        .enter()
        .append('text')
        .style("pointer-events", "none")
        .attr('class', 'edgelabel')
        .style('fill', 'black')
        .style("font-size", getSize);

    edgelabels.append('textPath')
        .attr('xlink:href',function(d,i) {return '#edgepath'+i})
        .style("pointer-events", "none")
        .attr('text-anchor', 'middle')
        .attr('startOffset', '50%')
        .attr('alignment-baseline', 'central')
        .text(function(d,i){return d.label});

    var node = svg.selectAll(".node")
        .data(graph.nodes)
        .enter()
        .append("g")
        .attr("class", "node")
        .call(container.drag);

    node.append("circle")
        .attr("cx", 0)
        .attr("cy", 0)
        .attr("r", getSize)
        .style("fill", getColor);

    node.append("text")
        .attr("x", 0)
        .attr("dy", ".35em")
        .attr("text-anchor", "middle")
        .style("font-size", getSize)
        .text(function(d) { return d.label });

    container.force.on("tick", function() {
        link.attr("x1", function(d) { return d.source.x; })
            .attr("y1", function(d) { return d.source.y; })
            .attr("x2", function(d) { return d.target.x; })
            .attr("y2", function(d) { return d.target.y; });

        node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });

        edgepaths.attr('d', function(d) { var path='M '+d.source.x+' '+d.source.y+' L '+ d.target.x +' '+d.target.y;
                                           //console.log(d)
                                           return path});

        edgelabels.attr('transform',function(d,i){
            if (d.target.x<d.source.x){
                bbox = this.getBBox();
                rx = bbox.x+bbox.width/2;
                ry = bbox.y+bbox.height/2;
                return 'rotate(180 '+rx+' '+ry+')';
                }
            else {
                return 'rotate(0)';
                }
        });
    });
}

function showFastHeinzAndMWCS(shouldShow) {
    if (shouldShow) {
        $("option[value='fastHeinz']").removeAttr("disabled");
        $("option[value='mwcs']").removeAttr("disabled");
    } else {
        $("option[value='fastHeinz']").attr("disabled", "disabled");
        $("option[value='mwcs']").attr("disabled", "disabled");
        if ($("#solver").val() == "fastHeinz" ||
            $("#solver").val() == "mwcs") {
            $("#solver").val("heinz");
        }
    }
}

<|endoftext|>


<commit_before>var config = require('../config');

if (config.environment !== 'development')
  throw 'This script must only be run locally.';

if (__dirname !== '/Users/David/Projects/Blot/scripts')
  throw 'This script must only be run locally.';<commit_msg>moved dev folder<commit_after>var config = require('../config');

if (config.environment !== 'development')
  throw 'This script must only be run locally.';

if (__dirname !== '/Users/David/Projects/blot/scripts')
  throw 'This script must only be run locally.';<|endoftext|>


<commit_before>/*
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

const mime = require('browser-media-mime-type');
const {html} = require('common-tags');
const path = require('path');
const url = require('url');
const {imgix} = require('../filters/imgix');

const GCS_URL = 'https://storage.googleapis.com';

/**
 * @param {string} bucket GCP bucket name
 * @param {string} src Prefix for video src
 * @return {string} Video URL
 */
const generateSource = (bucket, src) => {
  const extname = path.extname(src);
  let type = mime(extname);
  if (type === 'video/quicktime') {
    type = 'video/mp4';
  }
  src = new url.URL(path.join(bucket, src), GCS_URL).href;
  return html`
    <source src="${src}" ${type ? `type="${type}"` : ''} />
  `.replace(/\n/g, '');
};

/**
 * @param {string} bucket GCP nucket name
 * @param {string} domain imgix domain
 * @returns {(args: import('types').VideoArgs) => string} Video shortcode.
 */
const Video = function (bucket, domain) {
  /**
   * @param {import('types').VideoArgs} args Named arguments
   * @returns {string}
   */
  const returnedFunction = function (args) {
    const checkHereIfError = `ERROR IN ${
      // @ts-ignore: `this` has type of `any`
      this.page ? this.page.inputPath : 'UNKNOWN'
    }`;

    if (typeof args.src === 'string') {
      args.src = [args.src];
    }

    if (args.src.length === 0) {
      throw new Error(`${checkHereIfError}: no src provided`);
    }

    const {
      autoplay,
      autoPictureInPicture,
      class: className,
      controls,
      disablePictureInPicture,
      height,
      id,
      loop,
      linkTo,
      muted,
      playsinline,
      poster,
      preload,
      src,
      width,
    } = args;

    let videoTag = html`<video
      ${autoplay ? 'autoplay' : ''}
      ${autoPictureInPicture ? 'autoPictureInPicture' : ''}
      ${className ? `class="${className}"` : ''}
      ${controls ? 'controls' : ''}
      ${disablePictureInPicture ? 'disablePictureInPicture' : ''}
      ${height ? `height="${height}"` : ''}
      ${id ? `id="${id}"` : ''}
      ${loop ? 'loop' : ''}
      ${muted || autoplay ? 'muted' : ''}
      ${playsinline ? 'playsinline' : ''}
      ${poster ? `poster="${imgix(domain)(poster)}"` : ''}
      ${preload ? `preload="${preload}"` : ''}
      ${width ? `width="${width}"` : ''}
    >
      ${src.map(s => generateSource(bucket, s))}
    </video>`;

    if (linkTo) {
      videoTag = html`<a
        href="${new url.URL(path.join(bucket, src[0]), GCS_URL).href}"
        >${videoTag}</a
      >`;
    }

    return videoTag.replace(/\n/g, '');
  };

  return returnedFunction;
};

module.exports = {Video};
<commit_msg>Add custom props for video width and height.<commit_after>/*
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

const mime = require('browser-media-mime-type');
const {html} = require('common-tags');
const path = require('path');
const url = require('url');
const {imgix} = require('../filters/imgix');

const GCS_URL = 'https://storage.googleapis.com';

/**
 * @param {string} bucket GCP bucket name
 * @param {string} src Prefix for video src
 * @return {string} Video URL
 */
const generateSource = (bucket, src) => {
  const extname = path.extname(src);
  let type = mime(extname);
  if (type === 'video/quicktime') {
    type = 'video/mp4';
  }
  src = new url.URL(path.join(bucket, src), GCS_URL).href;
  return html`
    <source src="${src}" ${type ? `type="${type}"` : ''} />
  `.replace(/\n/g, '');
};

/**
 * @param {string} bucket GCP nucket name
 * @param {string} domain imgix domain
 * @returns {(args: import('types').VideoArgs) => string} Video shortcode.
 */
const Video = function (bucket, domain) {
  /**
   * @param {import('types').VideoArgs} args Named arguments
   * @returns {string}
   */
  const returnedFunction = function (args) {
    const checkHereIfError = `ERROR IN ${
      // @ts-ignore: `this` has type of `any`
      this.page ? this.page.inputPath : 'UNKNOWN'
    }`;

    if (typeof args.src === 'string') {
      args.src = [args.src];
    }

    if (args.src.length === 0) {
      throw new Error(`${checkHereIfError}: no src provided`);
    }

    const {
      autoplay,
      autoPictureInPicture,
      class: className,
      controls,
      disablePictureInPicture,
      height,
      id,
      loop,
      linkTo,
      muted,
      playsinline,
      poster,
      preload,
      src,
      width,
    } = args;

    let videoTag = html`<video
      ${autoplay ? 'autoplay' : ''}
      ${autoPictureInPicture ? 'autoPictureInPicture' : ''}
      ${className ? `class="${className}"` : ''}
      ${controls ? 'controls' : ''}
      ${disablePictureInPicture ? 'disablePictureInPicture' : ''}
      ${height ? `height="${height}"` : ''}
      ${id ? `id="${id}"` : ''}
      ${loop ? 'loop' : ''}
      ${muted || autoplay ? 'muted' : ''}
      ${playsinline ? 'playsinline' : ''}
      ${poster ? `poster="${imgix(domain)(poster)}"` : ''}
      ${preload ? `preload="${preload}"` : ''}
      ${width ? `width="${width}"` : ''}
      ${
        // This allows the video dimensions to be used in
        // an aspect-ratio CSS rule.
        // This needs to be done manually because the solution standards folks
        // spec'd doesn't work for <video>.
        width !== undefined && height !== undefined
          ? `style="--vid-width: ${width}; --vid-height: ${height}"`
          : ''
      }
    >
      ${src.map(s => generateSource(bucket, s))}
    </video>`;

    if (linkTo) {
      videoTag = html`<a
        href="${new url.URL(path.join(bucket, src[0]), GCS_URL).href}"
        >${videoTag}</a
      >`;
    }

    return videoTag.replace(/\n/g, '');
  };

  return returnedFunction;
};

module.exports = {Video};
<|endoftext|>


<commit_before>import { TabNavigator } from 'react-navigation';

import HomeScreen from '../screens/HomeScreen';
import HistoryScreen from '../screens/HistoryScreen';
import SettingsScreen from '../screens/SettingsScreen';
import Colors from '../constants/Colors';

export default TabNavigator({
  Home: {
    screen: HomeScreen,
  },
  History: {
    screen: HistoryScreen,
  },
  Settings: {
    screen: SettingsScreen,
  },
}, {
  animationEnabled: true,
  tabBarPosition: 'bottom',
  tabBarOptions: {
    showLabel: false,
    showIcon: true,
    inactiveTintColor: Colors.greyColour,
    activeTintColor: Colors.mainTheme,
    pressColor: Colors.mainTheme,
    style: {
      backgroundColor: Colors.whiteColour,
    },
    indicatorStyle: {
      backgroundColor: Colors.mainTheme,
    },
  },
});
<commit_msg>#17 | Disable swipe to switch screens as it is causing weird behaviour with screen headers jumping around<commit_after>import { TabNavigator } from 'react-navigation';

import HomeScreen from '../screens/HomeScreen';
import HistoryScreen from '../screens/HistoryScreen';
import SettingsScreen from '../screens/SettingsScreen';
import Colors from '../constants/Colors';

export default TabNavigator({
  Home: {
    screen: HomeScreen,
  },
  History: {
    screen: HistoryScreen,
  },
  Settings: {
    screen: SettingsScreen,
  },
}, {
  animationEnabled: true,
  swipeEnabled: false,
  tabBarPosition: 'bottom',
  tabBarOptions: {
    showLabel: false,
    showIcon: true,
    inactiveTintColor: Colors.greyColour,
    activeTintColor: Colors.mainTheme,
    pressColor: Colors.mainTheme,
    style: {
      backgroundColor: Colors.whiteColour,
    },
    indicatorStyle: {
      backgroundColor: Colors.mainTheme,
    },
  },
});
<|endoftext|>


<commit_before>describe("app.Pages.Stream", function(){
  beforeEach(function(){
    app.setPreload("stream", [factory.post().attributes])
    this.page = new app.pages.Stream()
    this.post = this.page.model.items.models[0]
    expect(this.post).toBeTruthy()
  })

  describe("rendering", function(){
    beforeEach(function(){
      this.page.render()
    })

    context("clicking the content", function(){
      it("triggers frame interacted", function(){
        spyOn(this.post.interactions, "fetch").andReturn(new $.Deferred)
        this.page.$('.canvas-frame:first .content').click()
        expect(this.post.interactions.fetch).toHaveBeenCalled()
      })
    })
  })
});<commit_msg>backfill some stream.js specs<commit_after>describe("app.Pages.Stream", function(){
  beforeEach(function(){
    app.setPreload("stream", [factory.post().attributes])
    this.page = new app.pages.Stream()
    this.post = this.page.model.items.models[0]
    expect(this.post).toBeTruthy()
  })

  describe('postRenderTemplate', function(){
    it("sets the background-image of #header", function(){
      this.page.render()
      console.log(this.page.$('#header').css('background-image'))
      expect(this.page.$('#header').css('background-image')).toBeTruthy()
    })

    it('calls setUpHashChangeOnStreamLoad', function(){
      spyOn(this.page, 'setUpHashChangeOnStreamLoad')
      this.page.render();
      expect(this.page.setUpHashChangeOnStreamLoad).toHaveBeenCalled()
    })
  })

  describe("rendering", function(){
    beforeEach(function(){
      this.page.render()
    })

    context("clicking the content", function(){
      it("triggers frame interacted", function(){
        spyOn(this.post.interactions, "fetch").andReturn(new $.Deferred)
        this.page.$('.canvas-frame:first .content').click()
        expect(this.post.interactions.fetch).toHaveBeenCalled()
      })
    })
  })
});<|endoftext|>


<commit_before>define(function(require) {
    var $ = require('jquery');
    var IPython = require('base/js/namespace');
    var utils = require('base/js/utils');
    var _ = require('underscore');
    var moduleavail = null;
    var modulelist = null;

    var lmod_tab_html = $([
    '
',
    '
',
    '
',
    '      Currently loaded softwares',
    '
',
    '
',
    '      ',
    '         <button id="refresh_lmod_list" title="Refresh software list" class="btn btn-default btn-xs"></button>',
    '      ',
    '
',
    '
',
    '
',
    '     Place holder',
    '
',
    '
'
    ].join('\n'));

    var lmod_pane_html_tpl = _.template([
    '    <div class="panel panel-default" id="lmod_panel_<%= id %>">',
    '
',
    '        <a data-toggle="collapse" data-target="#lmod_collapse_<%= id %>" href="#">',
    '          <%= title %> ',
    '        ',
    '
',
    '      <div id="lmod_collapse_<%= id %>" class="collapse in">',
    '        <div class="panel-body" id="lmod_list_<%= id %>">',
    '
',
    '
',
    '
',
    ].join('\n'));

    function refresh_view() {
	$.when($.get('lmod/avail/', {}, null, "json"),
	       $.get('lmod/list/', {}, null, "json"))
	 .done(function(avail, list) {
		update_panes(avail[0]);
		update_checked(list[0]);
	});
    }

    function module_change(event) {
        var checkbox = event.target;
	$.ajax({
		url: (checkbox.checked ? 'lmod/load' : 'lmod/unload'),
		type: "POST",
		dataType: "json",
		data: {"module" : checkbox.id},
		success: refresh_view
	});
    }

    function update_panes(data) {
	    data_str = JSON.stringify(data);
	    if (moduleavail == data_str) {
                 return;
	    }
	    moduleavail = data_str;
	    $("#lmod_list").html("");
	    var i = 0;
	    for (var key in data) {
		    var pane = $(lmod_pane_html_tpl({"title": key, "id": i}));
		    $("#lmod_list").append(pane);
		    for (var j = 0; j < data[key].length; j++) {
              	        if ( j % 6 == 0) {
                            var row = $("
", { class : 'row' });
                        }

                        var container = $("
")

                        var checkbox = document.createElement('input');
                        checkbox.type = "checkbox";
                        checkbox.name = "module";
                        checkbox.value = data[key][j];
                        checkbox.id = data[key][j];
                        checkbox.onclick = module_change;

                        var label = document.createElement('label');
                        label.htmlFor = data[key][j];
                        label.appendChild(document.createTextNode(data[key][j]));

                        container.append(checkbox);
                        container.append(" ");
                        container.append(label);

                        row.append(container);
		        if ( j % 6 == 5 || j == data[key].length - 1) {
                            row.appendTo($("#lmod_list_" + i.toString()));
			}
                    }
		    i += 1;
	    }
    }

    function update_checked(data) {
	$("input[name='module']").prop('checked', false);
	var ids = $(data.map(function(obj){ return "input[id='" + obj + "']"; }).join(","));
	ids.prop('checked', true);
    }

    function load() {
        if (!IPython.notebook_list) return;
        $(".tab-content").append(lmod_tab_html);
        refresh_view()
        $("#tabs").append(
            $('
')
            .append(
                $('')
                .attr('href', '#lmod')
                .attr('data-toggle', 'tab')
                .text('Softwares')
                .click(function (e) {
                    window.history.pushState(null, null, '#lmod');
                })
            )
        );

    }
    return {
        load_ipython_extension: load
    };
});
<commit_msg>Fix lmod tab when tree is not working directory root.<commit_after>define(function(require) {
    var $ = require('jquery');
    var IPython = require('base/js/namespace');
    var base_url = IPython.notebook_list.base_url;
    var utils = require('base/js/utils');
    var _ = require('underscore');
    var moduleavail = null;
    var modulelist = null;

    var lmod_tab_html = $([
        '
',
        '
',
        '
',
        '      Currently loaded softwares',
        '
',
        '
',
        '      ',
        '         <button id="refresh_lmod_list" title="Refresh software list" class="btn btn-default btn-xs"></button>',
        '      ',
        '
',
        '
',
        '
',
        '     Place holder',
        '
',
        '
'
    ].join('\n'));

    var lmod_pane_html_tpl = _.template([
        '    <div class="panel panel-default" id="lmod_panel_<%= id %>">',
        '
',
        '        <a data-toggle="collapse" data-target="#lmod_collapse_<%= id %>" href="#">',
        '          <%= title %> ',
        '        ',
        '
',
        '      <div id="lmod_collapse_<%= id %>" class="collapse in">',
        '        <div class="panel-body" id="lmod_list_<%= id %>">',
        '
',
        '
',
        '
',
    ].join('\n'));

    function refresh_view() {
        $.when($.get(base_url + 'lmod/avail/', {}, null, "json"),
        $.get(base_url + 'lmod/list/', {}, null, "json"))
        .done(function(avail, list) {
            update_panes(avail[0]);
            update_checked(list[0]);
        });
    }

    function module_change(event) {
        var checkbox = event.target;
        $.ajax({
            url: base_url + (checkbox.checked ? 'lmod/load' : 'lmod/unload'),
            type: "POST",
            dataType: "json",
            data: {"module" : checkbox.id},
            success: refresh_view
        });
    }

    function update_panes(data) {
        data_str = JSON.stringify(data);
        if (moduleavail == data_str) {
            return;
        }
        moduleavail = data_str;
        $("#lmod_list").html("");
        var i = 0;
        for (var key in data) {
            var pane = $(lmod_pane_html_tpl({"title": key, "id": i}));
            $("#lmod_list").append(pane);
            for (var j = 0; j < data[key].length; j++) {
                if ( j % 6 == 0) {
                    var row = $("
", { class : 'row' });
                }

                var container = $("
")

                var checkbox = document.createElement('input');
                checkbox.type = "checkbox";
                checkbox.name = "module";
                checkbox.value = data[key][j];
                checkbox.id = data[key][j];
                checkbox.onclick = module_change;

                var label = document.createElement('label');
                label.htmlFor = data[key][j];
                label.appendChild(document.createTextNode(data[key][j]));

                container.append(checkbox);
                container.append(" ");
                container.append(label);

                row.append(container);
                if ( j % 6 == 5 || j == data[key].length - 1) {
                    row.appendTo($("#lmod_list_" + i.toString()));
                }
            }
            i += 1;
        }
    }

    function update_checked(data) {
        $("input[name='module']").prop('checked', false);
        var ids = $(data.map(function(obj){ return "input[id='" + obj + "']"; }).join(","));
        ids.prop('checked', true);
    }

    function load() {
        if (!IPython.notebook_list) return;
        $(".tab-content").append(lmod_tab_html);
        refresh_view()
        $("#tabs").append(
            $('
')
            .append(
                $('')
                .attr('href', '#lmod')
                .attr('data-toggle', 'tab')
                .text('Softwares')
                .click(function (e) {
                    window.history.pushState(null, null, '#lmod');
                })
            )
        );
    }
    return {
        load_ipython_extension: load
    };
});
<|endoftext|>


<commit_before>function startApp() {
    showHideMenuLinks();
    showHomeView();

    // Bind the navigation menu links
    $("#linkHome").click(showHomeView);
    $("#linkLogin").click(showLoginView);
    $("#linkRegister").click(showRegisterView);
    $("#linkListAds").click(listAdverts);
    $("#linkCreateAd").click(showCreateAdView);
    $("#linkLogout").click(logoutUser);

    // Bind the form submit buttons
    $("#buttonLoginUser").click(loginUser);
    $("#buttonRegisterUser").click(registerUser);
    $("#buttonCreateAd").click(createAdvert);
    $("#buttonEditAd").click(editAdvert);

    const kinveyBaseUrl = "https://mock.api.com/";
    const kinveyAppKey = "kid_rk";
    const kinveyAppSecret = "736804a668";

    function showView(viewName) {
        // Hide all views and show the selected view only
        $('main > section').hide();
        $('#' + viewName).show();
    }

    function showHideMenuLinks() {
        $("#linkHome").show();
        if (sessionStorage.getItem('authToken') === null) {
            // No logged in user
            $("#linkLogin").show();
            $("#linkRegister").show();
            $("#linkListAds").hide();
            $("#linkCreateAd").hide();
            $("#linkLogout").hide();
        } else {
            // We have logged in user
            $("#linkLogin").hide();
            $("#linkRegister").hide();
            $("#linkListAds").show();
            $("#linkCreateAd").show();
            $("#linkLogout").show();
        }
    }

    function showHomeView() {
        showView('viewHome');
    }

    function showLoginView() {
        showView('viewLogin');
        $('#formLogin').trigger('reset');
    }

    function showRegisterView() {
        $('#formRegister').trigger('reset');
        showView('viewRegister');
    }

    function showCreateAdView() {
        $('#formCreateAd').trigger('reset');
        showView('viewCreateAd');
    }

    // user/login
    function loginUser() {
        const kinveyLoginUrl = kinveyBaseUrl + "user/" + kinveyAppKey + "/login";
        const kinveyAuthHeaders = {
            'Authorization': "Basic " + btoa(kinveyAppKey + ":" + kinveyAppSecret),
        };
        let userData = {
            username: $('#formLogin input[name=username]').val(),
            password: $('#formLogin input[name=passwd]').val()
        };

        $.ajax({
            method: "POST",
            url: kinveyLoginUrl,
            headers: kinveyAuthHeaders,
            data: userData,
            success: loginSuccess
        });

        function loginSuccess(userInfo) {
            saveAuthInSession(userInfo);
            showHideMenuLinks();
            listAdverts();
        }
    }

    function saveAuthInSession(userInfo) {
        let userAuth = userInfo._kmd.authtoken;
        sessionStorage.setItem('authToken', userAuth);
        let userId = userInfo._id;
        sessionStorage.setItem('userId', userId);
    }

    // user/register
    function registerUser() {
        const kinveyRegisterUrl = kinveyBaseUrl + "user/" + kinveyAppKey + "/";
        const kinveyAuthHeaders = {
            'Authorization': "Basic " + btoa(kinveyAppKey + ":" + kinveyAppSecret),
        };

        let userData = {
            username: $('#formRegister input[name=username]').val(),
            password: $('#formRegister input[name=passwd]').val()
        };

        $.ajax({
            method: "POST",
            url: kinveyRegisterUrl,
            headers: kinveyAuthHeaders,
            data: userData,
            success: registerSuccess
        });

        function registerSuccess(userInfo) {
            console.log(userInfo);
            saveAuthInSession(userInfo);
            showHideMenuLinks();
            listAdverts();
        }
    }

    // user/logout
    function logoutUser() {
        sessionStorage.clear();
        $('#loggedInUser').text("");
        showHideMenuLinks();
        showHomeView();
    }

    // advertisement/all
    function listAdverts() {
        $('#ads').empty();
        showView('viewAds');

        const kinveyAdvertsUrl = kinveyBaseUrl + "appdata/" + kinveyAppKey + "/adverts";
        const kinveyAuthHeaders = {
            'Authorization': "Kinvey " + sessionStorage.getItem('authToken'),
        };
        $.ajax({
            method: "GET",
            url: kinveyAdvertsUrl,
            headers: kinveyAuthHeaders,
            success: loadAdvertsSuccess
        });

        function loadAdvertsSuccess(adverts) {
            if (adverts.length === 0) {
                $('#ads').text('No advertisements available.');
            } else {
                let advertsTable = $('
')
                    .append($('
').append(
                        'Title	',
                        'Publisher	',
                        'Date Published	',
                        'Price	',
                        'Actions	')
                    );

                for (let advert of adverts) {
                    let links = [];

                    if (advert._acl.creator == sessionStorage['userId']) {
                        let deleteLink = $(`<a data-id="${advert._id}" href="#">[Delete]</a>`)
                            .click(function() { deleteAdvert($(this).attr("data-id")) });
                        let editLink = $(`<a data-id="${advert._id}" href="#">[Edit]</a>`)
                            .click(function() { loadAdvertForEdit($(this).attr("data-id")) });
                        links = [deleteLink, ' ', editLink];
                    }

                    advertsTable.append($('
').append(
                        $('').text(advert.title),
                        $('').text(advert.publisher),
                        $('').text(advert.datePublished),
                        $('').text(advert.price),
                        $('').append(links)
                    ));
                }

                $('#ads').append(advertsTable);
            }
        }
    }

    // advertisement/create
    function createAdvert() {
        const kinveyAuthHeaders = {
            'Authorization': "Kinvey " + sessionStorage.getItem('authToken'),
        };

        const kinveyUserUrl =
            `${kinveyBaseUrl}user/${kinveyAppKey}/${sessionStorage.getItem('userId')}`;

        $.ajax({
            method: "GET",
            url: kinveyUserUrl,
            headers: kinveyAuthHeaders,
            success: afterPublisherRequest
        });

        function afterPublisherRequest(publisher) {
            let advertData = {
                title: $('#formCreateAd input[name=title]').val(),
                publisher: publisher.username,
                datePublished: $('#formCreateAd input[name=datePublished]').val(),
                price: Number($('#formCreateAd input[name=price]').val())
            };

            const kinveyAdvertsUrl = kinveyBaseUrl + "appdata/" + kinveyAppKey + "/adverts";
            $.ajax({
                method: "POST",
                url: kinveyAdvertsUrl,
                headers: kinveyAuthHeaders,
                data: advertData,
                success: createAdvertSuccess
            });

            function createAdvertSuccess(response) {
                listAdverts();
            }
        }
    }

    // advertisement/delete
    function deleteAdvert(advertId) {
        const kinveyBookUrl = kinveyBaseUrl + "appdata/" +
            kinveyAppKey + "/adverts/" + advertId;
        const kinveyAuthHeaders = {
            'Authorization': "Kinvey " + sessionStorage.getItem('authToken'),
        };

        $.ajax({
            method: "DELETE",
            url: kinveyBookUrl,
            headers: kinveyAuthHeaders,
            success: deleteBookSuccess
        });

        function deleteBookSuccess(response) {
            listAdverts();
        }
    }

    // advertisement/edit GET
    function loadAdvertForEdit(advertId) {
        const kinveyBookUrl = kinveyBaseUrl + "appdata/" +
            kinveyAppKey + "/adverts/" + advertId;
        const kinveyAuthHeaders = {
            'Authorization': "Kinvey " + sessionStorage.getItem('authToken'),
        };

        $.ajax({
            method: "GET",
            url: kinveyBookUrl,
            headers: kinveyAuthHeaders,
            success: loadAdvertForEditSuccess
        });

        function loadAdvertForEditSuccess(advert) {
            $('#formEditAd input[name=id]').val(advert._id);
            $('#formEditAd input[name=title]').val(advert.title);
            $('#formEditAd input[name=publisher]').val(advert.publisher);
            $('#formEditAd input[name=datePublished]').val(advert.datePublished);
            $('#formEditAd input[name=price]').val(advert.price);
            showView('viewEditAd');
        }
    }

    // advertisement/edit POST
    function editAdvert() {
        const kinveyAdvertUrl =  kinveyBaseUrl + "appdata/" + kinveyAppKey +
            "/adverts/" + $('#formEditAd input[name=id]').val();
        const kinveyAuthHeaders = {
            'Authorization': "Kinvey " + sessionStorage.getItem('authToken'),
        };

        let advertData = {
            title: $('#formEditAd input[name=title]').val(),
            publisher: $('#formEditAd input[name=publisher]').val(),
            datePublished: $('#formEditAd input[name=datePublished]').val(),
            price: $('#formEditAd input[name=price]').val()
        };

        $.ajax({
            method: "PUT",
            url: kinveyAdvertUrl,
            headers: kinveyAuthHeaders,
            data: advertData,
            success: editAdvertSuccess
        });

        function editAdvertSuccess(response) {
            listAdverts();
        }
    }
}<commit_msg>6.2 Detailed View add function in advertisement/all<commit_after>function startApp() {
    showHideMenuLinks();
    showHomeView();

    // Bind the navigation menu links
    $("#linkHome").click(showHomeView);
    $("#linkLogin").click(showLoginView);
    $("#linkRegister").click(showRegisterView);
    $("#linkListAds").click(listAdverts);
    $("#linkCreateAd").click(showCreateAdView);
    $("#linkLogout").click(logoutUser);

    // Bind the form submit buttons
    $("#buttonLoginUser").click(loginUser);
    $("#buttonRegisterUser").click(registerUser);
    $("#buttonCreateAd").click(createAdvert);
    $("#buttonEditAd").click(editAdvert);

    const kinveyBaseUrl = "https://mock.api.com/";
    const kinveyAppKey = "kid_rk";
    const kinveyAppSecret = "736804a668";

    function showView(viewName) {
        // Hide all views and show the selected view only
        $('main > section').hide();
        $('#' + viewName).show();
    }

    function showHideMenuLinks() {
        $("#linkHome").show();
        if (sessionStorage.getItem('authToken') === null) {
            // No logged in user
            $("#linkLogin").show();
            $("#linkRegister").show();
            $("#linkListAds").hide();
            $("#linkCreateAd").hide();
            $("#linkLogout").hide();
        } else {
            // We have logged in user
            $("#linkLogin").hide();
            $("#linkRegister").hide();
            $("#linkListAds").show();
            $("#linkCreateAd").show();
            $("#linkLogout").show();
        }
    }

    function showHomeView() {
        showView('viewHome');
    }

    function showLoginView() {
        showView('viewLogin');
        $('#formLogin').trigger('reset');
    }

    function showRegisterView() {
        $('#formRegister').trigger('reset');
        showView('viewRegister');
    }

    function showCreateAdView() {
        $('#formCreateAd').trigger('reset');
        showView('viewCreateAd');
    }

    // user/login
    function loginUser() {
        const kinveyLoginUrl = kinveyBaseUrl + "user/" + kinveyAppKey + "/login";
        const kinveyAuthHeaders = {
            'Authorization': "Basic " + btoa(kinveyAppKey + ":" + kinveyAppSecret),
        };
        let userData = {
            username: $('#formLogin input[name=username]').val(),
            password: $('#formLogin input[name=passwd]').val()
        };

        $.ajax({
            method: "POST",
            url: kinveyLoginUrl,
            headers: kinveyAuthHeaders,
            data: userData,
            success: loginSuccess
        });

        function loginSuccess(userInfo) {
            saveAuthInSession(userInfo);
            showHideMenuLinks();
            listAdverts();
        }
    }

    function saveAuthInSession(userInfo) {
        let userAuth = userInfo._kmd.authtoken;
        sessionStorage.setItem('authToken', userAuth);
        let userId = userInfo._id;
        sessionStorage.setItem('userId', userId);
    }

    // user/register
    function registerUser() {
        const kinveyRegisterUrl = kinveyBaseUrl + "user/" + kinveyAppKey + "/";
        const kinveyAuthHeaders = {
            'Authorization': "Basic " + btoa(kinveyAppKey + ":" + kinveyAppSecret),
        };

        let userData = {
            username: $('#formRegister input[name=username]').val(),
            password: $('#formRegister input[name=passwd]').val()
        };

        $.ajax({
            method: "POST",
            url: kinveyRegisterUrl,
            headers: kinveyAuthHeaders,
            data: userData,
            success: registerSuccess
        });

        function registerSuccess(userInfo) {
            console.log(userInfo);
            saveAuthInSession(userInfo);
            showHideMenuLinks();
            listAdverts();
        }
    }

    // user/logout
    function logoutUser() {
        sessionStorage.clear();
        $('#loggedInUser').text("");
        showHideMenuLinks();
        showHomeView();
    }

    // advertisement/all
    function listAdverts() {
        $('#ads').empty();
        showView('viewAds');

        const kinveyAdvertsUrl = kinveyBaseUrl + "appdata/" + kinveyAppKey + "/adverts";
        const kinveyAuthHeaders = {
            'Authorization': "Kinvey " + sessionStorage.getItem('authToken'),
        };
        $.ajax({
            method: "GET",
            url: kinveyAdvertsUrl,
            headers: kinveyAuthHeaders,
            success: loadAdvertsSuccess
        });

        function loadAdvertsSuccess(adverts) {
            if (adverts.length === 0) {
                $('#ads').text('No advertisements available.');
            } else {
                let advertsTable = $('
')
                    .append($('
').append(
                        'Title	',
                        'Description	',
                        'Publisher	',
                        'Date Published	',
                        'Price	',
                        'Actions	')
                    );

                for (let advert of adverts) {
                    let readMoreLink = $(`<a data-id="${advert._id}" href="#">[Read More]</a>`)
                        .click(function() { displayAdvert($(this).attr("data-id")) });

                    advertsTable.append($('
').append(
                        $('').text(advert.title),
                        $('').text(advert.description),
                        $('').text(advert.publisher),
                        $('').text(advert.datePublished),
                        $('').text(advert.price),
                        $('').append(readMoreLink)
                    ));
                }

                $('#ads').append(advertsTable);
            }
        }
    }
            // Add function advert
    function displayAdvert(advertId){
        const kinveyAdvertUrl = kinveyBaseUrl + "appdata/" +
            kinveyAppKey + "/adverts/" + advertId;
        const kinveyAuthHeaders = {
            'Authorization': "Kinvey " + sessionStorage.getItem('authToken'),
        };

        $.ajax({
            method: "GET",
            url: kinveyAdvertUrl,
            headers: kinveyAuthHeaders,
            success: displayAdvertSuccess
        });

        $('#viewDetailsAd').empty();

        function displayAdvertSuccess(advert) {
            let advertInfo = $('
').append(
                $('').attr("src", advert.image),
                $('
'),
                $('').text('Title:'),
                $('
').text(advert.title),
                $('').text('Description:'),
                $('
').text(advert.description),
                $('').text('Publisher:'),
                $('
').text(advert.publisher),
                $('').text('Date:'),
                $('
').text(advert.datePublished));

            $('#viewDetailsAd').append(advertInfo);

            showView('viewDetailsAd');
        }
    }

    // advertisement/create
    function createAdvert() {
        const kinveyAuthHeaders = {
            'Authorization': "Kinvey " + sessionStorage.getItem('authToken'),
        };

        const kinveyUserUrl =
            `${kinveyBaseUrl}user/${kinveyAppKey}/${sessionStorage.getItem('userId')}`;

        $.ajax({
            method: "GET",
            url: kinveyUserUrl,
            headers: kinveyAuthHeaders,
            success: afterPublisherRequest
        });

        function afterPublisherRequest(publisher) {
            let advertData = {
                title: $('#formCreateAd input[name=title]').val(),
                publisher: publisher.username,
                datePublished: $('#formCreateAd input[name=datePublished]').val(),
                price: Number($('#formCreateAd input[name=price]').val())
            };

            const kinveyAdvertsUrl = kinveyBaseUrl + "appdata/" + kinveyAppKey + "/adverts";
            $.ajax({
                method: "POST",
                url: kinveyAdvertsUrl,
                headers: kinveyAuthHeaders,
                data: advertData,
                success: createAdvertSuccess
            });

            function createAdvertSuccess(response) {
                listAdverts();
            }
        }
    }

    // advertisement/delete
    function deleteAdvert(advertId) {
        const kinveyBookUrl = kinveyBaseUrl + "appdata/" +
            kinveyAppKey + "/adverts/" + advertId;
        const kinveyAuthHeaders = {
            'Authorization': "Kinvey " + sessionStorage.getItem('authToken'),
        };

        $.ajax({
            method: "DELETE",
            url: kinveyBookUrl,
            headers: kinveyAuthHeaders,
            success: deleteBookSuccess
        });

        function deleteBookSuccess(response) {
            listAdverts();
        }
    }

    // advertisement/edit GET
    function loadAdvertForEdit(advertId) {
        const kinveyBookUrl = kinveyBaseUrl + "appdata/" +
            kinveyAppKey + "/adverts/" + advertId;
        const kinveyAuthHeaders = {
            'Authorization': "Kinvey " + sessionStorage.getItem('authToken'),
        };

        $.ajax({
            method: "GET",
            url: kinveyBookUrl,
            headers: kinveyAuthHeaders,
            success: loadAdvertForEditSuccess
        });

        function loadAdvertForEditSuccess(advert) {
            $('#formEditAd input[name=id]').val(advert._id);
            $('#formEditAd input[name=title]').val(advert.title);
            $('#formEditAd input[name=publisher]').val(advert.publisher);
            $('#formEditAd input[name=datePublished]').val(advert.datePublished);
            $('#formEditAd input[name=price]').val(advert.price);
            showView('viewEditAd');
        }
    }

    // advertisement/edit POST
    function editAdvert() {
        const kinveyAdvertUrl =  kinveyBaseUrl + "appdata/" + kinveyAppKey +
            "/adverts/" + $('#formEditAd input[name=id]').val();
        const kinveyAuthHeaders = {
            'Authorization': "Kinvey " + sessionStorage.getItem('authToken'),
        };

        let advertData = {
            title: $('#formEditAd input[name=title]').val(),
            publisher: $('#formEditAd input[name=publisher]').val(),
            datePublished: $('#formEditAd input[name=datePublished]').val(),
            price: $('#formEditAd input[name=price]').val()
        };

        $.ajax({
            method: "PUT",
            url: kinveyAdvertUrl,
            headers: kinveyAuthHeaders,
            data: advertData,
            success: editAdvertSuccess
        });

        function editAdvertSuccess(response) {
            listAdverts();
        }
    }

}<|endoftext|>


<commit_before>// This is a Controller mixin for adding methods to manage middleware creation.

// __Dependencies__
var middleware = require('../middleware');

// __Private Module Members__

// Parse middleware
function factor (stage, howMany, verbs, middleware) {
  if (!stage) throw new Error('Must supply stage.');
  if (!middleware && !verbs && !howMany) throw new Error('Too few arguments.');

  if (!middleware && !verbs) {
    middleware = howMany;
    delete verbs;
    delete howMany;
  }

  if (!middleware) {
    middleware = verbs;
    verbs = howMany;
    delete howMany;
  }

  if (verbs) verbs = verbs.toLowerCase();

  // Prevent explicitly setting query-stage POST middleware.  Implicitly adding
  // this middleware is ignored.
  if (stage === 'query' && verbs && verbs.indexOf('post') !== -1) {
    throw new Error('Query stage not executed for POST.');
  }

  var factored = [];

  // Middleware function or array
  if (Array.isArray(middleware) || typeof middleware === 'function') {
    if (howMany !== 'collection') factored.push({ stage: stage, howMany: 'instance', verbs: verbs, middleware: middleware });
    if (howMany !== 'instance') factored.push({ stage: stage, howMany: 'collection', verbs: verbs, middleware: middleware });
    return factored;
  }

  if (howMany) throw new Error('Specified instance/collection twice.');
  if (verbs) throw new Error('Specified verbs twice.');

  // Middleware hash keyed on instance/collection, then verb
  Object.keys(middleware).forEach(function (howManyKey) {
    Object.keys(middleware[howManyKey]).map(function (verb) {
      factored.push({
        stage: stage,
        howMany: howManyKey,
        verbs: verb,
        middleware: middleware[howManyKey][verb]
      });
    });
  });

  return factored;
}

// __Module Definition__
var mixin = module.exports = function () {

  // __Private Instance Members__

  // Flags whether the custom middleware has been activated
  var activated = false;
  // A hash for storing user middleware
  var custom = {
    "request":
    { "instance": { "head": [], "get": [], "post": [], "put": [], "del": [] },
     "collection": { "head": [], "get": [], "post": [], "put": [], "del": [] }
    },
    "query":
    { "instance": { "head": [], "get": [], "post": [], "put": [], "del": [] },
     "collection": { "head": [], "get": [], "post": [], "put": [], "del": [] }
    },
    "documents":
    { "instance": { "head": [], "get": [], "post": [], "put": [], "del": [] },
     "collection": { "head": [], "get": [], "post": [], "put": [], "del": [] }
    }
  };

  // A method used to register user middleware to be activated during intialization.
  function register (stage, howMany, verbs, middleware) {
    if (activated) {
      throw new Error("Can't add middleware after the controller has been activated.");
    }

    factor(stage, howMany, verbs, middleware).forEach(function (definition) {
      var verbs = definition.verbs || 'head get post put del';
      verbs.split(' ').forEach(function (verb) {
        if (controller.get(verb) === false) return;
        custom[definition.stage][definition.howMany][verb] = custom[definition.stage][definition.howMany][verb].concat(definition.middleware);
      });
    });
  }

  // A method used to activate user middleware that was previously registered.
  function activate (stage, howMany, verbs, middleware) {
    if (activated) throw new Error("Can't activate middleware after the controller has been activated.");

    var that = this;

    factor(stage, howMany, verbs, middleware).forEach(function (definition) {
      var verbs = definition.verbs || 'head get post put del';

      verbs.split(' ').forEach(function (verb) {
        if (that.get(verb) === false) return;

        var path;

        if (definition.howMany === 'instance') path = that.get('basePathWithId');
        else if (definition.howMany === 'collection') path = that.get('basePath');
        else throw new Error('Unrecognized howMany.');

        that[verb](path, definition.middleware);
      });
    });
  }

  // __Public Instance Methods__

  // A method used to register request-stage middleware.
  this.request = function (howMany, verbs, middleware) {
    register('request', howMany, verbs, middleware);
    return this;
  };

  // A method used to register query-stage middleware.
  this.query = function (howMany, verbs, middleware) {
    register('query', howMany, verbs, middleware);
    return this;
  };

  // A method used to register document-stage middleware.
  this.documents = function (howMany, verbs, middleware) {
    register('documents', howMany, verbs, middleware);
    return this;
  };

  // A method used to intialize the controller and activate user middleware.  It
  // may be called multiple times, but will trigger intialization only once.
  this.activate = function () {
    if (activated) return this;

    // __Request-Stage Middleware__

    // Activate middleware that sets the Allow & Accept headers
    activate.call(this, 'request', [ middleware.headers.allow, middleware.headers.accept ]);
    // Activate middleware to set request.baucis.conditions for find/remove
    activate.call(this, 'request', 'collection', 'head get del', middleware.configure.conditions);
    // Next, activate the request-stage user middleware.
    activate.call(this, 'request', custom['request']);
    // Activate middleware to build the query (except for POST requests).
    activate.call(this,'request', middleware.query);

    // __Query-Stage Middleware__
    // The query will have been created (except for POST, which doesn't use a
    // find or remove query).

    // Activate middleware to handle controller and query options.
    activate.call(this, 'query', [ middleware.configure.controller, middleware.configure.query ]);

    // Delete any query-stage POST middleware that was added implicitly.
    custom.query.instance.post = [];
    custom.query.collection.post = [];

    // Activate user middleware for the query-stage
    activate.call(this, 'query', custom['query']);

    // Activate middleware to execute the query:

    // Get the count for HEAD requests.
    activate.call(this, 'query', 'head', middleware.exec.count);
    // Execute the find or remove query for GET and DELETE.
    activate.call(this, 'query', 'get del', middleware.exec.exec);
    // Create the documents for a POST request.
    activate.call(this, 'query', 'collection', 'post', middleware.exec.create);
    // Update the documents specified for a PUT request.
    activate.call(this, 'query', 'instance', 'put', middleware.exec.update);

    // Activate some middleware that will set the Link header when that feature
    // is enabled.  (This must come after exec or else the count is
    // returned for all subsequqent executions of the query.)
    if (this.get('relations') === true) {
      activate.call(this, 'query', 'instance', middleware.headers.link);
      activate.call(this, 'query', 'collection', middleware.headers.linkCollection);
    }

    // __Document-Stage Middleware__

    // Activate the middleware that sets the `Last-Modified` header when appropriate.
    activate.call(this, 'documents', middleware.documents.lastModified);
    // Activate the the document-stage user middleware.
    activate.call(this, 'documents', custom['documents']);
    // Activate the middleware that sends the resulting document(s) or count.
    activate.call(this, 'documents', middleware.documents.send);

    delete custom;
    activated = true;
    return this;
  };
};
<commit_msg>Spacing<commit_after>// This is a Controller mixin for adding methods to manage middleware creation.

// __Dependencies__
var middleware = require('../middleware');

// __Private Module Members__

// Parse middleware
function factor (stage, howMany, verbs, middleware) {
  if (!stage) throw new Error('Must supply stage.');
  if (!middleware && !verbs && !howMany) throw new Error('Too few arguments.');

  if (!middleware && !verbs) {
    middleware = howMany;
    delete verbs;
    delete howMany;
  }

  if (!middleware) {
    middleware = verbs;
    verbs = howMany;
    delete howMany;
  }

  if (verbs) verbs = verbs.toLowerCase();

  // Prevent explicitly setting query-stage POST middleware.  Implicitly adding
  // this middleware is ignored.
  if (stage === 'query' && verbs && verbs.indexOf('post') !== -1) {
    throw new Error('Query stage not executed for POST.');
  }

  var factored = [];

  // Middleware function or array
  if (Array.isArray(middleware) || typeof middleware === 'function') {
    if (howMany !== 'collection') factored.push({ stage: stage, howMany: 'instance', verbs: verbs, middleware: middleware });
    if (howMany !== 'instance') factored.push({ stage: stage, howMany: 'collection', verbs: verbs, middleware: middleware });
    return factored;
  }

  if (howMany) throw new Error('Specified instance/collection twice.');
  if (verbs) throw new Error('Specified verbs twice.');

  // Middleware hash keyed on instance/collection, then verb
  Object.keys(middleware).forEach(function (howManyKey) {
    Object.keys(middleware[howManyKey]).map(function (verb) {
      factored.push({
        stage: stage,
        howMany: howManyKey,
        verbs: verb,
        middleware: middleware[howManyKey][verb]
      });
    });
  });

  return factored;
}

// __Module Definition__
var mixin = module.exports = function () {

  // __Private Instance Members__

  // Flags whether the custom middleware has been activated
  var activated = false;
  // A hash for storing user middleware
  var custom = {
    "request":
    { "instance": { "head": [], "get": [], "post": [], "put": [], "del": [] },
     "collection": { "head": [], "get": [], "post": [], "put": [], "del": [] }
    },
    "query":
    { "instance": { "head": [], "get": [], "post": [], "put": [], "del": [] },
     "collection": { "head": [], "get": [], "post": [], "put": [], "del": [] }
    },
    "documents":
    { "instance": { "head": [], "get": [], "post": [], "put": [], "del": [] },
     "collection": { "head": [], "get": [], "post": [], "put": [], "del": [] }
    }
  };

  // A method used to register user middleware to be activated during intialization.
  function register (stage, howMany, verbs, middleware) {
    if (activated) {
      throw new Error("Can't add middleware after the controller has been activated.");
    }

    factor(stage, howMany, verbs, middleware).forEach(function (definition) {
      var verbs = definition.verbs || 'head get post put del';
      verbs.split(' ').forEach(function (verb) {
        if (controller.get(verb) === false) return;
        custom[definition.stage][definition.howMany][verb] = custom[definition.stage][definition.howMany][verb].concat(definition.middleware);
      });
    });
  }

  // A method used to activate user middleware that was previously registered.
  function activate (stage, howMany, verbs, middleware) {
    if (activated) throw new Error("Can't activate middleware after the controller has been activated.");

    var that = this;

    factor(stage, howMany, verbs, middleware).forEach(function (definition) {
      var verbs = definition.verbs || 'head get post put del';

      verbs.split(' ').forEach(function (verb) {
        if (that.get(verb) === false) return;

        var path;

        if (definition.howMany === 'instance') path = that.get('basePathWithId');
        else if (definition.howMany === 'collection') path = that.get('basePath');
        else throw new Error('Unrecognized howMany.');

        that[verb](path, definition.middleware);
      });
    });
  }

  // __Public Instance Methods__

  // A method used to register request-stage middleware.
  this.request = function (howMany, verbs, middleware) {
    register('request', howMany, verbs, middleware);
    return this;
  };

  // A method used to register query-stage middleware.
  this.query = function (howMany, verbs, middleware) {
    register('query', howMany, verbs, middleware);
    return this;
  };

  // A method used to register document-stage middleware.
  this.documents = function (howMany, verbs, middleware) {
    register('documents', howMany, verbs, middleware);
    return this;
  };

  // A method used to intialize the controller and activate user middleware.  It
  // may be called multiple times, but will trigger intialization only once.
  this.activate = function () {
    if (activated) return this;

    // __Request-Stage Middleware__

    // Activate middleware that sets the Allow & Accept headers
    activate.call(this, 'request', [ middleware.headers.allow, middleware.headers.accept ]);
    // Activate middleware to set request.baucis.conditions for find/remove
    activate.call(this, 'request', 'collection', 'head get del', middleware.configure.conditions);
    // Next, activate the request-stage user middleware.
    activate.call(this, 'request', custom['request']);
    // Activate middleware to build the query (except for POST requests).
    activate.call(this, 'request', middleware.query);

    // __Query-Stage Middleware__
    // The query will have been created (except for POST, which doesn't use a
    // find or remove query).

    // Activate middleware to handle controller and query options.
    activate.call(this, 'query', [ middleware.configure.controller, middleware.configure.query ]);

    // Delete any query-stage POST middleware that was added implicitly.
    custom.query.instance.post = [];
    custom.query.collection.post = [];

    // Activate user middleware for the query-stage
    activate.call(this, 'query', custom['query']);

    // Activate middleware to execute the query:

    // Get the count for HEAD requests.
    activate.call(this, 'query', 'head', middleware.exec.count);
    // Execute the find or remove query for GET and DELETE.
    activate.call(this, 'query', 'get del', middleware.exec.exec);
    // Create the documents for a POST request.
    activate.call(this, 'query', 'collection', 'post', middleware.exec.create);
    // Update the documents specified for a PUT request.
    activate.call(this, 'query', 'instance', 'put', middleware.exec.update);

    // Activate some middleware that will set the Link header when that feature
    // is enabled.  (This must come after exec or else the count is
    // returned for all subsequqent executions of the query.)
    if (this.get('relations') === true) {
      activate.call(this, 'query', 'instance', middleware.headers.link);
      activate.call(this, 'query', 'collection', middleware.headers.linkCollection);
    }

    // __Document-Stage Middleware__

    // Activate the middleware that sets the `Last-Modified` header when appropriate.
    activate.call(this, 'documents', middleware.documents.lastModified);
    // Activate the the document-stage user middleware.
    activate.call(this, 'documents', custom['documents']);
    // Activate the middleware that sends the resulting document(s) or count.
    activate.call(this, 'documents', middleware.documents.send);

    delete custom;
    activated = true;
    return this;
  };
};
<|endoftext|>


<commit_before>module.exports = function (robot) {

	robot.respond(/trello get token/i, function (res_r) {

		var slackMsgs = require('./slackMsgs.js');

		var key = process.env.HUBOT_TRELLO_KEY;

		let scope = 'read,write,account';
		let name = 'Hubot';
		let expr = '30days';
		let cb_method = '';
		let return_url = '';
		let url = `https://trello.com/1/authorize?expiration=${expr}&name=${name}&scope=${scope}&key=${key}&response_type=token`;
		//https://trello.com/1/authorize?expiration=never&name=SinglePurposeToken&key=51def9cb08cf171cd0970d8607ad8f97&callback_method=fragment&return_url=https://andreasbot.herokuapp.com/hubot/trello-token
		var msg = slackMsgs.basicMessage();

		msg.attachments[0].pretext = "Please get a token to authorize your Trello account";
		msg.attachments[0].title = "Trello Token";
		msg.attachments[0].title_link = url;
		msg.attachments[0].text = "Copy the token from the link above and run\n *trello add token <YOUR TOKEN>*";
		msg.attachments[0].footer = "Trello";
		msg.attachments[0].footer_icon = "https://d2k1ftgv7pobq7.cloudfront.net/meta/u/res/images/b428584f224c42e98d158dad366351b0/trello-mark-blue.png";
		res_r.send(msg);
	})

	robot.router.get('/hubot/trello-token', function (req, res) {
		// TODO: do something with the token
		robot.logger.info(req.body);
		robot.logger.info(`res body: ${res.body}`);
		robot.logger.info(`REQ: ${req}`);
		robot.logger.info(`RES: ${res}`);
		res.send(`
Token succesfuly received. You can now close the window.
\n<button type="button"
        onclick="window.open('', '_self', ''); window.close();">Close</button>\n
<button type="button" onclick="javascript:window.close()">Discard</button>
`);
	});

	robot.respond(/trello add token (.*)/i, function (res_r) {
		var token = res_r.match[1];
		//***IMPORTANT***
		// the .env assignment doesnt work with HEROKU!
		// must set up a heroku client and communicate through their api
		process.env['HUBOT_TRELLO_TOKEN'] = token;
	})
}<commit_msg>update trello token<commit_after>module.exports = function (robot) {

	robot.respond(/trello get token/i, function (res_r) {

		var slackMsgs = require('./slackMsgs.js');

		var key = process.env.HUBOT_TRELLO_KEY;

		let scope = 'read,write,account';
		let name = 'Hubot';
		let expr = '30days';
		let cb_method = '';
		let return_url = '';
		let url = `https://trello.com/1/authorize?expiration=${expr}&name=${name}&scope=${scope}&key=${key}&response_type=token`;
		//https://trello.com/1/authorize?expiration=never&name=SinglePurposeToken&key=51def9cb08cf171cd0970d8607ad8f97&callback_method=fragment&return_url=https://andreasbot.herokuapp.com/hubot/trello-token
		var msg = slackMsgs.basicMessage();

		msg.attachments[0].pretext = "Please get a token to authorize your Trello account";
		msg.attachments[0].title = "Trello Token";
		msg.attachments[0].title_link = url;
		msg.attachments[0].text = "Copy the token from the link above and run\n *trello add token <YOUR TOKEN>*";
		msg.attachments[0].footer = "Trello";
		msg.attachments[0].footer_icon = "https://d2k1ftgv7pobq7.cloudfront.net/meta/u/res/images/b428584f224c42e98d158dad366351b0/trello-mark-blue.png";
		res_r.send(msg);
	})

	robot.router.get('/hubot/trello-token', function (req, res) {
		// TODO: do something with the token
		robot.logger.info(res);
		res.send(`
Token succesfuly received. You can now close the window.
\n
		<input type="button" value="Close this window" onclick="self.close()">`);
		res.send(`<input type="button" value="Close this window" onclick="self.close()">`);
	});

	robot.respond(/trello add token (.*)/i, function (res_r) {
		var token = res_r.match[1];
		//***IMPORTANT***
		// the .env assignment doesnt work with HEROKU!
		// must set up a heroku client and communicate through their api
		process.env['HUBOT_TRELLO_TOKEN'] = token;
	})
}<|endoftext|>


<commit_before><commit_msg>upgrade mpd.js. closes #65<commit_after><|endoftext|>


<commit_before>// kludge until this is normal.
if (!process.EventEmitter.prototype.on) {
  process.EventEmitter.prototype.on = process.EventEmitter.prototype.addListener
}
var path = require("path")
if (!process.execPath) {
  process.execPath = path.join(process.installPrefix, "bin", "node")
}

var npm = exports
  , set = require("./lib/utils/set")
  , get = require("./lib/utils/get")
  , ini = require("./lib/utils/ini")
  , log = require("./lib/utils/log")
  , fs = require("fs")

npm.commands = {}
npm.SHOULD_EXIT = true

try {
  var j = JSON.parse(fs.readFileSync(path.join(__dirname, "package.json"))+"")
  npm.version = j.version
} catch (ex) {
  log(ex, "error reading version")
  npm.version = ex
}

var commandCache = {}
; [ "install"
  , "activate"
  , "deactivate"
  , "uninstall"
  , "build"
  , "link"
  , "publish"
  , "tag"
  , "adduser"
  , "config"
  , "help"
  , "cache"
  , "test"
  , "stop"
  , "start"
  , "restart"
  , "unpublish"
  , "list"
  , "ls"
  , "rm"
  ].forEach(function (c) {
    Object.defineProperty(npm.commands, c, { get : function () {
      c = c === "list" ? "ls"
        : c === "rm" ? "uninstall"
        : c
      if (c in commandCache) return commandCache[c]
      return commandCache[c] = require("./lib/"+c)
    }})
  })

// Local store for package data, so it won't have to be fetched/read more than
// once in a single pass.  TODO: cache this to disk somewhere when we're using
// the registry, to cut down on HTTP calls.
var registry = {}
npm.set = function (key, val) {
  if (typeof key === "object" && !val && key._id) {
    val = key
    key = key._id
  }
  return set(registry, key, val)
}
npm.get = function (key) { return get(registry, key) }

var path = require("path")
  , config = Object.create(ini.config)
npm.config =
  { get : function (key) {
      return ini.get(key, config)
    }
  , set : function (key, val) {
      if (typeof key === "object" && !val && key._id) {
        val = key
        key = key._id
      }
      return ini.set(key, val, config)
    }
  , del : function (key, val) {
      return ini.del(key, val, config)
    }
  }

// shorthand a few of these, because they're common
Object.defineProperty(npm, "root",
  { get: function () { return npm.config.get("root") }
  , set: function (newRoot) {
      TEMPFOLDER = npm.temp
      npm.config.set("root", newRoot)
    }
  })
Object.defineProperty(npm, "dir",
  { get: function () { return path.join(npm.root, ".npm") }
  , enumerable:true
  })
Object.defineProperty(npm, "cache",
  { get: function () { return path.join(npm.root, ".npm", ".cache") }
  , enumerable:true
  })
Object.defineProperty(npm, "tmp",
  { get: function () {
      log(path.join(npm.root, ".npm", ".tmp"), "temp folder")
      return path.join(npm.root, ".npm", ".tmp") }
  , enumerable:true
  })

var TEMPFOLDER = npm.tmp
process.on("exit", function () {
  ini.save()
  try {
    var files = fs.readdirSync(TEMPFOLDER)
  } catch (er) {
    return log(er, "Couldn't clean up tmp folder")
  }
  files.forEach(function (f) {
    try { fs.unlinkSync(TEMPFOLDER + "/" +f) }
    catch (er) { log(er, "Couldn't remove "+TEMPFOLDER+"/"+f) }
  })
})
<commit_msg>Logging the temp folder is just dumbface<commit_after>// kludge until this is normal.
if (!process.EventEmitter.prototype.on) {
  process.EventEmitter.prototype.on = process.EventEmitter.prototype.addListener
}
var path = require("path")
if (!process.execPath) {
  process.execPath = path.join(process.installPrefix, "bin", "node")
}

var npm = exports
  , set = require("./lib/utils/set")
  , get = require("./lib/utils/get")
  , ini = require("./lib/utils/ini")
  , log = require("./lib/utils/log")
  , fs = require("fs")

npm.commands = {}
npm.SHOULD_EXIT = true

try {
  var j = JSON.parse(fs.readFileSync(path.join(__dirname, "package.json"))+"")
  npm.version = j.version
} catch (ex) {
  log(ex, "error reading version")
  npm.version = ex
}

var commandCache = {}
; [ "install"
  , "activate"
  , "deactivate"
  , "uninstall"
  , "build"
  , "link"
  , "publish"
  , "tag"
  , "adduser"
  , "config"
  , "help"
  , "cache"
  , "test"
  , "stop"
  , "start"
  , "restart"
  , "unpublish"
  , "list"
  , "ls"
  , "rm"
  ].forEach(function (c) {
    Object.defineProperty(npm.commands, c, { get : function () {
      c = c === "list" ? "ls"
        : c === "rm" ? "uninstall"
        : c
      if (c in commandCache) return commandCache[c]
      return commandCache[c] = require("./lib/"+c)
    }})
  })

// Local store for package data, so it won't have to be fetched/read more than
// once in a single pass.  TODO: cache this to disk somewhere when we're using
// the registry, to cut down on HTTP calls.
var registry = {}
npm.set = function (key, val) {
  if (typeof key === "object" && !val && key._id) {
    val = key
    key = key._id
  }
  return set(registry, key, val)
}
npm.get = function (key) { return get(registry, key) }

var path = require("path")
  , config = Object.create(ini.config)
npm.config =
  { get : function (key) {
      return ini.get(key, config)
    }
  , set : function (key, val) {
      if (typeof key === "object" && !val && key._id) {
        val = key
        key = key._id
      }
      return ini.set(key, val, config)
    }
  , del : function (key, val) {
      return ini.del(key, val, config)
    }
  }

// shorthand a few of these, because they're common
Object.defineProperty(npm, "root",
  { get: function () { return npm.config.get("root") }
  , set: function (newRoot) {
      TEMPFOLDER = npm.temp
      npm.config.set("root", newRoot)
    }
  })
Object.defineProperty(npm, "dir",
  { get: function () { return path.join(npm.root, ".npm") }
  , enumerable:true
  })
Object.defineProperty(npm, "cache",
  { get: function () { return path.join(npm.root, ".npm", ".cache") }
  , enumerable:true
  })
Object.defineProperty(npm, "tmp",
  { get: function () { return path.join(npm.root, ".npm", ".tmp") }
  , enumerable:true
  })

var TEMPFOLDER = npm.tmp
process.on("exit", function () {
  ini.save()
  try {
    var files = fs.readdirSync(TEMPFOLDER)
  } catch (er) {
    return log(er, "Couldn't clean up tmp folder")
  }
  files.forEach(function (f) {
    try { fs.unlinkSync(TEMPFOLDER + "/" +f) }
    catch (er) { log(er, "Couldn't remove "+TEMPFOLDER+"/"+f) }
  })
})
<|endoftext|>