<commit_before>var data_array={
"20160326":2,
"20160325":5.5,
"20160324":5,
"20160323":4,
"20160322":2.5,
"20160321":5.5,
"20160320":2,
"20160319":0.5,
"20160318":6,
"20160317":0,
"20160316":0,
"20160315":1.5,
"20160314":0,
"20160313":2,
"20160312":2,
"20160311":0,
"20160310":5,
"20160309":1,
"20160308":0,
"20160307":5,
"20160306":7,
"20160305":3,
"20160304":6,
"20160303":3,
"20160302":6,
"20160301":7,
"20160229":7,
"20160228":7,
"20160227":3,
"20160226":2,
"20160225":2.5,
"20160224":5.5,
"20160223":5,
"20160222":7,
"20160221":3.5,
"20160220":3,
"20160219":7,
"20160218":7,
"20160217":6,
"20160216":5.5,
"20160215":6,
"20160214":3.5,
"20160213":0,
"20160212":4,
"20160211":5,
"20160210":7,
"20160209":6,
"20160208":5,
"20160207":0,
"20160206":0,
"20160205":3,
"20160204":5,
"20160203":5,
"20160202":4,
"20160201":6,
"20160131":3,
"20160130":0,
"20160129":7,
"20160128":7,
"20160127":6.5,
"20160126":5,
"20160125":7,
"20160124":3,
"20160123":0,
"20160122":7,
"20160121":7,
"20160120":7,
"20160119":6,
"20160118":5,
"20160117":0,
"20160116":1,
"20160115":4,
"20160114":5,
"20160113":5,
"20160112":5,
"20160111":5,
"20160110":3,
"20160109":0,
"20160108":5.5,
"20160107":5,
"20160106":5,
"20160105":5,
"20160104":4.5,
"20160103":0,
"20160102":2,
"20160101":0,
"20151231":0,
"20151230":1.5,
"20151229":2,
"20151228":2,
"20151227":3.5,
"20151226":1.5,
"20151225":0,
"20151224":0,
"20151223":2.5,
"20151222":3,
"20151221":2,
"20151220":4,
"20151219":2,
"20151218":4,
"20151217":4.5,
"20151216":4,
"20151215":4,
"20151214":5,
"20151213":4,
"20151212":4,
"20151211":4.5,
"20151210":7,
"20151209":6,
"20151208":5,
"20151207":7,
"20151206":4,
"20151205":7,
"20151204":4,
"20151203":5.5,
"20151202":6,
"20151201":4.5,
"20151130":5,
"20151129":4,
"20151128":4
};

var width = 900,
    height = 120,
    cellSize = 15; // cell size
    month = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
    color = ["#eee","#d6e685","#8cc665","#44a340","#1e6823"];
    range = [0,4,5,7];

var day = d3.time.format("%w"),
    week = d3.time.format("%U"),
    percent = d3.format(".1%"),
	format = d3.time.format("%Y%m%d");
	parseDate = d3.time.format("%Y%m%d").parse;

var svg = d3.select(".calender-map").selectAll("svg")
    .data(d3.range(2015, 2017))
  .enter().append("svg")
    .attr("width", '100%')
    .attr("data-height", '0.5678')
    .attr("viewBox",'0 0 ' + width + ' ' + height)
  .append("g")
    .attr("transform", "translate(" + ((width - cellSize * 53) / 2) + "," + (height - cellSize * 7 - 1) + ")");

svg.append("text")
    .attr("transform", "translate(-10," + cellSize * 3.5 + ")rotate(-90)")
    .style("text-anchor", "middle")
    .text(function(d) { return d; });

var rect = svg.selectAll(".day")
    .data(function(d) { return d3.time.days(new Date(d, 0, 1), new Date(d + 1, 0, 1)); })
  .enter()
	.append("rect")
    .attr("class", "day")
    .attr("width", cellSize)
    .attr("height", cellSize)
    .attr("x", function(d) { return week(d) * cellSize; })
    .attr("y", function(d) { return day(d) * cellSize; })
    .attr("fill",'#fff')
    .datum(format);

var legend = svg.selectAll(".legend")
      .data(month)
    .enter().append("g")
      .attr("class", "legend")
      .attr("transform", function(d, i) { return "translate(" + (((i+1) * 50)+8) + ",0)"; });

svg.selectAll(".month")
    .data(function(d) { return d3.time.months(new Date(d, 0, 1), new Date(d + 1, 0, 1)); })
  .enter().append("path")
    .attr("class", "month")
    .attr("d", monthPath);

function getRange(d) {
  for (i = 1; i < range.length; i++) {
    if (d < range[i])
      return i;
  }
  return -1;
}

function getColor(d) {
  if (d == 0)
    return color[0];
  if (d >= range[range.length - 1])
    return color[range.length];
  index = getRange(d);
  change = d3.scale.linear().range([color[index - 1], color[index]])
    .domain([range[index - 1], range[index]])
  return change(d)
}

  rect
      .attr("fill", function(d) {if (isNaN(data_array[d])) return color[0];  return getColor(data_array[d]); })
	  .attr("data-title", function(d) { if (isNaN(data_array[d])) ret = "No record on "; else ret = data_array[d] + " hours on "; return ret + month[parseDate(d).getMonth()] + ". " + parseDate(d).getDate()});

d3.csv("",function() {
	$("rect").tooltip({container: 'body'});

});

function numberWithCommas(x) {
    x = x.toString();
    var pattern = /(-?\d+)(\d{3})/;
    while (pattern.test(x))
        x = x.replace(pattern, "$1,$2");
    return x;
}

function monthPath(t0) {
  var t1 = new Date(t0.getFullYear(), t0.getMonth() + 1, 0),
      d0 = +day(t0), w0 = +week(t0),
      d1 = +day(t1), w1 = +week(t1);
  return "M" + (w0 + 1) * cellSize + "," + d0 * cellSize
      + "H" + w0 * cellSize + "V" + 7 * cellSize
      + "H" + w1 * cellSize + "V" + (d1 + 1) * cellSize
      + "H" + (w1 + 1) * cellSize + "V" + 0
      + "H" + (w0 + 1) * cellSize + "Z";
}

<commit_msg>tracker<commit_after>var data_array={
"20160328":7,
"20160327":4.5,
"20160326":2,
"20160325":5.5,
"20160324":5,
"20160323":4,
"20160322":2.5,
"20160321":5.5,
"20160320":2,
"20160319":0.5,
"20160318":6,
"20160317":0,
"20160316":0,
"20160315":1.5,
"20160314":0,
"20160313":2,
"20160312":2,
"20160311":0,
"20160310":5,
"20160309":1,
"20160308":0,
"20160307":5,
"20160306":7,
"20160305":3,
"20160304":6,
"20160303":3,
"20160302":6,
"20160301":7,
"20160229":7,
"20160228":7,
"20160227":3,
"20160226":2,
"20160225":2.5,
"20160224":5.5,
"20160223":5,
"20160222":7,
"20160221":3.5,
"20160220":3,
"20160219":7,
"20160218":7,
"20160217":6,
"20160216":5.5,
"20160215":6,
"20160214":3.5,
"20160213":0,
"20160212":4,
"20160211":5,
"20160210":7,
"20160209":6,
"20160208":5,
"20160207":0,
"20160206":0,
"20160205":3,
"20160204":5,
"20160203":5,
"20160202":4,
"20160201":6,
"20160131":3,
"20160130":0,
"20160129":7,
"20160128":7,
"20160127":6.5,
"20160126":5,
"20160125":7,
"20160124":3,
"20160123":0,
"20160122":7,
"20160121":7,
"20160120":7,
"20160119":6,
"20160118":5,
"20160117":0,
"20160116":1,
"20160115":4,
"20160114":5,
"20160113":5,
"20160112":5,
"20160111":5,
"20160110":3,
"20160109":0,
"20160108":5.5,
"20160107":5,
"20160106":5,
"20160105":5,
"20160104":4.5,
"20160103":0,
"20160102":2,
"20160101":0,
"20151231":0,
"20151230":1.5,
"20151229":2,
"20151228":2,
"20151227":3.5,
"20151226":1.5,
"20151225":0,
"20151224":0,
"20151223":2.5,
"20151222":3,
"20151221":2,
"20151220":4,
"20151219":2,
"20151218":4,
"20151217":4.5,
"20151216":4,
"20151215":4,
"20151214":5,
"20151213":4,
"20151212":4,
"20151211":4.5,
"20151210":7,
"20151209":6,
"20151208":5,
"20151207":7,
"20151206":4,
"20151205":7,
"20151204":4,
"20151203":5.5,
"20151202":6,
"20151201":4.5,
"20151130":5,
"20151129":4,
"20151128":4
};

var width = 900,
    height = 120,
    cellSize = 15; // cell size
    month = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
    color = ["#eee","#d6e685","#8cc665","#44a340","#1e6823"];
    range = [0,4,5,7];

var day = d3.time.format("%w"),
    week = d3.time.format("%U"),
    percent = d3.format(".1%"),
	format = d3.time.format("%Y%m%d");
	parseDate = d3.time.format("%Y%m%d").parse;

var svg = d3.select(".calender-map").selectAll("svg")
    .data(d3.range(2015, 2017))
  .enter().append("svg")
    .attr("width", '100%')
    .attr("data-height", '0.5678')
    .attr("viewBox",'0 0 ' + width + ' ' + height)
  .append("g")
    .attr("transform", "translate(" + ((width - cellSize * 53) / 2) + "," + (height - cellSize * 7 - 1) + ")");

svg.append("text")
    .attr("transform", "translate(-10," + cellSize * 3.5 + ")rotate(-90)")
    .style("text-anchor", "middle")
    .text(function(d) { return d; });

var rect = svg.selectAll(".day")
    .data(function(d) { return d3.time.days(new Date(d, 0, 1), new Date(d + 1, 0, 1)); })
  .enter()
	.append("rect")
    .attr("class", "day")
    .attr("width", cellSize)
    .attr("height", cellSize)
    .attr("x", function(d) { return week(d) * cellSize; })
    .attr("y", function(d) { return day(d) * cellSize; })
    .attr("fill",'#fff')
    .datum(format);

var legend = svg.selectAll(".legend")
      .data(month)
    .enter().append("g")
      .attr("class", "legend")
      .attr("transform", function(d, i) { return "translate(" + (((i+1) * 50)+8) + ",0)"; });

svg.selectAll(".month")
    .data(function(d) { return d3.time.months(new Date(d, 0, 1), new Date(d + 1, 0, 1)); })
  .enter().append("path")
    .attr("class", "month")
    .attr("d", monthPath);

function getRange(d) {
  for (i = 1; i < range.length; i++) {
    if (d < range[i])
      return i;
  }
  return -1;
}

function getColor(d) {
  if (d == 0)
    return color[0];
  if (d >= range[range.length - 1])
    return color[range.length];
  index = getRange(d);
  change = d3.scale.linear().range([color[index - 1], color[index]])
    .domain([range[index - 1], range[index]])
  return change(d)
}

  rect
      .attr("fill", function(d) {if (isNaN(data_array[d])) return color[0];  return getColor(data_array[d]); })
	  .attr("data-title", function(d) { if (isNaN(data_array[d])) ret = "No record on "; else ret = data_array[d] + " hours on "; return ret + month[parseDate(d).getMonth()] + ". " + parseDate(d).getDate()});

