<commit_before>/**
 * OsmGeoCoder is a Backbone model representing a place on an OSM map
 *
 */
"use strict";
define(function (require) {
    var Location = require('models/Location');

    var OsmGeoCoder = function (args) {};

    OsmGeoCoder.prototype._buildUrl = function (query) {
        return "http://nominatim.openstreetmaps.org/search" + this._buildQuery(query) + '&limit=1&format=json';
    };

    OsmGeoCoder.prototype._buildQuery = function (query) {
        return '?q=' + query.split(' ').join('+');
    };

    OsmGeoCoder.prototype.fetch = function (options) {
        var location = new Location({query: options.query});
        $.ajax({
            url: this._buildUrl(options.query),
            method: 'GET',
            dataType: 'json',
            jsonp: true,
            success: function (response) {
                if (response.length > 0) {
                    var place = response[0];
                    location.set({lat: place.lat, lon: place.lon, boundingbox: place.boundingbox});
                    options.success({location: location});
                } else {
                    options.error("No results");
                }
            },
            error: function (response, status) {
                options.error(response, status);
            },
            complete: function() {
                if (typeof options != 'undefined' && options.complete != 'undefined') {
                    options.complete({location: location, status: status});
                }
            }
        });
    };

    return OsmGeoCoder;
});
<commit_msg>Changed OSM location to use MapQuest location.<commit_after>/**
 * OsmGeoCoder is a Backbone model representing a place on an OSM map
 *
 */
"use strict";
define(function (require) {
    var Location = require('models/Location');

    var OsmGeoCoder = function (args) {};

    OsmGeoCoder.prototype._buildUrl = function (query) {
        var baseURL = "http://www.mapquestapi.com/geocoding/v1/address?key=E1aPfpcd72j9wfglxliaYXnCeKO4pFD1&inFormat=kvp&outFormat=json&maxResults=1&thumbMaps=false";
        return baseURL + this._buildQuery(query);
    };

    OsmGeoCoder.prototype._buildQuery = function (query) {
        return '&location=' + query.split(' ').join('+');
    };

    OsmGeoCoder.prototype.fetch = function (options) {
        var location = new Location({query: options.query});
        $.ajax({
            url: this._buildUrl(options.query),
            method: 'GET',
            jsonp: true,
            success: function (response) {

                var info = response.info;
                if (info.statuscode === 0) {
                    var results = response.results[0];
                    var place = results.locations[0];
                    var latLng = place.latLng;
                    location.set({lat: latLng.lat, lon: latLng.lng});
                    options.success({location: location});
                } else {
                    options.error(info.messages, info.statuscode);
                }
            },
            error: function (response, status) {
                options.error(response, status);
            },
            complete: function() {
                if (typeof options != 'undefined' && options.complete != 'undefined') {
                    options.complete({location: location, status: status});
                }
            }
        });
    };

    return OsmGeoCoder;
});
<|endoftext|>


<commit_before>Package.describe({
  summary: "pull ical-generator"
});

Package.on_use(function (api, where) {
	api.use('iron:router');
	api.add_files('ical.js', 'server');
});

Npm.depends({'ical-generator': '0.1.10'});
<commit_msg>update description<commit_after>Package.describe({
  summary: "generate calendars"
});

Package.on_use(function (api, where) {
	api.use('iron:router');
	api.add_files('ical.js', 'server');
});

Npm.depends({'ical-generator': '0.1.10'});
<|endoftext|>


<commit_before>$(document).ready(function () {
                    add_ui(reports);
                  });
