<commit_before>'use strict';
/*jshint browser: true*/

/*global require: false*/
var utils = require('./utils');

var months = [
  'January',
  'February',
  'March',
  'April',
  'May',
  'June',
  'July',
  'August',
  'September',
  'October',
  'November',
  'December'
];

var attr = utils.attr;
var query = utils.query;
var mkEl = utils.mkEl;
var keys = utils.keys;
var tmpl = utils.tmpl;

function mkListItems(target, texts, clickCb, that) {
  var items = [];
  that = that || {};

  texts.forEach(function (text, i) {
    var el = mkEl('li');
    el.innerHTML = '' + text + '';

    el.addEventListener('click', function (evt) {
      evt.preventDefault();
      items.forEach(function (e) {
        var cl = e.classList;
        if (e === el) {
          if (!cl.contains('active')) {
            cl.add('active');
          }
        }
        else {
          cl.remove('active');
        }
      });

      clickCb.call(that, i, el);
    });

    target.appendChild(el);

    items.push(el);
  });

  return items;
}

function camDownloadsWidget(info, holder) {
  var majorList = query('ul.major', holder);
  var patchList = query('ul.patch', holder);
  var serverList = query('ul.server', holder);
  var infoDiv = query('.selected-server', holder);
  var standaloneDiv = query('.standalone', infoDiv);

  var releaseTitle = query('.info h3', holder);
  var notesA = query('a.notes', holder);
  var dateSpan = query('span.date', holder);
  var zipA = query('a.zip', holder);
  var targzA = query('a.tar-gz', holder);
  var warA = query('a.war', holder);

  var branches = keys(info.branches).sort(function (a, b) {
    return (a > b ? -1 : (a < b ? 1 : 0));
  });

  function getReleaseInfo(branch, version) {
    return info.branches[branch].find(function (release) {
      return release.number === version;
    });
  }

  function getBranchVersions(branch) {
    return info.branches[branch].map(function (release) {
      return release.number;
    }).filter(function (item) { return !!item; });
  }

  function getServers(release) {
    var servers = keys(info.servers);
    if (release.excludeServers) {
      servers = servers.filter(function (name) {
        return release.excludeServers.indexOf(name) < 0;
      });
    }
    return servers;
  }

  var dlBasePath = 'https://camunda.org/enterprise-release/camunda-bpm/';
  function mkServerClickHandler(servers, version, branch) {
    return function (s) {
      var selectedServer = servers[s];
      var release = getReleaseInfo(branch, version);
      infoDiv.classList.add('accessible');

      var dl = tmpl('{server}/{branch}/{version}/camunda-bpm-ee-{server}-{version}-ee', {
        version:  version,
        branch:   (version.indexOf('alpha') > -1) ? 'nightly' : branch,
        server:   selectedServer
      });

      releaseTitle.innerHTML = version + '-ee for ' + info.servers[selectedServer];

      var parts = release.date.split('.').map(function (part) {
        return parseInt(part, 10);
      });
      dateSpan.innerHTML = parts[2] + ' ' + months[parts[1] - 1] + ' ' + parts[0];

      attr(notesA, 'href', release.note);

      attr(warA, 'href', dlBasePath + tmpl('{server}/{branch}/{version}/camunda-webapp-ee-{server}-standalone-{version}-ee', {
        version:  version,
        branch:   (version.indexOf('alpha') > -1) ? 'nightly' : branch,
        server:   selectedServer
      }) + '.war');

      attr(targzA, 'href', dlBasePath + dl + '.tar.gz');

      attr(zipA, 'href', dlBasePath + dl + '.zip');

      if (selectedServer === 'ibm-was' || selectedServer === 'oracle-wls') {
        dl = tmpl('{vendor}-{server}/{branch}/{version}/camunda-ee-{vendor}-{server}-{version}-ee', {
          version:  version,
          branch:   (version.indexOf('alpha') > -1) ? 'nightly' : branch,
          vendor:   selectedServer.split('-')[0],
          server:   selectedServer.split('-')[1]
        });

        attr(targzA, 'href', dlBasePath + dl + '.tar.gz');

        attr(zipA, 'href', dlBasePath + dl + '.zip');

        attr(warA, 'href', dlBasePath + tmpl('{vendor}-{server}/{branch}/{version}/camunda-webapp-ee-{server}-standalone-{version}-ee', {
          version:  version,
          branch:   (version.indexOf('alpha') > -1) ? 'nightly' : branch,
          vendor:   selectedServer.split('-')[0],
          server:   selectedServer.split('-')[1]
        }) + '.war');
      }

      if (release.excludeFormats && release.excludeFormats.indexOf('war') > -1) {
        standaloneDiv.style.display = 'none';
      }
      else {
        standaloneDiv.style.display = 'block';
      }
    };
  }

  function mkVersionClickHandler(branchName) {
    var patchReleases = getBranchVersions(branchName);

    return function selectVersion(r) {
      serverList.innerHTML = '';

      infoDiv.classList.remove('accessible');

      var selectedVersion = patchReleases[r];

      var releaseInfo = getReleaseInfo(branchName, selectedVersion);

      var releaseServers = getServers(releaseInfo);

      return mkListItems(serverList, releaseServers.map(function (name) {
        return info.servers[name];
      }), mkServerClickHandler(releaseServers, selectedVersion, branchName));
    };
  }

  function selectBranch(b) {
    patchList.innerHTML = '';

    serverList.innerHTML = '';

    infoDiv.classList.remove('accessible');

    var branchName = branches[b];

    var patchReleases = getBranchVersions(branchName);

    return mkListItems(patchList, patchReleases, mkVersionClickHandler(branchName));
  }

  var branchEls = mkListItems(majorList, branches, selectBranch);

  if (info.selected) {
    var b = branches.indexOf(info.selected.branch);

    var versionEls = selectBranch(b);

    branchEls[b].classList.add('active');

    var patchReleases = getBranchVersions(branches[b]);

    var v = patchReleases.indexOf(info.selected.version);

    var serverEls = mkVersionClickHandler(branches[b])(v);

    versionEls[v].classList.add('active');

    var servers = getServers(patchReleases[v]);

    var s = servers.indexOf(info.selected.server);

    serverEls[s].classList.add('active');

    mkServerClickHandler(servers, info.selected.version, info.selected.branch)(s);
  }
}

var camDownloadsEl = query('.cam-downloads');
if (window.camDownloads && camDownloadsEl) {
  camDownloadsWidget(window.camDownloads, camDownloadsEl);
}
<commit_msg>fix(ee-downloads): override wildfly .war links to point to jboss .war files<commit_after>'use strict';
/*jshint browser: true*/

/*global require: false*/
var utils = require('./utils');

var months = [
  'January',
  'February',
  'March',
  'April',
  'May',
  'June',
  'July',
  'August',
  'September',
  'October',
  'November',
  'December'
];

var attr = utils.attr;
var query = utils.query;
var mkEl = utils.mkEl;
var keys = utils.keys;
var tmpl = utils.tmpl;

function mkListItems(target, texts, clickCb, that) {
  var items = [];
  that = that || {};

  texts.forEach(function (text, i) {
    var el = mkEl('li');
    el.innerHTML = '' + text + '';

    el.addEventListener('click', function (evt) {
      evt.preventDefault();
      items.forEach(function (e) {
        var cl = e.classList;
        if (e === el) {
          if (!cl.contains('active')) {
            cl.add('active');
          }
        }
        else {
          cl.remove('active');
        }
      });

      clickCb.call(that, i, el);
    });

    target.appendChild(el);

    items.push(el);
  });

  return items;
}

function camDownloadsWidget(info, holder) {
  var majorList = query('ul.major', holder);
  var patchList = query('ul.patch', holder);
  var serverList = query('ul.server', holder);
  var infoDiv = query('.selected-server', holder);
  var standaloneDiv = query('.standalone', infoDiv);

  var releaseTitle = query('.info h3', holder);
  var notesA = query('a.notes', holder);
  var dateSpan = query('span.date', holder);
  var zipA = query('a.zip', holder);
  var targzA = query('a.tar-gz', holder);
  var warA = query('a.war', holder);

  var branches = keys(info.branches).sort(function (a, b) {
    return (a > b ? -1 : (a < b ? 1 : 0));
  });

  function getReleaseInfo(branch, version) {
    return info.branches[branch].find(function (release) {
      return release.number === version;
    });
  }

  function getBranchVersions(branch) {
    return info.branches[branch].map(function (release) {
      return release.number;
    }).filter(function (item) { return !!item; });
  }

  function getServers(release) {
    var servers = keys(info.servers);
    if (release.excludeServers) {
      servers = servers.filter(function (name) {
        return release.excludeServers.indexOf(name) < 0;
      });
    }
    return servers;
  }

  var dlBasePath = 'https://camunda.org/enterprise-release/camunda-bpm/';
  function mkServerClickHandler(servers, version, branch) {
    return function (s) {
      var selectedServer = servers[s];
      var release = getReleaseInfo(branch, version);
      infoDiv.classList.add('accessible');

      var dl = tmpl('{server}/{branch}/{version}/camunda-bpm-ee-{server}-{version}-ee', {
        version:  version,
        branch:   (version.indexOf('alpha') > -1) ? 'nightly' : branch,
        server:   selectedServer
      });

      releaseTitle.innerHTML = version + '-ee for ' + info.servers[selectedServer];

      var parts = release.date.split('.').map(function (part) {
        return parseInt(part, 10);
      });
      dateSpan.innerHTML = parts[2] + ' ' + months[parts[1] - 1] + ' ' + parts[0];

      attr(notesA, 'href', release.note);

      attr(warA, 'href', dlBasePath + tmpl('{server}/{branch}/{version}/camunda-webapp-ee-{server}-standalone-{version}-ee', {
        version:  version,
        branch:   (version.indexOf('alpha') > -1) ? 'nightly' : branch,
        server:   selectedServer === 'wildfly' ? 'jboss' : selectedServer
      }) + '.war');

      attr(targzA, 'href', dlBasePath + dl + '.tar.gz');

      attr(zipA, 'href', dlBasePath + dl + '.zip');

      if (selectedServer === 'ibm-was' || selectedServer === 'oracle-wls') {
        dl = tmpl('{vendor}-{server}/{branch}/{version}/camunda-ee-{vendor}-{server}-{version}-ee', {
          version:  version,
          branch:   (version.indexOf('alpha') > -1) ? 'nightly' : branch,
          vendor:   selectedServer.split('-')[0],
          server:   selectedServer.split('-')[1]
        });

        attr(targzA, 'href', dlBasePath + dl + '.tar.gz');

        attr(zipA, 'href', dlBasePath + dl + '.zip');

        attr(warA, 'href', dlBasePath + tmpl('{vendor}-{server}/{branch}/{version}/camunda-webapp-ee-{server}-standalone-{version}-ee', {
          version:  version,
          branch:   (version.indexOf('alpha') > -1) ? 'nightly' : branch,
          vendor:   selectedServer.split('-')[0],
          server:   selectedServer.split('-')[1]
        }) + '.war');
      }

      if (release.excludeFormats && release.excludeFormats.indexOf('war') > -1) {
        standaloneDiv.style.display = 'none';
      }
      else {
        standaloneDiv.style.display = 'block';
      }
    };
  }

  function mkVersionClickHandler(branchName) {
    var patchReleases = getBranchVersions(branchName);

    return function selectVersion(r) {
      serverList.innerHTML = '';

      infoDiv.classList.remove('accessible');

      var selectedVersion = patchReleases[r];

      var releaseInfo = getReleaseInfo(branchName, selectedVersion);

      var releaseServers = getServers(releaseInfo);

      return mkListItems(serverList, releaseServers.map(function (name) {
        return info.servers[name];
      }), mkServerClickHandler(releaseServers, selectedVersion, branchName));
    };
  }

  function selectBranch(b) {
    patchList.innerHTML = '';

    serverList.innerHTML = '';

    infoDiv.classList.remove('accessible');

    var branchName = branches[b];

    var patchReleases = getBranchVersions(branchName);

    return mkListItems(patchList, patchReleases, mkVersionClickHandler(branchName));
  }

  var branchEls = mkListItems(majorList, branches, selectBranch);

  if (info.selected) {
    var b = branches.indexOf(info.selected.branch);

    var versionEls = selectBranch(b);

    branchEls[b].classList.add('active');

    var patchReleases = getBranchVersions(branches[b]);

    var v = patchReleases.indexOf(info.selected.version);

    var serverEls = mkVersionClickHandler(branches[b])(v);

    versionEls[v].classList.add('active');

    var servers = getServers(patchReleases[v]);

    var s = servers.indexOf(info.selected.server);

    serverEls[s].classList.add('active');

    mkServerClickHandler(servers, info.selected.version, info.selected.branch)(s);
  }
}

