<commit_before>var ractive,
    triggerStartTime = Date.now(),
    printLengthPerPrintCm = 5,
    minTriggerResetTimeMs = 3 * 1000,
    viewTransitionTimeMs = 2000;

$.get('/config').then(initWithConfig);

function initWithConfig(config) {
  var collectorBase = 'http://' + config.collector.host + ':' + config.collector.port;
  var client = new Faye.Client(collectorBase + '/faye');
  ractive = new Ractive({
    el: '#ui',
    template: '#ui-template',
    computed: {
      recentDevices: function () {
        var devices = _.sortByOrder(this.get('metadata'), ['time']);
        return devices;
      },
      deviceTotalsByManufacturer: function () {
        var counts = _( this.get('metadata') )
                      .countBy('shortName')
                      .value();

        if (counts['undefined']) {
          counts['Unknown'] = counts['undefined'];
          delete counts['undefined'];
        }

        // Sort
        counts = _(counts)
          .pairs()
          .sortBy(function (item) { return item[1]; })
          .reverse()
          .map(function (item) {
            return {
              name : item[0],
              count: item[1]
            };
          })
          .value();

        return counts;
      },
      totalDevices: function () {
        return this.get('metadata').length;
      },
      printLength: function () {
        return this.get('printCount') * printLengthPerPrintCm;
      },
      totalCameras: function () {
        return this.get('latestImages').length;
      }
    },
    data: {
      collectorBase: collectorBase,
      currentView: 'images',
      isTriggering: false,
      latestImages: [],
      metadata: [],
      printCount: 0,
      imageCount: 0,
      filterNoAps: function (data) {
        return _.filter(data, function (d) {
          return d.aps != '';
        });
      }
    }
  });

  window.onhashchange = renderNextView;

  function viewInUrlHash() {
    if (window.location.hash) {
      return window.location.hash.replace('#', '');
    } else {
      return null;
    }
  }

  client.subscribe('/trigger', handleTrigger);
  client.subscribe('/reload', handleReload);
  client.subscribe('/render', handleRender);
  handleRender({}); // Initial render

  function incrementPrintCount() {
    ractive.set('printCount', ractive.get('printCount') + 1);
  }

  function incrementImageCount() {
    ractive.set('imageCount', ractive.get('imageCount') + 1);
  }

  // Transition to new view when the
  // 'nextView' property is set
  ractive.observe('nextView', function (newValue, oldValue, keypath) {
    if (newValue == null) { return; }

    var currentView = ractive.get('currentView'),
        nextView = newValue;

    if (currentView === nextView) {
      console.info('Views are the same, will not transition', currentView);
      return;
    }

    ractive.set({incomingView: nextView});
    ractive.set({outgoingView: currentView});

    setTimeout(function() {
      ractive.set({
        incomingView: null, outgoingView: null, currentView: nextView
      });
    }, viewTransitionTimeMs);
  });

  renderNextView();

  function renderNextView() {
    var currentView = ractive.get('currentView'),
        timeBetweenViewsMs,
        nextView,
        views = _.map(ractive.findAll('.view'), function(x) {
      var viewId = x.getAttribute('id');

      if(viewId != currentView) {
        return viewId;
      }
    });

    views = _.compact(views);
    nextView = _.sample(views);

    if (viewInUrlHash()) {
      console.warn('URL hash is overriding random view selection');
      nextView = viewInUrlHash();
    }

    console.log('nextView', nextView);
    ractive.set('nextView', nextView);

    if(nextView === 'images') {
      timeBetweenViewsMs = viewTransitionTimeMs + 10000;
    } else {
      timeBetweenViewsMs = viewTransitionTimeMs + 5000;
    }

    setTimeout(renderNextView, timeBetweenViewsMs);
  }

  function handleTrigger(msg) {
    console.log('TRIGGER', msg);
    ractive.set('isTriggering', true);
    triggerStartTime = Date.now();
  }

  function handleReload(msg) {
    console.log('RELOAD', msg);
    window.location.reload(false);
  }

  function handleRender(msg) {
    console.log('RENDER', msg);

    incrementPrintCount();

    $.get(collectorBase + '/state')
      .then(function (data) {
        console.log('data', data);
        window.d = data;
        ractive.set(data);
        incrementImageCount();

        var renderInterval = Date.now() - triggerStartTime,
        timeLeft = minTriggerResetTimeMs - renderInterval;

        if (timeLeft <= 0) {
          ractive.set('isTriggering', false);
        } else {
          setTimeout(function () {
            ractive.set('isTriggering', false);
          }, timeLeft);
        }
      });
  }

  function addCachebuster(url) {
    return url + '?' + Date.now();
  }
}
<commit_msg>Shuffle recents<commit_after>var ractive,
    triggerStartTime = Date.now(),
    printLengthPerPrintCm = 5,
    minTriggerResetTimeMs = 3 * 1000,
    viewTransitionTimeMs = 2000;

$.get('/config').then(initWithConfig);

function initWithConfig(config) {
  var collectorBase = 'http://' + config.collector.host + ':' + config.collector.port;
  var client = new Faye.Client(collectorBase + '/faye');
  ractive = new Ractive({
    el: '#ui',
    template: '#ui-template',
    computed: {
      recentDevices: function () {
        // var devices = _.sortByOrder(this.get('metadata'), ['time']);
        var devices = _.shuffle(this.get('metadata'));
        return devices;
      },
      deviceTotalsByManufacturer: function () {
        var counts = _( this.get('metadata') )
                      .countBy('shortName')
                      .value();

        if (counts['undefined']) {
          counts['Unknown'] = counts['undefined'];
          delete counts['undefined'];
        }

        // Sort
        counts = _(counts)
          .pairs()
          .sortBy(function (item) { return item[1]; })
          .reverse()
          .map(function (item) {
            return {
              name : item[0],
              count: item[1]
            };
          })
          .value();

        return counts;
      },
      totalDevices: function () {
        return this.get('metadata').length;
      },
      printLength: function () {
        return this.get('printCount') * printLengthPerPrintCm;
      },
      totalCameras: function () {
        return this.get('latestImages').length;
      }
    },
    data: {
      collectorBase: collectorBase,
      currentView: 'images',
      isTriggering: false,
      latestImages: [],
      metadata: [],
      printCount: 0,
      imageCount: 0,
      filterNoAps: function (data) {
        return _.filter(data, function (d) {
          return d.aps != '';
        });
      }
    }
  });

  window.onhashchange = renderNextView;

  function viewInUrlHash() {
    if (window.location.hash) {
      return window.location.hash.replace('#', '');
    } else {
      return null;
    }
  }

  client.subscribe('/trigger', handleTrigger);
  client.subscribe('/reload', handleReload);
  client.subscribe('/render', handleRender);
  handleRender({}); // Initial render

  function incrementPrintCount() {
    ractive.set('printCount', ractive.get('printCount') + 1);
  }

  function incrementImageCount() {
    ractive.set('imageCount', ractive.get('imageCount') + 1);
  }

  // Transition to new view when the
  // 'nextView' property is set
  ractive.observe('nextView', function (newValue, oldValue, keypath) {
    if (newValue == null) { return; }

    var currentView = ractive.get('currentView'),
        nextView = newValue;

    if (currentView === nextView) {
      console.info('Views are the same, will not transition', currentView);
      return;
    }

    ractive.set({incomingView: nextView});
    ractive.set({outgoingView: currentView});

    setTimeout(function() {
      ractive.set({
        incomingView: null, outgoingView: null, currentView: nextView
      });
    }, viewTransitionTimeMs);
  });

  renderNextView();

  function renderNextView() {
    var currentView = ractive.get('currentView'),
        timeBetweenViewsMs,
        nextView,
        views = _.map(ractive.findAll('.view'), function(x) {
      var viewId = x.getAttribute('id');

      if(viewId != currentView) {
        return viewId;
      }
    });

    views = _.compact(views);
    nextView = _.sample(views);

    if (viewInUrlHash()) {
      console.warn('URL hash is overriding random view selection');
      nextView = viewInUrlHash();
    }

    console.log('nextView', nextView);
    ractive.set('nextView', nextView);

    if(nextView === 'images') {
      timeBetweenViewsMs = viewTransitionTimeMs + 10000;
    } else {
      timeBetweenViewsMs = viewTransitionTimeMs + 5000;
    }

    setTimeout(renderNextView, timeBetweenViewsMs);
  }

  function handleTrigger(msg) {
    console.log('TRIGGER', msg);
    ractive.set('isTriggering', true);
    triggerStartTime = Date.now();
  }

  function handleReload(msg) {
    console.log('RELOAD', msg);
    window.location.reload(false);
  }

  function handleRender(msg) {
    console.log('RENDER', msg);

    incrementPrintCount();

    $.get(collectorBase + '/state')
      .then(function (data) {
        console.log('data', data);
        window.d = data;
        ractive.set(data);
        incrementImageCount();

        var renderInterval = Date.now() - triggerStartTime,
        timeLeft = minTriggerResetTimeMs - renderInterval;

        if (timeLeft <= 0) {
          ractive.set('isTriggering', false);
        } else {
          setTimeout(function () {
            ractive.set('isTriggering', false);
          }, timeLeft);
        }
      });
  }

  function addCachebuster(url) {
    return url + '?' + Date.now();
  }
}
<|endoftext|>


<commit_before>//= require /node_modules/d3/d3.min.js
//= require common.js
//= require_self

"use strict";

var OpenSpeedMonitor = OpenSpeedMonitor || {};
OpenSpeedMonitor.ChartComponents = OpenSpeedMonitor.ChartComponents || {};

