<commit_before>/*
 Copyright (c) 2013-2017 by Tawi Jordan - ๖ۣۜĐJ - ɴᴇᴏɴ - TFL

 Permission to use this software for any purpose without fee is hereby granted, provided
 that the above copyright notice and this permission notice appear in all copies.

 Permission to copy and/or edit this software or parts of it for any purpose is permitted,
 provided that the following points are followed.
 - The above copyright notice and this permission notice appear in all copies
 - Within two (2) days after modification is proven working, any modifications are send back
   to the original authors to be inspected with the goal of inclusion in the official software
 - Any edited version are only test versions and not permitted to be run as a final product
 - Any edited version aren't to be distributed
 - Any edited version have the prerelease version set to something that can be distinguished
   from a version used in the original software

 TERMS OF REPRODUCTION USE

 Failure to follow these terms will result in me getting very angry at you
 and having your software tweaked or removed if possible. Either way, you're
 still an idiot for not following such a basic rule.
 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE
 INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS
 BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
 RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
 OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

 * @Author:    Tawi Jordan - ๖ۣۜĐJ - ɴᴇᴏɴ - TFL (Member. on Plug.dj)

 * [NOTE]: THERE IS NOTHING HERE FOR YOU! COPYING ANY PART OF THIS SCRIPT AND USING "IT" or "AS" (yours)
 *         WELL SERIOUSLY GET YOU TO FACE THE CONSEQUENCES!
 */

var path = 'http://pastebin.com/raw.php?i=';

function message(contents) {
        var msg = '
Plugwoot™  ' + contents + '
';
        $('#chat-messages').append(msg);
}

var scriptFail = window.setTimeout(function() {
  message('Oops! An Error Occurred');
  //message('Sorry plugwoot alpha is updating! :(');
  }, 2000);

$.getScript(path + 'wwm3cyi8', function() {
  message("Alpha version "+ PlugStation.version +" is now running!");
  console.log("Plugwoot Alpha "+ PlugStation.version +" - Created by ๖ۣۜĐل - ɴᴇᴏɴ - TFL");
 window.clearTimeout(scriptFail);
 });
<commit_msg>Update Alpha.js<commit_after>/*
 Copyright (c) 2013-2017 by Tawi Jordan - ๖ۣۜĐJ - ɴᴇᴏɴ - TFL

 Permission to use this software for any purpose without fee is hereby granted, provided
 that the above copyright notice and this permission notice appear in all copies.

 Permission to copy and/or edit this software or parts of it for any purpose is permitted,
 provided that the following points are followed.
 - The above copyright notice and this permission notice appear in all copies
 - Within two (2) days after modification is proven working, any modifications are send back
   to the original authors to be inspected with the goal of inclusion in the official software
 - Any edited version are only test versions and not permitted to be run as a final product
 - Any edited version aren't to be distributed
 - Any edited version have the prerelease version set to something that can be distinguished
   from a version used in the original software

 TERMS OF REPRODUCTION USE

 Failure to follow these terms will result in me getting very angry at you
 and having your software tweaked or removed if possible. Either way, you're
 still an idiot for not following such a basic rule.
 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE
 INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS
 BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
 RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
 OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

 * @Author:    Tawi Jordan - ๖ۣۜĐJ - ɴᴇᴏɴ - TFL (Member. on Plug.dj)

 * [NOTE]: THERE IS NOTHING HERE FOR YOU! COPYING ANY PART OF THIS SCRIPT AND USING "IT" or "AS" (yours)
 *         WELL SERIOUSLY GET YOU TO FACE THE CONSEQUENCES!
 */

var path = 'http://pastebin.com/raw.php?i=';

function message(contents) {
        var msg = '
Plugwoot™  ' + contents + '
';
        $('#chat-messages').append(msg);
}

var scriptFail = window.setTimeout(function() {
  //message('Oops! An Error Occurred');
  message('Sorry plugwoot alpha is updating! :(');
  }, 2000);

$.getScript(path +/* 'wwm3cyi8',*/function() {
  //message("Alpha version "+ PlugStation.version +" is now running!");
  //console.log("Plugwoot Alpha "+ PlugStation.version +" - Created by ๖ۣۜĐل - ɴᴇᴏɴ - TFL");
 window.clearTimeout(scriptFail);
 });
<|endoftext|>


<commit_before>function initLineChart() {

  var maxTime = Number.MIN_VALUE;
  var minTime = Number.MAX_VALUE;
  var frameworkData = {};

  d3.json("/snapshots", function(error, json) {
    if (error) console.warn(error);

    json.forEach(function(datum) {

      var time = (new Date(datum.timestamp).getTime());

      maxTime = Math.max(time, maxTime);
      minTime = Math.min(time, minTime);

      var tally = JSON.parse(datum.tally);
      for (var t in tally) {
        frameworkData[t] = frameworkData[t] || [];
        frameworkData[t].push({
          sale: tally[t],
          year: time
        });
      }
    });

    var div = d3.select("#line-chart"),
        WIDTH = 500,
        HEIGHT = 350,
        vis = div.append("svg")
          .attr("viewBox", "0 0 " + WIDTH + " " + HEIGHT)
          .attr("width", "100%")
          .attr("height", "100%")
          .attr("preserveAspectRatio", "xMinYMin meet"),
        MARGINS = {
          top: 20,
          right: 20,
          bottom: 20,
          left: 50
        },
        xScale = d3.scale.linear().range([MARGINS.left, WIDTH - MARGINS.right]).domain([minTime, maxTime]),
        yScale = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([0, 1000]),
        xAxis = d3.svg.axis()
          .scale(xScale),
        yAxis = d3.svg.axis()
          .scale(yScale)
          .orient("left");

    vis.append("svg:g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")")
      .call(xAxis);
    vis.append("svg:g")
      .attr("class", "y axis")
      .attr("transform", "translate(" + (MARGINS.left) + ",0)")
      .call(yAxis);

    var lineGen = d3.svg.line()
          .x(function(d) {
            return xScale(d.year);
          })
          .y(function(d) {
            return yScale(d.sale);
          });
    // .interpolate("basis");

    for (var fw in frameworkData) {
      vis.append('svg:path')
        .attr('d', lineGen(frameworkData[fw]))
        .attr('stroke', frameworkColor[fw])
        .attr('stroke-width', 2)
        .attr('fill', 'none');
    }
  });
}
<commit_msg>making y scale dynamic re max value<commit_after>function initLineChart() {

  var maxTime = Number.MIN_VALUE;
  var minTime = Number.MAX_VALUE;
  var maxValue = Number.MIN_VALUE;
  var frameworkData = {};

  d3.json("/snapshots", function(error, json) {
    if (error) console.warn(error);

    json.forEach(function(datum) {

      var time = (new Date(datum.timestamp).getTime());

      maxTime = Math.max(time, maxTime);
      minTime = Math.min(time, minTime);

      var tally = JSON.parse(datum.tally);
      for (var t in tally) {
        frameworkData[t] = frameworkData[t] || [];
        frameworkData[t].push({
          value: tally[t],
          day: time
        });

        maxValue = Math.max(maxValue, tally[t]);

      }
    });

    var div = d3.select("#line-chart"),
        WIDTH = 500,
        HEIGHT = 350,
        vis = div.append("svg")
          .attr("viewBox", "0 0 " + WIDTH + " " + HEIGHT)
          .attr("width", "100%")
          .attr("height", "100%")
          .attr("preserveAspectRatio", "xMinYMin meet"),
        MARGINS = {
          top: 20,
          right: 20,
          bottom: 20,
          left: 50
        },
        xScale = d3.scale.linear().range([MARGINS.left, WIDTH - MARGINS.right]).domain([minTime, maxTime]),
        yScale = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([0, maxValue + 100]),
        xAxis = d3.svg.axis()
          .scale(xScale),
        yAxis = d3.svg.axis()
          .scale(yScale)
          .orient("left");

    vis.append("svg:g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")")
      .call(xAxis);
    vis.append("svg:g")
      .attr("class", "y axis")
      .attr("transform", "translate(" + (MARGINS.left) + ",0)")
      .call(yAxis);

    var lineGen = d3.svg.line()
          .x(function(d) {
            return xScale(d.day);
          })
          .y(function(d) {
            return yScale(d.value);
          });

    for (var fw in frameworkData) {
      vis.append('svg:path')
        .attr('d', lineGen(frameworkData[fw]))
        .attr('stroke', frameworkColor[fw])
        .attr('stroke-width', 2)
        .attr('fill', 'none');
    }
  });
}
<|endoftext|>


<commit_before>/*
   Copyright 2015 7thGrader
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at
       http://www.apache.org/licenses/LICENSE-2.0
*/

// TaxHeap for CraftySkyAPI
// ver 0.1.0a

// Please copy full code to API.js

var tax = 1; // Amount of tax
var taxtick = 1200; // Every configured ticks, Tax will be taken
var mca000003 = 0; // Do Not Edit!

function modTick()
{
mca000003 += 1;
if(mca000003 >= taxtick)
{
mca000003 = 0;
clientMessage("[TaxHeap]Tax Taken(" + monetaryUnit + tax + ")");
money -= tax;
}
}
<commit_msg>Update TaxHeap.js<commit_after>/*
   Copyright 2015 7thGrader
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at
       http://www.apache.org/licenses/LICENSE-2.0
*/

// TaxHeap for CraftySkyAPI
// ver 0.1.1a

// Please copy full code to API.js

var tax = 1; // Amount of tax
var taxtick = 1200; // Every configured ticks, Tax will be taken
var mca000003 = 0; // Do Not Edit!

function modTick()
{
mca000003 += 1;
if(mca000003 >= taxtick)
{
mca000003 = 0;
if(money-tax>=0)
{
clientMessage("[TaxHeap]Tax Taken(" + monetaryUnit + tax + ")");
money -= tax;
}
}
}
<|endoftext|>


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

localPath=process.argv[process.argv.length - 2];
sharedPath=process.argv[process.argv.length - 1];

chokidar.watch(
  localPath,
  { ignored: /[\/\\]\./, ignoreInitial: true}
).on('all', function(event, path) {
    utils.calcHash(path, function(error, sha1) {
      if (error != null) {
        if (error.code == 1) {
          console.log('missing file');
        }
      } else {
        sharedFile=path.replace(localPath, sharedPath);
        console.log(event, sharedFile, sha1);
      }
    });
});
<commit_msg>removed unused sharedPath variable<commit_after>var chokidar = require('chokidar');
var utils = require('./utils');

path=process.argv[process.argv.length - 1];

chokidar.watch(
  path,
  { ignored: /[\/\\]\./, ignoreInitial: true}
).on('all', function(event, path) {
    utils.calcHash(path, function(error, sha1) {
      if (error != null) {
        if (error.code == 1) {
          console.log('missing file');
        }
      } else {
        sharedFile=path.replace(path, '');
        console.log(event, sharedFile, sha1);
      }
    });
});
<|endoftext|>


