<commit_before>// Packages
const ghgot = require('gh-got');
const moment = require('moment');

// Mine
const getResponse = query => {
  const token = require('../config.json').token || false;

  if (!token) {
    throw new Error(`token is not defined`);
  }

  return ghgot('https://api.github.com/graphql', {
    json: true,
    headers: { authorization: `bearer ${token}` },
    body: { query }
  });
};

exports.tools = {
  status: () => {
    return new Promise((resolve, reject) => {
      ghgot('https://status.github.com/api/last-message.json')
        .then(response => {
          let data = response.body;

          resolve({
            status: `${data.status} 🦄`,
            msg: data.body,
            date: moment(data.created_on).format('MMMM DD YYYY HH:mm')
          });
        })
        .catch(err => {
          reject(err);
        });
    });
  },
  radar: () => {
    return new Promise((resolve, reject) => {
      let query = `query {
        repository(owner: "github", name: "services") {
          issues(first: 1, labels: "O: radar", states: OPEN) {
            edges {
              node {
                url
              }
            }
          }
        }
      }`;

      getResponse(query)
        .then(response => {
          let url = response.body.data.repository.issues.edges[0].node.url;

          resolve(`${url}`);
        })
        .catch(err => {
          reject(err);
        });
    });
  },
  repo: repo => {
    return new Promise((resolve, reject) => {
      let query = `query {
        repository(owner: "github", name: "${repo}") {
          url
        }
      }`;

      getResponse(query)
        .then(response => {
          let url = response.body.data.repository.url;

          resolve(`${url}`);
        })
        .catch(err => {
          reject(err);
        });
    });
  },
  territory: territory => {
    return new Promise((resolve, reject) => {
      let query = `query {
        repository(owner: "github", name: "services") {
          url
          issues(states: OPEN, labels: "ST: ${territory}") {
            totalCount
          }
          projects(search: "ST: ${territory}") {
            nodes {
              url
            }
          }
        }
      }`;

      getResponse(query)
        .then(response => {
          resolve({
            url: response.body.data.repository.url
              ? `${response.body.data.repository.url}/issues?q=is:open is:issue label:"ST: ${territory}"`
              : null,
            count: Number.parseInt(
              response.body.data.repository.issues.totalCount
            ),
            project: response.body.data.repository.projects.nodes[0].url
          });
        })
        .catch(err => {
          reject(err);
        });
    });
  },
  projects: (number = 2) => {
    return new Promise(function(resolve, reject) {
      let query = `query {
        repository(owner: "github", name: "services") {
          project(number: ${number}) {
            ... on Project {
              columns(first: 1) {
                nodes {
                  ... on ProjectColumn {
                    columnname: name
                  }
                  cards(first: 100) {
                    edges {
                      node {
                        content {
                          ... on Issue {
                            title
                            url
                          }
                          ... on PullRequest {
                            title
                            url
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }`;

      getResponse(query)
        .then(response => {
          resolve(response.body.data.repository.project);
        })
        .catch(err => {
          reject(err);
        });
    });
  }
};
<commit_msg>Fix territory query<commit_after>// Packages
const ghgot = require('gh-got');
const moment = require('moment');

// Mine
const getResponse = query => {
  const token = require('../config.json').token || false;

  if (!token) {
    throw new Error(`token is not defined`);
  }

  return ghgot('https://api.github.com/graphql', {
    json: true,
    headers: { authorization: `bearer ${token}` },
    body: { query }
  });
};

exports.tools = {
  status: () => {
    return new Promise((resolve, reject) => {
      ghgot('https://status.github.com/api/last-message.json')
        .then(response => {
          let data = response.body;

          resolve({
            status: `${data.status} 🦄`,
            msg: data.body,
            date: moment(data.created_on).format('MMMM DD YYYY HH:mm')
          });
        })
        .catch(err => {
          reject(err);
        });
    });
  },
  radar: () => {
    return new Promise((resolve, reject) => {
      let query = `query {
        repository(owner: "github", name: "services") {
          issues(first: 1, labels: "O: radar", states: OPEN) {
            edges {
              node {
                url
              }
            }
          }
        }
      }`;

      getResponse(query)
        .then(response => {
          let url = response.body.data.repository.issues.edges[0].node.url;

          resolve(`${url}`);
        })
        .catch(err => {
          reject(err);
        });
    });
  },
  repo: repo => {
    return new Promise((resolve, reject) => {
      let query = `query {
        repository(owner: "github", name: "${repo}") {
          url
        }
      }`;

      getResponse(query)
        .then(response => {
          let url = response.body.data.repository.url;

          resolve(`${url}`);
        })
        .catch(err => {
          reject(err);
        });
    });
  },
  territory: territory => {
    return new Promise((resolve, reject) => {
      let query = `query {
        repository(owner: "github", name: "services") {
          url
          issues(states: OPEN, labels: "ST: ${territory}") {
            totalCount
          }
          projects(first: 1, search: "ST: ${territory}") {
            nodes {
              url
            }
          }
        }
      }`;

      getResponse(query)
        .then(response => {
          let repo = response.body.data.repository;

          resolve({
            url: repo.url
              ? `${repo.url}/issues?q=is:open is:issue label:"ST: ${territory}"`
              : null,
            count: Number.parseInt(repo.issues.totalCount),
            project: repo.projects.nodes[0].url
          });
        })
        .catch(err => {
          reject(err);
        });
    });
  },
  projects: (number = 2) => {
    return new Promise(function(resolve, reject) {
      let query = `query {
        repository(owner: "github", name: "services") {
          project(number: ${number}) {
            ... on Project {
              columns(first: 1) {
                nodes {
                  ... on ProjectColumn {
                    columnname: name
                  }
                  cards(first: 100) {
                    edges {
                      node {
                        content {
                          ... on Issue {
                            title
                            url
                          }
                          ... on PullRequest {
                            title
                            url
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }`;

      getResponse(query)
        .then(response => {
          resolve(response.body.data.repository.project);
        })
        .catch(err => {
          reject(err);
        });
    });
  }
};
<|endoftext|>


<commit_before>var assert = require('assert')

describe('App', function () {
  it('should contain a welcoming message', function () {
    // TODO
  })
})
<commit_msg>refactor(cycle-scripts-es-browserify): change test template<commit_after>var assert = require('assert')

describe('App', function () {
  it('should test something', function () {
    // TODO: Add your tests here
  })
})
<|endoftext|>


<commit_before>/**
 * Defines custom events for touch related gusters.
 * Following events are defined:
 * tap, dbltap, taphold, swipe, swipeleft, swiperight
 * @author anaik
 */
(function($) {
   var state = {}, timer;

   /**
    * Calculate the delta difference between two points (x1,y1) and (x2,y2)
    * @return A delta object {x: xdelta, y: ydelta} if the difference is more
    * than 30 pixels or null if its less. The values x and y can be -ve
    */
   function movement(x1, y1, x2, y2) {
      var dx = x1 - x2, dy = y1 - y2, xa, ya;
      if((xa = Math.abs(dx)) < 30 & (ya = Math.abs(dy)) < 30) {
         return null;
      }
      return {
         x: dx,
         y: dy,
         dir: xa >= ya ? (dx < 0 ? "left" : "right") : (dy < 0 ? "up" : "down")
      };
   }

   function ontouch(te) {
      var now, elapsed, touches = te.touches, cTouches = te.changedTouches, touch, target = te.target,
         type = te.type, distance, tar;

      // bail out if we have more than one touches
      if(touches.length > 1 || cTouches.length > 1) {
         state = {};
         return;
      }

      switch(type) {
         case "touchstart":
            touch = touches[0];
            now = Date.now();
            elapsed = now - (state.last || now);
            // check if this is a double tap
            if(elapsed > 0 && elapsed < 250 && state.target === target) {
               state.dbltap = true;
            }else {
               // this is a new tap so record some values in the current state
               state.last = now;
               state.x = touch.screenX;
               state.y = touch.screenY;
               state.target = target;
               // set up a timer for 'taphold' event. Will only fire if there was no movement
               timer = setTimeout(function() {
                  if(state.moved) {
                     return; //there was movement, so don't fire taphold
                  }
                  // fire taphold and record the fact in the current state
                  state.wastaphold = true;
                  $(target).dispatch("taphold");
               }, 750);
            }
            break;
         case "touchmove":
            if(!state.last) {
               return; // hmm, state seems to have been reset
            }
            touch = cTouches[0];
            state.distance = movement(touch.screenX, touch.screenY, state.x, state.y);
            if(state.distance) {
               state.moved = true;
            }
            break;
         case "touchend":
            clearTimeout(timer); // clear the timer or taphold will fire!
            touch = cTouches[0];
            if(state.wastaphold || !state.last) { // check if the taphold event was fired
               state.wastaphold = false;  //clear the state and we have nothing to do
               return;
            }

            // check for swipe events
            distance = state.distance;
            tar = $(target);
            if(distance) {
               tar.dispatch("swipe").dispatch("swipe" + distance.dir);
               state.x = state.y = state.distance = state.moved = null;
            }else {
               tar.dispatch("tap");  // here the dbltap is fired as -> 'tap', 'tap', 'doubletap'
               if(state.dbltap) {
                  state.last = state.dbltap = false;
                  if(state.target === target) {
                     tar.dispatch("dbltap");
                  }
               }
            }
            break;
         default:
            break;
      }
   }

   $.defineEvent({
      setup: function() {
         $(document).on("touchstart", ontouch)
            .on("touchmove", ontouch)
            .on("touchend", ontouch)
            .on("touchcancel", ontouch);
      },
      destroy: function() {
         $(document).un("touchstart", ontouch)
            .un("touchmove", ontouch)
            .un("touchend", ontouch)
            .un("touchcancel", ontouch);
      }
   });
})(h5);

<commit_msg>Renamed some methods and vars to meaningful names<commit_after>/**
 * Defines custom events for touch related gusters.
 * Following events are defined:
 * tap, dbltap, taphold, swipe, swipeleft, swiperight
 * @author anaik
 */