d3.csv("",function() {
	$("rect").tooltip({container: 'body'});

});

function numberWithCommas(x) {
    x = x.toString();
    var pattern = /(-?\d+)(\d{3})/;
    while (pattern.test(x))
        x = x.replace(pattern, "$1,$2");
    return x;
}

function monthPath(t0) {
  var t1 = new Date(t0.getFullYear(), t0.getMonth() + 1, 0),
      d0 = +day(t0), w0 = +week(t0),
      d1 = +day(t1), w1 = +week(t1);
  return "M" + (w0 + 1) * cellSize + "," + d0 * cellSize
      + "H" + w0 * cellSize + "V" + 7 * cellSize
      + "H" + w1 * cellSize + "V" + (d1 + 1) * cellSize
      + "H" + (w1 + 1) * cellSize + "V" + 0
      + "H" + (w0 + 1) * cellSize + "Z";
}

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint evil: true */

/*global $, brackets, define, describe, it, xit, expect, beforeEach, afterEach, waitsFor, waitsForDone, runs, window, spyOn, jasmine */

define(function (require, exports, module) {
    "use strict";

    var SpecRunnerUtils = brackets.getModule("spec/SpecRunnerUtils"),
        FileUtils       = brackets.getModule("file/FileUtils");

    describe("LiveDevelopment2", function () {

        // load from testWindow
        var testWindow,
            brackets,
            extensionRequire,
            CommandManager,
            Commands,
            EditorManager,
            DocumentManager,
            LiveDevelopment,
            LiveDevProtocol,
            LiveHTMLDocument,
            editor;

        var testFolder = FileUtils.getNativeModuleDirectoryPath(module) + "/unittest-files/",
            tempDir = SpecRunnerUtils.getTempDirectory(),
            allSpacesRE = /\s+/gi;

        beforeEach(function () {
            // Create a new window that will be shared by ALL tests in this spec.
            if (!testWindow) {
                runs(function () {
                    SpecRunnerUtils.createTestWindowAndRun(this, function (w) {
                        testWindow = w;
                        // Load module instances from brackets.test
                        brackets = testWindow.brackets;
                        CommandManager = brackets.test.CommandManager;
                        Commands = brackets.test.Commands;
                        EditorManager = brackets.test.EditorManager;
                        DocumentManager = brackets.test.DocumentManager;
                        extensionRequire = brackets.test.ExtensionLoader.getRequireContextForExtension("brackets-livedev2");
                        LiveDevelopment = extensionRequire("LiveDevelopment");
                        LiveDevProtocol = extensionRequire("protocol/LiveDevProtocol");
                    });
                });

                runs(function () {
                    SpecRunnerUtils.loadProjectInTestWindow(testFolder);
                });
            }
        });

        afterEach(function () {
            DocumentManager.closeAll();
            testWindow.close();
            testWindow = null;
            brackets = null;
            LiveDevelopment = null;
        });

        function openLiveDevelopmentAndWait() {
            runs(function () {
                LiveDevelopment.open();
            });
            waitsFor(
                function isLiveDevelopmentActive() {
                    return LiveDevelopment.status === LiveDevelopment.STATUS_ACTIVE;
                },
                "livedevelopment.done.opened",
                5000
            );
        }

        describe("Start-up - LiveDevProtocolRemote", function () {

            it("should establish a browser connection for an opened html file", function () {
                //open a file
                runs(function () {
                    waitsForDone(SpecRunnerUtils.openProjectFiles(["simple1.html"]), "SpecRunnerUtils.openProjectFiles simple1.html", 1000);
                });

                openLiveDevelopmentAndWait();

                runs(function () {
                    expect(LiveDevelopment.status).toBe(LiveDevelopment.STATUS_ACTIVE);
                });
            });

            it("should send all external stylesheets as related docs on start-up", function () {
                var liveDoc;
                runs(function () {
                    waitsForDone(SpecRunnerUtils.openProjectFiles(["simple1.html"]), "SpecRunnerUtils.openProjectFiles simple1.html", 1000);
                });
                openLiveDevelopmentAndWait();
                runs(function () {
                    liveDoc = LiveDevelopment._getCurrentLiveDoc();
                });
                waitsFor(
                    function relatedDocsReceived() {
                        return (Object.getOwnPropertyNames(liveDoc.getRelated().stylesheets).length > 0);
                    },
                    "relateddocuments.done.received",
                    10000
                );
                runs(function () {
                    expect(liveDoc.isRelated(testFolder + "simple1.css")).toBeTruthy();
                });
                runs(function () {
                    expect(liveDoc.isRelated(testFolder + "simpleShared.css")).toBeTruthy();
                });
            });

            it("should send all import-ed stylesheets as related docs on start-up", function () {
                var liveDoc;
                runs(function () {
                    waitsForDone(SpecRunnerUtils.openProjectFiles(["simple1.html"]), "SpecRunnerUtils.openProjectFiles simple1.html", 1000);
                });
                openLiveDevelopmentAndWait();
                runs(function () {
                    liveDoc = LiveDevelopment._getCurrentLiveDoc();
                });
                waitsFor(
                    function relatedDocsReceived() {
                        return (Object.getOwnPropertyNames(liveDoc.getRelated().scripts).length > 0);
                    },
                    "relateddocuments.done.received",
                    10000
                );
                runs(function () {
                    expect(liveDoc.isRelated(testFolder + "import1.css")).toBeTruthy();
                });
            });

            it("should send all external javascript files as related docs on start-up", function () {
                var liveDoc;
                runs(function () {
                    waitsForDone(SpecRunnerUtils.openProjectFiles(["simple1.html"]), "SpecRunnerUtils.openProjectFiles simple1.html", 1000);
                });
                openLiveDevelopmentAndWait();

                runs(function () {
                    liveDoc = LiveDevelopment._getCurrentLiveDoc();
                });
                waitsFor(
                    function relatedDocsReceived() {
                        return (Object.getOwnPropertyNames(liveDoc.getRelated().scripts).length > 0);
                    },
                    "relateddocuments.done.received",
                    10000
                );
                runs(function () {
                    expect(liveDoc.isRelated(testFolder + "simple1.js")).toBeTruthy();
                });
            });

            it("should send notifications for added/removed stylesheets through link nodes", function () {
                var liveDoc;
                runs(function () {
                    waitsForDone(SpecRunnerUtils.openProjectFiles(["simple1.html"]), "SpecRunnerUtils.openProjectFiles simple1.html", 1000);
                });
                openLiveDevelopmentAndWait();

                runs(function () {
                    liveDoc = LiveDevelopment._getCurrentLiveDoc();
                });

                runs(function () {
                    var curDoc =  DocumentManager.getCurrentDocument();
                    curDoc.replaceRange('<link href="simple2.css" rel="stylesheet">\n', {line: 8, ch: 0});
                });

                waitsFor(
                    function relatedDocsReceived() {
                        return (Object.getOwnPropertyNames(liveDoc.getRelated().stylesheets).length === 4);
                    },
                    "relateddocuments.done.received",
                    10000
                );

                runs(function () {
                    expect(liveDoc.isRelated(testFolder + "simple2.css")).toBeTruthy();
                });

                runs(function () {
                    var curDoc =  DocumentManager.getCurrentDocument();
                    curDoc.replaceRange('', {line: 8, ch: 0}, {line: 8, ch: 50});
                });

                waitsFor(
                    function relatedDocsReceived() {
                        return (Object.getOwnPropertyNames(liveDoc.getRelated().stylesheets).length === 3);
                    },
                    "relateddocuments.done.received",
                    10000
                );

                runs(function () {
                    expect(liveDoc.isRelated(testFolder + "simple2.css")).toBeFalsy();
                });
            });
        });
    });
});<commit_msg>rename openLiveDevelopmentAndWait<commit_after>/*
 * Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint evil: true */

/*global $, brackets, define, describe, it, xit, expect, beforeEach, afterEach, waitsFor, waitsForDone, runs, window, spyOn, jasmine */