var camDownloadsEl = query('.cam-downloads');
if (window.camDownloads && camDownloadsEl) {
  camDownloadsWidget(window.camDownloads, camDownloadsEl);
}
<|endoftext|>


<commit_before>window.qd.plotComparisonForHourlyEvents = function(divId, myHourlyEvents, theirHourlyEvents) {
	$(divId).html("");
	var baseColor = "#EEEEEE"
	var margin = {
			top: 50,
			right: 0,
			bottom: 100,
			left: 28
		},
		width = $(divId).width() - 10,
		height = width / 2.5,
		p = [height * 0.05, width * 0.1, height * 0.35, width * 0.05],
		gridSize = Math.floor(width / 24),
		legendElementWidth = gridSize * 2,
		buckets = 9,
		colors = ["#DBEDFF", "#A8D4FF", "#8FC7FF", "#75BAFF", "#5CADFF",
			"#42A1FF", "#2994FF", "#007AF5", "#0054A8"
		], // alternatively colorbrewer.YlGnBu[9]
		days = ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
		times = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24"];

	var segmentDataForMyEvents = [];
	var segmentDataForTheirEvents = [];

	for (var hour = 0; hour < 24 * 7; hour++) {
		var myEventCountForAnHour = myHourlyEvents[hour].hourlyEventCount;
		segmentDataForMyEvents[hour] = myEventCountForAnHour;
		var theirEventCountForAnHour = theirHourlyEvents[hour].hourlyEventCount;
		segmentDataForTheirEvents[hour] = theirEventCountForAnHour;
	};

	var daywiseMyHourlyBuildCountsSundayToMonday = _.toArray(_.groupBy(segmentDataForMyEvents, function(element, index) {
		return Math.floor(index / 24);
	}));

	var daywiseTheirHourlyBuildCountsSundayToMonday = _.toArray(_.groupBy(segmentDataForTheirEvents, function(element, index) {
		return Math.floor(index / 24);
	}));

	var myHourlyBuildCountsMondayToSunday = _.flatten(daywiseMyHourlyBuildCountsSundayToMonday);
	var theirHourlyBuildCountsMondayToSunday = _.flatten(daywiseTheirHourlyBuildCountsSundayToMonday);

	var rotateArray = function(a, inc) {
		for (var l = a.length, inc = (Math.abs(inc) >= l && (inc %= l), inc < 0 && (inc += l), inc), i, x; inc; inc = (Math.ceil(l / inc) - 1) * inc - l + (l = inc))
			for (i = l; i > inc; x = a[--i], a[i] = a[i - inc], a[i - inc] = x);
		return a;
	};

	var myHourlyBuildCountsData = rotateArray(myHourlyBuildCountsMondayToSunday.slice(), -1 * window.qd.timezoneDifferenceInHours);
	var theirHourlyBuildCountsData = rotateArray(theirHourlyBuildCountsMondayToSunday.slice(), -1 * window.qd.timezoneDifferenceInHours);

	console.info("myHourlyBuildCountsData: ", myHourlyBuildCountsData);
	console.info("theirHourlyBuildCountsData: ", theirHourlyBuildCountsData);
	var _generateHeatMap = function(data) {
		var maximumEventValue = d3.max([1, d3.max(data, function(d) {
			return d.value;
		})]);
		var colorScale = d3.scale.quantile()
			.domain([1, maximumEventValue])
			.range(colors);
		var createSvg = function(width, height) {
			d3.select(divId).selectAll("svg").remove();
			return d3.select(divId).append("svg")
				.attr("width", width)
				.attr("height", height)
				.append("g")
				.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
		};
		var createDayLabels = function(svg, constantAxis, changingAxis, changingAxisAdjustment, gridSize, transformAttribute) {
			return svg.selectAll(".dayLabel")
				.data(days)
				.enter().append("text")
				.text(function(d) {
					return d;
				})
				.attr(constantAxis, 0)
				.attr(changingAxis, function(d, i) {
					return (i * gridSize) - changingAxisAdjustment;
				})
				.style("text-anchor", "end")
				.attr("transform", transformAttribute)
				.attr("class", function(d, i) {
					return ((i >= 0 && i <= 4) ? "dayLabel mono axis axis-workweek" : "dayLabel mono axis");
				});
		};
		var createTimeLabels = function(svg, constantAxis, changingAxis, constantAxisAdjustment, gridSize, transformAttribute) {
			return svg.selectAll(".timeLabel")
				.data(times)
				.enter().append("text")
				.text(function(d) {
					return d;
				})
				.attr(constantAxis, constantAxisAdjustment)
				.attr(changingAxis, function(d, i) {
					return (i * gridSize);
				})
				.attr("font-size", "10px")
				.style("text-anchor", "middle")
				.attr("transform", transformAttribute)
				.attr("class", function(d, i) {
					return ((i >= 7 && i <= 16) ? "timeLabel mono axis axis-worktime" : "timeLabel mono axis");
				});
		};
		var createHeatMap = function(svg, timeAxis, dayAxis, timeAxisAdjustment, dayAxisAdjustment, gridDaySize, gridTimeSize) {
			return svg.selectAll(".hour")
				.data(data)
				.enter().append("rect")
				.attr(timeAxis, function(d, i) {
					if (i % 2 == 0) {
						return ((d.hour) * gridTimeSize + 9) - timeAxisAdjustment;
					} else {
						return ((d.hour) * gridTimeSize) - timeAxisAdjustment;
					}
				})
				.attr(dayAxis, function(d) {
					return ((d.day) * gridDaySize) - dayAxisAdjustment;
				})
				.attr("rx", 4)
				.attr("ry", 4)
				.attr("class", "hour bordered")
				.attr("width", gridDaySize / 2)
				.attr("height", gridTimeSize)
				.style("fill", baseColor);
		};
		var createLegend = function() {
			return svg.selectAll(".legend")
				.data([1].concat(colorScale.quantiles()), function(d) {
					return d;
				})
				.enter().append("g")
				.attr("class", "legend");
		};

		if ($(window).width() < 480) {
			var svgWidth = 300;
			var svgHeight = 450;
			gridDaySize = Math.floor(190 / 7);
			gridTimeSize = Math.floor(400 / 24);
			var svg = createSvg(svgWidth, svgHeight);
			var dayLabels = createDayLabels(svg, "y", "x", 10, gridDaySize, "translate(" + gridDaySize / 1.5 + ",-6)");
			var timeLabels = createTimeLabels(svg, "x", "y", -15, gridTimeSize, "translate( -6," + (gridTimeSize) / 2.5 + ")");
			var heatMap = createHeatMap(svg, "y", "x", 2.5, 10, gridDaySize, gridTimeSize);
			heatMap.transition().duration(1000)
				.style("fill", function(d) {
					if (d.value === 0) {
						return baseColor;
					} else {
						return colorScale(d.value);
					}
				});
			heatMap.append("title").text(function(d) {
				return d.value;
			});
			var legend = createLegend();
			var legendRectXaxis = (gridDaySize * 7) - 5;
			var legendTextXaxis = legendRectXaxis + (gridSize / 2) + 2;
			legend.append("rect")
				.attr("y", function(d, i) {
					return legendElementWidth * i;
				})
				.attr("x", legendRectXaxis)
				.attr("height", legendElementWidth + 10)
				.attr("width", gridSize / 2)
				.style("fill", function(d, i) {
					return colors[i];
				});

			legend.append("text")
				.attr("class", "mono")
				.text(function(d) {
					return "≥ " + Math.round(d * 10) / 10;
				})
				.attr("font-size", "10px")
				.attr("y", function(d, i) {
					return legendElementWidth * i;
				})
				.attr("x", legendTextXaxis);
		} else {
			var svg = createSvg(width + 50, height + 50);
			var dayLabels = createDayLabels(svg, "x", "y", 0, gridSize, "translate(-6," + gridSize / 1.5 + ")");
			var timeLabels = createTimeLabels(svg, "y", "x", 0, gridSize, "translate(" + gridSize / 2.5 + ", -6)");
			var heatMap = createHeatMap(svg, "x", "y", 0, 0, gridSize, gridSize);

			heatMap.transition().duration(1000)
				.style("fill", function(d) {
					if (d.value === 0) {
						return baseColor;
					} else {
						return colorScale(d.value);
					}
				});

			heatMap.append("title").text(function(d) {
				return d.value;
			});
			var legend = createLegend();

			var legendRectYaxis = (gridSize * 7) + 5;
			var legendTextYaxis = legendRectYaxis + 20;
			legend.append("rect")
				.attr("x", function(d, i) {
					return legendElementWidth * i;
				})
				.attr("y", legendRectYaxis)
				.attr("width", legendElementWidth)
				.attr("height", gridSize / 2)
				.style("fill", function(d, i) {
					return colors[i];
				});

			legend.append("text")
				.attr("class", "mono")
				.text(function(d) {
					return "≥ " + Math.round(d * 10) / 10;
				})
				.attr("font-size", "10px")
				.attr("x", function(d, i) {
					return legendElementWidth * i;
				})
				.attr("y", legendTextYaxis);
		}

	};

	var _generateHourlyBuildEventsData = function(myHourlyBuildCountsData, theirHourlyBuildCountsData) {
		var index = 0;
		var data = [];
		for (var day = 0; day < 7; day++) {
			for (var timeOfDay = 0; timeOfDay < 24; timeOfDay++) {
				console.info("My Data: ", myHourlyBuildCountsData[index]);
				console.info("Their Data: ", theirHourlyBuildCountsData[index])
				var tempData = [];
				tempData.day = day;
				tempData.hour = timeOfDay;
				tempData.value = myHourlyBuildCountsData[index];
				data[index++] = tempData;
				tempData.value = theirHourlyBuildCountsData[index];
				data[index++] = tempData;

				console.info("Data: ",data[index-2]);
				console.info("Data: ",data[index-1]);
			}
		}
		return data;
	};

	var buildEventData = _generateHourlyBuildEventsData(myHourlyBuildCountsData, theirHourlyBuildCountsData);
	_generateHeatMap(buildEventData);

};<commit_msg>-- Adjusted the heatmap to show my data and other's data side by side<commit_after>window.qd.plotComparisonForHourlyEvents = function(divId, myHourlyEvents, theirHourlyEvents) {
	$(divId).html("");
	var baseColor = "#EEEEEE"
	var margin = {
			top: 50,
			right: 0,
			bottom: 100,
			left: 28
		},
		width = $(divId).width() - 10,
		height = width / 2.5,
		p = [height * 0.05, width * 0.1, height * 0.35, width * 0.05],
		gridSize = Math.floor(width / 24),
		legendElementWidth = gridSize * 2,
		buckets = 9,
		myColors = ["#DBEDFF", "#A8D4FF", "#8FC7FF", "#75BAFF", "#5CADFF",
			"#42A1FF", "#2994FF", "#007AF5", "#0054A8"
		],
		/*theirColors = ["#FFCCE5", "#FF99CC", "#FF66B2", "#FF3399", "#FF007F",
			"#CC0066", "#99004C", "#660033", "#330019"
		]*/theirColors = myColors, // alternatively colorbrewer.YlGnBu[9]
		days = ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
		times = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24"];

	var segmentDataForMyEvents = [];
	var segmentDataForTheirEvents = [];

	for (var hour = 0; hour < 24 * 7; hour++) {
		var myEventCountForAnHour = myHourlyEvents[hour].hourlyEventCount;
		segmentDataForMyEvents[hour] = myEventCountForAnHour;
		var theirEventCountForAnHour = theirHourlyEvents[hour].hourlyEventCount;
		segmentDataForTheirEvents[hour] = theirEventCountForAnHour;
	};

	var daywiseMyHourlyBuildCountsSundayToMonday = _.toArray(_.groupBy(segmentDataForMyEvents, function(element, index) {
		return Math.floor(index / 24);
	}));

	var daywiseTheirHourlyBuildCountsSundayToMonday = _.toArray(_.groupBy(segmentDataForTheirEvents, function(element, index) {
		return Math.floor(index / 24);
	}));

	var myHourlyBuildCountsMondayToSunday = _.flatten(daywiseMyHourlyBuildCountsSundayToMonday);
	var theirHourlyBuildCountsMondayToSunday = _.flatten(daywiseTheirHourlyBuildCountsSundayToMonday);

	var rotateArray = function(a, inc) {
		for (var l = a.length, inc = (Math.abs(inc) >= l && (inc %= l), inc < 0 && (inc += l), inc), i, x; inc; inc = (Math.ceil(l / inc) - 1) * inc - l + (l = inc))
			for (i = l; i > inc; x = a[--i], a[i] = a[i - inc], a[i - inc] = x);
		return a;
	};

	var myHourlyBuildCountsData = rotateArray(myHourlyBuildCountsMondayToSunday.slice(), -1 * window.qd.timezoneDifferenceInHours);
	var theirHourlyBuildCountsData = rotateArray(theirHourlyBuildCountsMondayToSunday.slice(), -1 * window.qd.timezoneDifferenceInHours);

	var _generateHeatMap = function(data) {
		var maximumEventValue = d3.max([1, d3.max(data, function(d, i) {
			return d.value;
		})]);
		var myColorScale = d3.scale.quantile()
			.domain([1, maximumEventValue])
			.range(myColors);
		var theirColorScale = d3.scale.quantile()
			.domain([1, maximumEventValue])
			.range(theirColors);
		var createSvg = function(width, height) {
			d3.select(divId).selectAll("svg").remove();
			return d3.select(divId).append("svg")
				.attr("width", width)
				.attr("height", height)
				.append("g")
				.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
		};
		var createDayLabels = function(svg, constantAxis, changingAxis, changingAxisAdjustment, gridSize, transformAttribute) {
			return svg.selectAll(".dayLabel")
				.data(days)
				.enter().append("text")
				.text(function(d) {
					return d;
				})
				.attr(constantAxis, 0)
				.attr(changingAxis, function(d, i) {
					return (i * gridSize) - changingAxisAdjustment;
				})
				.style("text-anchor", "end")
				.attr("transform", transformAttribute)
				.attr("class", function(d, i) {
					return ((i >= 0 && i <= 4) ? "dayLabel mono axis axis-workweek" : "dayLabel mono axis");
				});
		};
		var createTimeLabels = function(svg, constantAxis, changingAxis, constantAxisAdjustment, gridSize, transformAttribute) {
			return svg.selectAll(".timeLabel")
				.data(times)
				.enter().append("text")
				.text(function(d) {
					return d;
				})
				.attr(constantAxis, constantAxisAdjustment)
				.attr(changingAxis, function(d, i) {
					return (i * gridSize);
				})
				.attr("font-size", "10px")
				.style("text-anchor", "middle")
				.attr("transform", transformAttribute)
				.attr("class", function(d, i) {
					return ((i >= 7 && i <= 16) ? "timeLabel mono axis axis-worktime" : "timeLabel mono axis");
				});
		};

		var createLegend = function(id, colorScale) {
			return svg.selectAll(id)
				.data([1].concat(colorScale.quantiles()), function(d) {
					return d;
				})
				.enter().append("g")
				.attr("class", "legend");
		};

		if ($(window).width() < 480) {
			var svgWidth = 300;
			var svgHeight = 450;
			gridDaySize = Math.floor(190 / 7);
			gridTimeSize = Math.floor(400 / 24);
			var svg = createSvg(svgWidth, svgHeight);
			var dayLabels = createDayLabels(svg, "y", "x", 10, gridDaySize, "translate(" + gridDaySize / 1.5 + ",-6)");
			var timeLabels = createTimeLabels(svg, "x", "y", -15, gridTimeSize, "translate( -6," + (gridTimeSize) / 2.5 + ")");
			var heatMap = svg.selectAll(".hour")
				.data(data)
				.enter().append("rect")
				.attr("y", function(d, i) {
					if (i % 2 == 0) {
						return ((d.hour) * gridTimeSize + 7) - 2.5;
					} else {
						return ((d.hour) * gridTimeSize) - 2.5;
					}
				})
				.attr("x", function(d) {
					return ((d.day) * gridDaySize) - 10;
				})
				.attr("rx", 4)
				.attr("ry", 4)
				.attr("width", gridDaySize)
				.attr("height", gridTimeSize / 2)
				.style("fill", baseColor);
			heatMap.transition().duration(1000)
				.style("fill", function(d, i) {
					if (d.value === 0) {
						return baseColor;
					} else {
						if (i % 2 != 0) {
							return myColorScale(d.value);
						} else {
							return theirColorScale(d.value);
						}
					}
				});
			heatMap.append("title").text(function(d) {
				return d.value;
			});
			var myLegend = createLegend(".myLegend",myColorScale);
			var legendRectXaxis = (gridDaySize * 7) - 5;
			var legendTextXaxis = legendRectXaxis + (gridSize / 2) + 2;
			myLegend.append("rect")
				.attr("y", function(d, i) {
					return legendElementWidth * i;
				})
				.attr("x", legendRectXaxis)
				.attr("height", legendElementWidth + 10)
				.attr("width", gridSize / 2)
				.style("fill", function(d, i) {
					return myColors[i];
				});
			var theirLegend = createLegend(".theirLegend",theirColorScale);
			var legendRectXaxis = (gridDaySize * 7) - 5;
			var legendTextXaxis = legendRectXaxis + (gridSize / 2) + 2;
			theirLegend.append("rect")
				.attr("y", function(d, i) {
					return legendElementWidth * i;
				})
				.attr("x", legendRectXaxis)
				.attr("height", legendElementWidth + 10)
				.attr("width", gridSize / 2)
				.style("fill", function(d, i) {
					return myColors[i];
				});

			theirLegend.append("text")
				.attr("class", "mono")
				.text(function(d) {
					return "≥ " + Math.round(d * 10) / 10;
				})
				.attr("font-size", "10px")
				.attr("y", function(d, i) {
					return legendElementWidth * i;
				})
				.attr("x", legendTextXaxis);
		} else {
			var svg = createSvg(width + 50, height + 50);
			var dayLabels = createDayLabels(svg, "x", "y", 0, gridSize, "translate(-6," + gridSize / 1.5 + ")");
			var timeLabels = createTimeLabels(svg, "y", "x", 0, gridSize, "translate(" + gridSize / 2.5 + ", -6)");
			var heatMap = svg.selectAll(".hour")
				.data(data)
				.enter().append("rect")
				.attr("x", function(d, i) {
					if (i % 2 == 0) {
						return ((d.hour) * gridSize + 9);
					} else {
						return ((d.hour) * gridSize);
					}
				})
				.attr("y", function(d) {
					return ((d.day) * gridSize);
				})
				.attr("rx", 4)
				.attr("ry", 4)
				.attr("width", gridSize / 2)
				.attr("height", gridSize)
				.style("fill", baseColor);

			heatMap.transition().duration(1000)
				.style("fill", function(d, i) {
					if (d.value === 0) {
						return baseColor;
					} else {
						if (i % 2 != 0) {
							return myColorScale(d.value);
						} else {
							return theirColorScale(d.value);
						}
					}
				});

			heatMap.append("title").text(function(d) {
				return d.value;
			});
			var myLegend = createLegend(".myLegend",myColorScale);
			var legendRectYaxis = (gridSize * 7) + 5;
			var legendTextYaxis = legendRectYaxis + 20;
			myLegend.append("rect")
				.attr("x", function(d, i) {
					return legendElementWidth * i;
				})
				.attr("y", legendRectYaxis)
				.attr("width", legendElementWidth)
				.attr("height", gridSize / 2)
				.style("fill", function(d, i) {
					return myColors[i];
				});
			var theirLegend = createLegend(".theirLegend",theirColorScale);
			var legendRectYaxis = legendRectYaxis + 9 ;
			var legendTextYaxis = legendRectYaxis + 20;
			theirLegend.append("rect")
				.attr("x", function(d, i) {
					return legendElementWidth * i;
				})
				.attr("y", legendRectYaxis)
				.attr("width", legendElementWidth)
				.attr("height", gridSize / 2)
				.style("fill", function(d, i) {
					return theirColors[i];
				});

			theirLegend.append("text")
				.attr("class", "mono")
				.text(function(d) {
					return "≥ " + Math.round(d * 10) / 10;
				})
				.attr("font-size", "10px")
				.attr("x", function(d, i) {
					return legendElementWidth * i;
				})
				.attr("y", legendTextYaxis);
		}

	};

	var _generateHourlyBuildEventsData = function(myHourlyBuildCountsData, theirHourlyBuildCountsData) {
		var indexOfData = 0;
		var data = [];
		var index = 0;
		for (var day = 0; day < 7; day++) {
			for (var timeOfDay = 0; timeOfDay < 24; timeOfDay++) {
				var tempData = [];
				tempData.day = day;
				tempData.hour = timeOfDay;
				tempData.value = myHourlyBuildCountsData[index];
				data[indexOfData++] = tempData;
				tempData = [];
				tempData.day = day;
				tempData.hour = timeOfDay;
				tempData.value = theirHourlyBuildCountsData[index];
				data[indexOfData++] = tempData;
				index++;
			}
		}
		return data;
	};

	var buildEventData = _generateHourlyBuildEventsData(myHourlyBuildCountsData, theirHourlyBuildCountsData);
	_generateHeatMap(buildEventData);

};<|endoftext|>