(function($) {
   var state = {}, timer;

   /**
    * Calculate the delta difference between two points (x1,y1) and (x2,y2)
    * @return A delta object {x: xdelta, y: ydelta} if the difference is more
    * than 30 pixels or null if its less. The values x and y can be -ve
    */
   function getMovement(x1, y1, x2, y2) {
      var dx = x1 - x2, dy = y1 - y2, xa, ya;
      if((xa = Math.abs(dx)) < 30 & (ya = Math.abs(dy)) < 30) {
         return null;
      }
      return {
         x: dx,
         y: dy,
         dir: xa >= ya ? (dx < 0 ? "left" : "right") : (dy < 0 ? "up" : "down")
      };
   }

   function ontouch(te) {
      var now, elapsed, touches = te.touches, cTouches = te.changedTouches, touch, target = te.target,
         type = te.type, movement, tar;

      // bail out if we have more than one touches
      if(touches.length > 1 || cTouches.length > 1) {
         state = {};
         return;
      }

      switch(type) {
         case "touchstart":
            touch = touches[0];
            now = Date.now();
            elapsed = now - (state.last || now);
            // check if this is a double tap
            if(elapsed > 0 && elapsed < 250 && state.target === target) {
               state.dbltap = true;
            }else {
               // this is a new tap so record some values in the current state
               state.last = now;
               state.x = touch.screenX;
               state.y = touch.screenY;
               state.target = target;
               // set up a timer for 'taphold' event. Will only fire if there was no movement
               timer = setTimeout(function() {
                  if(state.moved) {
                     return; //there was movement, so don't fire taphold
                  }
                  // fire taphold and record the fact in the current state
                  state.wastaphold = true;
                  $(target).dispatch("taphold");
               }, 750);
            }
            break;
         case "touchmove":
            if(!state.last) {
               return; // hmm, state seems to have been reset
            }
            touch = cTouches[0];
            state.movement = getMovement(touch.screenX, touch.screenY, state.x, state.y);
            if(state.movement) {
               state.moved = true;
            }
            break;
         case "touchend":
            clearTimeout(timer); // clear the timer or taphold will fire!
            touch = cTouches[0];
            if(state.wastaphold || !state.last) { // check if the taphold event was fired
               state.wastaphold = false;  //clear the state and we have nothing to do
               return;
            }

            // check for swipe events
            movement = state.movement;
            tar = $(target);
            if(movement) {
               tar.dispatch("swipe").dispatch("swipe" + movement.dir);
               state.x = state.y = state.movement = state.moved = null;
            }else {
               tar.dispatch("tap");  // here the dbltap is fired as -> 'tap', 'tap', 'doubletap'
               if(state.dbltap) {
                  state.last = state.dbltap = false;
                  if(state.target === target) {
                     tar.dispatch("dbltap");
                  }
               }
            }
            break;
         default:
            break;
      }
   }

   $.defineEvent({
      setup: function() {
         $(document).on("touchstart", ontouch)
            .on("touchmove", ontouch)
            .on("touchend", ontouch)
            .on("touchcancel", ontouch);
      },
      destroy: function() {
         $(document).un("touchstart", ontouch)
            .un("touchmove", ontouch)
            .un("touchend", ontouch)
            .un("touchcancel", ontouch);
      }
   });
})(h5);

<|endoftext|>


<commit_before>'use strict';

const bulk = require('bulk-require');
const lib = bulk(__dirname, 'types/**/*.js');

module.exports = {
    getType(type, kind, custom) {
        if(kind) {
            if(lib.types[kind][type]) {
                return Object.assign({}, lib.types.default, lib.types[kind].default, lib.types[kind][type], custom);
            }
        } else {
            for(var kind in lib.types) {
                if(lib.types[kind][type]) {
                    return Object.assign({}, lib.types.default, lib.types[kind].default, lib.types[kind][type], custom);
                }
            }
        }

        return Object.assign({}, lib.types.default);
    },

    getAllTypes(kind, custom) {
        var all = [];

        for(var type in lib.types[kind]) {
            if(type !== 'default') {
                all.push(module.exports.getType(type, kind, custom));
            }
        }
        return all;
    }
};<commit_msg>add getUtil function to types<commit_after>'use strict';

const bulk = require('bulk-require');
const lib = bulk(__dirname, 'types/**/*.js');

module.exports = {
    getType(type, kind, custom) {
        if(kind) {
            if(lib.types[kind][type]) {
                return Object.assign({}, lib.types.default, lib.types[kind].default, lib.types[kind][type], custom);
            }
        } else {
            for(var kind in lib.types) {
                if(lib.types[kind][type]) {
                    return Object.assign({}, lib.types.default, lib.types[kind].default, lib.types[kind][type], custom);
                }
            }
        }

        return Object.assign({}, lib.types.default);
    },

    getAllTypes(kind, custom) {
        var all = [];

        for(var type in lib.types[kind]) {
            if(type !== 'default') {
                all.push(module.exports.getType(type, kind, custom));
            }
        }
        return all;
    }

    getUtil(kind) {
        var kind =  lib.types[kind];
        if (kind) {
            return kind.util;
        }
        return undefined;
    }
};
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';

/**
 * @function Input
 * @description An input in a field.
 */
const Input = (props) => {
  const handleChange = (e) => props.onChange(e.target.value);

  return (

      {props.type === 'textarea' ? (
        <textarea
          {...props}
          role="textbox"
          className="input"
          onChange={handleChange}
        />
      ) : (

          <input
            {...props}
            className="input"
            onChange={handleChange}
          />
          {props.renderInner ? props.renderInner() : null}

      )}
      {props.type === 'textbox' ? (
        {props.checkboxText}
      ) : null}
      {props.error ? (

          {props.error}

      ) : null}

  );
}

Input.propTypes = {
  onChange: PropTypes.func.isRequired
};

export default Input;
<commit_msg>Fix build error<commit_after>import React, { Component, PropTypes } from 'react';

/**
 * @function Input
 * @description An input in a field.
 */
const Input = (props) => {
  const handleChange = (e) => props.onChange(e.target.value);

  return (

      {props.type === 'textarea' ? (
        <textarea
          {...props}
          role="textbox"
          className="input"
          onChange={handleChange}
        />
      ) : (

          <input
            {...props}
            className="input"
            onChange={handleChange}
          />
          {props.renderInner ? props.renderInner() : null}

      )}
      {props.type === 'textbox' ? (
        {props.checkboxText}
      ) : null}
      {props.error ? (

          {props.error}

      ) : null}

  );
}

Input.propTypes = {
  onChange: PropTypes.func.isRequired
};

export default Input;
<|endoftext|>


<commit_before>/* global VolumeDetails, MashupPlatform, JSTACK  */

var UI = (function () {
	'use strict';

	/*****************************************************************
    *                        C O N S T A N T S                       *
    *****************************************************************/

	var NONUSABLEWIDTH = 158;

	// Colors
	var RED = 'rgb(217, 83, 79)';
	var GREEN = 'green';
	var AMBAR = 'rgb(239, 163, 0)';
	var GRAY = 'gray';

	var STATES = {

		// GREEN
		'available': {
			'class': 'glyphicon glyphicon-ok  fa-inverse',
			'color': GREEN
		},
		'in-use': {
			'class': 'fa fa-link fa-inverse',
			'color': GREEN
		},
		'attaching': {
			'class': 'fa fa-repeat fa-spin  fa-inverse',
			'color': GREEN
		},

		// AMBAR
		'creating': {
			'class': 'fa fa-spinner fa-pulse  fa-inverse',
			'color': AMBAR
		},
		'detaching': {
			'class': 'fa fa-repeat fa-spin  fa-inverse',
			'color': AMBAR
		},

		// RED
		'error': {
			'class': 'fa fa-trash  fa-inverse',
			'color': RED
		},
		'deleting': {
			'class': 'fa fa-trash fa-inverse',
			'color': RED,
			'animation': 'working-animation'
		},
		'error_deleting': {
			'class': 'fa fa-arrows-alt  fa-inverse',
			'color': RED
		}
	};

	/*****************************************************************
    *                          P R I V A T E                         *
    *****************************************************************/

	function setNameMaxWidth (nonUsableWidth) {

		var bodyWidth = $('body').attr('width') > 360 ? $('body').attr('width') : 360;

		$('#volume-name').css('max-width', bodyWidth - nonUsableWidth);

	}

	function showView (viewId) {

		// Hide all views
		$('#error-view').addClass('hide');
		$('#default-view').addClass('hide');
		$('#detail-view').addClass('hide');
		$('body').removeClass('stripes angled-135');

		if (viewId === 'default-view' || viewId === 'error-view') {
			$('body').addClass('stripes angled-135');
		}

		$('#' + viewId).removeClass('hide');

	}

	/*****************************************************************
    *                          P U B L I C                           *
    *****************************************************************/

    function init (callbacks) {

		// Register resize callback
		MashupPlatform.widget.context.registerCallback(function (newValues) {
			if ('heightInPixels' in newValues || 'widthInPixels' in newValues) {

				// Set body size
				$('body').attr('height', newValues.heightInPixels);
				$('body').attr('width', newValues.widthInPixels);

				// Set name max-width
				setNameMaxWidth(NONUSABLEWIDTH);

			}
		});

		// Init click events
		$('#refresh-button').click(function () {
			callbacks.refresh();
		});

		$('#attach-volume').click(function () {
			var instanceId = $('#id_instance').val();
			var device = $('#id_device').val();
			callbacks.attach(instanceId, device);
		});

		$('#volume-terminate').click(function () {
			callbacks.delete();
		});

	}

	function buildDetailView (instanceById, detach, volumeData) {

		var statusTooltip = 'Status: ' + volumeData.status;
		var displayableSize = volumeData.size + ' GB';
		var attachment, instanceId;

		// Remove previous attachments
		$('#volume-attachment span').empty().removeClass();

		// Fields
		$('#volume-name').text(volumeData.display_name);
		$('#volume-name').attr('title', volumeData.display_name);
		$('#volume-id > span').text(volumeData.id);
		$('#volume-availability-zone > span').text(volumeData.availability_zone);
		$('#volume-size > span').text(displayableSize);
		$('#volume-created > span').text(volumeData.created_at);
		$('#volume-description > span').text(volumeData.display_description);

		// Status
		$('#volume-status').removeClass('working-animation');
		$('#volume-status > div > i').removeClass();

		$('#volume-status > div > i').addClass(STATES[volumeData.status].class);
		$('#volume-status').css('background-color', STATES[volumeData.status].color);

		if (volumeData.status === 'deleting') {
			$('#volume-status > div > i').addClass(STATES.deleting.class);
			$('#volume-status').css('background-color', STATES.deleting.color);
			$('#volume-status').addClass(STATES.deleting.animation);
		}
		else {
			$('#volume-status > div > i').addClass(STATES[volumeData.status].class);
			$('#volume-status').css('background-color', STATES[volumeData.status].color);
		}

		if (volumeData.status !== 'available') {
			$('#attach-button')
				.addClass('disabled')
				.attr('data-toggle', '');
		}
		else {
			$('#attach-button')
				.removeClass('disabled')
				.attr('data-toggle', 'modal');
		}

		// Set name max-width
		setNameMaxWidth(NONUSABLEWIDTH);

		if (volumeData.attachments.length > 0) {

			instanceId = volumeData.attachments[0].server_id;
			attachment = instanceById[instanceId] ? instanceById[instanceId] : '';

			$('#volume-attachment span')
				.attr('id', instanceId)
				.addClass('list-group-item')
				.html(attachment);

			// Detach button
			$('<button>')
				.html('')
				.addClass('btn btn-warning pull-right')
				.attr('id', 'detach-button')
				.attr('data-toggle', 'tooltip')
				.attr('data-placement', 'bottom')
				.appendTo('#volume-attachment span');

			// Fix tooltip
			$('#detach-button').attr('data-original-title', 'Detach Volume');

			// Detach click event
			$('#detach-button').click(function () {

				var instanceId = $('#detach-button').parent().attr('id');
				detach(instanceId);
			}.bind(this));
		}
		else {
			$('#volume-attachment span').text('None');
		}

		// Fix tooltips
		$('#volume-status').attr('title', statusTooltip);
		$('#volume-status').attr('data-original-title', $('#volume-status').attr('title'));
		$('#volume-status').attr('title', '');

		$('#volume-name').attr('data-original-title', $('#volume-name').attr('title'));
		$('#volume-name').attr('title', '');

		// Initialize tooltips
		$('[data-toggle="tooltip"]').tooltip();

		showView('detail-view');
	}

	function buildDefaultView () {

		showView('default-view');

	}

	function buildErrorView (errorResponse) {

		// Build
		if (errorResponse.message) {
			$('#error-view').text(errorResponse.message);
		}
		else {
			$('#error-view').text(errorResponse);
		}

		showView('error-view');
	}

	return {
		buildDetailView: buildDetailView,
		buildDefaultView: buildDefaultView,
		buildErrorView: buildErrorView,
		init:init
	};

})();<commit_msg>Call buildDefaultBuild in UI.init<commit_after>/* global VolumeDetails, MashupPlatform, JSTACK  */