OpenSpeedMonitor.ChartComponents.ChartBars = (function () {
    var data = [];
    var minValue = 0;
    var maxValue = 10000;
    var height = 500;
    var width = 1000;
    var barBand = OpenSpeedMonitor.ChartComponents.common.barBand;
    var barColor = "#1660a7";
    var individualColors = false;
    var transitionDuration = OpenSpeedMonitor.ChartComponents.common.transitionDuration;
    var isRestrained = false;
    var forceSignInLabel = false;
    var highlightId;
    var eventHandlers = {};

    var setData = function (componentData) {
        data = componentData.values || data;
        minValue = (componentData.min !== undefined) ? componentData.min : minValue;
        maxValue = (componentData.max !== undefined) ? componentData.max : maxValue;
        height = componentData.height || height;
        width = componentData.width || width;
        barColor = componentData.color || barColor;
        individualColors = componentData.individualColors || individualColors;
        forceSignInLabel = (componentData.forceSignInLabel !== undefined) ? componentData.forceSignInLabel : forceSignInLabel;
        isRestrained = (componentData.isRestrained !== undefined) ? componentData.isRestrained : isRestrained;
        highlightId = highlightId!==componentData.highLightId ? componentData.highLightId || highlightId : undefined;
    };

    var render = function (selection, isAggregationValueChange) {
        var xScale = d3.scale.linear().range([0, width]);
        var yScale = d3.scale.ordinal().rangeBands([0, height]);

        xScale.domain([minValue, maxValue]);
        yScale.domain(data.map(function(d) { return d.id; }));
        var bars = selection.selectAll(".bar").data(data, function (d) {
            return d.id;
        });
        renderExit(bars.exit());
        renderEnter(bars.enter(), yScale);
        renderUpdate(bars, xScale, yScale, isAggregationValueChange);
    };

    var renderEnter = function (enterSelection) {
        var bars = enterSelection.append("g")
            .attr("class", "bar");
        bars.append("rect")
            .attr("class", "bar-rect")
            .attr("x", 0)
            .attr("y", 0)
            .attr("height", barBand)
            .each(function (d) {
                var color = individualColors?d.color: barColor;
                d3.select(this).attr("fill", color);
            });
        bars.append("text")
            .attr("class", "bar-value")
            .attr("dominant-baseline", "middle")
            .style("fill", "white")
            .style("font-weight", "bold");
    };

    var renderUpdate = function (updateSelection, xScale, yScale, isAggregationValueChange) {
        var valueLabelOffset = 10;
        updateSelection
            .on("mouseover", function(data) { callEventHandler("mouseover", data) })
            .on("mouseout", function(data) { callEventHandler("mouseout", data) })
            .on("click", function(data) { callEventHandler("click", data) });

        updateSelection.select(".bar-value").text(function (d) {
            if (d.value === null) {
                var prefix = d.showLabelOnTop ? d.label + ": " : "";
                prefix = prefix + (d.value > 0 && forceSignInLabel ? "+" : "");
                return prefix + formatValue(d.value) + " " + d.unit;
            } else {
                return ''
            }
        });

        var transition;
        var xTransition;
        if (isAggregationValueChange) {
            xTransition = updateSelection.transition().duration(transitionDuration);
            transition = xTransition;
        } else {
            xTransition = updateSelection;
            transition = updateSelection
                .transition()
                .duration(transitionDuration);
        }

        xTransition.select(".bar-rect")
            .attr("x", function (d) {
                return barStart(xScale, d.value)
            })
            .attr("width", function (d) {
                return barWidth(xScale, d.value);
            });
        xTransition.select(".bar-value")
            .attr("x", function (d) {
                return (d.value < 0) ? (barStart(xScale, d.value) + valueLabelOffset) : (barEnd(xScale, d.value) - valueLabelOffset);
            });

        transition.style("opacity", getOpacity);
        transition.select(".bar-rect")
            .style("opacity", function (d) {
                return !(d.id===highlightId || !highlightId) ? 0.2 : 1;
            })
            .attr("y", function (d) {
                return yScale(d.id)
            })
            .each(function (d) {
                var color = individualColors?d.color: barColor;
                d3.select(this).attr("fill", color);
            });
        transition.select(".bar-value")
            .attr("y", function (d) {
                return yScale(d.id) + barBand / 2;
            })
            .attr("text-anchor", function (d) {
                return (d.value < 0) ? "start" : "end";
            })
            .style("opacity", function(d) {
                return ((this.getComputedTextLength() + 2 * valueLabelOffset) > barWidth(xScale, d.value)) ? 0 : 1;
            });
    };

    var barEnd = function(xScale, value) {
        return (value < 0) ? xScale(0) : xScale(value);
    };

    var barStart = function (xScale, value) {
        return (value < 0) ? xScale(value) : xScale(0);
    };

    var barWidth = function(xScale, value) {
        return value === null ? 0 : (barEnd(xScale, value) - barStart(xScale, value));
    };

    var renderExit = function (exitSelection) {
        var exitTransition = exitSelection
            .transition()
            .duration(transitionDuration);
        exitTransition
            .style("opacity", 0)
            .remove();
    };

    var formatValue = function (value) {
        var precision = (maxValue >= 1000 || minValue <= -1000) ? 0 : 2;
        return parseFloat(value).toFixed(precision).toString();
    };

    var callEventHandler = function (eventType, bar) {
        if (eventHandlers[eventType]) {
            eventHandlers[eventType](bar);
        }
    };

    var registerEventHandler = function (eventType, eventHandler) {
        eventHandlers[eventType] = eventHandler;
    };

    var getOpacity = function () {
        return isRestrained ? 0.2 : 1
    };

    var setOpacityFunction = function (func) {
        getOpacity = func;
    };

    return {
        render: render,
        setData: setData,
        on: registerEventHandler,
        setOpacitiyFunction: setOpacityFunction
    };
});
<commit_msg>[IT-2264] Fixed wrong check for null<commit_after>//= require /node_modules/d3/d3.min.js
//= require common.js
//= require_self

"use strict";

var OpenSpeedMonitor = OpenSpeedMonitor || {};
OpenSpeedMonitor.ChartComponents = OpenSpeedMonitor.ChartComponents || {};

OpenSpeedMonitor.ChartComponents.ChartBars = (function () {
    var data = [];
    var minValue = 0;
    var maxValue = 10000;
    var height = 500;
    var width = 1000;
    var barBand = OpenSpeedMonitor.ChartComponents.common.barBand;
    var barColor = "#1660a7";
    var individualColors = false;
    var transitionDuration = OpenSpeedMonitor.ChartComponents.common.transitionDuration;
    var isRestrained = false;
    var forceSignInLabel = false;
    var highlightId;
    var eventHandlers = {};

    var setData = function (componentData) {
        data = componentData.values || data;
        minValue = (componentData.min !== undefined) ? componentData.min : minValue;
        maxValue = (componentData.max !== undefined) ? componentData.max : maxValue;
        height = componentData.height || height;
        width = componentData.width || width;
        barColor = componentData.color || barColor;
        individualColors = componentData.individualColors || individualColors;
        forceSignInLabel = (componentData.forceSignInLabel !== undefined) ? componentData.forceSignInLabel : forceSignInLabel;
        isRestrained = (componentData.isRestrained !== undefined) ? componentData.isRestrained : isRestrained;
        highlightId = highlightId!==componentData.highLightId ? componentData.highLightId || highlightId : undefined;
    };

    var render = function (selection, isAggregationValueChange) {
        var xScale = d3.scale.linear().range([0, width]);
        var yScale = d3.scale.ordinal().rangeBands([0, height]);

        xScale.domain([minValue, maxValue]);
        yScale.domain(data.map(function(d) { return d.id; }));
        var bars = selection.selectAll(".bar").data(data, function (d) {
            return d.id;
        });
        renderExit(bars.exit());
        renderEnter(bars.enter(), yScale);
        renderUpdate(bars, xScale, yScale, isAggregationValueChange);
    };

    var renderEnter = function (enterSelection) {
        var bars = enterSelection.append("g")
            .attr("class", "bar");
        bars.append("rect")
            .attr("class", "bar-rect")
            .attr("x", 0)
            .attr("y", 0)
            .attr("height", barBand)
            .each(function (d) {
                var color = individualColors?d.color: barColor;
                d3.select(this).attr("fill", color);
            });
        bars.append("text")
            .attr("class", "bar-value")
            .attr("dominant-baseline", "middle")
            .style("fill", "white")
            .style("font-weight", "bold");
    };

    var renderUpdate = function (updateSelection, xScale, yScale, isAggregationValueChange) {
        var valueLabelOffset = 10;
        updateSelection
            .on("mouseover", function(data) { callEventHandler("mouseover", data) })
            .on("mouseout", function(data) { callEventHandler("mouseout", data) })
            .on("click", function(data) { callEventHandler("click", data) });

        updateSelection.select(".bar-value").text(function (d) {
          if (d.value !== null) {
                var prefix = d.showLabelOnTop ? d.label + ": " : "";
                prefix = prefix + (d.value > 0 && forceSignInLabel ? "+" : "");
                return prefix + formatValue(d.value) + " " + d.unit;
            } else {
                return ''
            }
        });

        var transition;
        var xTransition;
        if (isAggregationValueChange) {
            xTransition = updateSelection.transition().duration(transitionDuration);
            transition = xTransition;
        } else {
            xTransition = updateSelection;
            transition = updateSelection
                .transition()
                .duration(transitionDuration);
        }

        xTransition.select(".bar-rect")
            .attr("x", function (d) {
                return barStart(xScale, d.value)
            })
            .attr("width", function (d) {
                return barWidth(xScale, d.value);
            });
        xTransition.select(".bar-value")
            .attr("x", function (d) {
                return (d.value < 0) ? (barStart(xScale, d.value) + valueLabelOffset) : (barEnd(xScale, d.value) - valueLabelOffset);
            });

        transition.style("opacity", getOpacity);
        transition.select(".bar-rect")
            .style("opacity", function (d) {
                return !(d.id===highlightId || !highlightId) ? 0.2 : 1;
            })
            .attr("y", function (d) {
                return yScale(d.id)
            })
            .each(function (d) {
                var color = individualColors?d.color: barColor;
                d3.select(this).attr("fill", color);
            });
        transition.select(".bar-value")
            .attr("y", function (d) {
                return yScale(d.id) + barBand / 2;
            })
            .attr("text-anchor", function (d) {
                return (d.value < 0) ? "start" : "end";
            })
            .style("opacity", function(d) {
                return ((this.getComputedTextLength() + 2 * valueLabelOffset) > barWidth(xScale, d.value)) ? 0 : 1;
            });
    };

    var barEnd = function(xScale, value) {
        return (value < 0) ? xScale(0) : xScale(value);
    };

    var barStart = function (xScale, value) {
        return (value < 0) ? xScale(value) : xScale(0);
    };

    var barWidth = function(xScale, value) {
        return value === null ? 0 : (barEnd(xScale, value) - barStart(xScale, value));
    };

    var renderExit = function (exitSelection) {
        var exitTransition = exitSelection
            .transition()
            .duration(transitionDuration);
        exitTransition
            .style("opacity", 0)
            .remove();
    };

    var formatValue = function (value) {
        var precision = (maxValue >= 1000 || minValue <= -1000) ? 0 : 2;
        return parseFloat(value).toFixed(precision).toString();
    };

    var callEventHandler = function (eventType, bar) {
        if (eventHandlers[eventType]) {
            eventHandlers[eventType](bar);
        }
    };

    var registerEventHandler = function (eventType, eventHandler) {
        eventHandlers[eventType] = eventHandler;
    };

    var getOpacity = function () {
        return isRestrained ? 0.2 : 1
    };

    var setOpacityFunction = function (func) {
        getOpacity = func;
    };

    return {
        render: render,
        setData: setData,
        on: registerEventHandler,
        setOpacitiyFunction: setOpacityFunction
    };
});
<|endoftext|>


<commit_before>// Dependencies
var Config = require("./config")
  , Request = require("request")
  , Logger = require("bug-killer")
  , Repo = require("gry")
  , Async = require("async")
  , Fs = require("fs")
  ;

