<commit_before>// --------------------------------------------------
// Used in generic autocompletes and designed to be
// extended by other views that need extended feature
// --------------------------------------------------
define(function (require) {

	// dependencies
	var $ = require('jquery'),
		_ = require('underscore'),
		Backbone = require('backbone');
	require('typeahead');

	// public view module
	var Autocomplete = Backbone.View.extend({

		// Initial state and inheritable vars
		found: false,
		data: {}, // Stores the key (label) - value (row data) pairs
		id: null,
		title: null,
		selection: null,  // The whole object (from the JSON server response) that is chosen
		route: null,
		throttle: 150,
		last_query: null,

		// Init
		initialize: function () {
			_.bindAll(this);

			// Get the path to the controller.  If this is not specified via a
			// data attribtue of "controller-route" then we attempt to infer it from
			// the current URL.
			this.route = this.$el.data('controller-route');
			if (!this.route) this.route = window.location.pathname;

			// Cache selectors
			this.$input = this.$('input[type="text"]');

			// Init Bloodhound instance that tells typeahead where to get data
			this.bloodhound = new Bloodhound({
				remote: {
					url: this.url(),
					rateLimitWait: this.throttle
				},
				datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.val); },
				queryTokenizer: Bloodhound.tokenizers.whitespace
			});
			this.bloodhound.initialize();

			// Initialize the Bootstrap typahead plugin, which generates the
			// autocomplete menu
			this.$input.typeahead({
				highlight: true,
				hint: false // I don't like the visual redundancy this introduces
			},{
				displayKey: 'title',
				source: this.bloodhound.ttAdapter()
			});

			// Listen for matching events
			this.$input.on('typeahead:opened', _.bind(function() {
				this.$input.off('input change', this.match);
				this.$input.on('typeahead:selected typeahead:autocompleted', this.match);
			}, this));
			this.$input.on('typeahead:closed', _.bind(function() {
				this.$input.off('typeahead:selected typeahead:autocompleted', this.match);
				this.$input.on('input change', this.match);
			}, this));

		},

		// Form the URL for the query
		url: function() {
			return this.route+'/autocomplete?query=%QUERY';
		},

		// Query the server for matches.  Defined as it's own method so it can be
		// overriden without having to replace the whole AJAX call.
		query: function(query, process) {

			// Make sure the term actually changed.  This is to prevent the
			// command key (for instance, when doing a command-a) from
			// trigger it.
			if (query == this.last_query) return;

			// Run the query.
			this.execute({query:query}, process);
			this.last_query = query
		},

		// Execute the query on the server.  In other words, do the ajax
		execute: function(request, process) {

			// Make the request
			$.ajax(this.route+'/autocomplete', {
				data: request,
				type:'GET',
				dataType: 'JSON'
			})

			// Success
			.done(_.bind(function(data) { this.response(data, process); }, this));

		},

		// The response from the server
		response: function(data, process) {

			// Loop through results and massage the results.  We need an array
			// of just labels for the typeahead.  And we need a key/val pairs
			// to get the id back from the label when saving it.
			this.data = {};
			var labels = [];
			if (_.isArray(data)) {
				_.each(data, function(row) {
					labels.push({ value: row.title });
					this.data[row.title] = row;
				}, this);
			}

			// Tell typeahead about the labels
			process(labels);

			// Check again if there is a match in the textfield
			this.match();

		},

		// Callback from after the user inputs anything in the textfield.  Basically,
		// we want to constantly check if what they've entered is valid rather than
		// rely on bootstrap to tell us.  Cause their events to fire with every change
		// the user makes.
		match: function(e, suggestion, dataset) {

			// A suggestion was found
			if (suggestion) {
				this.found = true;
				this.title = suggestion.title;
				this.id = suggestion.id;
				this.selection = suggestion;

			// The current input is different than the old one and there
			// was no suggestion, so wipe it.
			} else if (this.title != this.$input.val()) {
				this.found = false;
				this.title = this.selection = this.id = null;
			}

		},

		// Add a new item to the data array.  Title is the key to the collection
		// dicitonary. Model is an object like: {id, title, columns:{}}
		add:function(title, model) {
			this.data[title] = model;
		}

	});

	return Autocomplete;
});
<commit_msg>Removing code that is deprecated by switch to bloodhound<commit_after>// --------------------------------------------------
// Used in generic autocompletes and designed to be
// extended by other views that need extended feature
// --------------------------------------------------
define(function (require) {

	// dependencies
	var $ = require('jquery'),
		_ = require('underscore'),
		Backbone = require('backbone');
	require('typeahead');

	// public view module
	var Autocomplete = Backbone.View.extend({

		// Initial state and inheritable vars
		found: false,
		data: {}, // Stores the key (label) - value (row data) pairs
		id: null,
		title: null,
		selection: null,  // The whole object (from the JSON server response) that is chosen
		route: null,
		throttle: 150,
		last_query: null,

		// Init
		initialize: function () {
			_.bindAll(this);

			// Get the path to the controller.  If this is not specified via a
			// data attribtue of "controller-route" then we attempt to infer it from
			// the current URL.
			this.route = this.$el.data('controller-route');
			if (!this.route) this.route = window.location.pathname;

			// Cache selectors
			this.$input = this.$('input[type="text"]');

			// Init Bloodhound instance that tells typeahead where to get data
			this.bloodhound = new Bloodhound({
				remote: {
					url: this.url(),
					rateLimitWait: this.throttle
				},
				datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.val); },
				queryTokenizer: Bloodhound.tokenizers.whitespace
			});
			this.bloodhound.initialize();

			// Initialize the Bootstrap typahead plugin, which generates the
			// autocomplete menu
			this.$input.typeahead({
				highlight: true,
				hint: false // I don't like the visual redundancy this introduces
			},{
				displayKey: 'title',
				source: this.bloodhound.ttAdapter()
			});

			// Listen for matching events
			this.$input.on('typeahead:opened', _.bind(function() {
				this.$input.off('input change', this.match);
				this.$input.on('typeahead:selected typeahead:autocompleted', this.match);
			}, this));
			this.$input.on('typeahead:closed', _.bind(function() {
				this.$input.off('typeahead:selected typeahead:autocompleted', this.match);
				this.$input.on('input change', this.match);
			}, this));

		},

		// Form the URL for the query
		url: function() {
			return this.route+'/autocomplete?query=%QUERY';
		},

		// Callback from after the user inputs anything in the textfield.  Basically,
		// we want to constantly check if what they've entered is valid rather than
		// rely on bootstrap to tell us.  Cause their events to fire with every change
		// the user makes.
		match: function(e, suggestion, dataset) {

			// A suggestion was found
			if (suggestion) {
				this.found = true;
				this.title = suggestion.title;
				this.id = suggestion.id;
				this.selection = suggestion;

			// The current input is different than the old one and there
			// was no suggestion, so wipe it.
			} else if (this.title != this.$input.val()) {
				this.found = false;
				this.title = this.selection = this.id = null;
			}

		},

		// Add a new item to the data array.  Title is the key to the collection
		// dicitonary. Model is an object like: {id, title, columns:{}}
		add:function(title, model) {
			this.data[title] = model;
		}

	});

	return Autocomplete;
});
<|endoftext|>


<commit_before>// yeah, nasty, but it allows me to switch from a RTF to plain text if we're running a iOS
var noop = function () {},
    rootClassName = document.body.className;

if (jsbin.mobile || jsbin.tablet || rootClassName.indexOf('ie6') !== -1 || rootClassName.indexOf('ie7') !== -1) {
  $('body').addClass('mobile');
  jsbin.lameEditor = true;
  Editor = function (el, options) {
    this.textarea = el;
    this.win = { document : this.textarea };
    this.ready = true;
    this.wrapping = document.createElement('div');

    var textareaParent = this.textarea.parentNode;
    this.wrapping.appendChild(this.textarea);
    textareaParent.appendChild(this.wrapping);

    this.textarea.style.opacity = 1;
    // this.textarea.style.width = '100%';

    $(this.textarea).blur(throttle(function () {
      $(document).trigger('codeChange', { panelId: el.id });
    }, 200));

    options.initCallback && $(options.initCallback);
  };

  Editor.prototype = {
    getWrapperElement: function () {
      return this.wrapping;
    },
    getScrollerElement: function () {
      return this.textarea;
    },
    setOption: function (type, handler) {
      if (type == 'onChange') {
        $(this.textarea).change(handler);
      }
    },
    setCode: function (code) {
      this.textarea.value = code;
    },
    getCode: function () {
      return this.textarea.value;
    },
    getValue: function () {
      return this.textarea.value;
    },
    setValue: function (code)  {
      this.textarea.value = code;
    },
    focus: noop,
    getCursor: function () {
      return { line: 0, ch: 0 };
    },
    setCursor: noop,
    currentLine: function () {
      return 0;
    },
    cursorPosition: function () {
      return { character: 0 };
    },
    nthLine: noop,
    refresh: noop,
    selectLines: noop,
    on: noop
  };

  var _oldCM = CodeMirror;

  CodeMirror = noop;

  for (var key in _oldCM) {
    CodeMirror[key] = noop;
  }

  CodeMirror.fromTextArea = function (el, options) {
      return new Editor(el, options);
  };

  CodeMirror.keyMap = { basic: {} };

}<commit_msg>Add missing methods as noop's<commit_after>// yeah, nasty, but it allows me to switch from a RTF to plain text if we're running a iOS
var noop = function () {},
    rootClassName = document.body.className;

if (jsbin.mobile || jsbin.tablet || rootClassName.indexOf('ie6') !== -1 || rootClassName.indexOf('ie7') !== -1) {
  $('body').addClass('mobile');
  jsbin.lameEditor = true;
  Editor = function (el, options) {
    this.textarea = el;
    this.win = { document : this.textarea };
    this.ready = true;
    this.wrapping = document.createElement('div');

    var textareaParent = this.textarea.parentNode;
    this.wrapping.appendChild(this.textarea);
    textareaParent.appendChild(this.wrapping);

    this.textarea.style.opacity = 1;
    // this.textarea.style.width = '100%';

    $(this.textarea).blur(throttle(function () {
      $(document).trigger('codeChange', { panelId: el.id });
    }, 200));

    options.initCallback && $(options.initCallback);
  };

  Editor.prototype = {
    getWrapperElement: function () {
      return this.wrapping;
    },
    getScrollerElement: function () {
      return this.textarea;
    },
    setOption: function (type, handler) {
      if (type == 'onChange') {
        $(this.textarea).change(handler);
      }
    },
    setCode: function (code) {
      this.textarea.value = code;
    },
    getCode: function () {
      return this.textarea.value;
    },
    getValue: function () {
      return this.textarea.value;
    },
    setValue: function (code)  {
      this.textarea.value = code;
    },
    focus: noop,
    getCursor: function () {
      return { line: 0, ch: 0 };
    },
    setCursor: noop,
    currentLine: function () {
      return 0;
    },
    addKeyMap: noop,
    indentLine: noop,
    cursorPosition: function () {
      return { character: 0 };
    },
    nthLine: noop,
    refresh: noop,
    selectLines: noop,
    on: noop
  };

  var _oldCM = CodeMirror;

  CodeMirror = noop;

  for (var key in _oldCM) {
    CodeMirror[key] = noop;
  }

  CodeMirror.fromTextArea = function (el, options) {
      return new Editor(el, options);
  };

  CodeMirror.keyMap = { basic: {} };

}<|endoftext|>