define(function (require, exports, module) {
    "use strict";

    var SpecRunnerUtils = brackets.getModule("spec/SpecRunnerUtils"),
        FileUtils       = brackets.getModule("file/FileUtils");

    describe("LiveDevelopment2", function () {

        // load from testWindow
        var testWindow,
            brackets,
            extensionRequire,
            CommandManager,
            Commands,
            EditorManager,
            DocumentManager,
            LiveDevelopment,
            LiveDevProtocol,
            LiveHTMLDocument,
            editor;

        var testFolder = FileUtils.getNativeModuleDirectoryPath(module) + "/unittest-files/",
            tempDir = SpecRunnerUtils.getTempDirectory(),
            allSpacesRE = /\s+/gi;

        beforeEach(function () {
            // Create a new window that will be shared by ALL tests in this spec.
            if (!testWindow) {
                runs(function () {
                    SpecRunnerUtils.createTestWindowAndRun(this, function (w) {
                        testWindow = w;
                        // Load module instances from brackets.test
                        brackets = testWindow.brackets;
                        CommandManager = brackets.test.CommandManager;
                        Commands = brackets.test.Commands;
                        EditorManager = brackets.test.EditorManager;
                        DocumentManager = brackets.test.DocumentManager;
                        extensionRequire = brackets.test.ExtensionLoader.getRequireContextForExtension("brackets-livedev2");
                        LiveDevelopment = extensionRequire("LiveDevelopment");
                        LiveDevProtocol = extensionRequire("protocol/LiveDevProtocol");
                    });
                });

                runs(function () {
                    SpecRunnerUtils.loadProjectInTestWindow(testFolder);
                });
            }
        });

        afterEach(function () {
            DocumentManager.closeAll();
            testWindow.close();
            testWindow = null;
            brackets = null;
            LiveDevelopment = null;
        });

        function waitsForLiveDevelopmentToOpen() {
            runs(function () {
                LiveDevelopment.open();
            });
            waitsFor(
                function isLiveDevelopmentActive() {
                    return LiveDevelopment.status === LiveDevelopment.STATUS_ACTIVE;
                },
                "livedevelopment.done.opened",
                5000
            );
        }

        describe("Start-up - LiveDevProtocolRemote", function () {

            it("should establish a browser connection for an opened html file", function () {
                //open a file
                runs(function () {
                    waitsForDone(SpecRunnerUtils.openProjectFiles(["simple1.html"]), "SpecRunnerUtils.openProjectFiles simple1.html", 1000);
                });

                waitsForLiveDevelopmentToOpen();

                runs(function () {
                    expect(LiveDevelopment.status).toBe(LiveDevelopment.STATUS_ACTIVE);
                });
            });

            it("should send all external stylesheets as related docs on start-up", function () {
                var liveDoc;
                runs(function () {
                    waitsForDone(SpecRunnerUtils.openProjectFiles(["simple1.html"]), "SpecRunnerUtils.openProjectFiles simple1.html", 1000);
                });
                waitsForLiveDevelopmentToOpen();
                runs(function () {
                    liveDoc = LiveDevelopment._getCurrentLiveDoc();
                });
                waitsFor(
                    function relatedDocsReceived() {
                        return (Object.getOwnPropertyNames(liveDoc.getRelated().stylesheets).length > 0);
                    },
                    "relateddocuments.done.received",
                    10000
                );
                runs(function () {
                    expect(liveDoc.isRelated(testFolder + "simple1.css")).toBeTruthy();
                });
                runs(function () {
                    expect(liveDoc.isRelated(testFolder + "simpleShared.css")).toBeTruthy();
                });
            });

            it("should send all import-ed stylesheets as related docs on start-up", function () {
                var liveDoc;
                runs(function () {
                    waitsForDone(SpecRunnerUtils.openProjectFiles(["simple1.html"]), "SpecRunnerUtils.openProjectFiles simple1.html", 1000);
                });
                waitsForLiveDevelopmentToOpen();
                runs(function () {
                    liveDoc = LiveDevelopment._getCurrentLiveDoc();
                });
                waitsFor(
                    function relatedDocsReceived() {
                        return (Object.getOwnPropertyNames(liveDoc.getRelated().scripts).length > 0);
                    },
                    "relateddocuments.done.received",
                    10000
                );
                runs(function () {
                    expect(liveDoc.isRelated(testFolder + "import1.css")).toBeTruthy();
                });
            });

            it("should send all external javascript files as related docs on start-up", function () {
                var liveDoc;
                runs(function () {
                    waitsForDone(SpecRunnerUtils.openProjectFiles(["simple1.html"]), "SpecRunnerUtils.openProjectFiles simple1.html", 1000);
                });
                waitsForLiveDevelopmentToOpen();

                runs(function () {
                    liveDoc = LiveDevelopment._getCurrentLiveDoc();
                });
                waitsFor(
                    function relatedDocsReceived() {
                        return (Object.getOwnPropertyNames(liveDoc.getRelated().scripts).length > 0);
                    },
                    "relateddocuments.done.received",
                    10000
                );
                runs(function () {
                    expect(liveDoc.isRelated(testFolder + "simple1.js")).toBeTruthy();
                });
            });

            it("should send notifications for added/removed stylesheets through link nodes", function () {
                var liveDoc;
                runs(function () {
                    waitsForDone(SpecRunnerUtils.openProjectFiles(["simple1.html"]), "SpecRunnerUtils.openProjectFiles simple1.html", 1000);
                });
                waitsForLiveDevelopmentToOpen();

                runs(function () {
                    liveDoc = LiveDevelopment._getCurrentLiveDoc();
                });

                runs(function () {
                    var curDoc =  DocumentManager.getCurrentDocument();
                    curDoc.replaceRange('<link href="simple2.css" rel="stylesheet">\n', {line: 8, ch: 0});
                });

                waitsFor(
                    function relatedDocsReceived() {
                        return (Object.getOwnPropertyNames(liveDoc.getRelated().stylesheets).length === 4);
                    },
                    "relateddocuments.done.received",
                    10000
                );

                runs(function () {
                    expect(liveDoc.isRelated(testFolder + "simple2.css")).toBeTruthy();
                });

                runs(function () {
                    var curDoc =  DocumentManager.getCurrentDocument();
                    curDoc.replaceRange('', {line: 8, ch: 0}, {line: 8, ch: 50});
                });

                waitsFor(
                    function relatedDocsReceived() {
                        return (Object.getOwnPropertyNames(liveDoc.getRelated().stylesheets).length === 3);
                    },
                    "relateddocuments.done.received",
                    10000
                );

                runs(function () {
                    expect(liveDoc.isRelated(testFolder + "simple2.css")).toBeFalsy();
                });
            });
        });
    });
});<|endoftext|>


<commit_before>(function(h){var f=true,l=false,k=null;var d=function(o,p){return Object.prototype.toString.call(o)==="[object "+p+"]"};var m=function(o){return d(o,"Function")};var e=function(p,q){var o;for(o in p){if(p.hasOwnProperty(o)){q(p[o],o)}}};var c=function(p,o){p=p||{};e(o,function(r,q){if(d(r,"Object")){r=c(p[q],r)}p[q]=r});return p};var b=function(o){return Array.prototype.slice.call(o)};var a=function(o,p,r){var q;if(o.__decorated__){return o}q=function(){try{return o.apply(p,b(arguments))}catch(s){g.ErrorHandler.log(r+s.message)}};q.__decorated__=f;return q};var i={log:function(o){h.console&&h.console.error(o)}};var j=(function(){var s={};var p=0;var o={};var r={};var q=function(t){var u=t;return{subscribe:function(A,w,x){var v=0,z,y;if(m(w)){A=d(A,"Array")?A:[A];for(z=A.length;v<z;v++){y=A[v];o[y]=o[y]||{};if(!o[y][u]){o[y][u]=g.debugMode?function(){w.apply(x,b(arguments))}:a(w,x,'Error publishing topic "'+y+'": ');r[u]=r[u]||[];r[u].push(y)}}}},publish:function(v,x){var w=o[v];if(w){h.setTimeout(function(){e(w,function(y){y({name:v,data:x})})},0)}},unSubscribe:function(x){var x=d(x,"Array")?x:[x],v=x.length,w;while(v--){w=o[x[v]];if(w&&w[u]){delete w[u]}}},unSubscribeAll:function(){if(r[u]){this.unSubscribe(r[u])}}}};return{build:function(t){return c(q(++p),s[t]||{})},register:function(u,t){if(!s[u]){s[u]=t;return f}return l}}}());var n=(function(){var p={};var o=function(q){if(!p[q]){throw new Error('Module "'+q+'" is not registered!')}};return{register:function(s,q,r){if(!p[s]){if(!m(q)){throw new Error('The creator of module "'+s+'" is not a function!')}p[s]={fpCreator:q,sSandBoxType:r||"",oInstance:k,bIsStarted:l};return f}return l},start:function(r,q){o(r);if(!p[r].bIsStarted){if(!p[r].oInstance){p[r].oInstance=this.instanciate(r)}p[r].oInstance.onStart(q);p[r].bIsStarted=f}},stop:function(q){o(q);if(p[q].bIsStarted&&p[q].oInstance){if(m(p[q].oInstance.onStop)){p[q].oInstance.onStop()}p[q].oInstance.__sandbox__.unSubscribeAll();p[q].bIsStarted=l}},instanciate:function(s){var r,q;o(s);r=j.build(p[s].sSandBoxType);q=p[s].fpCreator(r);if(!g.debugMode){e(q,function(u,t){if(m(u)){q[t]=a(u,q,'Error in module "'+s+'" executing method "'+t+'": ')}})}q.__sandbox__=r;return q},getModules:function(){return p},}}());var g={version:"0.4.0",debugMode:l,extend:function(o){c(this,o)},Module:n,SandBox:j,ErrorHandler:i};h.TinyCore=g;if(h.define){h.define("TinyCore",g)}}(this));<commit_msg>rebuilt min version of TinyCore after IE7 fix<commit_after>(function(h){var f=true,l=false,k=null;var d=function(o,p){return Object.prototype.toString.call(o)==="[object "+p+"]"};var m=function(o){return d(o,"Function")};var e=function(p,q){var o;for(o in p){if(p.hasOwnProperty(o)){q(p[o],o)}}};var c=function(p,o){p=p||{};e(o,function(r,q){if(d(r,"Object")){r=c(p[q],r)}p[q]=r});return p};var b=function(o){return Array.prototype.slice.call(o)};var a=function(o,p,r){var q;if(o.__decorated__){return o}q=function(){try{return o.apply(p,b(arguments))}catch(s){g.ErrorHandler.log(r+s.message)}};q.__decorated__=f;return q};var i={log:function(o){h.console&&h.console.error(o)}};var j=(function(){var s={};var p=0;var o={};var r={};var q=function(t){var u=t;return{subscribe:function(A,w,x){var v=0,z,y;if(m(w)){A=d(A,"Array")?A:[A];for(z=A.length;v<z;v++){y=A[v];o[y]=o[y]||{};if(!o[y][u]){o[y][u]=g.debugMode?function(){w.apply(x,b(arguments))}:a(w,x,'Error publishing topic "'+y+'": ');r[u]=r[u]||[];r[u].push(y)}}}},publish:function(v,x){var w=o[v];if(w){h.setTimeout(function(){e(w,function(y){y({name:v,data:x})})},0)}},unSubscribe:function(x){var x=d(x,"Array")?x:[x],v=x.length,w;while(v--){w=o[x[v]];if(w&&w[u]){delete w[u]}}},unSubscribeAll:function(){if(r[u]){this.unSubscribe(r[u])}}}};return{build:function(t){return c(q(++p),s[t]||{})},register:function(u,t){if(!s[u]){s[u]=t;return f}return l}}}());var n=(function(){var p={};var o=function(q){if(!p[q]){throw new Error('Module "'+q+'" is not registered!')}};return{register:function(s,q,r){if(!p[s]){if(!m(q)){throw new Error('The creator of module "'+s+'" is not a function!')}p[s]={fpCreator:q,sSandBoxType:r||"",oInstance:k,bIsStarted:l};return f}return l},start:function(r,q){o(r);if(!p[r].bIsStarted){if(!p[r].oInstance){p[r].oInstance=this.instanciate(r)}p[r].oInstance.onStart(q);p[r].bIsStarted=f}},stop:function(q){o(q);if(p[q].bIsStarted&&p[q].oInstance){if(m(p[q].oInstance.onStop)){p[q].oInstance.onStop()}p[q].oInstance.__sandbox__.unSubscribeAll();p[q].bIsStarted=l}},instanciate:function(s){var r,q;o(s);r=j.build(p[s].sSandBoxType);q=p[s].fpCreator(r);if(!g.debugMode){e(q,function(u,t){if(m(u)){q[t]=a(u,q,'Error in module "'+s+'" executing method "'+t+'": ')}})}q.__sandbox__=r;return q},getModules:function(){return p}}}());var g={version:"0.4.0",debugMode:l,extend:function(o){c(this,o)},Module:n,SandBox:j,ErrorHandler:i};h.TinyCore=g;if(h.define){h.define("TinyCore",g)}}(this));<|endoftext|>