// Logger configuration
Logger.config.progress = {
    color: "#3498db"
  , text: "   > "
};

/**
 * makeApiRequest
 * Run API requests.
 *
 * @name makeApiRequest
 * @function
 * @param {String} api The relative API url.
 * @param {Function} callback The callback function.
 * @return {undefined}
 */
function makeApiRequest(api, callback) {
    Request({
        url: "https://api.github.com/" + api
      , auth: Config.github
      , json: true
      , headers: {
            "user-agent": "Repo Downloader"
        }
    }, function (err, res, body) {
        err = err || body.error || body.message;
        if (err) { return callback(err); }
        callback(null, body);
    });
}

/**
 * getOrgs
 * Gets the organizations where the authenticated user is member.
 *
 * @name getOrgs
 * @function
 * @param {Function} callback The callback function.
 * @return {undefined}
 */
function getOrgs(callback) {
    makeApiRequest("user/orgs", callback);
}

/**
 * getPRRepos
 * Gets the repositories where the `user` created pull requests.
 *
 * @name getPRRepos
 * @function
 * @param {String} user The user login value.
 * @param {Array} orgs The organizations where the user belongs to.
 * @param {Function} callback The callback function.
 * @return {undefined}
 */
function getPRRepos(user, orgs, callback) {
    var api = "search/issues?q=author:" + user + "%20is:pr"
      , page = 0
      , allRepos = []
      , ignoreAccounts = orgs.map(function (c) { return c.login; }).concat([Config.github.username])
      , match = null
      ;

    function seq() {
        Logger.log("Page: " + (++page), "progress");
        makeApiRequest(api + "&per_page=100&page=" + page, function (err, res) {
            if (err) { return callback(err); }

            allRepos = allRepos.concat(res.items.filter(function (c) {

                if (!c.full_name || !c.ssh_url || !c.owner) {
                    match = c.html_url.match(/github\.com\/(.*)\/(.*)\/pull/);
                    if (!match || match.length !== 3) {
                        Logger.log("Failed to get repository data for: " + c.html_url + " Incident must be reported.", "error");
                        return false;
                    }

                    c.owner = {
                        login: match[1]
                    };

                    c.full_name = c.owner.login + "/" + match[2];
                    c.ssh_url = "git@github.com:" + c.full_name + ".git";
                }

                return ignoreAccounts.indexOf(c.owner.login) === -1;
            }));

            if (!res.items.length) {
                return callback(null, allRepos);
            }

            seq();
        });
    }
    seq();
}

/**
 * getAllRepos
 * Gets all repositories from the provided `user`.
 *
 * @name getAllRepos
 * @function
 * @param {String} user The user login value.
 * @param {Array} orgs The organizations where the user belongs to.
 * @param {Boolean} isOrg A flag if the `user` is an organization or not.
 * @param {Function} callback The callback function.
 * @return {undefined}
 */
function getAllRepos(user, orgs, isOrg, callback) {
    if (typeof isOrg === "function") {
        callback = isOrg;
        isOrg = false;
    }

    var api = "users/" + user + "/repos"
      , page = 0
      , allRepos = []
      ;

    if (isOrg) {
        api = "orgs/" + user + "/repos";
    }

    function seq() {
        Logger.log("Page: " + (++page), "progress");
        makeApiRequest(api + "?per_page=100&page=" + page, function (err, res) {
            if (err) { return callback(err); }
            allRepos = allRepos.concat(res);
            if (!res.length) {
                Logger.log("Getting the repositories where " + user + " created pull requests.", "info");
                return getPRRepos(user, orgs, function (err, prRepos) {
                    if (err) {
                        Logger.log(err, "warn");
                    }
                    allRepos = allRepos.concat(prRepos);
                    return callback(null, allRepos);
                });
            }
            seq();
        });
    }
    seq();
}

/**
 * downloadRepos
 * Download repositories the provided repositories.
 *
 * @name downloadRepos
 * @function
 * @param {Array} repos An array with the repositories to download.
 * @param {Function} callback The callback function.
 * @return {undefined}
 */
function downloadRepos(repos, callback) {
    var funcs = []
      , complete = 0
      , notDownloaded = []
      ;

    repos.forEach(function (c) {

        if (!c) { return; }

        funcs.push(function (callback) {
            var repo = new Repo("./downloads")
              , path = "github/" + c.full_name
              ;

            if (Fs.existsSync(__dirname + "/downloads/" + path)) {
                Logger.log("Repository already downloaded: " + c.full_name, "warn");
                return callback();
            }

            Logger.log("Repository: " + c.full_name, "progress");
            repo.exec("clone " + c.ssh_url + " " + path, function (err) {

                if (err) {
                    notDownloaded.push(c);
                    return callback();
                }

                Logger.log("Downloaded " + c.full_name + " (" + (++complete) + "/" + repos.length + ")", "progress");
                callback();
            });
        });
    });

    Async.parallel(funcs, function (err) {

        if (notDownloaded.length) {
            Logger.log(notDownloaded.length + " repos failed to download. Trying again.", "warn");
            return downloadRepos(notDownloaded, callback);
        }
        callback();
    });
}

// Start the magic
Logger.log("Getting the organizations you belong to.", "info");
getOrgs(function (err, orgs) {
    if (err) { return Logger.log(err, "error"); }

    // Download user reposiotires
    Logger.log("Getting all your repositories.", "info");
    getAllRepos(Config.github.username, orgs, function (err, myRepos) {
        if (err) { return Logger.log(err, "error"); }

        // Download user repositories
        Logger.log("Downloading all your repositories.", "info");
        downloadRepos(myRepos, function (err) {
            if (err) { return Logger.log(err, "error"); }
            Logger.log("Downloaded all user repos.", "info");

            // Download the organization repositories
            var downloadOrgRepos = [];
            orgs.forEach(function (c) {
                downloadOrgRepos.push(function (callback) {
                    Logger.log("Getting " + c.login + "'s repositories.", "info");
                    getAllRepos(c.login, orgs, true, function (err, repos) {
                        if (err) { return callback(err); }
                        Logger.log("Downloading " + c.login + "'s repositories.", "info");
                        downloadRepos(repos, callback);
                    });
                });
            });

            Async.series(downloadOrgRepos, function (err) {
                if (err) { return Logger.log(err, "error"); }
                Logger.log("Done.", "info");
            });
        });
    });
});
<commit_msg>Use HTTPS url instead of GIT url to avoid some authentication issues.<commit_after>// Dependencies
var Config = require("./config")
  , Request = require("request")
  , Logger = require("bug-killer")
  , Repo = require("gry")
  , Async = require("async")
  , Fs = require("fs")
  ;

// Logger configuration
Logger.config.progress = {
    color: "#3498db"
  , text: "   > "
};

/**
 * makeApiRequest
 * Run API requests.
 *
 * @name makeApiRequest
 * @function
 * @param {String} api The relative API url.
 * @param {Function} callback The callback function.
 * @return {undefined}
 */
function makeApiRequest(api, callback) {
    Request({
        url: "https://api.github.com/" + api
      , auth: Config.github
      , json: true
      , headers: {
            "user-agent": "Repo Downloader"
        }
    }, function (err, res, body) {
        err = err || body.error || body.message;
        if (err) { return callback(err); }
        callback(null, body);
    });
}

/**
 * getOrgs
 * Gets the organizations where the authenticated user is member.
 *
 * @name getOrgs
 * @function
 * @param {Function} callback The callback function.
 * @return {undefined}
 */
function getOrgs(callback) {
    makeApiRequest("user/orgs", callback);
}

/**
 * getPRRepos
 * Gets the repositories where the `user` created pull requests.
 *
 * @name getPRRepos
 * @function
 * @param {String} user The user login value.
 * @param {Array} orgs The organizations where the user belongs to.
 * @param {Function} callback The callback function.
 * @return {undefined}
 */
function getPRRepos(user, orgs, callback) {
    var api = "search/issues?q=author:" + user + "%20is:pr"
      , page = 0
      , allRepos = []
      , ignoreAccounts = orgs.map(function (c) { return c.login; }).concat([Config.github.username])
      , match = null
      ;

    function seq() {
        Logger.log("Page: " + (++page), "progress");
        makeApiRequest(api + "&per_page=100&page=" + page, function (err, res) {
            if (err) { return callback(err); }

            allRepos = allRepos.concat(res.items.filter(function (c) {

                if (!c.full_name || !c.ssh_url || !c.owner) {
                    match = c.html_url.match(/github\.com\/(.*)\/(.*)\/pull/);
                    if (!match || match.length !== 3) {
                        Logger.log("Failed to get repository data for: " + c.html_url + " Incident must be reported.", "error");
                        return false;
                    }

                    c.owner = {
                        login: match[1]
                    };

                    c.full_name = c.owner.login + "/" + match[2];
                    c.ssh_url = "git@github.com:" + c.full_name + ".git";
                    c.clone_url = "https://github.com/" + c.full_name + ".git";
                }

                return ignoreAccounts.indexOf(c.owner.login) === -1;
            }));

            if (!res.items.length) {
                return callback(null, allRepos);
            }

            seq();
        });
    }
    seq();
}

/**
 * getAllRepos
 * Gets all repositories from the provided `user`.
 *
 * @name getAllRepos
 * @function
 * @param {String} user The user login value.
 * @param {Array} orgs The organizations where the user belongs to.
 * @param {Boolean} isOrg A flag if the `user` is an organization or not.
 * @param {Function} callback The callback function.
 * @return {undefined}
 */
function getAllRepos(user, orgs, isOrg, callback) {
    if (typeof isOrg === "function") {
        callback = isOrg;
        isOrg = false;
    }

    var api = "users/" + user + "/repos"
      , page = 0
      , allRepos = []
      ;

    if (isOrg) {
        api = "orgs/" + user + "/repos";
    }

    function seq() {
        Logger.log("Page: " + (++page), "progress");
        makeApiRequest(api + "?per_page=100&page=" + page, function (err, res) {
            if (err) { return callback(err); }
            allRepos = allRepos.concat(res);
            if (!res.length) {
                Logger.log("Getting the repositories where " + user + " created pull requests.", "info");
                return getPRRepos(user, orgs, function (err, prRepos) {
                    if (err) {
                        Logger.log(err, "warn");
                    }
                    allRepos = allRepos.concat(prRepos);
                    return callback(null, allRepos);
                });
            }
            seq();
        });
    }
    seq();
}

/**
 * downloadRepos
 * Download repositories the provided repositories.
 *
 * @name downloadRepos
 * @function
 * @param {Array} repos An array with the repositories to download.
 * @param {Function} callback The callback function.
 * @return {undefined}
 */