var UI = (function () {
	'use strict';

	/*****************************************************************
    *                        C O N S T A N T S                       *
    *****************************************************************/

	var NONUSABLEWIDTH = 158;

	// Colors
	var RED = 'rgb(217, 83, 79)';
	var GREEN = 'green';
	var AMBAR = 'rgb(239, 163, 0)';
	var GRAY = 'gray';

	var STATES = {

		// GREEN
		'available': {
			'class': 'glyphicon glyphicon-ok  fa-inverse',
			'color': GREEN
		},
		'in-use': {
			'class': 'fa fa-link fa-inverse',
			'color': GREEN
		},
		'attaching': {
			'class': 'fa fa-repeat fa-spin  fa-inverse',
			'color': GREEN
		},

		// AMBAR
		'creating': {
			'class': 'fa fa-spinner fa-pulse  fa-inverse',
			'color': AMBAR
		},
		'detaching': {
			'class': 'fa fa-repeat fa-spin  fa-inverse',
			'color': AMBAR
		},

		// RED
		'error': {
			'class': 'fa fa-trash  fa-inverse',
			'color': RED
		},
		'deleting': {
			'class': 'fa fa-trash fa-inverse',
			'color': RED,
			'animation': 'working-animation'
		},
		'error_deleting': {
			'class': 'fa fa-arrows-alt  fa-inverse',
			'color': RED
		}
	};

	/*****************************************************************
    *                          P R I V A T E                         *
    *****************************************************************/

	function setNameMaxWidth (nonUsableWidth) {

		var bodyWidth = $('body').attr('width') > 360 ? $('body').attr('width') : 360;

		$('#volume-name').css('max-width', bodyWidth - nonUsableWidth);

	}

	function showView (viewId) {

		// Hide all views
		$('#error-view').addClass('hide');
		$('#default-view').addClass('hide');
		$('#detail-view').addClass('hide');
		$('body').removeClass('stripes angled-135');

		if (viewId === 'default-view' || viewId === 'error-view') {
			$('body').addClass('stripes angled-135');
		}

		$('#' + viewId).removeClass('hide');

	}

	/*****************************************************************
    *                          P U B L I C                           *
    *****************************************************************/

    function init (callbacks) {

		// Register resize callback
		MashupPlatform.widget.context.registerCallback(function (newValues) {
			if ('heightInPixels' in newValues || 'widthInPixels' in newValues) {

				// Set body size
				$('body').attr('height', newValues.heightInPixels);
				$('body').attr('width', newValues.widthInPixels);

				// Set name max-width
				setNameMaxWidth(NONUSABLEWIDTH);

			}
		});

		// Init click events
		$('#refresh-button').click(function () {
			callbacks.refresh();
		});

		$('#attach-volume').click(function () {
			var instanceId = $('#id_instance').val();
			var device = $('#id_device').val();
			callbacks.attach(instanceId, device);
		});

		$('#volume-terminate').click(function () {
			callbacks.delete();
		});

		UI.buildDefaultView();

	}

	function buildDetailView (instanceById, detach, volumeData) {

		var statusTooltip = 'Status: ' + volumeData.status;
		var displayableSize = volumeData.size + ' GB';
		var attachment, instanceId;

		// Remove previous attachments
		$('#volume-attachment span').empty().removeClass();

		// Fields
		$('#volume-name').text(volumeData.display_name);
		$('#volume-name').attr('title', volumeData.display_name);
		$('#volume-id > span').text(volumeData.id);
		$('#volume-availability-zone > span').text(volumeData.availability_zone);
		$('#volume-size > span').text(displayableSize);
		$('#volume-created > span').text(volumeData.created_at);
		$('#volume-description > span').text(volumeData.display_description);

		// Status
		$('#volume-status').removeClass('working-animation');
		$('#volume-status > div > i').removeClass();

		$('#volume-status > div > i').addClass(STATES[volumeData.status].class);
		$('#volume-status').css('background-color', STATES[volumeData.status].color);

		if (volumeData.status === 'deleting') {
			$('#volume-status > div > i').addClass(STATES.deleting.class);
			$('#volume-status').css('background-color', STATES.deleting.color);
			$('#volume-status').addClass(STATES.deleting.animation);
		}
		else {
			$('#volume-status > div > i').addClass(STATES[volumeData.status].class);
			$('#volume-status').css('background-color', STATES[volumeData.status].color);
		}

		if (volumeData.status !== 'available') {
			$('#attach-button')
				.addClass('disabled')
				.attr('data-toggle', '');
		}
		else {
			$('#attach-button')
				.removeClass('disabled')
				.attr('data-toggle', 'modal');
		}

		// Set name max-width
		setNameMaxWidth(NONUSABLEWIDTH);

		if (volumeData.attachments.length > 0) {

			instanceId = volumeData.attachments[0].server_id;
			attachment = instanceById[instanceId] ? instanceById[instanceId] : '';

			$('#volume-attachment span')
				.attr('id', instanceId)
				.addClass('list-group-item')
				.html(attachment);

			// Detach button
			$('<button>')
				.html('')
				.addClass('btn btn-warning pull-right')
				.attr('id', 'detach-button')
				.attr('data-toggle', 'tooltip')
				.attr('data-placement', 'bottom')
				.appendTo('#volume-attachment span');

			// Fix tooltip
			$('#detach-button').attr('data-original-title', 'Detach Volume');

			// Detach click event
			$('#detach-button').click(function () {

				var instanceId = $('#detach-button').parent().attr('id');
				detach(instanceId);
			}.bind(this));
		}
		else {
			$('#volume-attachment span').text('None');
		}

		// Fix tooltips
		$('#volume-status').attr('title', statusTooltip);
		$('#volume-status').attr('data-original-title', $('#volume-status').attr('title'));
		$('#volume-status').attr('title', '');

		$('#volume-name').attr('data-original-title', $('#volume-name').attr('title'));
		$('#volume-name').attr('title', '');

		// Initialize tooltips
		$('[data-toggle="tooltip"]').tooltip();

		showView('detail-view');
	}

	function buildDefaultView () {

		showView('default-view');

	}

	function buildErrorView (errorResponse) {

		// Build
		if (errorResponse.message) {
			$('#error-view').text(errorResponse.message);
		}
		else {
			$('#error-view').text(errorResponse);
		}

		showView('error-view');
	}

	return {
		buildDetailView: buildDetailView,
		buildDefaultView: buildDefaultView,
		buildErrorView: buildErrorView,
		init:init
	};

})();<|endoftext|>


<commit_before>// ==========================================================================
// Plyr UI
// ==========================================================================

import captions from './captions';
import controls from './controls';
import i18n from './i18n';
import support from './support';
import utils from './utils';

// Sniff out the browser
const browser = utils.getBrowser();