<commit_before>var sounds   = require("./sounds");
var formulas = require("./formulas");

/** Checks equality between two arrays. */  // needs to handle nested arrays
var arraysEqual = function(a, b) {
  if (a === b)                  return true;
  if (a === null || b === null) return false;
  if (a.length != b.length)     return false;
  for (var i = 0; i < a.length; ++i)
    if (a[i] !== b[i]) return false;
  return true;
};

/** Generates an array that contains the permutations of the input array */
var permute = function(input) {
    var permArr = [],
    usedChars = [];
    function main(input){
        var i, ch;
        for (i = 0; i < input.length; i++) {
            ch = input.splice(i, 1)[0];
            usedChars.push(ch);
            if (input.length === 0) {
                permArr.push(usedChars.slice());
            }
            main(input);
            input.splice(i, 0, ch);
            usedChars.pop();
        }
        return permArr;
    }
    return main(input);
};

/** Counts the steps between two notes. */
var stepCount = function(note1, note2, pool){
    var thePool = pool || formulas.ET12POOL;
    var result  = thePool.indexOf(note2.getName()) - thePool.indexOf(note1.getName());
    if (result < 0) result += thePool.length;
    return result;
};

/** Builds a Scale object, based on a formula. */
var scalize = function(note, formula, pool){
    var thePool      = pool || formulas.ET12POOL;
    var noteArray    = [];
    var currentIndex = thePool.indexOf(note.getName());
    var poolSize     = thePool.length;
    for (var i in formula){
        noteArray.push(new sounds.Note(thePool[currentIndex]));
        currentIndex = (currentIndex + formula[i]) % poolSize;
    }
    return new sounds.Scale(noteArray);
};