<commit_before>/*
 * Tangram
 * Copyright 2010 Baidu Inc. All rights reserved.
 * @path:ui/carousel/Carousel.js
 * @author:linlingyu
 * @version:1.0.0
 * @date:2010-09-06
 */

///import baidu.dom.insertHTML;
///import baidu.dom.setStyles;
///import baidu.array.each;
///import baidu.dom.g;
///import baidu.dom.children;
///import baidu.dom.remove;
///import baidu.dom.addClass;
///import baidu.dom.removeClass;
///import baidu.lang.isNumber;
///import baidu.string.format;
///import baidu.ui.createUI;

/**
 * carousel滚动控件。
 * @class carousel类
 * @param  {Object}   [options]           carousel的参数选项
 * @config {HTMLElement}   target              存放控件的元素
 * @config {Array}    contentText         用于生成滚动的条目
 * @config {String}   orientation         排列方式，取值：horizontal（默认），vertical。
 * @config {String}   flip                滚动按钮方式，取值：item（一次滚动一个项），page（翻页滚动）。
 * @config {Number}   pageSize            一行显示几个item，默认值3。
 * @config {Boolean}  isCycle             是否循环滚动，默认值false。
 * @config {Boolean}  autoScroll          是否自动滚动。
 * @config {Boolean}  showButton          是否显示翻转按钮，默认值true。
 * @config {Number}   offsetWidth         用户自定义的滚动宽度
 * @config {Number}   offsetHeight        用户自定义的滚动高度
 * @config {Function} onload              初始化时的触发事件
 * @config {Function} onbeforescroll      开始滚动时的触发事件
 * @config {Function} onafterscroll       结束滚动时的触发事件
 * @config {Function} onprevitem          当跳到上一个滚动项时触发该事件
 * @config {Function} onnextitem          当跳到下一个滚动项时触发该事件
 * @config {Function} onprevpage          当跳到上一页时触发该事件
 * @config {Function} onnextPage          当跳到下一页时触发该事件
 * @config {Function} onitemclick         点击某个滚动项时的触发事件
 * @config {Function} onmouseover         当鼠标悬停在某个滚动项时的触发事件
 * @config {Function} onmouseout          当鼠标移开某个滚动项时的触发事件
 * @plugin autoScroll                     自动滚动
 * @plugin btn                            为跑马灯添加控制按钮插件
 * @plugin fx                             为跑马灯添加动画效果
 * @plugin scrollByItem                   单次滚动单个元素的模式
 * @plugin scrollByPage                   单次滚动一页的模式
 * @plugin table                          让跑马灯支持多行多列
 */

baidu.ui.Carousel = baidu.ui.createUI(

    function(opts){
    this.contentText = opts.contentText || [];  //数组或对象在prototype中定义时会造成新建对象共用数据
}).extend(
    /**
     *  @lends baidu.ui.carousel.Carousel.prototype
     */
{

    uiType : "carousel",        // ui控件的类型 **必须**
    orientation : "horizontal", //横竖向的排列方式，取值horizontal,vertical
    pageSize : 3,               //每页显示多少个item

    scrollIndex : -1,           //当前焦点滚动到的项索引

    totalCount : 0,             //总记录数
    itemCount : 0,              //用于创建item的自增数
    offsetWidth : 0,            //单个item的宽度
    offsetHeight : 0,       //单个item的高度

    axis : {
        horizontal : {offsetPos : "offsetLeft", offsetSize : "offsetWidth", scroll : "scrollLeft"},
        vertical : {offsetPos : "offsetTop", offsetSize : "offsetHeight", scroll:"scrollTop"}
    },//关于位置的换算

    tplDOM : "
#{content}
",

    tplItem : "
#{content}
",

    /**
     * 渲染carousel到指定的target容器中
     * @public
     * @param {HTMLElement} target table的父层容器
     */
    render : function(target){
        var me = this;
        baidu.dom.insertHTML(me.renderMain(target || me.target), "beforeEnd", me.getString());
        me.totalCount = me.contentText.length || 0;
        me._resize();
        me.dispatchEvent("onload");
    },

    /**
     * 根据item的尺寸运算可视区域的大小和滚动层的大小
     * @param {boolean} val true:第一次resize, false:一般的resize
     */
    _resize : function(){
        var me = this,
            offset_x = me.axis[me.orientation].offsetSize,//由pageSize决定长度的一方
            offset_y = me.axis["horizontal"==me.orientation ? "vertical" : "horizontal"].offsetSize,//直接设置成item长度的一方
            item = me.getItem(0);
        if(item && (me.getBody()[offset_x] < me.pageSize * item[offset_x] || me.getBody()[offset_y] < item[offset_y])){
            me.offsetWidth = me.offsetWidth || item.offsetWidth;
            me.offsetHeight = me.offsetHeight || item.offsetHeight;
            //这里设置container的宽度和高度让用户可以看到一个按照pageSize和orientation计算出来的固定介面
            baidu.dom.setStyles(me.getBody(), {
                width : me.offsetWidth * ("horizontal" == me.orientation ? me.pageSize : 1) + "px",
                height : me.offsetHeight * ("vertical" == me.orientation ? me.pageSize : 1) + "px"
            });
        }
        //这里运算scrollContainer的宽度是为了让item都能展开排成一行
        if("horizontal" == me.orientation){
            baidu.setStyles(me.getScrollContainer(), {width : me.offsetWidth * me.totalCount + "px"});
        }
    },

    /**
     * 生成滚动结构的html字符串代码
     * @private
     * @return {String} 生成html字符串
     */
    getString : function(){
        var me = this, itemStr = [], scrollStr;
        baidu.array.each(me.contentText, function(item){
            itemStr.push(baidu.format(me.tplItem, {
                id : me.getId("item" + me.itemCount),//这里的编号只是一个识别符，不包含任何业务联系
                "class" : me.getClass("item"),
                handler : me.getCallString("focus", me.getId("item" + me.itemCount)),
                mouseoverHandler : me.getCallString("_onMouse", me.getId("item" + me.itemCount)),
                mouseoutHandler : me.getCallString("_onMouse",  me.getId("item" + me.itemCount++)),
                content : item.content
            }));
        });
        scrollStr = baidu.format(me.tplDOM, {
            id : me.getId("scroll"),
            "class" : me.getClass("scroll"),
            content : itemStr.join("")
        });
        return baidu.format(me.tplDOM, {
            id : me.getId(),
            "class" : me.getClass(),
            content : scrollStr
        });
    },

    /**
     * 取得滚动容器
     * @return {HTMLElement}  滚动容器
     */
    getScrollContainer : function(){
        return baidu.g(this.getId("scroll"));
    },

    /**
     * 取得参数索引值对应的item
     * @param {Number} index 取item的索引
     * @return {HTMLElement} 返回该索引下的html对象
     */

    getItem : function(index){
        return baidu.dom.children(this.getScrollContainer())[index];
    },

    /**
     * 插入一个item到末端，当存在第二参数表示要在该索引对应的item之前插入
     * @param {HTMLElement} ele 需要插入的item，只取ele的innerHTML内容
     * @param {Number} index 在该索引指定的item前面插入
     */

    addItem : function(ele, index) {

        var me = this,

            item = baidu.format(me.tplItem, {

                id : me.getId("item" + me.itemCount),

                "class" : me.getClass("item"),

                handler : me.getCallString("focus", me.getId("item" + me.itemCount)),
                mouseoverHandler : me.getCallString("_onMouse", 'over', me.getId("item" + me.itemCount)),
                mouseoutHandler : me.getCallString("_onMouse", 'out',  me.getId("item" + me.itemCount++)),

                content : ele.innerHTML

            });
        if(baidu.lang.isNumber(index)){

            baidu.dom.insertHTML(me.getItem(index), "beforeBegin", item);

            index <= me.scrollIndex && me.scrollIndex++;//当插入一个item，需要更新原来的scrollIndex

        }else{

            baidu.dom.insertHTML(me.getScrollContainer(), "beforeEnd", item);

        }
        me.totalCount++;

        //这里不重新设置会造成掉行

        me._resize();

    },

    /**
     * 移除一个item
     * @public
     * @param {Number} index 需移除的item的索引
     * @return {HTMLElement} 被移除的项
     */

    removeItem : function(index) {

        var me = this,

            item = me.getItem(index);

        if(item){

            baidu.dom.remove(item.id);

            me.scrollIndex = (index == me.scrollIndex) ? 0 : (index<me.scrollIndex ? me.scrollIndex-1 : me.scrollIndex);

            me.totalCount--;
//          if("horizontal" == me.orientation){
//              baidu.setStyles(me.getScrollContainer(), {width : me.getScrollContainer().offsetWidth - me.offsetWidth + "px"});
//          }
            me._resize();

        }
        return item;

    },

    /**
     * 滚动到索引指定的item
     * @public
     * @param {Number} index 目标索引
     * @param {Number} scrollOffset 把item滚动到的位置，取值(0-pageSize)
     */

    scrollTo : function(index, scrollOffset) {

        var me = this,
            scrollOffset = scrollOffset || 0;
        if(me.dispatchEvent("onbeforescroll", {index : index, scrollOffset : scrollOffset})){
            me._scrollTo(index, scrollOffset);
        }

    },

    /**
     * 直接滚动到索引指定的item(无动画效果)
     * @param {Number} index 目标索引
     * @param {Number} scrollOffset 把item滚动到的位置，定义域(0, pageSize-1)
     */

    _scrollTo : function(index, scrollOffset) {

        var me = this,
            scrollOffset = scrollOffset || 0,

            item = me.getItem(index);

        if(item){
            me.dispatchEvent("onbeforestartscroll", {index : index, scrollOffset : scrollOffset});
            me.getBody()[me.axis[me.orientation].scroll] = me[me.axis[me.orientation].offsetSize] * (index - scrollOffset);
            me.dispatchEvent("onafterscroll", {index : index, scrollOffset : scrollOffset});
        }
    },

    /**
     * 设置索引对应的item的焦点
     * @param {Number} index 目标索引
     */

    focus : function(index) {

        var me = this, item;

        //这里当index是传入id时转换成索引

        if("string" == typeof(index)){

            baidu.array.each(baidu.dom.children(me.getScrollContainer()), function(item, i){

                if(index == item.id){

                    index = i;

                    return;

                }

            });

        }

        item = me.getItem(index);

        if(item && me.scrollIndex != index){

            me._blur();

            baidu.dom.addClass(item, me.getClass("item-focus"));

            me.scrollIndex = index;

        }

        me.dispatchEvent("onitemclick");

    },

    /**
     * 失去焦点
     */

    _blur : function() {

        var me = this,

            item = me.getItem(me.scrollIndex);

        if(item){

            baidu.dom.removeClass(item, me.getClass("item-focus"));

            me.scrollIndex = -1;

        }

    },
    /**
     * 控件单个项的鼠标移入或移出的样式
     * @param {String} type 事件类型
     * @param {Number} rsid 目标id
     */
    _onMouse : function(type, rsid){
        this.dispatchEvent("mouse" + type, {target : baidu.g(rsid)});
    },

    /**
     * 销毁实例
     */
    dispose : function(){
        var me = this;
        me.dispatchEvent("dispose");
        baidu.dom.remove(me.getMain());
        baidu.lang.Class.prototype.dispose.call(me);
    }

});<commit_msg>去掉resize的判断<commit_after>/*
 * Tangram
 * Copyright 2010 Baidu Inc. All rights reserved.
 * @path:ui/carousel/Carousel.js
 * @author:linlingyu
 * @version:1.0.0
 * @date:2010-09-06
 */