const ui = {
    addStyleHook() {
        utils.toggleClass(this.elements.container, this.config.selectors.container.replace('.', ''), true);
        utils.toggleClass(this.elements.container, this.config.classNames.uiSupported, this.supported.ui);
    },

    // Toggle native HTML5 media controls
    toggleNativeControls(toggle = false) {
        if (toggle && this.isHTML5) {
            this.media.setAttribute('controls', '');
        } else {
            this.media.removeAttribute('controls');
        }
    },

    // Setup the UI
    build() {
        // Re-attach media element listeners
        // TODO: Use event bubbling?
        this.listeners.media();

        // Don't setup interface if no support
        if (!this.supported.ui) {
            this.debug.warn(`Basic support only for ${this.provider} ${this.type}`);

            // Restore native controls
            ui.toggleNativeControls.call(this, true);

            // Bail
            return;
        }

        // Inject custom controls if not present
        if (!utils.is.element(this.elements.controls)) {
            // Inject custom controls
            controls.inject.call(this);

            // Re-attach control listeners
            this.listeners.controls();
        }

        // Remove native controls
        ui.toggleNativeControls.call(this);

        // Setup captions for html5
        if (this.isHTML5) {
            captions.setup.call(this);
        }

        // Reset volume
        this.volume = null;

        // Reset mute state
        this.muted = null;

        // Reset speed
        this.speed = null;

        // Reset loop state
        this.loop = null;

        // Reset quality setting
        this.quality = null;

        // Reset volume display
        controls.updateVolume.call(this);

        // Reset time display
        controls.timeUpdate.call(this);

        // Update the UI
        ui.checkPlaying.call(this);

        // Check for picture-in-picture support
        utils.toggleClass(this.elements.container, this.config.classNames.pip.supported, support.pip && this.isHTML5 && this.isVideo);

        // Check for airplay support
        utils.toggleClass(this.elements.container, this.config.classNames.airplay.supported, support.airplay && this.isHTML5);

        // Add iOS class
        utils.toggleClass(this.elements.container, this.config.classNames.isIos, browser.isIos);

        // Add touch class
        utils.toggleClass(this.elements.container, this.config.classNames.isTouch, this.touch);

        // Ready for API calls
        this.ready = true;

        // Ready event at end of execution stack
        setTimeout(() => {
            utils.dispatchEvent.call(this, this.media, 'ready');
        }, 0);

        // Set the title
        ui.setTitle.call(this);

        // Assure the poster image is set, if the property was added before the element was created
        if (this.poster && this.elements.poster && !this.elements.poster.style.backgroundImage) {
            ui.setPoster.call(this, this.poster);
        }
    },

    // Setup aria attribute for play and iframe title
    setTitle() {
        // Find the current text
        let label = i18n.get('play', this.config);

        // If there's a media title set, use that for the label
        if (utils.is.string(this.config.title) && !utils.is.empty(this.config.title)) {
            label += `, ${this.config.title}`;

            // Set container label
            this.elements.container.setAttribute('aria-label', this.config.title);
        }

        // If there's a play button, set label
        if (utils.is.nodeList(this.elements.buttons.play)) {
            Array.from(this.elements.buttons.play).forEach(button => {
                button.setAttribute('aria-label', label);
            });
        }

        // Set iframe title
        // https://github.com/sampotts/plyr/issues/124
        if (this.isEmbed) {
            const iframe = utils.getElement.call(this, 'iframe');

            if (!utils.is.element(iframe)) {
                return;
            }

            // Default to media type
            const title = !utils.is.empty(this.config.title) ? this.config.title : 'video';
            const format = i18n.get('frameTitle', this.config);

            iframe.setAttribute('title', format.replace('{title}', title));
        }
    },

    // Toggle poster
    togglePoster(enable) {
        utils.toggleClass(this.elements.container, this.config.classNames.posterEnabled, enable);
    },

    // Set the poster image (async)
    setPoster(poster) {
        // Set property regardless of validity
        this.media.setAttribute('poster', poster);

        // Bail if element is missing
        if (!utils.is.element(this.elements.poster)) {
            return Promise.reject();
        }

        // Load the image, and set poster if successful
        const loadPromise = utils.loadImage(poster)
            .then(() => {
                this.elements.poster.style.backgroundImage = `url('${poster}')`;
                Object.assign(this.elements.poster.style, {
                    backgroundImage: `url('${poster}')`,
                    // Reset backgroundSize as well (since it can be set to "cover" for padded thumbnails for youtube)
                    backgroundSize: '',
                });
                ui.togglePoster.call(this, true);
                return poster;
            });

        // Hide the element if the poster can't be loaded (otherwise it will just be a black element covering the video)
        loadPromise.catch(() => ui.togglePoster.call(this, false));

        // Return the promise so the caller can use it as well
        return loadPromise;
    },

    // Check playing state
    checkPlaying(event) {
        // Class hooks
        utils.toggleClass(this.elements.container, this.config.classNames.playing, this.playing);
        utils.toggleClass(this.elements.container, this.config.classNames.paused, this.paused);
        utils.toggleClass(this.elements.container, this.config.classNames.stopped, this.stopped);

        // Set ARIA state
        utils.toggleState(this.elements.buttons.play, this.playing);

        // Only update controls on non timeupdate events
        if (utils.is.event(event) && event.type === 'timeupdate') {
            return;
        }

        // Toggle controls
        ui.toggleControls.call(this);
    },

    // Check if media is loading
    checkLoading(event) {
        this.loading = [
            'stalled',
            'waiting',
        ].includes(event.type);

        // Clear timer
        clearTimeout(this.timers.loading);

        // Timer to prevent flicker when seeking
        this.timers.loading = setTimeout(() => {
            // Update progress bar loading class state
            utils.toggleClass(this.elements.container, this.config.classNames.loading, this.loading);

            // Update controls visibility
            ui.toggleControls.call(this);
        }, this.loading ? 250 : 0);
    },

    // Toggle controls based on state and `force` argument
    toggleControls(force) {
        const { controls } = this.elements;

        if (controls && this.config.hideControls) {
            // Show controls if force, loading, paused, or button interaction, otherwise hide
            this.toggleControls(Boolean(force || this.loading || this.paused || controls.pressed || controls.hover));
        }
    },
};

export default ui;
<commit_msg>Fix typo<commit_after>// ==========================================================================
// Plyr UI
// ==========================================================================

import captions from './captions';
import controls from './controls';
import i18n from './i18n';
import support from './support';
import utils from './utils';

// Sniff out the browser
const browser = utils.getBrowser();

const ui = {
    addStyleHook() {
        utils.toggleClass(this.elements.container, this.config.selectors.container.replace('.', ''), true);
        utils.toggleClass(this.elements.container, this.config.classNames.uiSupported, this.supported.ui);
    },

    // Toggle native HTML5 media controls
    toggleNativeControls(toggle = false) {
        if (toggle && this.isHTML5) {
            this.media.setAttribute('controls', '');
        } else {
            this.media.removeAttribute('controls');
        }
    },

    // Setup the UI
    build() {
        // Re-attach media element listeners
        // TODO: Use event bubbling?
        this.listeners.media();

        // Don't setup interface if no support
        if (!this.supported.ui) {
            this.debug.warn(`Basic support only for ${this.provider} ${this.type}`);

            // Restore native controls
            ui.toggleNativeControls.call(this, true);

            // Bail
            return;
        }

        // Inject custom controls if not present
        if (!utils.is.element(this.elements.controls)) {
            // Inject custom controls
            controls.inject.call(this);

            // Re-attach control listeners
            this.listeners.controls();
        }

        // Remove native controls
        ui.toggleNativeControls.call(this);

        // Setup captions for HTML5
        if (this.isHTML5) {
            captions.setup.call(this);
        }

        // Reset volume
        this.volume = null;

        // Reset mute state
        this.muted = null;

        // Reset speed
        this.speed = null;

        // Reset loop state
        this.loop = null;

        // Reset quality setting
        this.quality = null;

        // Reset volume display
        controls.updateVolume.call(this);

        // Reset time display
        controls.timeUpdate.call(this);

        // Update the UI
        ui.checkPlaying.call(this);

        // Check for picture-in-picture support
        utils.toggleClass(this.elements.container, this.config.classNames.pip.supported, support.pip && this.isHTML5 && this.isVideo);

        // Check for airplay support
        utils.toggleClass(this.elements.container, this.config.classNames.airplay.supported, support.airplay && this.isHTML5);

        // Add iOS class
        utils.toggleClass(this.elements.container, this.config.classNames.isIos, browser.isIos);

        // Add touch class
        utils.toggleClass(this.elements.container, this.config.classNames.isTouch, this.touch);

        // Ready for API calls
        this.ready = true;

        // Ready event at end of execution stack
        setTimeout(() => {
            utils.dispatchEvent.call(this, this.media, 'ready');
        }, 0);

        // Set the title
        ui.setTitle.call(this);

        // Assure the poster image is set, if the property was added before the element was created
        if (this.poster && this.elements.poster && !this.elements.poster.style.backgroundImage) {
            ui.setPoster.call(this, this.poster);
        }
    },

    // Setup aria attribute for play and iframe title
    setTitle() {
        // Find the current text
        let label = i18n.get('play', this.config);

        // If there's a media title set, use that for the label
        if (utils.is.string(this.config.title) && !utils.is.empty(this.config.title)) {
            label += `, ${this.config.title}`;

            // Set container label
            this.elements.container.setAttribute('aria-label', this.config.title);
        }

        // If there's a play button, set label
        if (utils.is.nodeList(this.elements.buttons.play)) {
            Array.from(this.elements.buttons.play).forEach(button => {
                button.setAttribute('aria-label', label);
            });
        }

        // Set iframe title
        // https://github.com/sampotts/plyr/issues/124
        if (this.isEmbed) {
            const iframe = utils.getElement.call(this, 'iframe');

            if (!utils.is.element(iframe)) {
                return;
            }

            // Default to media type
            const title = !utils.is.empty(this.config.title) ? this.config.title : 'video';
            const format = i18n.get('frameTitle', this.config);

            iframe.setAttribute('title', format.replace('{title}', title));
        }
    },

    // Toggle poster
    togglePoster(enable) {
        utils.toggleClass(this.elements.container, this.config.classNames.posterEnabled, enable);
    },

    // Set the poster image (async)
    setPoster(poster) {
        // Set property regardless of validity
        this.media.setAttribute('poster', poster);

        // Bail if element is missing
        if (!utils.is.element(this.elements.poster)) {
            return Promise.reject();
        }

        // Load the image, and set poster if successful
        const loadPromise = utils.loadImage(poster)
            .then(() => {
                this.elements.poster.style.backgroundImage = `url('${poster}')`;
                Object.assign(this.elements.poster.style, {
                    backgroundImage: `url('${poster}')`,
                    // Reset backgroundSize as well (since it can be set to "cover" for padded thumbnails for youtube)
                    backgroundSize: '',
                });
                ui.togglePoster.call(this, true);
                return poster;
            });

        // Hide the element if the poster can't be loaded (otherwise it will just be a black element covering the video)
        loadPromise.catch(() => ui.togglePoster.call(this, false));

        // Return the promise so the caller can use it as well
        return loadPromise;
    },

    // Check playing state
    checkPlaying(event) {
        // Class hooks
        utils.toggleClass(this.elements.container, this.config.classNames.playing, this.playing);
        utils.toggleClass(this.elements.container, this.config.classNames.paused, this.paused);
        utils.toggleClass(this.elements.container, this.config.classNames.stopped, this.stopped);

        // Set ARIA state
        utils.toggleState(this.elements.buttons.play, this.playing);

        // Only update controls on non timeupdate events
        if (utils.is.event(event) && event.type === 'timeupdate') {
            return;
        }

        // Toggle controls
        ui.toggleControls.call(this);
    },

    // Check if media is loading
    checkLoading(event) {
        this.loading = [
            'stalled',
            'waiting',
        ].includes(event.type);

        // Clear timer
        clearTimeout(this.timers.loading);

        // Timer to prevent flicker when seeking
        this.timers.loading = setTimeout(() => {
            // Update progress bar loading class state
            utils.toggleClass(this.elements.container, this.config.classNames.loading, this.loading);

            // Update controls visibility
            ui.toggleControls.call(this);
        }, this.loading ? 250 : 0);
    },

    // Toggle controls based on state and `force` argument
    toggleControls(force) {
        const { controls } = this.elements;

        if (controls && this.config.hideControls) {
            // Show controls if force, loading, paused, or button interaction, otherwise hide
            this.toggleControls(Boolean(force || this.loading || this.paused || controls.pressed || controls.hover));
        }
    },
};