/** Builds an array with all the possible inversions of a Chord object. */
var buildInversions = function(chord){
    var chordCopy   = new sounds.Chord(chord.getNotes().slice(0));
    var chordSize   = chordCopy.getSize();
    var returnArray = [];
    for (var i = 0; i < chordSize; i++){
        returnArray.push(new sounds.Chord(chordCopy.getNotes().slice(0)));
        chordCopy.invert(1);
    }
    return returnArray;
};

/** Builds an array with all the permutations of a Chord object. */
var buildPermutations = function (chord){
    var chordNotes    = chord.getNotes().slice(0);  // Copy array of notes, the notes of the chord.
    var permutedArray = permute(chordNotes);        // Build an array of its permutations.
    var returnArray   = [];                         // Array that will be populated with Chord objects.
    for (var i in permutedArray)                    // Create a Chord object with each permutation.
        returnArray.push(new sounds.Chord(permutedArray[i]));
    return returnArray;                             // Return the array of Chord objects.
};

// !!! handle other data types
/** Returns the formula of the provided sequence of notes */
var toFormula = function(notes, pool){
    var thePool       = pool || formulas.ET12POOL;
    var returnArray   = [];
    var notesLength   = notes.length;
    var thePoolLength = thePool.length;
    if (typeof notes[0] === "string") return _toFormula0(notes, thePool, [], notesLength, thePoolLength);
    else throw new Error("notes format not supported");
};

// Helper for toFormula, handles array of strings
var _toFormula0 = function(notes, thePool, returnArray, notesLength, thePoolLength){
    for (var i = 0; i < notesLength; i++){
        if (thePool.indexOf(notes[i]) === -1){    // Checks that the note is in the pool.
            throw new Error(notes[i] + " is not in the pool.");}
        var value = thePool.indexOf(notes[i]) - thePool.indexOf(notes[(i + 1) % notesLength]);
        if (value > 0) value -= thePoolLength;
        returnArray.push(Math.abs(value));
    }
    return returnArray;
};

// !!! needs to handle var args, and in that case firstNote and pool are the default values.
/** Returns the note representaiton of a formula. */
var fromFormulaToNotes = function(formula, firstNote, pool){
    pool              = pool || formulas.ET12POOL;  // A pool of notes.
    firstNote         = firstNote || pool[0];       // The note group will be buildt with this note as reference.
    var currentIndex  = pool.indexOf(firstNote);    // To keep track of the position in the pool.
    var steps         = formula.length + 1;         // Number of steps needed to complete.
    var poolLength    = pool.length;                // Length of the pool.
    var returnArray  = [];                          // Will be populated with the results.
    for (var i = 0; i < steps; i++){                // Iterate through the pool and formula, collecting the results.
        returnArray.push(pool[currentIndex]);
        currentIndex = (currentIndex + formula[i]) % poolLength;
    }
    return returnArray;                             // Return the results as an array.
};

// Node exports:
exports.arraysEqual        = arraysEqual;
exports.permute            = permute;
exports.stepCount          = stepCount;
exports.scalize            = scalize;
exports.buildInversions    = buildInversions;
exports.buildPermutations  = buildPermutations;
exports.toFormula          = toFormula;
exports.fromFormulaToNotes = fromFormulaToNotes;
<commit_msg>toFormula now handles 4 datatypes<commit_after>// ===========================================
//                 Imports
// ===========================================
var sounds   = require("./sounds");
var formulas = require("./formulas");

/** Checks equality between two arrays. */  // needs to handle nested arrays
var arraysEqual = function(a, b) {
  if (a === b)                  return true;
  if (a === null || b === null) return false;
  if (a.length != b.length)     return false;
  for (var i = 0; i < a.length; ++i)
    if (a[i] !== b[i]) return false;
  return true;
};

/** Generates an array that contains the permutations of the input array. */
var permute = function(input) {
    var permArr = [],
    usedChars = [];
    function main(input){
        var i, ch;
        for (i = 0; i < input.length; i++) {
            ch = input.splice(i, 1)[0];
            usedChars.push(ch);
            if (input.length === 0) {
                permArr.push(usedChars.slice());
            }
            main(input);
            input.splice(i, 0, ch);
            usedChars.pop();
        }
        return permArr;
    }
    return main(input);
};

/** Counts the steps between two notes. */
var stepCount = function(note1, note2, pool){
    var thePool = pool || formulas.ET12POOL;
    var result  = thePool.indexOf(note2.getName()) - thePool.indexOf(note1.getName());
    if (result < 0) result += thePool.length;
    return result;
};

/** Builds a Scale object, based on a formula. */
var scalize = function(note, formula, pool){
    var thePool      = pool || formulas.ET12POOL;
    var noteArray    = [];
    var currentIndex = thePool.indexOf(note.getName());
    var poolSize     = thePool.length;
    for (var i in formula){
        noteArray.push(new sounds.Note(thePool[currentIndex]));
        currentIndex = (currentIndex + formula[i]) % poolSize;
    }
    return new sounds.Scale(noteArray);
};

/** Builds an array with all the possible inversions of a Chord object. */
var buildInversions = function(chord){
    var chordCopy   = new sounds.Chord(chord.getNotes().slice(0));
    var chordSize   = chordCopy.getSize();
    var returnArray = [];
    for (var i = 0; i < chordSize; i++){
        returnArray.push(new sounds.Chord(chordCopy.getNotes().slice(0)));
        chordCopy.invert(1);
    }
    return returnArray;
};

/** Builds an array with all the permutations of a Chord object. */
var buildPermutations = function (chord){
    var chordNotes    = chord.getNotes().slice(0);  // Copy array of notes, the notes of the chord.
    var permutedArray = permute(chordNotes);        // Build an array of its permutations.
    var returnArray   = [];                         // Array that will be populated with Chord objects.
    for (var i in permutedArray)                    // Create a Chord object with each permutation.
        returnArray.push(new sounds.Chord(permutedArray[i]));
    return returnArray;                             // Return the array of Chord objects.
};

// ===========================================
//                 toFormula
// ===========================================
// !!! needs to handle NoteCOllection objects (you need to take a different OOP approach)
/**
* Returns the formula of the provided sequence of notes.
* If variable arguments, the last argument must be the pool.
*/
var toFormula = function(notes, pool){
    if (typeof arguments[0] === "string")                            // Case for var args of type string.
        return _toFormulaVarArgs(arguments, "string");
    if (arguments[0] instanceof sounds.Note)                         // Case for var args of type note.
        return _toFormulaVarArgs(arguments, "Note");
    if (notes instanceof Array){                                     // Cases for array of Note or array of string.
        if (typeof notes[0] === "string")
            return _toFormulaStringArray(notes, pool);
        if (arguments[0] instanceof sounds.Note)
            return _toFormulaNoteArray(notes, pool);
    }
    else throw new Error("datatype is not supported");
};

// Helper for toFormula, handles variable arguments of type string.
var _toFormulaVarArgs = function(){
    var type         = arguments[1];
    var theArguments = Array.prototype.slice.call(arguments[0]);                 // Cast arguments to array.
    var hasPool      = theArguments[theArguments.length - 1] instanceof Array;   // Is the last index a pool?
    var pool         = hasPool ? theArguments.pop() : formulas.ET12POOL;         // Assign a pool.
    if (type === "string")                                                       // Case for string array.
        return _toFormulaStringArray(theArguments, pool);
    if (type === "Note")                                                         // Case for Note array.
        return _toFormulaNoteArray(theArguments, pool);
};

// Helper for _toFormulaVarArgs, deals with variable arguments of type Note.
var _toFormulaNoteArray = function(notes, pool){
    for (var i = 0; i < notes.length; i++)       // From array of Note to array of Note.name.
        notes[i] = notes[i].getName();
    return _toFormulaStringArray(notes, pool);   // Call _toFormulaStringArray with the new array.
};

// Helper for toFormula, _toFormulaNoteArray, and _toFormulaVarArgsString; handles array of strings.
var _toFormulaStringArray = function(notes, pool){
    var thePool     = pool || formulas.ET12POOL;
    var returnArray = [];
    var notesLength = notes.length;
    var poolLength  = thePool.length;
    for (var i = 0; i < notesLength; i++){
        if (thePool.indexOf(notes[i]) === -1)      // Checks that the note is in the pool.
            throw new Error(notes[i] + " is not in the pool.");
        var value = thePool.indexOf(notes[i]) - thePool.indexOf(notes[(i + 1) % notesLength]);
        if (value > 0) value -= poolLength;
        returnArray.push(Math.abs(value));
    }
    return returnArray;
};

// ===========================================
//             fromFormulaToNotes
// ===========================================
// !!! needs to handle var args, and in that case firstNote and pool are the default values.
/** Returns the note representaiton of a formula. */
var fromFormulaToNotes = function(formula, firstNote, pool){
    pool              = pool || formulas.ET12POOL;  // A pool of notes.
    firstNote         = firstNote || pool[0];       // The note group will be buildt with this note as reference.
    var currentIndex  = pool.indexOf(firstNote);    // To keep track of the position in the pool.
    var steps         = formula.length + 1;         // Number of steps needed to complete.
    var poolLength    = pool.length;                // Length of the pool.
    var returnArray  = [];                          // Will be populated with the results.
    for (var i = 0; i < steps; i++){                // Iterate through the pool and formula, collecting the results.
        returnArray.push(pool[currentIndex]);
        currentIndex = (currentIndex + formula[i]) % poolLength;
    }
    return returnArray;                             // Return the results as an array.
};

// Node exports:
exports.arraysEqual        = arraysEqual;
exports.permute            = permute;
exports.stepCount          = stepCount;
exports.scalize            = scalize;
exports.buildInversions    = buildInversions;
exports.buildPermutations  = buildPermutations;
exports.toFormula          = toFormula;
exports.fromFormulaToNotes = fromFormulaToNotes;
<|endoftext|>