$("#add-filter").on("click", $.fancybox.close);
$("#add-another").on("click", add_ui);
function add_ui(initial_reports) {
  var machine = new StateMachine('reporting-ui',
                                 'uninitialized',
                                 { 'uninitialized': { 'init': build_selection_ui },
                                   'ui-ready': { 'select': doSelect },
                                   'loading': { 'success': show_reports,
                                                'error': show_error,
                                                'select': doSelect },
                                   'reports-ready': { 'select': doSelect }
                                 });
  machine.init();
  if (initial_reports)
    machine.select(initial_reports);
  function build_selection_ui(event, state) {
    var stuff = $("
", { 'class': 'whatsit' }).data("reporting-ui-state-machine",
                                                        machine);
    var question_select = $("#hidden_controls > select").clone()
                                                        .on("change", machine.select);
    var filter_link = $("", { text: "Filter this report...",
                                 href: "#filter_selection" });
    filter_link.on("click",
                   function () {
                     controller.showModalDialog("#filter_selection",
                                                { beforeClose: machine.select });
                   });
    machine.selector_ui = $("
", { 'class': 'selector' }).append($("
", { 'class': 'busy-indicator' }),
                                                                     question_select,
                                                                     filter_link,
                                                                     $("

"))
                                                             .appendTo(stuff);
    machine.container = $("
").appendTo(stuff);
    stuff.appendTo("#all-reports");
    return 'ui-ready';
  }
  function doSelect(event, state) {
    if (machine.req)
      machine.req.abort();
    machine.selector_ui.addClass("loading");
    var question = machine.selector_ui.find("select").find(":checked").attr("value");
    if (!question)
      return 'ui-ready';
    var states = $("#type-state").is(":checked") && $("#id_states").val();
    var jurisdictions = $("#type-jurisdiction").is(":checked") && $("#id_jurisdictions").val();
    machine.req = $.ajax(buildURL("/reporting/"+ question +"/",
                                  { states: states,
                                    jurisdictions: jurisdictions }),
                         { dataType: 'json' })
                   .done(machine.success)
                   .fail(machine.error);
    return 'loading';
  }
  function show_error(event, state) {
    machine.container.empty();
    var again = $("", { text: "Try again" }).on("click", machine.select);
    $("", { text: "Oops, there was an error." }).append(again)
                                                      .appendTo(machine.container);
    machine.selector_ui.removeClass("loading");
    return 'ui-ready';
  }
  function show_reports(event, state, data) {
    machine.container.empty();
    if (data.description)
      machine.selector_ui.find(".description").html(data.description);
    else
      machine.selector_ui.find(".description").empty();
    $.each(data.reports,
           function (idx, report) {
             show_report(report, machine.container);
           });
    machine.selector_ui.removeClass("loading");
    return 'reports-ready';
  }
  function show_report(report, container) {
    var ui = build_ui(report);
    container.append(ui);
    draw_graph(report, ui);
  }
  function build_ui(report) {
    var even_odd = (function () {
                      var n = 0;
                      return function () {
                               n += 1;
                               return (n % 2 === 0) ? 'even' : 'odd';
                             };
                    })();
    var ui = $("
", { id: "report"+ report.idx, 'class': "report" }), table, temporal_table;
    ui.append($("
", { id: "graph"+ report.idx, 'class': "graph" }));
    if (report.type == "temporal") {
      report.table = report.statsd_metrics.map(function (m) {
                                                 return { key: m, value: "" };
                                               });
      ui.append(table = $("
", { 'class': "data_table" }));
      table.append($("
Value	Jurisdictions
"));
      $.each(report.table,
             function (i, row) {
               var tr = $("
", { 'class': even_odd() }),
                   name = "series-"+ i +"-enabled";
               tr.append($("").append($("", { for: name }).append($("", { 'class': "legend-dot" }),
                                                                             $("", { text: row.key }))),
                         $("").append($("<input>", { type: "checkbox",
                                                         checked: true,
                                                         name: name,
                                                         'class': name })));
               table.append(tr);
             });
    } else {
      if ('table' in report) {
        ui.append(table = $("
", { 'class': "data_table" }));
        table.append($("
Value	Jurisdictions
"));
        report.table.forEach(function (row) {
                               var tr = $("
", { 'class': even_odd() });
                               tr.append($("").append($("", { 'class': "legend-dot" }),
                                                          $("", { text: row.key })),
                                         $("").append($("", { text: row.value })));
                               table.append(tr);
                             });
      }
    }
    if (report.type == "temporal") {
      ui.append(temporal_table = $("
", { 'class': "data_table temporal_table" }),
                $("
", { 'class': 'date-slider' }));
      temporal_table.append($("
From	To
"),
                            $("
", { 'class': "odd" }).append($("").append($("", { html: " " })),
                                                                 $("").append($("", { html: " " }))));
    }
    return ui;
  }
  function draw_graph(report, container) {
    var values = 'table' in report ? report.table.map(select("value")).filter(defined)
                                   : [],
        sum = values.reduce(function (a, b) { return a+b; }, 0),
        idx = report.idx;
    var r = Raphael(container.find("#graph"+ idx).get(0)), graph, path_colors = [];
    if (report.type == "histogram") {
      if (sum <= 0)
        return;
      graph = r.barchart(0, 0, 320, 320, values);
      $.each(graph.bars,
             function(k, v) {
               if (v.node && report.table[k].key != "Total")
                 path_colors[k] = $(v.node).css("fill");
             });
    } else if (report.type == "pie") {
      if (sum <= 0)
        return;
      graph = r.piechart(160, 160, 150, values);
      var is_funky = graph.series.length == 1;
      if (is_funky)
        path_colors = [$(graph.series[0].node).css("fill")];
      else
        $.each(graph.series,
               function(k, v) {
                 if (v.value && report.table[k].key != "Total")
                   path_colors[v.value.order] = $(v.node).css("fill");
               });
    } else if (report.type == "temporal" && report.name) {
      var metrics = $.map(report.statsd_metrics,
                          function (metric) {
                            return "integral(solarpermit.dev.counters.question."+ report.name +"."+ report.question_id +"."+ metric.toLowerCase() +".count)";
                          });
      $.ajax({ url: "http://permit01.dev.cpf.com:9001/render/",
               data: { from: "00:00_20120901",
                       target: metrics,
                       format: "json" },
               dataType: "json",
               success: function(data) {
                          var max = tomorrow() / 1000,
                              min = Date.UTC(2013,6,13) / 1000;
                          var end = max,
                              start = min; //Math.max(monthago() / 1000, min);
                          var slider = container.find(".date-slider").slider({ range: true,
                                                                               min: min,
                                                                               max: max,
                                                                               values: [ start, end ],
                                                                               step: 86400,
                                                                               slide: draw,
                                                                               change: draw
                                                                             });
                          var checkboxes = container.find("input[type=checkbox]");
                          checkboxes.on("change", draw);
                          draw();
                          function draw(event, ui) {
                            var s = ui ? ui.values[0] : start,
                                e = ui ? ui.values[1] : end;
                            var cells = container.find(".temporal_table span");
                            $(cells[0]).text(formatStamp(s));
                            $(cells[1]).text(formatStamp(e));
                            var processed = processData(data, s, e, checkboxes);
                            r.clear();
                            graph = r.linechart(0, 0, 320, 320, processed[0], processed[1], { snapEnds: false });
                            $.each(graph.lines,
                                   function(i, l) {
                                     if (l.node)
                                       path_colors[i] = $(l.node).css("stroke");
                                   });
                            var color_idx = 0;
                            container.find(".legend-dot")
                                     .each(function (idx, elem) {
                                             if (checkboxes[idx].checked)
                                               color(color_idx++, elem);
                                             else
                                               $(elem).css("background-color", "transparent");
                                           });
                          }
                          function processData(alldata, start, end, enabled) {
                            var lines = $.map(alldata,
                                              function (line) {
                                                return [processSeries(line.datapoints, start, end)];
                                              });
                            var map = {};
                            $.each(lines,
                                   function (i, line) {
                                     $.each(line,
                                            function (j, point) {
                                              if (!(point[1] in map)) {
                                                map[point[1]] = [];
                                              }
                                              map[point[1]][i] = point[0];
                                            });
                                   });
                            var x = [];
                            var ys = [];
                            $.each(map,
                                   function (stamp, counts) {
                                     x.push(parseInt(stamp, 10));
                                   });
                            x.sort();
                            $.each(x,
                                   function (i, stamp) {
                                     var column = map[stamp];
                                     $.each(column,
                                            function (j, value) {
                                              if (!ys[j]) {
                                                ys[j] = [];
                                              }
                                              if (typeof value === "undefined")
                                                if (i-1 in ys[j])
                                                  value = ys[j][i-1];
                                                else
                                                  value = 0;
                                              ys[j][i] = value;
                                            });
                                   });
                            var enabled_ys = [];
                            $.each(enabled,
                                   function (i, checkbox) {
                                     if (checkbox.checked)
                                       enabled_ys.push(ys[i]);
                                   });
                            return [x, enabled_ys];
                          }
                          function processSeries(datapoints, start, end) {
                            return filterData($.grep(datapoints,
                                                     function (p) {
                                                       return !!p[0];
                                                     }),
                                              start,
                                              end);
                          }
                          function filterData(datapoints, start, end) {
                            var data = $.grep(datapoints,
                                              function (p) {
                                                return start <= p[1] && p[1] <= end;
                                              });
                            if (data.length == 0 || data[0][1] > start) {
                              var earlier = firstBefore(start, datapoints);
                              data.unshift([earlier ? earlier[0] : 0, start]);
                            }
                            if (data[data.length-1][1] < end) {
                              data.push([data[data.length-1][0], end]);
                            }
                            return data;
                          }
                          function firstBefore(timestamp, datapoints) {
                            for (var i = datapoints.length - 1; i >= 0; i--) {
                              if (datapoints[i][1] < timestamp)
                                return datapoints[i];
                            }
                          }
                          function formatStamp(stamp) {
                            if (typeof stamp === "string")
                              stamp = parseInt(stamp, 10);
                            return new Date(stamp * 1000).toLocaleDateString(window.navigator.userLanguage ||
                                                                             window.navigator.language,
                                                                             { weekday: "long",
                                                                               year: "numeric",
                                                                               month: "long",
                                                                               day: "numeric"
                                                                             });
                          }
                          function tomorrow() {
                            d = new Date();
                            d.setUTCDate(d.getUTCDate()+1);
                            d.setUTCHours(0);
                            d.setUTCMinutes(0);
                            d.setUTCSeconds(0);
                            d.setUTCMilliseconds(0);
                            return d.getTime();
                          }
                          function monthago() {
                            d = new Date();
                            d.setUTCDate(d.getUTCMonth()-1);
                            d.setUTCHours(0);
                            d.setUTCMinutes(0);
                            d.setUTCSeconds(0);
                            d.setUTCMilliseconds(0);
                            return d.getTime();
                          }
                        }
             });
    }
    var n = 0;
    container.find(".legend-dot").each(color);
    function color(idx, elem) {
      var head = $(elem).parent();
      if (!(is_funky && head.next().text() == "0")) {
        $(elem).css("background-color",
                    path_colors[is_funky ? n++ : idx]);
      }
    }
  }
  function select(field) {
    return function (elem) {
             if (elem.key != 'Total')
               return elem[field];
           };
  }
  function defined(val) {
    return typeof val != "undefined";
  }
}
function buildURL(base, params) {
  var kv = [];
  $.each(params,
         function (key, values) {
           if ($.isArray(values)) {
             $.each(values,
                    function (i, value) {
                      if (value)
                        kv.push([key, encodeURIComponent(value)]);
                    });
           } else {
             if (values)
               kv.push([key, encodeURIComponent(values)]);
           }
         });
  kv = kv.map(function (param) { return param[0] +'='+ param[1]; });
  if (kv)
    base += '?' + kv.join('&');
  return base;
}
<commit_msg>go back to jan 2012 for the data; some questions go back further than others<commit_after>$(document).ready(function () {
                    add_ui(reports);
                  });
$("#add-filter").on("click", $.fancybox.close);
$("#add-another").on("click", add_ui);
function add_ui(initial_reports) {
  var machine = new StateMachine('reporting-ui',
                                 'uninitialized',
                                 { 'uninitialized': { 'init': build_selection_ui },
                                   'ui-ready': { 'select': doSelect },
                                   'loading': { 'success': show_reports,
                                                'error': show_error,
                                                'select': doSelect },
                                   'reports-ready': { 'select': doSelect }
                                 });
  machine.init();
  if (initial_reports)
    machine.select(initial_reports);
  function build_selection_ui(event, state) {
    var stuff = $("
", { 'class': 'whatsit' }).data("reporting-ui-state-machine",
                                                        machine);
    var question_select = $("#hidden_controls > select").clone()
                                                        .on("change", machine.select);
    var filter_link = $("", { text: "Filter this report...",
                                 href: "#filter_selection" });
    filter_link.on("click",
                   function () {
                     controller.showModalDialog("#filter_selection",
                                                { beforeClose: machine.select });
                   });
    machine.selector_ui = $("
", { 'class': 'selector' }).append($("
", { 'class': 'busy-indicator' }),
                                                                     question_select,
                                                                     filter_link,
                                                                     $("

"))
                                                             .appendTo(stuff);
    machine.container = $("
").appendTo(stuff);
    stuff.appendTo("#all-reports");
    return 'ui-ready';
  }
  function doSelect(event, state) {
    if (machine.req)
      machine.req.abort();
    machine.selector_ui.addClass("loading");
    var question = machine.selector_ui.find("select").find(":checked").attr("value");
    if (!question)
      return 'ui-ready';
    var states = $("#type-state").is(":checked") && $("#id_states").val();
    var jurisdictions = $("#type-jurisdiction").is(":checked") && $("#id_jurisdictions").val();
    machine.req = $.ajax(buildURL("/reporting/"+ question +"/",
                                  { states: states,
                                    jurisdictions: jurisdictions }),
                         { dataType: 'json' })
                   .done(machine.success)
                   .fail(machine.error);
    return 'loading';
  }
  function show_error(event, state) {
    machine.container.empty();
    var again = $("", { text: "Try again" }).on("click", machine.select);
    $("", { text: "Oops, there was an error." }).append(again)
                                                      .appendTo(machine.container);
    machine.selector_ui.removeClass("loading");
    return 'ui-ready';
  }
  function show_reports(event, state, data) {
    machine.container.empty();
    if (data.description)
      machine.selector_ui.find(".description").html(data.description);
    else
      machine.selector_ui.find(".description").empty();
    $.each(data.reports,
           function (idx, report) {
             show_report(report, machine.container);
           });
    machine.selector_ui.removeClass("loading");
    return 'reports-ready';
  }
  function show_report(report, container) {
    var ui = build_ui(report);
    container.append(ui);
    draw_graph(report, ui);
  }
  function build_ui(report) {
    var even_odd = (function () {
                      var n = 0;
                      return function () {
                               n += 1;
                               return (n % 2 === 0) ? 'even' : 'odd';
                             };
                    })();
    var ui = $("
", { id: "report"+ report.idx, 'class': "report" }), table, temporal_table;
    ui.append($("
", { id: "graph"+ report.idx, 'class': "graph" }));
    if (report.type == "temporal") {
      report.table = report.statsd_metrics.map(function (m) {
                                                 return { key: m, value: "" };
                                               });
      ui.append(table = $("
", { 'class': "data_table" }));
      table.append($("
Value	Jurisdictions
"));
      $.each(report.table,
             function (i, row) {
               var tr = $("
", { 'class': even_odd() }),
                   name = "series-"+ i +"-enabled";
               tr.append($("").append($("", { for: name }).append($("", { 'class': "legend-dot" }),
                                                                             $("", { text: row.key }))),
                         $("").append($("<input>", { type: "checkbox",
                                                         checked: true,
                                                         name: name,
                                                         'class': name })));
               table.append(tr);
             });
    } else {
      if ('table' in report) {
        ui.append(table = $("
", { 'class': "data_table" }));
        table.append($("
Value	Jurisdictions
"));
        report.table.forEach(function (row) {
                               var tr = $("
", { 'class': even_odd() });
                               tr.append($("").append($("", { 'class': "legend-dot" }),
                                                          $("", { text: row.key })),
                                         $("").append($("", { text: row.value })));
                               table.append(tr);
                             });
      }
    }
    if (report.type == "temporal") {
      ui.append(temporal_table = $("
", { 'class': "data_table temporal_table" }),
                $("
", { 'class': 'date-slider' }));
      temporal_table.append($("
From	To
"),
                            $("
", { 'class': "odd" }).append($("").append($("", { html: " " })),
                                                                 $("").append($("", { html: " " }))));
    }
    return ui;
  }
  function draw_graph(report, container) {
    var values = 'table' in report ? report.table.map(select("value")).filter(defined)
                                   : [],
        sum = values.reduce(function (a, b) { return a+b; }, 0),
        idx = report.idx;
    var r = Raphael(container.find("#graph"+ idx).get(0)), graph, path_colors = [];
    if (report.type == "histogram") {
      if (sum <= 0)
        return;
      graph = r.barchart(0, 0, 320, 320, values);
      $.each(graph.bars,
             function(k, v) {
               if (v.node && report.table[k].key != "Total")
                 path_colors[k] = $(v.node).css("fill");
             });
    } else if (report.type == "pie") {
      if (sum <= 0)
        return;
      graph = r.piechart(160, 160, 150, values);
      var is_funky = graph.series.length == 1;
      if (is_funky)
        path_colors = [$(graph.series[0].node).css("fill")];
      else
        $.each(graph.series,
               function(k, v) {
                 if (v.value && report.table[k].key != "Total")
                   path_colors[v.value.order] = $(v.node).css("fill");
               });
    } else if (report.type == "temporal" && report.name) {
      var metrics = $.map(report.statsd_metrics,
                          function (metric) {
                            return "integral(solarpermit.dev.counters.question."+ report.name +"."+ report.question_id +"."+ metric.toLowerCase() +".count)";
                          });
      $.ajax({ url: "http://permit01.dev.cpf.com:9001/render/",
               data: { from: "00:00_20120101",
                       target: metrics,
                       format: "json" },
               dataType: "json",
               success: function(data) {
                          var max = tomorrow() / 1000,
                              min = Date.UTC(2013,6,13) / 1000;
                          var end = max,
                              start = min; //Math.max(monthago() / 1000, min);
                          var slider = container.find(".date-slider").slider({ range: true,
                                                                               min: min,
                                                                               max: max,
                                                                               values: [ start, end ],
                                                                               step: 86400,
                                                                               slide: draw,
                                                                               change: draw
                                                                             });
                          var checkboxes = container.find("input[type=checkbox]");
                          checkboxes.on("change", draw);
                          draw();
                          function draw(event, ui) {
                            var s = ui ? ui.values[0] : start,
                                e = ui ? ui.values[1] : end;
                            var cells = container.find(".temporal_table span");
                            $(cells[0]).text(formatStamp(s));
                            $(cells[1]).text(formatStamp(e));
                            var processed = processData(data, s, e, checkboxes);
                            r.clear();
                            graph = r.linechart(0, 0, 320, 320, processed[0], processed[1], { snapEnds: false });
                            $.each(graph.lines,
                                   function(i, l) {
                                     if (l.node)
                                       path_colors[i] = $(l.node).css("stroke");
                                   });
                            var color_idx = 0;
                            container.find(".legend-dot")
                                     .each(function (idx, elem) {
                                             if (checkboxes[idx].checked)
                                               color(color_idx++, elem);
                                             else
                                               $(elem).css("background-color", "transparent");
                                           });
                          }
                          function processData(alldata, start, end, enabled) {
                            var lines = $.map(alldata,
                                              function (line) {
                                                return [processSeries(line.datapoints, start, end)];
                                              });
                            var map = {};
                            $.each(lines,
                                   function (i, line) {
                                     $.each(line,
                                            function (j, point) {
                                              if (!(point[1] in map)) {
                                                map[point[1]] = [];
                                              }
                                              map[point[1]][i] = point[0];
                                            });
                                   });
                            var x = [];
                            var ys = [];
                            $.each(map,
                                   function (stamp, counts) {
                                     x.push(parseInt(stamp, 10));
                                   });
                            x.sort();
                            $.each(x,
                                   function (i, stamp) {
                                     var column = map[stamp];
                                     $.each(column,
                                            function (j, value) {
                                              if (!ys[j]) {
                                                ys[j] = [];
                                              }
                                              if (typeof value === "undefined")
                                                if (i-1 in ys[j])
                                                  value = ys[j][i-1];
                                                else
                                                  value = 0;
                                              ys[j][i] = value;
                                            });
                                   });
                            var enabled_ys = [];
                            $.each(enabled,
                                   function (i, checkbox) {
                                     if (checkbox.checked)
                                       enabled_ys.push(ys[i]);
                                   });
                            return [x, enabled_ys];
                          }
                          function processSeries(datapoints, start, end) {
                            return filterData($.grep(datapoints,
                                                     function (p) {
                                                       return !!p[0];
                                                     }),
                                              start,
                                              end);
                          }
                          function filterData(datapoints, start, end) {
                            var data = $.grep(datapoints,
                                              function (p) {
                                                return start <= p[1] && p[1] <= end;
                                              });
                            if (data.length == 0 || data[0][1] > start) {
                              var earlier = firstBefore(start, datapoints);
                              data.unshift([earlier ? earlier[0] : 0, start]);
                            }
                            if (data[data.length-1][1] < end) {
                              data.push([data[data.length-1][0], end]);
                            }
                            return data;
                          }
                          function firstBefore(timestamp, datapoints) {
                            for (var i = datapoints.length - 1; i >= 0; i--) {
                              if (datapoints[i][1] < timestamp)
                                return datapoints[i];
                            }
                          }
                          function formatStamp(stamp) {
                            if (typeof stamp === "string")
                              stamp = parseInt(stamp, 10);
                            return new Date(stamp * 1000).toLocaleDateString(window.navigator.userLanguage ||
                                                                             window.navigator.language,
                                                                             { weekday: "long",
                                                                               year: "numeric",
                                                                               month: "long",
                                                                               day: "numeric"
                                                                             });
                          }
                          function tomorrow() {
                            d = new Date();
                            d.setUTCDate(d.getUTCDate()+1);
                            d.setUTCHours(0);
                            d.setUTCMinutes(0);
                            d.setUTCSeconds(0);
                            d.setUTCMilliseconds(0);
                            return d.getTime();
                          }
                          function monthago() {
                            d = new Date();
                            d.setUTCDate(d.getUTCMonth()-1);
                            d.setUTCHours(0);
                            d.setUTCMinutes(0);
                            d.setUTCSeconds(0);
                            d.setUTCMilliseconds(0);
                            return d.getTime();
                          }
                        }
             });
    }
    var n = 0;
    container.find(".legend-dot").each(color);
    function color(idx, elem) {
      var head = $(elem).parent();
      if (!(is_funky && head.next().text() == "0")) {
        $(elem).css("background-color",
                    path_colors[is_funky ? n++ : idx]);
      }
    }
  }
  function select(field) {
    return function (elem) {
             if (elem.key != 'Total')
               return elem[field];
           };
  }
  function defined(val) {
    return typeof val != "undefined";
  }
}
function buildURL(base, params) {
  var kv = [];
  $.each(params,
         function (key, values) {
           if ($.isArray(values)) {
             $.each(values,
                    function (i, value) {
                      if (value)
                        kv.push([key, encodeURIComponent(value)]);
                    });
           } else {
             if (values)
               kv.push([key, encodeURIComponent(values)]);
           }
         });
  kv = kv.map(function (param) { return param[0] +'='+ param[1]; });
  if (kv)
    base += '?' + kv.join('&');
  return base;
}
<|endoftext|>


<commit_before>/**
 * plugin.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2015 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/*global tinymce:true */

tinymce.PluginManager.add('pagebreak', function(editor) {
	var pageBreakClass = 'mce-pagebreak', separatorHtml = editor.getParam('pagebreak_separator', '');

	var pageBreakSeparatorRegExp = new RegExp(separatorHtml.replace(/[\?\.\*\[\]\(\)\{\}\+\^\$\:]/g, function(a) {
		return '\\' + a;
	}), 'gi');

	var pageBreakPlaceHolderHtml = '';

	// Register commands
	editor.addCommand('mcePageBreak', function() {
		if (editor.settings.pagebreak_split_block) {
			editor.insertContent('
' + pageBreakPlaceHolderHtml + '
');
		} else {
			editor.insertContent(pageBreakPlaceHolderHtml);
		}
	});

	// Register buttons
	editor.addButton('pagebreak', {
		title: 'Page break',
		cmd: 'mcePageBreak'
	});

	editor.addMenuItem('pagebreak', {
		text: 'Page break',
		icon: 'pagebreak',
		cmd: 'mcePageBreak',
		context: 'insert'
	});

	editor.on('ResolveName', function(e) {
		if (e.target.nodeName == 'IMG' && editor.dom.hasClass(e.target, pageBreakClass)) {
			e.name = 'pagebreak';
		}
	});

	editor.on('click', function(e) {
		e = e.target;

		if (e.nodeName === 'IMG' && editor.dom.hasClass(e, pageBreakClass)) {
			editor.selection.select(e);
		}
	});

	editor.on('BeforeSetContent', function(e) {
		e.content = e.content.replace(pageBreakSeparatorRegExp, pageBreakPlaceHolderHtml);
	});

	editor.on('PreInit', function() {
		editor.serializer.addNodeFilter('img', function(nodes) {
			var i = nodes.length, node, className;

			while (i--) {
				node = nodes[i];
				className = node.attr('class');
				if (className && className.indexOf('mce-pagebreak') !== -1) {
					// Replace parent block node if pagebreak_split_block is enabled
					var parentNode = node.parent;
					if (editor.schema.getBlockElements()[parentNode.name] && editor.settings.pagebreak_split_block) {
						parentNode.type = 3;
						parentNode.value = separatorHtml;
						parentNode.raw = true;
						node.remove();
						continue;
					}

					node.type = 3;
					node.value = separatorHtml;
					node.raw = true;
				}
			}
		});
	});
});<commit_msg>Fixed bug where pagebreaks were editable to imagetools.<commit_after>/**
 * plugin.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2015 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/*global tinymce:true */

tinymce.PluginManager.add('pagebreak', function(editor) {
	var pageBreakClass = 'mce-pagebreak', separatorHtml = editor.getParam('pagebreak_separator', '');

	var pageBreakSeparatorRegExp = new RegExp(separatorHtml.replace(/[\?\.\*\[\]\(\)\{\}\+\^\$\:]/g, function(a) {
		return '\\' + a;
	}), 'gi');

	var pageBreakPlaceHolderHtml = '';

	// Register commands
	editor.addCommand('mcePageBreak', function() {
		if (editor.settings.pagebreak_split_block) {
			editor.insertContent('
' + pageBreakPlaceHolderHtml + '
');
		} else {
			editor.insertContent(pageBreakPlaceHolderHtml);
		}
	});

	// Register buttons
	editor.addButton('pagebreak', {
		title: 'Page break',
		cmd: 'mcePageBreak'
	});

	editor.addMenuItem('pagebreak', {
		text: 'Page break',
		icon: 'pagebreak',
		cmd: 'mcePageBreak',
		context: 'insert'
	});

	editor.on('ResolveName', function(e) {
		if (e.target.nodeName == 'IMG' && editor.dom.hasClass(e.target, pageBreakClass)) {
			e.name = 'pagebreak';
		}
	});

	editor.on('click', function(e) {
		e = e.target;

		if (e.nodeName === 'IMG' && editor.dom.hasClass(e, pageBreakClass)) {
			editor.selection.select(e);
		}
	});

	editor.on('BeforeSetContent', function(e) {
		e.content = e.content.replace(pageBreakSeparatorRegExp, pageBreakPlaceHolderHtml);
	});

	editor.on('PreInit', function() {
		editor.serializer.addNodeFilter('img', function(nodes) {
			var i = nodes.length, node, className;

			while (i--) {
				node = nodes[i];
				className = node.attr('class');
				if (className && className.indexOf('mce-pagebreak') !== -1) {
					// Replace parent block node if pagebreak_split_block is enabled
					var parentNode = node.parent;
					if (editor.schema.getBlockElements()[parentNode.name] && editor.settings.pagebreak_split_block) {
						parentNode.type = 3;
						parentNode.value = separatorHtml;
						parentNode.raw = true;
						node.remove();
						continue;
					}

					node.type = 3;
					node.value = separatorHtml;
					node.raw = true;
				}
			}
		});
	});
});
<|endoftext|>


<commit_before>module.exports = function nodeFetchCookieDecorator (nodeFetch, jar) {
  const fetchCookie = require('./')(nodeFetch, jar)

  return function nodeFetchCookie (url, userOptions = {}) {
    const opts = Object.assign({}, userOptions, { redirect: 'manual' })

    // Forward identical options to wrapped node-fetch but tell to not handle redirection.
    return fetchCookie(url, opts)
      .then(res => {
        const isRedirect = (res.status === 303 || res.status === 301 || res.status === 302 || res.status === 307)

        // Interpret the proprietary "redirect" option in the same way that node-fetch does.
        if (isRedirect && userOptions.redirect !== 'manual' && userOptions.follow !== 0) {

          let statusOpts = {
            // Since the "follow" flag is not relevant for node-fetch in this case,
            // we'll hijack it for our internal bookkeeping.
	    follow: userOptions.follow !== undefined ? userOptions.follow - 1 : undefined,
          }

          if (res.status !== 307) {
            statusOpts.method= "GET",
            statusOpts.body= null
          }

          const redirectOpts = Object.assign({}, userOptions, statusOpts)

          return nodeFetchCookie(res.headers.get("location"), redirectOpts)
        } else {
          return res
        }
      })
  }
}
<commit_msg>Formatting<commit_after>module.exports = function nodeFetchCookieDecorator (nodeFetch, jar) {
  const fetchCookie = require('./')(nodeFetch, jar)

  return function nodeFetchCookie (url, userOptions = {}) {
    const opts = Object.assign({}, userOptions, { redirect: 'manual' })

    // Forward identical options to wrapped node-fetch but tell to not handle redirection.
    return fetchCookie(url, opts)
      .then(res => {
        const isRedirect = (res.status === 303 || res.status === 301 || res.status === 302 || res.status === 307)

        // Interpret the proprietary "redirect" option in the same way that node-fetch does.
        if (isRedirect && userOptions.redirect !== 'manual' && userOptions.follow !== 0) {

          let statusOpts = {
            // Since the "follow" flag is not relevant for node-fetch in this case,
            // we'll hijack it for our internal bookkeeping.
	      follow: userOptions.follow !== undefined ? userOptions.follow - 1 : undefined,
          }

          if (res.status !== 307) {
            statusOpts.method= "GET",
            statusOpts.body= null
          }

          const redirectOpts = Object.assign({}, userOptions, statusOpts)

          return nodeFetchCookie(res.headers.get("location"), redirectOpts)
        } else {
          return res
        }
      })
  }
}
<|endoftext|>


<commit_before>import { gltfInput } from './input.js';

import { GltfView, computePrimitiveCentroids, loadGltf, loadEnvironment, initKtxLib, initDracoLib } from 'gltf-sample-viewer';

import { UIModel } from './logic/uimodel.js';
import { app } from './ui/ui.js';
import { Observable, from } from 'rxjs';
import { mergeMap, filter } from 'rxjs/operators';
import { gltfModelPathProvider } from './model_path_provider.js';

async function main()
{
    const canvas = document.getElementById("canvas");
    const view = new GltfView(canvas);
    const state = view.createState();

    initDracoLib();
    initKtxLib(view);

    loadEnvironment("assets/environments/footprint_court_512.hdr", view).then( (environment) => {
        state.environment = environment;
    });

    const pathProvider = new gltfModelPathProvider('assets/models/2.0/model-index.json');
    await pathProvider.initialize();

    const uiModel = await new UIModel(app, pathProvider);

    // whenever a new model is selected, load it and when complete pass the loaded gltf
    // into a stream back into the UI
    const gltfLoadedObservable = uiModel.model.pipe(
        mergeMap( (gltf_path, additionalFiles) =>
        {
            return from(loadGltf(gltf_path, view, additionalFiles).then( (gltf) => {
                state.gltf = gltf;
                const scene = state.gltf.scenes[state.sceneIndex];
                scene.applyTransformHierarchy(state.gltf);
                computePrimitiveCentroids(state.gltf);
                state.userCamera.fitViewToScene(state.gltf, state.sceneIndex);
                state.userCamera.updatePosition();
                state.animationIndices = [0];
                state.animationTimer.start();
                return state.gltf;
            })
            );
        })
    );

    uiModel.attachGltfLoaded(gltfLoadedObservable);

    uiModel.scene.subscribe( scene => {
        state.sceneIndex = scene;
    });

    uiModel.camera.pipe(filter(camera => camera === "User Camera")).subscribe( () => {
        state.cameraIndex = undefined;
    });
    uiModel.camera.pipe(filter(camera => camera !== "User Camera")).subscribe( camera => {
        state.cameraIndex = camera;
    });
    uiModel.variant.subscribe( variant => {
        state.variant = variant;
        console.log(variant);
    });

    uiModel.tonemap.subscribe( tonemap => {
        state.renderingParameters.toneMap = tonemap;
    });

    uiModel.debugchannel.subscribe( debugchannel => {
        state.renderingParameters.debugOutput = debugchannel;
    });

    uiModel.skinningEnabled.subscribe( skinningEnabled => {
        state.skinningEnabled = skinningEnabled;
    });

    uiModel.morphingEnabled.subscribe( morphingEnabled => {
        state.morphingEnabled = morphingEnabled;
    });

    uiModel.iblEnabled.subscribe( iblEnabled => {
        state.renderingParameters.useIBL = iblEnabled;
    });

    uiModel.punctualLightsEnabled.subscribe( punctualLightsEnabled => {
        state.renderingParameters.usePunctual = punctualLightsEnabled;
    });

    uiModel.environmentEnabled.subscribe( environmentEnabled => {
        state.renderingParameters.environmentBackground = environmentEnabled;
    });

    uiModel.clearColor.subscribe( clearColor => {
        state.renderingParameters.clearColor = clearColor;
    });

    const input = new gltfInput(canvas);
    input.setupGlobalInputBindings(document);
    input.setupCanvasInputBindings(canvas);
    input.onRotate = (deltaX, deltaY) =>
    {
        state.userCamera.rotate(deltaX, deltaY);
        state.userCamera.updatePosition();
    };
    input.onPan = (deltaX, deltaY) =>
    {
        state.userCamera.pan(deltaX, deltaY);
        state.userCamera.updatePosition();
    };
    input.onZoom = (delta) =>
    {
        state.userCamera.zoomIn(delta);
        state.userCamera.updatePosition();
    };
    input.onDropFiles = (mainFile, additionalFiles) => {
        if (mainFile.name.endsWith(".hdr"))
        {
            loadEnvironment(mainFile, view).then( (environment) => {
                state.environment = environment;
                });
        }
    };

    await view.startRendering(state);
}

export { main };
<commit_msg>ui now updates the selected variant<commit_after>import { gltfInput } from './input.js';

import { GltfView, computePrimitiveCentroids, loadGltf, loadEnvironment, initKtxLib, initDracoLib } from 'gltf-sample-viewer';

import { UIModel } from './logic/uimodel.js';
import { app } from './ui/ui.js';
import { Observable, from } from 'rxjs';
import { mergeMap, filter } from 'rxjs/operators';
import { gltfModelPathProvider } from './model_path_provider.js';

async function main()
{
    const canvas = document.getElementById("canvas");
    const view = new GltfView(canvas);
    const state = view.createState();

    initDracoLib();
    initKtxLib(view);

    loadEnvironment("assets/environments/footprint_court_512.hdr", view).then( (environment) => {
        state.environment = environment;
    });

    const pathProvider = new gltfModelPathProvider('assets/models/2.0/model-index.json');
    await pathProvider.initialize();

    const uiModel = await new UIModel(app, pathProvider);

    // whenever a new model is selected, load it and when complete pass the loaded gltf
    // into a stream back into the UI
    const gltfLoadedObservable = uiModel.model.pipe(
        mergeMap( (gltf_path, additionalFiles) =>
        {
            return from(loadGltf(gltf_path, view, additionalFiles).then( (gltf) => {
                state.gltf = gltf;
                const scene = state.gltf.scenes[state.sceneIndex];
                scene.applyTransformHierarchy(state.gltf);
                computePrimitiveCentroids(state.gltf);
                state.userCamera.fitViewToScene(state.gltf, state.sceneIndex);
                state.userCamera.updatePosition();
                state.animationIndices = [0];
                state.animationTimer.start();
                return state.gltf;
            })
            );
        })
    );

    uiModel.attachGltfLoaded(gltfLoadedObservable);

    uiModel.scene.subscribe( scene => {
        state.sceneIndex = scene;
    });

    uiModel.camera.pipe(filter(camera => camera === "User Camera")).subscribe( () => {
        state.cameraIndex = undefined;
    });
    uiModel.camera.pipe(filter(camera => camera !== "User Camera")).subscribe( camera => {
        state.cameraIndex = camera;
    });

    uiModel.variant.subscribe( variant => {
        state.renderingParameters.variant = variant;
    });

    uiModel.tonemap.subscribe( tonemap => {
        state.renderingParameters.toneMap = tonemap;
    });

    uiModel.debugchannel.subscribe( debugchannel => {
        state.renderingParameters.debugOutput = debugchannel;
    });

    uiModel.skinningEnabled.subscribe( skinningEnabled => {
        state.skinningEnabled = skinningEnabled;
    });

    uiModel.morphingEnabled.subscribe( morphingEnabled => {
        state.morphingEnabled = morphingEnabled;
    });

    uiModel.iblEnabled.subscribe( iblEnabled => {
        state.renderingParameters.useIBL = iblEnabled;
    });

    uiModel.punctualLightsEnabled.subscribe( punctualLightsEnabled => {
        state.renderingParameters.usePunctual = punctualLightsEnabled;
    });

    uiModel.environmentEnabled.subscribe( environmentEnabled => {
        state.renderingParameters.environmentBackground = environmentEnabled;
    });

    uiModel.clearColor.subscribe( clearColor => {
        state.renderingParameters.clearColor = clearColor;
    });

    const input = new gltfInput(canvas);
    input.setupGlobalInputBindings(document);
    input.setupCanvasInputBindings(canvas);
    input.onRotate = (deltaX, deltaY) =>
    {
        state.userCamera.rotate(deltaX, deltaY);
        state.userCamera.updatePosition();
    };
    input.onPan = (deltaX, deltaY) =>
    {
        state.userCamera.pan(deltaX, deltaY);
        state.userCamera.updatePosition();
    };
    input.onZoom = (delta) =>
    {
        state.userCamera.zoomIn(delta);
        state.userCamera.updatePosition();
    };
    input.onDropFiles = (mainFile, additionalFiles) => {
        if (mainFile.name.endsWith(".hdr"))
        {
            loadEnvironment(mainFile, view).then( (environment) => {
                state.environment = environment;
                });
        }
    };

    await view.startRendering(state);
}

export { main };
<|endoftext|>


<commit_before>"use import";

import .LogClass;

exports = LogClass('lib.Sortable', function(logger) {

	this.toStringPush = function(indexer) {
		if (!this._toString || !this._toString.push) {
			this._toString = [this.toString];
		} else {
			this._toString.push(this.toString);
		}

		this.toString = indexer;
	}

	this.toStringPop = function() {
		this.toString = this._toString.pop();
	}
});

var zeroPadding = [];
function ensurePadding(n) {
	for (var i = zeroPadding.length; i < n; ++i) {
		var str = [];
		for (var j = 0; j < i; ++j) { str.push('0'); }
		zeroPadding[i] = str.join('');
	}
}

/**
 * Here we handle arbitrary sorting indexes transparently converting numbers to strings
 * for efficient sorting with toString.  Unfortunately, this does not work for large floating
 * point values, but that functionality could theoretically be added if desired.
 */
exports.sort = function(arr, indexer) {

	var len = arr.length,
		index = new Array(len);

	function sortIndex(i) { return this[i]; }

	for (var i = 0; i < len; ++i) {
		index[i] = indexer.call(arr[i], i);
		arr[i].toStringPush(bind(index, sortIndex, i));
	}

	if (typeof index[0] == 'number') {
		// we do two passes here:
		//  1: find the max and min numerical indices
		//  2: convert the indices to strings with appropriate zero-padding
		var largest = index[0],
			smallest = index[0];

		for (var i = 1; i < len; ++i) {
			if (index[i] > largest) {
				largest = index[i];
			} else if (index[i] < smallest) {
				smallest = index[i];
			}
		}

		// we have to be very careful here - large floating point numbers will break the
		// string padding code
		var paddingPositive = String(Math.floor(largest)).length,
			paddingNegative = String(Math.floor(smallest)).length;

		ensurePadding(Math.max(paddingPositive, paddingNegative));

		var strLen;
		for (var i = 0; i < len; ++i) {
			var val = index[i];
			if (val < 0) {
				val = -(smallest - val);
				strLen = ('' + Math.floor(val)).length;
				index[i] = '-' + zeroPadding[paddingNegative - strLen] + val;
			} else {
				strLen = ('' + Math.floor(val)).length;
				index[i] = zeroPadding[paddingPositive - strLen] + val;
			}
		}
	}

	Array.prototype.sort.apply(arr);

	for (var i = 0; i < len; ++i) {
		arr[i].toStringPop(indexer);
	}
}
<commit_msg>update Sortable to take multiple sort indexers passed in to sort(), independently handled with results joined by '|' characters<commit_after>"use import";

import .LogClass;

exports = LogClass('lib.Sortable', function(logger) {

	this.toStringPush = function(indexer) {
		if (!this._toString || !this._toString.push) {
			this._toString = [this.toString];
		} else {
			this._toString.push(this.toString);
		}

		this.toString = indexer;
	}

	this.toStringPop = function() {
		this.toString = this._toString.pop();
	}
});

var zeroPadding = [];
function ensurePadding(n) {
	for (var i = zeroPadding.length; i < n; ++i) {
		var str = [];
		for (var j = 0; j < i; ++j) { str.push('0'); }
		zeroPadding[i] = str.join('');
	}
}

/**
 * Here we handle arbitrary sorting indexes transparently converting numbers to strings
 * for efficient sorting with toString.  Unfortunately, this does not work for large floating
 * point values, but that functionality could theoretically be added if desired.
 */
exports.sort = function(arr, indexer) {

	var len = arr.length,
		index = new Array(len),
		result = new Array(len),
		toString = new Array(len),
		indexers = Array.prototype.slice.call(arguments, 1),
		haveMultiple = !!indexers[1];

	function sortIndex(i) { return this[i]; }

	if (haveMultiple) {
		for (var i = 0; i < len; ++i) {
			result[i] = [];
		}
	}

	for (var k = 0, indexer; indexer = indexers[k]; ++k) {
		for (var i = 0; i < len; ++i) {
			index[i] = indexer.call(arr[i], i);
		}

		if (typeof index[0] == 'number') {
			// we do two passes here:
			//  1: find the max and min numerical indices
			//  2: convert the indices to strings with appropriate zero-padding
			var largest = index[0],
				smallest = index[0];

			for (var i = 1; i < len; ++i) {
				if (index[i] > largest) {
					largest = index[i];
				} else if (index[i] < smallest) {
					smallest = index[i];
				}
			}

			// we have to be very careful here - large floating point numbers will break the
			// string padding code
			var paddingPositive = String(Math.floor(largest)).length,
				paddingNegative = String(Math.floor(smallest)).length;

			ensurePadding(Math.max(paddingPositive, paddingNegative));

			var strLen;
			for (var i = 0; i < len; ++i) {
				var val = index[i];
				if (val < 0) {
					val = -(smallest - val);
					strLen = ('' + Math.floor(val)).length;
					index[i] = '-' + zeroPadding[paddingNegative - strLen] + val;
				} else {
					strLen = ('' + Math.floor(val)).length;
					index[i] = zeroPadding[paddingPositive - strLen] + val;
				}
			}
		}

		if (haveMultiple) {
			for (var i = 0; i < len; ++i) {
				result[i].push(index[i]);
			}
		} else {
			result = index;
		}
	}

	for (var i = 0; i < len; ++i) {
		if (haveMultiple) {
			result[i] = result[i].join('|');
		}

		toString[i] = arr[i].toString;
		arr[i].toString = bind(result, sortIndex, i);
	}

	Array.prototype.sort.apply(arr);

	for (var i = 0; i < len; ++i) {
		arr[i].toString = toString[i];
	}
}
<|endoftext|>


<commit_before>(function() {
    /*
     * Setup jquery
     * TODO: this is application-wide setup... Better solution?
     */
    var csrf_token = $('meta[name=csrf_token]').attr('content');
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': csrf_token,
        }
    });

    /*
     * Main class "Tele"
     */
    function Tele(class_name)
    {
        this.tree = {
            'class' : class_name,
            'calls' : []
        }
    }

    /*
     * Prepare args: different serialization for values and closures
     */
    Tele.prototype.make_args = function(args){
        var arr = [];
        for(var i in args) {
            var a = args[i];
            if(typeof a == 'function') {
                var q = new Tele('<closure>');
                a(q);
                arr.push(q.tree);
            } else
                arr.push({v:a});
        }
        return arr;
    }

    /*
     * Helper for creating Eloquent replica methods
     */
    function make_call(fname)
    {
        return function() {
            this.tree.calls.push({
                'name': fname,
                'args': this.make_args(arguments)
            });
            return this;
        }
    }

    /*
     * Helper for "chain-finish" calls which sends JSON tree to server.
     * Builded metthod returns a promise and accepts a callback as a parameter.
     */
    function make_send_call(fname) {
        var func = make_call(fname);

        return function() {
            // SEE: http://stackoverflow.com/a/4775938
            var args = Array.prototype.slice.call(arguments);

            var callback = args.pop();  // last argument is always callback
            func.apply(this, args);     // call func in context of Tele object

            // TODO: get name of route from package config
            return $.ajax({
                url: '/telekinesis',
                type: 'POST',
                data: JSON.stringify(this.tree),
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: callback,
            });
        }
    }

    /*
     * List of mirrored Eloquent's methods
     */
    Tele.prototype.where    = make_call('where');
    Tele.prototype.whereHas = make_call('whereHas');
    Tele.prototype.get      = make_send_call('get');

    /*
     * Global helpers for Telekinesis usage
     */
    window.T = function( class_name ){
        return new Tele(class_name);
    }
})();

/* -------------------------- */
T('\\App\\Vacancy').where('test', '<', 5).get(function(data){
    console.log("data>>>", data);
});
<commit_msg>(b) new testing code... It must be removed...<commit_after>(function() {
    /*
     * Setup jquery
     * TODO: this is application-wide setup... Better solution?
     */
    var csrf_token = $('meta[name=csrf_token]').attr('content');
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': csrf_token,
        }
    });

    /*
     * Main class "Tele"
     */
    function Tele(class_name)
    {
        this.tree = {
            'class' : class_name,
            'calls' : []
        }
    }

    /*
     * Prepare args: different serialization for values and closures
     */
    Tele.prototype.make_args = function(args){
        var arr = [];
        for(var i in args) {
            var a = args[i];
            if(typeof a == 'function') {
                var q = new Tele('<closure>');
                a(q);
                arr.push(q.tree);
            } else
                arr.push({v:a});
        }
        return arr;
    }

    /*
     * Helper for creating Eloquent replica methods
     */
    function make_call(fname)
    {
        return function() {
            this.tree.calls.push({
                'name': fname,
                'args': this.make_args(arguments)
            });
            return this;
        }
    }

    /*
     * Helper for "chain-finish" calls which sends JSON tree to server.
     * Builded metthod returns a promise and accepts a callback as a parameter.
     */
    function make_send_call(fname) {
        var func = make_call(fname);

        return function() {
            // SEE: http://stackoverflow.com/a/4775938
            var args = Array.prototype.slice.call(arguments);

            var callback = args.pop();  // last argument is always callback
            func.apply(this, args);     // call func in context of Tele object

            // TODO: get name of route from package config
            return $.ajax({
                url: '/telekinesis',
                type: 'POST',
                data: JSON.stringify(this.tree),
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: callback,
            });
        }
    }

    /*
     * List of mirrored Eloquent's methods
     */
    Tele.prototype.where    = make_call('where');
    Tele.prototype.whereHas = make_call('whereHas');
    Tele.prototype.get      = make_send_call('get');

    /*
     * Global helpers for Telekinesis usage
     */
    window.T = function( class_name ){
        return new Tele(class_name);
    }
})();

/* -------------------------- */
T('\\App\\Resume').whereHas('vacancies', function(q){
    q.where('test', '>', 0);
}).get(function(data){
    console.log("data>>>", data);
});
<|endoftext|>


<commit_before>(function () {
  //
  // Dependencies
  //

  var argv = require('minimist')(process.argv.slice(2));
  var Compiler = require('docxtemplater');
  var ngExp = require('angular-expressions');
  var q = require('q');
  var fs = require('fs');
  var buffer = [];
  var input = argv.s === '-' ? process.stdin : fs.createReadStream(argv.s);
  var output = argv.o === undefined || argv.o === false ? process.stdout : fs.createWriteStream(argv.o);

  //
  // Runtime
  //

  checkTemplate(argv.t)
    .then(readData)
    .then(validateData)
    .then(compileData)
    .then(outputCompiled)
    .catch(handleError);

  //
  // Implementations
  //

  /**
   * Verifies the existance of the template
   *
   * @param  {String} template Path to the template file
   * @return {Promise}
   */
  function checkTemplate(template) {
    var def = q.defer();

    fs.access(template || '', fs.R_OK, function (err) {
      if (err) {
        def.reject(err);
      } else {
        def.resolve();
      }
    });

    return def.promise;
  }

  /**
   * Reads the data from input
   *
   * @return {Promise}
   */
  function readData () {
    var buffer =[];
    var def = q.defer();

    input.on('data', function (data) {
      buffer.push(new Buffer(data));
      def.notify(data);
    });

    input.on('end', function () {
      def.resolve(Buffer.concat(buffer));
    });

    input.on('error', function (err) {
      def.reject(err);
    });

    return def.promise;
  }

  /**
   * Validates and parses data
   *
   * @param  {String}  data String with data coded in JSON
   * @return {Promise}
   */
  function validateData (data) {
    return JSON.parse(data.toString());
  }

  /**
   * Compilate data into the compiler
   *
   * @param  {String}  data String with data coded in JSON
   * @return {Promise}
   */
  function compileData (data) {
    var template = fs.readFileSync(argv.t);
    var options = {
      parser: getNgExpParser(),
      delimiters: {
        start: '${',
        end: '}'
      }
    };
    var doc = new Compiler(template).setOptions(options);

    doc.setData(data);

    doc.render();

    return doc.getZip().generate({type: 'nodebuffer'});
  }

  function getNgExpParser() {
    return function (tag) {
      return {
        get: tag == '.' ? function (s) { return s; } : ngExp.compile(tag)
      };
    };
  }

  function handleError (err) {
    process.stderr.write(err.message + '\n');
    process.exit(1);
  }

  function outputCompiled (data) {
    output.end(data);
  }
})();<commit_msg>Removido script index<commit_after><|endoftext|>


<commit_before>//
// RS485 Modbus RTU Control for Taiwan Hitachi Air Conditioner
// RESTful web services server.
//
// To enable ECMAScript 2015 features, use the following command to run:
//   node --harmony app.js
//
// Put app.js and index.html file in /root/index.html
//
// Author: Yu-Hua Chang
//
"use strict";
process.title = 'node-app';

////////////////////////////////////////////////////////////////////////////////
// Settings
const HTTP_PORT = 8080;

////////////////////////////////////////////////////////////////////////////////
// Import libraries
const http = require('http');
const url = require('url');
const SerialPort = require("serialport").SerialPort;
const fs = require('fs');

////////////////////////////////////////////////////////////////////////////////
// Request Queue
const requestQueue = [];

////////////////////////////////////////////////////////////////////////////////
// open serial port to MCU
const serial = new SerialPort("/dev/ttyS0", {
  baudrate: 57600
});

////////////////////////////////////////////////////////////////////////////////
// http server to server the static pages
const server = http.createServer((request, response) => {

  if (requestQueue.length > 0) {
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.writeHead(423, {'Content-Type': 'text/plain'});
    response.write('423 Locked\n');
    response.end();
    return;
  }

  // lock
  requestQueue.push({
    'slaveAddr': undefined,
    'functionCode': undefined,
    'registerAddr': undefined,
    'registerValue': undefined,
    'response': response
  });

  let body = [];
  request.on('error', (err) => {
    console.error(err);
  }).on('data', (chunk) => {
    body.push(chunk);
  }).on('end', () => {
    body = Buffer.concat(body).toString();

    // retrieve slave address and target register address from url
    let req = request.url.split('/');
    if (req.length == 3) {
      requestQueue[0].slaveAddr = parseInt(req[1], 16);
      requestQueue[0].registerAddr = parseInt(req[2], 16);
    }

    // determine function by request method.
    if (request.method === 'GET') {
      // read holding register
      requestQueue[0].functionCode = 0x03;
      requestQueue[0].registerValue = 0x00;
    } else if (request.method === 'PUT') {
      // write single register
      requestQueue[0].functionCode = 0x06;
      try {
        let json = JSON.parse(body);
        requestQueue[0].registerValue = json.value;
      } catch (err) {
        console.error(err);
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.writeHead(400, {'Content-Type': 'text/plain'});
        response.write('400 Bad Request\n');
        response.end();
        return;
      }
    } else {
      response.setHeader("Access-Control-Allow-Origin", "*");
      response.writeHead(405, {'Content-Type': 'text/plain'});
      response.write('405 Method Not Allowed\n');
      response.end();
      return;
    }

    if (requestQueue[0].slaveAddr === undefined || requestQueue[0].registerAddr === undefined) {
      response.setHeader("Access-Control-Allow-Origin", "*");
      response.writeHead(404, {'Content-Type': 'text/plain'});
      response.write('404 Not Found\n');
      response.end();
      return;
    } else {

      // prepare the binary data to be sent to MCU.
      let buffer = new Buffer(4);
      buffer[0] = requestQueue[0].slaveAddr;
      buffer[1] = requestQueue[0].functionCode;
      buffer[2] = requestQueue[0].registerAddr;
      buffer[3] = requestQueue[0].registerValue;

      console.log('slaveAddr: 0x%s functionCode: 0x%s registerAddr: 0x%s registerValue: 0x%s',
          buffer[0].toString(16), buffer[1].toString(16), buffer[2].toString(16), buffer[3].toString(16));

      // send to MCU
      serial.write(buffer, (err) => {
        if (err) {
          return console.log('Error on write: ', err.message);
        }
        console.log('packet sent.');
        // now we wait for the response...
      });
    }
  });
});

////////////////////////////////////////////////////////////////////////////////
// run server
serial.on('open', (err) => {
  if (err) {
    console.log('serial port opened has error:', err);
    return;
  }
  console.log('serial port opened.');

  // Listen http port.
  server.listen(HTTP_PORT, () => {
    console.log("%s HTTP Server listening on %s", new Date(), HTTP_PORT);
  });
});

serial.on('error', (err) => {
  console.log('SerialPort Error: ', err.message);
});

// process the response from MCU
serial.on('data', (data) => {

  // the response will be one byte unsigned integer.
  // if reading register success, the return value will be an integer
  // and is 0xFF if it failed.
  // if writeing register success, the return value will be 0x00
  // and any non-zero value if failed.
  requestQueue[0].response.setHeader("Access-Control-Allow-Origin", "*");
  requestQueue[0].response.writeHead(200, {'Content-Type': 'application/json'});
  requestQueue[0].response.write('{ "value": ' + data[0] + ' }');
  requestQueue[0].response.end();

  // unlock
  let req = requestQueue.pop();
  console.log('response to => slaveAddr: 0x%s functionCode: 0x%s registerAddr: 0x%s registerValue: 0x%s => value: %s',
    req.slaveAddr, req.functionCode, req.registerAddr, req.registerValue, data[0]);
});

<commit_msg>fix preflight issue<commit_after>//
// RS485 Modbus RTU Control for Taiwan Hitachi Air Conditioner
// RESTful web services server.
//
// To enable ECMAScript 2015 features, use the following command to run:
//   node --harmony app.js
//
// Put app.js and index.html file in /root/index.html
//
// Author: Yu-Hua Chang
//
"use strict";
process.title = 'node-app';

////////////////////////////////////////////////////////////////////////////////
// Settings
const HTTP_PORT = 8080;

////////////////////////////////////////////////////////////////////////////////
// Import libraries
const http = require('http');
const url = require('url');
const SerialPort = require("serialport").SerialPort;
const fs = require('fs');

////////////////////////////////////////////////////////////////////////////////
// Request Queue
const requestQueue = [];

////////////////////////////////////////////////////////////////////////////////
// open serial port to MCU
const serial = new SerialPort("/dev/ttyS0", {
  baudrate: 57600
});

////////////////////////////////////////////////////////////////////////////////
// http server to server the static pages
const server = http.createServer((request, response) => {

  if (requestQueue.length > 0) {
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.writeHead(423, {'Content-Type': 'text/plain'});
    response.write('423 Locked\n');
    response.end();
    return;
  }

  // lock
  requestQueue.push({
    'slaveAddr': undefined,
    'functionCode': undefined,
    'registerAddr': undefined,
    'registerValue': undefined,
    'response': response
  });

  let body = [];
  request.on('error', (err) => {
    console.error(err);
  }).on('data', (chunk) => {
    body.push(chunk);
  }).on('end', () => {
    body = Buffer.concat(body).toString();

    // retrieve slave address and target register address from url
    let req = request.url.split('/');
    if (req.length == 3) {
      requestQueue[0].slaveAddr = parseInt(req[1], 16);
      requestQueue[0].registerAddr = parseInt(req[2], 16);
    }

    // determine function by request method.
    if (request.method === 'GET') {
      // read holding register
      requestQueue[0].functionCode = 0x03;
      requestQueue[0].registerValue = 0x00;
    } else if (request.method === 'PUT') {
      // write single register
      requestQueue[0].functionCode = 0x06;
      try {
        let json = JSON.parse(body);
        requestQueue[0].registerValue = json.value;
      } catch (err) {
        console.error(err);
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.writeHead(400, {'Content-Type': 'text/plain'});
        response.write('400 Bad Request\n');
        response.end();
        requestQueue.pop();
        return;
      }
    } else if (request.method === 'OPTIONS') {
      // handle preflight
      console.log('preflight header', request.headers);
      response.setHeader("Access-Control-Allow-Origin", "*");
      response.setHeader("Access-Control-Allow-Methods", "GET, PUT");
      response.setHeader("Access-Control-Allow-Headers", "Content-Type");
      response.writeHead(200);
      response.end();
      requestQueue.pop();
      return;
    } else {
      response.setHeader("Access-Control-Allow-Origin", "*");
      response.writeHead(405, {'Content-Type': 'text/plain'});
      response.write('405 Method Not Allowed\n');
      response.end();
      requestQueue.pop();
      return;
    }

    if (requestQueue[0].slaveAddr === undefined || requestQueue[0].registerAddr === undefined) {
      response.setHeader("Access-Control-Allow-Origin", "*");
      response.writeHead(404, {'Content-Type': 'text/plain'});
      response.write('404 Not Found\n');
      response.end();
      requestQueue.pop();
      return;
    } else {

      // prepare the binary data to be sent to MCU.
      let buffer = new Buffer(4);
      buffer[0] = requestQueue[0].slaveAddr;
      buffer[1] = requestQueue[0].functionCode;
      buffer[2] = requestQueue[0].registerAddr;
      buffer[3] = requestQueue[0].registerValue;

      console.log('slaveAddr: 0x%s functionCode: 0x%s registerAddr: 0x%s registerValue: 0x%s',
          buffer[0].toString(16), buffer[1].toString(16), buffer[2].toString(16), buffer[3].toString(16));

      // send to MCU
      serial.write(buffer, (err) => {
        if (err) {
          return console.log('Error on write: ', err.message);
        }
        console.log('packet sent.');
        // now we wait for the response...
      });
    }
  });
});

////////////////////////////////////////////////////////////////////////////////
// run server
serial.on('open', (err) => {
  if (err) {
    console.log('serial port opened has error:', err);
    return;
  }
  console.log('serial port opened.');

  // Listen http port.
  server.listen(HTTP_PORT, () => {
    console.log("%s HTTP Server listening on %s", new Date(), HTTP_PORT);
  });
});

serial.on('error', (err) => {
  console.log('SerialPort Error: ', err.message);
});

// process the response from MCU
serial.on('data', (data) => {

  // the response will be one byte unsigned integer.
  // if reading register success, the return value will be an integer
  // and is 0xFF if it failed.
  // if writeing register success, the return value will be 0x00
  // and any non-zero value if failed.
  requestQueue[0].response.setHeader("Access-Control-Allow-Origin", "*");
  requestQueue[0].response.writeHead(200, {'Content-Type': 'application/json'});
  requestQueue[0].response.write('{ "value": ' + data[0] + ' }');
  requestQueue[0].response.end();

  // unlock
  let req = requestQueue.pop();
  console.log('response to => slaveAddr: 0x%s functionCode: 0x%s registerAddr: 0x%s registerValue: 0x%s => value: %s',
    req.slaveAddr, req.functionCode, req.registerAddr, req.registerValue, data[0]);
});

<|endoftext|>


<commit_before>if (jsio.__env.name == 'browser') {
	jsio('external .sizzle import Sizzle');

	var DOM2 = typeof HTMLElement === "object";
	function isElement(el) {
		return el &&
			(DOM2 ? el instanceof HTMLElement
				: typeof el.nodeType == 'number' && typeof el.nodeName == 'string');
	}

	function isWindow(el) {
		return el && !isElement(el) && isElement(el.document);
	}

	var singleId = /^#([\w-]+)$/;

	var $ = exports.$ = function(selector, win) {
		switch(typeof selector) {
			case 'object':
				if (isElement(selector)) {
					return $.remove(selector);
				} else if (isElement(selector.document && selector.document.body)) {
					return $.size(selector);
				}
				return $.create(selector);
			case 'string':
				if (singleId.test(selector)) { return $.id(selector.substring(1), win); }
				return Sizzle.apply(GLOBAL, arguments);
		}
	}

	$.id = function(id, win) { return typeof id == 'string' ? (win || window).document.getElementById(id) : id; }

	$.create = function(params) {
		var doc = (params.win || window).document;
		if(!params) { params = 'div'; }
		if(typeof params == 'string') { return doc.createElement(params); }

		var el = doc.createElement(params.tag || params.tagName || 'div');
		if(params.style) { $.style(el, params.style); }
		if(params.src) { el.src = params.src; }
		if(params.attrs) {
			for(attr in params.attrs) {
				el.setAttribute(attr, params.attrs[attr]);
			}
		}

		if(params['class'] || params['className']) {
			el.className = params['class'] || params['className'];
		}

		if(params.parent) { params.parent.appendChild(el); }
		if ('before' in params) {
			if (params.before) {
				params.before.parentNode.insertBefore(el, params.before);
			}
		}
		if(params.html) { el.innerHTML = params.html; }
		if(params.text) { $.setText(el, params.text); }
		return el;
	}

	$.show = function(el, how) { $.id(el).style.display = how || 'block'; }
	$.hide = function(el) { $.id(el).style.display = 'none'; }

	// accepts an array or a space-delimited string of classNames
	$.addClass = function(el, classNames) {
		if (!el) { return; }
		var el = $.id(el);
		if(typeof classNames == "string") {
			classNames = classNames.split(' ');
		}

		var current = ' ' + el.className + ' ';
		for(var i = 0, len = classNames.length, c; (c = classNames[i]) || i < len; ++i) {
			if(current.indexOf(' '+c+' ') == -1) {
				current += c + ' ';
			}
		}

		el.className = current;
		return $;
	}

	$.getTag = function(from, tag) { return from.getElementsByTagName(tag); }

	$.removeClass = function(el, classNames) {
		if (!el) { return; }
		var el = $.id(el);
		el.className = (' ' + el.className + ' ')
			.replace(' ', '  ')
			.replace(new RegExp('( ' + classNames.replace('\s+', ' | ').replace('-','\-') + ' )', 'g'), '')
			.replace(/\s+/, ' ')
			.replace(/^\s+|\s+%/, '');
	}

	function ieGetAlpha(el) {
		try {
			return el.filters.item("alpha");
		} catch(e) {}

		try {
			return el.filters.item("progid:DXImageTransform.Microsoft.Alpha");
		} catch(e) {}

		return null;
	}

	$.style = function(el, style) {
		if(el instanceof Array) {
			for(var i = 0, o; o = el[i]; ++i) { $.style(o, style); }
			return;
		}

		el = $.id(el);
		var s = el.style;
		for(prop in style) {
			switch(prop) {
				case 'float':
					s.styleFloat = s.cssFloat = style[prop];
					break;
				case 'opacity':
					s.opacity = style[prop];
					if(el.filters) {
						try {
							var alpha = ieGetAlpha();
							var opacity = style[prop] == 1 ? 99.99 : style[prop] * 100;
							if(!alpha) {
								// TODO: this might destroy any existing filters?
								s.filter = "alpha(opacity=" + opacity + ")";
							} else {
								alpha.Opacity = opacity;
							}
						} catch(e) {}
					}
					break;
				case 'boxSizing':
					s.MsBoxSizing = s.MozBoxSizing = s.WebkitBoxSizing = style[prop];
				default:
					s[prop] = style[prop];
					break;
			}
		}
	};

	$.onEvent = function(el, name, f) {
		if (typeof f != 'function') {
			f = bind.apply(GLOBAL, Array.prototype.slice.call(arguments, 2));
		}

		var handler = f;

		el = $.id(el);
		if(el.addEventListener) {
			el.addEventListener(name, handler, false);
		} else {
			handler = function(e) {
				var evt = e || window.event;
				// TODO: normalize the event object
				f(evt);
			};

			el.attachEvent('on' + name, handler);
		}

		return bind($, 'removeEvent', el, name, handler);
	};

	$.removeEvent = function(el, name, f) {
		el = $.id(el);
		if (el.addEventListener) {
			el.removeEventListener(name, f, false);
		} else {
			el.detachEvent('on' + name, f);
		}
	}

	$.stopEvent = function(e) {
		e.cancelBubble = true;
		if(e.stopPropagation) e.stopPropagation();
		if(e.preventDefault) e.preventDefault();
	}

	$.setText = function(el, text) {
		el = $.id(el);
		text = String(text);
		if ('textContent' in el) {
			el.textContent = text;
		} else if ('innerText' in el) {
			el.innerText = text.replace(/\n/g, ' ');
		} else {
			el.innerHTML = '';
			el.appendChild(document.createTextNode(text));
		}
	}

	$.remove = function(el) {
		el = $.id(el);
		if(el && el.parentNode) {
			el.parentNode.removeChild(el);
		}
	}

	$.cursorPos = function(ev, el) {
		var offset = $.pos(el);
		offset.top = ev.clientY - offset.top + (window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);
		offset.left = ev.clientX - offset.left + (window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft);
		return offset;
	}

	$.pos = function(el) {
		var parent = el;
		var offset = {top: 0, left: 0};
		while(parent && parent != document.body) {
			offset.left += parent.offsetLeft;
			offset.top += parent.offsetTop;
			while(parent.offsetParent != parent.parentNode) {
				offset.top -= parent.scrollTop; offset.left -= parent.scrollLeft;
				parent = parent.parentNode;
			}
			parent = parent.offsetParent;
		}
		return offset;
	}

	$.size = function(el) {
		if (isElement(el)) {
			return {width: el.offsetWidth, height: el.offsetHeight};
		} else if (el.document) {
			return {
				width: el.innerWidth || (el.document.documentElement.clientWidth || el.document.body.clientWidth),
				height: el.innerHeight || (el.document.documentElement.clientHeight || el.document.body.clientHeight)
			};
		}
	}
}
<commit_msg>improve $.insertBefore and $.insertAfter separate create into create and apply so we can use the same JSON object to element logic for new and existing elements<commit_after>if (jsio.__env.name == 'browser') {
	jsio('external .sizzle import Sizzle');
	jsio('import math2D.Rect');

	var DOM2 = typeof HTMLElement === "object";
	function isElement(el) {
		return el &&
			(DOM2 ? el instanceof HTMLElement
				: typeof el.nodeType == 'number' && typeof el.nodeName == 'string');
	}

	function isWindow(el) {
		return el && !isElement(el) && isElement(el.document);
	}

	var singleId = /^#([\w-]+)$/;

	var $ = exports.$ = function(selector, win) {
		switch(typeof selector) {
			case 'object':
				if (isElement(selector)) {
					return $.remove(selector);
				} else if (isElement(selector.document && selector.document.body)) {
					return $.size(selector);
				}
				return $.create(selector);
			case 'string':
				if (singleId.test(selector)) { return $.id(selector.substring(1), win); }
				return Sizzle.apply(GLOBAL, arguments);
		}
	}

	$.id = function(id, win) { return typeof id == 'string' ? (win || window).document.getElementById(id) : id; }

	$.apply = function(el, params) {
		if (params.attrs) {
			for(attr in params.attrs) {
				el.setAttribute(attr, params.attrs[attr]);
			}
		}

		if (params.style) { $.style(el, params.style); }
		if (params.src) { el.src = params.src; }
		if (params['class'] || params['className']) {
			el.className = params['class'] || params['className'];
		}

		var parent = params.parent || params.parentNode;
		if (params.before) {
			$.insertBefore(params.before.parentNode || parent, el, params.before);
		} else if (params.after) {
			$.insertAfter(params.after.parentNode || parent, el, params.after);
		} else if (parent) {
			parent.appendChild(el);
		}

		if (params.html) { el.innerHTML = params.html; }
		if (params.text) { $.setText(el, params.text); }
		return el;
	}

	$.insertBefore = function(parentNode, el, beforeNode) {
		if (!parentNode || !el) { return; }
		if (beforeNode && beforeNode.parentNode == parentNode) {
			parentNode.insertBefore(el, beforeNode);
		} else {
			parentNode.appendChild(el);
		}
	}

	$.insertAfter = function(parentNode, el, afterNode) {
		if (!parentNode || !el) { return; }
		if (!afterNode || afterNode.parentNode != parentNode) {
			$.insertBefore(parentNode, el, parentNode.firstChild);
		} else if (!afterNode.nextSibling) {
			parentNode.appendChild(el);
		} else {
			parentNode.insertBefore(el, afterNode.nextSibling);
		}
	}

	$.create = function(params) {
		var doc = (params.win || window).document;
		if (!params || typeof params == 'string') {
			return doc.createElement(params || 'div');
		};

		return $.apply(doc.createElement(params.tag || params.tagName || 'div'), params);
	}

	$.show = function(el, how) { $.id(el).style.display = how || 'block'; }
	$.hide = function(el) { $.id(el).style.display = 'none'; }

	// accepts an array or a space-delimited string of classNames
	$.addClass = function(el, classNames) {
		if (!el) { return; }
		var el = $.id(el);
		if(typeof classNames == "string") {
			classNames = classNames.split(' ');
		}

		var current = ' ' + el.className + ' ';
		for(var i = 0, len = classNames.length, c; (c = classNames[i]) || i < len; ++i) {
			if(current.indexOf(' '+c+' ') == -1) {
				current += c + ' ';
			}
		}

		el.className = current;
		return $;
	}

	$.getTag = function(from, tag) { return from.getElementsByTagName(tag); }

	$.removeClass = function(el, classNames) {
		if (!el) { return; }
		var el = $.id(el);
		el.className = (' ' + el.className + ' ')
			.replace(' ', '  ')
			.replace(new RegExp('( ' + classNames.replace('\s+', ' | ').replace('-','\-') + ' )', 'g'), '')
			.replace(/\s+/, ' ')
			.replace(/^\s+|\s+%/, '');
	}

	function ieGetAlpha(el) {
		try {
			return el.filters.item("alpha");
		} catch(e) {}

		try {
			return el.filters.item("progid:DXImageTransform.Microsoft.Alpha");
		} catch(e) {}

		return null;
	}

	$.style = function(el, style) {
		if(el instanceof Array) {
			for(var i = 0, o; o = el[i]; ++i) { $.style(o, style); }
			return;
		}

		el = $.id(el);
		var s = el.style;
		for(prop in style) {
			switch(prop) {
				case 'float':
					s.styleFloat = s.cssFloat = style[prop];
					break;
				case 'opacity':
					s.opacity = style[prop];
					if(el.filters) {
						try {
							var alpha = ieGetAlpha();
							var opacity = style[prop] == 1 ? 99.99 : style[prop] * 100;
							if(!alpha) {
								// TODO: this might destroy any existing filters?
								s.filter = "alpha(opacity=" + opacity + ")";
							} else {
								alpha.Opacity = opacity;
							}
						} catch(e) {}
					}
					break;
				case 'boxSizing':
					s.MsBoxSizing = s.MozBoxSizing = s.WebkitBoxSizing = style[prop];
				default:
					s[prop] = style[prop];
					break;
			}
		}
	};

	$.onEvent = function(el, name, f) {
		if (typeof f != 'function') {
			f = bind.apply(GLOBAL, Array.prototype.slice.call(arguments, 2));
		}

		var handler = f;

		el = $.id(el);
		if(el.addEventListener) {
			el.addEventListener(name, handler, false);
		} else {
			handler = function(e) {
				var evt = e || window.event;
				// TODO: normalize the event object
				f(evt);
			};

			el.attachEvent('on' + name, handler);
		}

		return bind($, 'removeEvent', el, name, handler);
	};

	$.removeEvent = function(el, name, f) {
		el = $.id(el);
		if (el.addEventListener) {
			el.removeEventListener(name, f, false);
		} else {
			el.detachEvent('on' + name, f);
		}
	}

	$.stopEvent = function(e) {
		e.cancelBubble = true;
		if(e.stopPropagation) e.stopPropagation();
		if(e.preventDefault) e.preventDefault();
	}

	$.setText = function(el, text) {
		el = $.id(el);
		text = String(text);
		if ('textContent' in el) {
			el.textContent = text;
		} else if ('innerText' in el) {
			el.innerText = text.replace(/\n/g, ' ');
		} else {
			el.innerHTML = '';
			el.appendChild(document.createTextNode(text));
		}
	}

	$.remove = function(el) {
		el = $.id(el);
		if(el && el.parentNode) {
			el.parentNode.removeChild(el);
		}
	}

	$.cursorPos = function(ev, el) {
		var offset = $.pos(el);
		offset.top = ev.clientY - offset.top + (window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);
		offset.left = ev.clientX - offset.left + (window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft);
		return offset;
	}

	$.pos = function(el) {
		var parent = el;
		var offset = {top: 0, left: 0};
		while(parent && parent != document.body) {
			offset.left += parent.offsetLeft;
			offset.top += parent.offsetTop;
			while(parent.offsetParent != parent.parentNode) {
				offset.top -= parent.scrollTop; offset.left -= parent.scrollLeft;
				parent = parent.parentNode;
			}
			parent = parent.offsetParent;
		}
		return offset;
	}

	$.size = function(el) {
		if (isElement(el)) {
			return {width: el.offsetWidth, height: el.offsetHeight};
		} else if (el.document) {
			var doc = el.document.documentElement || el.document.body;
			return new math2D.Rect(
				doc.offsetTop,
				doc.offsetLeft,
				el.innerWidth || (doc.clientWidth || doc.clientWidth),
				el.innerHeight || (doc.clientHeight || doc.clientHeight)
			);
		}
	}
}
<|endoftext|>