///import baidu.dom.insertHTML;
///import baidu.dom.setStyles;
///import baidu.array.each;
///import baidu.dom.g;
///import baidu.dom.children;
///import baidu.dom.remove;
///import baidu.dom.addClass;
///import baidu.dom.removeClass;
///import baidu.lang.isNumber;
///import baidu.string.format;
///import baidu.ui.createUI;

/**
 * carousel滚动控件。
 * @class carousel类
 * @param  {Object}   [options]           carousel的参数选项
 * @config {HTMLElement}   target              存放控件的元素
 * @config {Array}    contentText         用于生成滚动的条目
 * @config {String}   orientation         排列方式，取值：horizontal（默认），vertical。
 * @config {String}   flip                滚动按钮方式，取值：item（一次滚动一个项），page（翻页滚动）。
 * @config {Number}   pageSize            一行显示几个item，默认值3。
 * @config {Boolean}  isCycle             是否循环滚动，默认值false。
 * @config {Boolean}  autoScroll          是否自动滚动。
 * @config {Boolean}  showButton          是否显示翻转按钮，默认值true。
 * @config {Number}   offsetWidth         用户自定义的滚动宽度
 * @config {Number}   offsetHeight        用户自定义的滚动高度
 * @config {Function} onload              初始化时的触发事件
 * @config {Function} onbeforescroll      开始滚动时的触发事件
 * @config {Function} onafterscroll       结束滚动时的触发事件
 * @config {Function} onprevitem          当跳到上一个滚动项时触发该事件
 * @config {Function} onnextitem          当跳到下一个滚动项时触发该事件
 * @config {Function} onprevpage          当跳到上一页时触发该事件
 * @config {Function} onnextPage          当跳到下一页时触发该事件
 * @config {Function} onitemclick         点击某个滚动项时的触发事件
 * @config {Function} onmouseover         当鼠标悬停在某个滚动项时的触发事件
 * @config {Function} onmouseout          当鼠标移开某个滚动项时的触发事件
 * @plugin autoScroll                     自动滚动
 * @plugin btn                            为跑马灯添加控制按钮插件
 * @plugin fx                             为跑马灯添加动画效果
 * @plugin scrollByItem                   单次滚动单个元素的模式
 * @plugin scrollByPage                   单次滚动一页的模式
 * @plugin table                          让跑马灯支持多行多列
 */

baidu.ui.Carousel = baidu.ui.createUI(

    function(opts){
    this.contentText = opts.contentText || [];  //数组或对象在prototype中定义时会造成新建对象共用数据
}).extend(
    /**
     *  @lends baidu.ui.carousel.Carousel.prototype
     */
{

    uiType : "carousel",        // ui控件的类型 **必须**
    orientation : "horizontal", //横竖向的排列方式，取值horizontal,vertical
    pageSize : 3,               //每页显示多少个item

    scrollIndex : -1,           //当前焦点滚动到的项索引

    totalCount : 0,             //总记录数
    itemCount : 0,              //用于创建item的自增数
    offsetWidth : 0,            //单个item的宽度
    offsetHeight : 0,       //单个item的高度

    axis : {
        horizontal : {offsetPos : "offsetLeft", offsetSize : "offsetWidth", scroll : "scrollLeft"},
        vertical : {offsetPos : "offsetTop", offsetSize : "offsetHeight", scroll:"scrollTop"}
    },//关于位置的换算

    tplDOM : "
#{content}
",

    tplItem : "
#{content}
",

    /**
     * 渲染carousel到指定的target容器中
     * @public
     * @param {HTMLElement} target table的父层容器
     */
    render : function(target){
        var me = this;
        baidu.dom.insertHTML(me.renderMain(target || me.target), "beforeEnd", me.getString());
        me.totalCount = me.contentText.length || 0;
        me._resize();
        me.dispatchEvent("onload");
    },

    /**
     * 根据item的尺寸运算可视区域的大小和滚动层的大小
     * @param {boolean} val true:第一次resize, false:一般的resize
     */
    _resize : function(){
        var me = this,
            offset_x = me.axis[me.orientation].offsetSize,//由pageSize决定长度的一方
            offset_y = me.axis["horizontal" == me.orientation ? "vertical" : "horizontal"].offsetSize,//直接设置成item长度的一方
            item = me.getItem(0);

        me.offsetWidth = me.offsetWidth || item.offsetWidth;
        me.offsetHeight = me.offsetHeight || item.offsetHeight;
        //这里设置container的宽度和高度让用户可以看到一个按照pageSize和orientation计算出来的固定介面
        baidu.dom.setStyles(me.getBody(), {
            width : me.offsetWidth * ("horizontal" == me.orientation ? me.pageSize : 1) + "px",
            height : me.offsetHeight * ("vertical" == me.orientation ? me.pageSize : 1) + "px"
        });
        //这里运算scrollContainer的宽度是为了让item都能展开排成一行
        if("horizontal" == me.orientation){
            baidu.setStyles(me.getScrollContainer(), {width : me.offsetWidth * me.totalCount + "px"});
        }
    },

    /**
     * 生成滚动结构的html字符串代码
     * @private
     * @return {String} 生成html字符串
     */
    getString : function(){
        var me = this, itemStr = [], scrollStr;
        baidu.array.each(me.contentText, function(item){
            itemStr.push(baidu.format(me.tplItem, {
                id : me.getId("item" + me.itemCount),//这里的编号只是一个识别符，不包含任何业务联系
                "class" : me.getClass("item"),
                handler : me.getCallString("focus", me.getId("item" + me.itemCount)),
                mouseoverHandler : me.getCallString("_onMouse", me.getId("item" + me.itemCount)),
                mouseoutHandler : me.getCallString("_onMouse",  me.getId("item" + me.itemCount++)),
                content : item.content
            }));
        });
        scrollStr = baidu.format(me.tplDOM, {
            id : me.getId("scroll"),
            "class" : me.getClass("scroll"),
            content : itemStr.join("")
        });
        return baidu.format(me.tplDOM, {
            id : me.getId(),
            "class" : me.getClass(),
            content : scrollStr
        });
    },

    /**
     * 取得滚动容器
     * @return {HTMLElement}  滚动容器
     */
    getScrollContainer : function(){
        return baidu.g(this.getId("scroll"));
    },

    /**
     * 取得参数索引值对应的item
     * @param {Number} index 取item的索引
     * @return {HTMLElement} 返回该索引下的html对象
     */

    getItem : function(index){
        return baidu.dom.children(this.getScrollContainer())[index];
    },

    /**
     * 插入一个item到末端，当存在第二参数表示要在该索引对应的item之前插入
     * @param {HTMLElement} ele 需要插入的item，只取ele的innerHTML内容
     * @param {Number} index 在该索引指定的item前面插入
     */

    addItem : function(ele, index) {

        var me = this,

            item = baidu.format(me.tplItem, {

                id : me.getId("item" + me.itemCount),

                "class" : me.getClass("item"),

                handler : me.getCallString("focus", me.getId("item" + me.itemCount)),
                mouseoverHandler : me.getCallString("_onMouse", 'over', me.getId("item" + me.itemCount)),
                mouseoutHandler : me.getCallString("_onMouse", 'out',  me.getId("item" + me.itemCount++)),

                content : ele.innerHTML

            });
        if(baidu.lang.isNumber(index)){

            baidu.dom.insertHTML(me.getItem(index), "beforeBegin", item);

            index <= me.scrollIndex && me.scrollIndex++;//当插入一个item，需要更新原来的scrollIndex

        }else{

            baidu.dom.insertHTML(me.getScrollContainer(), "beforeEnd", item);

        }
        me.totalCount++;

        //这里不重新设置会造成掉行

        me._resize();

    },

    /**
     * 移除一个item
     * @public
     * @param {Number} index 需移除的item的索引
     * @return {HTMLElement} 被移除的项
     */

    removeItem : function(index) {

        var me = this,

            item = me.getItem(index);

        if(item){

            baidu.dom.remove(item.id);

            me.scrollIndex = (index == me.scrollIndex) ? 0 : (index<me.scrollIndex ? me.scrollIndex-1 : me.scrollIndex);

            me.totalCount--;
//          if("horizontal" == me.orientation){
//              baidu.setStyles(me.getScrollContainer(), {width : me.getScrollContainer().offsetWidth - me.offsetWidth + "px"});
//          }
            me._resize();

        }
        return item;

    },

    /**
     * 滚动到索引指定的item
     * @public
     * @param {Number} index 目标索引
     * @param {Number} scrollOffset 把item滚动到的位置，取值(0-pageSize)
     */

    scrollTo : function(index, scrollOffset) {

        var me = this,
            scrollOffset = scrollOffset || 0;
        if(me.dispatchEvent("onbeforescroll", {index : index, scrollOffset : scrollOffset})){
            me._scrollTo(index, scrollOffset);
        }

    },

    /**
     * 直接滚动到索引指定的item(无动画效果)
     * @param {Number} index 目标索引
     * @param {Number} scrollOffset 把item滚动到的位置，定义域(0, pageSize-1)
     */

    _scrollTo : function(index, scrollOffset) {

        var me = this,
            scrollOffset = scrollOffset || 0,

            item = me.getItem(index);

        if(item){
            me.dispatchEvent("onbeforestartscroll", {index : index, scrollOffset : scrollOffset});
            me.getBody()[me.axis[me.orientation].scroll] = me[me.axis[me.orientation].offsetSize] * (index - scrollOffset);
            me.dispatchEvent("onafterscroll", {index : index, scrollOffset : scrollOffset});
        }
    },

    /**
     * 设置索引对应的item的焦点
     * @param {Number} index 目标索引
     */

    focus : function(index) {

        var me = this, item;

        //这里当index是传入id时转换成索引

        if("string" == typeof(index)){

            baidu.array.each(baidu.dom.children(me.getScrollContainer()), function(item, i){

                if(index == item.id){

                    index = i;

                    return;

                }

            });

        }

        item = me.getItem(index);

        if(item && me.scrollIndex != index){

            me._blur();

            baidu.dom.addClass(item, me.getClass("item-focus"));

            me.scrollIndex = index;

        }

        me.dispatchEvent("onitemclick");

    },

    /**
     * 失去焦点
     */

    _blur : function() {

        var me = this,

            item = me.getItem(me.scrollIndex);

        if(item){

            baidu.dom.removeClass(item, me.getClass("item-focus"));

            me.scrollIndex = -1;

        }

    },
    /**
     * 控件单个项的鼠标移入或移出的样式
     * @param {String} type 事件类型
     * @param {Number} rsid 目标id
     */
    _onMouse : function(type, rsid){
        this.dispatchEvent("mouse" + type, {target : baidu.g(rsid)});
    },

    /**
     * 销毁实例
     */
    dispose : function(){
        var me = this;
        me.dispatchEvent("dispose");
        baidu.dom.remove(me.getMain());
        baidu.lang.Class.prototype.dispose.call(me);
    }

});<|endoftext|>