<commit_before>function PlatformWindow(title) {
	var self = Ti.UI.createWindow({
		title:title,
		backgroundColor:'white'
	});

	var isMobileWeb = Ti.Platform.osname === 'mobileweb';
	var isTizen = Ti.Platform.osname === 'tizen';

	var data = [];

	if (isTizen) {
		data.push({title: 'Tizen', hasChild: true,  test: 'ui/common/platform/tizen'});
	}
	// create table view data object
	data.push({title:'XHR', hasChild:true, test:'ui/common/platform/xhr'});
	!isTizen && data.push({title:'Network', hasChild:true, test:'ui/common/platform/network'});
	data.push({title:'Common JS', hasChild:true, test:'ui/common/platform/commonjs'});
	data.push({title:'Logging', hasChild:true, test:'ui/common/platform/logging'});
	data.push({title:'Application Data', hasChild:!isMobileWeb, test:'ui/common/platform/app_data', touchEnabled:!isMobileWeb, color:isMobileWeb?"#aaa":"#000"});
	!isTizen && data.push({title:'Application Events', hasChild:!isMobileWeb, test:'ui/common/platform/app_events', touchEnabled:!isMobileWeb, color:isMobileWeb?"#aaa":"#000"});
	data.push({title:'Properties API', hasChild:true, test:'ui/common/platform/properties'});
	if (Titanium.Platform.osname !== 'tizen') {
		data.push({title:'Database', hasChild:!isMobileWeb, test:'ui/common/platform/database', touchEnabled:!isMobileWeb, color:isMobileWeb?"#aaa":"#000"});
	}
	data.push({title:'Platform Data', hasChild:true, test:'ui/common/platform/platform'});
	data.push({title:'Filesystem', hasChild:true, test:'ui/common/platform/filesystem'});
	data.push({title:'JS Includes', hasChild:true, test:'ui/common/platform/js_include'});
	data.push({title:'Set Timeout (timer)', hasChild:true, test:'ui/common/platform/set_timeout'});
	data.push({title:'Set Interval (timer)', hasChild:true, test:'ui/common/platform/set_interval'});
	data.push({title:'XML RSS', hasChild:!isMobileWeb, test:'ui/common/platform/xml_rss', touchEnabled:!isMobileWeb, color:isMobileWeb?"#aaa":"#000"});
	data.push({title:'Utils', hasChild:true, test:'ui/common/platform/utils'});
	data.push({title:'JSON', hasChild:true, test:'ui/common/platform/json'});
	data.push({title:'JS search', hasChild:true, test:'ui/common/platform/search_case_insensitive'});
	data.push({title:'Clipboard', hasChild:true, test:'ui/common/platform/clipboard'});
	if (Titanium.Platform.osname !== 'tizen') {
		data.push({title:'Sockets', hasChild:!isMobileWeb, test:'ui/common/platform/sockets', touchEnabled:!isMobileWeb, color:isMobileWeb?"#aaa":"#000"});
	}

	if (Titanium.Platform.name == 'iPhone OS' || isMobileWeb) {
		data.push({title:'Passing Data (windows)', hasChild:true, test:'ui/common/platform/custom_properties'});
	}

	if (Titanium.Platform.name == 'iPhone OS') {
		data.push({title:'Bonjour', hasChild:true, test:'ui/handheld/ios/platform/bonjour'});
	}

	if (Titanium.Platform.osname === 'android') {
		data.push({title: 'Android services', hasChild:true, test:'ui/handheld/android/platform/android_services'});
	}

	// create table view
	for (var i = 0; i < data.length; i++ ) { data[i].color = '#000'; data[i].font = {fontWeight:'bold'} };
	var tableview = Titanium.UI.createTableView({
		data:data
	});

	// create table view event listener
	tableview.addEventListener('click', function(e) {
		if (e.rowData.test) {
			var ExampleWindow = require(e.rowData.test),
				win = new ExampleWindow({title:e.rowData.title,containingTab:self.containingTab});
			self.containingTab.open(win,{animated:true});
		}
	});

	// add table view to the window
	self.add(tableview);

	return self;
};

module.exports = PlatformWindow;
<commit_msg>Added the tab "Passing Data (window)" for tizen<commit_after>function PlatformWindow(title) {
	var self = Ti.UI.createWindow({
		title:title,
		backgroundColor:'white'
	});

	var isMobileWeb = Ti.Platform.osname === 'mobileweb';
	var isTizen = Ti.Platform.osname === 'tizen';

	var data = [];

	if (isTizen) {
		data.push({title: 'Tizen', hasChild: true,  test: 'ui/common/platform/tizen'});
	}
	// create table view data object
	data.push({title:'XHR', hasChild:true, test:'ui/common/platform/xhr'});
	!isTizen && data.push({title:'Network', hasChild:true, test:'ui/common/platform/network'});
	data.push({title:'Common JS', hasChild:true, test:'ui/common/platform/commonjs'});
	data.push({title:'Logging', hasChild:true, test:'ui/common/platform/logging'});
	data.push({title:'Application Data', hasChild:!isMobileWeb, test:'ui/common/platform/app_data', touchEnabled:!isMobileWeb, color:isMobileWeb?"#aaa":"#000"});
	!isTizen && data.push({title:'Application Events', hasChild:!isMobileWeb, test:'ui/common/platform/app_events', touchEnabled:!isMobileWeb, color:isMobileWeb?"#aaa":"#000"});
	data.push({title:'Properties API', hasChild:true, test:'ui/common/platform/properties'});
	if (Titanium.Platform.osname !== 'tizen') {
		data.push({title:'Database', hasChild:!isMobileWeb, test:'ui/common/platform/database', touchEnabled:!isMobileWeb, color:isMobileWeb?"#aaa":"#000"});
	}
	data.push({title:'Platform Data', hasChild:true, test:'ui/common/platform/platform'});
	data.push({title:'Filesystem', hasChild:true, test:'ui/common/platform/filesystem'});
	data.push({title:'JS Includes', hasChild:true, test:'ui/common/platform/js_include'});
	data.push({title:'Set Timeout (timer)', hasChild:true, test:'ui/common/platform/set_timeout'});
	data.push({title:'Set Interval (timer)', hasChild:true, test:'ui/common/platform/set_interval'});
	data.push({title:'XML RSS', hasChild:!isMobileWeb, test:'ui/common/platform/xml_rss', touchEnabled:!isMobileWeb, color:isMobileWeb?"#aaa":"#000"});
	data.push({title:'Utils', hasChild:true, test:'ui/common/platform/utils'});
	data.push({title:'JSON', hasChild:true, test:'ui/common/platform/json'});
	data.push({title:'JS search', hasChild:true, test:'ui/common/platform/search_case_insensitive'});
	data.push({title:'Clipboard', hasChild:true, test:'ui/common/platform/clipboard'});
	if (Titanium.Platform.osname !== 'tizen') {
		data.push({title:'Sockets', hasChild:!isMobileWeb, test:'ui/common/platform/sockets', touchEnabled:!isMobileWeb, color:isMobileWeb?"#aaa":"#000"});
	}

	if (Titanium.Platform.name == 'iPhone OS' || isMobileWeb || isTizen) {
		data.push({title:'Passing Data (windows)', hasChild:true, test:'ui/common/platform/custom_properties'});
	}

	if (Titanium.Platform.name == 'iPhone OS') {
		data.push({title:'Bonjour', hasChild:true, test:'ui/handheld/ios/platform/bonjour'});
	}

	if (Titanium.Platform.osname === 'android') {
		data.push({title: 'Android services', hasChild:true, test:'ui/handheld/android/platform/android_services'});
	}

	// create table view
	for (var i = 0; i < data.length; i++ ) { data[i].color = '#000'; data[i].font = {fontWeight:'bold'} };
	var tableview = Titanium.UI.createTableView({
		data:data
	});

	// create table view event listener
	tableview.addEventListener('click', function(e) {
		if (e.rowData.test) {
			var ExampleWindow = require(e.rowData.test),
				win = new ExampleWindow({title:e.rowData.title,containingTab:self.containingTab});
			self.containingTab.open(win,{animated:true});
		}
	});

	// add table view to the window
	self.add(tableview);

	return self;
};

module.exports = PlatformWindow;
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2020 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.nanos.column',
  name: 'ColumnConfigToPropertyConverter',
  documentation: `ColumnConfigToPropertyConverter gathers methods for converting (or mapping) property name to property if required
      and returns property and obj, which will return the proprty value on f function call`,
  javaImports: [
    'foam.core.ClassInfo',
    'foam.core.FObject',
    'foam.core.PropertyInfo',
    'foam.core.X',
    'foam.mlang.Expr',
    'foam.nanos.logger.Logger',
    'foam.util.StringUtil',
    'java.lang.reflect.Method'
  ],
  methods: [
    {
      name: 'filterExportedProps',
      documentation: 'returns propNames that are properties of the class and aren\'t networkTransient',
      code: function(of, propNames) {
        var props = of.getAxiomsByClass(foam.core.Property);
        var allColumnNames = props.map(p => p.name);
        if ( ! propNames )
          return props.filter(p => ! p.networkTransient ).map(p => p.name);
        return propNames.filter(n => {
          return allColumnNames.includes(n.split('.')[0]) && ! this.returnProperty(of, n).networkTransient;
        });
      }
    },
    {
      name: 'returnColumnHeader',
      type: 'String',
      args: [
        {
          name: 'of',
          type: 'ClassInfo'
        },
        {
          name: 'propName',
          class: 'String'
        }
      ],
      code: function(of, propName) {
        var cls = of;
        var property;
        var columnHeader = [];

        if ( foam.String.isInstance(propName) ) {
          var propNames = propName.split('.');
          for ( var i = 0 ; i < propNames.length ; i++ ) {
            property = foam.String.isInstance(propNames[i])
            ? cls.getAxiomByName(propNames[i])
            :  foam.Array.isInstance(propNames[i]) ?
            cls.getAxiomByName(propNames[i][0]) : propNames[i];
            if ( ! property )
              return '';
            columnHeader.push(property.tableHeader());
            cls = property.of;
          }
        } else {
          if ( propName.label )
            columnHeader.push(propName.label);
          else {
            if ( ! propName.name )
              columnHeader.push('-');
            else {
              property = cls.getAxiomByName(propName.name);
              if ( property )
                columnHeader.push(propName.tableHeader());
              else
                columnHeader.push('-');
            }
          }
        }
        return columnHeader.join('/');
      }
    },
    {
      name: 'returnProperty',
      documentation: 'returns last property for chain of properties e.g. city property for address.city',
      type: 'PropertyInfo',
      args: [
        {
          name: 'of',
          type: 'ClassInfo'
        },
        {
          name: 'propName',
          class: 'String'
        }
      ],
      code: function(of, propName) {
        var cls = of;
        var property;
        if ( foam.String.isInstance(propName) ) {
          var propNames = propName.split('.');
          for ( var i = 0 ; i < propNames.length ; i++ ) {
            property = foam.String.isInstance(propNames[i])
            ? cls.getAxiomByName(propNames[i])
            :  foam.Array.isInstance(propNames[i]) ?
            cls.getAxiomByName(propNames[i]) : propNames[i];
            if ( ! property )
              break;
            cls = property.of;
          }
        } else
          property = propName;
        return property;
      },
      javaCode: `
        ClassInfo ci = of;
        PropertyInfo p = null;
        String[] propNames = propName.split("\\\\.");
        StringBuilder sb = new StringBuilder("find");

        for ( int i = 0 ; i < propNames.length ; i++ ) {
          if ( ( p == null && i != 0 ) || ci == null )
            break;
          p = (PropertyInfo) ci.getAxiomByName(propNames[i]);
          if ( i != propNames.length - 1 ) {
            try {
              Class cls;
              if ( p instanceof foam.core.AbstractFObjectPropertyInfo ) {
                cls = p.getValueClass();
              } else {
                Method m = ci.getObjClass().getMethod(StringUtil.capitalize(p.getName()), foam.core.X.class);
                cls = m.getReturnType();
                //cleaning up StringBuilder by setting it to "find" for another property to use
                sb.setLength(4);
              }
              ci = (ClassInfo) cls.getMethod("getOwnClassInfo").invoke(null);
            } catch (Exception e) {
              Logger logger = (Logger) getX().get("logger");
              logger.error(e);
              return null;
            }
          }
        }
        return p;
      `
    },
    {
      name: 'returnPropertyAndObject',
      type: 'foam.nanos.column.ColumnPropertyValue',
      documentation: 'returns property and object on which such property\'s functions as f or toCSV can be called',
      args: [
        {
          name: 'x',
          type: 'Context'
        },
        {
          name: 'of',
          type: 'ClassInfo'
        },
        {
          name: 'propName',
          class: 'String',
        },
        {
          name: 'obj',
          type: 'FObject'
        }
      ],
      code: async function(of, propName, obj) {
        var cls = of;
        var property;
        var obj1 = obj;
        if ( foam.String.isInstance(propName) ) {
          var propNames = propName.split('.');
          for ( var i = 0 ; i < propNames.length ; i++ ) {
            property = foam.String.isInstance(propNames[i])
            ? cls.getAxiomByName(propNames[i])
            :  foam.Array.isInstance(propNames[i]) ?
            cls.getAxiomByName(propNames[i]) : propNames[i];
            if ( ! property )
              break;
            cls = property.of;

            if ( i !== propNames.length - 1 && obj1 ) {
              if ( foam.core.Reference.isInstance(property) ) {
                obj1 = await obj1[property.name + '$find'];
              } else {
                obj1 = property.f(obj1);
              }
            }
          }
        } else
          property = propName;
        return foam.nanos.column.ColumnPropertyValue.create({propertyValue:property, objValue:obj1});
      },
      javaCode: `
        ClassInfo ci = of;
        FObject obj1 = obj;
        PropertyInfo p = null;
        String[] propNames = propName.split("\\\\.");
        StringBuilder sb = new StringBuilder("find");
        for ( int i = 0 ; i < propNames.length ; i++ ) {
          if ( ( p == null && i != 0 ) || ci == null )
            break;
          p = (PropertyInfo) ci.getAxiomByName(propNames[i]);

          if ( i != propNames.length - 1 ) {
            try {
              Class cls;
              if ( p instanceof foam.core.AbstractFObjectPropertyInfo ) {
                obj1 = (FObject) p.f(obj1);
                cls = p.getValueClass();
              } else {
                obj1 = (FObject)obj1.getClass().getMethod(StringUtil.capitalize(p.getName()), foam.core.X.class).invoke(obj1, x);
                sb.setLength(4);
                if ( obj1 == null ) return new ColumnPropertyValue.Builder(x).setPropertyValue(null).setObjValue(null).build();
                cls = obj1.getClass();
              }
              ci = (ClassInfo) cls.getMethod("getOwnClassInfo").invoke(null);
            } catch (Exception e) {
              Logger logger = (Logger) getX().get("logger");
              logger.error(e);
              return new ColumnPropertyValue.Builder(x).setPropertyValue(null).setObjValue(null).build();
            }
          }
        }
        return new ColumnPropertyValue.Builder(x).setPropertyValue(p).setObjValue(obj1).build();
      `
    },
    async function returnValueForPropertyName(x, of, propName, obj) {
      //returns property and value of the obj that corresponds to the property
      var columnPropertyVal = await this.returnPropertyAndObject(x, of, propName, obj);
      if ( foam.core.Reference.isInstance(columnPropertyVal.propertyValue) )
        return foam.nanos.column.ColumnPropertyValue.create({ propertyValue:columnPropertyVal.propertyValue, objValue: await columnPropertyVal.objValue[columnPropertyVal.propertyValue.name + '$find']});
      return foam.nanos.column.ColumnPropertyValue.create({ propertyValue:columnPropertyVal.propertyValue, objValue: columnPropertyVal.propertyValue.f(columnPropertyVal.objValue)});
    },
    function returnProperties(of, propNames) {
      var arr = [];

      for ( var prop of propNames ) {
        arr.push(this.returnProperty(of, prop));
      }
      return arr;
    },
    function returnPropertyLabel(propName) {
      if ( propName.label )
            columnHeader.push(propName.label);
          else {
            if ( ! propName.name )
              columnHeader.push('-');
            else {
              property = cls.getAxiomByName(propName.name);
              if ( property )
                columnHeader.push(propName.tableHeader());
              else
                columnHeader.push('-');
            }
          }
    }
  ]
});