<commit_before>module.exports = {
    USA : {
        production: {
            host_name : 'twonetprod.qualcomm.com',
            url_path : 'cuc/rest/'
        },
        sandbox : {
            host_name : 'twonetusdmoapi.qualcommlife.com/demo3',
            url_path  : 'cuc/rest/'
        }
    },
    EU : {
        production: {
            host_name : 'twonet.qualcommlife.com',
            url_path : 'cuc/rest/',
        }
    },
    FR : {
        production : {
            host_name : 'twonetprodfr.qualcommlife.com',
            url_path : 'cuc/rest/',
        }
    }
};<commit_msg>update usa production and eu production hostnames<commit_after>module.exports = {
    USA : {
        production: {
            host_name : 'twonetprodapi.qualcommlife.com',
            url_path : 'cuc/rest/'
        },
        sandbox : {
            host_name : 'twonetusdmoapi.qualcommlife.com/demo3',
            url_path  : 'cuc/rest/'
        }
    },
    EU : {
        production: {
            host_name : 'twonetapi.qualcommlife.com',
            url_path : 'cuc/rest/',
        }
    },
    FR : {
        production : {
            host_name : 'twonetprodfr.qualcommlife.com',
            url_path : 'cuc/rest/',
        }
    }
};<|endoftext|>


<commit_before>var dest = "./build";
var src = './app';

module.exports = {
  browserSync: {
    server: {
      // We're serving the src folder as well
      // for sass sourcemap linking
      baseDir: [dest, src]
    },
    files: [
      dest + "/**",
      // Exclude Map files
      "!" + dest + "/**.map"
    ]
  },
  stylus: {
    src: src + "/styles/*",
    dest: dest+'/styles'
  },
  images: {
    src: src + "/images/**",
    dest: dest + "/images"
  },
  markup: {
    src: src + "/htdocs/**",
    dest: dest
  },
  browserify: {
    // Enable source maps
    debug: true,
    // Additional file extentions to make optional
    //extensions: ['.coffee', '.hbs'],
    src: ['components/*'],
    // A separate bundle will be generated for each
    // bundle config in the list below
    bundleConfigs: [{
      entries: './app/scripts/site/app.coffee',
      dest: dest+'/scripts',
      outputName: 'app.js'
    }, {
      entries: './app/scripts/site/head.coffee',
      dest: dest+'/scripts',
      outputName: 'head.js'
    }]
  }
};
<commit_msg>remove head js<commit_after>var dest = "./build";
var src = './app';

module.exports = {
  browserSync: {
    server: {
      // We're serving the src folder as well
      // for sass sourcemap linking
      baseDir: [dest, src]
    },
    files: [
      dest + "/**",
      // Exclude Map files
      "!" + dest + "/**.map"
    ]
  },
  stylus: {
    src: src + "/styles/*",
    dest: dest+'/styles'
  },
  images: {
    src: src + "/images/**",
    dest: dest + "/images"
  },
  markup: {
    src: src + "/htdocs/**",
    dest: dest
  },
  browserify: {
    // Enable source maps
    debug: true,
    // Additional file extentions to make optional
    //extensions: ['.coffee', '.hbs'],
    src: ['components/*'],
    // A separate bundle will be generated for each
    // bundle config in the list below
    bundleConfigs: [{
      entries: './app/scripts/site/app.coffee',
      dest: dest+'/scripts',
      outputName: 'app.js'
    }]
  }
};
<|endoftext|>


<commit_before>
/**
 * Module requirements.
 */

var Transport = require('../transport')
  , parser = require('../parser')
  , debug = require('debug')('engine.transport')

/**
 * Exports the constructor.
 */

module.exports = Polling;

/**
 * HTTP polling constructor.
 *
 * @api public.
 */

function Polling (req) {
  Transport.call(this, req);
};

/**
 * Inherits from Transport.
 *
 * @api public.
 */

Polling.prototype.__proto__ = Transport.prototype;

/**
 * Transport name
 *
 * @api public
 */

Polling.prototype.name = 'polling';

/**
 * Overrides onRequest.
 *
 * @param {http.ServerRequest}
 * @api private
 */

Polling.prototype.onRequest = function (req) {
  var res = req.res;

  if ('GET' == req.method) {
    this.onPollRequest(req, res);
  } else if ('POST' == req.method) {
    this.onDataRequest(req, res);
  } else {
    res.writeHead(500);
    res.end();
  }
};

/**
 * The client sends a request awaiting for us to send data.
 *
 * @api private
 */

Polling.prototype.onPollRequest = function (req, res) {
  // if there's an ongoing poll
  if (this.req) {
    // assert: this.res, '.req and .res should be (un)set together'
    this.onError('poll overlap from client');
    res.writeHead(500);
  } else {
    this.req = req;
    this.res = res;

    var self = this;

    function onClose () {
      self.onError('poll connection closed prematurely');
    }

    function cleanup () {
      req.removeListener('close', onClose);
      self.req = self.res = null;
    }

    req.cleanup = cleanup;
    req.on('close', onClose);

    this.buffer = false;
    this.flush();
  }
};

/**
 * The client sends a request with data.
 *
 * @api private
 */

Polling.prototype.onDataRequest = function (req, res) {
  if (this.dataReq) {
    // assert: this.dataRes, '.dataReq and .dataRes should be (un)set together'
    this.onError('data request overlap from client');
    res.writeHead(500);
  } else {
    this.dataReq = req;
    this.dataRes = res;

    var chunks = ''
      , self = this

    function cleanup () {
      chunks = '';
      req.removeListener('data', onData);
      req.removeListener('end', onEnd);
      req.removeListener('close', cleanup);
      self.dataReq = self.dataRes = null;
    };

    function onClose () {
      cleanup();
      self.onError('data request connection closed prematurely');
    };

    function onData () {
      chunks += data;
    };

    function onEnd () {
      self.onData(chunks);
      res.writeHead(204);
      res.end();
      cleanup();
    };

    req.abort = cleanup;
    req.on('close', onClose);
    req.on('data', onData);
    req.on('end', onEnd);
    req.setEncoding('utf8');
  }
};

/**
 * Processes the incoming data payload.
 */

Polling.prototype.onData = function (data) {
  var packets = parser.decodePayload(data);
  for (var i = 0, l = packets.length; i < l; i++) {
    this.onPacket(packets[i]);
  }
};

/**
 * Flushes buffers.
 *
 * @api private
 */

HTTPTransport.prototype.handleRequest = function (req) {
  if (req.method == 'POST') {
    var buffer = ''
      , res = req.res
      , origin = req.headers.origin
      , headers = { 'Content-Length': 1 }
      , self = this;

    req.on('data', function (data) {
      buffer += data;
    });

    req.on('end', function () {
      res.writeHead(200, headers);
      res.end('1');

      self.onData(self.postEncoded ? qs.parse(buffer).d : buffer);
    });

    if (origin) {
      // https://developer.mozilla.org/En/HTTP_Access_Control
      headers['Access-Control-Allow-Origin'] = '*';

      if (req.headers.cookie) {
        headers['Access-Control-Allow-Credentials'] = 'true';
      }
    }
  } else {
    this.response = req.res;

    if (req.method == 'GET') {
      var self = this;

      this.pollTimeout = setTimeout(function () {
        self.packet({ type: 'noop' });
        self.log.debug(self.name + ' closed due to exceeded duration');
      }, this.manager.get('polling duration') * 1000);

      this.log.debug('setting poll timeout');
    }
  }
};

/**
 * Handles data payload.
 *
 * @api private
 */

HTTPTransport.prototype.onData = function (data) {
  var messages = parser.decodePayload(data);
  this.log.debug(this.name + ' received data packet', data);

  for (var i = 0, l = messages.length; i < l; i++) {
    this.onMessage(messages[i]);
  }
};

/**
 * Closes the request-response cycle
 *
 * @api private
 */

HTTPTransport.prototype.doClose = function () {
  this.response.end();
};

/**
 * Writes a payload of messages
 *
 * @api private
 */

HTTPTransport.prototype.payload = function (msgs) {
  this.write(parser.encodePayload(msgs));
};
<commit_msg>Implemented Polling#flush<commit_after>
/**
 * Module requirements.
 */

var Transport = require('../transport')
  , parser = require('../parser')
  , debug = require('debug')('engine.transport')

/**
 * Exports the constructor.
 */

module.exports = Polling;

/**
 * HTTP polling constructor.
 *
 * @api public.
 */

function Polling (req) {
  Transport.call(this, req);
};

/**
 * Inherits from Transport.
 *
 * @api public.
 */

Polling.prototype.__proto__ = Transport.prototype;

/**
 * Transport name
 *
 * @api public
 */

Polling.prototype.name = 'polling';

/**
 * Overrides onRequest.
 *
 * @param {http.ServerRequest}
 * @api private
 */

Polling.prototype.onRequest = function (req) {
  var res = req.res;

  if ('GET' == req.method) {
    this.onPollRequest(req, res);
  } else if ('POST' == req.method) {
    this.onDataRequest(req, res);
  } else {
    res.writeHead(500);
    res.end();
  }
};

/**
 * The client sends a request awaiting for us to send data.
 *
 * @api private
 */

Polling.prototype.onPollRequest = function (req, res) {
  // if there's an ongoing poll
  if (this.req) {
    // assert: this.res, '.req and .res should be (un)set together'
    this.onError('poll overlap from client');
    res.writeHead(500);
  } else {
    this.req = req;
    this.res = res;

    var self = this;

    function onClose () {
      self.onError('poll connection closed prematurely');
    }

    function cleanup () {
      req.removeListener('close', onClose);
      self.req = self.res = null;
    }

    req.cleanup = cleanup;
    req.on('close', onClose);

    this.buffer = false;
    this.flush();
  }
};

/**
 * The client sends a request with data.
 *
 * @api private
 */

Polling.prototype.onDataRequest = function (req, res) {
  if (this.dataReq) {
    // assert: this.dataRes, '.dataReq and .dataRes should be (un)set together'
    this.onError('data request overlap from client');
    res.writeHead(500);
  } else {
    this.dataReq = req;
    this.dataRes = res;

    var chunks = ''
      , self = this

    function cleanup () {
      chunks = '';
      req.removeListener('data', onData);
      req.removeListener('end', onEnd);
      req.removeListener('close', cleanup);
      self.dataReq = self.dataRes = null;
    };

    function onClose () {
      cleanup();
      self.onError('data request connection closed prematurely');
    };

    function onData () {
      chunks += data;
    };

    function onEnd () {
      self.onData(chunks);
      res.writeHead(204);
      res.end();
      cleanup();
    };

    req.abort = cleanup;
    req.on('close', onClose);
    req.on('data', onData);
    req.on('end', onEnd);
    req.setEncoding('utf8');
  }
};

/**
 * Processes the incoming data payload.
 */

Polling.prototype.onData = function (data) {
  var packets = parser.decodePayload(data);
  for (var i = 0, l = packets.length; i < l; i++) {
    this.onPacket(packets[i]);
  }
};

/**
 * Flushes buffers.
 *
 * @api private
 */

Polling.prototype.flush = function () {
  if (this.writeBuffer) {
    this.write(parser.encodePayload(this.writeBuffer));
    this.writeBuffer = null;
  }
};

/**
 * Handles data payload.
 *
 * @api private
 */

HTTPTransport.prototype.onData = function (data) {
  var messages = parser.decodePayload(data);
  this.log.debug(this.name + ' received data packet', data);

  for (var i = 0, l = messages.length; i < l; i++) {
    this.onMessage(messages[i]);
  }
};

/**
 * Closes the request-response cycle
 *
 * @api private
 */