<commit_before>(function(bespoke) {

  bespoke.plugins.secondary = function(deck) {

    /*
      Interact with the deck
      https://github.com/markdalgleish/bespoke.js#deck-instances
    */
    deck.next();
    deck.prev();
    deck.slide(0);

    /*
       Handle events
       https://github.com/markdalgleish/bespoke.js#events
    */
    deck.on('activate', function(e) {
      console.log('Slide #' + e.index + ' was activated!', e.slide);
    });

    deck.on('deactivate', function(e) {
      console.log('Slide #' + e.index + ' was deactivated!', e.slide);
    });

    deck.on('next', function(e) {
      console.log('The next slide is #' + (e.index + 1), deck.slides[e.index + 1]);
      // return false to cancel user interaction
    });

    deck.on('prev', function(e) {
      console.log('The previous slide is #' + (e.index - 1), deck.slides[e.index - 1]);
      // return false to cancel user interaction
    });

    deck.on('slide', function(e) {
      console.log('The requested slide is #' + e.index, e.slide);
      // return false to cancel user interaction
    });
  };

}(bespoke));
<commit_msg>Functional first version<commit_after>/*global window:true, document:true, Math:true, bespoke:true */

(function(window, document, Math, bespoke, convenient, ns, pluginName, undefined) {
    "use strict";

    var cv = convenient.builder(pluginName),

        KeyConstants = {
            // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Virtual_key_codes
            S: 0x53, // (83) "S" key.
        },

        defaults = {
            notes: "aside",
            keys: {
                toggle: KeyConstants.S
            }
        },

        randomInteger = function(from, to) {
            // TODO: look for someone else's implementation - they've probably covered all the corner cases.
            // This should do for 0 <= from < to < (random's resolution) though.
            var diff;

            if (to === undefined) {
                to = from;
                from = 0;
            }

            diff = to - from;

            var rnd = from + Math.floor(Math.random() * diff);

            return rnd;
        },

        baseWindowName = pluginName + "-window-",

        generateWindowName = function() {
            var rnd = randomInteger(1000, 10000),
                windowName = baseWindowName + rnd;

            return windowName;
        },

        initializeSecondaryWindowContents = function(doc) {
            doc.body.innerHTML = "
Notes

";
        },

        plugin = function(deck, options) {
            var off = {},

                activeSlide = null,

                activeSlideIndex = null,

                unboundActiveSlideDeckMethods = {
                    // TODO: break out activeSlide functionality to separate library
                    // Plugin functions expect to be executed in a deck context
                    enableActiveSlideListener: function() {
                        off.saveActiveSlide = this.on("activate", unboundActiveSlideDeckMethods.saveActiveSlide.bind(this));
                    },

                    saveActiveSlide: function(e) {
                        activeSlide = e.slide;
                        activeSlideIndex = e.index;
                    },

                    getActiveSlide: function() {
                        return activeSlide;
                    },

                    getActiveSlideIndex: function() {
                        return activeSlideIndex;
                    }
                },

                unboundSecondaryDeckMethods = {
                    // Plugin functions expect to be executed in a deck context
                    getNotesElement: function() {
                        return this.secondary.window && this.secondary.window.document && this.secondary.window.document.getElementById("notes");
                    },

                    isOpen: function() {
                        var s = this.secondary,
                            w = s.window,
                            // isInitialized, isNotNull, isNotClosed, isOwnedByThisWindow, containsNotesElement
                            result = (true && s !== undefined && w !== null && w.closed !== true && w.opener === window && this.secondary.getNotesElement() !== null);

                        return result;
                    },

                    open: function() {
                        if (!this.secondary.isOpen()) {
                            (this.secondary.window = window.open());
                            initializeSecondaryWindowContents(this.secondary.window.document);
                        }

                        return this.secondary.isOpen();
                    },

                    close: function() {
                        if (this.secondary.isOpen()) {
                            this.secondary.window.close();
                        }

                        return !this.secondary.isOpen();
                    },

                    focus: function() {
                        if (this.secondary.isOpen()) {
                            this.secondary.window.focus();
                        }

                        return this.secondary.isOpen();
                    },

                    toggle: function() {
                        if (this.secondary.isOpen()) {
                            this.secondary.close();
                        } else {
                            this.secondary.open();
                        }

                        return this.secondary.isOpen();
                    },

                    synchronize: function() {
                        var element,
                            slide,
                            slideNotes,
                            allNotes;

                        if (!this.secondary.isOpen()) {
                            return false;
                        }

                        element = this.secondary.getNotesElement();
                        slide = this.getActiveSlide();

                        slideNotes = cv.copyArray(slide.querySelectorAll(options.notes));

                        allNotes = slideNotes.reduce(function(notesHtml, slideNote) {
                            return notesHtml + slideNote.outerHTML;
                        }, "");

                        element.innerHTML = allNotes;

                        return this.secondary.isOpen();
                    }
                },

                registerDeckExtensions = function() {
                    deck.getActiveSlide = unboundActiveSlideDeckMethods.getActiveSlide.bind(deck);
                    deck.getActiveSlideIndex = unboundActiveSlideDeckMethods.getActiveSlideIndex.bind(deck);

                    deck.secondary = {
                        window: null,
                        secondaryWindowName: generateWindowName(),
                        getNotesElement: unboundSecondaryDeckMethods.getNotesElement.bind(deck),
                        isOpen: unboundSecondaryDeckMethods.isOpen.bind(deck),
                        open: unboundSecondaryDeckMethods.open.bind(deck),
                        close: unboundSecondaryDeckMethods.close.bind(deck),
                        focus: unboundSecondaryDeckMethods.focus.bind(deck),
                        toggle: unboundSecondaryDeckMethods.toggle.bind(deck),
                        synchronize: unboundSecondaryDeckMethods.synchronize.bind(deck)
                    };
                },

                initOptions = function() {
                    // TODO: merge function?
                    // Only merge known options
                    var merged = {};

                    merged.keys = {};
                    merged.keys.toggle = options.keys && options.keys.toggle || defaults.keys.toggle;

                    merged.notes = options.notes || defaults.notes;

                    options = merged;
                },

                keyDownListener = function(e) {
                    var eventHandled = false;

                    // No modifier keys, please
                    if (!e.altKey && !e.ctrlKey && !e.metaKey && !e.shiftKey) {
                        eventHandled = eventHandled || (e.which === options.keys.toggle && cv.fire(deck, "toggle", e) && deck.secondary.toggle() && deck.secondary.synchronize());
                    }

                    if (eventHandled) {
                        e.preventDefault();
                    }

                    return !eventHandled;
                },

                onBeforeUnload = function() {
                    deck.secondary.close();

                    return null;
                },

                onActivate = function() {
                    deck.secondary.synchronize();
                },

                enable = function() {
                    unboundActiveSlideDeckMethods.enableActiveSlideListener.call(deck);

                    // window.addEventListener doesn't seem to work for onbeforeunload
                    window.onbeforeunload = onBeforeUnload;

                    document.addEventListener("keydown", keyDownListener, false);
                    off.activate = deck.on("activate", onActivate);
                },

                init = function() {
                    initOptions();
                    registerDeckExtensions();
                    enable();
                };

            init();
        };

    if (ns[pluginName] !== undefined) {
        throw cv.generateErrorObject("The " + pluginName + " plugin has already been loaded.");
    }

    ns[pluginName] = plugin;
}(window, document, Math, bespoke, bespoke.plugins.convenient, bespoke.plugins, "secondary"));
<|endoftext|>