export default ui;
<|endoftext|>


<commit_before>dc.dateFormat = d3.time.format("%m/%d/%Y");

dc.printers = {};

dc.printers.filters = function (filters) {
    var s = "";

    for (var i = 0; i < filters.length; ++i) {
        if (i > 0) s += ", ";
        s += dc.printers.filter(filters[i]);
    }

    return s;
};

dc.printers.filter = function (filter) {
    var s = "";

    if (filter) {
        if (filter instanceof Array) {
            if (filter.length >= 2)
                s = "[" + dc.utils.printSingleValue(filter[0]) + " -> " + dc.utils.printSingleValue(filter[1]) + "]";
            else if (filter.length >= 1)
                s = dc.utils.printSingleValue(filter[0]);
        } else {
            s = dc.utils.printSingleValue(filter);
        }
    }

    return s;
};

dc.utils = {};

dc.utils.printSingleValue = function (filter) {
    var s = "" + filter;

    if (filter instanceof Date)
        s = dc.dateFormat(filter);
    else if (typeof(filter) == "string")
        s = filter;
    else if (dc.utils.isFloat(filter))
        s = dc.utils.printSingleValue.fformat(filter);
    else if (dc.utils.isInteger(filter))
        s = Math.round(filter);

    return s;
};
dc.utils.printSingleValue.fformat = d3.format(".2f");

dc.utils.add = function (l, r) {
    if (typeof r === "string")
        r = r.replace("%", "");

    if (l instanceof Date) {
        if (typeof r === "string") r = +r;
        var d = new Date();
        d.setTime(l.getTime());
        d.setDate(l.getDate() + r);
        return d;
    } else if (typeof r === "string") {
        var percentage = (+r / 100);
        return l > 0 ? l * (1 + percentage) : l * (1 - percentage);
    } else {
        return l + r;
    }
};

dc.utils.subtract = function (l, r) {
    if (typeof r === "string")
        r = r.replace("%", "");

    if (l instanceof Date) {
        if (typeof r === "string") r = +r;
        var d = new Date();
        d.setTime(l.getTime());
        d.setDate(l.getDate() - r);
        return d;
    } else if (typeof r === "string") {
        var percentage = (+r / 100);
        return l < 0 ? l * (1 + percentage) : l * (1 - percentage);
    } else {
        return l - r;
    }
};

dc.utils.GroupStack = function () {
    var _dataLayers = [];
    var _groups = [];
    var _defaultAccessor;

    function initializeDataLayer(i) {
        if (!_dataLayers[i])
            _dataLayers[i] = [];
    }

    this.setDataPoint = function (layerIndex, pointIndex, data) {
        initializeDataLayer(layerIndex);
        _dataLayers[layerIndex][pointIndex] = data;
    };

    this.getDataPoint = function (x, y) {
        initializeDataLayer(x);
        var dataPoint = _dataLayers[x][y];
        if (dataPoint === undefined)
            dataPoint = 0;
        return dataPoint;
    };

    this.addGroup = function (group, accessor) {
        if (!accessor)
            accessor = _defaultAccessor;
        _groups.push([group, accessor]);
        return _groups.length - 1;
    };

    this.getGroupByIndex = function (index) {
        return _groups[index][0];
    };

    this.getAccessorByIndex = function (index) {
        return _groups[index][1];
    };

    this.size = function () {
        return _groups.length;
    };

    this.clear = function () {
        _dataLayers = [];
        _groups = [];
    };

    this.setDefaultAccessor = function (retriever) {
        _defaultAccessor = retriever;
    };

    this.getDataLayers = function () {
        return _dataLayers;
    };

    this.toLayers = function () {
        var layers = [];

        for (var i = 0; i < _dataLayers.length; ++i) {
            var layer = {index: i, points: []};
            var dataPoints = _dataLayers[i];

            for (var j = 0; j < dataPoints.length; ++j)
                layer.points.push(dataPoints[j]);

            layers.push(layer);
        }

        return layers;
    };
};

dc.utils.isFloat = function (n) {
    return n===+n && n!==(n|0);
};

dc.utils.isInteger = function (n) {
    return n===+n && n===(n|0);
};

dc.utils.isNegligible = function (max) {
    return max === undefined || (max < dc.constants.NEGLIGIBLE_NUMBER && max > -dc.constants.NEGLIGIBLE_NUMBER);
};

dc.utils.groupMax = function (group, accessor) {
    var max = d3.max(group.all(), function (e) {
        return accessor(e);
    });
    if (dc.utils.isNegligible(max)) max = 0;
    return max;
};

dc.utils.groupMin = function (group, accessor) {
    var min = d3.min(group.all(), function (e) {
        return accessor(e);
    });
    if (dc.utils.isNegligible(min)) min = 0;
    return min;
};