foam.CLASS({
  package: 'foam.nanos.column',
  name: 'ColumnPropertyValue',
  properties: [
    {
      name: 'propertyValue',
      class: 'FObjectProperty',
      javaType: 'foam.core.PropertyInfo'
    },
    {
      name: 'objValue',
      class: 'FObjectProperty',
      of: 'FObject'
    }
  ]
});<commit_msg>clean up<commit_after>/**
 * @license
 * Copyright 2020 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.nanos.column',
  name: 'ColumnConfigToPropertyConverter',
  documentation: `ColumnConfigToPropertyConverter gathers methods for converting (or mapping) property name to property if required
      and returns property and obj, which will return the proprty value on f function call`,
  javaImports: [
    'foam.core.ClassInfo',
    'foam.core.FObject',
    'foam.core.PropertyInfo',
    'foam.core.X',
    'foam.mlang.Expr',
    'foam.nanos.logger.Logger',
    'foam.util.StringUtil',
    'java.lang.reflect.Method'
  ],
  methods: [
    {
      name: 'filterExportedProps',
      documentation: 'returns propNames that are properties of the class and aren\'t networkTransient',
      code: function(of, propNames) {
        var props = of.getAxiomsByClass(foam.core.Property);
        var allColumnNames = props.map(p => p.name);
        if ( ! propNames )
          return props.filter(p => ! p.networkTransient ).map(p => p.name);
        return propNames.filter(n => {
          return allColumnNames.includes(n.split('.')[0]) && ! this.returnProperty(of, n).networkTransient;
        });
      }
    },
    {
      name: 'returnColumnHeader',
      type: 'String',
      args: [
        {
          name: 'of',
          type: 'ClassInfo'
        },
        {
          name: 'propName',
          class: 'String'
        }
      ],
      code: function(of, propName) {
        var cls = of;
        var property;
        var columnHeader = [];

        if ( foam.String.isInstance(propName) ) {
          var propNames = propName.split('.');
          for ( var i = 0 ; i < propNames.length ; i++ ) {
            property = foam.String.isInstance(propNames[i])
            ? cls.getAxiomByName(propNames[i])
            :  foam.Array.isInstance(propNames[i]) ?
            cls.getAxiomByName(propNames[i][0]) : propNames[i];
            if ( ! property )
              return '';
            columnHeader.push(property.tableHeader());
            cls = property.of;
          }
        } else {
          if ( propName.label )
            columnHeader.push(propName.label);
          else {
            if ( ! propName.name )
              columnHeader.push('-');
            else {
              property = cls.getAxiomByName(propName.name);
              if ( property )
                columnHeader.push(propName.tableHeader());
              else
                columnHeader.push('-');
            }
          }
        }
        return columnHeader.join('/');
      }
    },
    {
      name: 'returnProperty',
      documentation: 'returns last property for chain of properties e.g. city property for address.city',
      type: 'PropertyInfo',
      args: [
        {
          name: 'of',
          type: 'ClassInfo'
        },
        {
          name: 'propName',
          class: 'String'
        }
      ],
      code: function(of, propName) {
        var cls = of;
        var property;
        if ( foam.String.isInstance(propName) ) {
          var propNames = propName.split('.');
          for ( var i = 0 ; i < propNames.length ; i++ ) {
            property = foam.String.isInstance(propNames[i])
            ? cls.getAxiomByName(propNames[i])
            :  foam.Array.isInstance(propNames[i]) ?
            cls.getAxiomByName(propNames[i]) : propNames[i];
            if ( ! property )
              break;
            cls = property.of;
          }
        } else
          property = propName;
        return property;
      },
      javaCode: `
        ClassInfo ci = of;
        PropertyInfo p = null;
        String[] propNames = propName.split("\\\\.");
        StringBuilder sb = new StringBuilder("find");

        for ( int i = 0 ; i < propNames.length ; i++ ) {
          if ( ( p == null && i != 0 ) || ci == null )
            break;
          p = (PropertyInfo) ci.getAxiomByName(propNames[i]);
          if ( i != propNames.length - 1 ) {
            try {
              Class cls;
              if ( p instanceof foam.core.AbstractFObjectPropertyInfo ) {
                cls = p.getValueClass();
              } else {
                Method m = ci.getObjClass().getMethod(StringUtil.capitalize(p.getName()), foam.core.X.class);
                cls = m.getReturnType();
                //cleaning up StringBuilder by setting it to "find" for another property to use
                sb.setLength(4);
              }
              ci = (ClassInfo) cls.getMethod("getOwnClassInfo").invoke(null);
            } catch (Exception e) {
              Logger logger = (Logger) getX().get("logger");
              logger.error(e);
              return null;
            }
          }
        }
        return p;
      `
    },
    {
      name: 'returnPropertyAndObject',
      type: 'foam.nanos.column.ColumnPropertyValue',
      documentation: 'returns property and object on which such property\'s functions as f or toCSV can be called',
      args: [
        {
          name: 'x',
          type: 'Context'
        },
        {
          name: 'of',
          type: 'ClassInfo'
        },
        {
          name: 'propName',
          class: 'String',
        },
        {
          name: 'obj',
          type: 'FObject'
        }
      ],
      code: async function(of, propName, obj) {
        var cls = of;
        var property;
        var obj1 = obj;
        if ( foam.String.isInstance(propName) ) {
          var propNames = propName.split('.');
          for ( var i = 0 ; i < propNames.length ; i++ ) {
            property = foam.String.isInstance(propNames[i])
            ? cls.getAxiomByName(propNames[i])
            :  foam.Array.isInstance(propNames[i]) ?
            cls.getAxiomByName(propNames[i]) : propNames[i];
            if ( ! property )
              break;
            cls = property.of;

            if ( i !== propNames.length - 1 && obj1 ) {
              if ( foam.core.Reference.isInstance(property) ) {
                obj1 = await obj1[property.name + '$find'];
              } else {
                obj1 = property.f(obj1);
              }
            }
          }
        } else
          property = propName;
        return foam.nanos.column.ColumnPropertyValue.create({propertyValue:property, objValue:obj1});
      },
      javaCode: `
        ClassInfo ci = of;
        FObject obj1 = obj;
        PropertyInfo p = null;
        String[] propNames = propName.split("\\\\.");
        StringBuilder sb = new StringBuilder("find");
        for ( int i = 0 ; i < propNames.length ; i++ ) {
          if ( ( p == null && i != 0 ) || ci == null )
            break;
          p = (PropertyInfo) ci.getAxiomByName(propNames[i]);

          if ( i != propNames.length - 1 ) {
            try {
              Class cls;
              if ( p instanceof foam.core.AbstractFObjectPropertyInfo ) {
                obj1 = (FObject) p.f(obj1);
                cls = p.getValueClass();
              } else {
                obj1 = (FObject)obj1.getClass().getMethod(StringUtil.capitalize(p.getName()), foam.core.X.class).invoke(obj1, x);
                sb.setLength(4);
                if ( obj1 == null ) return new ColumnPropertyValue.Builder(x).setPropertyValue(null).setObjValue(null).build();
                cls = obj1.getClass();
              }
              ci = (ClassInfo) cls.getMethod("getOwnClassInfo").invoke(null);
            } catch (Exception e) {
              Logger logger = (Logger) getX().get("logger");
              logger.error(e);
              return new ColumnPropertyValue.Builder(x).setPropertyValue(null).setObjValue(null).build();
            }
          }
        }
        return new ColumnPropertyValue.Builder(x).setPropertyValue(p).setObjValue(obj1).build();
      `
    },
    async function returnValueForPropertyName(x, of, propName, obj) {
      //returns property and value of the obj that corresponds to the property
      var columnPropertyVal = await this.returnPropertyAndObject(x, of, propName, obj);
      if ( foam.core.Reference.isInstance(columnPropertyVal.propertyValue) )
        return foam.nanos.column.ColumnPropertyValue.create({ propertyValue:columnPropertyVal.propertyValue, objValue: await columnPropertyVal.objValue[columnPropertyVal.propertyValue.name + '$find']});
      return foam.nanos.column.ColumnPropertyValue.create({ propertyValue:columnPropertyVal.propertyValue, objValue: columnPropertyVal.propertyValue.f(columnPropertyVal.objValue)});
    },
    function returnProperties(of, propNames) {
      var arr = [];

      for ( var prop of propNames ) {
        arr.push(this.returnProperty(of, prop));
      }
      return arr;
    }
  ]
});

foam.CLASS({
  package: 'foam.nanos.column',
  name: 'ColumnPropertyValue',
  properties: [
    {
      name: 'propertyValue',
      class: 'FObjectProperty',
      javaType: 'foam.core.PropertyInfo'
    },
    {
      name: 'objValue',
      class: 'FObjectProperty',
      of: 'FObject'
    }
  ]
});<|endoftext|>


<commit_before><commit_msg>add process.js<commit_after><|endoftext|>


<commit_before>/*
  Accessible through browser at location path static/foam2/src/foam/nanos/controller/index.html
  Available on browser console as ctrl. (exports axiom)
*/