<commit_before>// JavaScript Document

	$(window).scroll(function(){
		var divHeight = $(window).height()*1;
		var divIndex = $(window).scrollTop() / divHeight;

		console.log(divIndex);
				console.log(divHeight);

	$(function () {
   function runIt() {
      $('#fond19 img').animate({"opacity":"0.4"},500)
               .animate({"opacity":"1"},500, runIt);
   }

   runIt();
});

		$("#n1").append(function() {

			if (divIndex < 1) {
				$("#n1").css({opacity:'1'},1);}
			else {
			$("#n1").css({opacity:'0.4'},1);}

		});

		$("#n2").append(function() {

			if (divIndex >= 2.19 && divIndex < 3.39) {
				$("#n2").css({opacity:'1'},1);}
			else {
			$("#n2").css({opacity:'0.4'},1);}
		});

		$("#n3").append(function() {

			if (divIndex >= 3.39 && divIndex < 4.59) {
				$("#n3").css({opacity:'1'},1);}
			else {
			$("#n3").css({opacity:'0.4'},1);}
		});

		$("#n4").append(function() {

		if (divIndex >= 4.59 && divIndex < 5.79) {
		$("#n4").css({opacity:'1'},1);}
			else {
		$("#n4").css({opacity:'0.4'},1);}
		});

		$("#n5").append(function() {

			if (divIndex >= 5.79 && divIndex < 6.99) {
		$("#n5").css({opacity:'1'},1);}
			else {
		$("#n5").css({opacity:'0.4'},1);}
		});

		$("#n6").append(function() {

			if (divIndex >= 6.99 && divIndex < 8.19) {
		$("#n6").css({opacity:'1'},1);}
			else {
		$("#n6").css({opacity:'0.4'},1);}
		});

		$("#n7").append(function() {

		if (divIndex >= 8.19 && divIndex < 9.39) {
		$("#n7").css({opacity:'1'},1);}
			else {
		$("#n7").css({opacity:'0.4'},1);}
		});

		$("#n8").append(function() {

			if (divIndex >= 9.39 && divIndex < 10.59) {
		$("#n8").css({opacity:'1'},1);}
			else {
		$("#n8").css({opacity:'0.4'},1);}
		});

		$("#n9").append(function() {

			if (divIndex >= 10.59 && divIndex < 11.79) {
		$("#n9").css({opacity:'1'},1);}
			else {
		$("#n9").css({opacity:'0.4'},1);}
		});

		$("#n10").append(function() {

			if (divIndex >= 11.79 && divIndex < 12.99) {
		$("#n10").css({opacity:'1'},1);}
			else {
		$("#n10").css({opacity:'0.4'},1);}
		});

		$("#n11").append(function() {

			if (divIndex >= 12.99 && divIndex < 14.19) {
		$("#n11").css({opacity:'1'},1);}
			else {
		$("#n11").css({opacity:'0.4'},1);}
		});

		$("#n12").append(function() {

			if (divIndex >= 14.19 && divIndex < 15.39) {
		$("#n12").css({opacity:'1'},1);}
			else {
		$("#n12").css({opacity:'0.4'},1);}
		});

		$("#n13").append(function() {

			if (divIndex >= 15.39 && divIndex < 16.59) {
		$("#n13").css({opacity:'1'},1);}
			else {
		$("#n13").css({opacity:'0.4'},1);}
		});

		$("#n14").append(function() {

			if (divIndex >= 16.59 && divIndex < 17.79) {
		$("#n14").css({opacity:'1'},1);}
			else {
		$("#n14").css({opacity:'0.4'},1);}
		});

		$("#n15").append(function() {

			if (divIndex >= 17.79 && divIndex < 18.99) {
		$("#n15").css({opacity:'1'},1);}
			else {
		$("#n15").css({opacity:'0.4'},1);}
		});

		$("#n16").append(function() {

			if (divIndex >= 18.99 && divIndex < 20.19) {
		$("#n16").css({opacity:'1'},1);}
			else {
		$("#n16").css({opacity:'0.4'},1);}
		});

		$("#n17").append(function() {

			if (divIndex >= 20.19 && divIndex < 21.39) {
		$("#n17").css({opacity:'1'},1);}
			else {
		$("#n17").css({opacity:'0.4'},1);}
		});

		$("#n18").append(function() {

			if (divIndex >= 21.39 && divIndex < 22.59) {
		$("#n18").css({opacity:'1'},1);}
			else {
		$("#n18").css({opacity:'0.4'},1);}
		});

		$("#n20").append(function() {

			if (divIndex >= 22.59) {
		$("#n20").css({opacity:'1'},1);}
			else {
		$("#n20").css({opacity:'0.4'},1);}
		});

		$("#intro a").append(function() {

			if (divIndex < 1) {
				$("#intro a").attr("href", "#fond19");}
			if (divIndex >= 1) {
				$("#intro a").attr("href", "#traveler");}
			if (divIndex >= 2.19) {
				$("#intro a").attr("href", "#third");}
			if (divIndex >= 3.39) {
				$("#intro a").attr("href", "#hipster");}
			if (divIndex >= 4.59) {
				$("#intro a").attr("href", "#fond4");}
			if (divIndex >= 5.79) {
				$("#intro a").attr("href", "#fond5");}
			if (divIndex >= 6.99) {
				$("#intro a").attr("href", "#fond6");}
			if (divIndex >= 8.19) {
				$("#intro a").attr("href", "#fond7");}
			if (divIndex >= 9.39) {
				$("#intro a").attr("href", "#fond8");}
			if (divIndex >= 10.59) {
				$("#intro a").attr("href", "#fond9");}
			if (divIndex >= 11.79) {
				$("#intro a").attr("href", "#fond10");}
			if (divIndex >= 12.99) {
				$("#intro a").attr("href", "#fond11");}
			if (divIndex >= 14.19) {
				$("#intro a").attr("href", "#fond12");}
			if (divIndex >= 15.39) {
				$("#intro a").attr("href", "#fond13");}
			if (divIndex >= 16.59) {
				$("#intro a").attr("href", "#fond14");}
			if (divIndex >= 17.79) {
				$("#intro a").attr("href", "#fond15");}
			if (divIndex >= 18.99) {
				$("#intro a").attr("href", "#fond16");}
			if (divIndex >= 20.19) {
				$("#intro a").attr("href", "#fond17");}
			if (divIndex >= 21.39) {
				$("#intro a").attr("href", "footer");}
			if (divIndex >= 21.59) {
				$("#intro a").css({display:'none'},1);}
			else {
				$("#intro a").css({display:'block'},1);}

		});

		$("#fond19 img,#fond19 p,#fond19 hr").append(function() {
			if (divIndex >= 0.19 && divIndex <= 1.36) {
		$("#fond19 img").css({display:'block'},1);
		$("#fond19 p,#fond19 hr").fadeIn('fast');}
			else {
		$("#fond19 img").css({display:'none'},1);
		$("#fond19 p,#fond19 hr").fadeOut('fast');}
		});

		});

<commit_msg>number<commit_after>// JavaScript Document

	$(window).scroll(function(){
		var divHeight = $(window).height()*1;
		var divIndex = $(window).scrollTop() / divHeight;

		console.log(divIndex);
				console.log(divHeight);

	$(function () {
   function runIt() {
      $('#fond19 img').animate({"opacity":"0.4"},500)
               .animate({"opacity":"1"},500, runIt);
   }

   runIt();
});

		$("#n1").append(function() {

			if (divIndex < 1) {
				$("#n1").css({opacity:'1'},1);}
			else {
			$("#n1").css({opacity:'0.4'},1);}

		});

		$("#n2").append(function() {

			if (divIndex >= 1 && divIndex < 2.19) {
				$("#n2").css({opacity:'1'},1);}
			else {
			$("#n2").css({opacity:'0.4'},1);}

		});

		$("#n3").append(function() {

			if (divIndex >= 2.19 && divIndex < 3.39) {
				$("#n3").css({opacity:'1'},1);}
			else {
			$("#n3").css({opacity:'0.4'},1);}
		});

		$("#n3").append(function() {

			if (divIndex >= 3.39 && divIndex < 4.59) {
				$("#n3").css({opacity:'1'},1);}
			else {
			$("#n3").css({opacity:'0.4'},1);}
		});

		$("#n4").append(function() {

		if (divIndex >= 4.59 && divIndex < 5.79) {
		$("#n4").css({opacity:'1'},1);}
			else {
		$("#n4").css({opacity:'0.4'},1);}
		});

		$("#n5").append(function() {

			if (divIndex >= 5.79 && divIndex < 6.99) {
		$("#n5").css({opacity:'1'},1);}
			else {
		$("#n5").css({opacity:'0.4'},1);}
		});

		$("#n6").append(function() {

			if (divIndex >= 6.99 && divIndex < 8.19) {
		$("#n6").css({opacity:'1'},1);}
			else {
		$("#n6").css({opacity:'0.4'},1);}
		});

		$("#n7").append(function() {

		if (divIndex >= 8.19 && divIndex < 9.39) {
		$("#n7").css({opacity:'1'},1);}
			else {
		$("#n7").css({opacity:'0.4'},1);}
		});

		$("#n8").append(function() {

			if (divIndex >= 9.39 && divIndex < 10.59) {
		$("#n8").css({opacity:'1'},1);}
			else {
		$("#n8").css({opacity:'0.4'},1);}
		});

		$("#n9").append(function() {

			if (divIndex >= 10.59 && divIndex < 11.79) {
		$("#n9").css({opacity:'1'},1);}
			else {
		$("#n9").css({opacity:'0.4'},1);}
		});

		$("#n10").append(function() {

			if (divIndex >= 11.79 && divIndex < 12.99) {
		$("#n10").css({opacity:'1'},1);}
			else {
		$("#n10").css({opacity:'0.4'},1);}
		});

		$("#n11").append(function() {

			if (divIndex >= 12.99 && divIndex < 14.19) {
		$("#n11").css({opacity:'1'},1);}
			else {
		$("#n11").css({opacity:'0.4'},1);}
		});

		$("#n12").append(function() {

			if (divIndex >= 14.19 && divIndex < 15.39) {
		$("#n12").css({opacity:'1'},1);}
			else {
		$("#n12").css({opacity:'0.4'},1);}
		});

		$("#n13").append(function() {

			if (divIndex >= 15.39 && divIndex < 16.59) {
		$("#n13").css({opacity:'1'},1);}
			else {
		$("#n13").css({opacity:'0.4'},1);}
		});

		$("#n14").append(function() {

			if (divIndex >= 16.59 && divIndex < 17.79) {
		$("#n14").css({opacity:'1'},1);}
			else {
		$("#n14").css({opacity:'0.4'},1);}
		});

		$("#n15").append(function() {

			if (divIndex >= 17.79 && divIndex < 18.99) {
		$("#n15").css({opacity:'1'},1);}
			else {
		$("#n15").css({opacity:'0.4'},1);}
		});

		$("#n16").append(function() {

			if (divIndex >= 18.99 && divIndex < 20.19) {
		$("#n16").css({opacity:'1'},1);}
			else {
		$("#n16").css({opacity:'0.4'},1);}
		});

		$("#n17").append(function() {

			if (divIndex >= 20.19 && divIndex < 21.39) {
		$("#n17").css({opacity:'1'},1);}
			else {
		$("#n17").css({opacity:'0.4'},1);}
		});

		$("#n18").append(function() {

			if (divIndex >= 21.39 && divIndex < 22.59) {
		$("#n18").css({opacity:'1'},1);}
			else {
		$("#n18").css({opacity:'0.4'},1);}
		});

		$("#n20").append(function() {

			if (divIndex >= 22.59) {
		$("#n20").css({opacity:'1'},1);}
			else {
		$("#n20").css({opacity:'0.4'},1);}
		});

		$("#intro a").append(function() {

			if (divIndex < 1) {
				$("#intro a").attr("href", "#fond19");}
			if (divIndex >= 1) {
				$("#intro a").attr("href", "#traveler");}
			if (divIndex >= 2.19) {
				$("#intro a").attr("href", "#third");}
			if (divIndex >= 3.39) {
				$("#intro a").attr("href", "#hipster");}
			if (divIndex >= 4.59) {
				$("#intro a").attr("href", "#fond4");}
			if (divIndex >= 5.79) {
				$("#intro a").attr("href", "#fond5");}
			if (divIndex >= 6.99) {
				$("#intro a").attr("href", "#fond6");}
			if (divIndex >= 8.19) {
				$("#intro a").attr("href", "#fond7");}
			if (divIndex >= 9.39) {
				$("#intro a").attr("href", "#fond8");}
			if (divIndex >= 10.59) {
				$("#intro a").attr("href", "#fond9");}
			if (divIndex >= 11.79) {
				$("#intro a").attr("href", "#fond10");}
			if (divIndex >= 12.99) {
				$("#intro a").attr("href", "#fond11");}
			if (divIndex >= 14.19) {
				$("#intro a").attr("href", "#fond12");}
			if (divIndex >= 15.39) {
				$("#intro a").attr("href", "#fond13");}
			if (divIndex >= 16.59) {
				$("#intro a").attr("href", "#fond14");}
			if (divIndex >= 17.79) {
				$("#intro a").attr("href", "#fond15");}
			if (divIndex >= 18.99) {
				$("#intro a").attr("href", "#fond16");}
			if (divIndex >= 20.19) {
				$("#intro a").attr("href", "#fond17");}
			if (divIndex >= 21.39) {
				$("#intro a").attr("href", "footer");}
			if (divIndex >= 21.59) {
				$("#intro a").css({display:'none'},1);}
			else {
				$("#intro a").css({display:'block'},1);}

		});

		$("#fond19 img,#fond19 p,#fond19 hr").append(function() {
			if (divIndex >= 0.19 && divIndex <= 1.36) {
		$("#fond19 img").css({display:'block'},1);
		$("#fond19 p,#fond19 hr").fadeIn('fast');}
			else {
		$("#fond19 img").css({display:'none'},1);
		$("#fond19 p,#fond19 hr").fadeOut('fast');}
		});

		});

<|endoftext|>