HTTPTransport.prototype.doClose = function () {
  this.response.end();
};

/**
 * Writes a payload of messages
 *
 * @api private
 */

HTTPTransport.prototype.payload = function (msgs) {
  this.write(parser.encodePayload(msgs));
};
<|endoftext|>


<commit_before>/*
 * grunt
 * https://github.com/cowboy/grunt
 *
 * Copyright (c) 2012 "Cowboy" Ben Alman
 * Licensed under the MIT license.
 * http://benalman.com/about/license/
 */

var uglifyjs = require('uglify-js');
var deflate = require('deflate-js');

// ============================================================================
// TASKS
// ============================================================================

task.registerBasicTask('min', 'Minify files with UglifyJS.', function(data, name) {
  var files = file.expand(data);
  // Get banner, if specified. It would be nice if UglifyJS supported ignoring
  // all comments matching a certain pattern, like /*!...*/, but it doesn't.
  var banner = task.directive(files[0], function() { return null; });
  if (banner === null) {
    banner = '';
  } else {
    files.shift();
  }
  // Concat specified files. This should really be a single, pre-built (and
  // linted) file, but it supports any number of files.
  var max = task.helper('concat', files);

  // Concat banner + minified source.
  var min = banner + task.helper('uglify', max, config('uglify'));
  file.write(name, min);

  // Fail task if errors were logged.
  if (task.hadErrors()) { return false; }

  // Otherwise, print a success message.
  log.writeln('File "' + name + '" created.');

  // Report some sizes.
  var gzipSize = String(task.helper('gzip', min).length);
  log.writeln('Uncompressed size: ' + String(max.length).green + ' bytes.');
  log.writeln('Compressed size: ' + gzipSize.green + ' bytes gzipped (' + String(min.length).green + ' bytes minified).');
});

// ============================================================================
// HELPERS
// ============================================================================

// Minify with UglifyJS.
// From https://github.com/mishoo/UglifyJS
task.registerHelper('uglify', function(src, options) {
  if (!options) { options = {}; }
  var jsp = uglifyjs.parser;
  var pro = uglifyjs.uglify;
  var ast, pos;
  var msg = 'Minifying with UglifyJS...';
  verbose.write(msg);
  try {
    ast = jsp.parse(src);
    ast = pro.ast_mangle(ast, options.mangle || {});
    ast = pro.ast_squeeze(ast, options.squeeze || {});
    src = pro.gen_code(ast, options.codegen || {});
    // Success!
    verbose.ok();
    return src;
  } catch(e) {
    // Something went wrong.
    verbose.or.write(msg);
    pos = '['.red + ('L' + e.line).yellow + ':'.red + ('C' + e.col).yellow + ']'.red;
    log.error().writeln(pos + ' ' + (e.message + ' (position: ' + e.pos + ')').yellow);
    fail.warn('UglifyJS found errors.', 10);
  }
});

// Return deflated source.
task.registerHelper('gzip', function(src) {
  return src ? deflate.deflate(new Buffer(src)) : '';
});

// Strip /*...*/ comments from source.
task.registerHelper('strip_comments', function(src) {
  return src.replace(/\/\*[\s\S]*?\*\/\n*/g, '\n');
});
<commit_msg>Breaking min_max_info out into a separate helper, to facilitate re-use.<commit_after>/*
 * grunt
 * https://github.com/cowboy/grunt
 *
 * Copyright (c) 2012 "Cowboy" Ben Alman
 * Licensed under the MIT license.
 * http://benalman.com/about/license/
 */

var uglifyjs = require('uglify-js');
var deflate = require('deflate-js');

// ============================================================================
// TASKS
// ============================================================================

task.registerBasicTask('min', 'Minify files with UglifyJS.', function(data, name) {
  var files = file.expand(data);
  // Get banner, if specified. It would be nice if UglifyJS supported ignoring
  // all comments matching a certain pattern, like /*!...*/, but it doesn't.
  var banner = task.directive(files[0], function() { return null; });
  if (banner === null) {
    banner = '';
  } else {
    files.shift();
  }
  // Concat specified files. This should really be a single, pre-built (and
  // linted) file, but it supports any number of files.
  var max = task.helper('concat', files);

  // Concat banner + minified source.
  var min = banner + task.helper('uglify', max, config('uglify'));
  file.write(name, min);

  // Fail task if errors were logged.
  if (task.hadErrors()) { return false; }

  // Otherwise, print a success message....
  log.writeln('File "' + name + '" created.');
  // ...and report some size information.
  task.helper('min_max_info', min, max);
});

// ============================================================================
// HELPERS
// ============================================================================

// Minify with UglifyJS.
// From https://github.com/mishoo/UglifyJS
task.registerHelper('uglify', function(src, options) {
  if (!options) { options = {}; }
  var jsp = uglifyjs.parser;
  var pro = uglifyjs.uglify;
  var ast, pos;
  var msg = 'Minifying with UglifyJS...';
  verbose.write(msg);
  try {
    ast = jsp.parse(src);
    ast = pro.ast_mangle(ast, options.mangle || {});
    ast = pro.ast_squeeze(ast, options.squeeze || {});
    src = pro.gen_code(ast, options.codegen || {});
    // Success!
    verbose.ok();
    return src;
  } catch(e) {
    // Something went wrong.
    verbose.or.write(msg);
    pos = '['.red + ('L' + e.line).yellow + ':'.red + ('C' + e.col).yellow + ']'.red;
    log.error().writeln(pos + ' ' + (e.message + ' (position: ' + e.pos + ')').yellow);
    fail.warn('UglifyJS found errors.', 10);
  }
});

// Return deflated source.
task.registerHelper('gzip', function(src) {
  return src ? deflate.deflate(new Buffer(src)) : '';
});

// Output some size info about a file.
task.registerHelper('min_max_info', function(min, max) {
  var gzipSize = String(task.helper('gzip', min).length);
  log.writeln('Uncompressed size: ' + String(max.length).green + ' bytes.');
  log.writeln('Compressed size: ' + gzipSize.green + ' bytes gzipped (' + String(min.length).green + ' bytes minified).');
});

// Strip /*...*/ comments from source.
task.registerHelper('strip_comments', function(src) {
  return src.replace(/\/\*[\s\S]*?\*\/\n*/g, '\n');
});
<|endoftext|>


<commit_before>/**
 * [IL]
 * Library Import
 */
import React, { PropTypes } from 'react';

/**
 * [IS]
 * Style Import
 */
import Styles from './Styles/main.scss';
import Palette from 'theme/Palette';

/**
 * [IA]
 * Assets Import
 */
import Arrow from 'components/Assets/Arrow.js';

/**
 * [IBP]
 * Breakpoints
 */
import BP from 'lib/breakpoints';

function Common(props) {
    const { mediaType, breadcrumbs } = props;
    const items = breadcrumbs.map((item) => {
        return (

                { item.title }

        );
    });

    const arrow = (<Arrow className={ Styles.arrow } color={ Palette.midGray }/>);

    return (

                { items[0] }
                { arrow }
                { items[1] }
                { arrow }
                { items[2] }
                { BP.isPhonePortrait(mediaType) || BP.isTabletPortrait(mediaType) ? null : arrow }
                { BP.isPhonePortrait(mediaType) || BP.isTabletPortrait(mediaType) ? null : items[3] }

    );
}

/**
 * [CPT]
 * Component prop types
 */
Common.propTypes = {
    mediaType: PropTypes.string.isRequired,
    breadcrumbs: PropTypes.array.isRequired
};

/**
 * [IE]
 * Export
 */
export default Common;
<commit_msg>props completed<commit_after>/**
 * [IL]
 * Library Import
 */
import React, { PropTypes } from 'react';

/**
 * [IS]
 * Style Import
 */
import Styles from './Styles/main.scss';
import Palette from 'theme/Palette';

/**
 * [IA]
 * Assets Import
 */
import Arrow from 'components/Assets/Arrow.js';

function Common(props) {
    const { breadcrumbs } = props;

    const arrow = (

            <Arrow color={ Palette.midGray }/>

    );

    const items = breadcrumbs.map((item) => {
        return (

                { item.title }

        );
    })
    .reduce((row, item, i, arr) => {
        row.push(item);
        if (i < arr.length - 1) {
            row.push(arrow);
        }

        return row;
    }, []);

    console.log(items.props);

    return (

                { items }

    );
}

/**
 * [CPT]
 * Component prop types
 */
Common.propTypes = {
    breadcrumbs: PropTypes.array.isRequired
};

/**
 * [IE]
 * Export
 */
export default Common;
<|endoftext|>


<commit_before>// This is a JavaScript implementation of the fnmatch-like
// stuff that git uses in its .gitignore files.
// See `man 5 gitignore`.

module.exports = minimatch

var re = {}
  , path = require("path")

function minimatch (p, pattern) {
  if (!pattern) return false
  if (pattern.trim().charAt(0) === "#") return false
  if (!re[pattern]) re[pattern] = makeRe(pattern)
  // patterns that end in / can only match dirs
  // however, dirs also match the same thing that *doesn't*
  // end in a slash.
  //
  // a pattern with *no* slashes will match against either the full
  // path, or just the basename.
  return !!p.match(re[pattern])
      || ( p.substr(-1) === "/"
         && !!p.substr(0, -1).match(re[pattern]) )
      || (pattern.indexOf("/") === -1 && path.basename(p).match(re[pattern]))
}

function makeRe (pattern) {
  var braceDepth = 0
    , re = ""
    , escaping = false
    , oneStar = "[^\\/]*?"
    , twoStar = ".*?"
    , reSpecials = "().*{}+?[]^$/\\"
    , patternListStack = []
    , stateChar
    , negate = false
    , negating = false

  for ( var i = 0, len = pattern.length, c
      ; (i < len) && (c = pattern.charAt(i))
      ; i ++ ) {

    switch (c) {
      case "\\":
        if (escaping) {
          re += "\\\\" // must match literal \
          escaping = false
        } else {
          escaping = true
        }
        continue

      case "!":
        if (i === 0 || negating) {
          negate = !negate
          negating = true
          break
        }
        // fallthrough
      case "+":
      case "@":
      case "*":
      case "?":
        if (escaping) {
          re += "\\" + c
          escaping = false
        } else {
          if (c === "*" && stateChar === "*") { // **
            re += twoStar
            stateChar = false
          } else {
            stateChar = c
          }
        }
        continue

      case "(":
        if (escaping) {
          re += "\\("
          escaping = false
        } else if (stateChar) {
          plType = stateChar
          patternListStack.push(plType)
          re += stateChar === "!" ? "(?!" : "(:?"
          stateChar = false
        } else {
          re += "\\("
        }
        continue

      case ")":
        if (escaping) {
          re += "\\)"
          escaping = false
        } else if (patternListStack.length) {
          re += ")"
          plType = patternListStack.pop()
          switch (plType) {
            case "?":
            case "+":
            case "*": re += plType
            case "!":
            case "@": break
          }
        } else {
          re += "\\)"
        }
        continue

      case "|":
        if (escaping) {
          re += "\\|"
          escaping = false
        } else if (patternListStack.length) {
          re += "|"
        } else {
          re += "\\|"
        }
        continue

      // turns out these are the same in regexp and glob :)
      case "]":
      case "[":
        if (escaping) {
          re += "\\" + c
          escaping = false
        } else {
          re += c
        }
        continue

      case "{":
        if (escaping) {
          re += "\\{"
          escaping = false
        } else {
          re += "(:?"
          braceDepth ++
        }
        continue

      case "}":
        if (escaping || braceDepth === 0) {
          re += "\\}"
          escaping = false
        } else {
          re += ")"
          braceDepth --
        }
        continue

      case ",":
        if (escaping || braceDepth === 0) {
          re += ","
          escaping = false
        } else {
          re += "|"
        }
        continue

      default:
        if (stateChar) {
          // we had some state-tracking character
          // that wasn't consumed by this pass.
          switch (stateChar) {
            case "*":
              re += oneStar
              break
            case "?":
              re += "."
              break
            default:
              re += "\\"+stateChar
              break
          }
          stateChar = false
        }
        if (escaping) {
          // no need
          escaping = false
        } else if (reSpecials.indexOf(c) !== -1) {
          re += "\\"
        }
        re += c
    } // switch

    if (negating && c !== "!") negating = false

  } // for

  // handle trailing things that only matter at the very end.
  if (stateChar) {
    // we had some state-tracking character
    // that wasn't consumed by this pass.
    switch (stateChar) {
      case "*":
        re += oneStar
        break
      case "?":
        re += "."
        break
      default:
        re += "\\"+stateChar
        break
    }
    stateChar = false
  } else if (escaping) {
    re += "\\\\"
  }

  // must match entire pattern
  // ending in a * or ** will make it less strict.
  re = "^" + re + "$"

  // fail on the pattern, but allow anything otherwise.
  if (negate) re = "^(!?" + re + ").*$"

  return new RegExp(re)
}