function downloadRepos(repos, callback) {
    var funcs = []
      , complete = 0
      , notDownloaded = []
      ;

    repos.forEach(function (c) {

        if (!c) { return; }

        funcs.push(function (callback) {
            var repo = new Repo("./downloads")
              , path = "github/" + c.full_name
              ;

            if (Fs.existsSync(__dirname + "/downloads/" + path)) {
                Logger.log("Repository already downloaded: " + c.full_name, "warn");
                return callback();
            }

            Logger.log("Repository: " + c.full_name, "progress");
            repo.exec("clone " + c.clone_url + " " + path, function (err) {

                if (err) {
                    console.log(err);
                    notDownloaded.push(c);
                    return callback();
                }

                Logger.log("Downloaded " + c.full_name + " (" + (++complete) + "/" + repos.length + ")", "progress");
                callback();
            });
        });
    });

    Async.parallel(funcs, function (err) {

        if (notDownloaded.length) {
            Logger.log(notDownloaded.length + " repos failed to download. Trying again.", "warn");
            return downloadRepos(notDownloaded, callback);
        }
        callback();
    });
}

// Start the magic
Logger.log("Getting the organizations you belong to.", "info");
getOrgs(function (err, orgs) {
    if (err) { return Logger.log(err, "error"); }

    // Download user reposiotires
    Logger.log("Getting all your repositories.", "info");
    getAllRepos(Config.github.username, orgs, function (err, myRepos) {
        if (err) { return Logger.log(err, "error"); }

        // Download user repositories
        Logger.log("Downloading all your repositories.", "info");
        downloadRepos(myRepos, function (err) {
            if (err) { return Logger.log(err, "error"); }
            Logger.log("Downloaded all user repos.", "info");

            // Download the organization repositories
            var downloadOrgRepos = [];
            orgs.forEach(function (c) {
                downloadOrgRepos.push(function (callback) {
                    Logger.log("Getting " + c.login + "'s repositories.", "info");
                    getAllRepos(c.login, orgs, true, function (err, repos) {
                        if (err) { return callback(err); }
                        Logger.log("Downloading " + c.login + "'s repositories.", "info");
                        downloadRepos(repos, callback);
                    });
                });
            });

            Async.series(downloadOrgRepos, function (err) {
                if (err) { return Logger.log(err, "error"); }
                Logger.log("Done.", "info");
            });
        });
    });
});
<|endoftext|>


<commit_before>(function(T, doc){
	'use strict';

	/**
	 * Represents a handler for gestures, used to set up basic structure for creating gestures.
	 * @name T.GestureHandler
	 * @class
	 * @param {DOMElement} element The element attached to the {@link T.GestureHandler}
	 */
	T.GestureHandler = Object.augment(function() {

		this.activate = function() {
			this.on(this.element, T.utils.getEvents().start);
		};

		this.deactivate = function() {
			this.off(this.element, T.utils.getEvents().start);
			this.bindDoc(false);
			T.cache.remove(this.element);
		};

		this.on = function(element, event) {
			if(T.utils.msPointer) {
				if(element.style && element.style.msTouchAction) {
					this.msTouchAction = element.style.msTouchAction;
				} else if (!element.style) {
					element.style = '';
				}
				element.style.msTouchAction = 'none';
			}
			element.addEventListener(event, this, false);
		};

		this.off = function(element, event) {
			element.removeEventListener(event, this, false);
			if(T.utils.msPointer) {
				if(element.style) {
					element.style.msTouchAction = this.msTouchAction;
				}
			}
		};

		this.reset = function() {
			this.gestures.forEach(function(gesture) {
				gesture.started = false;
				gesture.cancelled = false;
				gesture.countTouches = 0;
			});
			this.data.pointerIds = [];
			this.data.points = [];
			this.started = false;
			this.ended = false;
		};

		this.trigger = function(action, event, data) {
			var gesture;
			this.sortedGestures.forEach(function(sorted) {
				gesture = sorted.context;
				if(gesture.paused && T.utils.isFunction(gesture[action]) && !gesture.cancelled) {
					gesture.addPausedCallback(action, event, data);
				} else if(T.utils.isFunction(gesture[action]) && !gesture.cancelled) {
					gesture[action].call(gesture, event, data);
				}
			}, this);
		};

		this.play = function(trigger) {
			trigger = trigger || false;
			this.sortedGestures.map(function(sorted) {
				return sorted.context;
			}).filter(function(gesture) {
				return gesture.paused;
			}).forEach(function(gesture) {
				gesture.play(trigger);
			});
		};

		this.pause = function(type, excludeGesture) {
			this.sortedGestures.map(function(sorted){
				return sorted.context;
			}).filter(function(gesture) {
				return type ? (excludeGesture !== gesture && type === gesture.type) : (excludeGesture !== gesture);
			}).forEach(function(gesture) {
				gesture.pause();
			});
		};

		this.addGesture = function(gesture) {
			this.gestures.push(gesture);
			this.sortGestures();

			if(this.gestures.length === 1) {
				this.activate();
			}
		};

		this.removeGesture = function(gesture) {
			this.gestures = this.gestures.filter(function(obj) {
				return obj !== gesture;
			});
			this.sortGestures();

			if(this.gestures.length === 0) {
				this.deactivate();
			}
		};

		this.removeGestures = function(type) {
			this.gestures.filter(function(obj) {
				if(type) {
					return obj.type === type;
				}
				return true;
			}).forEach(function(gesture) {
				this.removeGesture(gesture);
			}, this);
		};

		this.cancelGesture = function(gesture) {
			if(!gesture.cancelled) {
				gesture.cancel.call(gesture);
				gesture.cancelled = true;
			}
		};

		this.cancelGestures = function(excludeType) {
			this.gestures.filter(function(obj) {
				return obj.type !== excludeType;
			}).forEach(function(gesture) {
				this.cancelGesture(gesture);
			}, this);
			return this;
		};

		this.cancelGesturesWithProps = function(props, excludeGesture) {
			this.gestures.filter(function(obj) {
				if(excludeGesture &&
					excludeGesture === obj) {
					return false;
				}
				return T.utils.validateProperties(obj, props);
			}).forEach(function(gesture) {
				this.cancelGesture(gesture);
			}, this);
		};

		this.sortGestures = function() {
			var sorted = [];

			this.gestures.forEach(function(gesture){
				sorted.push({
					key: gesture.sortKey,
					context: gesture
				});
			}, this);

			sorted.sort(function(g1, g2) {
				return g1.key - g2.key;
			});

			this.sortedGestures = sorted;
		};

		this.bindDoc = function(on) {
			this[on ? 'on' : 'off'](doc, T.utils.getEvents().move);
			this[on ? 'on' : 'off'](doc, T.utils.getEvents().end);
		};

		this.handleEvent = function(event) {
			var events = T.utils.getEvents();

			switch(event.type) {
			case events.start:
				if(this.started && this.ended) {
					this.reset();
				}
				this.bindDoc(true);
				this.setPoints(event);
				this.trigger('start', event, this.data);
				this.started = true;
				break;
			case events.move:
				this.setPoints(event);
				this.trigger('update', event, this.data);
				break;
			case events.end:
				this.bindDoc(false);
				this.trigger('end', event, this.data);
				this.ended = true;
				break;
			}
		};

		this.setPoints = function(event, touchList) {
			touchList = touchList || 'touches';

			var i, len, touches, pointerId, index;

			if(T.utils.touch) {
				touches = event[touchList];
				len = touches.length;

				for(i = 0; i < len; ++i) {
					this.data.points.length = len;
					this.data.points[i] = T.utils.transformPoint(event.target, new T.Point(touches[i].pageX, touches[i].pageY));
				}
			} else if(T.utils.msPointer) {
				pointerId = event.pointerId;
				index = this.data.pointerIds.indexOf(pointerId);
				if(index < 0 ) {
					index = this.data.pointerIds.push(pointerId) -1;
				}
				len = this.data.pointerIds.length;
				this.data.points.length = len;
				this.data.points[index] = T.utils.transformPoint(event.target, new T.Point(event.pageX, event.pageY));
			} else {
				this.data.points.length = 1;
				this.data.points[0] = T.utils.transformPoint(event.target, new T.Point(event.pageX, event.pageY));
			}
		};

		function GestureHandler(element) {
			this.element = element;
			this.gestures = [];
			this.sortedGestures = [];
			this.data = {};
			this.data.points = [];
			this.data.pointerIds = [];
			this.started = false;
			this.ended = false;
		}
		return GestureHandler;
	});
})(window.Touche, window.document);<commit_msg>Refactor sorting<commit_after>(function(T, doc){
	'use strict';

	/**
	 * Represents a handler for gestures, used to set up basic structure for creating gestures.
	 * @name T.GestureHandler
	 * @class
	 * @param {DOMElement} element The element attached to the {@link T.GestureHandler}
	 */
	T.GestureHandler = Object.augment(function() {

		this.activate = function() {
			this.on(this.element, T.utils.getEvents().start);
		};

		this.deactivate = function() {
			this.off(this.element, T.utils.getEvents().start);
			this.bindDoc(false);
			T.cache.remove(this.element);
		};

		this.on = function(element, event) {
			if(T.utils.msPointer) {
				if(element.style && element.style.msTouchAction) {
					this.msTouchAction = element.style.msTouchAction;
				} else if (!element.style) {
					element.style = '';
				}
				element.style.msTouchAction = 'none';
			}
			element.addEventListener(event, this, false);
		};

		this.off = function(element, event) {
			element.removeEventListener(event, this, false);
			if(T.utils.msPointer) {
				if(element.style) {
					element.style.msTouchAction = this.msTouchAction;
				}
			}
		};

		this.reset = function() {
			this.gestures.forEach(function(gesture) {
				gesture.started = false;
				gesture.cancelled = false;
				gesture.countTouches = 0;
			});
			this.data.pointerIds = [];
			this.data.points = [];
			this.started = false;
			this.ended = false;
		};

		this.trigger = function(action, event, data) {
			var gesture;
			this.sortedGestures.forEach(function(sorted) {
				gesture = sorted.context;
				if(gesture.paused && T.utils.isFunction(gesture[action]) && !gesture.cancelled) {
					gesture.addPausedCallback(action, event, data);
				} else if(T.utils.isFunction(gesture[action]) && !gesture.cancelled) {
					gesture[action].call(gesture, event, data);
				}
			}, this);
		};

		this.play = function(trigger) {
			trigger = trigger || false;
			this.sortedGestures.map(function(sorted) {
				return sorted.context;
			}).filter(function(gesture) {
				return gesture.paused;
			}).forEach(function(gesture) {
				gesture.play(trigger);
			});
		};

		this.pause = function(type, excludeGesture) {
			this.sortedGestures.map(function(sorted){
				return sorted.context;
			}).filter(function(gesture) {
				return type ? (excludeGesture !== gesture && type === gesture.type) : (excludeGesture !== gesture);
			}).forEach(function(gesture) {
				gesture.pause();
			});
		};

		this.addGesture = function(gesture) {
			this.gestures.push(gesture);
			this.sortGestures();

			if(this.gestures.length === 1) {
				this.activate();
			}
		};

		this.removeGesture = function(gesture) {
			this.gestures = this.gestures.filter(function(obj) {
				return obj !== gesture;
			});
			this.sortGestures();

			if(this.gestures.length === 0) {
				this.deactivate();
			}
		};

		this.removeGestures = function(type) {
			this.gestures.filter(function(obj) {
				if(type) {
					return obj.type === type;
				}
				return true;
			}).forEach(function(gesture) {
				this.removeGesture(gesture);
			}, this);
		};

		this.cancelGesture = function(gesture) {
			if(!gesture.cancelled) {
				gesture.cancel.call(gesture);
				gesture.cancelled = true;
			}
		};

		this.cancelGestures = function(excludeType) {
			this.gestures.filter(function(obj) {
				return obj.type !== excludeType;
			}).forEach(function(gesture) {
				this.cancelGesture(gesture);
			}, this);
			return this;
		};

		this.cancelGesturesWithProps = function(props, excludeGesture) {
			this.gestures.filter(function(obj) {
				if(excludeGesture &&
					excludeGesture === obj) {
					return false;
				}
				return T.utils.validateProperties(obj, props);
			}).forEach(function(gesture) {
				this.cancelGesture(gesture);
			}, this);
		};

		this.sortGestures = function() {
			this.sortedGestures = this.gestures.map(function(gesture) {
				return {
					key: gesture.sortKey,
					context: gesture
				};
			}).sort(function(g1, g2) {
				return g1.key - g2.key;
			});
		};

		this.bindDoc = function(on) {
			this[on ? 'on' : 'off'](doc, T.utils.getEvents().move);
			this[on ? 'on' : 'off'](doc, T.utils.getEvents().end);
		};

		this.handleEvent = function(event) {
			var events = T.utils.getEvents();

			switch(event.type) {
			case events.start:
				if(this.started && this.ended) {
					this.reset();
				}
				this.bindDoc(true);
				this.setPoints(event);
				this.trigger('start', event, this.data);
				this.started = true;
				break;
			case events.move:
				this.setPoints(event);
				this.trigger('update', event, this.data);
				break;
			case events.end:
				this.bindDoc(false);
				this.trigger('end', event, this.data);
				this.ended = true;
				break;
			}
		};

		this.setPoints = function(event, touchList) {
			touchList = touchList || 'touches';

			var i, len, touches, pointerId, index;

			if(T.utils.touch) {
				touches = event[touchList];
				len = touches.length;

				for(i = 0; i < len; ++i) {
					this.data.points.length = len;
					this.data.points[i] = T.utils.transformPoint(event.target, new T.Point(touches[i].pageX, touches[i].pageY));
				}
			} else if(T.utils.msPointer) {
				pointerId = event.pointerId;
				index = this.data.pointerIds.indexOf(pointerId);
				if(index < 0 ) {
					index = this.data.pointerIds.push(pointerId) -1;
				}
				len = this.data.pointerIds.length;
				this.data.points.length = len;
				this.data.points[index] = T.utils.transformPoint(event.target, new T.Point(event.pageX, event.pageY));
			} else {
				this.data.points.length = 1;
				this.data.points[0] = T.utils.transformPoint(event.target, new T.Point(event.pageX, event.pageY));
			}
		};

		function GestureHandler(element) {
			this.element = element;
			this.gestures = [];
			this.sortedGestures = [];
			this.data = {};
			this.data.points = [];
			this.data.pointerIds = [];
			this.started = false;
			this.ended = false;
		}
		return GestureHandler;
	});
})(window.Touche, window.document);<|endoftext|>