<commit_before>
// This file sets up boxing of javascript native objects into squeak objects
// All relevant classes are enhanced by that functionality and there are
// Several global functions to box or unbox objects.

// Some objects are boxing primitive js-values. Unboxing these values is polymorphic.
// The real version of this method is below. This could alternatively throw an error,
// but we try to be tolerant.
var __isBoxedObject = function() { throw "just access this slot without calling."; };
_Object._addInstanceMethods({
	__giveError: function(methodname) {
		var msg = "We have an obsolete " + methodname + "()-call! Fix it.";
		alert(msg);
		throw msg;
	},
	// TODO if we're sure everything is fixed, remove these warnings.
	js: function() {
		this.__giveError("js");
	},
	jsNew_: function() {
		this.__giveError("jsNew:");
	},
	js_: function() {
		this.__giveError("js:");
	},
	slot_be_: function() {
		this.__giveError("slot:be:");
	},
	slot_: function() {
		this.__giveError("slot:");
	},
	slot_apply_: function() {
		this.__giveError("slot:apply:");
	},

	_unbox: function() {
		return this;
	},
	// This never gets called, we just need a true-ish slot in each box-instance
	_isBoxedObject: __isBoxedObject
});

// Class, that will wrap native javascript-objects to implement the Object-interface.
// Additionally, it adds accessor-methods for all fields to provide a squeak-API to
// set slots on javascript-objects.
Class("_Box", {
	superclass: _DoesNotUnderstandClass_,
	// regarding this method, see _Object._isBoxedObject
	instanceMethods: { _isBoxedObject: __isBoxedObject }});

// Functions to bootstrap primitive values and wrap them into 'squeak'-objects
// Most functions are used in translated code directly, to avoid switch-statement in _boxObject()
// (Instead of bool(), compiled code uses _true/_false directly. bool() is used in kernel_primitives.js etc.)
var bool = function(aBool) { if (aBool) { return _true; } else { return _false; } }
var character = function(aString) { return Character._wrapping(aString); }
var string = function(aString) { return ByteString._wrapping(aString); }
var number = function(aNumber) { return Float._wrapping(aNumber); }
var array = function(anArray) { return _Array._wrapping(anArray); }
var object = function(anObject) { return _Box._wrapping(anObject); }
// if we box a javascript function into a smalltalk block we must bind it on creation
// Non-local-return handling is not required here
var boundBlock = function(func, that) {
	var b = BlockClosure._newInstance();
	// This block is unboxed to func, but additional things happen on evaluation
	b.original$ = func;
	b.evaluated$ = function() {
		return _boxObject(func.apply(that, _unboxIterable(arguments)));
	}
	b.constructorArguments$ = function(argumentCollection) {
		// When using a library-function as constructor, unpack the arguments
		return _unboxIterable(argumentCollection);
	}
	return b;
}

// There are multiple js-'classes', that will be wrapped into a Squeak-Array
var arrayConstructors = [Array, NodeList];
var isArrayObject = function(anObject) {
	var constructor = anObject.constructor;
	for (index in arrayConstructors) {
		if (arrayConstructors[index] == constructor) {
			return true;
		}
	}
	return false;
};

// This static unboxing-function is added to avoid adding an _unbox method to native js-objects
var _unboxObject = function(anyObject) {
	if (anyObject._isBoxedObject) {
		return anyObject._unbox();
	}
	return anyObject;
};
var _unboxIterable = function(iterable) {
	var unboxed = [];
	for (index in iterable) {
		unboxed.push(_unboxObject(iterable[index]));
	}
	return unboxed;
}
var _unboxSlotObject = function(slotObject) {
	// This unboxes all slot-values of the object. The value does not need to be returned.
	// This is used in serialization of Slot-Objects (S2JSlotObject >> fillInstVars:guardedBy:)
	for (index in slotObject) {
		slotObject[index] = _unboxObject(slotObject[index]);
	}
}
// The 'that' parameter is optional and will be undefined otherwise
// It is relevant for functions, to bind them to their containing object when invoking them.
var _boxObject = function(nativeObject, that) {
	if (nativeObject === null || nativeObject === undefined) {
		return nil;
	}
	if (!nativeObject._isBoxedObject) {
		switch( typeof(nativeObject) ) {
			case "number": return number(nativeObject); break;
			case "string": return string(nativeObject); break;
			case "boolean": return bool(nativeObject); break;
			case "function": return boundBlock(nativeObject, that); break;
			case "object":
				if (isArrayObject(nativeObject)) {
					return array(nativeObject);
				} else {
					return object(nativeObject);
				}
				break;
			default:
				alert("Could not box creepy object: " + nativeObject);
		}
    }
	// nativeObject is already boxed!
	return nativeObject;
};
var _boxIterable = function(iterable) {
	var boxed = [];
	for (index in iterable) {
		boxed.push(_boxObject(iterable[index]));
	}
	return boxed;
}

// These boxing classes box fixed, immutable values
False._addInstanceMethods( { _unbox: function() { return false; } } );
True._addInstanceMethods( { _unbox: function() { return true; } } );
UndefinedObject._addInstanceMethods( { _unbox: function() { return null; } } );

// This DummyClass implements doesNotUnderstand: returning nil. This enables correct behaviour
// Of the _Box-class. An instance of _Box needs an instance of such a Dummy to implement the Object-interface.
// This Dummy-instance is invoked, if the original$-object does not have the queried slot.
Class("_DummyClass", {superclass: _Object, instanceMethods: { doesNotUnderstand_: function() { return nil; }}});
var _wrappingImpl = function(originalObject) {
	var result = this._newInstance(); // Polymorphic for different kinds of boxes
	result.original$ = originalObject;
	return result;
};
// These boxing classes box variable values and are all added the same functionality.
var boxingClasses = [_Box, ByteString, _Number, Character, BlockClosure, _Array];
for (index in boxingClasses) {
	var aClass = boxingClasses[index];
	aClass._addClassMethods({
		_wrapping: _wrappingImpl
	});
	aClass._addInstanceMethods({
		_hiddenGetter_: function(slotName) {
			return this.original$[slotName];
		},
		doesNotUnderstand_: function(aMessage) {
			var methodName = _unboxObject(aMessage.selector());
			if (methodName[methodName.length - 1] == ':') {
				// setter. Set the unboxed, native-js, value.
				var value = aMessage._arguments();
				if (value.length >= 1) // If more then one argument, ignore the rest!
					value = value[0];
				else // No arguments given when invoking setter!? Don't set an empty array.
					value = undefined;

				this.original$[methodName.substring(0, methodName.length - 1)] = _unboxObject(value);
				return value;
			} else {
				// getter. Second parameter relevant, if slot contains a function.
				// For most boxing classes, the javascript-native is hidden totally (this implementation).
				// _Box refines this method (_hiddenGetter_) to also check the underlying original$ for the slot
				// An example is the slot 'value', which is important on a DOM-TextArea and also implemented in Object
				return _boxObject(this._hiddenGetter_(methodName), this.original$);
			}
		},
		_unbox: function() {
			return this.original$;
		}
	});
}
_Box._addClassMethods({
	_wrapping: function(originalObject) {
		// In addition to the default original$-slot, also create a dummy-Object-instance.
		// This is a hack to implement the Object-protocol in a _Box. _Box inherits from _DoesNotUnderstandClass_,
		// so it does not implement any of Object's methods (to be able to fully access the underlying native object).
		// If the underlying object does not contain a certain slot, the method is invoked on the dummy-instance instead.
		// This way we have methods like #hash and #ifNil:ifNotNil: on boxed native objects.
		var result = _wrappingImpl.apply(this, arguments);
		result.dummyObject$ = _DummyClass._newInstance();
		return result;
	}
});
_Box._addInstanceMethods({
	_hiddenGetter_: function(slotName) {
		var result = this.original$[slotName];
		// First check, if the underlying object has this slot.
		// If not, try to invoke the corresponding Method implemented on Object (e.g. ifNil:ifNotNil:)
		// If this is not present, return nil.
		if (result === undefined) {
			// If not, invoke it on our 'dummyObject' to implement the Object-protocol of Squeak.
			// As this covers only 'getters', invoke without arguments.
			// This returns nil, if there is no such method. This corresponds to the javascript-behaviour,
			// when querying a slot, that is not present.
			result = this.dummyObject$[slotName]();
		}
		return result;
	}
});
<commit_msg>Undefined check in unbox-attempt<commit_after>
// This file sets up boxing of javascript native objects into squeak objects
// All relevant classes are enhanced by that functionality and there are
// Several global functions to box or unbox objects.

// Some objects are boxing primitive js-values. Unboxing these values is polymorphic.
// The real version of this method is below. This could alternatively throw an error,
// but we try to be tolerant.
var __isBoxedObject = function() { throw "just access this slot without calling."; };
_Object._addInstanceMethods({
	__giveError: function(methodname) {
		var msg = "We have an obsolete " + methodname + "()-call! Fix it.";
		alert(msg);
		throw msg;
	},
	// TODO if we're sure everything is fixed, remove these warnings.
	js: function() {
		this.__giveError("js");
	},
	jsNew_: function() {
		this.__giveError("jsNew:");
	},
	js_: function() {
		this.__giveError("js:");
	},
	slot_be_: function() {
		this.__giveError("slot:be:");
	},
	slot_: function() {
		this.__giveError("slot:");
	},
	slot_apply_: function() {
		this.__giveError("slot:apply:");
	},

	_unbox: function() {
		return this;
	},
	// This never gets called, we just need a true-ish slot in each box-instance
	_isBoxedObject: __isBoxedObject
});

// Class, that will wrap native javascript-objects to implement the Object-interface.
// Additionally, it adds accessor-methods for all fields to provide a squeak-API to
// set slots on javascript-objects.
Class("_Box", {
	superclass: _DoesNotUnderstandClass_,
	// regarding this method, see _Object._isBoxedObject
	instanceMethods: { _isBoxedObject: __isBoxedObject }});

// Functions to bootstrap primitive values and wrap them into 'squeak'-objects
// Most functions are used in translated code directly, to avoid switch-statement in _boxObject()
// (Instead of bool(), compiled code uses _true/_false directly. bool() is used in kernel_primitives.js etc.)
var bool = function(aBool) { if (aBool) { return _true; } else { return _false; } }
var character = function(aString) { return Character._wrapping(aString); }
var string = function(aString) { return ByteString._wrapping(aString); }
var number = function(aNumber) { return Float._wrapping(aNumber); }
var array = function(anArray) { return _Array._wrapping(anArray); }
var object = function(anObject) { return _Box._wrapping(anObject); }
// if we box a javascript function into a smalltalk block we must bind it on creation
// Non-local-return handling is not required here
var boundBlock = function(func, that) {
	var b = BlockClosure._newInstance();
	// This block is unboxed to func, but additional things happen on evaluation
	b.original$ = func;
	b.evaluated$ = function() {
		return _boxObject(func.apply(that, _unboxIterable(arguments)));
	}
	b.constructorArguments$ = function(argumentCollection) {
		// When using a library-function as constructor, unpack the arguments
		return _unboxIterable(argumentCollection);
	}
	return b;
}