<commit_before>var duree = "longue";
var duration_longue = true;
var duration_courte = false;

  $(document).ready(function(){
  //on initialise les variables avec les valeurs par défaut
    var duree = "longue";
    var pub = "adu";
    var nbDePersonnes = 16;
    var sce = 1;
  //on appuie les boutons en conséquence
    $("#dur_lon").addClass("active");
    $("#pub_adu").addClass("active");
    $("#sce_1").addClass("active");
    //$("#car").load('carousel_long.html');

    //On remplit le champ du bouton +/- avec la valeur par défaut
    $("#inputnb").val(nbDePersonnes);

    //var carousel_c = $.get("carousel_court.html");
    //var carousel_l = $.get("carousel_long.html");
  //On change la valeur des variables en fonction des actions utilisateurs
  //Pour la durée :
    $("#dur_cou").click(function(e){
      duree = "courte";
      duration_courte = true;
      duration_longue = false;
      $("#dur_lon").removeClass("active");
      $("#dur_cou").addClass("active");
      //var code = load("carousel_court.html");
      //$("#myCarousel").replaceWith("
 This text is strong
  This text is italic
");
      //alert(carousel_c);
      //$("#car").empty();
      $("#car").load('carousel_court.html');
      $("#p1").show();
      alert("Chargement terminé \n Guide pour atelier court !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();});
    });
    $("#dur_lon").click(function(e){
      duree = "longue";
      duration_longue = true;
      duration_courte =false;
      $("#dur_cou").removeClass("active");
      $("#dur_lon").addClass("active");
      //$("#myCarousel").replaceWith(carousel_l);
      //$("#car").empty();
      $("#car").load('carousel_long.html');
      $("#p1").show();
      alert("Chargement terminé \n Guide pour atelier long !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();})
    });
  //Pour le public :
    $("#pub_enf").click(function(e){
      pub = "enf";
      $("#pub_adu").removeClass("active");
      $("#pub_enf").addClass("active");
    });
    $("#pub_adu").click(function(e){
      pub = "adu";
      $("#pub_enf").removeClass("active");
      $("#pub_adu").addClass("active");
    });
  //Pour le scénario :
    $("#sce_2").click(function(e){
      sce = 2;
      $("#sce_1").removeClass("active");
      $("#sce_2").addClass("active");
    });
    $("#sce_1").click(function(e){
      sce = 1;
      $("#sce_2").removeClass("active");
      $("#sce_1").addClass("active");
    });

    $("#pointLien").click(function(e){
      if(pub == "enf"){
        $("#pointLien").attr('href','graphiques_enfants.html');
      }else{
        $("#pointLien").attr('href','graphiques_adultes.html');
      }
    });

  });

function demoFromHTML() {

          pdf = new jsPDF('p', 'pt', 'a4', false);
          pdf.text(30,30,"hello);
       //  logo.src = "1.png";
        //    pdf.addImage(logo, 'JPEG', 2, 2, 590,850);

 /*
          if(duration_longue){
            var logo = new Image();
            logo.src = "../donnees/1.png";
            pdf.addImage(logo, 'JPEG', 2, 2, 590,850);
            pdf.addPage();
            var logo = new Image();
            logo.src = "2.png";
            pdf.addImage(logo, 'JPEG', 2, 2, 590,850);

          }else if(duration_courte) {
            logo.src = "../donnees/2.png";
            pdf.addImage(logo, 'JPEG', 2, 2, 590,850);
            pdf.addPage();
            logo.src = "3.png";
            pdf.addImage(logo, 'JPEG', 2, 2, 590,850);

          }

           var uno= 1;

          var paso;
        for (paso = 4; paso < 6; paso++) {
            pdf.addPage();
            var logo = new Image();
            logo.src = paso+".png";
            pdf.addImage(logo, 'JPEG', 2, 2, 590,850);
          // Se ejecuta 5 veces, con valores desde paso desde 0 hasta 4.

          };*/

      pdf.output("dataurlnewwindow");

        }
<commit_msg>Update dynamic_carousel.js<commit_after>var duree = "longue";
var duration_longue = true;
var duration_courte = false;

  $(document).ready(function(){
  //on initialise les variables avec les valeurs par défaut
    var duree = "longue";
    var pub = "adu";
    var nbDePersonnes = 16;
    var sce = 1;
  //on appuie les boutons en conséquence
    $("#dur_lon").addClass("active");
    $("#pub_adu").addClass("active");
    $("#sce_1").addClass("active");
    //$("#car").load('carousel_long.html');

    //On remplit le champ du bouton +/- avec la valeur par défaut
    $("#inputnb").val(nbDePersonnes);

    //var carousel_c = $.get("carousel_court.html");
    //var carousel_l = $.get("carousel_long.html");
  //On change la valeur des variables en fonction des actions utilisateurs
  //Pour la durée :
    $("#dur_cou").click(function(e){
      duree = "courte";
      duration_courte = true;
      duration_longue = false;
      $("#dur_lon").removeClass("active");
      $("#dur_cou").addClass("active");
      //var code = load("carousel_court.html");
      //$("#myCarousel").replaceWith("
 This text is strong
  This text is italic
");
      //alert(carousel_c);
      //$("#car").empty();
      $("#car").load('carousel_court.html');
      $("#p1").show();
      alert("Chargement terminé \n Guide pour atelier court !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();});
    });
    $("#dur_lon").click(function(e){
      duree = "longue";
      duration_longue = true;
      duration_courte =false;
      $("#dur_cou").removeClass("active");
      $("#dur_lon").addClass("active");
      //$("#myCarousel").replaceWith(carousel_l);
      //$("#car").empty();
      $("#car").load('carousel_long.html');
      $("#p1").show();
      alert("Chargement terminé \n Guide pour atelier long !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();})
    });
  //Pour le public :
    $("#pub_enf").click(function(e){
      pub = "enf";
      $("#pub_adu").removeClass("active");
      $("#pub_enf").addClass("active");
    });
    $("#pub_adu").click(function(e){
      pub = "adu";
      $("#pub_enf").removeClass("active");
      $("#pub_adu").addClass("active");
    });
  //Pour le scénario :
    $("#sce_2").click(function(e){
      sce = 2;
      $("#sce_1").removeClass("active");
      $("#sce_2").addClass("active");
    });
    $("#sce_1").click(function(e){
      sce = 1;
      $("#sce_2").removeClass("active");
      $("#sce_1").addClass("active");
    });

    $("#pointLien").click(function(e){
      if(pub == "enf"){
        $("#pointLien").attr('href','graphiques_enfants.html');
      }else{
        $("#pointLien").attr('href','graphiques_adultes.html');
      }
    });

  });

function demoFromHTML() {

          pdf = new jsPDF('p', 'pt', 'a4', false);
          pdf.text(30,30,"hello");
       //  logo.src = "1.png";
        //    pdf.addImage(logo, 'JPEG', 2, 2, 590,850);

 /*
          if(duration_longue){
            var logo = new Image();
            logo.src = "../donnees/1.png";
            pdf.addImage(logo, 'JPEG', 2, 2, 590,850);
            pdf.addPage();
            var logo = new Image();
            logo.src = "2.png";
            pdf.addImage(logo, 'JPEG', 2, 2, 590,850);

          }else if(duration_courte) {
            logo.src = "../donnees/2.png";
            pdf.addImage(logo, 'JPEG', 2, 2, 590,850);
            pdf.addPage();
            logo.src = "3.png";
            pdf.addImage(logo, 'JPEG', 2, 2, 590,850);

          }

           var uno= 1;

          var paso;
        for (paso = 4; paso < 6; paso++) {
            pdf.addPage();
            var logo = new Image();
            logo.src = paso+".png";
            pdf.addImage(logo, 'JPEG', 2, 2, 590,850);
          // Se ejecuta 5 veces, con valores desde paso desde 0 hasta 4.

          };*/

      pdf.output("dataurlnewwindow");

        }
<|endoftext|>


<commit_before>/*
 * The MIT License

Copyright (c) 2013 by Juergen Marsch

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
"use strict";
(function(){
    // Code to handle 'require("...")' and to load the relevant modules
    Espruino["Modules"] = {};
    Espruino.Modules.Config = {
      url : "http://www.espruino.com/modules",
      fileExtensions : [ ".min.js", ".js" ]
    };
    Espruino.Modules["initOptions"] = function(){
      Espruino.Options.optionFields.push({id:"#urlModules",module:"Modules",object:"Config",field:"url",type:"text"});
      Espruino.Options.optionFields.push({id:"#fileExtensionsModules",module:"Modules",object:"Config",field:"fileExtensions",type:"JSON"});
      Espruino.Options.optionBlocks.push();
      Espruino.Options.optionBlocks.push({id:"#divOptionModules",htmlUrl:"data/Espruino_Modules.html"});
    };
    Espruino.Modules.init = function(){
    };

    var getModulesRequired = function(code) {
      var modules = [];
      var requires = code.match(/require\(\"[^\"]*\"\)/g);
      for (var i in requires) {
        // strip off beginning and end, and parse the string
        var module = JSON.parse(requires[i].substring(8,requires[i].length-1));
        // add it to our array - FIXME don't hard code these
        var builtin_modules = ["http","fs","CC3000"];
        if (builtin_modules.indexOf(module)<0 && modules.indexOf(module)<0)
          modules.push(module);
      }
      return modules;
    };

    /* Finds instances of 'require' and then ensures that
     those modules are loaded into the module cache beforehand
     (by inserting the relevant 'addCached' commands into 'code' */
    Espruino.Modules.loadModules = function(code,callback){
      var defs = [], maxWait = 5000,urlParts;
      var requires = getModulesRequired(code);
      var moduleCode = "Modules.removeAllCached();";
      var urlexp = new RegExp( '(http|https)://[\\w-]+(\\.[\\w-]+)+([\\w-.,@?^=%&:/~+#-]*[\\w@?^=%&;/~+#-])?' );
      for(var i = 0; i < requires.length; i++){
        if(urlexp.test(requires[i])){
          defs.push(loadModule(requires[i].substr(requires[i].lastIndexOf("/") + 1).split(".")[0],requires[i]));}
        else{defs.push(loadModule(requires[i],Espruino.Modules.Config.url + "/" + requires[i], Espruino.Modules.Config.fileExtensions));}
      }
      if(defs.length > 0) {$.when.apply(null,defs).then(function(){returnCode();});}
      else{callback(code);}

      function loadModule(modName,url,extensions) {
        var t, localUrl,dfd = $.Deferred();
        var extensionTry = 0;
        var downloadModule = function(localUrl) {
          $.get(localUrl,function(data){
            moduleCode += "Modules.addCached(" + JSON.stringify(modName) + "," + JSON.stringify(data) + ");\n";
            dfd.resolve();
          },"text").fail(function() {
            if(extensionTry < extensions.length) {
              downloadModule(url + extensions[extensionTry++]);
            } else {
              console.log(modName + " not found");
              dfd.resolve();
            }
          });
        };

        t = setInterval(function(){clearInterval(t);dfd.resolve();},maxWait);
        if (extensions && extensions.length>0){
          downloadModule(url + extensions[extensionTry++]);
        } else {
          code = code.replace("require(\"" + url + "\")","require(\"" + modName + "\")");
          downloadModule(url);
        }

        return dfd.promise();
      }

      function returnCode(){ callback(moduleCode + "\n" + code); }
    };

})();
<commit_msg>absolutely mental module loading code now :( has to cope with modules referenced from modules<commit_after>/*
 * The MIT License

Copyright (c) 2013 by Juergen Marsch

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
"use strict";
(function(){
    // Code to handle 'require("...")' and to load the relevant modules
    Espruino["Modules"] = {};
    Espruino.Modules.Config = {
      url : "http://www.espruino.com/modules",
      fileExtensions : [ ".min.js", ".js" ]
    };
    Espruino.Modules["initOptions"] = function(){
      Espruino.Options.optionFields.push({id:"#urlModules",module:"Modules",object:"Config",field:"url",type:"text"});
      Espruino.Options.optionFields.push({id:"#fileExtensionsModules",module:"Modules",object:"Config",field:"fileExtensions",type:"JSON"});
      Espruino.Options.optionBlocks.push();
      Espruino.Options.optionBlocks.push({id:"#divOptionModules",htmlUrl:"data/Espruino_Modules.html"});
    };
    Espruino.Modules.init = function(){
    };

    var getModulesRequired = function(code) {
      var modules = [];
      var requires = code.match(/require\(\"[^\"]*\"\)/g);
      for (var i in requires) {
        // strip off beginning and end, and parse the string
        var module = JSON.parse(requires[i].substring(8,requires[i].length-1));
        // add it to our array - FIXME don't hard code these
        var builtin_modules = ["http","fs","CC3000"];
        if (builtin_modules.indexOf(module)<0 && modules.indexOf(module)<0)
          modules.push(module);
      }
      return modules;
    };

    /* Finds instances of 'require' and then ensures that
     those modules are loaded into the module cache beforehand
     (by inserting the relevant 'addCached' commands into 'code' */
    Espruino.Modules.loadModules = function(code,callback){
      var promises = [], maxWait = 5000,urlParts;
      var moduleCode = "Modules.removeAllCached();";

      var requires = getModulesRequired(code);
      var urlexp = new RegExp( '(http|https)://[\\w-]+(\\.[\\w-]+)+([\\w-.,@?^=%&:/~+#-]*[\\w@?^=%&;/~+#-])?' );
      // Kick off the module loading (each returns a promise)
      for(var i = 0; i < requires.length; i++)
        promises.push(loadModule(requires[i]));
      // When all
      if(promises.length > 0) {
        $.when.apply(null,promises).then(function(){ callback(moduleCode + "\n" + code); });
      } else {
        callback(code);
      }
      // function to actually load the modules
      function loadModule(fullModuleName) {
        console.log("loadModule("+fullModuleName+")");
        var modName,url,extensions;
        if(urlexp.test(fullModuleName)) {
          modName = fullModuleName.substr(fullModuleName.lastIndexOf("/") + 1).split(".")[0];
          url = fullModuleName;
          extensions = [];
        } else {
          modName = fullModuleName;
          url = Espruino.Modules.Config.url + "/" + fullModuleName;
          extensions = Espruino.Modules.Config.fileExtensions;
        }

        var t, localUrl,dfd = $.Deferred();
        var extensionTry = 0;
        var downloadModule = function(localUrl) {
          $.get(localUrl,function(data){
            moduleCode += "Modules.addCached(" + JSON.stringify(modName) + "," + JSON.stringify(data) + ");\n";
            // Check for any modules used from this module that we don't already have
            var newRequires = getModulesRequired(data);
            console.log(" - "+fullModuleName+" requires "+JSON.stringify(newRequires));
            // if we need new modules, set them to load and get their promises
            var newPromises = [];
            for (var i in newRequires)
              if (requires.indexOf(newRequires[i])<0) {
                requires.push(newRequires[i]);
                newPromises.push(loadModule(newRequires[i]));
              }
            // if we need to load something, wait until we have all promises complete before resolving our promise!
            if(newPromises.length > 0) {
              $.when.apply(null,newPromises).then(function(){ dfd.resolve(); });
            } else {
              dfd.resolve();
            }

          },"text").fail(function() {
            if(extensionTry < extensions.length) {
              downloadModule(url + extensions[extensionTry++]);
            } else {
              console.log(modName + " not found");
              dfd.resolve();
            }
          });
        };

        t = setInterval(function(){clearInterval(t);dfd.resolve();},maxWait);
        if (extensions.length>0){
          downloadModule(url + extensions[extensionTry++]);
        } else {
          code = code.replace("require(\"" + url + "\")","require(\"" + modName + "\")");
          downloadModule(url);
        }

        return dfd.promise();
      }
    };

})();
<|endoftext|>


<commit_before>define(['js/core/DomElement', 'underscore'], function (DomElement, _) {

    var HTML_Namespace = "http://www.w3.org/1999/xhtml",
        POLICY_OUT = 'out',
        POLICY_IN = 'in',
        POLICY_BOTH = 'both',
        attributeMap = {
            height: 'offsetHeight',
            width: 'offsetWidth'
        };

    /**
     * Sets the size of an element, if the policy requires it
     * @param element
     * @param policy
     * @param attribute
     */
    var checkSizePolicy = function(element, policy, attribute){
        if (policy === POLICY_IN || policy === POLICY_BOTH) {
            element.set(attribute, element.$el[attributeMap[attribute]]);
        }
    };

    /**
     * Binds the window resize event and sets the size on resize if the policy requires it
     * @param element
     * @param policy
     * @param attribute
     */
    var bindSizePolicy = function (element, policy, attribute) {

        if (policy === POLICY_IN || policy === POLICY_BOTH) {
            if (!element["__update"+attribute]) {
                var self = element;
                element["__update" + attribute] = function () {
                    self.set(attribute, self.$el[attributeMap[attribute]]);
                };
                element.dom(element.$stage.$window).bindDomEvent('resize', element["__update" + attribute]);
            }
        } else {
            if (element["__update" + attribute]) {
                element.dom(element.$stage.$window).unbindDomEvent('resize', element["__update" + attribute]);
                delete element["__update" + attribute];
            }
        }

    };

    var HtmlElement = DomElement.inherit("js.html.HtmlElement", {

        defaults: {
            selected: undefined,
            selectable: undefined,
            namespace: HTML_Namespace,
            enabled: true,
            position: null,

            heightUpdatePolicy: POLICY_OUT,
            widthUpdatePolicy: POLICY_OUT
        },

        $classAttributes: ['heightUpdatePolicy', 'widthUpdatePolicy', 'content'],

        $excludedStyleAttributes: ['src','content'],

        $renderAsStyleWithPx: ['left', 'top'],
        /**
         *
         * @private
         */
        _onDomAdded: function(){
            this.callBase();

            checkSizePolicy(this,this.$.widthUpdatePolicy,'width');
            checkSizePolicy(this,this.$.heightUpdatePolicy,'height');
        },
        /**
         *
         * @param policy
         * @private
         */
        _renderHeightUpdatePolicy: function (policy) {
            bindSizePolicy(this, policy, "height");
        },
        /**
         *
         * @param policy
         * @private
         */
        _renderWidthUpdatePolicy: function (policy) {
            bindSizePolicy(this, policy, "width");
        },
        /**
         *
         * @param selected
         * @private
         */
        _renderSelected: function (selected) {
            if (selected) {
                this.addClass('active');
            } else {
                this.removeClass('active');
            }
        },
        /**
         *
         * @param key
         * @param value
         * @private
         */
        _setAttribute: function (key, value) {

            if (_.indexOf(this.$renderAsStyleWithPx, key) !== -1) {
                if (!_.isString(value)) {
                    value += "px";
                }
            }

            this.callBase(key, value);

        },
        /**
         *
         * @param selectable
         * @private
         */
        _renderSelectable: function (selectable) {
            if (selectable) {
                if (!this._onSelect) {
                    var self = this;
                    this._onSelect = function () {
                        if(self.$.enabled){
                            self.set({selected: !self.$.selected});
                        }
                    };
                }
                this.bindDomEvent('click', this._onSelect);
            } else {
                if (this._onSelect) {
                    this.unbindDomEvent('click', this._onSelect);
                }
            }
        },
        _renderEnabled: function (enabled) {
            if ("disabled" in this.$el) {
                if (!enabled) {
                    this.$el.setAttribute('disabled', true);
                } else {
                    this.$el.removeAttribute('disabled');
                }
            }
            if (enabled) {
                this.removeClass('disabled');
            } else {
                this.addClass('disabled');
            }
        },

        /***
         * renders the width of the element if the update-policy allows out-going
         * @param width - the width in pixel if not a string
         * @private
         */
        _renderWidth: function (width) {

            if (width !== undefined && width !== null && typeof(width) !== "string") {
                width += "px";
            }

            this._renderPolicyValue('width', width);
        },

        /***
         * renders the height of the element if the update-policy allows out-going
         * @param height - the width in pixel if not a string
         * @private
         */
        _renderHeight: function (height) {

            if (height !== undefined && height !== null && typeof(height) !== "string") {
                // TODO: check browser
                height = Math.min(17895697, height); // max height in firefox
                height += "px";
            }

            this._renderPolicyValue('height', height);
        },

        /***
         *
         * @param name
         * @param value
         * @private
         */
        _renderPolicyValue: function (name, value) {
            var policy = this.$[name + 'UpdatePolicy'];

            if (policy === POLICY_OUT || policy === POLICY_BOTH) {
                if(value != null && value !== undefined){
                    this.$el.style[name] = value;
                }
            }

        },

        _renderAttributeInternal: function(key, value) {
            if (this._isStyleAttribute(key)) {
                if (_.indexOf(this.$renderAsStyleWithPx, key) !== -1) {
                    if (!_.isString(value)) {
                        value += "px";
                    }
                }

                if(value){
                    if (key in this.$el.style) {
                        this.$el.style[key] = value;
                    } else {

                        var transformedKey = HtmlElement.transformCache[key];

                        if (!transformedKey) {
                            // transform key
                            var split = key.split("-");
                            transformedKey = split[0];
                            for (var i = 1; i < split.length; i++) {
                                transformedKey += split[i].charAt(0).toUpperCase() + split[1].substr(1);
                            }

                            HtmlElement.transformCache[key] = transformedKey;
                        }

                        if (transformedKey in this.$el.style) {
                            this.$el.style[transformedKey] = value;
                        }
                    }
                }

            } else {
                this.callBase();
            }
        },

        _isStyleAttribute: function(key) {

            var supportedCssProperties = this.$stage.$supportedCssProperties;

            if (!supportedCssProperties && this.runsInBrowser()) {

                var window = this.$stage.$window,
                    document = this.$stage.$document;

                supportedCssProperties = this.$stage.$supportedCssProperties = [];

                if (document && window) {
                    var body = document.body || document.getElementsByName("body")[0] || document.getElementsByName("html")[0];
                    if (body) {
                        var styles = window.getComputedStyle(body);
                        for (var i = 0; i < styles.length; i++) {
                            supportedCssProperties.push(styles[i]);
                        }
                    }
                }
            }

            return _.indexOf(this.$excludedStyleAttributes, key) === -1 && this.$el && (key in this.$el.style || (supportedCssProperties && _.indexOf(supportedCssProperties, key) !== -1));

        },

        _createDOMEventHandler: function(type){
            return new HtmlElement.EventHandler(this, type);
        }

    });

    HtmlElement.EventHandler = DomElement.EventHandler.inherit('js.html.HtmlElement.EventHandler',{
        handleEvent: function(e){
            if(this._isEventEnabled()){
                this.callBase();
            }else{
                e.preventDefault();
                return false;
            }
        },
        _isEventEnabled: function(){
            if(!this.component.$.enabled){
                if(_.include(['on:click','on:dblclick'],this.type)){
                    return false;
                }
            }
            return true;
        }
    });

    HtmlElement.transformCache = {};

    HtmlElement.HTML_Namespace = HTML_Namespace;

    return HtmlElement;
});<commit_msg>fixed getComputedStyles for firefox<commit_after>define(['js/core/DomElement', 'underscore'], function (DomElement, _) {

    var HTML_Namespace = "http://www.w3.org/1999/xhtml",
        POLICY_OUT = 'out',
        POLICY_IN = 'in',
        POLICY_BOTH = 'both',
        attributeMap = {
            height: 'offsetHeight',
            width: 'offsetWidth'
        };

    /**
     * Sets the size of an element, if the policy requires it
     * @param element
     * @param policy
     * @param attribute
     */
    var checkSizePolicy = function(element, policy, attribute){
        if (policy === POLICY_IN || policy === POLICY_BOTH) {
            element.set(attribute, element.$el[attributeMap[attribute]]);
        }
    };

    /**
     * Binds the window resize event and sets the size on resize if the policy requires it
     * @param element
     * @param policy
     * @param attribute
     */
    var bindSizePolicy = function (element, policy, attribute) {

        if (policy === POLICY_IN || policy === POLICY_BOTH) {
            if (!element["__update"+attribute]) {
                var self = element;
                element["__update" + attribute] = function () {
                    self.set(attribute, self.$el[attributeMap[attribute]]);
                };
                element.dom(element.$stage.$window).bindDomEvent('resize', element["__update" + attribute]);
            }
        } else {
            if (element["__update" + attribute]) {
                element.dom(element.$stage.$window).unbindDomEvent('resize', element["__update" + attribute]);
                delete element["__update" + attribute];
            }
        }

    };

    var HtmlElement = DomElement.inherit("js.html.HtmlElement", {

        defaults: {
            selected: undefined,
            selectable: undefined,
            namespace: HTML_Namespace,
            enabled: true,
            position: null,

            heightUpdatePolicy: POLICY_OUT,
            widthUpdatePolicy: POLICY_OUT
        },

        $classAttributes: ['heightUpdatePolicy', 'widthUpdatePolicy', 'content'],

        $excludedStyleAttributes: ['src','content'],

        $renderAsStyleWithPx: ['left', 'top'],
        /**
         *
         * @private
         */
        _onDomAdded: function(){
            this.callBase();

            checkSizePolicy(this,this.$.widthUpdatePolicy,'width');
            checkSizePolicy(this,this.$.heightUpdatePolicy,'height');
        },
        /**
         *
         * @param policy
         * @private
         */
        _renderHeightUpdatePolicy: function (policy) {
            bindSizePolicy(this, policy, "height");
        },
        /**
         *
         * @param policy
         * @private
         */
        _renderWidthUpdatePolicy: function (policy) {
            bindSizePolicy(this, policy, "width");
        },
        /**
         *
         * @param selected
         * @private
         */
        _renderSelected: function (selected) {
            if (selected) {
                this.addClass('active');
            } else {
                this.removeClass('active');
            }
        },
        /**
         *
         * @param key
         * @param value
         * @private
         */
        _setAttribute: function (key, value) {

            if (_.indexOf(this.$renderAsStyleWithPx, key) !== -1) {
                if (!_.isString(value)) {
                    value += "px";
                }
            }

            this.callBase(key, value);

        },
        /**
         *
         * @param selectable
         * @private
         */
        _renderSelectable: function (selectable) {
            if (selectable) {
                if (!this._onSelect) {
                    var self = this;
                    this._onSelect = function () {
                        if(self.$.enabled){
                            self.set({selected: !self.$.selected});
                        }
                    };
                }
                this.bindDomEvent('click', this._onSelect);
            } else {
                if (this._onSelect) {
                    this.unbindDomEvent('click', this._onSelect);
                }
            }
        },
        _renderEnabled: function (enabled) {
            if ("disabled" in this.$el) {
                if (!enabled) {
                    this.$el.setAttribute('disabled', true);
                } else {
                    this.$el.removeAttribute('disabled');
                }
            }
            if (enabled) {
                this.removeClass('disabled');
            } else {
                this.addClass('disabled');
            }
        },

        /***
         * renders the width of the element if the update-policy allows out-going
         * @param width - the width in pixel if not a string
         * @private
         */
        _renderWidth: function (width) {

            if (width !== undefined && width !== null && typeof(width) !== "string") {
                width += "px";
            }

            this._renderPolicyValue('width', width);
        },

        /***
         * renders the height of the element if the update-policy allows out-going
         * @param height - the width in pixel if not a string
         * @private
         */
        _renderHeight: function (height) {

            if (height !== undefined && height !== null && typeof(height) !== "string") {
                // TODO: check browser
                height = Math.min(17895697, height); // max height in firefox
                height += "px";
            }

            this._renderPolicyValue('height', height);
        },

        /***
         *
         * @param name
         * @param value
         * @private
         */
        _renderPolicyValue: function (name, value) {
            var policy = this.$[name + 'UpdatePolicy'];

            if (policy === POLICY_OUT || policy === POLICY_BOTH) {
                if(value != null && value !== undefined){
                    this.$el.style[name] = value;
                }
            }

        },

        _renderAttributeInternal: function(key, value) {
            if (this._isStyleAttribute(key)) {
                if (_.indexOf(this.$renderAsStyleWithPx, key) !== -1) {
                    if (!_.isString(value)) {
                        value += "px";
                    }
                }

                if(value){
                    if (key in this.$el.style) {
                        this.$el.style[key] = value;
                    } else {

                        var transformedKey = HtmlElement.transformCache[key];

                        if (!transformedKey) {
                            // transform key
                            var split = key.split("-");
                            transformedKey = split[0];
                            for (var i = 1; i < split.length; i++) {
                                transformedKey += split[i].charAt(0).toUpperCase() + split[1].substr(1);
                            }

                            HtmlElement.transformCache[key] = transformedKey;
                        }

                        if (transformedKey in this.$el.style) {
                            this.$el.style[transformedKey] = value;
                        }
                    }
                }

            } else {
                this.callBase();
            }
        },

        _isStyleAttribute: function(key) {

            var supportedCssProperties = this.$stage.$supportedCssProperties;

            if (!supportedCssProperties && this.runsInBrowser()) {

                var window = this.$stage.$window,
                    document = this.$stage.$document;

                supportedCssProperties = this.$stage.$supportedCssProperties = [];

                if (document && window) {
                    var body = document.body || document.getElementsByName("body")[0] || document.getElementsByName("html")[0];
                    if (body) {
                        var styles = window.getComputedStyle(body, null);
                        for (var i = 0; i < styles.length; i++) {
                            supportedCssProperties.push(styles[i]);
                        }
                    }
                }
            }

            return _.indexOf(this.$excludedStyleAttributes, key) === -1 && this.$el && (key in this.$el.style || (supportedCssProperties && _.indexOf(supportedCssProperties, key) !== -1));

        },

        _createDOMEventHandler: function(type){
            return new HtmlElement.EventHandler(this, type);
        }

    });

    HtmlElement.EventHandler = DomElement.EventHandler.inherit('js.html.HtmlElement.EventHandler',{
        handleEvent: function(e){
            if(this._isEventEnabled()){
                this.callBase();
            }else{
                e.preventDefault();
                return false;
            }
        },
        _isEventEnabled: function(){
            if(!this.component.$.enabled){
                if(_.include(['on:click','on:dblclick'],this.type)){
                    return false;
                }
            }
            return true;
        }
    });

    HtmlElement.transformCache = {};

    HtmlElement.HTML_Namespace = HTML_Namespace;

    return HtmlElement;
});<|endoftext|>


<commit_before>var CACHE_NAME = 'v0.1-cieltech',urlsToCache=['/','/index.html','/manifest.json','/js/fontfaceobserver.js','/img/logo.svg','/favicon-16x16.png'];
self.addEventListener('install',function(evt){evt.waitUntil(caches.open(CACHE_NAME).then(function(cache){return cache.addAll(urlsToCache);}));});
self.addEventListener('activate',function(evt){evt.waitUntil(caches.keys().then(function(cacheNames){return Promise.all(cacheNames.filter(function(cacheName){return cacheName!==CACHE_NAME;}).map(function(cacheName){console.log('Deleting '+cacheName);return caches.delete(cacheName);}));}));});
self.addEventListener('fetch',function(evt){evt.respondWith(caches.match(evt.request).then(function(response){return response||fetch(evt.request);}).catch(function(){return caches.match('index.html');}))});
<commit_msg>Added skipWaiting() and clients.claim()<commit_after>var CACHE_NAME = 'v0.1-cieltech',urlsToCache=['/','/index.html','/manifest.json','/js/fontfaceobserver.js','/img/logo.svg','/favicon-16x16.png'];
self.addEventListener('install',function(evt){evt.waitUntil(caches.open(CACHE_NAME).then(function(cache){return cache.addAll(urlsToCache);}).then(function(){return self.skipWaiting();}));});
self.addEventListener('activate',function(evt){return self.clients.claim();});
self.addEventListener('fetch',function(evt){evt.respondWith(caches.match(evt.request).then(function(response){return response||fetch(evt.request);}).catch(function(){return caches.match('index.html');}))});
<|endoftext|>


<commit_before>var AdmZip = require('adm-zip'),
parser = require('xml2js').Parser(),
_ = require('underscore'),
fs = require('fs'),
et = require('elementtree');

var XML = et.XML;
var ElementTree = et.ElementTree;
var element = et.Element;
var subElement = et.SubElement;

var etree;

// unzip docx and get body text
getBody = function(path, callback) {

    // path validation
    fs.exists(path, function (exists) {
        if (!exists) return callback(undefined, "Error: file does not exist.");

        var zip = new AdmZip(path);
        var zipEntries = zip.getEntries();

        // grabs the body xml
        var entry = _.findWhere(zipEntries, {entryName: "word/document.xml"});
        entry = entry.getData().toString();
        etree = et.parse(entry);
        console.log(etree.findall('w:body/w:p'));

    });
};

exports.getBody = getBody;

getBody("./nom.docx", function(data, err) {
    if (err) console.dir(err);
    else console.dir(data);
});<commit_msg>fixed return for getBody<commit_after>var AdmZip = require('adm-zip'),
parser = require('xml2js').Parser(),
_ = require('underscore'),
fs = require('fs'),
et = require('elementtree');

var XML = et.XML;
var ElementTree = et.ElementTree;
var element = et.Element;
var subElement = et.SubElement;

// unzip docx and get body text
getBody = function(path, callback) {
    var etree;

    // path validation
    fs.exists(path, function (exists) {
        if (!exists) return callback(undefined, "Error: file does not exist.");

        var zip = new AdmZip(path);
        var zipEntries = zip.getEntries();

        // grabs the body xml
        var entry = _.findWhere(zipEntries, {entryName: "word/document.xml"});
        entry = entry.getData().toString();
        etree = et.parse(entry).findall('w:body/w:p');
        return callback(etree, undefined);
    });
};

exports.getBody = getBody;

getBody("./nom.docx", function(data, err) {
    if (err) console.log(err);
    else console.log(data);
});<|endoftext|>


<commit_before>(function(window, factory) {
	var dom = factory(window, window.document);
	window.dom = dom;
	if(typeof module == 'object' && module.exports){
		module.exports = dom;
	}
}(typeof window != 'undefined' ? window : this , function(window, document) {
	'use strict';
	var slice = [].slice;
	var Dom = function(elements){

		if(typeof elements == 'string'){
			return Dom.q(elements);
		}
		if(!(this instanceof Dom)){
			return new Dom(elements);
		}

		/*
		if(typeof elements == 'function'){
			if(Dom.isReady){
				elements(Dom);
			} else {
				document.addEventListener('DOMContentLoaded', function(){
					elements(Dom);
				});
			}
		}
		*/
		if(!Array.isArray(elements)){
			if(!elements){
				elements = [];
			} else if(elements.nodeName || !('length' in elements) || elements == window){
				elements = [elements];
			} else {
				elements = slice.call(elements);
			}
		}

		this.elements = elements;
		this.length = this.elements.length || 0;
	};
	var fn = Dom.prototype;

	var tween = function(element, endProps, options){

		var easing, isStopped, isJumpToEnd;
		var hardStop = false;
		var start = Date.now();
		var elementStyle = element.style;
		var startProps = {};
		var rAF = rb.rAFQueue;
		var stop = function(clearQueue, jumpToEnd){
			isStopped = true;
			if(jumpToEnd){
				isJumpToEnd = true;
			}
			step();
			rAF.remove(step);
		};

		var step = function() {
			if(hardStop){return;}
			var prop, value, eased;
			var pos = (Date.now() - start) / options.duration;

			if(pos > 1 || isJumpToEnd){
				pos = 1;
			}

			if(!isStopped){
				eased = easing(pos);

				for(prop in startProps){
					value = (endProps[prop] - startProps[prop]) * eased + startProps[prop];

					if(prop in elementStyle){
						if(!Dom.cssNumber[prop]){
							value += 'px';
						}
						elementStyle[prop] = value;
					} else {
						element[prop] = value;
					}
				}
			}

			if(pos < 1){
				if(!isStopped){
					rAF.add(step);
				} else if(options.always){
					options.always.call(element);
				}
			} else{
				if(element._rbTweenStop){
					delete element._rbTweenStop;
				}
				if(options.complete && !isStopped){
					options.complete.call(element);
				}
				if(options.always){
					options.always.call(element);
				}
			}
		};

		tween.getStartValues(element, elementStyle, startProps, endProps);

		options = Object.assign({duration: 400, easing: 'ease'}, options || {});

		easing = Dom.easing[options.easing] || Dom.easing.ease || Dom.easing.swing;
		element._rbTweenStop = stop;

		rAF.add(step);
	};

	tween.getStartValues = function(element, elementStyle, startProps, endProps){
		var prop;
		for(prop in endProps){
			if(typeof endProps[prop] == 'string'){
				endProps[prop] = parseFloat(endProps[prop]) || 0;
			}
			if(prop in elementStyle){
				startProps[prop] = parseFloat(getComputedStyle(element).getPropertyValue(prop)) || 0;
			} else {
				startProps[prop] = element[prop];
			}
		}
	};

	Object.assign(Dom, {
		easing: {
			linear: function(pos) {
				return pos;
			},
			swing: function(p) {
				return 0.5 - Math.cos( p * Math.PI ) / 2;
			}
		},
		fn: Dom.prototype,
		cssNumber: {
			"opacity": true,
		},
		isNumeric: function( obj ) {
			return !Array.isArray( obj ) && (obj - parseFloat( obj ) + 1) >= 0;
		},
		//isReady: document.readyState != 'loading',
		noop: function(){},
		q: function(sel, context){
			return new Dom( (context || document).querySelectorAll(sel) );
		},
		Event: function(type, options){
			var event;
			if(!options){
				options = {};
			}

			if(options.bubbles == null){
				options.bubbles = true;
			}
			event = new CustomEvent(type, options);

			if(!event.isDefaultPrevented){
				event.isDefaultPrevented = function(){
					return event.defaultPrevented;
				};
			}

			return event;
		},
		Callbacks: function(flags){
			if(flags){
				console.error('not supported: '+ flags);
			}
			var list = [];

			return {
				add: function(fn){
					list.push(fn);
				},
				remove: function(fn){
					var index = list.indexOf(fn);

					if(index != -1){
						list.splice(index, 1);
					}
				},
				fire: function(){
					this.fireWith(this, arguments);
				},
				fireWith: function(that, args){
					var i, len;
					for(i = 0, len = list.length; i < len; i++){
						list[i].apply(that, args);
					}
				},
				has: function(){
					return !!list.length;
				}
			};
		},
		css: function( elem, name, extra, styles ) {
			var ret;
			styles = styles || getComputedStyle(elem, null);
			ret = styles.getPropertyValue(name) || styles[name];

			if(extra === true || (extra && Dom.isNumeric(ret))){
				ret = parseFloat(ret) || 0;
			}
			return ret;
		},
	});

	Object.assign(fn, {
		find: function(sel){
			var array = [];
			this.elements.forEach(function(elem){
				var i, len;
				var elements = elem.querySelectorAll(sel);
				for(i = 0, len = elements.length; i < len; i++){
					if(array.indexOf(elements[i]) == -1){
						array.push(elements[i]);
					}
				}
			});

			return new Dom( array );
		},
		closest: function(sel){
			var array = [];
			this.elements.forEach(function(elem){
				var element = elem.closest(sel);
				if(array.indexOf(element) == -1){
					array.push(element);
				}
			});
			return new Dom( array );
		},
		get: function(number){
			return arguments.length ? this.elements[number] : this.elements;
		},
		eq: function(number){
			return new Dom(this.elements[number] ? [this.elements[number]] : []);
		},
		css: function(style){
			var elem;
			if(typeof style == 'string'){
				elem = this.elements[0]
				return elem && DOM.css(elem, style);
			}
			this.elements.forEach(function(elem){
				var prop;
				var eStyle = elem.style;
				for(prop in style){
					eStyle[prop] = style[prop];
				}
			});
			return this;
		},
		prop: function(props){
			var elem;
			if(typeof props == 'string'){
				elem = this.elements[0];
				return elem && elem[props];
			}
			this.elements.forEach(function(elem){
				var prop;
				for(prop in props){
					elem[prop] = props[prop];
				}
			});
			return this;
		},
		attr: function(attrs){
			var elem;
			if(typeof attrs == 'string'){
				elem = this.elements[0];
				return elem && elem.getAttribute(attrs);
			}
			this.elements.forEach(function(elem){
				var attr;
				for(attr in attrs){
					elem.setAttribute(attr, attrs[attr]);
				}
			});
			return this;
		},
		removeAttr: function(attr){
			this.elements.forEach(function(elem){
				elem.removeAttribute(attr);
			});
			return this;
		},
		is: function(sel){
			return this.elements.some(function(elem){
				return elem.matches(sel);
			});
		},
		html: function(html){
			var elem;
			var isString = typeof html == 'string';
			if(!arguments.length){
				elem = this.elements[0];
				return elem && elem.innerHTML || '';
			}
			this.elements.forEach(function(elem){
				if(isString){
					elem.innerHTML = html;
				} else {
					elem.innerHTML = '';
					elem.appendChild(html);
				}
			});
			return this;
		},
		before: function(html){
			var isString = typeof html == 'string';
			this.elements.forEach(function(elem){
				var parentElement;
				if (isString){
					elem.insertAdjacentHTML('beforebegin', html);
				} else {
					parentElement = elem.parentNode;
					if(parentElement){
						parentElement.insertBefore(html, elem);
					}
				}
			});
			return this;
		},
		prepend: function(html){
			var isString = typeof html == 'string';
			this.elements.forEach(function(elem){
				if (isString){
					elem.insertAdjacentHTML('afterbegin', html);
				} else {
					elem.insertBefore(html, elem.firstChild);
				}
			});
			return this;
		},
		append: function(html){
			var isString = typeof html == 'string';
			this.elements.forEach(function(elem){
				if (isString){
					elem.insertAdjacentHTML('beforeend', html);
				} else {
					elem.insertBefore(html, null);
				}
			});
			return this;
		},
		after: function(html){
			var isString = typeof html == 'string';
			this.elements.forEach(function(elem){
				var parentElement;
				if (isString){
					elem.insertAdjacentHTML('afterend', html);
				} else {
					parentElement = elem.parentNode;
					if(parentElement){
						parentElement.insertBefore(html, elem.nextElementSibling);
					}
				}
			});
			return this;
		},
		each: function(cb){
			this.elements.forEach(function(elem, index){
				cb.call(elem, index, elem);
			});
			return this;
		},
		remove: function(){
			this.elements.forEach(function(elem){
				var parent = elem.parentNode;
				if(parent && parent.removeChild){
					parent.removeChild(elem);
				}
			});
			return this;
		},
		trigger: function(type, options){
			var firstEvent;

			if(typeof type == 'object'){
				firstEvent = type;
				type = firstEvent.type;
			}

			if(!options){
				options = {};
			}

			if(options.bubbles == null){
				options.bubbles = true;
			}

			this.elements.forEach(function(elem){
				var event = firstEvent || new CustomEvent(type, options);
				firstEvent = null;
				elem.dispatchEvent(event);
			});

			return this;
		},
		animate: function(endProps, options){
			this.elements.forEach(function(elem){
				tween(elem, endProps, options);
			});
			return this;
		},
		stop: function(clearQueue, jumpToEnd){
			this.elements.forEach(function(elem) {
				if (elem._rbTweenStop) {
					elem._rbTweenStop(clearQueue, jumpToEnd);
				}
			});
			return this;
		},
		index: function(elem){
			if(!elem.nodeName && elem.get){
				elem = elem.get(0);
			}
			return this.elements.indexOf(elem);
		},
	});

	['add', 'remove', 'has', 'toggle'].forEach(function(action){
		fn[action + 'Class'] =  function(cl){
			this.elements.forEach(function(elem){
				elem.classList[action](cl);
			});
			return this;
		};

		if(action == 'has'){
			action = 'contains';
		}
	});

	//new array or returns array
	['map', 'filter'].forEach(function(name){
		fn[name] = function(fn){
			var sel;

			if(typeof fn == 'string'){
				sel = fn;
				fn = function(){
					return this.matches(sel);
				};
			}
			return new Dom(this.elements[name](function(elem, index){
				return fn.call(elem, index, elem);
			}));
		};
	});

	['every', 'findIndex', 'includes', 'indexOf', 'lastIndexOf', 'some'].forEach(function(name){
		fn[name] = function(){
			return this.elements[name].apply(this.elements, arguments);
		};
	});

	[['on', 'addEventListener'], ['off', 'removeEventListener']].forEach(function(action){
		Dom.fn[action[0]] = function(type, sel, fn, capture){
			var useFn;
			if(typeof sel == 'function'){
				capture = fn;
				fn = sel;
				sel = null;
			}

			if(sel){
				if(!fn[sel]){
					fn[sel] = function(e){
						e.delegatedTarget = e.target.closest(sel);
						if(!e.delegatedTarget){return;}
						return fn.apply(this, arguments);
					};
				}
				useFn = fn[sel];
			} else {
				useFn = fn;
			}

			this.elements.forEach(function(elem){
				elem[action[1]](type, useFn, capture || false);
			});

			return this;
		};
	});

	if(!window.rb){
		window.rb = {};
	}

	if(!window.rb.$){
		window.rb.$ = window.dom;
	}

	return Dom;
}));
<commit_msg>improvements<commit_after>(function(window, factory) {
	var dom = factory(window, window.document);
	window.dom = dom;
	if(typeof module == 'object' && module.exports){
		module.exports = dom;
	}
}(typeof window != 'undefined' ? window : this , function(window, document) {
	'use strict';
	var slice = [].slice;
	var Dom = function(elements){

		if(typeof elements == 'string'){
			return Dom.q(elements);
		}
		if(!(this instanceof Dom)){
			return new Dom(elements);
		}

		/*
		if(typeof elements == 'function'){
			if(Dom.isReady){
				elements(Dom);
			} else {
				document.addEventListener('DOMContentLoaded', function(){
					elements(Dom);
				});
			}
		}
		*/
		if(!Array.isArray(elements)){
			if(!elements){
				elements = [];
			} else if(elements.nodeName || !('length' in elements) || elements == window){
				elements = [elements];
			} else {
				elements = slice.call(elements);
			}
		}

		this.elements = elements;
		this.length = this.elements.length || 0;
	};
	var fn = Dom.prototype;

	var tween = function(element, endProps, options){

		var easing, isStopped, isJumpToEnd;
		var hardStop = false;
		var start = Date.now();
		var elementStyle = element.style;
		var startProps = {};
		var rAF = rb.rAFQueue;
		var stop = function(clearQueue, jumpToEnd){
			isStopped = true;
			if(jumpToEnd){
				isJumpToEnd = true;
			}
			step();
			rAF.remove(step);
		};

		var step = function() {
			if(hardStop){return;}
			var prop, value, eased;
			var pos = (Date.now() - start) / options.duration;

			if(pos > 1 || isJumpToEnd){
				pos = 1;
			}

			if(!isStopped){
				eased = easing(pos);

				for(prop in startProps){
					value = (endProps[prop] - startProps[prop]) * eased + startProps[prop];

					if(prop in elementStyle){
						if(!Dom.cssNumber[prop]){
							value += 'px';
						}
						elementStyle[prop] = value;
					} else {
						element[prop] = value;
					}
				}
			}

			if(pos < 1){
				if(!isStopped){
					rAF.add(step);
				} else if(options.always){
					options.always.call(element);
				}
			} else{
				if(element._rbTweenStop){
					delete element._rbTweenStop;
				}
				if(options.complete && !isStopped){
					options.complete.call(element);
				}
				if(options.always){
					options.always.call(element);
				}
			}
		};

		tween.getStartValues(element, elementStyle, startProps, endProps);

		options = Object.assign({duration: 400, easing: 'ease'}, options || {});

		easing = Dom.easing[options.easing] || Dom.easing.ease || Dom.easing.swing;
		element._rbTweenStop = stop;

		rAF.add(step);
	};

	tween.getStartValues = function(element, elementStyle, startProps, endProps){
		var prop;
		for(prop in endProps){
			if(typeof endProps[prop] == 'string'){
				endProps[prop] = parseFloat(endProps[prop]) || 0;
			}
			if(prop in elementStyle){
				startProps[prop] = parseFloat(getComputedStyle(element).getPropertyValue(prop)) || 0;
			} else {
				startProps[prop] = element[prop];
			}
		}
	};

	Object.assign(Dom, {
		easing: {
			linear: function(pos) {
				return pos;
			},
			swing: function(p) {
				return 0.5 - Math.cos( p * Math.PI ) / 2;
			}
		},
		fn: Dom.prototype,
		cssNumber: {
			"opacity": true,
		},
		//isReady: document.readyState != 'loading',
		noop: function(){},
		q: function(sel, context){
			return new Dom( (context || document).querySelectorAll(sel) );
		},
		Event: function(type, options){
			var event;
			if(!options){
				options = {};
			}

			if(options.bubbles == null){
				options.bubbles = true;
			}
			event = new CustomEvent(type, options);

			if(!event.isDefaultPrevented){
				event.isDefaultPrevented = function(){
					return event.defaultPrevented;
				};
			}

			return event;
		},
		Callbacks: function(flags){
			if(flags){
				console.error('not supported: '+ flags);
			}
			var list = [];

			return {
				add: function(fn){
					list.push(fn);
				},
				remove: function(fn){
					var index = list.indexOf(fn);

					if(index != -1){
						list.splice(index, 1);
					}
				},
				fire: function(){
					this.fireWith(this, arguments);
				},
				fireWith: function(that, args){
					var i, len;
					for(i = 0, len = list.length; i < len; i++){
						list[i].apply(that, args);
					}
				},
				has: function(){
					return !!list.length;
				}
			};
		},
		css: function( elem, name, extra, styles ) {
			var ret, num;
			styles = styles || getComputedStyle(elem, null);
			ret = styles.getPropertyValue(name) || styles[name];

			if(extra){
				num = parseFloat(ret);
				if(extra === true || !isNaN(num)){
					ret = num;
				}
			}
			return ret;
		},
	});

	Object.assign(fn, {
		find: function(sel){
			var array = [];
			this.elements.forEach(function(elem){
				var i, len;
				var elements = elem.querySelectorAll(sel);
				for(i = 0, len = elements.length; i < len; i++){
					if(array.indexOf(elements[i]) == -1){
						array.push(elements[i]);
					}
				}
			});

			return new Dom( array );
		},
		closest: function(sel){
			var array = [];
			this.elements.forEach(function(elem){
				var element = elem.closest(sel);
				if(array.indexOf(element) == -1){
					array.push(element);
				}
			});
			return new Dom( array );
		},
		get: function(number){
			return arguments.length ? this.elements[number] : this.elements;
		},
		eq: function(number){
			return new Dom(this.elements[number] ? [this.elements[number]] : []);
		},
		css: function(style){
			var elem;
			if(typeof style == 'string'){
				elem = this.elements[0]
				return elem && DOM.css(elem, style);
			}
			this.elements.forEach(function(elem){
				var prop;
				var eStyle = elem.style;
				for(prop in style){
					eStyle[prop] = style[prop];
				}
			});
			return this;
		},
		prop: function(props){
			var elem;
			if(typeof props == 'string'){
				elem = this.elements[0];
				return elem && elem[props];
			}
			this.elements.forEach(function(elem){
				var prop;
				for(prop in props){
					elem[prop] = props[prop];
				}
			});
			return this;
		},
		attr: function(attrs){
			var elem;
			if(typeof attrs == 'string'){
				elem = this.elements[0];
				return elem && elem.getAttribute(attrs);
			}
			this.elements.forEach(function(elem){
				var attr;
				for(attr in attrs){
					elem.setAttribute(attr, attrs[attr]);
				}
			});
			return this;
		},
		removeAttr: function(attr){
			this.elements.forEach(function(elem){
				elem.removeAttribute(attr);
			});
			return this;
		},
		is: function(sel){
			return this.elements.some(function(elem){
				return elem.matches(sel);
			});
		},
		html: function(html){
			var elem;
			var isString = typeof html == 'string';
			if(!arguments.length){
				elem = this.elements[0];
				return elem && elem.innerHTML || '';
			}
			this.elements.forEach(function(elem){
				if(isString){
					elem.innerHTML = html;
				} else {
					elem.innerHTML = '';
					elem.appendChild(html);
				}
			});
			return this;
		},
		before: function(html){
			var isString = typeof html == 'string';
			this.elements.forEach(function(elem){
				var parentElement;
				if (isString){
					elem.insertAdjacentHTML('beforebegin', html);
				} else {
					parentElement = elem.parentNode;
					if(parentElement){
						parentElement.insertBefore(html, elem);
					}
				}
			});
			return this;
		},
		prepend: function(html){
			var isString = typeof html == 'string';
			this.elements.forEach(function(elem){
				if (isString){
					elem.insertAdjacentHTML('afterbegin', html);
				} else {
					elem.insertBefore(html, elem.firstChild);
				}
			});
			return this;
		},
		append: function(html){
			var isString = typeof html == 'string';
			this.elements.forEach(function(elem){
				if (isString){
					elem.insertAdjacentHTML('beforeend', html);
				} else {
					elem.insertBefore(html, null);
				}
			});
			return this;
		},
		after: function(html){
			var isString = typeof html == 'string';
			this.elements.forEach(function(elem){
				var parentElement;
				if (isString){
					elem.insertAdjacentHTML('afterend', html);
				} else {
					parentElement = elem.parentNode;
					if(parentElement){
						parentElement.insertBefore(html, elem.nextElementSibling);
					}
				}
			});
			return this;
		},
		each: function(cb){
			this.elements.forEach(function(elem, index){
				cb.call(elem, index, elem);
			});
			return this;
		},
		remove: function(){
			this.elements.forEach(function(elem){
				var parent = elem.parentNode;
				if(parent && parent.removeChild){
					parent.removeChild(elem);
				}
			});
			return this;
		},
		trigger: function(type, options){
			var firstEvent;

			if(typeof type == 'object'){
				firstEvent = type;
				type = firstEvent.type;
			}

			if(!options){
				options = {};
			}

			if(options.bubbles == null){
				options.bubbles = true;
			}

			this.elements.forEach(function(elem){
				var event = firstEvent || new CustomEvent(type, options);
				firstEvent = null;
				elem.dispatchEvent(event);
			});

			return this;
		},
		animate: function(endProps, options){
			this.elements.forEach(function(elem){
				tween(elem, endProps, options);
			});
			return this;
		},
		stop: function(clearQueue, jumpToEnd){
			this.elements.forEach(function(elem) {
				if (elem._rbTweenStop) {
					elem._rbTweenStop(clearQueue, jumpToEnd);
				}
			});
			return this;
		},
		index: function(elem){
			if(!elem.nodeName && elem.get){
				elem = elem.get(0);
			}
			return this.elements.indexOf(elem);
		},
	});

	['add', 'remove', 'has', 'toggle'].forEach(function(action){
		fn[action + 'Class'] =  function(cl){
			this.elements.forEach(function(elem){
				elem.classList[action](cl);
			});
			return this;
		};

		if(action == 'has'){
			action = 'contains';
		}
	});

	//new array or returns array
	['map', 'filter'].forEach(function(name){
		fn[name] = function(fn){
			var sel;

			if(typeof fn == 'string'){
				sel = fn;
				fn = function(){
					return this.matches(sel);
				};
			}
			return new Dom(this.elements[name](function(elem, index){
				return fn.call(elem, index, elem);
			}));
		};
	});

	['every', 'findIndex', 'includes', 'indexOf', 'lastIndexOf', 'some'].forEach(function(name){
		fn[name] = function(){
			return this.elements[name].apply(this.elements, arguments);
		};
	});

	[['on', 'addEventListener'], ['off', 'removeEventListener']].forEach(function(action){
		Dom.fn[action[0]] = function(type, sel, fn, capture){
			var useFn;
			if(typeof sel == 'function'){
				capture = fn;
				fn = sel;
				sel = null;
			}

			if(sel){
				if(!fn[sel]){
					fn[sel] = function(e){
						e.delegatedTarget = e.target.closest(sel);
						if(!e.delegatedTarget){return;}
						return fn.apply(this, arguments);
					};
				}
				useFn = fn[sel];
			} else {
				useFn = fn;
			}

			this.elements.forEach(function(elem){
				elem[action[1]](type, useFn, capture || false);
			});

			return this;
		};
	});

	if(!window.rb){
		window.rb = {};
	}

	if(!window.rb.$){
		window.rb.$ = window.dom;
	}

	return Dom;
}));
<|endoftext|>