foam.CLASS({
  package: 'foam.nanos.controller',
  name: 'ApplicationController',
  extends: 'foam.u2.Element',

  arequire: function() { return foam.nanos.client.ClientBuilder.create(); },

  documentation: 'FOAM Application Controller.',

  implements: [
    'foam.nanos.client.Client',
  ],

  requires: [
    'foam.u2.stack.Stack',
    'foam.u2.stack.StackView',
    'foam.nanos.auth.User'
  ],

  exports: [
    'stack',
    'user',
    'logo',
    'signUpEnabled',
    'webApp',
    'requestLogin',
    'loginSuccess',
    'as ctrl',
    'wrapCSS as installCSS'
  ],

  imports: [
    'sessionSuccess',
    'installCSS'
  ],

  css: `
    body {
      font-family: 'Roboto', sans-serif;
      font-size: 14px;
      letter-spacing: 0.2px;
      color: #373a3c;
      background: #edf0f5;
      margin: 0;
    }

    .stack-wrapper {
      margin-bottom: -10px;
      min-height: calc(80% - 60px);
    }

    .stack-wrapper:after {
      content: "";
      display: block;
    }
  `,

  properties: [
    {
      name: 'stack',
      factory: function() { return this.Stack.create(); }
    },
    {
      class: 'foam.core.FObjectProperty',
      of: 'foam.nanos.auth.User',
      name: 'user',
      factory: function() { return this.User.create(); }
    },
    {
      class: 'Boolean',
      name: 'signUpEnabled',
      adapt: function(v) {
        return v === 'false' ? false : true;
      }
    },
    {
      class: 'Boolean',
      name: 'loginSuccess',
      value: false
    },
    'logo',
    'webApp',
    'primaryColor',
    'secondaryColor',
    'tableColor',
    'accentColor'
  ],

  methods: [
    function init() {
      this.SUPER();
      var self = this;

      // get current user, else show login
      this.auth.getCurrentUser(null).then(function (result) {
        self.loginSuccess = result ? true : false;
        self.user.copyFrom(result);
        return self.accountDAO.where(self.EQ(self.Account.OWNER, self.user.id)).limit(1).select();
      })
      .then(function (result) {
        self.account.copyFrom(result.array[0]);
      })
      .catch(function (err) {
        self.requestLogin();
      });

      window.onpopstate = function(event) {
        if ( location.hash != null ) {
          var hid = location.hash.substr(1);

          hid && self.menuDAO.find(hid).then(function(menu) {
            menu && menu.launch(this,null);
         })
        }
      };
      window.onpopstate();
    },

    function initE() {
      this
        .addClass(this.myClass())
        .tag({class: 'foam.u2.navigation.TopNavigation'})
        .start('div').addClass('stack-wrapper')
          .tag({class: 'foam.u2.stack.StackView', data: this.stack, showActions: false})
        .end()
    },

    //CSS preprocessor, works on classes instantiated in subContext
    function wrapCSS(text, id) {
      if ( text ) {
        if ( ! this.accentColor ) {
          var self = this;
          this.accentColor$.sub(function(s) {
            self.wrapCSS(text, id);
            s.detach();
          });
        }
        this.installCSS(text.
          replace(/%PRIMARYCOLOR%/g, this.primaryColor).
          replace(/%SECONDARYCOLOR%/g, this.secondaryColor).
          replace(/%TABLECOLOR%/g, this.tableColor).
          replace(/%ACCENTCOLOR%/g, this.accentColor),
          id);
      }
    },

    function requestLogin(){
      var self = this;
      // don't go to log in screen if going to reset password screen
      if ( location.hash != null && location.hash === '#reset' ) {
        return;
      }

      return new Promise(function(resolve, reject) {
        self.stack.push({ class: 'foam.nanos.auth.SignInView' });
        self.loginSuccess$.sub(resolve);
      });
    }
  ]
});
<commit_msg>Formatting.<commit_after>/*
  Accessible through browser at location path static/foam2/src/foam/nanos/controller/index.html
  Available on browser console as ctrl. (exports axiom)
*/

foam.CLASS({
  package: 'foam.nanos.controller',
  name: 'ApplicationController',
  extends: 'foam.u2.Element',

  arequire: function() { return foam.nanos.client.ClientBuilder.create(); },

  documentation: 'FOAM Application Controller.',

  implements: [
    'foam.nanos.client.Client',
  ],

  requires: [
    'foam.nanos.auth.User',
    'foam.u2.stack.Stack',
    'foam.u2.stack.StackView'
  ],

  exports: [
    'as ctrl',
    'loginSuccess',
    'logo',
    'requestLogin',
    'signUpEnabled',
    'stack',
    'user',
    'webApp',
    'wrapCSS as installCSS'
  ],

  imports: [
    'sessionSuccess',
    'installCSS'
  ],

  css: `
    body {
      font-family: 'Roboto', sans-serif;
      font-size: 14px;
      letter-spacing: 0.2px;
      color: #373a3c;
      background: #edf0f5;
      margin: 0;
    }

    .stack-wrapper {
      margin-bottom: -10px;
      min-height: calc(80% - 60px);
    }

    .stack-wrapper:after {
      content: "";
      display: block;
    }
  `,

  properties: [
    {
      name: 'stack',
      factory: function() { return this.Stack.create(); }
    },
    {
      class: 'foam.core.FObjectProperty',
      of: 'foam.nanos.auth.User',
      name: 'user',
      factory: function() { return this.User.create(); }
    },
    {
      class: 'Boolean',
      name: 'signUpEnabled',
      adapt: function(v) {
        return v === 'false' ? false : true;
      }
    },
    {
      class: 'Boolean',
      name: 'loginSuccess',
      value: false
    },
    'logo',
    'webApp',
    'primaryColor',
    'secondaryColor',
    'tableColor',
    'accentColor'
  ],

  methods: [
    function init() {
      this.SUPER();
      var self = this;

      // get current user, else show login
      this.auth.getCurrentUser(null).then(function (result) {
        self.loginSuccess = result ? true : false;
        self.user.copyFrom(result);
        return self.accountDAO.where(self.EQ(self.Account.OWNER, self.user.id)).limit(1).select();
      })
      .then(function (result) {
        self.account.copyFrom(result.array[0]);
      })
      .catch(function (err) {
        self.requestLogin();
      });

      window.onpopstate = function(event) {
        if ( location.hash != null ) {
          var hid = location.hash.substr(1);

          hid && self.menuDAO.find(hid).then(function(menu) {
            menu && menu.launch(this,null);
         })
        }
      };
      window.onpopstate();
    },

    function initE() {
      this
        .addClass(this.myClass())
        .tag({class: 'foam.u2.navigation.TopNavigation'})
        .start('div').addClass('stack-wrapper')
          .tag({class: 'foam.u2.stack.StackView', data: this.stack, showActions: false})
        .end()
    },

    //CSS preprocessor, works on classes instantiated in subContext
    function wrapCSS(text, id) {
      if ( text ) {
        if ( ! this.accentColor ) {
          var self = this;
          this.accentColor$.sub(function(s) {
            self.wrapCSS(text, id);
            s.detach();
          });
        }
        this.installCSS(text.
          replace(/%PRIMARYCOLOR%/g, this.primaryColor).
          replace(/%SECONDARYCOLOR%/g, this.secondaryColor).
          replace(/%TABLECOLOR%/g, this.tableColor).
          replace(/%ACCENTCOLOR%/g, this.accentColor),
          id);
      }
    },

    function requestLogin(){
      var self = this;
      // don't go to log in screen if going to reset password screen
      if ( location.hash != null && location.hash === '#reset' ) {
        return;
      }

      return new Promise(function(resolve, reject) {
        self.stack.push({ class: 'foam.nanos.auth.SignInView' });
        self.loginSuccess$.sub(resolve);
      });
    }
  ]
});
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2020 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.nanos.crunch.extra',
  name: 'ImplyReviewedAction',
  implements: ['foam.nanos.ruler.RuleAction'],

  javaImports: [
    'foam.core.ContextAgent',
    'foam.core.X',
    'foam.dao.ArraySink',
    'foam.dao.DAO',
    'foam.nanos.crunch.Capability',
    'foam.nanos.crunch.CrunchService',
    'foam.nanos.crunch.UserCapabilityJunction',
    'java.util.List',
    'static foam.mlang.MLang.*'
  ],

  methods: [
    {
      name: 'applyAction',
      javaCode: `
      agency.submit(x, new ContextAgent() {
        @Override
        public void execute(X x) {
          // In case this rule action is misconfigured
          if ( ! (obj instanceof UserCapabilityJunction) ) {
            throw new RuntimeException(
              "ImplyReviewedAction can only be triggered on UCJ objects");
          }

          // Context requirements
          var capabilityDAO = (DAO) x.get("capabilityDAO");

          var cap = (Capability) capabilityDAO.find(
            ((UserCapabilityJunction) obj).getTargetId());

          // Find the review wizard corresponding to this capability.
          //   A list is used in case there is more than one.
          List reviewWizards = ((ArraySink) capabilityDAO.where(AND(
            INSTANCE_OF(ReviewWizard.class),
            EQ(ReviewWizard.CAPABILITY_TO_REVIEW, cap.getId())
          )).select(new ArraySink())).getArray();
          for ( Object o : reviewWizards ) {
            var reviewWizard = (ReviewWizard) o;
            grantReview(x, reviewWizard);
          }
        }
      }, "Imply review capabilities");
      `
    },
    {
      name: 'grantReview',
      args: [
        { name: 'x', type: 'Context' },
        { name: 'reviewWizard', type: 'ReviewWizard' },
      ],
      javaCode: `
        var capabilityDAO = (DAO) x.get("capabilityDAO");
        var crunchService = (CrunchService) x.get("crunchService");

        var caps = (ReviewCapability[]) ((ArraySink) capabilityDAO.where(AND(
          IN(Capability.ID, crunchService.getPrereqs(reviewWizard.getId())),
          INSTANCE_OF(ReviewCapability.class)
        )).select(new ArraySink())).getArray().toArray(new ReviewCapability[0]);

        // Default data for a reviewed ReviewCapability
        var data = new ReviewCapabilityData.Builder(x)
          .setReviewed(true)
          .build();

        // Apply data to each ReviewCapability
        for ( ReviewCapability cap : caps ) {
          crunchService.updateJunction(x, cap.getId(), data, null);
        }

        // Grant final review capability
        crunchService.updateJunction(x, reviewWizard.getId(), null, null);
      `
    }
  ]
});<commit_msg>Fix context subject for review capability granting<commit_after>/**
 * @license
 * Copyright 2020 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.nanos.crunch.extra',
  name: 'ImplyReviewedAction',
  implements: ['foam.nanos.ruler.RuleAction'],

  javaImports: [
    'foam.core.ContextAgent',
    'foam.core.X',
    'foam.dao.ArraySink',
    'foam.dao.DAO',
    'foam.nanos.crunch.Capability',
    'foam.nanos.crunch.CrunchService',
    'foam.nanos.crunch.UserCapabilityJunction',
    'java.util.List',
    'static foam.mlang.MLang.*'
  ],

  methods: [
    {
      name: 'applyAction',
      javaCode: `
      agency.submit(x, new ContextAgent() {
        @Override
        public void execute(X x) {
          // In case this rule action is misconfigured
          if ( ! (obj instanceof UserCapabilityJunction) ) {
            throw new RuntimeException(
              "ImplyReviewedAction can only be triggered on UCJ objects");
          }

          // Context requirements
          var capabilityDAO = (DAO) x.get("capabilityDAO");

          var ucj = (UserCapabilityJunction) obj;
          var cap = (Capability) capabilityDAO.find(ucj.getTargetId());

          // Create UCJ subject context
          x = x.put("subject", ucj.getSubject(x));

          // Find the review wizard corresponding to this capability.
          //   A list is used in case there is more than one.
          List reviewWizards = ((ArraySink) capabilityDAO.where(AND(
            INSTANCE_OF(ReviewWizard.class),
            EQ(ReviewWizard.CAPABILITY_TO_REVIEW, cap.getId())
          )).select(new ArraySink())).getArray();
          for ( Object o : reviewWizards ) {
            var reviewWizard = (ReviewWizard) o;
            grantReview(x, reviewWizard);
          }
        }
      }, "Imply review capabilities");
      `
    },
    {
      name: 'grantReview',
      args: [
        { name: 'x', type: 'Context' },
        { name: 'reviewWizard', type: 'ReviewWizard' },
      ],
      javaCode: `
        var capabilityDAO = (DAO) x.get("capabilityDAO");
        var crunchService = (CrunchService) x.get("crunchService");

        var caps = (ReviewCapability[]) ((ArraySink) capabilityDAO.where(AND(
          IN(Capability.ID, crunchService.getPrereqs(reviewWizard.getId())),
          INSTANCE_OF(ReviewCapability.class)
        )).select(new ArraySink())).getArray().toArray(new ReviewCapability[0]);

        // Default data for a reviewed ReviewCapability
        var data = new ReviewCapabilityData.Builder(x)
          .setReviewed(true)
          .build();

        // Apply data to each ReviewCapability
        for ( ReviewCapability cap : caps ) {
          crunchService.updateJunction(x, cap.getId(), data, null);
        }

        // Grant final review capability
        crunchService.updateJunction(x, reviewWizard.getId(), null, null);
      `
    }
  ]
});<|endoftext|>


<commit_before>(function(){
  var onMessageCreated = function(user, store) {
    return function(data) {
      store.find('message', data.message.id).then(function(message) {
        var title = data.message.senderName;
        new Notification(title, {
          body: data.message.bodyPlain,
          icon: data.message.senderIconUrl
        });
      });
    }
  };

  window.addEventListener('ready.idobata', function(e) {
    var container = e.detail.container;
    var pusher = container.lookup('pusher:main');
    var user   = container.lookup('service:session').get('user.id');
    var store  = container.lookup('store:main');

    pusher.bind('message:created', onMessageCreated(user, store));
  });
})();
<commit_msg>Fix notification<commit_after>(function(){
  var onMessageCreated = function(user, store) {
    return function(data) {
      store.find('message', data.message.id).then(function(message) {
        var title = message.get('senderName');

        new Notification(title, {
          body: message.get('bodyPlain'),
          icon: message.get('senderIconUrl')
        });
      });
    }
  };

  window.addEventListener('ready.idobata', function(e) {
    var container = e.detail.container;
    var pusher = container.lookup('pusher:main');
    var user   = container.lookup('service:session').get('user.id');
    var store  = container.lookup('service:store');

    pusher.bind('message:created', onMessageCreated(user, store));
  });
})();
<|endoftext|>


<commit_before>// requirements

var program = require('commander');
var path = require('path');
var pkg = require(path.join(__dirname, 'package.json'));

var keypress = require('keypress');

var ansi = require('ansi'),
        cursor = ansi(process.stdout);

var figlet = require('figlet');

var fs = require('fs');

var ImageToAscii = require("image-to-ascii");

// ----

var slides = [];
var currentSlide = 0;

// ---- GLOBALS

var author = '';
var font = 'Standard';
var created = '';

// ----

function showSlide() {
    clearScreen();
    if (slides[currentSlide].indexOf('IMAGE') == 0) {
        var image = slides[currentSlide].substring('IMAGE'.length).trim();
        console.log(image);
        ImageToAscii(image, function(err, result){
            if (err) {
                console.log(err);
            }
            cursor.goto(0, 0).write(result);
        });
    }
    else {
        var text = figlet.textSync(slides[currentSlide], {
            font: font,
            horizontalLayout: 'default',
            verticalLayout: 'default'
        });
        cursor.goto(0, 0).write(text);
    }

    cursor.goto(0, process.stdout.rows).write(currentSlide + 1 + ' / ' + slides.length);

    if (author) {
        var authorText = 'by ' + author;
        cursor.goto(process.stdout.columns - authorText.length, process.stdout.rows).write(authorText);
    }
}

function clearScreen() {
    for (var i = 1; i <= process.stdout.rows; i++) {
        cursor.goto(0, i).eraseLine();
    }
}

function nextSlide() {
    currentSlide = (currentSlide + 1) % slides.length;
    showSlide();
}

function previousSlide() {
    currentSlide = currentSlide - 1;
    if (currentSlide < 0) currentSlide = slides.length - 1;
    showSlide();
}

function isNewLine(line) {
    return line.trim().match(/===(=)*/)
}