// There are multiple js-'classes', that will be wrapped into a Squeak-Array
var arrayConstructors = [Array, NodeList];
var isArrayObject = function(anObject) {
	var constructor = anObject.constructor;
	for (index in arrayConstructors) {
		if (arrayConstructors[index] == constructor) {
			return true;
		}
	}
	return false;
};

// This static unboxing-function is added to avoid adding an _unbox method to native js-objects
var _unboxObject = function(anyObject) {
	if (anyObject != undefined && anyObject != null && anyObject._isBoxedObject) {
		return anyObject._unbox();
	}
	return anyObject;
};
var _unboxIterable = function(iterable) {
	var unboxed = [];
	for (index in iterable) {
		unboxed.push(_unboxObject(iterable[index]));
	}
	return unboxed;
}
var _unboxSlotObject = function(slotObject) {
	// This unboxes all slot-values of the object. The value does not need to be returned.
	// This is used in serialization of Slot-Objects (S2JSlotObject >> fillInstVars:guardedBy:)
	for (index in slotObject) {
		slotObject[index] = _unboxObject(slotObject[index]);
	}
}
// The 'that' parameter is optional and will be undefined otherwise
// It is relevant for functions, to bind them to their containing object when invoking them.
var _boxObject = function(nativeObject, that) {
	if (nativeObject === null || nativeObject === undefined) {
		return nil;
	}
	if (!nativeObject._isBoxedObject) {
		switch( typeof(nativeObject) ) {
			case "number": return number(nativeObject); break;
			case "string": return string(nativeObject); break;
			case "boolean": return bool(nativeObject); break;
			case "function": return boundBlock(nativeObject, that); break;
			case "object":
				if (isArrayObject(nativeObject)) {
					return array(nativeObject);
				} else {
					return object(nativeObject);
				}
				break;
			default:
				alert("Could not box creepy object: " + nativeObject);
		}
    }
	// nativeObject is already boxed!
	return nativeObject;
};
var _boxIterable = function(iterable) {
	var boxed = [];
	for (index in iterable) {
		boxed.push(_boxObject(iterable[index]));
	}
	return boxed;
}

// These boxing classes box fixed, immutable values
False._addInstanceMethods( { _unbox: function() { return false; } } );
True._addInstanceMethods( { _unbox: function() { return true; } } );
UndefinedObject._addInstanceMethods( { _unbox: function() { return null; } } );

// This DummyClass implements doesNotUnderstand: returning nil. This enables correct behaviour
// Of the _Box-class. An instance of _Box needs an instance of such a Dummy to implement the Object-interface.
// This Dummy-instance is invoked, if the original$-object does not have the queried slot.
Class("_DummyClass", {superclass: _Object, instanceMethods: { doesNotUnderstand_: function() { return nil; }}});
var _wrappingImpl = function(originalObject) {
	var result = this._newInstance(); // Polymorphic for different kinds of boxes
	result.original$ = originalObject;
	return result;
};
// These boxing classes box variable values and are all added the same functionality.
var boxingClasses = [_Box, ByteString, _Number, Character, BlockClosure, _Array];
for (index in boxingClasses) {
	var aClass = boxingClasses[index];
	aClass._addClassMethods({
		_wrapping: _wrappingImpl
	});
	aClass._addInstanceMethods({
		_hiddenGetter_: function(slotName) {
			return this.original$[slotName];
		},
		doesNotUnderstand_: function(aMessage) {
			var methodName = _unboxObject(aMessage.selector());
			if (methodName[methodName.length - 1] == ':') {
				// setter. Set the unboxed, native-js, value.
				var value = aMessage._arguments();
				if (value.length >= 1) // If more then one argument, ignore the rest!
					value = value[0];
				else // No arguments given when invoking setter!? Don't set an empty array.
					value = undefined;

				this.original$[methodName.substring(0, methodName.length - 1)] = _unboxObject(value);
				return value;
			} else {
				// getter. Second parameter relevant, if slot contains a function.
				// For most boxing classes, the javascript-native is hidden totally (this implementation).
				// _Box refines this method (_hiddenGetter_) to also check the underlying original$ for the slot
				// An example is the slot 'value', which is important on a DOM-TextArea and also implemented in Object
				return _boxObject(this._hiddenGetter_(methodName), this.original$);
			}
		},
		_unbox: function() {
			return this.original$;
		}
	});
}
_Box._addClassMethods({
	_wrapping: function(originalObject) {
		// In addition to the default original$-slot, also create a dummy-Object-instance.
		// This is a hack to implement the Object-protocol in a _Box. _Box inherits from _DoesNotUnderstandClass_,
		// so it does not implement any of Object's methods (to be able to fully access the underlying native object).
		// If the underlying object does not contain a certain slot, the method is invoked on the dummy-instance instead.
		// This way we have methods like #hash and #ifNil:ifNotNil: on boxed native objects.
		var result = _wrappingImpl.apply(this, arguments);
		result.dummyObject$ = _DummyClass._newInstance();
		return result;
	}
});
_Box._addInstanceMethods({
	_hiddenGetter_: function(slotName) {
		var result = this.original$[slotName];
		// First check, if the underlying object has this slot.
		// If not, try to invoke the corresponding Method implemented on Object (e.g. ifNil:ifNotNil:)
		// If this is not present, return nil.
		if (result === undefined) {
			// If not, invoke it on our 'dummyObject' to implement the Object-protocol of Squeak.
			// As this covers only 'getters', invoke without arguments.
			// This returns nil, if there is no such method. This corresponds to the javascript-behaviour,
			// when querying a slot, that is not present.
			result = this.dummyObject$[slotName]();
		}
		return result;
	}
});
<|endoftext|>


<commit_before>module.bootstrap.install = def(
  [
     module.config.builtins,
    module.config.config,
    module.config.specs,
    module.mapper.mapper,
    module.bootstrap.deferred,
    module.runtime,
    ephox.bolt.kernel.fp.functions
  ],

  function (builtins, config, specs, mapper, deferred, runtime, fn) {
    var install = function (pather) {
      var configure = function (configuration) {
        var bolt = config.configure(configuration, pather, builtins.browser);

        runtime.define = bolt.define;
        runtime.require = bolt.require;
        runtime.demand = bolt.demand;

        deferred.configured(runtime.require);
      };

      runtime.configure = configure;
      runtime.source = specs.source;
      runtime.type = specs.type;
      runtime.modulator = specs.type; // FIX transitioning to type, kill after Wed 7th December.
      runtime.require = deferred.require;
      runtime.main = function (id, configs, callback) {
        runtime.require(configs || [], function () {
          callback && callback.apply(null, arguments);
          runtime.require([id], fn.apply);
        });
      };
    };

    return {
      install: install
    };
  }
);
<commit_msg>Added arguments to main.<commit_after>module.bootstrap.install = def(
  [
    module.config.builtins,
    module.config.config,
    module.config.specs,
    module.mapper.mapper,
    module.bootstrap.deferred,
    module.runtime
  ],

  function (builtins, config, specs, mapper, deferred, runtime) {
    var install = function (pather) {
      var configure = function (configuration) {
        var bolt = config.configure(configuration, pather, builtins.browser);

        runtime.define = bolt.define;
        runtime.require = bolt.require;
        runtime.demand = bolt.demand;

        deferred.configured(runtime.require);
      };

      var main = function (id, args, configs, callback) {
        runtime.require(configs || [], function () {
          callback && callback.apply(null, arguments);
          runtime.require([id], function (module) {
            module.apply(null, args);
          });
        });
      };

      runtime.configure = configure;
      runtime.source = specs.source;
      runtime.type = specs.type;
      runtime.modulator = specs.type; // FIX transitioning to type, kill after Wed 7th December.
      runtime.require = deferred.require;
      runtime.main = main;
    };

    return {
      install: install
    };
  }
);
<|endoftext|>


<commit_before>import assert from 'assert';
import gitHub from 'github-basic';
import Promise from 'promise';
import request from 'then-request';
import {maxSatisfying} from 'semver';

const client = gitHub({version: 3, auth: process.env.GITHUB_TOKEN});

function maxVersion(releases) {
  return maxSatisfying(
    releases.filter(
      release => /^v\d+\.\d+\.\d+$/.test(release.version),
    ).map(
      release => release.version.substr(1),
    ),
    '*',
  );
}
function getNodeVersion() {
  return Promise.all([
    request('https://nodejs.org/download/release/index.json')
      .getBody('utf8')
      .then(JSON.parse),
    request('https://index.docker.io/v1/repositories/circleci/node/tags')
      .getBody('utf8')
      .then(JSON.parse),
  ])
    .then(([releases, circleCITags]) => {
      return {
        isLTS: releases.reduce((all, release) => {
          if (/^v\d+\.\d+\.\d+$/.test(release.version)) {
            all[release.version.substr(1)] = !!release.lts;
          }
          return all;
        }, {}),
        stable: maxVersion(releases),
        lts: maxVersion(releases.filter(release => !!release.lts)),
        stable_circle: maxVersion(releases.filter(release => {
          return circleCITags.some(tag => 'v' + tag.name === release.version)
        })),
        lts_circle: maxVersion(releases.filter(release => {
          return !!release.lts && circleCITags.some(tag => 'v' + tag.name === release.version)
        }))
      };
    });
}

function getContent(owner, repo, path) {
  return client.get('/repos/:owner/:repo/contents/:path', {
    owner,
    repo,
    path,
  }).then(result => {
    assert(result.type === 'file', 'Expected result.type to be a file');
    assert(
      typeof result.content === 'string',
      'Expected result.content to be a string. This validation is security critical.',
    );
    return (new Buffer(result.content, result.encoding)).toString('utf8');
  });
}
function tryGetContent(owner, repo, path) {
  return getContent(owner, repo, path).then(
    content => ({exists: true, content}),
    err => {
      if (err.statusCode === 404) return {exists: false};
      else throw err;
    },
  );
}

function needsUpdate(owner, repo, version) {
  return Promise.all([
    getContent(owner, repo, 'package.json'),
    tryGetContent(owner, repo, '.circleci/config.yml'),
  ]).then(([oldPackageSrc, circle2]) => {
    const oldPackage = JSON.parse(oldPackageSrc);

    // If engines are already up to date, our work here is done
    if (
      oldPackage.engines.node === version.lts ||
      oldPackage.engines.node === version.stable
    ) {
      return false;
    }
    const mode = (
      (version.isLTS[oldPackage.engines.node] ? 'lts' : 'stable') +
      (circle2.exists ? '_circle' : '')
    );
    const branch = 'node-' + version[mode];
    return client.get('/repos/:owner/:repo/branches/:branch', {owner, repo, branch}).then(
      b => {
        assert(b.name === branch);
        // if the branch exists, the bot doesn't need to do anything more
        return false;
      },
      err => {
        if (err.statusCode !== 404) throw err;
        return mode;
      },
    );
  });
}