<commit_before>'use strict';

// Required args: base, entity
// Optional args: offset-x, offset-y
function canvas_attach(args){
    args = core_args({
      'args': args,
      'defaults': {
        'offset-x': 0,
        'offset-y': 0,
      },
    });

    core_entities[args['entity']]['attach'] = {
      'offset': {
        'x': args['offset-x'],
        'y': args['offset-y'],
      },
      'to': args['base'],
    };
}

function canvas_draw(){
    if(canvas_properties['clearColor'] === '#000'){
        canvas_buffer.clearRect(
          0,
          0,
          canvas_properties['width'],
          canvas_properties['height']
        );

    }else{
        canvas_setproperties({
          'properties': {
            'fillStyle': canvas_properties['clearColor'],
          },
        });
        canvas_buffer.fillRect(
          0,
          0,
          canvas_properties['width'],
          canvas_properties['height']
        );
    }

    draw_logic();

    canvas_canvas.drawImage(
      document.getElementById('buffer'),
      0,
      0
    );
}

function canvas_drawloop(){
    if(!core_menu_open){
        canvas_draw();
    }
    core_interval_animationFrame({
      'id': 'canvas-animationFrame',
    });
}

// Required args: vertices
// Optional args: properties, style, type, x, y
function canvas_draw_path(args){
    args = core_args({
      'args': args,
      'defaults': {
        'properties': {},
        'style': canvas_properties['style'],
        'translate': false,
        'type': 'lineTo',
        'x': 0,
        'y': 0,
      },
    });

    if(args['translate']){
        canvas_buffer.save();
        canvas_buffer.translate(
          args['x'],
          args['y']
        );
    }

    canvas_buffer.beginPath();
    for(var vertex in args['vertices']){
        canvas_buffer[args['vertices'][vertex]['type'] || args['type']](
          args['vertices'][vertex]['x'] || 0,
          args['vertices'][vertex]['y'] || 0,
          args['vertices'][vertex]['radius'],
          args['vertices'][vertex]['startAngle'],
          args['vertices'][vertex]['endAngle'],
          args['vertices'][vertex]['antiClockwise']
        );
    }
    canvas_buffer.closePath();

    canvas_setproperties({
      'properties': args['properties'],
    });

    canvas_buffer[args['style']]();

    if(args['translate']){
        canvas_buffer.restore();
    }
}

// Required args: stops
// Optional args: height, width, x, y
function canvas_gradient(args){
    args = core_args({
      'args': args,
      'defaults': {
        'height': 0,
        'width': 0,
        'x': 0,
        'y': 0,
      },
    });

    var gradient = canvas_buffer.createLinearGradient(
      args['x'],
      args['y'],
      args['width'],
      args['height']
    );
    for(var step in args['stops']){
        gradient.addColorStop(
          args['stops'][step]['offset'] || 0,
          args['stops'][step]['color'] || '#000'
        );
    }
    return gradient;
}

// Optional args: contextmenu
function canvas_init(args){
    args = core_args({
      'args': args,
      'defaults': {
        'contextmenu': true,
      },
    });

    canvas_properties = {
      'clearColor': '#000',
      'fillStyle': '#fff',
      'font': canvas_fonts['medium'],
      'height': 0,
      'lineJoin': 'miter',
      'lineWidth': 1,
      'strokeStyle': '#fff',
      'style': 'fill',
      'textAlign': 'start',
      'textBaseline': 'alphabetic',
      'width': 0,
    };

    var properties = {
      'id': 'canvas',
    };
    if(!args['contextmenu']){
        properties['oncontextmenu'] = function(){
            return false;
        };
    }
    core_html({
      'parent': document.body,
      'properties': properties,
      'type': 'canvas',
    });
    core_html({
      'parent': document.body,
      'properties': {
        'id': 'buffer',
      },
      'type': 'canvas',
    });

    canvas_buffer = document.getElementById('buffer').getContext(
      '2d',
      {
        'alpha': false,
      }
    );
    canvas_canvas = document.getElementById('canvas').getContext(
      '2d',
      {
        'alpha': false,
      }
    );

    window.onresize = canvas_resize;
    canvas_resize();

    core_entity_set({
      'default': true,
      'properties': {
        'attach': false,
        'x': 0,
        'y': 0,
      },
      'type': 'canvas',
    });

    if(core_type({
      'var': 'logic',
      'type': 'function',
    })){
        core_interval_modify({
          'id': 'canvas-interval',
          'paused': true,
          'todo': canvas_logicloop,
        });
    }
    core_interval_modify({
      'animationFrame': true,
      'id': 'canvas-animationFrame',
      'paused': true,
      'todo': canvas_drawloop,
    });

    if(!core_menu_open){
        canvas_setmode();
    }
}

function canvas_logicloop(){
    logic();

    core_group_modify({
      'groups': [
        'canvas',
      ],
      'todo': function(entity){
          canvas_logicloop_handle_entity(entity);
      },
    });
}

function canvas_logicloop_handle_entity(entity){
    if(core_entities[entity]['attach'] !== false){
        var attached = core_entities[core_entities[entity]['attach']['id']];
        for(var axis in core_entities[entity]['position']){
            core_entities[entity]['position'][axis] = attached['position'][axis] + core_entities[entity]['attach']['offset'][axis];
        }
    }
}

function canvas_resize(){
    var buffer = document.getElementById('buffer');
    var canvas = document.getElementById('canvas');

    canvas_properties['height'] = window.innerHeight;
    canvas_properties['height-half'] = canvas_properties['height'] / 2;
    buffer.height = canvas_properties['height'];
    canvas.height = canvas_properties['height'];

    canvas_properties['width'] = window.innerWidth;
    canvas_properties['width-half'] = canvas_properties['width'] / 2;
    buffer.width = canvas_properties['width'];
    canvas.width = canvas_properties['width'];

    Object.assign(
      canvas_buffer,
      canvas_properties
    );

    core_call({
      'todo': 'resize_logic',
    });
}

// Optional args: mode, newgame
function canvas_setmode(args){
    args = core_args({
      'args': args,
      'defaults': {
        'mode': 0,
        'newgame': false,
      },
    });

    core_storage_save();
    core_entity_remove_all();
    canvas_resize();

    core_mode = args['mode'];

    core_call({
      'args': core_mode,
      'todo': 'load_data',
    });

    if(args['newgame']){
        core_escape();
    }

    core_interval_resume_all();
}

// Required args: properties
function canvas_setproperties(args){
    Object.assign(
      canvas_properties,
      args['properties']
    );
    Object.assign(
      canvas_buffer,
      args['properties']
    );
}

// Optional args: id, quality, type
function canvas_uri(args){
    args = core_args({
      'args': args,
      'defaults': {
        'id': 'buffer',
        'quality': 1,
        'type': 'image/png',
      },
    });

    return document.getElementById(args['id']).toDataURL(
      args['type'],
      args['quality']
    );
}

var canvas_buffer = 0;
var canvas_canvas = 0;
var canvas_fonts = {
  'big': '300% monospace',
  'medium': '200% monospace',
  'small': '100% monospace',
};
var canvas_properties = {};
<commit_msg>reverted clear replacement with alpha<commit_after>'use strict';