if (require.main === module) {
  var tests = ["{a,b{c,d}}"
              ,"a.*$?"
              ,"\\{a,b{c,d}}"
              ,"a/{c/,}d/{e/,f/{g,h,i}/}k"
              ,"!*.bak"
              ,"!!*.bak"
              ,"!!!*.bak"
              ,"\\a\\b\\c\\d"
              ]
  tests.forEach(function (t) {
    console.log([t,makeRe(t)])
  })
}

<commit_msg>glob matching: 'foo' should match 'foo/'<commit_after>// This is a JavaScript implementation of the fnmatch-like
// stuff that git uses in its .gitignore files.
// See `man 5 gitignore`.

module.exports = minimatch

var re = {}
  , path = require("path")

function minimatch (p, pattern) {
  if (!pattern) return false
  if (pattern.trim().charAt(0) === "#") return false
  if (!re[pattern]) re[pattern] = makeRe(pattern)
  // patterns that end in / can only match dirs
  // however, dirs also match the same thing that *doesn't*
  // end in a slash.
  //
  // a pattern with *no* slashes will match against either the full
  // path, or just the basename.
  return !!p.match(re[pattern])
      || ( p.substr(-1) === "/"
         && !!p.slice(0, -1).match(re[pattern]) )
      || (pattern.indexOf("/") === -1 && path.basename(p).match(re[pattern]))
}

function makeRe (pattern) {
  var braceDepth = 0
    , re = ""
    , escaping = false
    , oneStar = "[^\\/]*?"
    , twoStar = ".*?"
    , reSpecials = "().*{}+?[]^$/\\"
    , patternListStack = []
    , stateChar
    , negate = false
    , negating = false

  for ( var i = 0, len = pattern.length, c
      ; (i < len) && (c = pattern.charAt(i))
      ; i ++ ) {

    switch (c) {
      case "\\":
        if (escaping) {
          re += "\\\\" // must match literal \
          escaping = false
        } else {
          escaping = true
        }
        continue

      case "!":
        if (i === 0 || negating) {
          negate = !negate
          negating = true
          break
        }
        // fallthrough
      case "+":
      case "@":
      case "*":
      case "?":
        if (escaping) {
          re += "\\" + c
          escaping = false
        } else {
          if (c === "*" && stateChar === "*") { // **
            re += twoStar
            stateChar = false
          } else {
            stateChar = c
          }
        }
        continue

      case "(":
        if (escaping) {
          re += "\\("
          escaping = false
        } else if (stateChar) {
          plType = stateChar
          patternListStack.push(plType)
          re += stateChar === "!" ? "(?!" : "(:?"
          stateChar = false
        } else {
          re += "\\("
        }
        continue

      case ")":
        if (escaping) {
          re += "\\)"
          escaping = false
        } else if (patternListStack.length) {
          re += ")"
          plType = patternListStack.pop()
          switch (plType) {
            case "?":
            case "+":
            case "*": re += plType
            case "!":
            case "@": break
          }
        } else {
          re += "\\)"
        }
        continue

      case "|":
        if (escaping) {
          re += "\\|"
          escaping = false
        } else if (patternListStack.length) {
          re += "|"
        } else {
          re += "\\|"
        }
        continue

      // turns out these are the same in regexp and glob :)
      case "]":
      case "[":
        if (escaping) {
          re += "\\" + c
          escaping = false
        } else {
          re += c
        }
        continue

      case "{":
        if (escaping) {
          re += "\\{"
          escaping = false
        } else {
          re += "(:?"
          braceDepth ++
        }
        continue

      case "}":
        if (escaping || braceDepth === 0) {
          re += "\\}"
          escaping = false
        } else {
          re += ")"
          braceDepth --
        }
        continue

      case ",":
        if (escaping || braceDepth === 0) {
          re += ","
          escaping = false
        } else {
          re += "|"
        }
        continue

      default:
        if (stateChar) {
          // we had some state-tracking character
          // that wasn't consumed by this pass.
          switch (stateChar) {
            case "*":
              re += oneStar
              break
            case "?":
              re += "."
              break
            default:
              re += "\\"+stateChar
              break
          }
          stateChar = false
        }
        if (escaping) {
          // no need
          escaping = false
        } else if (reSpecials.indexOf(c) !== -1) {
          re += "\\"
        }
        re += c
    } // switch

    if (negating && c !== "!") negating = false

  } // for

  // handle trailing things that only matter at the very end.
  if (stateChar) {
    // we had some state-tracking character
    // that wasn't consumed by this pass.
    switch (stateChar) {
      case "*":
        re += oneStar
        break
      case "?":
        re += "."
        break
      default:
        re += "\\"+stateChar
        break
    }
    stateChar = false
  } else if (escaping) {
    re += "\\\\"
  }

  // must match entire pattern
  // ending in a * or ** will make it less strict.
  re = "^" + re + "$"

  // fail on the pattern, but allow anything otherwise.
  if (negate) re = "^(!?" + re + ").*$"

  return new RegExp(re)
}

if (require.main === module) {
  var tests = ["{a,b{c,d}}"
              ,"a.*$?"
              ,"\\{a,b{c,d}}"
              ,"a/{c/,}d/{e/,f/{g,h,i}/}k"
              ,"!*.bak"
              ,"!!*.bak"
              ,"!!!*.bak"
              ,"\\a\\b\\c\\d"
              ]
  tests.forEach(function (t) {
    console.log([t,makeRe(t)])
  })
}

<|endoftext|>


<commit_before>var _ = require('underscore');

/*
 * Replace variables with actual values
 */