function updateRepo(owner, repo, version, {dryRun = false} = {}) {
  return needsUpdate(owner, repo, version).then(mode => {
    if (!mode) return [];
    console.log('Updating ' + owner + '/' + repo);
    return Promise.all([
      getContent(owner, repo, 'package.json'),
      tryGetContent(owner, repo, '.travis.yml'),
      tryGetContent(owner, repo, 'circle.yml'),
      tryGetContent(owner, repo, '.circleci/config.yml'),
    ]).then(([pkg, travis, circle, circle2]) => {
      const updates = [];
      const newPkg = pkg.replace(/\"node\"\: \"\d+\.\d+\.\d+\"/g, '"node": "' + version[mode] + '"');
      assert(newPkg !== pkg, 'Expected package.json to be edited');
      assert(
        JSON.parse(newPkg).engines.node === version[mode],
        'Expected package.json to be updated to current version',
      );
      updates.push({
        path: 'package.json',
        content: newPkg,
      });
      if (travis.exists) {
        const newTravisA = travis.content.replace(
          /node\_js\:\n {2}\- \"\d+\.\d+\.\d+\"/g,
          'node_js:\n  - "' + version[mode] + '"',
        );
        assert(travis.content !== newTravisA, 'Expected .travis.yml to be edited');

        const newTravisB = newTravisA.replace(
          /node\_js\: \d+\.\d+\.\d+/g,
          'node_js: ' + version[mode],
        );
        assert(newTravisA !== newTravisB, 'Expected .travis.yml to be edited');
        updates.push({
          path: '.travis.yml',
          content: newTravisB,
        });
      }
      if (circle.exists) {
        const newCircle = circle.content.replace(
          /node\:\n {4}version\: \d+\.\d+\.\d+/g,
          'node:\n    version: ' + version[mode],
        );
        assert(circle.content !== newCircle, 'Expected circle.yml to be edited');
        updates.push({
          path: 'circle.yml',
          content: newCircle,
        });
      }
      if (circle2.exists) {
        const newCircle2 = circle2.content.replace(
          /node\:\d+\.\d+\.\d+/g,
          'node:' + version[mode],
        );
        assert(circle2.content !== newCircle2, 'Expected .circleci/config.yml to be edited');
        updates.push({
          path: '.circleci/config.yml',
          content: newCircle2,
        });
      }
      const commit = {
        branch,
        message: 'Update to node v' + version[mode],
        updates,
      };
      const calls = [
        {method: 'branch', args: [owner, repo, 'master', branch]},
        {method: 'commit', args: [owner, repo, commit]},
        {
          method: 'pull',
          args: [
            {
              user: owner,
              repo,
              branch,
            },
            {
              user: owner,
              repo,
              branch: 'master',
            },
            {
              title: 'Update to node v' + version[mode],
              body: (
                'This is an automated pull request to update the version of node.js. You can ' +
                'find release notes for what changed in this release at ' +
                'https://nodejs.org/en/blog/release/v' + version[mode] + '/' +
                '\n\n' +
                'If integration tests pass, this pull request can be safely merged.'
              ),
            },
          ],
        },
      ];
      if (dryRun) {
        return calls;
      } else {
        return calls.reduce((ready, call) => {
          return ready.then(() => client[call.method](...call.args));
        }, Promise.resolve(null)).then(() => calls);
      }
    });
  });
}

export default function (data) {
  return getNodeVersion().then(
    version => {
      return Promise.all([
        updateRepo('ForbesLindesay', 'forbeslindesay-bots', version, data),
        updateRepo('ForbesLindesay', 'tempjs.org', version, data),
        updateRepo('esdiscuss', 'bot', version, data),
        updateRepo('esdiscuss', 'esdiscuss.org', version, data),
        updateRepo('readable-email', 'readable-email-bot', version, data),
        updateRepo('readable-email', 'readable-email-site', version, data),
        updateRepo('jepso', 'MAPS', version, data),
        updateRepo('jepso', 'canoeslalomentries', version, data),
      ]);
    },
  );
}
<commit_msg>Fix lint etc<commit_after>import assert from 'assert';
import gitHub from 'github-basic';
import Promise from 'promise';
import request from 'then-request';
import {maxSatisfying} from 'semver';

const client = gitHub({version: 3, auth: process.env.GITHUB_TOKEN});

function maxVersion(releases) {
  return maxSatisfying(
    releases.filter(
      release => /^v\d+\.\d+\.\d+$/.test(release.version),
    ).map(
      release => release.version.substr(1),
    ),
    '*',
  );
}
function getNodeVersion() {
  return Promise.all([
    request('https://nodejs.org/download/release/index.json')
      .getBody('utf8')
      .then(JSON.parse),
    request('https://index.docker.io/v1/repositories/circleci/node/tags')
      .getBody('utf8')
      .then(JSON.parse),
  ])
    .then(([releases, circleCITags]) => {
      return {
        isLTS: releases.reduce((all, release) => {
          if (/^v\d+\.\d+\.\d+$/.test(release.version)) {
            all[release.version.substr(1)] = !!release.lts;
          }
          return all;
        }, {}),
        stable: maxVersion(releases),
        lts: maxVersion(releases.filter(release => !!release.lts)),
        stable_circle: maxVersion(releases.filter(release => {
          return circleCITags.some(tag => 'v' + tag.name === release.version);
        })),
        lts_circle: maxVersion(releases.filter(release => {
          return !!release.lts && circleCITags.some(tag => 'v' + tag.name === release.version);
        })),
      };
    });
}

function getContent(owner, repo, path) {
  return client.get('/repos/:owner/:repo/contents/:path', {
    owner,
    repo,
    path,
  }).then(result => {
    assert(result.type === 'file', 'Expected result.type to be a file');
    assert(
      typeof result.content === 'string',
      'Expected result.content to be a string. This validation is security critical.',
    );
    return (new Buffer(result.content, result.encoding)).toString('utf8');
  });
}
function tryGetContent(owner, repo, path) {
  return getContent(owner, repo, path).then(
    content => ({exists: true, content}),
    err => {
      if (err.statusCode === 404) return {exists: false};
      else throw err;
    },
  );
}

function needsUpdate(owner, repo, version) {
  return Promise.all([
    getContent(owner, repo, 'package.json'),
    tryGetContent(owner, repo, '.circleci/config.yml'),
  ]).then(([oldPackageSrc, circle2]) => {
    const oldPackage = JSON.parse(oldPackageSrc);

    // If engines are already up to date, our work here is done
    if (
      oldPackage.engines.node === version.lts ||
      oldPackage.engines.node === version.stable
    ) {
      return false;
    }
    const mode = (
      (version.isLTS[oldPackage.engines.node] ? 'lts' : 'stable') +
      (circle2.exists ? '_circle' : '')
    );
    const branch = 'node-' + version[mode];
    return client.get('/repos/:owner/:repo/branches/:branch', {owner, repo, branch}).then(
      b => {
        assert(b.name === branch);
        // if the branch exists, the bot doesn't need to do anything more
        return false;
      },
      err => {
        if (err.statusCode !== 404) throw err;
        return mode;
      },
    );
  });
}

function updateRepo(owner, repo, version, {dryRun = false} = {}) {
  return needsUpdate(owner, repo, version).then(mode => {
    if (!mode) return [];
    console.log('Updating ' + owner + '/' + repo);
    return Promise.all([
      getContent(owner, repo, 'package.json'),
      tryGetContent(owner, repo, '.travis.yml'),
      tryGetContent(owner, repo, 'circle.yml'),
      tryGetContent(owner, repo, '.circleci/config.yml'),
    ]).then(([pkg, travis, circle, circle2]) => {
      const branch = 'node-' + version[mode];
      const updates = [];
      const newPkg = pkg.replace(/\"node\"\: \"\d+\.\d+\.\d+\"/g, '"node": "' + version[mode] + '"');
      assert(newPkg !== pkg, 'Expected package.json to be edited');
      assert(
        JSON.parse(newPkg).engines.node === version[mode],
        'Expected package.json to be updated to current version',
      );
      updates.push({
        path: 'package.json',
        content: newPkg,
      });
      if (travis.exists) {
        const newTravisA = travis.content.replace(
          /node\_js\:\n {2}\- \"\d+\.\d+\.\d+\"/g,
          'node_js:\n  - "' + version[mode] + '"',
        );
        assert(travis.content !== newTravisA, 'Expected .travis.yml to be edited');

        const newTravisB = newTravisA.replace(
          /node\_js\: \d+\.\d+\.\d+/g,
          'node_js: ' + version[mode],
        );
        assert(newTravisA !== newTravisB, 'Expected .travis.yml to be edited');
        updates.push({
          path: '.travis.yml',
          content: newTravisB,
        });
      }
      if (circle.exists) {
        const newCircle = circle.content.replace(
          /node\:\n {4}version\: \d+\.\d+\.\d+/g,
          'node:\n    version: ' + version[mode],
        );
        assert(circle.content !== newCircle, 'Expected circle.yml to be edited');
        updates.push({
          path: 'circle.yml',
          content: newCircle,
        });
      }
      if (circle2.exists) {
        const newCircle2 = circle2.content.replace(
          /node\:\d+\.\d+\.\d+/g,
          'node:' + version[mode],
        );
        assert(circle2.content !== newCircle2, 'Expected .circleci/config.yml to be edited');
        updates.push({
          path: '.circleci/config.yml',
          content: newCircle2,
        });
      }
      const commit = {
        branch,
        message: 'Update to node v' + version[mode],
        updates,
      };
      const calls = [
        {method: 'branch', args: [owner, repo, 'master', branch]},
        {method: 'commit', args: [owner, repo, commit]},
        {
          method: 'pull',
          args: [
            {
              user: owner,
              repo,
              branch,
            },
            {
              user: owner,
              repo,
              branch: 'master',
            },
            {
              title: 'Update to node v' + version[mode],
              body: (
                'This is an automated pull request to update the version of node.js. You can ' +
                'find release notes for what changed in this release at ' +
                'https://nodejs.org/en/blog/release/v' + version[mode] + '/' +
                '\n\n' +
                'If integration tests pass, this pull request can be safely merged.'
              ),
            },
          ],
        },
      ];
      if (dryRun) {
        return calls;
      } else {
        return calls.reduce((ready, call) => {
          return ready.then(() => client[call.method](...call.args));
        }, Promise.resolve(null)).then(() => calls);
      }
    });
  });
}

export default function (data) {
  return getNodeVersion().then(
    version => {
      return Promise.all([
        updateRepo('ForbesLindesay', 'forbeslindesay-bots', version, data),
        updateRepo('ForbesLindesay', 'tempjs.org', version, data),
        updateRepo('esdiscuss', 'bot', version, data),
        updateRepo('esdiscuss', 'esdiscuss.org', version, data),
        updateRepo('readable-email', 'readable-email-bot', version, data),
        updateRepo('readable-email', 'readable-email-site', version, data),
        updateRepo('jepso', 'MAPS', version, data),
        updateRepo('jepso', 'canoeslalomentries', version, data),
      ]);
    },
  );
}
<|endoftext|>