dc.utils.nameToId = function (name) {
    return name.toLowerCase().replace(/[\s]/g, "_").replace(/[\.']/g, "");
};

dc.utils.appendOrSelect = function (parent, name) {
    var element = parent.select(name);
    if (element.empty()) element = parent.append(name);
    return element;
};

dc.utils.createLegendable = function (chart, group, index, accessor) {
    var legendable = {name: chart.getGroupName(group, accessor), data: group};
    if (typeof chart.colors === 'function') legendable.color = chart.colors()(index);
    return legendable;
};

dc.utils.safeNumber = function(n){return isNaN(n)?0:n;};
<commit_msg>add dc.utils.isNumber<commit_after>dc.dateFormat = d3.time.format("%m/%d/%Y");

dc.printers = {};

dc.printers.filters = function (filters) {
    var s = "";

    for (var i = 0; i < filters.length; ++i) {
        if (i > 0) s += ", ";
        s += dc.printers.filter(filters[i]);
    }

    return s;
};

dc.printers.filter = function (filter) {
    var s = "";

    if (filter) {
        if (filter instanceof Array) {
            if (filter.length >= 2)
                s = "[" + dc.utils.printSingleValue(filter[0]) + " -> " + dc.utils.printSingleValue(filter[1]) + "]";
            else if (filter.length >= 1)
                s = dc.utils.printSingleValue(filter[0]);
        } else {
            s = dc.utils.printSingleValue(filter);
        }
    }

    return s;
};

dc.utils = {};

dc.utils.printSingleValue = function (filter) {
    var s = "" + filter;

    if (filter instanceof Date)
        s = dc.dateFormat(filter);
    else if (typeof(filter) == "string")
        s = filter;
    else if (dc.utils.isFloat(filter))
        s = dc.utils.printSingleValue.fformat(filter);
    else if (dc.utils.isInteger(filter))
        s = Math.round(filter);

    return s;
};
dc.utils.printSingleValue.fformat = d3.format(".2f");

dc.utils.add = function (l, r) {
    if (typeof r === "string")
        r = r.replace("%", "");

    if (l instanceof Date) {
        if (typeof r === "string") r = +r;
        var d = new Date();
        d.setTime(l.getTime());
        d.setDate(l.getDate() + r);
        return d;
    } else if (typeof r === "string") {
        var percentage = (+r / 100);
        return l > 0 ? l * (1 + percentage) : l * (1 - percentage);
    } else {
        return l + r;
    }
};

dc.utils.subtract = function (l, r) {
    if (typeof r === "string")
        r = r.replace("%", "");

    if (l instanceof Date) {
        if (typeof r === "string") r = +r;
        var d = new Date();
        d.setTime(l.getTime());
        d.setDate(l.getDate() - r);
        return d;
    } else if (typeof r === "string") {
        var percentage = (+r / 100);
        return l < 0 ? l * (1 + percentage) : l * (1 - percentage);
    } else {
        return l - r;
    }
};

dc.utils.GroupStack = function () {
    var _dataLayers = [];
    var _groups = [];
    var _defaultAccessor;

    function initializeDataLayer(i) {
        if (!_dataLayers[i])
            _dataLayers[i] = [];
    }

    this.setDataPoint = function (layerIndex, pointIndex, data) {
        initializeDataLayer(layerIndex);
        _dataLayers[layerIndex][pointIndex] = data;
    };

    this.getDataPoint = function (x, y) {
        initializeDataLayer(x);
        var dataPoint = _dataLayers[x][y];
        if (dataPoint === undefined)
            dataPoint = 0;
        return dataPoint;
    };

    this.addGroup = function (group, accessor) {
        if (!accessor)
            accessor = _defaultAccessor;
        _groups.push([group, accessor]);
        return _groups.length - 1;
    };

    this.getGroupByIndex = function (index) {
        return _groups[index][0];
    };

    this.getAccessorByIndex = function (index) {
        return _groups[index][1];
    };

    this.size = function () {
        return _groups.length;
    };

    this.clear = function () {
        _dataLayers = [];
        _groups = [];
    };

    this.setDefaultAccessor = function (retriever) {
        _defaultAccessor = retriever;
    };

    this.getDataLayers = function () {
        return _dataLayers;
    };

    this.toLayers = function () {
        var layers = [];

        for (var i = 0; i < _dataLayers.length; ++i) {
            var layer = {index: i, points: []};
            var dataPoints = _dataLayers[i];

            for (var j = 0; j < dataPoints.length; ++j)
                layer.points.push(dataPoints[j]);

            layers.push(layer);
        }

        return layers;
    };
};

dc.utils.isNumber = function(n) {
    return n===+n;
};

dc.utils.isFloat = function (n) {
    return n===+n && n!==(n|0);
};

dc.utils.isInteger = function (n) {
    return n===+n && n===(n|0);
};

dc.utils.isNegligible = function (max) {
    return max === undefined || (max < dc.constants.NEGLIGIBLE_NUMBER && max > -dc.constants.NEGLIGIBLE_NUMBER);
};

dc.utils.groupMax = function (group, accessor) {
    var max = d3.max(group.all(), function (e) {
        return accessor(e);
    });
    if (dc.utils.isNegligible(max)) max = 0;
    return max;
};

dc.utils.groupMin = function (group, accessor) {
    var min = d3.min(group.all(), function (e) {
        return accessor(e);
    });
    if (dc.utils.isNegligible(min)) min = 0;
    return min;
};

dc.utils.nameToId = function (name) {
    return name.toLowerCase().replace(/[\s]/g, "_").replace(/[\.']/g, "");
};

dc.utils.appendOrSelect = function (parent, name) {
    var element = parent.select(name);
    if (element.empty()) element = parent.append(name);
    return element;
};

dc.utils.createLegendable = function (chart, group, index, accessor) {
    var legendable = {name: chart.getGroupName(group, accessor), data: group};
    if (typeof chart.colors === 'function') legendable.color = chart.colors()(index);
    return legendable;
};

dc.utils.safeNumber = function(n){return isNaN(n)?0:n;};
<|endoftext|>


<commit_before>require('lazy-ass');
var check = require('check-more-types');

function repoNameToSlug(repoName) {
  la(check.unemptyString(repoName), 'missing repo name', repoName);
  var name = require('path').basename(repoName);
  var slug = require('slug');
  return slug(name);
}

module.exports = {
  repoNameToSlug: repoNameToSlug
};
<commit_msg>handling current folder<commit_after>require('lazy-ass');
var check = require('check-more-types');

function repoNameToSlug(repoName) {
  la(check.unemptyString(repoName), 'missing repo name', repoName);

  if (repoName === '.') {
    repoName = process.cwd();
  }

  var name = require('path').basename(repoName);
  var slug = require('slug');
  return slug(name);
}

module.exports = {
  repoNameToSlug: repoNameToSlug
};
<|endoftext|>


<commit_before>import React from 'react'
import classnames from 'classnames'
//
export default {
  get,
  set,
  takeRight,
  last,
  orderBy,
  range,
  remove,
  clone,
  getFirstDefined,
  sum,
  makeTemplateComponent,
  groupBy,
  isArray,
  splitProps,
  compactObject,
  isSortingDesc,
  normalizeComponent,
  asPx,
}

function get (obj, path, def) {
  if (!path) {
    return obj
  }
  const pathObj = makePathArray(path)
  let val
  try {
    val = pathObj.reduce((current, pathPart) => current[pathPart], obj)
  } catch (e) {
    // continue regardless of error
  }
  return typeof val !== 'undefined' ? val : def
}

function set (obj = {}, path, value) {
  const keys = makePathArray(path)
  let keyPart
  let cursor = obj
  while ((keyPart = keys.shift()) && keys.length) {
    if (!cursor[keyPart]) {
      cursor[keyPart] = {}
    }
    cursor = cursor[keyPart]
  }
  cursor[keyPart] = value
  return obj
}

function takeRight (arr, n) {
  const start = n > arr.length ? 0 : arr.length - n
  return arr.slice(start)
}

function last (arr) {
  return arr[arr.length - 1]
}

function range (n) {
  const arr = []
  for (let i = 0; i < n; i += 1) {
    arr.push(n)
  }
  return arr
}

function orderBy (arr, funcs, dirs, indexKey) {
  return arr.sort((rowA, rowB) => {
    for (let i = 0; i < funcs.length; i += 1) {
      const comp = funcs[i]
      const desc = dirs[i] === false || dirs[i] === 'desc'
      const sortInt = comp(rowA, rowB)
      if (sortInt) {
        return desc ? -sortInt : sortInt
      }
    }
    // Use the row index for tie breakers
    return dirs[0] ? rowA[indexKey] - rowB[indexKey] : rowB[indexKey] - rowA[indexKey]
  })
}

function remove (a, b) {
  return a.filter((o, i) => {
    const r = b(o)
    if (r) {
      a.splice(i, 1)
      return true
    }
    return false
  })
}

function clone (a) {
  try {
    return JSON.parse(
      JSON.stringify(a, (key, value) => {
        if (typeof value === 'function') {
          return value.toString()
        }
        return value
      })
    )
  } catch (e) {
    return a
  }
}

function getFirstDefined (...args) {
  for (let i = 0; i < args.length; i += 1) {
    if (typeof args[i] !== 'undefined') {
      return args[i]
    }
  }
}

function sum (arr) {
  return arr.reduce((a, b) => a + b, 0)
}

function makeTemplateComponent (compClass, displayName) {
  if (!displayName) {
    throw new Error('No displayName found for template component:', compClass)
  }
  const cmp = ({ children, className, ...rest }) => (

      {children}

  )
  cmp.displayName = displayName
  return cmp
}

function groupBy (xs, key) {
  return xs.reduce((rv, x, i) => {
    const resKey = typeof key === 'function' ? key(x, i) : x[key]
    rv[resKey] = isArray(rv[resKey]) ? rv[resKey] : []
    rv[resKey].push(x)
    return rv
  }, {})
}

function asPx (value) {
  value = Number(value)
  return Number.isNaN(value) ? null : `${value}px`
}

function isArray (a) {
  return Array.isArray(a)
}

// ########################################################################
// Non-exported Helpers
// ########################################################################

function makePathArray (obj) {
  return flattenDeep(obj)
    .join('.')
    .replace(/\[/g, '.')
    .replace(/\]/g, '')
    .split('.')
}

function flattenDeep (arr, newArr = []) {
  if (!isArray(arr)) {
    newArr.push(arr)
  } else {
    for (let i = 0; i < arr.length; i += 1) {
      flattenDeep(arr[i], newArr)
    }
  }
  return newArr
}

function splitProps ({ className, style, ...rest }) {
  return {
    className,
    style,
    rest: rest || {},
  }
}

function compactObject (obj) {
  const newObj = {}
  if (obj) {
    Object.keys(obj).map(key => {
      if (
        Object.prototype.hasOwnProperty.call(obj, key) &&
        obj[key] !== undefined &&
        typeof obj[key] !== 'undefined'
      ) {
        newObj[key] = obj[key]
      }
      return true
    })
  }
  return newObj
}

function isSortingDesc (d) {
  return !!(d.sort === 'desc' || d.desc === true || d.asc === false)
}

function normalizeComponent (Comp, params = {}, fallback = Comp) {
  return typeof Comp === 'function' ? (
    Object.getPrototypeOf(Comp).isReactComponent ? (
      <Comp {...params} />
    ) : (
      Comp(params)
    )
  ) : (
    fallback
  )
}
<commit_msg>Resolve "cannot call class as a function" error (#1050)<commit_after>import React from 'react'
import classnames from 'classnames'
//
export default {
  get,
  set,
  takeRight,
  last,
  orderBy,
  range,
  remove,
  clone,
  getFirstDefined,
  sum,
  makeTemplateComponent,
  groupBy,
  isArray,
  splitProps,
  compactObject,
  isSortingDesc,
  normalizeComponent,
  asPx,
}

function get (obj, path, def) {
  if (!path) {
    return obj
  }
  const pathObj = makePathArray(path)
  let val
  try {
    val = pathObj.reduce((current, pathPart) => current[pathPart], obj)
  } catch (e) {
    // continue regardless of error
  }
  return typeof val !== 'undefined' ? val : def
}

function set (obj = {}, path, value) {
  const keys = makePathArray(path)
  let keyPart
  let cursor = obj
  while ((keyPart = keys.shift()) && keys.length) {
    if (!cursor[keyPart]) {
      cursor[keyPart] = {}
    }
    cursor = cursor[keyPart]
  }
  cursor[keyPart] = value
  return obj
}

function takeRight (arr, n) {
  const start = n > arr.length ? 0 : arr.length - n
  return arr.slice(start)
}

function last (arr) {
  return arr[arr.length - 1]
}

function range (n) {
  const arr = []
  for (let i = 0; i < n; i += 1) {
    arr.push(n)
  }
  return arr
}

function orderBy (arr, funcs, dirs, indexKey) {
  return arr.sort((rowA, rowB) => {
    for (let i = 0; i < funcs.length; i += 1) {
      const comp = funcs[i]
      const desc = dirs[i] === false || dirs[i] === 'desc'
      const sortInt = comp(rowA, rowB)
      if (sortInt) {
        return desc ? -sortInt : sortInt
      }
    }
    // Use the row index for tie breakers
    return dirs[0] ? rowA[indexKey] - rowB[indexKey] : rowB[indexKey] - rowA[indexKey]
  })
}

function remove (a, b) {
  return a.filter((o, i) => {
    const r = b(o)
    if (r) {
      a.splice(i, 1)
      return true
    }
    return false
  })
}

function clone (a) {
  try {
    return JSON.parse(
      JSON.stringify(a, (key, value) => {
        if (typeof value === 'function') {
          return value.toString()
        }
        return value
      })
    )
  } catch (e) {
    return a
  }
}

function getFirstDefined (...args) {
  for (let i = 0; i < args.length; i += 1) {
    if (typeof args[i] !== 'undefined') {
      return args[i]
    }
  }
}

function sum (arr) {
  return arr.reduce((a, b) => a + b, 0)
}

function makeTemplateComponent (compClass, displayName) {
  if (!displayName) {
    throw new Error('No displayName found for template component:', compClass)
  }
  const cmp = ({ children, className, ...rest }) => (

      {children}

  )
  cmp.displayName = displayName
  return cmp
}

function groupBy (xs, key) {
  return xs.reduce((rv, x, i) => {
    const resKey = typeof key === 'function' ? key(x, i) : x[key]
    rv[resKey] = isArray(rv[resKey]) ? rv[resKey] : []
    rv[resKey].push(x)
    return rv
  }, {})
}

function asPx (value) {
  value = Number(value)
  return Number.isNaN(value) ? null : `${value}px`
}

function isArray (a) {
  return Array.isArray(a)
}

// ########################################################################
// Non-exported Helpers
// ########################################################################

function makePathArray (obj) {
  return flattenDeep(obj)
    .join('.')
    .replace(/\[/g, '.')
    .replace(/\]/g, '')
    .split('.')
}

function flattenDeep (arr, newArr = []) {
  if (!isArray(arr)) {
    newArr.push(arr)
  } else {
    for (let i = 0; i < arr.length; i += 1) {
      flattenDeep(arr[i], newArr)
    }
  }
  return newArr
}

function splitProps ({ className, style, ...rest }) {
  return {
    className,
    style,
    rest: rest || {},
  }
}

function compactObject (obj) {
  const newObj = {}
  if (obj) {
    Object.keys(obj).map(key => {
      if (
        Object.prototype.hasOwnProperty.call(obj, key) &&
        obj[key] !== undefined &&
        typeof obj[key] !== 'undefined'
      ) {
        newObj[key] = obj[key]
      }
      return true
    })
  }
  return newObj
}

function isSortingDesc (d) {
  return !!(d.sort === 'desc' || d.desc === true || d.asc === false)
}

function normalizeComponent (Comp, params = {}, fallback = Comp) {
  return typeof Comp === 'function' ? (
    <Comp {...params} />
  ) : (
    fallback
  )
}
<|endoftext|>


<commit_before>/* require:
jsziptools.js
*/

utils.noop = function() {};

/**
 * @param {*} arg
 * @return {Array}
 */
utils.toArray = function(arg) {
    return Array.prototype.slice.call(arg);
};

/**
 * @param  {Arguments} args
 * @param  {Array.<string>} propertyNames
 * @return {object}
 */
utils.getParams = function (args, propertyNames) {
    if (Object.prototype.toString.call(args[0]) === '[object Object]') return args[0];
    var params = {};
    propertyNames.forEach(function (name, i) {
        params[name] = args[i];
    });
    return params;
}

/**
 * convert Array, ArrayBuffer or String to Uint8Array.
 * @param {ArrayBuffer|Uint8Array|Int8Array|Array|string} buffer
 * @return {Uint8Array}
 *
 * @example
 * var bytes = jz.utils.toBytes('foo');
 * var bytes = jz.utils.toBytes([1, 2, 3]);
 */
utils.toBytes = function(buffer){
    switch(Object.prototype.toString.call(buffer)){
        case '[object String]': return utils.stringToBytes(buffer);
        case '[object Array]':
        case '[object ArrayBuffer]': return new Uint8Array(buffer);
        case '[object Uint8Array]': return buffer;
        case '[object Int8Array]':
        case '[object Uint8ClampedArray]':
        case '[object CanvasPixelArray]': return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
        default: throw new Error('jz.utils.toBytes: not supported type.');
    }
};

expose('jz.utils.toBytes', utils.toBytes);

utils.readFileAs = function (type, blob, encoding) {
    var fn;
    if (env.isWorker) {
        fn = function (resolve) {
            var fr = new FileReaderSync;
            resolve(fr['readAs' + type].call(fr, blob, encoding));
        };
    } else {
        fn = function (resolve, reject) {
            var fr = new FileReader;
            fr.onload = function () {
                resolve(fr.result);
            };
            fr.onerror = reject;
            fr['readAs' + type].call(fr, blob, encoding);
        };
    }
    return new Promise(fn);
}

utils.readFileAsText = function (blob, encoding) {
    return utils.readFileAs('Text', blob, encoding || 'UTF-8');
};

utils.readFileAsArrayBuffer = utils.readFileAs.bind(null, 'ArrayBuffer');
utils.readFileAsDataURL = utils.readFileAs.bind(null, 'DataURL');
utils.readFileAsBinaryString = utils.readFileAs.bind(null, 'BinaryString');

/**
 * @param {string} str
 * @return {Uint8Array}
 */
utils.stringToBytes = function(str){
    var n = str.length,
        idx = -1,
        byteLength = 32,
        bytes = new Uint8Array(byteLength),
        i, c, _bytes;

    for(i = 0; i < n; ++i){
        c = str.charCodeAt(i);
        if(c <= 0x7F){
            bytes[++idx] = c;
        } else if(c <= 0x7FF){
            bytes[++idx] = 0xC0 | (c >>> 6);
            bytes[++idx] = 0x80 | (c & 0x3F);
        } else if(c <= 0xFFFF){
            bytes[++idx] = 0xE0 | (c >>> 12);
            bytes[++idx] = 0x80 | ((c >>> 6) & 0x3F);
            bytes[++idx] = 0x80 | (c & 0x3F);
        } else {
            bytes[++idx] = 0xF0 | (c >>> 18);
            bytes[++idx] = 0x80 | ((c >>> 12) & 0x3F);
            bytes[++idx] = 0x80 | ((c >>> 6) & 0x3F);
            bytes[++idx] = 0x80 | (c & 0x3F);
        }
        if(byteLength - idx <= 4){
            _bytes = bytes;
            byteLength *= 2;
            bytes = new Uint8Array(byteLength);
            bytes.set(_bytes);
        }
    }
    return bytes.subarray(0, ++idx);
};

/**
 * Convert Uint8Array to String.
 * @param {Uint8Array|ArrayBuffer} bytes
 * @param {string}     encoding Character encoding
 * @return {Promise}
 *
 * @example
 * jz.utils.bytesToString(bytes).done(function(str) {
 *     console.log(str);
 * });
 *
 * jz.utils.bytesToString(bytes, 'UTF-8').done(function(str) {
 *     console.log(str);
 * });
 */
utils.bytesToString = function(bytes, encoding) {
    return utils.readFileAsText(new Blob([utils.toBytes(bytes)]), encoding);
};

expose('jz.utils.bytesToString', utils.bytesToString);

utils.bytesToStringSync = null;

if(env.isWorker) {
    /**
     * @param {Uint8Array|Array|ArrayBuffer} bytes
     * @param {string} encoding
     * @return {string}
     *
     * @example
     * var str = jz.utils.bytesToStringSync(bytes);
     * var str = jz.utils.bytesToStringSync(bytes, 'UTF-8');
     */
    utils.bytesToStringSync = function(bytes, encoding) {
        return new FileReaderSync().readAsText(new Blob([utils.toBytes(bytes)]), encoding || 'UTF-8');
    };

    expose('jz.utils.bytesToStringSync', utils.bytesToStringSync);
}

/**
 * @param {Uint8Array} bytes
 * @return {string} encoding
 *
 * @example
 * var encoding = jz.utils.detectEncoding(bytes);
 * jz.utils.bytesToString(bytes, encoding).done(function(str) {
 *     console.log(str);
 * });
 */
utils.detectEncoding = function(bytes) {
    bytes = utils.toBytes(bytes);

    for(var i = 0, n = bytes.length; i < n; ++i) {
        if(bytes[i] < 0x80) {
            continue;
        } else if((bytes[i] & 0xE0) === 0xC0) {
            if((bytes[++i] & 0xC0) === 0x80) continue;
        } else if((bytes[i] & 0xF0) === 0xE0) {
            if((bytes[++i] & 0xC0) === 0x80 && (bytes[++i] & 0xC0) === 0x80) continue;
        } else if((bytes[i] & 0xF8) === 0xF0) {
            if((bytes[++i] & 0xC0) === 0x80 && (bytes[++i] & 0xC0) === 0x80 && (bytes[++i] & 0xC0) === 0x80) continue;
        } else {
            return 'Shift_JIS';
        }
    }

    return 'UTF-8';
};
expose('jz.utils.detectEncoding', utils.detectEncoding);

Promise.prototype.spread = function (onFulfillment, onRejection) {
    return Promise.prototype.then.call(this, Function.prototype.apply.bind(onFulfillment, null), onRejection);
};

/**
 * Load buffers with Ajax(async).
 * @param {Array.<string>|...string} urls
 * @return {Promise}
 *
 * @example
 * utils.load(['a.zip', 'b.zip'])
 * .spread(function(a, b){
 *   // arguments are Uint8Array
 * });
 * // or
 * utils.load('a.zip', 'b.zip')
 */
utils.load = function(urls){
    urls = Array.isArray(urls) ? urls : utils.toArray(arguments);
    return Promise.all(urls.map(function (url, i) {
        return new Promise(function (resolve, reject) {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', url);
            xhr.responseType = 'arraybuffer';
            xhr.onloadend = function () {
                var s = xhr.status;
                (s === 200 || s === 206 || s === 0) ?
                    resolve(new Uint8Array(xhr.response)) : reject(new Error('Load Error: ' + s + ' ' + url));
            };
            xhr.onerror = reject;
            xhr.send();
        });
    }));
};

expose('jz.utils.load', utils.load);

/**
 * @param {...(Uint8Array|ArrayBuffer)} buffers
 * @return {Uint8Array}
 *
 * @example
 * var bytes = jz.utils.concatBytes(bytes1, bytes2, bytes3);
 * var bytes = jz.utils.concatBytes([bytes1, bytes2, bytes3]);
 */
utils.concatBytes = function(buffers){
    var buffers = Array.isArray(buffers) ? buffers : utils.toArray(arguments),
        size = 0,
        offset = 0,
        i, n, ret;

    for(i = 0, n = buffers.length; i < n; ++i) size += buffers[i].length;
    ret = new Uint8Array(size);
    for(i = 0; i < n; ++i) {
        ret.set(buffers[i], offset);
        offset += buffers[i].length;
    }
    return ret;
};

expose('jz.utils.concatBytes', utils.concatBytes);
<commit_msg>format<commit_after>/* require:
jsziptools.js
*/

utils.noop = function() {};

/**
 * @param {*} arg
 * @return {Array}
 */
utils.toArray = function(arg) {
    return Array.prototype.slice.call(arg);
};

/**
 * @param  {Arguments} args
 * @param  {Array.<string>} propertyNames
 * @return {object}
 */
utils.getParams = function(args, propertyNames) {
    if (Object.prototype.toString.call(args[0]) === '[object Object]') return args[0];
    var params = {};
    propertyNames.forEach(function(name, i) {
        params[name] = args[i];
    });
    return params;
}

/**
 * convert Array, ArrayBuffer or String to Uint8Array.
 * @param {ArrayBuffer|Uint8Array|Int8Array|Array|string} buffer
 * @return {Uint8Array}
 *
 * @example
 * var bytes = jz.utils.toBytes('foo');
 * var bytes = jz.utils.toBytes([1, 2, 3]);
 */
utils.toBytes = function(buffer) {
    switch (Object.prototype.toString.call(buffer)) {
    case '[object String]':
        return utils.stringToBytes(buffer);
    case '[object Array]':
    case '[object ArrayBuffer]':
        return new Uint8Array(buffer);
    case '[object Uint8Array]':
        return buffer;
    case '[object Int8Array]':
    case '[object Uint8ClampedArray]':
    case '[object CanvasPixelArray]':
        return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
    default:
        throw new Error('jz.utils.toBytes: not supported type.');
    }
};

expose('jz.utils.toBytes', utils.toBytes);

utils.readFileAs = function(type, blob, encoding) {
    var fn;
    if (env.isWorker) {
        fn = function(resolve) {
            var fr = new FileReaderSync;
            resolve(fr['readAs' + type].call(fr, blob, encoding));
        };
    } else {
        fn = function(resolve, reject) {
            var fr = new FileReader;
            fr.onload = function() {
                resolve(fr.result);
            };
            fr.onerror = reject;
            fr['readAs' + type].call(fr, blob, encoding);
        };
    }
    return new Promise(fn);
}

/**
 * @param  {Blob} blob
 * @param  {string} encoding
 * @return {Promise}
 */
utils.readFileAsText = function(blob, encoding) {
    return utils.readFileAs('Text', blob, encoding || 'UTF-8');
};

utils.readFileAsArrayBuffer = utils.readFileAs.bind(null, 'ArrayBuffer');
utils.readFileAsDataURL = utils.readFileAs.bind(null, 'DataURL');
utils.readFileAsBinaryString = utils.readFileAs.bind(null, 'BinaryString');

expose('jz.utils.readFileAsArrayBuffer', utils.readFileAsArrayBuffer);
expose('jz.utils.readFileAsText', utils.readFileAsText);
expose('jz.utils.readFileAsDataURL', utils.readFileAsDataURL);
expose('jz.utils.readFileAsBinaryString', utils.readFileAsBinaryString);

/**
 * @param {string} str
 * @return {Uint8Array}
 */
utils.stringToBytes = function(str) {
    var n = str.length,
        idx = -1,
        byteLength = 32,
        bytes = new Uint8Array(byteLength),
        i, c, _bytes;

    for (i = 0; i < n; ++i) {
        c = str.charCodeAt(i);
        if (c <= 0x7F) {
            bytes[++idx] = c;
        } else if (c <= 0x7FF) {
            bytes[++idx] = 0xC0 | (c >>> 6);
            bytes[++idx] = 0x80 | (c & 0x3F);
        } else if (c <= 0xFFFF) {
            bytes[++idx] = 0xE0 | (c >>> 12);
            bytes[++idx] = 0x80 | ((c >>> 6) & 0x3F);
            bytes[++idx] = 0x80 | (c & 0x3F);
        } else {
            bytes[++idx] = 0xF0 | (c >>> 18);
            bytes[++idx] = 0x80 | ((c >>> 12) & 0x3F);
            bytes[++idx] = 0x80 | ((c >>> 6) & 0x3F);
            bytes[++idx] = 0x80 | (c & 0x3F);
        }
        if (byteLength - idx <= 4) {
            _bytes = bytes;
            byteLength *= 2;
            bytes = new Uint8Array(byteLength);
            bytes.set(_bytes);
        }
    }
    return bytes.subarray(0, ++idx);
};

/**
 * Convert Uint8Array to String.
 * @param {Uint8Array|ArrayBuffer} bytes
 * @param {string}     encoding Character encoding
 * @return {Promise}
 *
 * @example
 * jz.utils.bytesToString(bytes).done(function(str) {
 *     console.log(str);
 * });
 *
 * jz.utils.bytesToString(bytes, 'UTF-8').done(function(str) {
 *     console.log(str);
 * });
 */
utils.bytesToString = function(bytes, encoding) {
    return utils.readFileAsText(new Blob([utils.toBytes(bytes)]), encoding);
};

expose('jz.utils.bytesToString', utils.bytesToString);

utils.bytesToStringSync = null;

if (env.isWorker) {
    /**
     * @param {Uint8Array|Array|ArrayBuffer} bytes
     * @param {string} encoding
     * @return {string}
     *
     * @example
     * var str = jz.utils.bytesToStringSync(bytes);
     * var str = jz.utils.bytesToStringSync(bytes, 'UTF-8');
     */
    utils.bytesToStringSync = function(bytes, encoding) {
        return new FileReaderSync().readAsText(new Blob([utils.toBytes(bytes)]), encoding || 'UTF-8');
    };

    expose('jz.utils.bytesToStringSync', utils.bytesToStringSync);
}

/**
 * @param {Uint8Array} bytes
 * @return {string} encoding
 *
 * @example
 * var encoding = jz.utils.detectEncoding(bytes);
 * jz.utils.bytesToString(bytes, encoding).done(function(str) {
 *     console.log(str);
 * });
 */
utils.detectEncoding = function(bytes) {
    bytes = utils.toBytes(bytes);

    for (var i = 0, n = bytes.length; i < n; ++i) {
        if (bytes[i] < 0x80) {
            continue;
        } else if ((bytes[i] & 0xE0) === 0xC0) {
            if ((bytes[++i] & 0xC0) === 0x80) continue;
        } else if ((bytes[i] & 0xF0) === 0xE0) {
            if ((bytes[++i] & 0xC0) === 0x80 && (bytes[++i] & 0xC0) === 0x80) continue;
        } else if ((bytes[i] & 0xF8) === 0xF0) {
            if ((bytes[++i] & 0xC0) === 0x80 && (bytes[++i] & 0xC0) === 0x80 && (bytes[++i] & 0xC0) === 0x80) continue;
        } else {
            return 'Shift_JIS';
        }
    }

    return 'UTF-8';
};
expose('jz.utils.detectEncoding', utils.detectEncoding);

Promise.prototype.spread = function(onFulfillment, onRejection) {
    return Promise.prototype.then.call(this, Function.prototype.apply.bind(onFulfillment, null), onRejection);
};

/**
 * Load buffers with Ajax(async).
 * @param {Array.<string>|...string} urls
 * @return {Promise}
 *
 * @example
 * utils.load(['a.zip', 'b.zip'])
 * .spread(function(a, b){
 *   // arguments are Uint8Array
 * });
 * // or
 * utils.load('a.zip', 'b.zip')
 */
utils.load = function(urls) {
    urls = Array.isArray(urls) ? urls : utils.toArray(arguments);
    return Promise.all(urls.map(function(url, i) {
        return new Promise(function(resolve, reject) {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', url);
            xhr.responseType = 'arraybuffer';
            xhr.onloadend = function() {
                var s = xhr.status;
                (s === 200 || s === 206 || s === 0) ? resolve(new Uint8Array(xhr.response)) : reject(new Error('Load Error: ' + s + ' ' + url));
            };
            xhr.onerror = reject;
            xhr.send();
        });
    }));
};

expose('jz.utils.load', utils.load);

/**
 * @param {...(Uint8Array|ArrayBuffer)} buffers
 * @return {Uint8Array}
 *
 * @example
 * var bytes = jz.utils.concatBytes(bytes1, bytes2, bytes3);
 * var bytes = jz.utils.concatBytes([bytes1, bytes2, bytes3]);
 */
utils.concatBytes = function(buffers) {
    var buffers = Array.isArray(buffers) ? buffers : utils.toArray(arguments),
        size = 0,
        offset = 0,
        i, n, ret;

    for (i = 0, n = buffers.length; i < n; ++i) size += buffers[i].length;
    ret = new Uint8Array(size);
    for (i = 0; i < n; ++i) {
        ret.set(buffers[i], offset);
        offset += buffers[i].length;
    }
    return ret;
};

expose('jz.utils.concatBytes', utils.concatBytes);<|endoftext|>