function replaceVariables(str, context) {
  return str.replace(/\#{platform}/, context.platform);
}

/*
 * Make sure the directory name has a trailing slash
 */
function normalizeDirName(dirName) {
  if (dirName.match(/\/$/)) {
    return dirName;
  }
  return dirName + '/';
}

module.exports = {
  mode: 'static',
  priority: 99,

  fileName: function(context, next, complete) {
    var resource = context.resource,
        src = resource.src || resource.sourceFile,
        dir = resource.dir;

    var root = '';

    if (resource.srcDir && resource.dest) {
      // srcDir is some prefix of src - we want to append the remaining part or src to dest
      src = src.substring(resource.srcDir.length + 1);
      root += normalizeDirName(resource.dest);
    } else if (resource.dest) {
      src = resource.dest;
    }

    root = replaceVariables(root, context);
    src = replaceVariables(src, context);

    var components = /(.*?)(?:\.([^.]+))?$/.exec(src);
    complete(undefined, {root: resource.root, path: root + components[1], extension: components[2]});
  },

  resource: function(context, next, complete) {
    next(function(err, resource) {
      if (_.isString(resource)) {
        resource = replaceVariables(resource, context);
      } else if (resource.src) {
        resource.src = replaceVariables(resource.src, context);
      }
      complete(undefined, resource);
    });
  }
};
<commit_msg>Fix regex escape<commit_after>var _ = require('underscore');

/*
 * Replace variables with actual values
 */
function replaceVariables(str, context) {
  return str.replace(/\#\{platform\}/, context.platform);
}

/*
 * Make sure the directory name has a trailing slash
 */
function normalizeDirName(dirName) {
  if (dirName.match(/\/$/)) {
    return dirName;
  }
  return dirName + '/';
}

module.exports = {
  mode: 'static',
  priority: 99,

  fileName: function(context, next, complete) {
    var resource = context.resource,
        src = resource.src || resource.sourceFile,
        dir = resource.dir;

    var root = '';

    if (resource.srcDir && resource.dest) {
      // srcDir is some prefix of src - we want to append the remaining part or src to dest
      src = src.substring(resource.srcDir.length + 1);
      root += normalizeDirName(resource.dest);
    } else if (resource.dest) {
      src = resource.dest;
    }

    root = replaceVariables(root, context);
    src = replaceVariables(src, context);

    var components = /(.*?)(?:\.([^.]+))?$/.exec(src);
    complete(undefined, {root: resource.root, path: root + components[1], extension: components[2]});
  },

  resource: function(context, next, complete) {
    next(function(err, resource) {
      if (_.isString(resource)) {
        resource = replaceVariables(resource, context);
      } else if (resource.src) {
        resource.src = replaceVariables(resource.src, context);
      }
      complete(undefined, resource);
    });
  }
};
<|endoftext|>


<commit_before>document.addEventListener( "DOMContentLoaded", function( e ){

    var printd = function( div, str ) {
        document.getElementById( div ).innerHTML = str + '<p>';
    };
    var cleard = function( div ) {
        document.getElementById( div ).innerHTML = '';
    };

    var canvas = document.getElementById( "test-canvas" );
    var resources = {};

    var game = function( engine ) {
        var math = engine.math;

        var CubicVR = engine.graphics.target.context;

        var PlayerComponent = engine.base.Component({
            type: 'Player'
        },
        function( options ) {

            options = options || {};
            var that = this;
            var service = engine.logic;

            this.onStartPlayerRotate = function( event ) {
                console.log( "onStartPlayerRotate" );
                console.log( event.type, event.data );
            };

            this.onStopPlayerRotate = function( event ) {
                console.log( "onStopPlayerRotate" );
                console.log( event.type, event.data );
            };

            this.onComponentOwnerChanged = function( e ){
                if( e.data.previous === null && this.owner !== null ) {
                    service.registerComponent( this.owner.id, this );
                }

                if( this.owner === null && e.data.previous !== null ) {
                    service.unregisterComponent( e.data.previous.id, this );
                }
            };

            this.onEntityManagerChanged = function( e ) {
                if( e.data.previous === null && e.data.current !== null && this.owner !== null ) {
                    service.registerComponent( this.owner.id, this );
                }

                if( e.data.previous !== null && e.data.current === null && this.owner !== null ) {
                    service.unregisterComponent( this.owner.id, this );
                }
            };

        });

        var run = function() {

            // Make a new space for our entities
            var space = new engine.core.Space();

            canvas = engine.graphics.target.element;

            var cube = new space.Entity({
                name: 'cube0',
                components: [
                             new engine.core.component.Transform({
                                 position: math.Vector3( 0, 0, 0 ),
                                 rotation: math.Vector3( 0, 0, 0 )
                             }),
                             new engine.graphics.component.Model({
                                 mesh: resources.mesh,
                                 material: resources.material
                             }),
                             new engine.input.component.Controller({
                                 onKey: function(e) {
                                     console.log( e.type, e.data );
                                     if( this.owner ) {
                                         new engine.core.Event({
                                             type: e.data.state === 'down' ? 'StartPlayerRotate' : 'StopPlayerRotate',
                                             data: {
                                                 direction: e.data.code === 'A' ? 'left' : 'right'
                                             }
                                         }).dispatch( [this.owner] );
                                     }
                                 }
                             }),
                             new PlayerComponent()
                             ]
            });

            var camera = new space.Entity({
                name: 'camera',
                components: [
                             new engine.core.component.Transform({
                                 position: math.Vector3( 0, 0, 10 )
                             }),
                             new engine.graphics.component.Camera({
                                 active: true,
                                 width: canvas.width,
                                 height: canvas.height,
                                 fov: 60
                             }),
                             new engine.graphics.component.Light({ intensity: 50 })
                             ]
            });
            camera.find( 'Camera' ).target = math.Vector3( 0, 0, 0 );

            var task = new engine.scheduler.Task({
                schedule: {
                    phase: engine.scheduler.phases.UPDATE,
                },
                callback: function() {
                    var delta = engine.scheduler.simulationTime.delta/1000;

                }
            });

            // Start the engine!
            engine.run();

        };

        engine.core.resource.get(
                [
                 {
                     type: engine.graphics.resource.Mesh,
                     url: 'procedural-mesh.js',
                     load: engine.core.resource.proceduralLoad,
                     onsuccess: function( mesh ) {
                         resources['mesh'] = mesh;
                     },
                     onfailure: function( error ) {
                     }
                 },
                 {
                     type: engine.graphics.resource.Material,
                     url: 'procedural-material.js',
                     load: engine.core.resource.proceduralLoad,
                     onsuccess: function( material ) {
                         resources['material'] = material;
                     },
                     onfailure: function( error ) {
                     }
                 },
                 ],
                 {
                    oncomplete: run
                 }
        );

    };

    gladius.create(
            {
                debug: true,
                services: {
                    graphics: {
                        src: 'graphics/service',
                        options: {
                            canvas: canvas
                        }
                    },
                    input: {
                        src: 'input/service',
                        options: {

                        }
                    },
                    logic: 'logic/game/service'
                }
            },
            game
    );

});
<commit_msg>Added some comments.<commit_after>document.addEventListener( "DOMContentLoaded", function( e ){

    var printd = function( div, str ) {
        document.getElementById( div ).innerHTML = str + '<p>';
    };
    var cleard = function( div ) {
        document.getElementById( div ).innerHTML = '';
    };

    var canvas = document.getElementById( "test-canvas" );
    var resources = {};

    var game = function( engine ) {
        var math = engine.math;

        var CubicVR = engine.graphics.target.context;

        var PlayerComponent = engine.base.Component({
            type: 'Player',
            depends: 'Transform'    // We're going to do some rotation, so we should have a transform
        },
        function( options ) {

            options = options || {};
            var that = this;
            var service = engine.logic; // This is a hack so that this component will have its message queue processed

            this.onStartPlayerRotate = function( event ) {
                console.log( "onStartPlayerRotate" );
                console.log( event.type, event.data );

                // Do some fun stuff here, like rotate.
                // We depend on transform, so it's OK to poke at this.owner.find( 'Transform' )
            };

            this.onStopPlayerRotate = function( event ) {
                console.log( "onStopPlayerRotate" );
                console.log( event.type, event.data );
            };

            // Boilerplate component registration; Lets our service know that we exist and want to do things
            this.onComponentOwnerChanged = function( e ){
                if( e.data.previous === null && this.owner !== null ) {
                    service.registerComponent( this.owner.id, this );
                }

                if( this.owner === null && e.data.previous !== null ) {
                    service.unregisterComponent( e.data.previous.id, this );
                }
            };

            this.onEntityManagerChanged = function( e ) {
                if( e.data.previous === null && e.data.current !== null && this.owner !== null ) {
                    service.registerComponent( this.owner.id, this );
                }

                if( e.data.previous !== null && e.data.current === null && this.owner !== null ) {
                    service.unregisterComponent( this.owner.id, this );
                }
            };

        });

        var run = function() {

            // Make a new space for our entities
            var space = new engine.core.Space();

            canvas = engine.graphics.target.element;

            var cube = new space.Entity({
                name: 'cube0',
                components: [
                             new engine.core.component.Transform({
                                 position: math.Vector3( 0, 0, 0 ),
                                 rotation: math.Vector3( 0, 0, 0 )
                             }),
                             new engine.graphics.component.Model({
                                 mesh: resources.mesh,
                                 material: resources.material
                             }),
                             new engine.input.component.Controller({
                                 onKey: function(e) {
                                     console.log( e.type, e.data );
                                     if( this.owner ) {
                                         // If we have an owner, dispatch a game event for it to enjoy
                                         new engine.core.Event({
                                             type: e.data.state === 'down' ? 'StartPlayerRotate' : 'StopPlayerRotate',
                                             data: {
                                                 direction: e.data.code === 'A' ? 'left' : 'right'
                                             }
                                         }).dispatch( [this.owner] );
                                     }
                                 }
                             }),
                             new PlayerComponent()
                             ]
            });

            var camera = new space.Entity({
                name: 'camera',
                components: [
                             new engine.core.component.Transform({
                                 position: math.Vector3( 0, 0, 10 )
                             }),
                             new engine.graphics.component.Camera({
                                 active: true,
                                 width: canvas.width,
                                 height: canvas.height,
                                 fov: 60
                             }),
                             new engine.graphics.component.Light({ intensity: 50 })
                             ]
            });
            camera.find( 'Camera' ).target = math.Vector3( 0, 0, 0 );

            var task = new engine.scheduler.Task({
                schedule: {
                    phase: engine.scheduler.phases.UPDATE,
                },
                callback: function() {
                    var delta = engine.scheduler.simulationTime.delta/1000;

                }
            });

            // Start the engine!
            engine.run();

        };

        engine.core.resource.get(
                [
                 {
                     type: engine.graphics.resource.Mesh,
                     url: 'procedural-mesh.js',
                     load: engine.core.resource.proceduralLoad,
                     onsuccess: function( mesh ) {
                         resources['mesh'] = mesh;
                     },
                     onfailure: function( error ) {
                     }
                 },
                 {
                     type: engine.graphics.resource.Material,
                     url: 'procedural-material.js',
                     load: engine.core.resource.proceduralLoad,
                     onsuccess: function( material ) {
                         resources['material'] = material;
                     },
                     onfailure: function( error ) {
                     }
                 },
                 ],
                 {
                    oncomplete: run
                 }
        );

    };

    gladius.create(
            {
                debug: true,
                services: {
                    graphics: {
                        src: 'graphics/service',
                        options: {
                            canvas: canvas
                        }
                    },
                    input: {
                        src: 'input/service',
                        options: {

                        }
                    },
                    logic: 'logic/game/service'
                }
            },
            game
    );

});
<|endoftext|>


<commit_before>/* $This file is distributed under the terms of the license in /doc/license.txt$ */

var customForm = {

    /* *** Initial page setup *** */

    onLoad: function() {
        this.mixIn();
        this.initObjects();
        this.initPage();
    },

    mixIn: function() {
        // Mix in the custom form utility methods
        vitro.utils.borrowMethods(vitro.customFormUtils, this);
    },

    // On page load, create references for easy access to form elements.
    // NB These must be assigned after the elements have been loaded onto the page.
    initObjects: function(){

        this.form = $('#content form');
        this.fullViewOnly = $('#fullViewOnly');
        this.button = $('#submit');
        this.requiredLegend = $('#requiredLegend');
        this.typeSelector = this.form.find('#typeSelector');

        // This is the label element for the field with name 'label'
        this.labelFieldLabel = $('label[for=' + $('#label').attr('id') + ']');
        // Get this on page load, so we can prepend to it. We can't just prepend to the current label text,
        // because it may have already been modified for a previous selection.
        this.baseLabelText = this.labelFieldLabel.html();

        this.or = $('span.or');
        this.cancel = this.form.find('.cancel');

        // These are classed rather than id'd in case we want more than one autocomplete on a form.
        this.acSelector = this.form.find('.acSelector');
        this.acSelection = this.form.find('.acSelection');

    },

    // Set up the form on page load
    initPage: function() {

        this.bindEventListeners();

        this.initAutocomplete();

        if (this.findValidationErrors()) {
            this.initFormFullView();
        } else {
            this.initFormTypeView();
        }

    },

    initFormTypeView: function() {

        this.hideFields(this.fullViewOnly);
        this.button.hide();
        this.requiredLegend.hide();
        this.or.hide();

        this.cancel.unbind('click');

    },

    initFormFullView: function() {

        this.fullViewOnly.show();
        this.or.show();
        this.requiredLegend.show();
        this.button.show();
        this.button.val('Create Publication');

        this.cancel.unbind('click');
        this.cancel.click(function() {
            customForm.clearFormData(); // clear any input and validation errors
            customForm.initFormTypeView();
            return false;
        });
    },

    // Bind event listeners that persist over the life of the page.
    bindEventListeners: function() {

        this.typeSelector.change(function() {
            var typeVal = $(this).val();
            // Set the type of individual that the autocomplete will search for.
            // We do this even if typeVal is empty, to clear out a previous value.
            customForm.resetAutocomplete(typeVal);
            if (typeVal.length) {
                customForm.labelFieldLabel.html(customForm.getSelectedTypeName() + ' ' + customForm.baseLabelText);
                customForm.initFormFullView();
            } else {
                // If no selection, go back to type view. This prevents problems like trying to run autocomplete
                // or submitting form without a type selection.
                customForm.initFormTypeView();
            }
        });
    },

    initAutocomplete: function() {

        var acFilter = this.getAcFilter();

        this.acCache = {};
        this.baseAcUrl = customFormData.acUrl;

        this.acSelector.autocomplete({
            minLength: 3,
            source: function(request, response) {
                if (request.term in customForm.acCache) {
                    // console.log('found term in cache');
                    response(customForm.acCache[request.term]);
                    return;
                }
                // console.log('not getting term from cache');

                $.ajax({
                    url: customForm.acUrl,
                    dataType: 'json',
                    data: request,
                    complete: function(xhr, status) {
                        // Not sure why, but we need an explicit json parse here. jQuery
                        // should parse the response text and return a json object.
                        var results = jQuery.parseJSON(xhr.responseText);

                        customForm.acCache[request.term] = results;

                        response(results);
                    }

                });
            },
            select: function(event, ui) {
                customForm.showAutocompleteSelection(ui);

            }
        });

    },

    getAcFilter: function() {
        // RY This gets put on the page for now. May want to put into a js file instead.
        var url = $('.sparqlQueryUrl').attr('id');

        $.ajax({
            url: customFormData.sparqlQueryUrl,
            data: {
                resultFormat: 'RS_JSON',
                query: customFormData.sparqlForAcFilter
            },
            success: function(data, status, xhr) {
                console.log(data);
            }
        })
    },

    // Reset some autocomplete values after type is changed
    resetAutocomplete: function(typeVal) {
        // Append the type parameter to the base autocomplete url
        var glue = this.baseAcUrl.indexOf('?') > -1 ? '&' : '?';
        this.acUrl = this.baseAcUrl + glue + 'type=' + typeVal;

        // Flush autocomplete cache when type is reset, since the cached values
        // are relevant only to the previous type.
        this.acCache = {};
    },

    showAutocompleteSelection: function(ui) {

        this.acSelector.hide();
        this.acSelector.attr('disabled', 'disabled');

        this.acSelection.find('label').html('Selected ' + this.getSelectedTypeName() + ':');
        this.acSelection.show();

        this.acReceiver.val(ui.item.uri);
        this.acSelectionInfo.html(ui.item.label);

        this.button.val('Add Publication');

        this.cancel.unbind('click');
        this.cancel.click(function() {
            // TODO Check out cancel action for authors form. Need to undo/empty some of the stuff above.
            // do we do it in the initfullview method, or here?
            customForm.initFormFullView();
            return false;
        });

    },

    getSelectedTypeName: function() {
        return this.typeSelector.find(':selected').html();
    }

};

$(document).ready(function() {
    customForm.onLoad();
});
<commit_msg>Making customFormWithAdvanceTypeSelection.js work where there isn't advance type selection.<commit_after>/* $This file is distributed under the terms of the license in /doc/license.txt$ */

var customForm = {

    /* *** Initial page setup *** */

    onLoad: function() {
        this.mixIn();
        this.initObjects();
        this.initPage();
    },

    mixIn: function() {
        // Mix in the custom form utility methods
        vitro.utils.borrowMethods(vitro.customFormUtils, this);
    },

    // On page load, create references for easy access to form elements.
    // NB These must be assigned after the elements have been loaded onto the page.
    initObjects: function(){

        this.form = $('#content form');
        this.fullViewOnly = $('#fullViewOnly');
        this.button = $('#submit');
        this.requiredLegend = $('#requiredLegend');
        this.typeSelector = this.form.find('#typeSelector');

        //if there isn't a two stage setup, don't do two stage behavior
        this.twoStageForm = ( this.typeSelector.length > 1 );

        // This is the label element for the field with name 'label'
        this.labelFieldLabel = $('label[for=' + $('#label').attr('id') + ']');
        // Get this on page load, so we can prepend to it. We can't just prepend to the current label text,
        // because it may have already been modified for a previous selection.
        this.baseLabelText = this.labelFieldLabel.html();

        this.or = $('span.or');
        this.cancel = this.form.find('.cancel');

        // These are classed rather than id'd in case we want more than one autocomplete on a form.
        this.acSelector = this.form.find('.acSelector');
        this.acSelection = this.form.find('.acSelection');

    },

    // Set up the form on page load
    initPage: function() {

        this.bindEventListeners();

        this.initAutocomplete();

        if (this.findValidationErrors() || ! this.twoStageForm) {
            this.initFormFullView();
        } else {
            this.initFormTypeView();
        }

    },

    initFormTypeView: function() {

        this.hideFields(this.fullViewOnly);
        this.button.hide();
        this.requiredLegend.hide();
        this.or.hide();

        if( twoStageForm ){
         this.cancel.unbind('click');
        }
    },

    initFormFullView: function() {

        this.fullViewOnly.show();
        this.or.show();
        this.requiredLegend.show();
        this.button.show();
        this.button.val('Create Publication');

        if( twoStageForm ){
        	this.cancel.unbind('click');
        	this.cancel.click(function() {
        		customForm.clearFormData(); // clear any input and validation errors
        		customForm.initFormTypeView();
        		return false;
        	});
        }
    },

    // Bind event listeners that persist over the life of the page.
    bindEventListeners: function() {

        this.typeSelector.change(function() {
            var typeVal = $(this).val();
            // Set the type of individual that the autocomplete will search for.
            // We do this even if typeVal is empty, to clear out a previous value.
            customForm.resetAutocomplete(typeVal);
            if (typeVal.length) {
                customForm.labelFieldLabel.html(customForm.getSelectedTypeName() + ' ' + customForm.baseLabelText);
                customForm.initFormFullView();
            } else {
                // If no selection, go back to type view. This prevents problems like trying to run autocomplete
                // or submitting form without a type selection.
                customForm.initFormTypeView();
            }
        });
    },

    initAutocomplete: function() {

        var acFilter = this.getAcFilter();

        this.acCache = {};
        this.baseAcUrl = customFormData.acUrl;

        this.acSelector.autocomplete({
            minLength: 3,
            source: function(request, response) {
                if (request.term in customForm.acCache) {
                    // console.log('found term in cache');
                    response(customForm.acCache[request.term]);
                    return;
                }
                // console.log('not getting term from cache');

                $.ajax({
                    url: customForm.acUrl,
                    dataType: 'json',
                    data: request,
                    complete: function(xhr, status) {
                        // Not sure why, but we need an explicit json parse here. jQuery
                        // should parse the response text and return a json object.
                        var results = jQuery.parseJSON(xhr.responseText);

                        customForm.acCache[request.term] = results;

                        response(results);
                    }

                });
            },
            select: function(event, ui) {
                customForm.showAutocompleteSelection(ui);

            }
        });

    },

    getAcFilter: function() {
        // RY This gets put on the page for now. May want to put into a js file instead.
        var url = $('.sparqlQueryUrl').attr('id');

        $.ajax({
            url: customFormData.sparqlQueryUrl,
            data: {
                resultFormat: 'RS_JSON',
                query: customFormData.sparqlForAcFilter
            },
            success: function(data, status, xhr) {
                console.log(data);
            }
        })
    },

    // Reset some autocomplete values after type is changed
    resetAutocomplete: function(typeVal) {
        // Append the type parameter to the base autocomplete url
        var glue = this.baseAcUrl.indexOf('?') > -1 ? '&' : '?';
        this.acUrl = this.baseAcUrl + glue + 'type=' + typeVal;

        // Flush autocomplete cache when type is reset, since the cached values
        // are relevant only to the previous type.
        this.acCache = {};
    },

    showAutocompleteSelection: function(ui) {

        this.acSelector.hide();
        this.acSelector.attr('disabled', 'disabled');

        this.acSelection.find('label').html('Selected ' + this.getSelectedTypeName() + ':');
        this.acSelection.show();

        this.acReceiver.val(ui.item.uri);
        this.acSelectionInfo.html(ui.item.label);

        this.button.val('Add Publication');

        if( this.twoStageForm){
        	this.cancel.unbind('click');
        	this.cancel.click(function() {
        		// TODO Check out cancel action for authors form. Need to undo/empty some of the stuff above.
        		//do we do it in the initfullview method, or here?
        		customForm.initFormFullView();
        		return false;
        	});
        }

    },

    getSelectedTypeName: function() {
        return this.typeSelector.find(':selected').html();
    }

};

$(document).ready(function() {
    customForm.onLoad();
});
<|endoftext|>


<commit_before>'use strict';

angular
 .module('dashboard')
 .controller('DashboardCtrl', ['$scope', '$mdDialog','databases', 'socket','$state', DashboardCtrl])
 .controller('CreateDatabaseCtrl', ['$scope', '$mdDialog', 'toaster', 'DbService', CreateDatabaseCtrl])
 .controller('DeleteDatabaseCtrl', ['$scope', '$mdDialog', 'toaster', 'DbService', DeleteDatabaseCtrl]);

function DashboardCtrl($scope, $mdDialog, databases, socket, $state) {

  socket.reqDbInfo();
  $scope.databases = databases;

  $scope.toggleDbSelect = function(db) {
    db.selected = !db.selected;
  };

  $scope.$on('db-info',function(event,data){

    var index = _.findIndex(databases,{'db_name' : data.name});
    data.size = (data.size).toFixed(2) + ' mb';

    $scope.databases[index].stats = {
      count : {
        val : (data.collections),
        icon : 'assignment'
      },
      size : {
        val : data.size,
        icon : 'view_column'
      },
      verified : {
        icon : (data.verified) ? 'check_circle' : 'warning'
      }
    };

  });

  $scope.viewCollections = function(index) {
    var database = $scope.databases[index].db_name;
    $state.go('home.collection',{'database' : database});
  };

  $scope.$on('db-create',function(event,data){
    $scope.databases.push(data);
  });

  $scope.showDailogForDb = function(ev) {

    $mdDialog.show({
      controller: CreateDatabaseCtrl,
      templateUrl: 'app/modules/dashboard/templates/createdb.view.html',
      parent: angular.element(document.body),
      clickOutsideToClose:true
    });

  };

  $scope.$on('db-delete',function(event,db_name){
    var index = _.findIndex(databases,{'db_name' : db_name});
    $scope.databases.splice(index,1);
    $scope.$apply();
  });

  $scope.deleteDb = function(dbName) {

    $mdDialog.show({
      controller: DeleteDatabaseCtrl,
      templateUrl: 'app/modules/dashboard/templates/deletedb.view.html',
      parent: angular.element(document.body),
      resolve : {
        database : function(){
          return dbName;
        }
      },
      clickOutsideToClose:true
    }).then(function(){
    },function(err){
      console.log(err);
    })
  }
}

function CreateDatabaseCtrl($scope, $mdDialog, toaster, DbService) {

  $scope.cancel = function() {
    $mdDialog.cancel();
  };

  $scope.create = function() {
    DbService.create($scope.dbname).then(function(){
      $mdDialog.hide();
      $scope.successPopup();
    });
  }

  $scope.successPopup = function(){
    toaster.pop({
      type: 'success',
      title: 'Congrats',
      body: 'Database has been created',
    });
  };

}

function DeleteDatabaseCtrl($scope, $mdDialog, toaster, DbService,database) {

  $scope.db = {
    'name' : database
  };

  $scope.cancel = function() {
    $mdDialog.cancel();
  };

  $scope.delete = function() {

    DbService.delete($scope.db)
      .then(function(result) {
        $mdDialog.hide();
        $scope.successPopup();
      },function() {
        console.log("error");
        $scope.failPopup()
      });

  }

  $scope.successPopup = function(){
    toaster.pop({
      type: 'success',
      body: 'Database has been deleted',
    });
  };

  $scope.failPopup = function() {
    toaster.pop({
      type: 'error',
      body: 'Problem while deleting database',
    });
  }

}<commit_msg>Add $scope.$apply() for db info update<commit_after>'use strict';

angular
 .module('dashboard')
 .controller('DashboardCtrl', ['$scope', '$mdDialog','databases', 'socket','$state', DashboardCtrl])
 .controller('CreateDatabaseCtrl', ['$scope', '$mdDialog', 'toaster', 'DbService', CreateDatabaseCtrl])
 .controller('DeleteDatabaseCtrl', ['$scope', '$mdDialog', 'toaster', 'DbService', DeleteDatabaseCtrl]);

function DashboardCtrl($scope, $mdDialog, databases, socket, $state) {

  socket.reqDbInfo();
  $scope.databases = databases;

  $scope.toggleDbSelect = function(db) {
    db.selected = !db.selected;
  };

  $scope.$on('db-info',function(event,data){

    var index = _.findIndex(databases,{'db_name' : data.name});
    data.size = (data.size).toFixed(2) + ' mb';

    $scope.databases[index].stats = {
      count : {
        val : (data.collections),
        icon : 'assignment'
      },
      size : {
        val : data.size,
        icon : 'view_column'
      },
      verified : {
        icon : (data.verified) ? 'check_circle' : 'warning'
      }
    };

    $scope.$apply();

  });

  $scope.viewCollections = function(index) {
    var database = $scope.databases[index].db_name;
    $state.go('home.collection',{'database' : database});
  };

  $scope.$on('db-create',function(event,data){
    $scope.databases.push(data);
  });

  $scope.showDailogForDb = function(ev) {

    $mdDialog.show({
      controller: CreateDatabaseCtrl,
      templateUrl: 'app/modules/dashboard/templates/createdb.view.html',
      parent: angular.element(document.body),
      clickOutsideToClose:true
    });

  };

  $scope.$on('db-delete',function(event,db_name){
    var index = _.findIndex(databases,{'db_name' : db_name});
    $scope.databases.splice(index,1);
    $scope.$apply();
  });

  $scope.deleteDb = function(dbName) {

    $mdDialog.show({
      controller: DeleteDatabaseCtrl,
      templateUrl: 'app/modules/dashboard/templates/deletedb.view.html',
      parent: angular.element(document.body),
      resolve : {
        database : function(){
          return dbName;
        }
      },
      clickOutsideToClose:true
    }).then(function(){
    },function(err){
      console.log(err);
    })
  }
}

function CreateDatabaseCtrl($scope, $mdDialog, toaster, DbService) {

  $scope.cancel = function() {
    $mdDialog.cancel();
  };

  $scope.create = function() {
    DbService.create($scope.dbname).then(function(){
      $mdDialog.hide();
      $scope.successPopup();
    });
  }

  $scope.successPopup = function(){
    toaster.pop({
      type: 'success',
      title: 'Congrats',
      body: 'Database has been created',
    });
  };

}

function DeleteDatabaseCtrl($scope, $mdDialog, toaster, DbService,database) {

  $scope.db = {
    'name' : database
  };

  $scope.cancel = function() {
    $mdDialog.cancel();
  };

  $scope.delete = function() {

    DbService.delete($scope.db)
      .then(function(result) {
        $mdDialog.hide();
        $scope.successPopup();
      },function() {
        console.log("error");
        $scope.failPopup()
      });

  }

  $scope.successPopup = function(){
    toaster.pop({
      type: 'success',
      body: 'Database has been deleted',
    });
  };

  $scope.failPopup = function() {
    toaster.pop({
      type: 'error',
      body: 'Problem while deleting database',
    });
  }

}<|endoftext|>


<commit_before>/*globals svgEditor */
svgEditor.readLang({
	lang: "mk",
	dir : "ltr",
	common: {
		"ok": "Зачувува",
		"cancel": "Откажи",
		"key_backspace": "backspace",
		"key_del": "delete",
		"key_down": "down",
		"key_up": "up",
		"more_opts": "More Options",
		"url": "URL",
		"width": "Width",
		"height": "Height"
	},
	misc: {
		"powered_by": "Powered by"
	},
	ui: {
		"toggle_stroke_tools": "Show/hide more stroke tools",
		"palette_info": "Кликни за да внесете промени бојата, промена клик да се промени бојата удар",
		"zoom_level": "Промена зум ниво",
		"panel_drag": "Drag left/right to resize side panel"
	},
	properties: {
		"id": "Identify the element",
		"fill_color": "Измени пополнете боја",
		"stroke_color": "Промена боја на мозочен удар",
		"stroke_style": "Промена удар цртичка стил",
		"stroke_width": "Промена удар Ширина",
		"pos_x": "Change X coordinate",
		"pos_y": "Change Y coordinate",
		"linecap_butt": "Linecap: Butt",
		"linecap_round": "Linecap: Round",
		"linecap_square": "Linecap: Square",
		"linejoin_bevel": "Linejoin: Bevel",
		"linejoin_miter": "Linejoin: Miter",
		"linejoin_round": "Linejoin: Round",
		"angle": "Change ротација агол",
		"blur": "Change gaussian blur value",
		"opacity": "Промена избрани ставка непроѕирноста",
		"circle_cx": "Промена круг на cx координира",
		"circle_cy": "Промена круг's cy координираат",
		"circle_r": "Промена на круг со радиус",
		"ellipse_cx": "Промена елипса's cx координираат",
		"ellipse_cy": "Промена на елипса cy координира",
		"ellipse_rx": "Промена на елипса x радиус",
		"ellipse_ry": "Промена на елипса у радиус",
		"line_x1": "Промена линија почетна x координира",
		"line_x2": "Промена линија завршува x координира",
		"line_y1": "Промена линија координираат почетна y",
		"line_y2": "Промена линија завршува y координира",
		"rect_height": "Промена правоаголник височина",
		"rect_width": "Промена правоаголник Ширина",
		"corner_radius": "Промена правоаголник Corner Radius",
		"image_width": "Промена Ширина на сликата",
		"image_height": "Промена на слика височина",
		"image_url": "Промена URL",
		"node_x": "Change node's x coordinate",
		"node_y": "Change node's y coordinate",
		"seg_type": "Change Segment type",
		"straight_segments": "Straight",
		"curve_segments": "Curve",
		"text_contents": "Промена текст содржина",
		"font_family": "Смени фонт Фамилија",
		"font_size": "Изменифонт Големина",
		"bold": "Задебелен текст",
		"italic": "Italic текст"
	},
	tools: {
		"main_menu": "Main Menu",
		"bkgnd_color_opac": "Смени позадина / непроѕирноста",
		"connector_no_arrow": "No arrow",
		"fitToContent": "Способен да Содржина",
		"fit_to_all": "Способен да сите содржина",
		"fit_to_canvas": "Побиране да платно",
		"fit_to_layer_content": "Способен да слој содржина",
		"fit_to_sel": "Способен да селекција",
		"align_relative_to": "Порамни во поглед на ...",
		"relativeTo": "во поглед на:",
		"страница": "страница",
		"largest_object": "најголемиот објект",
		"selected_objects": "избран објекти",
		"smallest_object": "најмалата објект",
		"new_doc": "Нови слики",
		"open_doc": "Отвори слика",
		"export_img": "Export",
		"save_doc": "Зачувај слика",
		"import_doc": "Import Image",
		"align_to_page": "Align Element to Page",
		"align_bottom": "Align Bottom",
		"align_center": "Центрирано",
		"align_left": "Порамни лево Порамни",
		"align_middle": "Израмни Среден",
		"align_right": "Порамни десно",
		"align_top": "Израмни почетокот",
		"mode_select": "Изберете ја алатката",
		"mode_fhpath": "Алатка за молив",
		"mode_line": "Line Tool",
		"mode_connect": "Connect two objects",
		"mode_rect": "Rectangle Tool",
		"mode_square": "Square Tool",
		"mode_fhrect": "Правоаголник слободна рака",
		"mode_ellipse": "Елипса",
		"mode_circle": "Круг",
		"mode_fhellipse": "Free-Hand Елипса",
		"mode_path": "Path Tool",
		"mode_shapelib": "Shape library",
		"mode_text": "Алатка за текст",
		"mode_image": "Алатка за сликата",
		"mode_zoom": "Алатка за зумирање",
		"mode_eyedropper": "Eye Dropper Tool",
		"no_embed": "NOTE: This image cannot be embedded. It will depend on this path to be displayed",
		"undo": "Врати",
		"redo": "Повтори",
		"tool_source": "Уреди Извор",
		"wireframe_mode": "Wireframe Mode",
		"toggle_grid": "Show/Hide Grid",
		"clone": "Clone Element(s)",
		"del": "Delete Element(s)",
		"group_elements": "Група на елементи",
		"make_link": "Make (hyper)link",
		"set_link_url": "Set link URL (leave empty to remove)",
		"to_path": "Convert to Path",
		"reorient_path": "Reorient path",
		"ungroup": "Ungroup Елементи",
		"docprops": "Својства на документот",
		"imagelib": "Image Library",
		"move_bottom": "Move to bottom",
		"move_top": "Поместување на почетокот",
		"node_clone": "Clone Node",
		"node_delete": "Delete Node",
		"node_link": "Link Control Points",
		"add_subpath": "Add sub-path",
		"openclose_path": "Open/close sub-path",
		"source_save": "Зачувува",
		"cut": "Cut",
		"copy": "Copy",
		"paste": "Paste",
		"paste_in_place": "Paste in Place",
		"delete": "Delete",
		"group": "Group",
		"move_front": "Bring to Front",
		"move_up": "Bring Forward",
		"move_down": "Send Backward",
		"move_back": "Send to Back"
	},
	layers: {
		"layer":"Layer",
		"layers": "Layers",
		"del": "Избриши Слој",
		"move_down": "Премести слој долу",
		"new": "Нов слој",
		"rename": "Преименувај слој",
		"move_up": "Премести слој горе",
		"dupe": "Duplicate Layer",
		"merge_down": "Merge Down",
		"merge_all": "Merge All",
		"move_elems_to": "Move elements to:",
		"move_selected": "Move selected elements to a different layer"
	},
	config: {
		"image_props": "Image Properties",
		"doc_title": "Title",
		"doc_dims": "Canvas Dimensions",
		"included_images": "Included Images",
		"image_opt_embed": "Embed data (local files)",
		"image_opt_ref": "Use file reference",
		"editor_prefs": "Editor Preferences",
		"icon_size": "Icon size",
		"language": "Language",
		"background": "Editor Background",
		"editor_img_url": "Image URL",
		"editor_bg_note": "Note: Background will not be saved with image.",
		"icon_large": "Large",
		"icon_medium": "Medium",
		"icon_small": "Small",
		"icon_xlarge": "Extra Large",
		"select_predefined": "Изберете предефинирани:",
		"units_and_rulers": "Units & Rulers",
		"show_rulers": "Show rulers",
		"base_unit": "Base Unit:",
		"grid": "Grid",
		"snapping_onoff": "Snapping on/off",
		"snapping_stepsize": "Snapping Step-Size:",
		"grid_color": "Grid color"
	},
	shape_cats: {
		"basic": "Basic",
		"object": "Objects",
		"symbol": "Symbols",
		"arrow": "Arrows",
		"flowchart": "Flowchart",
		"animal": "Animals",
		"game": "Cards & Chess",
		"dialog_balloon": "Dialog balloons",
		"electronics": "Electronics",
		"math": "Mathematical",
		"music": "Music",
		"misc": "Miscellaneous",
		"raphael_1": "raphaeljs.com set 1",
		"raphael_2": "raphaeljs.com set 2"
	},
	imagelib: {
		"select_lib": "Select an image library",
		"show_list": "Show library list",
		"import_single": "Import single",
		"import_multi": "Import multiple",
		"open": "Open as new document"
	},
	notification: {
		"invalidAttrValGiven":"Invalid value given",
		"noContentToFitTo":"No content to fit to",
		"dupeLayerName":"There is already a layer named that!",
		"enterUniqueLayerName":"Please enter a unique layer name",
		"enterNewLayerName":"Please enter the new layer name",
		"layerHasThatName":"Layer already has that name",
		"QmoveElemsToLayer":"Move selected elements to layer '%s'?",
		"QwantToClear":"Do you want to clear the drawing?\nThis will also erase your undo history!",
		"QwantToOpen":"Do you want to open a new file?\nThis will also erase your undo history!",
		"QerrorsRevertToSource":"There were parsing errors in your SVG source.\nRevert back to original SVG source?",
		"QignoreSourceChanges":"Ignore changes made to SVG source?",
		"featNotSupported":"Feature not supported",
		"enterNewImgURL":"Enter the new image URL",
		"defsFailOnSave": "NOTE: Due to a bug in your browser, this image may appear wrong (missing gradients or elements). It will however appear correct once actually saved.",
		"loadingImage":"Loading image, please wait...",
		"saveFromBrowser": "Select \"Save As...\" in your browser to save this image as a %s file.",
		"noteTheseIssues": "Also note the following issues: ",
		"unsavedChanges": "There are unsaved changes.",
		"enterNewLinkURL": "Enter the new hyperlink URL",
		"errorLoadingSVG": "Error: Unable to load SVG data",
		"URLloadFail": "Unable to load from URL",
		"retrieving": "Retrieving \"%s\"..."
	},
	confirmSetStorage: {
		message: "By default and where supported, SVG-Edit can store your editor "+
		"preferences and SVG content locally on your machine so you do not "+
		"need to add these back each time you load SVG-Edit. If, for privacy "+
		"reasons, you do not wish to store this information on your machine, "+
		"you can change away from the default option below.",
		storagePrefsAndContent: "Store preferences and SVG content locally",
		storagePrefsOnly: "Only store preferences locally",
		storagePrefs: "Store preferences locally",
		storageNoPrefsOrContent: "Do not store my preferences or SVG content locally",
		storageNoPrefs: "Do not store my preferences locally",
		rememberLabel: "Remember this choice?",
		rememberTooltip: "If you choose to opt out of storage while remembering this choice, the URL will change so as to avoid asking again."
	}
});<commit_msg>Update lang.mk.js<commit_after>/*globals svgEditor */
svgEditor.readLang({
	lang: "mk",
	dir : "ltr",
	common: {
		"ok": "Зачувува",
		"cancel": "Откажи",
		"key_backspace": "backspace",
		"key_del": "delete",
		"key_down": "down",
		"key_up": "up",
		"more_opts": "More Options",
		"url": "URL",
		"width": "Width",
		"height": "Height"
	},
	misc: {
		"powered_by": "Powered by"
	},
	ui: {
		"toggle_stroke_tools": "Show/hide more stroke tools",
		"palette_info": "Кликни за да внесете промени бојата, промена клик да се промени бојата удар",
		"zoom_level": "Промена зум ниво",
		"panel_drag": "Drag left/right to resize side panel"
	},
	properties: {
		"id": "Identify the element",
		"fill_color": "Измени пополнете боја",
		"stroke_color": "Промена боја на мозочен удар",
		"stroke_style": "Промена удар цртичка стил",
		"stroke_width": "Промена удар Ширина",
		"pos_x": "Change X coordinate",
		"pos_y": "Change Y coordinate",
		"linecap_butt": "Linecap: Butt",
		"linecap_round": "Linecap: Round",
		"linecap_square": "Linecap: Square",
		"linejoin_bevel": "Linejoin: Bevel",
		"linejoin_miter": "Linejoin: Miter",
		"linejoin_round": "Linejoin: Round",
		"angle": "Change ротација агол",
		"blur": "Change gaussian blur value",
		"opacity": "Промена избрани ставка непроѕирноста",
		"circle_cx": "Промена круг на cx координира",
		"circle_cy": "Промена круг's cy координираат",
		"circle_r": "Промена на круг со радиус",
		"ellipse_cx": "Промена елипса's cx координираат",
		"ellipse_cy": "Промена на елипса cy координира",
		"ellipse_rx": "Промена на елипса x радиус",
		"ellipse_ry": "Промена на елипса у радиус",
		"line_x1": "Промена линија почетна x координира",
		"line_x2": "Промена линија завршува x координира",
		"line_y1": "Промена линија координираат почетна y",
		"line_y2": "Промена линија завршува y координира",
		"rect_height": "Промена правоаголник височина",
		"rect_width": "Промена правоаголник Ширина",
		"corner_radius": "Промена правоаголник Corner Radius",
		"image_width": "Промена Ширина на сликата",
		"image_height": "Промена на слика височина",
		"image_url": "Промена URL",
		"node_x": "Change node's x coordinate",
		"node_y": "Change node's y coordinate",
		"seg_type": "Change Segment type",
		"straight_segments": "Straight",
		"curve_segments": "Curve",
		"text_contents": "Промена текст содржина",
		"font_family": "Смени фонт Фамилија",
		"font_size": "Изменифонт Големина",
		"bold": "Задебелен текст",
		"italic": "Italic текст"
	},
	tools: {
		"main_menu": "Main Menu",
		"bkgnd_color_opac": "Смени позадина / непроѕирноста",
		"connector_no_arrow": "No arrow",
		"fitToContent": "Способен да Содржина",
		"fit_to_all": "Способен да сите содржина",
		"fit_to_canvas": "Побиране да платно",
		"fit_to_layer_content": "Способен да слој содржина",
		"fit_to_sel": "Способен да селекција",
		"align_relative_to": "Порамни во поглед на ...",
		"relativeTo": "во поглед на:",
		"page": "страница",
		"largest_object": "најголемиот објект",
		"selected_objects": "избран објекти",
		"smallest_object": "најмалата објект",
		"new_doc": "Нови слики",
		"open_doc": "Отвори слика",
		"export_img": "Export",
		"save_doc": "Зачувај слика",
		"import_doc": "Import Image",
		"align_to_page": "Align Element to Page",
		"align_bottom": "Align Bottom",
		"align_center": "Центрирано",
		"align_left": "Порамни лево Порамни",
		"align_middle": "Израмни Среден",
		"align_right": "Порамни десно",
		"align_top": "Израмни почетокот",
		"mode_select": "Изберете ја алатката",
		"mode_fhpath": "Алатка за молив",
		"mode_line": "Line Tool",
		"mode_connect": "Connect two objects",
		"mode_rect": "Rectangle Tool",
		"mode_square": "Square Tool",
		"mode_fhrect": "Правоаголник слободна рака",
		"mode_ellipse": "Елипса",
		"mode_circle": "Круг",
		"mode_fhellipse": "Free-Hand Елипса",
		"mode_path": "Path Tool",
		"mode_shapelib": "Shape library",
		"mode_text": "Алатка за текст",
		"mode_image": "Алатка за сликата",
		"mode_zoom": "Алатка за зумирање",
		"mode_eyedropper": "Eye Dropper Tool",
		"no_embed": "NOTE: This image cannot be embedded. It will depend on this path to be displayed",
		"undo": "Врати",
		"redo": "Повтори",
		"tool_source": "Уреди Извор",
		"wireframe_mode": "Wireframe Mode",
		"toggle_grid": "Show/Hide Grid",
		"clone": "Clone Element(s)",
		"del": "Delete Element(s)",
		"group_elements": "Група на елементи",
		"make_link": "Make (hyper)link",
		"set_link_url": "Set link URL (leave empty to remove)",
		"to_path": "Convert to Path",
		"reorient_path": "Reorient path",
		"ungroup": "Ungroup Елементи",
		"docprops": "Својства на документот",
		"imagelib": "Image Library",
		"move_bottom": "Move to bottom",
		"move_top": "Поместување на почетокот",
		"node_clone": "Clone Node",
		"node_delete": "Delete Node",
		"node_link": "Link Control Points",
		"add_subpath": "Add sub-path",
		"openclose_path": "Open/close sub-path",
		"source_save": "Зачувува",
		"cut": "Cut",
		"copy": "Copy",
		"paste": "Paste",
		"paste_in_place": "Paste in Place",
		"delete": "Delete",
		"group": "Group",
		"move_front": "Bring to Front",
		"move_up": "Bring Forward",
		"move_down": "Send Backward",
		"move_back": "Send to Back"
	},
	layers: {
		"layer":"Layer",
		"layers": "Layers",
		"del": "Избриши Слој",
		"move_down": "Премести слој долу",
		"new": "Нов слој",
		"rename": "Преименувај слој",
		"move_up": "Премести слој горе",
		"dupe": "Duplicate Layer",
		"merge_down": "Merge Down",
		"merge_all": "Merge All",
		"move_elems_to": "Move elements to:",
		"move_selected": "Move selected elements to a different layer"
	},
	config: {
		"image_props": "Image Properties",
		"doc_title": "Title",
		"doc_dims": "Canvas Dimensions",
		"included_images": "Included Images",
		"image_opt_embed": "Embed data (local files)",
		"image_opt_ref": "Use file reference",
		"editor_prefs": "Editor Preferences",
		"icon_size": "Icon size",
		"language": "Language",
		"background": "Editor Background",
		"editor_img_url": "Image URL",
		"editor_bg_note": "Note: Background will not be saved with image.",
		"icon_large": "Large",
		"icon_medium": "Medium",
		"icon_small": "Small",
		"icon_xlarge": "Extra Large",
		"select_predefined": "Изберете предефинирани:",
		"units_and_rulers": "Units & Rulers",
		"show_rulers": "Show rulers",
		"base_unit": "Base Unit:",
		"grid": "Grid",
		"snapping_onoff": "Snapping on/off",
		"snapping_stepsize": "Snapping Step-Size:",
		"grid_color": "Grid color"
	},
	shape_cats: {
		"basic": "Basic",
		"object": "Objects",
		"symbol": "Symbols",
		"arrow": "Arrows",
		"flowchart": "Flowchart",
		"animal": "Animals",
		"game": "Cards & Chess",
		"dialog_balloon": "Dialog balloons",
		"electronics": "Electronics",
		"math": "Mathematical",
		"music": "Music",
		"misc": "Miscellaneous",
		"raphael_1": "raphaeljs.com set 1",
		"raphael_2": "raphaeljs.com set 2"
	},
	imagelib: {
		"select_lib": "Select an image library",
		"show_list": "Show library list",
		"import_single": "Import single",
		"import_multi": "Import multiple",
		"open": "Open as new document"
	},
	notification: {
		"invalidAttrValGiven":"Invalid value given",
		"noContentToFitTo":"No content to fit to",
		"dupeLayerName":"There is already a layer named that!",
		"enterUniqueLayerName":"Please enter a unique layer name",
		"enterNewLayerName":"Please enter the new layer name",
		"layerHasThatName":"Layer already has that name",
		"QmoveElemsToLayer":"Move selected elements to layer '%s'?",
		"QwantToClear":"Do you want to clear the drawing?\nThis will also erase your undo history!",
		"QwantToOpen":"Do you want to open a new file?\nThis will also erase your undo history!",
		"QerrorsRevertToSource":"There were parsing errors in your SVG source.\nRevert back to original SVG source?",
		"QignoreSourceChanges":"Ignore changes made to SVG source?",
		"featNotSupported":"Feature not supported",
		"enterNewImgURL":"Enter the new image URL",
		"defsFailOnSave": "NOTE: Due to a bug in your browser, this image may appear wrong (missing gradients or elements). It will however appear correct once actually saved.",
		"loadingImage":"Loading image, please wait...",
		"saveFromBrowser": "Select \"Save As...\" in your browser to save this image as a %s file.",
		"noteTheseIssues": "Also note the following issues: ",
		"unsavedChanges": "There are unsaved changes.",
		"enterNewLinkURL": "Enter the new hyperlink URL",
		"errorLoadingSVG": "Error: Unable to load SVG data",
		"URLloadFail": "Unable to load from URL",
		"retrieving": "Retrieving \"%s\"..."
	},
	confirmSetStorage: {
		message: "By default and where supported, SVG-Edit can store your editor "+
		"preferences and SVG content locally on your machine so you do not "+
		"need to add these back each time you load SVG-Edit. If, for privacy "+
		"reasons, you do not wish to store this information on your machine, "+
		"you can change away from the default option below.",
		storagePrefsAndContent: "Store preferences and SVG content locally",
		storagePrefsOnly: "Only store preferences locally",
		storagePrefs: "Store preferences locally",
		storageNoPrefsOrContent: "Do not store my preferences or SVG content locally",
		storageNoPrefs: "Do not store my preferences locally",
		rememberLabel: "Remember this choice?",
		rememberTooltip: "If you choose to opt out of storage while remembering this choice, the URL will change so as to avoid asking again."
	}
});
<|endoftext|>