function readSlides(data) {
    var file = data.trim();

    var lines = file.split('\n');
    var lineAt = 0;

    if (file.trim().charAt(0) == '{')  {
        // file has a json prologue
        var json = '';
        while (lineAt < lines.length && !isNewLine(lines[lineAt++])) {
            json += lines[lineAt-1];
        }
        var json = JSON.parse(json);
        author = json.author ? json.author : '';
        font = json.font ? json.font : 'Standard';
        created = json.created ? json.created : '';
    }

    var slide = '';
    while (lineAt < lines.length) {
        if (isNewLine(lines[lineAt])) {
            addNewSlide(slide);
            slide = '';
        } else {
            slide += lines[lineAt] + '\n';
        }
        lineAt++;
    }

    // there might be no newline at the end
    if (slide.trim().length > 0) {
        addNewSlide(slide);
    }
}

function addNewSlide(slide) {
    slides.push(slide);
}

program
        .version(pkg.version)
        .usage('[options] <file>')
        .parse(process.argv);

if (process.stdout.isTTY) {

    if (!program.args[0]) {
        console.log('Please specify asciipresent file');
        process.exit(-1);
    }

    var file = program.args[0];

    fs.readFile(file, 'utf8', function (err,data) {
        if (err) {
            console.log(err);
            process.exit(-1);
        }

        readSlides(data);

        showSlide();
    });

    keypress(process.stdin);

    // listen for the "keypress" event
    process.stdin.on('keypress', function (ch, key) {
        if (key && ((key.ctrl && key.name == 'c') || (key.name == 'escape') || (key.name == 'q'))) {
            process.stdin.pause();
            cursor.reset();
            cursor.show();
            cursor.goto(0, process.stdout.columns);
            console.log('\nBye!');
        }
        else if (key && key.name == 'left') {
            previousSlide();
        }
        else if (key && (key.name == 'right' || key.name == 'space')) {
            nextSlide();
        }
    });

    process.stdin.setRawMode(true);
    process.stdin.resume();

    cursor.hide();
} else {
    console.log("Please run this in console enviroment (I need TTY!)");
}
<commit_msg>don't print out image name<commit_after>// requirements

var program = require('commander');
var path = require('path');
var pkg = require(path.join(__dirname, 'package.json'));

var keypress = require('keypress');

var ansi = require('ansi'),
        cursor = ansi(process.stdout);

var figlet = require('figlet');

var fs = require('fs');

var ImageToAscii = require("image-to-ascii");

// ----

var slides = [];
var currentSlide = 0;

// ---- GLOBALS

var author = '';
var font = 'Standard';
var created = '';

// ----

function showSlide() {
    clearScreen();
    if (slides[currentSlide].indexOf('IMAGE') == 0) {
        var image = slides[currentSlide].substring('IMAGE'.length).trim();
        ImageToAscii(image, function(err, result){
            if (err) {
                console.log(err);
            }
            cursor.goto(0, 0).write(result);
        });
    }
    else {
        var text = figlet.textSync(slides[currentSlide], {
            font: font,
            horizontalLayout: 'default',
            verticalLayout: 'default'
        });
        cursor.goto(0, 0).write(text);
    }

    cursor.goto(0, process.stdout.rows).write(currentSlide + 1 + ' / ' + slides.length);

    if (author) {
        var authorText = 'by ' + author;
        cursor.goto(process.stdout.columns - authorText.length, process.stdout.rows).write(authorText);
    }
}

function clearScreen() {
    for (var i = 1; i <= process.stdout.rows; i++) {
        cursor.goto(0, i).eraseLine();
    }
}

function nextSlide() {
    currentSlide = (currentSlide + 1) % slides.length;
    showSlide();
}

function previousSlide() {
    currentSlide = currentSlide - 1;
    if (currentSlide < 0) currentSlide = slides.length - 1;
    showSlide();
}

function isNewLine(line) {
    return line.trim().match(/===(=)*/)
}

function readSlides(data) {
    var file = data.trim();

    var lines = file.split('\n');
    var lineAt = 0;

    if (file.trim().charAt(0) == '{')  {
        // file has a json prologue
        var json = '';
        while (lineAt < lines.length && !isNewLine(lines[lineAt++])) {
            json += lines[lineAt-1];
        }
        var json = JSON.parse(json);
        author = json.author ? json.author : '';
        font = json.font ? json.font : 'Standard';
        created = json.created ? json.created : '';
    }

    var slide = '';
    while (lineAt < lines.length) {
        if (isNewLine(lines[lineAt])) {
            addNewSlide(slide);
            slide = '';
        } else {
            slide += lines[lineAt] + '\n';
        }
        lineAt++;
    }

    // there might be no newline at the end
    if (slide.trim().length > 0) {
        addNewSlide(slide);
    }
}

function addNewSlide(slide) {
    slides.push(slide);
}

program
        .version(pkg.version)
        .usage('[options] <file>')
        .parse(process.argv);

if (process.stdout.isTTY) {

    if (!program.args[0]) {
        console.log('Please specify asciipresent file');
        process.exit(-1);
    }

    var file = program.args[0];

    fs.readFile(file, 'utf8', function (err,data) {
        if (err) {
            console.log(err);
            process.exit(-1);
        }

        readSlides(data);

        showSlide();
    });

    keypress(process.stdin);

    // listen for the "keypress" event
    process.stdin.on('keypress', function (ch, key) {
        if (key && ((key.ctrl && key.name == 'c') || (key.name == 'escape') || (key.name == 'q'))) {
            process.stdin.pause();
            cursor.reset();
            cursor.show();
            cursor.goto(0, process.stdout.columns);
            console.log('\nBye!');
        }
        else if (key && key.name == 'left') {
            previousSlide();
        }
        else if (key && (key.name == 'right' || key.name == 'space')) {
            nextSlide();
        }
    });

    process.stdin.setRawMode(true);
    process.stdin.resume();

    cursor.hide();
} else {
    console.log("Please run this in console enviroment (I need TTY!)");
}
<|endoftext|>