// Required args: base, entity
// Optional args: offset-x, offset-y
function canvas_attach(args){
    args = core_args({
      'args': args,
      'defaults': {
        'offset-x': 0,
        'offset-y': 0,
      },
    });

    core_entities[args['entity']]['attach'] = {
      'offset': {
        'x': args['offset-x'],
        'y': args['offset-y'],
      },
      'to': args['base'],
    };
}

function canvas_draw(){
    if(canvas_properties['clearColor'] === '#000'){
        canvas_buffer.clearRect(
          0,
          0,
          canvas_properties['width'],
          canvas_properties['height']
        );

    }else{
        canvas_setproperties({
          'properties': {
            'fillStyle': canvas_properties['clearColor'],
          },
        });
        canvas_buffer.fillRect(
          0,
          0,
          canvas_properties['width'],
          canvas_properties['height']
        );
    }

    draw_logic();

    canvas_canvas.clearRect(
      0,
      0,
      canvas_properties['width'],
      canvas_properties['height']
    );
    canvas_canvas.drawImage(
      document.getElementById('buffer'),
      0,
      0
    );
}

function canvas_drawloop(){
    if(!core_menu_open){
        canvas_draw();
    }
    core_interval_animationFrame({
      'id': 'canvas-animationFrame',
    });
}

// Required args: vertices
// Optional args: properties, style, type, x, y
function canvas_draw_path(args){
    args = core_args({
      'args': args,
      'defaults': {
        'properties': {},
        'style': canvas_properties['style'],
        'translate': false,
        'type': 'lineTo',
        'x': 0,
        'y': 0,
      },
    });

    if(args['translate']){
        canvas_buffer.save();
        canvas_buffer.translate(
          args['x'],
          args['y']
        );
    }

    canvas_buffer.beginPath();
    for(var vertex in args['vertices']){
        canvas_buffer[args['vertices'][vertex]['type'] || args['type']](
          args['vertices'][vertex]['x'] || 0,
          args['vertices'][vertex]['y'] || 0,
          args['vertices'][vertex]['radius'],
          args['vertices'][vertex]['startAngle'],
          args['vertices'][vertex]['endAngle'],
          args['vertices'][vertex]['antiClockwise']
        );
    }
    canvas_buffer.closePath();

    canvas_setproperties({
      'properties': args['properties'],
    });

    canvas_buffer[args['style']]();

    if(args['translate']){
        canvas_buffer.restore();
    }
}

// Required args: stops
// Optional args: height, width, x, y
function canvas_gradient(args){
    args = core_args({
      'args': args,
      'defaults': {
        'height': 0,
        'width': 0,
        'x': 0,
        'y': 0,
      },
    });

    var gradient = canvas_buffer.createLinearGradient(
      args['x'],
      args['y'],
      args['width'],
      args['height']
    );
    for(var step in args['stops']){
        gradient.addColorStop(
          args['stops'][step]['offset'] || 0,
          args['stops'][step]['color'] || '#000'
        );
    }
    return gradient;
}

// Optional args: contextmenu
function canvas_init(args){
    args = core_args({
      'args': args,
      'defaults': {
        'contextmenu': true,
      },
    });

    canvas_properties = {
      'clearColor': '#000',
      'fillStyle': '#fff',
      'font': canvas_fonts['medium'],
      'height': 0,
      'lineJoin': 'miter',
      'lineWidth': 1,
      'strokeStyle': '#fff',
      'style': 'fill',
      'textAlign': 'start',
      'textBaseline': 'alphabetic',
      'width': 0,
    };

    var properties = {
      'id': 'canvas',
    };
    if(!args['contextmenu']){
        properties['oncontextmenu'] = function(){
            return false;
        };
    }
    core_html({
      'parent': document.body,
      'properties': properties,
      'type': 'canvas',
    });
    core_html({
      'parent': document.body,
      'properties': {
        'id': 'buffer',
      },
      'type': 'canvas',
    });

    canvas_buffer = document.getElementById('buffer').getContext('2d');
    canvas_canvas = document.getElementById('canvas').getContext('2d');

    window.onresize = canvas_resize;
    canvas_resize();

    core_entity_set({
      'default': true,
      'properties': {
        'attach': false,
        'x': 0,
        'y': 0,
      },
      'type': 'canvas',
    });

    if(core_type({
      'var': 'logic',
      'type': 'function',
    })){
        core_interval_modify({
          'id': 'canvas-interval',
          'paused': true,
          'todo': canvas_logicloop,
        });
    }
    core_interval_modify({
      'animationFrame': true,
      'id': 'canvas-animationFrame',
      'paused': true,
      'todo': canvas_drawloop,
    });

    if(!core_menu_open){
        canvas_setmode();
    }
}

function canvas_logicloop(){
    logic();

    core_group_modify({
      'groups': [
        'canvas',
      ],
      'todo': function(entity){
          canvas_logicloop_handle_entity(entity);
      },
    });
}

function canvas_logicloop_handle_entity(entity){
    if(core_entities[entity]['attach'] !== false){
        var attached = core_entities[core_entities[entity]['attach']['id']];
        for(var axis in core_entities[entity]['position']){
            core_entities[entity]['position'][axis] = attached['position'][axis] + core_entities[entity]['attach']['offset'][axis];
        }
    }
}

function canvas_resize(){
    var buffer = document.getElementById('buffer');
    var canvas = document.getElementById('canvas');

    canvas_properties['height'] = window.innerHeight;
    canvas_properties['height-half'] = canvas_properties['height'] / 2;
    buffer.height = canvas_properties['height'];
    canvas.height = canvas_properties['height'];

    canvas_properties['width'] = window.innerWidth;
    canvas_properties['width-half'] = canvas_properties['width'] / 2;
    buffer.width = canvas_properties['width'];
    canvas.width = canvas_properties['width'];

    Object.assign(
      canvas_buffer,
      canvas_properties
    );

    core_call({
      'todo': 'resize_logic',
    });
}

// Optional args: mode, newgame
function canvas_setmode(args){
    args = core_args({
      'args': args,
      'defaults': {
        'mode': 0,
        'newgame': false,
      },
    });

    core_storage_save();
    core_entity_remove_all();
    canvas_resize();

    core_mode = args['mode'];

    core_call({
      'args': core_mode,
      'todo': 'load_data',
    });

    if(args['newgame']){
        core_escape();
    }

    core_interval_resume_all();
}

// Required args: properties
function canvas_setproperties(args){
    Object.assign(
      canvas_properties,
      args['properties']
    );
    Object.assign(
      canvas_buffer,
      args['properties']
    );
}

// Optional args: id, quality, type
function canvas_uri(args){
    args = core_args({
      'args': args,
      'defaults': {
        'id': 'buffer',
        'quality': 1,
        'type': 'image/png',
      },
    });

    return document.getElementById(args['id']).toDataURL(
      args['type'],
      args['quality']
    );
}

var canvas_buffer = 0;
var canvas_canvas = 0;
var canvas_fonts = {
  'big': '300% monospace',
  'medium': '200% monospace',
  'small': '100% monospace',
};
var canvas_properties = {};
<|endoftext|>


<commit_before>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';
import React, {
  AppRegistry,
  Component,
  StyleSheet,
  Text,
  View
} from 'react-native';

class ksaReactNativeTestSuite extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit index.ios.js
        </Text>
        <Text style={styles.instructions}>
          Press Cmd+R to reload,{'\n'}
          Cmd+D or shake for dev menu
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('ksaReactNativeTestSuite', () => ksaReactNativeTestSuite);
<commit_msg>add code to reproduce the bug<commit_after>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';
import React, {
  AppRegistry,
  Component,
  StyleSheet,
  Text,
  View
} from 'react-native';

import kde from 'ksana-database';
import ksa from 'ksana-simple-api';
import wylie from 'tibetan/wylie';

class ksaReactNativeTestSuite extends Component {

  componentDidMount() {

    const options = {
      db: 'jiangkangyur',
      q: wylie.fromWylieWithWildcard('-'),
      uti: ['1.1a']
    };

    ksa.fetch(options, (err, rows) => {
      if (err) {
        console.log('ksa.fetch err: ', err);
      }
      else {
        console.log('ksa.fetch rows: ', rows);
      }
    });

  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit index.ios.js
        </Text>
        <Text style={styles.instructions}>
          Press Cmd+R to reload,{'\n'}
          Cmd+D or shake for dev menu
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('ksaReactNativeTestSuite', () => ksaReactNativeTestSuite);
<|endoftext|>


<commit_before>// [VexFlow](http://vexflow.com) - Copyright (c) Mohit Muthanna 2010.

import { Vex } from './vex';
import { Flow } from './tables';
import { Element } from './element';
import { Fraction } from './fraction';
import { Renderer } from './renderer';
import { Formatter } from './formatter';
import { Music } from './music';
import { Glyph } from './glyph';
import { Stave } from './stave';
import { StaveNote } from './stavenote';
import { StaveModifier } from './stavemodifier';
import { StaveTempo } from "./stavetempo";
import { Voice } from './voice';
import { Accidental } from './accidental';
import { Beam } from './beam';
import { StaveTie } from './stavetie';
import { TabStave } from './tabstave';
import { TabNote } from './tabnote';
import { Bend } from './bend';
import { Vibrato } from './vibrato';
import { VibratoBracket } from './vibratobracket';
import { Note } from './note';
import { ModifierContext } from './modifiercontext';
import { TickContext } from './tickcontext';
import { Articulation } from './articulation';
import { Annotation } from './annotation';
import { Barline } from './stavebarline';
import { NoteHead } from './notehead';
import { StaveConnector } from './staveconnector';
import { ClefNote } from './clefnote';
import { KeySignature } from './keysignature';
import { TimeSignature } from './timesignature';
import { TimeSigNote } from './timesignote';
import { Stem } from './stem';
import { TabTie } from './tabtie';
import { Clef } from './clef';
import { Modifier } from './modifier';
import { TabSlide } from './tabslide';
import { Tuplet } from './tuplet';
import { GraceNote } from './gracenote';
import { GraceTabNote } from './gracetabnote';
import { Tuning } from './tuning';
import { KeyManager } from './keymanager';
import { StaveHairpin } from './stavehairpin';
import { BoundingBox } from './boundingbox';
import { Stroke } from './strokes';
import { TextNote } from './textnote';
import { Curve } from './curve';
import { TextDynamics } from './textdynamics';
import { StaveLine } from './staveline';
import { Ornament } from './ornament';
import { PedalMarking } from './pedalmarking';
import { TextBracket } from './textbracket';
import { FretHandFinger } from './frethandfinger';
import { Repetition } from './staverepetition';
import { BarNote } from './barnote';
import { GhostNote } from './ghostnote';
import { NoteSubGroup } from './notesubgroup';
import { GraceNoteGroup } from './gracenotegroup';
import { Tremolo } from './tremolo';
import { StringNumber } from './stringnumber';
import { Crescendo } from './crescendo';
import { Volta } from './stavevolta';
import { Font } from './fonts/vexflow_font';
import { System } from './system';
import { Factory } from './factory';
import { Parser } from './parser';
import { EasyScore } from './easyscore';
import { Registry } from './registry';

Vex.Flow = Flow;
Vex.Flow.Element = Element;
Vex.Flow.Fraction = Fraction;
Vex.Flow.Renderer = Renderer;
Vex.Flow.Formatter = Formatter;
Vex.Flow.Music = Music;
Vex.Flow.Glyph = Glyph;
Vex.Flow.Stave = Stave;
Vex.Flow.StaveNote = StaveNote;
Vex.Flow.StaveModifier = StaveModifier;
Vex.Flow.StaveTempo = StaveTempo;
Vex.Flow.Voice = Voice;
Vex.Flow.Accidental = Accidental;
Vex.Flow.Beam = Beam;
Vex.Flow.StaveTie = StaveTie;
Vex.Flow.TabStave = TabStave;
Vex.Flow.TabNote = TabNote;
Vex.Flow.Bend = Bend;
Vex.Flow.Vibrato = Vibrato;
Vex.Flow.VibratoBracket = VibratoBracket;
Vex.Flow.Note = Note;
Vex.Flow.ModifierContext = ModifierContext;
Vex.Flow.TickContext = TickContext;
Vex.Flow.Articulation = Articulation;
Vex.Flow.Annotation = Annotation;
Vex.Flow.Barline = Barline;
Vex.Flow.NoteHead = NoteHead;
Vex.Flow.StaveConnector = StaveConnector;
Vex.Flow.ClefNote = ClefNote;
Vex.Flow.KeySignature = KeySignature;
Vex.Flow.TimeSignature = TimeSignature;
Vex.Flow.TimeSigNote = TimeSigNote;
Vex.Flow.Stem = Stem;
Vex.Flow.TabTie = TabTie;
Vex.Flow.Clef = Clef;
Vex.Flow.Modifier = Modifier;
Vex.Flow.TabSlide = TabSlide;
Vex.Flow.Tuplet = Tuplet;
Vex.Flow.GraceNote = GraceNote;
Vex.Flow.GraceTabNote = GraceTabNote;
Vex.Flow.Tuning = Tuning;
Vex.Flow.KeyManager = KeyManager;
Vex.Flow.StaveHairpin = StaveHairpin;
Vex.Flow.BoundingBox = BoundingBox;
Vex.Flow.Stroke = Stroke;
Vex.Flow.TextNote = TextNote;
Vex.Flow.Curve = Curve;
Vex.Flow.TextDynamics = TextDynamics;
Vex.Flow.StaveLine = StaveLine;
Vex.Flow.Ornament = Ornament;
Vex.Flow.PedalMarking = PedalMarking;
Vex.Flow.TextBracket = TextBracket;
Vex.Flow.FretHandFinger = FretHandFinger;
Vex.Flow.Repetition = Repetition;
Vex.Flow.BarNote = BarNote;
Vex.Flow.GhostNote = GhostNote;
Vex.Flow.NoteSubGroup = NoteSubGroup;
Vex.Flow.GraceNoteGroup = GraceNoteGroup;
Vex.Flow.Tremolo = Tremolo;
Vex.Flow.StringNumber = StringNumber;
Vex.Flow.Crescendo = Crescendo;
Vex.Flow.Volta = Volta;
Vex.Flow.Font = Font;
Vex.Flow.System = System;
Vex.Flow.Factory = Factory;
Vex.Flow.Parser = Parser;
Vex.Flow.EasyScore = EasyScore;
Vex.Flow.Registry = Registry;

export default Vex;
<commit_msg>fix double quote lint warning<commit_after>// [VexFlow](http://vexflow.com) - Copyright (c) Mohit Muthanna 2010.

import { Vex } from './vex';
import { Flow } from './tables';
import { Element } from './element';
import { Fraction } from './fraction';
import { Renderer } from './renderer';
import { Formatter } from './formatter';
import { Music } from './music';
import { Glyph } from './glyph';
import { Stave } from './stave';
import { StaveNote } from './stavenote';
import { StaveModifier } from './stavemodifier';
import { StaveTempo } from './stavetempo';
import { Voice } from './voice';
import { Accidental } from './accidental';
import { Beam } from './beam';
import { StaveTie } from './stavetie';
import { TabStave } from './tabstave';
import { TabNote } from './tabnote';
import { Bend } from './bend';
import { Vibrato } from './vibrato';
import { VibratoBracket } from './vibratobracket';
import { Note } from './note';
import { ModifierContext } from './modifiercontext';
import { TickContext } from './tickcontext';
import { Articulation } from './articulation';
import { Annotation } from './annotation';
import { Barline } from './stavebarline';
import { NoteHead } from './notehead';
import { StaveConnector } from './staveconnector';
import { ClefNote } from './clefnote';
import { KeySignature } from './keysignature';
import { TimeSignature } from './timesignature';
import { TimeSigNote } from './timesignote';
import { Stem } from './stem';
import { TabTie } from './tabtie';
import { Clef } from './clef';
import { Modifier } from './modifier';
import { TabSlide } from './tabslide';
import { Tuplet } from './tuplet';
import { GraceNote } from './gracenote';
import { GraceTabNote } from './gracetabnote';
import { Tuning } from './tuning';
import { KeyManager } from './keymanager';
import { StaveHairpin } from './stavehairpin';
import { BoundingBox } from './boundingbox';
import { Stroke } from './strokes';
import { TextNote } from './textnote';
import { Curve } from './curve';
import { TextDynamics } from './textdynamics';
import { StaveLine } from './staveline';
import { Ornament } from './ornament';
import { PedalMarking } from './pedalmarking';
import { TextBracket } from './textbracket';
import { FretHandFinger } from './frethandfinger';
import { Repetition } from './staverepetition';
import { BarNote } from './barnote';
import { GhostNote } from './ghostnote';
import { NoteSubGroup } from './notesubgroup';
import { GraceNoteGroup } from './gracenotegroup';
import { Tremolo } from './tremolo';
import { StringNumber } from './stringnumber';
import { Crescendo } from './crescendo';
import { Volta } from './stavevolta';
import { Font } from './fonts/vexflow_font';
import { System } from './system';
import { Factory } from './factory';
import { Parser } from './parser';
import { EasyScore } from './easyscore';
import { Registry } from './registry';

Vex.Flow = Flow;
Vex.Flow.Element = Element;
Vex.Flow.Fraction = Fraction;
Vex.Flow.Renderer = Renderer;
Vex.Flow.Formatter = Formatter;
Vex.Flow.Music = Music;
Vex.Flow.Glyph = Glyph;
Vex.Flow.Stave = Stave;
Vex.Flow.StaveNote = StaveNote;
Vex.Flow.StaveModifier = StaveModifier;
Vex.Flow.StaveTempo = StaveTempo;
Vex.Flow.Voice = Voice;
Vex.Flow.Accidental = Accidental;
Vex.Flow.Beam = Beam;
Vex.Flow.StaveTie = StaveTie;
Vex.Flow.TabStave = TabStave;
Vex.Flow.TabNote = TabNote;
Vex.Flow.Bend = Bend;
Vex.Flow.Vibrato = Vibrato;
Vex.Flow.VibratoBracket = VibratoBracket;
Vex.Flow.Note = Note;
Vex.Flow.ModifierContext = ModifierContext;
Vex.Flow.TickContext = TickContext;
Vex.Flow.Articulation = Articulation;
Vex.Flow.Annotation = Annotation;
Vex.Flow.Barline = Barline;
Vex.Flow.NoteHead = NoteHead;
Vex.Flow.StaveConnector = StaveConnector;
Vex.Flow.ClefNote = ClefNote;
Vex.Flow.KeySignature = KeySignature;
Vex.Flow.TimeSignature = TimeSignature;
Vex.Flow.TimeSigNote = TimeSigNote;
Vex.Flow.Stem = Stem;
Vex.Flow.TabTie = TabTie;
Vex.Flow.Clef = Clef;
Vex.Flow.Modifier = Modifier;
Vex.Flow.TabSlide = TabSlide;
Vex.Flow.Tuplet = Tuplet;
Vex.Flow.GraceNote = GraceNote;
Vex.Flow.GraceTabNote = GraceTabNote;
Vex.Flow.Tuning = Tuning;
Vex.Flow.KeyManager = KeyManager;
Vex.Flow.StaveHairpin = StaveHairpin;
Vex.Flow.BoundingBox = BoundingBox;
Vex.Flow.Stroke = Stroke;
Vex.Flow.TextNote = TextNote;
Vex.Flow.Curve = Curve;
Vex.Flow.TextDynamics = TextDynamics;
Vex.Flow.StaveLine = StaveLine;
Vex.Flow.Ornament = Ornament;
Vex.Flow.PedalMarking = PedalMarking;
Vex.Flow.TextBracket = TextBracket;
Vex.Flow.FretHandFinger = FretHandFinger;
Vex.Flow.Repetition = Repetition;
Vex.Flow.BarNote = BarNote;
Vex.Flow.GhostNote = GhostNote;
Vex.Flow.NoteSubGroup = NoteSubGroup;
Vex.Flow.GraceNoteGroup = GraceNoteGroup;
Vex.Flow.Tremolo = Tremolo;
Vex.Flow.StringNumber = StringNumber;
Vex.Flow.Crescendo = Crescendo;
Vex.Flow.Volta = Volta;
Vex.Flow.Font = Font;
Vex.Flow.System = System;
Vex.Flow.Factory = Factory;
Vex.Flow.Parser = Parser;
Vex.Flow.EasyScore = EasyScore;
Vex.Flow.Registry = Registry;

export default Vex;
<|endoftext|>


<commit_before>jQuery(document).ready(function($){
  	var jump_to;
	$.fn.authguard = function(callback) {
		jump_to = $(this);

		// making sure the return path is set as it should.
		href = jump_to.attr("href");
		if (typeof (href) == "undefined"){
			query = "";
		}else{
			query = href.split('?');
		}
		if (query.length > 1){
			return_to_query = query[1].split('&');
			return_to = return_to_query[0].split('=');
			if (return_to[0] == 'return_to'){
				jQuery.cookie('return_to', return_to[1], { 'path': "/" });
			};
		}

		if ($("#not_logged_in:visible a#sign_in").click().length == 0) {
			if (callback == "facebox"){
				$.facebox({"ajax": jump_to.attr("href")});
			}else{
				$(document).trigger('close.facebox');
			}
			if ($.isFunction(callback)){

				callback(jump_to);
			}
			jump_to = undefined;
			return callback === undefined;
		}
		return false;
	};

	// $("#fb_login_link").live("click",function(){
	// 	var fb_pop=window.open($(this).attr("href"),'fbpopup','height=360,width=360');
	// 	// var fb = fb_pop.document.getElementById("login_form");
	// 	// alert(fb_pop);
	// 	return false;
	// });
	$('a.auth').livequery('click', function() {return $(this).authguard(function(jump_to) { window.location = jump_to.attr('href'); })});

	$('form.auth, form.button-to:has(input.auth)').livequery('submit', function() {return $(this).authguard();});

	$('a.authbox').livequery('click', function() {
		return $(this).authguard('facebox');
	});

	$('a[rel*=authdrop]').livequery('click', function() {
		return $(this).authguard(function(j) {
			$.get(j.attr("href"), function(data) {
				$("#authdrop").hide().html(data).show("slow")
			});
		});
	});

	$("#login_modal form.login").livequery(function() {
		var form = $(this);
		$('#loginError').hide();
		$(this).ajaxForm({
			complete: function(request,message) {
			if(message == "error") {
				//$("#facebox .content .login-boxer").replaceWith(request.responseText);
				if (typeof (request.getResponseHeader('error'))!=null) {
					$('#loginError').show();
					$('#flash').hide('');
				}else if (request.responseText == ' ')
					$(document).trigger('close.facebox')
				} else {
					$("#not_logged_in").hide();
					$("#logged_in").show();
					$("#sign_in_section").empty().append(request.responseText);
					if (jump_to && jump_to.attr("return_to")){
						window.location = jump_to.attr("return_to");
					} else if (jump_to && jump_to.attr("action")){
						jump_to.submit();
					} else if (jump_to && jump_to.attr("href")){
						jump_to.click();
					} else{
						$(document).trigger('close.facebox');
					}
					//renderUserHeader();
					window.reload();

					// not necessary when you reload the window...
					/*$("li.start_story a.authbox").removeClass("authbox").removeAttr("return_to").attr("href","/pitches/new");
					$("li.suggest_story a.authbox").removeClass("authbox").removeAttr("return_to").attr("href","/tips/new");
					if(("#assignment_admin").length > 0)
					{
					}
					if($("#flash").length > 0){
						$("#flash").html("");
					}*/
				}
			}
		}); // end ajax form
	}); // end livequery

	$("#facebox .content #fb_updater #fb_profile form").livequery(function() {
		var form = $(this);
		$(this).ajaxForm({
			complete: function(request,message) {
				if(message == "error") {
					$("#facebox .content #fb_profile").replaceWith(request.responseText);
				} else {
					$(document).trigger('close.facebox');
					renderUserHeader();
					$("li.start_story a.authbox").removeClass("authbox").removeAttr("return_to").attr("href","/start_story");
				}
			}
		});
	});

	$("#facebox .content #fb_updater #spotus_login form").livequery(function() {
		var form = $(this);
		$(this).ajaxForm({
			complete: function(request,message) {
				if(message == "error") {
					$("#facebox .content #spotus_login").replaceWith(request.responseText);
				} else {
					$(document).trigger('close.facebox');
					renderUserHeader();
					$("li.start_story a.authbox").removeClass("authbox").removeAttr("return_to").attr("href","/start_story");
				}
			}
		});
	});

	$('a[id*=help]').click(function() {
		jQuery.facebox({ajax:"/sections/"+$(this).attr('id')});
		return false;
	});

	$('span[id*=help]').click(function() {
		jQuery.facebox({ajax:"/sections/"+$(this).attr('id')});
		return false;
	});

});

function showProfileForm(){
	jQuery.facebox.settings.modal = true;
	jQuery.facebox({ajax:"/myspot/profile/edit"});
}<commit_msg>taking out https for some calls for sections<commit_after>jQuery(document).ready(function($){
  	var jump_to;
	$.fn.authguard = function(callback) {
		jump_to = $(this);

		// making sure the return path is set as it should.
		href = jump_to.attr("href");
		if (typeof (href) == "undefined"){
			query = "";
		}else{
			query = href.split('?');
		}
		if (query.length > 1){
			return_to_query = query[1].split('&');
			return_to = return_to_query[0].split('=');
			if (return_to[0] == 'return_to'){
				jQuery.cookie('return_to', return_to[1], { 'path': "/" });
			};
		}

		if ($("#not_logged_in:visible a#sign_in").click().length == 0) {
			if (callback == "facebox"){
				$.facebox({"ajax": jump_to.attr("href")});
			}else{
				$(document).trigger('close.facebox');
			}
			if ($.isFunction(callback)){

				callback(jump_to);
			}
			jump_to = undefined;
			return callback === undefined;
		}
		return false;
	};

	// $("#fb_login_link").live("click",function(){
	// 	var fb_pop=window.open($(this).attr("href"),'fbpopup','height=360,width=360');
	// 	// var fb = fb_pop.document.getElementById("login_form");
	// 	// alert(fb_pop);
	// 	return false;
	// });
	$('a.auth').livequery('click', function() {return $(this).authguard(function(jump_to) { window.location = jump_to.attr('href'); })});

	$('form.auth, form.button-to:has(input.auth)').livequery('submit', function() {return $(this).authguard();});

	$('a.authbox').livequery('click', function() {
		return $(this).authguard('facebox');
	});

	$('a[rel*=authdrop]').livequery('click', function() {
		return $(this).authguard(function(j) {
			$.get(j.attr("href"), function(data) {
				$("#authdrop").hide().html(data).show("slow")
			});
		});
	});

	$("#login_modal form.login").livequery(function() {
		var form = $(this);
		$('#loginError').hide();
		$(this).ajaxForm({
			complete: function(request,message) {
			if(message == "error") {
				//$("#facebox .content .login-boxer").replaceWith(request.responseText);
				if (typeof (request.getResponseHeader('error'))!=null) {
					$('#loginError').show();
					$('#flash').hide('');
				}else if (request.responseText == ' ')
					$(document).trigger('close.facebox')
				} else {
					$("#not_logged_in").hide();
					$("#logged_in").show();
					$("#sign_in_section").empty().append(request.responseText);
					if (jump_to && jump_to.attr("return_to")){
						window.location = jump_to.attr("return_to");
					} else if (jump_to && jump_to.attr("action")){
						jump_to.submit();
					} else if (jump_to && jump_to.attr("href")){
						jump_to.click();
					} else{
						$(document).trigger('close.facebox');
					}
					//renderUserHeader();
					window.reload();

					// not necessary when you reload the window...
					/*$("li.start_story a.authbox").removeClass("authbox").removeAttr("return_to").attr("href","/pitches/new");
					$("li.suggest_story a.authbox").removeClass("authbox").removeAttr("return_to").attr("href","/tips/new");
					if(("#assignment_admin").length > 0)
					{
					}
					if($("#flash").length > 0){
						$("#flash").html("");
					}*/
				}
			}
		}); // end ajax form
	}); // end livequery

	$("#facebox .content #fb_updater #fb_profile form").livequery(function() {
		var form = $(this);
		$(this).ajaxForm({
			complete: function(request,message) {
				if(message == "error") {
					$("#facebox .content #fb_profile").replaceWith(request.responseText);
				} else {
					$(document).trigger('close.facebox');
					renderUserHeader();
					$("li.start_story a.authbox").removeClass("authbox").removeAttr("return_to").attr("href","/start_story");
				}
			}
		});
	});

	$("#facebox .content #fb_updater #spotus_login form").livequery(function() {
		var form = $(this);
		$(this).ajaxForm({
			complete: function(request,message) {
				if(message == "error") {
					$("#facebox .content #spotus_login").replaceWith(request.responseText);
				} else {
					$(document).trigger('close.facebox');
					renderUserHeader();
					$("li.start_story a.authbox").removeClass("authbox").removeAttr("return_to").attr("href","/start_story");
				}
			}
		});
	});

	$('a[id*=help]').click(function() {
		jQuery.facebox({ajax:"/sections/"+$(this).attr('id')});
		return false;
	});

	$('span[id*=help]').click(function() {
		jQuery.facebox({ajax:"http://"+window.location.hostname+"/sections/"+$(this).attr('id')});
		return false;
	});

});

function showProfileForm(){
	jQuery.facebox.settings.modal = true;
	jQuery.facebox({ajax:"/myspot/profile/edit"});
}<|endoftext|>


<commit_before>import React, {Component} from 'react';
import {
    View,
    StyleSheet,
    Text,
    ScrollView
} from 'react-native';

import Pill from 'app/shared_features/pill/Pill';

class SetSummary extends Component {

    render() {
        let pills = [];
        if (this.props.tags) {
            this.props.tags.forEach((tag) => {
                pills.push(<Pill text={tag} style={styles.pill} />);
            });
        }

        return (
            <View style={[styles.border, {flex: 1}]}>
                <ScrollView horizontal={true}
                    scrollEnabled={true}
                    showsHorizontalScrollIndicator={false}
                    style={{flex:1}}>
                        <View style={{flexDirection: 'row'}}>
                            <View style={{marginLeft: 12, justifyContent: 'center'}}>
                                <Text style={styles.text}>{this.props.weight} {this.props.metric} x {this.props.numReps}</Text>
                            </View>

                            {pills}
                        </View>
                </ScrollView>
            </View>
        );
    }

}

const styles = StyleSheet.create({
    border: {
        borderColor: '#e0e0e0',
        borderWidth: 1,
        paddingTop: 5,
        paddingBottom: 5,
        backgroundColor: 'white'
    },
    text: {
        color: 'rgba(77, 77, 77, 1)',
        fontSize: 12,
        fontWeight: 'bold',
    },
    pill: {
        marginLeft: 5
    }
});

export default SetSummary;
<commit_msg>Fixed warning with set summary pills<commit_after>import React, {Component} from 'react';
import {
    View,
    StyleSheet,
    Text,
    ScrollView
} from 'react-native';

import Pill from 'app/shared_features/pill/Pill';

class SetSummary extends Component {

    render() {
        let pills = [];
        if (this.props.tags) {
            let position = 0;
            this.props.tags.forEach((tag) => {
                let key = position;
                pills.push(<Pill key={position} text={tag} style={styles.pill} />);
                position++;
            });
        }

        return (
            <View style={[styles.border, {flex: 1}]}>
                <ScrollView horizontal={true}
                    scrollEnabled={true}
                    showsHorizontalScrollIndicator={false}
                    style={{flex:1}}>
                        <View style={{flexDirection: 'row'}}>
                            <View style={{marginLeft: 12, justifyContent: 'center'}}>
                                <Text style={styles.text}>{this.props.weight} {this.props.metric} x {this.props.numReps}</Text>
                            </View>

                            {pills}
                        </View>
                </ScrollView>
            </View>
        );
    }

}

const styles = StyleSheet.create({
    border: {
        borderColor: '#e0e0e0',
        borderWidth: 1,
        paddingTop: 5,
        paddingBottom: 5,
        backgroundColor: 'white'
    },
    text: {
        color: 'rgba(77, 77, 77, 1)',
        fontSize: 12,
        fontWeight: 'bold',
    },
    pill: {
        marginLeft: 5
    }
});

export default SetSummary;
<|endoftext|>