<commit_before>/**
* @name utf8
* @module
*/
(function (jsPDF, global) {
    'use strict';
        var jsPDFAPI = jsPDF.API;
      /**************************************************/
      /* function : toHex                               */
      /* comment : Replace str with a hex string.       */
      /**************************************************/
      function toHex(str) {
        var hex = '';
        for (var i = 0; i < str.length; i++) {
          hex += '' + str.charCodeAt(i).toString(16);
        }
        return hex;
      }

      /***************************************************************************************************/
      /* function : pdfEscape16                                                                          */
      /* comment : The character id of a 2-byte string is converted to a hexadecimal number by obtaining */
      /*   the corresponding glyph id and width, and then adding padding to the string.                  */
      /***************************************************************************************************/
          var pdfEscape16 = jsPDFAPI.pdfEscape16 = function (text, font) {
            var widths = font.metadata.Unicode.widths;;
            var padz = ["", "0", "00", "000", "0000"];
            var ar = [""];
            for (var i = 0, l = text.length, t; i < l; ++i) {
              t = font.metadata.characterToGlyph(text.charCodeAt(i))
              font.metadata.glyIdsUsed.push(t);
              font.metadata.toUnicode[t] = text.charCodeAt(i);
              if (widths.indexOf(t) == -1) {
                widths.push(t);
                widths.push([parseInt(font.metadata.widthOfGlyph(t), 10)]);
              }
              if (t == '0') { //Spaces are not allowed in cmap.
                return ar.join("");
              } else {
                t = t.toString(16);
                ar.push(padz[4 - t.length], t);
              }
            }
            return ar.join("");
          };

          var toUnicodeCmap = function (map) {
              var code, codes, range, unicode, unicodeMap, _i, _len;
              unicodeMap = '/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CIDSystemInfo <<\n  /Registry (Adobe)\n  /Ordering (UCS)\n  /Supplement 0\n>> def\n/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n1 begincodespacerange\n<0000><ffff>\nendcodespacerange';
              codes = Object.keys(map).sort(function (a, b) {
                return a - b;
              });

              range = [];
              for (_i = 0, _len = codes.length; _i < _len; _i++) {
                code = codes[_i];
                if (range.length >= 100) {
                  unicodeMap += "\n" + range.length + " beginbfchar\n" + range.join('\n') + "\nendbfchar";
                  range = [];
                }
                unicode = ('0000' + map[code].toString(16)).slice(-4);
                code = ('0000' + (+code).toString(16)).slice(-4);
                range.push("<" + code + "><" + unicode + ">");
              }

              if (range.length) {
                unicodeMap += "\n" + range.length + " beginbfchar\n" + range.join('\n') + "\nendbfchar\n";
              }
              unicodeMap += 'endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend';
              return unicodeMap;
          };

          var identityHFunction = function (font, out, newObject, putStream) {

              if ((font.metadata instanceof jsPDF.API.TTFFont) && (font.encoding === 'Identity-H')) { //Tag with Identity-H
                var widths = font.metadata.Unicode.widths;
                var data = font.metadata.subset.encode(font.metadata.glyIdsUsed, 1);
                var pdfOutput = data;
                var pdfOutput2 = "";
                for (var i = 0; i < pdfOutput.length; i++) {
                  pdfOutput2 += String.fromCharCode(pdfOutput[i]);
                }
                var fontTable = newObject();
                putStream({data: pdfOutput2, addLength1: true});
                out('endobj');

                var cmap = newObject();
                var cmapData = toUnicodeCmap(font.metadata.toUnicode);
                putStream({data: cmapData, addLength1: true});
                out('endobj');

                var fontDescriptor = newObject();
                out('<<');
                out('/Type /FontDescriptor');
                out('/FontName /' + font.fontName);
                out('/FontFile2 ' + fontTable + ' 0 R');
                out('/FontBBox ' + jsPDF.API.PDFObject.convert(font.metadata.bbox));
                out('/Flags ' + font.metadata.flags);
                out('/StemV ' + font.metadata.stemV);
                out('/ItalicAngle ' + font.metadata.italicAngle);
                out('/Ascent ' + font.metadata.ascender);
                out('/Descent ' + font.metadata.decender);
                out('/CapHeight ' + font.metadata.capHeight);
                out('>>');
                out('endobj');

                var DescendantFont = newObject();
                out('<<');
                out('/Type /Font');
                out('/BaseFont /' + font.fontName);
                out('/FontDescriptor ' + fontDescriptor + ' 0 R');
                out('/W ' + jsPDF.API.PDFObject.convert(widths));
                out('/CIDToGIDMap /Identity');
                out('/DW 1000');
                out('/Subtype /CIDFontType2');
                out('/CIDSystemInfo');
                out('<<');
                out('/Supplement 0');
                out('/Registry (Adobe)');
                out('/Ordering (' + font.encoding + ')');
                out('>>');
                out('>>');
                out('endobj');

                font.objectNumber = newObject();
                out('<<');
                out('/Type /Font');
                out('/Subtype /Type0');
                out('/ToUnicode ' + cmap + ' 0 R');
                out('/BaseFont /' + font.fontName);
                out('/Encoding /' + font.encoding);
                out('/DescendantFonts [' + DescendantFont + ' 0 R]');
                out('>>');
                out('endobj');

                font.isAlreadyPutted = true;
              }
          }

          jsPDFAPI.events.push([
              'putFont'
              ,function(args) {
                  identityHFunction(args.font, args.out, args.newObject, args.putStream);
          }]);

        var winAnsiEncodingFunction = function (font, out, newObject, putStream) {

            if ((font.metadata instanceof jsPDF.API.TTFFont) && font.encoding === 'WinAnsiEncoding') { //Tag with WinAnsi encoding
              var widths = font.metadata.Unicode.widths;
              var data = font.metadata.rawData;
              var pdfOutput = data;
              var pdfOutput2 = "";
              for (var i = 0; i < pdfOutput.length; i++) {
                pdfOutput2 += String.fromCharCode(pdfOutput[i]);
              }
              var fontTable = newObject();
              putStream({data: pdfOutput2,addLength1: true});
              out('endobj');

              var cmap = newObject();
              var cmapData = toUnicodeCmap(font.metadata.toUnicode);
              putStream({data: cmapData, addLength1: true});
              out('endobj');

              var fontDescriptor = newObject();
              out('<<');
              out('/Descent ' + font.metadata.decender);
              out('/CapHeight ' + font.metadata.capHeight);
              out('/StemV ' + font.metadata.stemV);
              out('/Type /FontDescriptor');
              out('/FontFile2 ' + fontTable + ' 0 R');
              out('/Flags 96');
              out('/FontBBox ' + jsPDF.API.PDFObject.convert(font.metadata.bbox));
              out('/FontName /' + font.fontName);
              out('/ItalicAngle ' + font.metadata.italicAngle);
              out('/Ascent ' + font.metadata.ascender);
              out('>>');
              out('endobj');
              font.objectNumber = newObject();
              for (var i = 0; i < font.metadata.hmtx.widths.length; i++) {
                font.metadata.hmtx.widths[i] = parseInt(font.metadata.hmtx.widths[i] * (1000 / font.metadata.head.unitsPerEm)); //Change the width of Em units to Point units.
              }
              out('<</Subtype/TrueType/Type/Font/ToUnicode ' + cmap + ' 0 R/BaseFont/' + font.fontName + '/FontDescriptor ' + fontDescriptor + ' 0 R' + '/Encoding/' + font.encoding + ' /FirstChar 29 /LastChar 255 /Widths ' + jsPDF.API.PDFObject.convert(font.metadata.hmtx.widths) + '>>');
              out('endobj');
              font.isAlreadyPutted = true;
            }
        }

        jsPDFAPI.events.push([
            'putFont'
            ,function(args) {
                winAnsiEncodingFunction(args.font, args.out, args.newObject, args.putStream);
            }
        ]);

        var utf8TextFunction = function (args) {
            var text = args.text || '';
            var x = args.x;
            var y = args.y;
            var options = args.options || {};
            var tmp;
            var mutex = args.mutex || {};

            var pdfEscape = mutex.pdfEscape;
            var activeFontKey = mutex.activeFontKey;
            var fonts = mutex.fonts;
            var key, sum = 0,
              fontSize = mutex.activeFontSize, lineHeight = 0,
              axisCache;

            var str = '',
            v = 0,
            s = 0,
            tkey, widths, cmapConfirm;
            var strText = ''
            var attr;
            var key = activeFontKey;
            var encoding = fonts[key].encoding;

            if (fonts[key].encoding !== 'Identity-H') {
                return {
                    text : text,
                    x : x,
                    y : y,
                    options: options,
                    mutex: mutex
                };
            }
            var i = 0;
            strText = text;

            key = (attr) ? getFont(attr.font, attr.fontStyle) : activeFontKey;
            if (Object.prototype.toString.call(text) === '[object Array]') {
                strText = text[0];
            }
          for (s = 0; s < strText.length; s += 1) {
          if (fonts[key].metadata.hasOwnProperty('cmap')) {
              cmapConfirm = fonts[key].metadata.cmap.unicode.codeMap[strText[s].charCodeAt(0)];
              /*
             if (Object.prototype.toString.call(text) === '[object Array]') {
                var i = 0;
               // for (i = 0; i < text.length; i += 1) {
                    if (Object.prototype.toString.call(text[s]) === '[object Array]') {
                        cmapConfirm = fonts[key].metadata.cmap.unicode.codeMap[strText[s][0].charCodeAt(0)]; //Make sure the cmap has the corresponding glyph id
                    } else {

                    }
                //}

            } else {
                cmapConfirm = fonts[key].metadata.cmap.unicode.codeMap[strText[s].charCodeAt(0)]; //Make sure the cmap has the corresponding glyph id
            }*/
          }
            if (!cmapConfirm) {
                if (strText[s].charCodeAt(0) < 256 && fonts[key].metadata.hasOwnProperty('Unicode')) {
                  str += strText[s];
                } else {
                  str += '';
                }
            } else {
            str += strText[s];
            }
          }
          var result = '';
          if ((parseInt(key.slice(1)) < 14) || encoding === 'WinAnsiEncoding') { //For the default 13 font
                result = toHex(pdfEscape(str, key));
              } else if (encoding === 'Identity-H') {
                  result = pdfEscape16(str, fonts[key]);
              }
              mutex.isHex = true;

            return {
                text : result,
                x : x,
                y : y,
                options: options,
                mutex: mutex
            };
        }

        var utf8EscapeFunction = function(parms) {
            var text = parms.text || '',
            x = parms.x,
            y = parms.y,
            options = parms.options,
            mutex = parms.mutex
            var lang = options.lang;
            var tmpText = [];
            var tempPayLoad;
            var args = {
                    text : text,
                    x : x,
                    y : y,
                    options: options,
                    mutex: mutex
                };

            if (Object.prototype.toString.call(text) === '[object Array]') {
                var i = 0;
                for (i = 0; i < text.length; i += 1) {
                    if (Object.prototype.toString.call(text[i]) === '[object Array]') {
                        if (text[i].length === 3) {
                            tmpText.push([utf8TextFunction(Object.assign({}, args, {text: text[i][0]})).text, text[i][1], text[i][2]]);
                        } else {
                            tmpText.push(utf8TextFunction(Object.assign({}, args, {text: text[i]})).text);
                        }
                    } else {
                        tmpText.push(utf8TextFunction(Object.assign({}, args, {text: text[i]})).text);
                    }
                }
                parms.text = tmpText;

            } else {
                parms.text = utf8TextFunction(Object.assign({}, args, {text: text})).text;
            }
        }

        jsPDFAPI.events.push([
            'postProcessText'
            ,utf8EscapeFunction
        ]);

})(jsPDF, typeof self !== "undefined" && self || typeof global !== "undefined" && global || typeof window !== "undefined" && window || (Function ("return this"))());
<commit_msg>Fix custom font errors in IE (#2318)<commit_after>/**
* @name utf8
* @module
*/
(function (jsPDF, global) {
    'use strict';
        var jsPDFAPI = jsPDF.API;
      /**************************************************/
      /* function : toHex                               */
      /* comment : Replace str with a hex string.       */
      /**************************************************/
      function toHex(str) {
        var hex = '';
        for (var i = 0; i < str.length; i++) {
          hex += '' + str.charCodeAt(i).toString(16);
        }
        return hex;
      }

      /***************************************************************************************************/
      /* function : pdfEscape16                                                                          */
      /* comment : The character id of a 2-byte string is converted to a hexadecimal number by obtaining */
      /*   the corresponding glyph id and width, and then adding padding to the string.                  */
      /***************************************************************************************************/
          var pdfEscape16 = jsPDFAPI.pdfEscape16 = function (text, font) {
            var widths = font.metadata.Unicode.widths;;
            var padz = ["", "0", "00", "000", "0000"];
            var ar = [""];
            for (var i = 0, l = text.length, t; i < l; ++i) {
              t = font.metadata.characterToGlyph(text.charCodeAt(i))
              font.metadata.glyIdsUsed.push(t);
              font.metadata.toUnicode[t] = text.charCodeAt(i);
              if (widths.indexOf(t) == -1) {
                widths.push(t);
                widths.push([parseInt(font.metadata.widthOfGlyph(t), 10)]);
              }
              if (t == '0') { //Spaces are not allowed in cmap.
                return ar.join("");
              } else {
                t = t.toString(16);
                ar.push(padz[4 - t.length], t);
              }
            }
            return ar.join("");
          };

          var toUnicodeCmap = function (map) {
              var code, codes, range, unicode, unicodeMap, _i, _len;
              unicodeMap = '/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CIDSystemInfo <<\n  /Registry (Adobe)\n  /Ordering (UCS)\n  /Supplement 0\n>> def\n/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n1 begincodespacerange\n<0000><ffff>\nendcodespacerange';
              codes = Object.keys(map).sort(function (a, b) {
                return a - b;
              });

              range = [];
              for (_i = 0, _len = codes.length; _i < _len; _i++) {
                code = codes[_i];
                if (range.length >= 100) {
                  unicodeMap += "\n" + range.length + " beginbfchar\n" + range.join('\n') + "\nendbfchar";
                  range = [];
                }

                if (map[code] !== undefined && map[code] !== null && typeof map[code].toString === "function") {
                  unicode = ('0000' + map[code].toString(16)).slice(-4);
                  code = ('0000' + (+code).toString(16)).slice(-4);
                  range.push("<" + code + "><" + unicode + ">");
                }
              }

              if (range.length) {
                unicodeMap += "\n" + range.length + " beginbfchar\n" + range.join('\n') + "\nendbfchar\n";
              }
              unicodeMap += 'endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend';
              return unicodeMap;
          };

          var identityHFunction = function (font, out, newObject, putStream) {

              if ((font.metadata instanceof jsPDF.API.TTFFont) && (font.encoding === 'Identity-H')) { //Tag with Identity-H
                var widths = font.metadata.Unicode.widths;
                var data = font.metadata.subset.encode(font.metadata.glyIdsUsed, 1);
                var pdfOutput = data;
                var pdfOutput2 = "";
                for (var i = 0; i < pdfOutput.length; i++) {
                  pdfOutput2 += String.fromCharCode(pdfOutput[i]);
                }
                var fontTable = newObject();
                putStream({data: pdfOutput2, addLength1: true});
                out('endobj');

                var cmap = newObject();
                var cmapData = toUnicodeCmap(font.metadata.toUnicode);
                putStream({data: cmapData, addLength1: true});
                out('endobj');

                var fontDescriptor = newObject();
                out('<<');
                out('/Type /FontDescriptor');
                out('/FontName /' + font.fontName);
                out('/FontFile2 ' + fontTable + ' 0 R');
                out('/FontBBox ' + jsPDF.API.PDFObject.convert(font.metadata.bbox));
                out('/Flags ' + font.metadata.flags);
                out('/StemV ' + font.metadata.stemV);
                out('/ItalicAngle ' + font.metadata.italicAngle);
                out('/Ascent ' + font.metadata.ascender);
                out('/Descent ' + font.metadata.decender);
                out('/CapHeight ' + font.metadata.capHeight);
                out('>>');
                out('endobj');

                var DescendantFont = newObject();
                out('<<');
                out('/Type /Font');
                out('/BaseFont /' + font.fontName);
                out('/FontDescriptor ' + fontDescriptor + ' 0 R');
                out('/W ' + jsPDF.API.PDFObject.convert(widths));
                out('/CIDToGIDMap /Identity');
                out('/DW 1000');
                out('/Subtype /CIDFontType2');
                out('/CIDSystemInfo');
                out('<<');
                out('/Supplement 0');
                out('/Registry (Adobe)');
                out('/Ordering (' + font.encoding + ')');
                out('>>');
                out('>>');
                out('endobj');

                font.objectNumber = newObject();
                out('<<');
                out('/Type /Font');
                out('/Subtype /Type0');
                out('/ToUnicode ' + cmap + ' 0 R');
                out('/BaseFont /' + font.fontName);
                out('/Encoding /' + font.encoding);
                out('/DescendantFonts [' + DescendantFont + ' 0 R]');
                out('>>');
                out('endobj');

                font.isAlreadyPutted = true;
              }
          }

          jsPDFAPI.events.push([
              'putFont'
              ,function(args) {
                  identityHFunction(args.font, args.out, args.newObject, args.putStream);
          }]);

        var winAnsiEncodingFunction = function (font, out, newObject, putStream) {

            if ((font.metadata instanceof jsPDF.API.TTFFont) && font.encoding === 'WinAnsiEncoding') { //Tag with WinAnsi encoding
              var widths = font.metadata.Unicode.widths;
              var data = font.metadata.rawData;
              var pdfOutput = data;
              var pdfOutput2 = "";
              for (var i = 0; i < pdfOutput.length; i++) {
                pdfOutput2 += String.fromCharCode(pdfOutput[i]);
              }
              var fontTable = newObject();
              putStream({data: pdfOutput2,addLength1: true});
              out('endobj');

              var cmap = newObject();
              var cmapData = toUnicodeCmap(font.metadata.toUnicode);
              putStream({data: cmapData, addLength1: true});
              out('endobj');

              var fontDescriptor = newObject();
              out('<<');
              out('/Descent ' + font.metadata.decender);
              out('/CapHeight ' + font.metadata.capHeight);
              out('/StemV ' + font.metadata.stemV);
              out('/Type /FontDescriptor');
              out('/FontFile2 ' + fontTable + ' 0 R');
              out('/Flags 96');
              out('/FontBBox ' + jsPDF.API.PDFObject.convert(font.metadata.bbox));
              out('/FontName /' + font.fontName);
              out('/ItalicAngle ' + font.metadata.italicAngle);
              out('/Ascent ' + font.metadata.ascender);
              out('>>');
              out('endobj');
              font.objectNumber = newObject();
              for (var i = 0; i < font.metadata.hmtx.widths.length; i++) {
                font.metadata.hmtx.widths[i] = parseInt(font.metadata.hmtx.widths[i] * (1000 / font.metadata.head.unitsPerEm)); //Change the width of Em units to Point units.
              }
              out('<</Subtype/TrueType/Type/Font/ToUnicode ' + cmap + ' 0 R/BaseFont/' + font.fontName + '/FontDescriptor ' + fontDescriptor + ' 0 R' + '/Encoding/' + font.encoding + ' /FirstChar 29 /LastChar 255 /Widths ' + jsPDF.API.PDFObject.convert(font.metadata.hmtx.widths) + '>>');
              out('endobj');
              font.isAlreadyPutted = true;
            }
        }

        jsPDFAPI.events.push([
            'putFont'
            ,function(args) {
                winAnsiEncodingFunction(args.font, args.out, args.newObject, args.putStream);
            }
        ]);

        var utf8TextFunction = function (args) {
            var text = args.text || '';
            var x = args.x;
            var y = args.y;
            var options = args.options || {};
            var tmp;
            var mutex = args.mutex || {};

            var pdfEscape = mutex.pdfEscape;
            var activeFontKey = mutex.activeFontKey;
            var fonts = mutex.fonts;
            var key, sum = 0,
              fontSize = mutex.activeFontSize, lineHeight = 0,
              axisCache;

            var str = '',
            v = 0,
            s = 0,
            tkey, widths, cmapConfirm;
            var strText = ''
            var attr;
            var key = activeFontKey;
            var encoding = fonts[key].encoding;

            if (fonts[key].encoding !== 'Identity-H') {
                return {
                    text : text,
                    x : x,
                    y : y,
                    options: options,
                    mutex: mutex
                };
            }
            var i = 0;
            strText = text;

            key = (attr) ? getFont(attr.font, attr.fontStyle) : activeFontKey;
            if (Object.prototype.toString.call(text) === '[object Array]') {
                strText = text[0];
            }
          for (s = 0; s < strText.length; s += 1) {
          if (fonts[key].metadata.hasOwnProperty('cmap')) {
              cmapConfirm = fonts[key].metadata.cmap.unicode.codeMap[strText[s].charCodeAt(0)];
              /*
             if (Object.prototype.toString.call(text) === '[object Array]') {
                var i = 0;
               // for (i = 0; i < text.length; i += 1) {
                    if (Object.prototype.toString.call(text[s]) === '[object Array]') {
                        cmapConfirm = fonts[key].metadata.cmap.unicode.codeMap[strText[s][0].charCodeAt(0)]; //Make sure the cmap has the corresponding glyph id
                    } else {

                    }
                //}

            } else {
                cmapConfirm = fonts[key].metadata.cmap.unicode.codeMap[strText[s].charCodeAt(0)]; //Make sure the cmap has the corresponding glyph id
            }*/
          }
            if (!cmapConfirm) {
                if (strText[s].charCodeAt(0) < 256 && fonts[key].metadata.hasOwnProperty('Unicode')) {
                  str += strText[s];
                } else {
                  str += '';
                }
            } else {
            str += strText[s];
            }
          }
          var result = '';
          if ((parseInt(key.slice(1)) < 14) || encoding === 'WinAnsiEncoding') { //For the default 13 font
                result = toHex(pdfEscape(str, key));
              } else if (encoding === 'Identity-H') {
                  result = pdfEscape16(str, fonts[key]);
              }
              mutex.isHex = true;

            return {
                text : result,
                x : x,
                y : y,
                options: options,
                mutex: mutex
            };
        }

        var utf8EscapeFunction = function(parms) {
            var text = parms.text || '',
            x = parms.x,
            y = parms.y,
            options = parms.options,
            mutex = parms.mutex
            var lang = options.lang;
            var tmpText = [];
            var tempPayLoad;
            var args = {
                    text : text,
                    x : x,
                    y : y,
                    options: options,
                    mutex: mutex
                };

            if (Object.prototype.toString.call(text) === '[object Array]') {
                var i = 0;
                for (i = 0; i < text.length; i += 1) {
                    if (Object.prototype.toString.call(text[i]) === '[object Array]') {
                        if (text[i].length === 3) {
                            tmpText.push([utf8TextFunction(Object.assign({}, args, {text: text[i][0]})).text, text[i][1], text[i][2]]);
                        } else {
                            tmpText.push(utf8TextFunction(Object.assign({}, args, {text: text[i]})).text);
                        }
                    } else {
                        tmpText.push(utf8TextFunction(Object.assign({}, args, {text: text[i]})).text);
                    }
                }
                parms.text = tmpText;

            } else {
                parms.text = utf8TextFunction(Object.assign({}, args, {text: text})).text;
            }
        }

        jsPDFAPI.events.push([
            'postProcessText'
            ,utf8EscapeFunction
        ]);

})(jsPDF, typeof self !== "undefined" && self || typeof global !== "undefined" && global || typeof window !== "undefined" && window || (Function ("return this"))());
<|endoftext|>


<commit_before>/**
 *		Name: Util
 *
 *		Requires: app, jQuery
 */

var admanager = ( function( app, $ ) {

	app.util = ( function( $ ) {

		var _name = 'Util',
			_debug_enable = false
		;

		/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

		function init() {

			debug( _name + ': initialized' );

			_init_array_remove();
			_set_window_request_animation_frame();

			return app;

		}

		/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

		function debug( obj ) {

			if ( ! _debug_enable ) return;

			if ( ( typeof console == "object" ) && ( console.log ) ) {

				console.log( obj );

			}

		}

		/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

		/**
		 * Return difference between arrays
		 *
		 * @param  array array
		 * @param  array values
		 * @return array diff
		 */
		function difference( array, values ) {

			var diff = []
			;

			$.grep( array, function( element ) {
				if ( $.inArray( element, values ) === -1 ) diff.push( element );
			});

			return diff;

		}

		/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

		/**
		 * Is Mobile
		 *
		 * @return bool
		 */
		function is_mobile() {

			return $(window).width() < 768 ? true : false;

		}

		/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

		/**
		 * Set window.requestAnimationFrame
		 *
		 * requestAnimationFrame Firefox 23 / IE 10 / Chrome / Safari 7 (incl. iOS)
		 * mozRequestAnimationFrame Firefox < 23
		 * webkitRequestAnimationFrame Older versions of Safari / Chrome
		 */
		function _set_window_request_animation_frame() {

			window.requestAnimationFrame = window.requestAnimationFrame ||
				window.mozRequestAnimationFrame ||
				window.webkitRequestAnimationFrame ||
				window.oRequestAnimationFrame
			;

		}

		/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

		function _init_array_remove() {

			// Array Remove - By John Resig (MIT Licensed)
			Array.prototype.remove = function(from, to) {
				var rest = this.slice((to || from) + 1 || this.length);
				this.length = from < 0 ? this.length + from : from;
				return this.push.apply(this, rest);
			};

		}

		/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

		function page_config() {
			return {};
		}

		/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

		return {
			init        : init,
			debug       : debug,
			difference  : difference,
			is_mobile   : is_mobile,
			page_config : page_config
		};

	}( $ ) );

	return app;

}( admanager || {}, jQuery ) );<commit_msg>Read page config object<commit_after>/**
 *		Name: Util
 *
 *		Requires: app, jQuery
 */

var admanager = ( function( app, $ ) {

	app.util = ( function( $ ) {

		var _name = 'Util',
			_debug_enable = false
		;

		/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

		function init() {

			debug( _name + ': initialized' );

			_init_array_remove();
			_set_window_request_animation_frame();

			return app;

		}

		/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

		function debug( obj ) {

			if ( ! _debug_enable ) return;

			if ( ( typeof console == "object" ) && ( console.log ) ) {

				console.log( obj );

			}

		}

		/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

		/**
		 * Return difference between arrays
		 *
		 * @param  array array
		 * @param  array values
		 * @return array diff
		 */
		function difference( array, values ) {

			var diff = []
			;

			$.grep( array, function( element ) {
				if ( $.inArray( element, values ) === -1 ) diff.push( element );
			});

			return diff;

		}

		/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

		/**
		 * Is Mobile
		 *
		 * @return bool
		 */
		function is_mobile() {

			return $(window).width() < 768 ? true : false;

		}

		/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

		/**
		 * Set window.requestAnimationFrame
		 *
		 * requestAnimationFrame Firefox 23 / IE 10 / Chrome / Safari 7 (incl. iOS)
		 * mozRequestAnimationFrame Firefox < 23
		 * webkitRequestAnimationFrame Older versions of Safari / Chrome
		 */
		function _set_window_request_animation_frame() {

			window.requestAnimationFrame = window.requestAnimationFrame ||
				window.mozRequestAnimationFrame ||
				window.webkitRequestAnimationFrame ||
				window.oRequestAnimationFrame
			;

		}

		/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

		function _init_array_remove() {

			// Array Remove - By John Resig (MIT Licensed)
			Array.prototype.remove = function(from, to) {
				var rest = this.slice((to || from) + 1 || this.length);
				this.length = from < 0 ? this.length + from : from;
				return this.push.apply(this, rest);
			};

		}

		/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

		/**
		 * Get page config
		 *
		 * @return object
		 */
		function page_config() {
			if ( typeof app.config.page_config_selector === 'undefined' ) return {};

			return $( app.config.page_config_selector ).data('page-config');
		}

		/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

		return {
			init        : init,
			debug       : debug,
			difference  : difference,
			is_mobile   : is_mobile,
			page_config : page_config
		};

	}( $ ) );

	return app;

}( admanager || {}, jQuery ) );<|endoftext|>


<commit_before>/**
 * Convenience function for instantiating a new elasticlunr index and configuring it
 * with the default pipeline functions and the passed config function.
 *
 * When using this convenience function a new index will be created with the
 * following functions already in the pipeline:
 *
 * 1. elasticlunr.trimmer - trim non-word character
 * 2. elasticlunr.StopWordFilter - filters out any stop words before they enter the
 * index
 * 3. elasticlunr.stemmer - stems the tokens before entering the index.
 *
 *
 * Example:
 *
 *     var idx = elasticlunr(function () {
 *       this.addField('id');
 *       this.addField('title');
 *       this.addField('body');
 *
 *       //this.setRef('id'); // default ref is 'id'
 *
 *       this.pipeline.add(function () {
 *         // some custom pipeline function
 *       });
 *     });
 *
 *    idx.addDoc({
 *      id: 1,
 *      title: 'Oracle released database 12g',
 *      body: 'Yestaday, Oracle has released their latest database, named 12g, more robust. this product will increase Oracle profit.'
 *    });
 *
 *    idx.addDoc({
 *      id: 2,
 *      title: 'Oracle released annual profit report',
 *      body: 'Yestaday, Oracle has released their annual profit report of 2015, total profit is 12.5 Billion.'
 *    });
 *
 *    # simple search
 *    idx.search('oracle database');
 *
 *    # search with query-time boosting
 *    idx.search('oracle database', {fields: {title: {boost: 2}, body: {boost: 1}}});
 *
 * @param {Function} config A function that will be called with the new instance
 * of the elasticlunr.Index as both its context and first parameter. It can be used to
 * customize the instance of new elasticlunr.Index.
 * @namespace
 * @module
 * @return {elasticlunr.Index}
 *
 */
var elasticlunr = function (config) {
  var idx = new elasticlunr.Index;

  idx.pipeline.add(
    elasticlunr.trimmer,
    elasticlunr.stopWordFilter,
    elasticlunr.stemmer
  );

  if (config) config.call(idx, idx);

  return idx;
};

elasticlunr.version = "@VERSION";
<commit_msg>add copyright<commit_after>/*!
 * elasticlunr.js
 * Copyright (C) @YEAR Oliver Nightingale
 * Copyright (C) @YEAR Wei Song
 */

/**
 * Convenience function for instantiating a new elasticlunr index and configuring it
 * with the default pipeline functions and the passed config function.
 *
 * When using this convenience function a new index will be created with the
 * following functions already in the pipeline:
 *
 * 1. elasticlunr.trimmer - trim non-word character
 * 2. elasticlunr.StopWordFilter - filters out any stop words before they enter the
 * index
 * 3. elasticlunr.stemmer - stems the tokens before entering the index.
 *
 *
 * Example:
 *
 *     var idx = elasticlunr(function () {
 *       this.addField('id');
 *       this.addField('title');
 *       this.addField('body');
 *
 *       //this.setRef('id'); // default ref is 'id'
 *
 *       this.pipeline.add(function () {
 *         // some custom pipeline function
 *       });
 *     });
 *
 *    idx.addDoc({
 *      id: 1,
 *      title: 'Oracle released database 12g',
 *      body: 'Yestaday, Oracle has released their latest database, named 12g, more robust. this product will increase Oracle profit.'
 *    });
 *
 *    idx.addDoc({
 *      id: 2,
 *      title: 'Oracle released annual profit report',
 *      body: 'Yestaday, Oracle has released their annual profit report of 2015, total profit is 12.5 Billion.'
 *    });
 *
 *    # simple search
 *    idx.search('oracle database');
 *
 *    # search with query-time boosting
 *    idx.search('oracle database', {fields: {title: {boost: 2}, body: {boost: 1}}});
 *
 * @param {Function} config A function that will be called with the new instance
 * of the elasticlunr.Index as both its context and first parameter. It can be used to
 * customize the instance of new elasticlunr.Index.
 * @namespace
 * @module
 * @return {elasticlunr.Index}
 *
 */
var elasticlunr = function (config) {
  var idx = new elasticlunr.Index;

  idx.pipeline.add(
    elasticlunr.trimmer,
    elasticlunr.stopWordFilter,
    elasticlunr.stemmer
  );

  if (config) config.call(idx, idx);

  return idx;
};

elasticlunr.version = "@VERSION";
<|endoftext|>


<commit_before>module.exports = {
  afterInstall: function () {
    const packagesToRemove = [
      'ember-frost-button',
      'ember-frost-checkbox',
      'ember-frost-css-core',
      'ember-frost-icons',
      'ember-frost-link',
      'ember-frost-loading',
      'ember-frost-password',
      'ember-frost-select',
      'ember-frost-text',
      'ember-frost-textarea',
      'ember-frost-theme',
      'svg4everybody'
    ].map((packageName) => {
      return {name: packageName}
    })

    return this.removePackagesFromProject(packagesToRemove)
      .then(() => {
        return this.addAddonsToProject({
          packages: [
            {name: 'ember-cli-mocha', target: '^0.11.0'},
            {name: 'ember-concurrency', target: '~0.7.15'},
            {name: 'ember-computed-decorators', target: '~0.2.0'},
            {name: 'ember-elsewhere', target: '~0.4.1'},
            {name: 'ember-hook', target: '^1.3.5'},
            {name: 'ember-sinon', target: '^0.5.1'},
            {name: 'ember-spread', target: '^0.0.6'},
            {name: 'ember-test-utils', target: '^1.1.2'},
            {name: 'ember-truth-helpers', target: '^1.2.0'}
          ]
        })
      })
  },

  normalizeEntityName: function () {
    // this prevents an error when the entityName is
    // not specified (since that doesn't actually matter to us)
  }
}
<commit_msg>Remove from blueprint<commit_after>module.exports = {
  afterInstall: function () {
    const packagesToRemove = [
      'ember-frost-button',
      'ember-frost-checkbox',
      'ember-frost-css-core',
      'ember-frost-icons',
      'ember-frost-link',
      'ember-frost-loading',
      'ember-frost-password',
      'ember-frost-select',
      'ember-frost-text',
      'ember-frost-textarea',
      'ember-frost-theme',
      'svg4everybody'
    ].map((packageName) => {
      return {name: packageName}
    })

    return this.removePackagesFromProject(packagesToRemove)
      .then(() => {
        return this.addAddonsToProject({
          packages: [
            {name: 'ember-cli-mocha', target: '^0.11.0'},
            {name: 'ember-concurrency', target: '~0.7.15'},
            {name: 'ember-computed-decorators', target: '~0.2.0'},
            {name: 'ember-elsewhere', target: '~0.4.1'},
            {name: 'ember-hook', target: '^1.3.5'},
            {name: 'ember-sinon', target: '^0.5.1'},
            {name: 'ember-test-utils', target: '^1.1.2'},
            {name: 'ember-truth-helpers', target: '^1.2.0'}
          ]
        })
      })
  },

  normalizeEntityName: function () {
    // this prevents an error when the entityName is
    // not specified (since that doesn't actually matter to us)
  }
}
<|endoftext|>


<commit_before>if (jQuery === undefined) {
    jQuery = django.jQuery;
}

(function ($) {
    $(function () {
        $('.sortedm2m').parents('ul:first').each(function () {
            $(this).addClass('sortedm2m');
            var checkboxes = $(this).find('input[type=checkbox]');
            var id = checkboxes.first().attr('id').match(/^(.*)_\d+$/)[1];
            var name = checkboxes.first().attr('name');
            checkboxes.removeAttr('name');
            $(this).before('<input type="hidden" id="' + id + '" name="' + name + '" />');
            var that = this;
            var recalculate_value = function () {
                var values = [];
                $(that).find(':checked').each(function () {
                    values.push($(this).val());
                });
                $('#' + id).val(values.join(','));
            }
            recalculate_value();
            checkboxes.change(recalculate_value);
            $(this).sortable({
                axis: 'y',
                //containment: 'parent',
                update: recalculate_value
            });
        });

        $('.sortedm2m-container .selector-filter input').each(function () {
            $(this).bind('input', function() {
                var search = $(this).val().toLowerCase();
                var $el = $(this).closest('.selector-filter');
                var $container = $el.siblings('ul').each(function() {
                    // walk over each child list el and do name comparisons
                    $(this).children().each(function() {
                        var curr = $(this).find('label').text().toLowerCase();
                        if (curr.indexOf(search) === -1) {
                            $(this).css('display', 'none');
                        } else {
                            $(this).css('display', 'inherit');
                        };
                    });
                });
            });
        });

        if (window.showAddAnotherPopup) {
            var django_dismissAddAnotherPopup = window.dismissAddAnotherPopup;
            window.dismissAddAnotherPopup = function (win, newId, newRepr) {
                // newId and newRepr are expected to have previously been escaped by
                // django.utils.html.escape.
                newId = html_unescape(newId);
                newRepr = html_unescape(newRepr);
                var name = windowname_to_id(win.name);
                var elem = $('#' + name);
                var sortedm2m = elem.siblings('ul.sortedm2m');
                if (sortedm2m.length == 0) {
                    // no sortedm2m widget, fall back to django's default
                    // behaviour
                    return django_dismissAddAnotherPopup.apply(this, arguments);
                }

                if (elem.val().length > 0) {
                    elem.val(elem.val() + ',');
                }
                elem.val(elem.val() + newId);

                var id_template = '';
                var maxid = 0;
                sortedm2m.find('li input').each(function () {
                    var match = this.id.match(/^(.+)_(\d+)$/);
                    id_template = match[1];
                    id = parseInt(match[2]);
                    if (id > maxid) maxid = id;
                });

                var id = id_template + '_' + (maxid + 1);
                var new_li = $('<li/>').append(
                    $('<label/>').attr('for', id).append(
                        $('<input class="sortedm2m" type="checkbox" checked="checked" />').attr('id', id).val(newId)
                    ).append($('<span/>').text(' ' + newRepr))
                );
                sortedm2m.append(new_li);

                win.close();
            };
        }
    });
})(jQuery);
<commit_msg>Partially solves issue #20<commit_after>if (jQuery === undefined) {
    jQuery = django.jQuery;
}

(function ($) {
    $(function () {

        $.fn.prepare_ul = function () {
            this.addClass('sortedm2m');
            var checkboxes = this.find('input[type=checkbox]');
            var id = checkboxes.first().attr('id').match(/^(.*)_\d+$/)[1];
            var name = checkboxes.first().attr('name');
            checkboxes.removeAttr('name');
            this.before('<input type="hidden" id="' + id + '" name="' + name + '" />');
            var that = this;
            var recalculate_value = function () {
                var values = [];
                that.find(':checked').each(function () {
                    values.push($(this).val());
                });
                $('#' + id).val(values.join(','));
            }
            recalculate_value();
            checkboxes.change(recalculate_value);
            this.sortable({
                axis: 'y',
                //containment: 'parent',
                update: recalculate_value
            });
            return this;
        };

        var iterate_ul = function() {
            $('.sortedm2m').parents('ul').each(function () {
                $(this).prepare_ul();
            });
        }

        $(".add-row a").click(iterate_ul);

        iterate_ul();

        $('.sortedm2m-container .selector-filter input').each(function () {
            $(this).bind('input', function() {
                var search = $(this).val().toLowerCase();
                var $el = $(this).closest('.selector-filter');
                var $container = $el.siblings('ul').each(function() {
                    // walk over each child list el and do name comparisons
                    $(this).children().each(function() {
                        var curr = $(this).find('label').text().toLowerCase();
                        if (curr.indexOf(search) === -1) {
                            $(this).css('display', 'none');
                        } else {
                            $(this).css('display', 'inherit');
                        };
                    });
                });
            });
        });

        if (window.showAddAnotherPopup) {
            var django_dismissAddAnotherPopup = window.dismissAddAnotherPopup;
            window.dismissAddAnotherPopup = function (win, newId, newRepr) {
                // newId and newRepr are expected to have previously been escaped by
                // django.utils.html.escape.
                newId = html_unescape(newId);
                newRepr = html_unescape(newRepr);
                var name = windowname_to_id(win.name);
                var elem = $('#' + name);
                var sortedm2m = elem.siblings('ul.sortedm2m');
                if (sortedm2m.length == 0) {
                    // no sortedm2m widget, fall back to django's default
                    // behaviour
                    return django_dismissAddAnotherPopup.apply(this, arguments);
                }

                if (elem.val().length > 0) {
                    elem.val(elem.val() + ',');
                }
                elem.val(elem.val() + newId);

                var id_template = '';
                var maxid = 0;
                sortedm2m.find('li input').each(function () {
                    var match = this.id.match(/^(.+)_(\d+)$/);
                    id_template = match[1];
                    id = parseInt(match[2]);
                    if (id > maxid) maxid = id;
                });

                var id = id_template + '_' + (maxid + 1);
                var new_li = $('<li/>').append(
                    $('<label/>').attr('for', id).append(
                        $('<input class="sortedm2m" type="checkbox" checked="checked" />').attr('id', id).val(newId)
                    ).append($('<span/>').text(' ' + newRepr))
                );
                sortedm2m.append(new_li);

                win.close();
            };
        }
    });
})(jQuery);
<|endoftext|>


<commit_before>/*
 * Copyright 2009-2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE.txt or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

var copy = require('dryice').copy;
var path = require('path');
var fs = require('fs');

var gcliHome = __dirname;

/**
 * The main() function is called at the bottom of this file to ensure all the
 * globals are setup properly.
 */
function main() {
  var args = process.argv;
  if (args.length < 3 || args[2] === 'standard') {
    buildStandard();
  }
  else if (args[2] === 'firefox') {
    buildFirefox(args[3]);
  }
  else {
    console.error('Error: Unknown target: \'' + args[2] + '\'');
    process.exit(1);
  }
}

/**
 * There are 2 important ways to build GCLI.
 * The first is for use within a normal web page.
 * It has compressed and uncompressed versions of the output script file.
 */
function buildStandard() {
  console.log('Building built/gcli[-uncompressed].js:');

  if (!path.existsSync(gcliHome + '/built')) {
    fs.mkdirSync(gcliHome + '/built', 0755);
  }

  var project = copy.createCommonJsProject({
    roots: [ gcliHome + '/lib' ]
  });
  var sources = copy.createDataObject();

  copy({
    source: copy.source.commonjs({
      project: project,
      // This list of dependencies should be the same as in index.html
      require: [ 'gcli/index', 'demo/index', 'gclitest/index' ]
    }),
    filter: copy.filter.moduleDefines,
    dest: sources
  });
  copy({
    source: { root: project, include: /.*\.png$|.*\.gif$/ },
    filter: copy.filter.base64,
    dest: sources
  });
  console.log(project.report());

  // Create a GraphML dependency report. Directions:
  // - Install yEd (http://www.yworks.com/en/products_yed_about.htm)
  // - Load gcli/built/gcli.graphml
  // - Resize the nodes (Tools->Fit Node to Label)
  // - Apply a layout (Layout->Hierarchical)
  console.log('Outputting dependency graph to built/gcli.graphml\n');
  if (project.getDependencyGraphML) {
    copy({
      source: { value:project.getDependencyGraphML() },
      dest: 'built/gcli.graphml',
    });
  }

  // Create the output scripts, compressed and uncompressed
  copy({ source: 'index.html', filter: tweakIndex, dest: 'built/index.html' });
  copy({ source: 'scripts/es5-shim.js', dest: 'built/es5-shim.js' });
  copy({
    source: [ copy.getMiniRequire(), sources ],
    dest: 'built/gcli-uncompressed.js'
  });
  try {
    copy({
      source: [ copy.getMiniRequire(), sources ],
      filter: copy.filter.uglifyjs,
      dest: 'built/gcli.js'
    });
  }
  catch (ex) {
    console.log('ERROR: Uglify compression fails on windows/linux. ' +
        'Skipping creation of built/gcli.js\n');
  }
}

/**
 * Build the Javascript JSM files for Firefox
 * It consists of 1 output file: gcli.jsm
 */
function buildFirefox(destDir) {
  console.log('Building to ' + (destDir || 'built/ff') + '.\n');

  if (!destDir) {
    if (!path.existsSync(gcliHome + '/built')) {
      fs.mkdirSync(gcliHome + '/built', 0755);
    }
    if (!path.existsSync(gcliHome + '/built/ff')) {
      fs.mkdirSync(gcliHome + '/built/ff', 0755);
    }
  }
  }

  var project = copy.createCommonJsProject({
    roots: [ gcliHome + '/mozilla', gcliHome + '/lib' ],
    ignores: [ 'text!gcli/ui/inputter.css' ]
  });

  copy({
    source: [
      'mozilla/build/prefix-gcli.jsm',
      'mozilla/build/console.js',
      copy.getMiniRequire(),
      copy.source.commonjs({
        project: project,
        // This list of dependencies should be the same as in suffix-gcli.jsm
        require: [ 'gcli/index' ]
      }),
      'mozilla/build/suffix-gcli.jsm'
    ],
    filter: copy.filter.moduleDefines,
    dest: 'built/ff/gcli.jsm'
  });

  copy({
    source: [
      'mozilla/build/license-block.txt',
      { value: '\n/* From: $GCLI/mozilla/gcli/ui/gcliterm.css */' },
      'mozilla/gcli/ui/gcliterm.css',
      { value: '\n/* From: $GCLI/lib/gcli/ui/arg_fetch.css */' },
      'lib/gcli/ui/arg_fetch.css',
      { value: '\n/* From: $GCLI/lib/gcli/ui/hinter.css */' },
      'lib/gcli/ui/hinter.css',
      { value: '\n/* From: $GCLI/lib/gcli/ui/menu.css */' },
      'lib/gcli/ui/menu.css',
      { value: '\n/* From: $GCLI/lib/gcli/ui/inputter.css */' },
      'lib/gcli/ui/inputter.css',
      { value: '\n/* From: $GCLI/lib/gcli/ui/command_output_view.css */' },
      'lib/gcli/ui/command_output_view.css'
    ],
    dest: 'built/ff/gcli.css'
  });

  console.log(project.report());
}

/**
 * Filter index.html to:
 * - Make links relative, we flatten out the scripts directory
 * - Replace require.js with the built GCLI script file
 * - Remove the RequireJS configuration
 */
function tweakIndex(data) {
  return data
      .replace(/scripts\/es5-shim.js/, 'es5-shim.js')
      .replace(/scripts\/require.js/, 'gcli-uncompressed.js')
      .replace(/\s*require\([^;]*;\n/, '');
}
// Now everything is defined properly, start working
main();
<commit_msg>Bug 653139 (l10n): Makefile update - Write the generated JSM to the correct directory if a firefox dir is provided<commit_after>/*
 * Copyright 2009-2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE.txt or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

var copy = require('dryice').copy;
var path = require('path');
var fs = require('fs');

var gcliHome = __dirname;

/**
 * The main() function is called at the bottom of this file to ensure all the
 * globals are setup properly.
 */
function main() {
  var args = process.argv;
  if (args.length < 3 || args[2] === 'standard') {
    buildStandard();
  }
  else if (args[2] === 'firefox') {
    buildFirefox(args[3]);
  }
  else {
    console.error('Error: Unknown target: \'' + args[2] + '\'');
    process.exit(1);
  }
}

/**
 * There are 2 important ways to build GCLI.
 * The first is for use within a normal web page.
 * It has compressed and uncompressed versions of the output script file.
 */
function buildStandard() {
  console.log('Building built/gcli[-uncompressed].js:');

  if (!path.existsSync(gcliHome + '/built')) {
    fs.mkdirSync(gcliHome + '/built', 0755);
  }

  var project = copy.createCommonJsProject({
    roots: [ gcliHome + '/lib' ]
  });
  var sources = copy.createDataObject();

  copy({
    source: copy.source.commonjs({
      project: project,
      // This list of dependencies should be the same as in index.html
      require: [ 'gcli/index', 'demo/index', 'gclitest/index' ]
    }),
    filter: copy.filter.moduleDefines,
    dest: sources
  });
  copy({
    source: { root: project, include: /.*\.png$|.*\.gif$/ },
    filter: copy.filter.base64,
    dest: sources
  });
  console.log(project.report());

  // Create a GraphML dependency report. Directions:
  // - Install yEd (http://www.yworks.com/en/products_yed_about.htm)
  // - Load gcli/built/gcli.graphml
  // - Resize the nodes (Tools->Fit Node to Label)
  // - Apply a layout (Layout->Hierarchical)
  console.log('Outputting dependency graph to built/gcli.graphml\n');
  if (project.getDependencyGraphML) {
    copy({
      source: { value:project.getDependencyGraphML() },
      dest: 'built/gcli.graphml',
    });
  }

  // Create the output scripts, compressed and uncompressed
  copy({ source: 'index.html', filter: tweakIndex, dest: 'built/index.html' });
  copy({ source: 'scripts/es5-shim.js', dest: 'built/es5-shim.js' });
  copy({
    source: [ copy.getMiniRequire(), sources ],
    dest: 'built/gcli-uncompressed.js'
  });
  try {
    copy({
      source: [ copy.getMiniRequire(), sources ],
      filter: copy.filter.uglifyjs,
      dest: 'built/gcli.js'
    });
  }
  catch (ex) {
    console.log('ERROR: Uglify compression fails on windows/linux. ' +
        'Skipping creation of built/gcli.js\n');
  }
}

/**
 * Build the Javascript JSM files for Firefox
 * It consists of 1 output file: gcli.jsm
 */
function buildFirefox(destDir) {
  console.log('Building to ' + (destDir || 'built/ff') + '.\n');

  if (!destDir) {
    if (!path.existsSync(gcliHome + '/built')) {
      fs.mkdirSync(gcliHome + '/built', 0755);
    }
    if (!path.existsSync(gcliHome + '/built/ff')) {
      fs.mkdirSync(gcliHome + '/built/ff', 0755);
    }
  }
  var jsmDir = '/browser/devtools/webconsole';
  if (destDir) {
    var fail = false;
    if (!path.existsSync(destDir + jsmDir)) {
      console.error('Missing path for JSM: ' + destDir + jsmDir);
      fail = true;
    }
    if (fail) {
      process.exit(1);
    }
  }

  var project = copy.createCommonJsProject({
    roots: [ gcliHome + '/mozilla', gcliHome + '/lib' ],
    ignores: [ 'text!gcli/ui/inputter.css' ]
  });

  // Package the JavaScript
  copy({
    source: [
      'mozilla/build/prefix-gcli.jsm',
      'mozilla/build/console.js',
      copy.getMiniRequire(),
      copy.source.commonjs({
        project: project,
        // This list of dependencies should be the same as in suffix-gcli.jsm
        require: [ 'gcli/index' ]
      }),
      'mozilla/build/suffix-gcli.jsm'
    ],
    filter: copy.filter.moduleDefines,
    dest: (destDir ? destDir + jsmDir : 'built/ff') + '/gcli.jsm'
  });

  copy({
    source: [
      'mozilla/build/license-block.txt',
      { value: '\n/* From: $GCLI/mozilla/gcli/ui/gcliterm.css */' },
      'mozilla/gcli/ui/gcliterm.css',
      { value: '\n/* From: $GCLI/lib/gcli/ui/arg_fetch.css */' },
      'lib/gcli/ui/arg_fetch.css',
      { value: '\n/* From: $GCLI/lib/gcli/ui/hinter.css */' },
      'lib/gcli/ui/hinter.css',
      { value: '\n/* From: $GCLI/lib/gcli/ui/menu.css */' },
      'lib/gcli/ui/menu.css',
      { value: '\n/* From: $GCLI/lib/gcli/ui/inputter.css */' },
      'lib/gcli/ui/inputter.css',
      { value: '\n/* From: $GCLI/lib/gcli/ui/command_output_view.css */' },
      'lib/gcli/ui/command_output_view.css'
    ],
    dest: 'built/ff/gcli.css'
  });

  console.log(project.report());
}

/**
 * Filter index.html to:
 * - Make links relative, we flatten out the scripts directory
 * - Replace require.js with the built GCLI script file
 * - Remove the RequireJS configuration
 */
function tweakIndex(data) {
  return data
      .replace(/scripts\/es5-shim.js/, 'es5-shim.js')
      .replace(/scripts\/require.js/, 'gcli-uncompressed.js')
      .replace(/\s*require\([^;]*;\n/, '');
}
// Now everything is defined properly, start working
main();
<|endoftext|>


<commit_before>function cam_ar() {
	var win = Titanium.UI.createWindow();

	var button = Titanium.UI.createButton({
		color:'#fff',
		backgroundImage:'/images/BUTT_grn_on.png',
		backgroundSelectedImage:'/images/BUTT_grn_off.png',
		backgroundDisabledImage: '/images/BUTT_gry_on.png',
		bottom:10,
		width:301,
		height:57,
		font:{fontSize:20,fontWeight:'bold',fontFamily:'Helvetica Neue'},
		title:'Cancel'
	});

	var messageView = Titanium.UI.createView({
		height:60,
		width:250,
		top:10
	});

	var indView = Titanium.UI.createView({
		height:60,
		width:270,
		backgroundColor:'#000',
		borderRadius:10,
		opacity:0.7
	});
	messageView.add(indView);

	// message
	var message = Titanium.UI.createLabel({
		text:'Calculating...',
		color:'#fff',
		font:{fontSize:14,fontWeight:'bold',fontFamily:'Helvetica Neue'},
		textAlign:'center',
		width:270,
		height:'auto'
	});
	messageView.add(message);

	var overlay = Titanium.UI.createView();
	overlay.add(button);
	overlay.add(messageView);

	var heading;
	var gps='...';
	var address='calculating address';

	function refreshLabel()
	{
		var text = "Heading: "+Math.round(heading)+"°, Location: "+gps;
		if (address)
		{
			text+="\n"+address;
		}
		message.text = text;
	}

	Ti.include("/etc/version.js");
	if (isIPhone3_2_Plus())
	{
		Titanium.Geolocation.purpose = "AR Demo";
	}

	Titanium.Geolocation.addEventListener('location',function(e)
	{
		var longitude = e.coords.longitude;
		var latitude = e.coords.latitude;
		gps = Math.round(longitude)+' x '+Math.round(latitude);
		Titanium.Geolocation.reverseGeocoder(latitude,longitude,function(evt)
		{
			var places = evt.places[0];
			address = places.street ? places.street : places.address;
			refreshLabel();
		});
		refreshLabel();
	});

	Titanium.Geolocation.addEventListener('heading',function(e)
	{
		if (e.error)
		{
			updatedHeading.text = 'error: ' + e.error;
			return;
		}

		heading = e.heading.magneticHeading;
		refreshLabel();
	});

	Titanium.Media.showCamera({

		success:function(event)
		{
		},
		cancel:function()
		{
		},
		error:function(error)
		{
			var a = Titanium.UI.createAlertDialog({title:'Camera'});
			if (error.code == Titanium.Media.NO_CAMERA)
			{
				a.setMessage('Please run this test on device');
			}
			else
			{
				a.setMessage('Unexpected error: ' + error.code);
			}
			a.show();
		},
		overlay:overlay,
		showControls:false,	// don't show system controls
		mediaTypes:Ti.Media.MEDIA_TYPE_PHOTO,
		autohide:false	// tell the system not to auto-hide and we'll do it ourself
	});

	button.addEventListener('click',function()
	{
		alert("Close the camera");
		Ti.Media.hideCamera();
	});

	return win;
};

module.exports = cam_ar;<commit_msg>[TIMOB-10133]Wrapping all variables inside a container so that no variables are lost.<commit_after>function cam_ar() {
	container  = {};
	container.win = Titanium.UI.createWindow();

	container.button = Titanium.UI.createButton({
		color:'#fff',
		backgroundImage:'/images/BUTT_grn_on.png',
		backgroundSelectedImage:'/images/BUTT_grn_off.png',
		backgroundDisabledImage: '/images/BUTT_gry_on.png',
		bottom:10,
		width:301,
		height:57,
		font:{fontSize:20,fontWeight:'bold',fontFamily:'Helvetica Neue'},
		title:'Cancel'
	});

	container.button.addEventListener('click',function()
	{
		alert("Close the camera");
		Ti.Media.hideCamera();
		container.close();
	});

	container.messageView = Titanium.UI.createView({
		height:60,
		width:250,
		top:10
	});

	container.indView = Titanium.UI.createView({
		height:60,
		width:270,
		backgroundColor:'#000',
		borderRadius:10,
		opacity:0.7
	});
	container.messageView.add(container.indView);

	// message
	container.message = Titanium.UI.createLabel({
		text:'Calculating...',
		color:'#fff',
		font:{fontSize:14,fontWeight:'bold',fontFamily:'Helvetica Neue'},
		textAlign:'center',
		width:270,
		height:'auto'
	});
	container.messageView.add(container.message);

	container.overlay = Titanium.UI.createView();
	container.overlay.add(container.button);
	container.overlay.add(container.messageView);

	container.heading;
	container.gps='...';
	container.address='calculating address';

	container.refreshLabel = function ()
	{
		var text = "Heading: "+Math.round(container.heading)+"°, Location: "+container.gps;
		if (container.address)
		{
			text+="\n"+container.address;
		}
		container.message.text = text;
	}

	Titanium.Geolocation.purpose = "AR Demo";

	Titanium.Geolocation.addEventListener('location',function(e)
	{
		var longitude = e.coords.longitude;
		var latitude = e.coords.latitude;
		container.gps = Math.round(longitude)+' x '+Math.round(latitude);
		Titanium.Geolocation.reverseGeocoder(latitude,longitude,function(evt)
		{
			var places = evt.places[0];
			container.address = places.street ? places.street : places.address;
			container.refreshLabel();
		});
		container.refreshLabel();
	});

	Titanium.Geolocation.addEventListener('heading',function(e)
	{
		if (e.error)
		{
			container.updatedHeading.text = 'error: ' + e.error;
			return;
		}

		container.heading = e.heading.magneticHeading;
		container.refreshLabel();
	});

	Titanium.Media.showCamera({

		success:function(event)
		{
		},
		cancel:function()
		{
		},
		error:function(error)
		{
			var a = Titanium.UI.createAlertDialog({title:'Camera'});
			if (error.code == Titanium.Media.NO_CAMERA)
			{
				a.setMessage('Please run this test on device');
			}
			else
			{
				a.setMessage('Unexpected error: ' + error.code);
			}
			a.show();
		},
		overlay:container.overlay,
		showControls:false,	// don't show system controls
		mediaTypes:Ti.Media.MEDIA_TYPE_PHOTO,
		autohide:false	// tell the system not to auto-hide and we'll do it ourself
	});

	container.open = function(){
		container.win.open();
	};

	container.close = function(){
		container.win.close();
	}

	return container;
};

module.exports = cam_ar;<|endoftext|>


<commit_before>'use strict';

const program = require('commander');
const Promise = require("bluebird");
const fsa = Promise.promisifyAll(require("fs"));
const archiver = require('archiver');
const path = require('path');

const mkdirpAsync = Promise.promisify(require('mkdirp'));
const zipFileUtils = require('../servers/lib/zipFileUtils.js');

//const defaultPort =  29015; // true default
const defaultPort =  30815; // localhost version

let parameters = getControlParameters();

var port = parameters.port;
var base = parameters.base;
var zipbase = parameters.zipbase;
var replace = !!parameters.replace;
var idList = parameters.id;
var all = !!parameters.all;
var numberProcessed = 0;
var totalNumberToProcess = 0;
var pathForFileInZip = "Dataset/";

main();

function main() {

    verifyParameters();

    reportParameters();

    if (base) {
        zipFileUtils.setBase(base);
    }
    if (zipbase){
        zipFileUtils.setZipDirPath(zipbase);
    }

    Promise.coroutine(buildZipFiles)();
}

function* buildZipFiles() {
    try {
        console.log("setup");
        var r = require('rethinkdbdash')({
            db: 'materialscommons',
            port: port
        });
        console.log("setup done");

        var idSet = new Set(idList);
        var ids = (idList.length > 0);

        let allDatasetIds = yield r.db('materialscommons').table('datasets').pluck(["id","published"]);

        var idsToProcess = [];
        allDatasetIds.forEach(record => {
            let id = record['id'];
            if (all || (ids && (idSet.has(id)))) {
                if (record['published']) {
                    idsToProcess.push(id);
                } else {
                    console.log("No zip will be created for unpublished dataset: " + id);
                }
            }
        });

        console.log("Zip files to be created for " + idsToProcess.length + " datasets");

        if (idsToProcess.length == 0) {
            return Promise.reject("Error: no dataset id values to process");
        }

        totalNumberToProcess = idsToProcess.length;

        for (var i = 0; i < idsToProcess.length; i++) {
            var id = idsToProcess[i];
            Promise.coroutine(
                publishDatasetZipFile
            )(r, id);
        }

    } catch (error) {
        console.log("Error in buildZipFiles: ", error)
    }
}

function* publishDatasetZipFile(r, datasetId) {
    try {
        console.log("zip", datasetId);
        let ds = yield r.db('materialscommons').table('datasets').get(datasetId);
        let zipDirPath = zipFileUtils.zipDirPath(ds);
        let fillPathAndFilename = zipFileUtils.fullPathAndFilename(ds);

        console.log("full path and filename: ", fillPathAndFilename);

        let ds2dfEntries = yield r.db('materialscommons').table('dataset2datafile')
            .getAll(datasetId, {index: 'dataset_id'}).coerceTo('array');

        if (!ds2dfEntries.length) {
            numberProcessed++;
            console.log('no zip for id = ' + datasetId);
            console.log('total number of zip files processed: ' + numberProcessed + " of " + totalNumberToProcess);
            return new Promise(function(resolve, reject){resolve()});
        }

        yield mkdirpAsync(zipDirPath);

        let datafileIds = ds2dfEntries.map(entry => entry.datafile_id);
        let datafiles = yield r.table('datafiles').getAll(r.args(datafileIds));

        console.log("For id = " + datasetId + ", there are " + datafileIds.length + " files");

        let nameSourceList = [];
        var seenThisOne = {};

        for (var i=0; i < datafiles.length; i++) {
            let df = datafiles[i];

            let zipEntry = zipFileUtils.zipEntry(df); // sets fileName, checksum, sourcePath
            console.log("zipEntry: ", zipEntry);
            let path = zipEntry.sourcePath;
            let name = zipEntry.fileName;
            let checksum = zipEntry.checksum;
            name = resolveZipfileFilenameDuplicates(seenThisOne, name, checksum);
            console.log("before read stream");
            let stream = fsa.createReadStream(path,{
                flags: 'r',
                encoding: null,
                fd: null,
                mode: 0o666,
                autoClose: true
            });
            console.log("after read stream: ", path);
            nameSourceList.push({name: name, source: stream});
        }

        console.log("got files to add: " + nameSourceList.length);

        var output = fsa.createWriteStream(fillPathAndFilename);

        console.log("output stream set");

        let retP =  new Promise(function (resolve, reject) {
            var archive = archiver('zip');

            output.on('close', function () {
                console.log('for dataset: ' + datasetId + " with " + archive.pointer() + ' total bytes');
                numberProcessed++;
                console.log('total number of zip files processed: ' + numberProcessed + " of " + totalNumberToProcess);
                resolve();
                if (numberProcessed == totalNumberToProcess) {
                    process.exit(0);
                }
            });

            archive.on('error', reject);

            archive.on('close',function() {console.log('archive close');});

            archive.pipe(output);

            nameSourceList.forEach(ns => {
                let pathAndName = pathForFileInZip + ns.name;
                console.log("name: ", pathAndName);
                archive.append(ns.source, {name:pathAndName} );
            });

            archive.finalize();
        });

        console.log("Got return promise");

        return retP;

    } catch (error) {
        return yield Promise.reject("Error in publishDatasetZipFile: " +  error.message);
    }
}

function resolveZipfileFilenameDuplicates(seenThisOne,name,checksum){
    name = name.toLowerCase();

    if (name.startsWith(".")) {
        name = "dot_" + name;
    }

    if (name in seenThisOne) {
        var count = 0;
        if (seenThisOne[name] == checksum) {
            console.log("Seen this file before: " + name);
            return null;
        } else {
            let newName = resolveZipfileFilenameUnique(name, count);
            while (newName in seenThisOne) {
                count++;
                newName = resolveZipfileFilenameUnique(name, count);
            }
            // console.log(name + " --> " + newName);
            name = newName;
        }
    }
    seenThisOne[name] = checksum;
    return name;
}

function resolveZipfileFilenameUnique(name, count) {
    let parts = path.parse(name);
    return parts.name + "_" + count + parts.ext;
}

function verifyParameters() {
    var ids = (idList.length > 0);

    if (!all && !ids) {
        program.help(text => {
            var banner =    "\t--------------------------------\n";
            return banner + "\tOne of --id or --all is required\n"
                + banner + text;
        })
    }

    if (ids && all) {
        console.log("WARNING: --all (or -a) was specified, but one of more id valeus were given\n"
            + "\tThe id values take precident");
    }

    if (ids) {
        all = false;
    }

}

function reportParameters() {
    console.log("use --help for list of parameter options");
    console.log("port = " + port);
    console.log("base = " + base);
    console.log("zipbase = " + zipbase);
    console.log("replace = " + replace);
    if (all) {
        console.log("process all")
    } else {
        console.log("input id(s)");
        idList.forEach(id => {
            console.log("\tid = " + id);
        });
    }
}

function getControlParameters() {
    let accumulateIds = (id,ids) => {
        ids.push(id);
        return ids;
    };

    return program
        .option('-p, --port [port]', 'The RethinkDB port; defaults to ' + defaultPort,defaultPort)
        .option('-b, --base [base]', 'The base path of the datasets directory, optional')
        .option('-z, --zipbase [zipbase]', 'The base path for the zipfile directory, optional')
        .option('-i, --id [id]', 'If given, the id of the dataset to copy, can be repeated',accumulateIds,[])
        .option('-a, --all', 'If given, and no id(s), then copy all datasets, \n\t\tone of --id or --all required')
        .option('-r, --replace','If given, then replace files already generaåted, \n\t\totherwise not; optional')
        .parse(process.argv);
}
<commit_msg>Modified files to add filename and bytecount to database<commit_after>#!/usr/bin/env node
'use strict';

const program = require('commander');
const Promise = require("bluebird");
const fsa = Promise.promisifyAll(require("fs"));
const archiver = require('archiver');
const path = require('path');

const mkdirpAsync = Promise.promisify(require('mkdirp'));
const zipFileUtils = require('../servers/lib/zipFileUtils.js');

//const defaultPort =  29015; // true default
const defaultPort =  30815; // localhost version

let parameters = getControlParameters();

var port = parameters.port;
var base = parameters.base;
var zipbase = parameters.zipbase;
var replace = !!parameters.replace;
var idList = parameters.id;
var all = !!parameters.all;
var numberProcessed = 0;
var totalNumberToProcess = 0;
var pathForFileInZip = "Dataset/";

main();

function main() {

    verifyParameters();

    reportParameters();

    if (base) {
        zipFileUtils.setBase(base);
    }
    if (zipbase){
        zipFileUtils.setZipDirPath(zipbase);
    }

    Promise.coroutine(buildZipFiles)();
}

function* buildZipFiles() {
    try {
        console.log("setup");
        var r = require('rethinkdbdash')({
            db: 'materialscommons',
            port: port
        });
        console.log("setup done");

        var idSet = new Set(idList);
        var ids = (idList.length > 0);

        let allDatasetIds = yield r.db('materialscommons').table('datasets').pluck(["id","published"]);

        var idsToProcess = [];
        allDatasetIds.forEach(record => {
            let id = record['id'];
            if (all || (ids && (idSet.has(id)))) {
                if (record['published']) {
                    idsToProcess.push(id);
                } else {
                    console.log("No zip will be created for unpublished dataset: " + id);
                }
            }
        });

        console.log("Zip files to be created for " + idsToProcess.length + " datasets");

        if (idsToProcess.length == 0) {
            return Promise.reject("Error: no dataset id values to process");
        }

        totalNumberToProcess = idsToProcess.length;

        for (var i = 0; i < idsToProcess.length; i++) {
            var id = idsToProcess[i];
            Promise.coroutine(
                publishDatasetZipFile
            )(r, id);
        }

    } catch (error) {
        console.log("Error in buildZipFiles: ", error)
    }
}

function* publishDatasetZipFile(r, datasetId) {
    try {
        console.log("zip", datasetId);
        let ds = yield r.db('materialscommons').table('datasets').get(datasetId);
        let zipDirPath = zipFileUtils.zipDirPath(ds);
        let zipFileName = zipFileUtils.zipFilename(ds);
        let fillPathAndFilename = zipFileUtils.fullPathAndFilename(ds);

        console.log("full path and filename: ", fillPathAndFilename);

        let ds2dfEntries = yield r.db('materialscommons').table('dataset2datafile')
            .getAll(datasetId, {index: 'dataset_id'}).coerceTo('array');

        if (!ds2dfEntries.length) {
            numberProcessed++;
            console.log('no zip for id = ' + datasetId);
            console.log('total number of zip files processed: ' + numberProcessed + " of " + totalNumberToProcess);
            return new Promise(function(resolve, reject){resolve()});
        }

        yield mkdirpAsync(zipDirPath);

        let datafileIds = ds2dfEntries.map(entry => entry.datafile_id);
        let datafiles = yield r.table('datafiles').getAll(r.args(datafileIds));

        let nameSourceList = [];
        var seenThisOne = {};

        for (var i=0; i < datafiles.length; i++) {
            let df = datafiles[i];

            let zipEntry = zipFileUtils.zipEntry(df); // sets fileName, checksum, sourcePath
            let path = zipEntry.sourcePath;
            let name = zipEntry.fileName;
            let checksum = zipEntry.checksum;
            name = resolveZipfileFilenameDuplicates(seenThisOne, name, checksum);
            let stream = fsa.createReadStream(path,{
                flags: 'r',
                encoding: null,
                fd: null,
                mode: 0o666,
                autoClose: true
            });
            nameSourceList.push({name: name, source: stream});
        }

        console.log("For id = " + datasetId + ", there are " + nameSourceList.length + " files");

        var output = fsa.createWriteStream(fillPathAndFilename);

        let retP =  new Promise(function (resolve, reject) {
            var archive = archiver('zip');

            output.on('close', function () {
                let zipfileSize = archive.pointer();
                console.log('for dataset: ' + datasetId + " with " +zipfileSize + ' total bytes');
                numberProcessed++;
                console.log('total number of zip files processed: ' + numberProcessed + " of " + totalNumberToProcess);
                let zip = {size: zipfileSize, filename: zipFileName};
                r.db('materialscommons').table('datasets').get(datasetId).update({zip: zip}).then(() =>{
                    resolve();
                    if (numberProcessed == totalNumberToProcess) {
                        process.exit(0);
                    }
                });
            });

            archive.on('error', reject);

            archive.on('close',function() {console.log('archive close');});

            archive.pipe(output);

            nameSourceList.forEach(ns => {
                let pathAndName = pathForFileInZip + ns.name;
                archive.append(ns.source, {name:pathAndName} );
            });

            archive.finalize();
        });

        console.log("Starting of zip file For id = " + datasetId + "... (wait)");

        return retP;

    } catch (error) {
        return yield Promise.reject("Error in publishDatasetZipFile: " +  error.message);
    }
}

function resolveZipfileFilenameDuplicates(seenThisOne,name,checksum){
    name = name.toLowerCase();

    if (name.startsWith(".")) {
        name = "dot_" + name;
    }

    if (name in seenThisOne) {
        var count = 0;
        if (seenThisOne[name] == checksum) {
            console.log("Seen this file before: " + name);
            return null;
        } else {
            let newName = resolveZipfileFilenameUnique(name, count);
            while (newName in seenThisOne) {
                count++;
                newName = resolveZipfileFilenameUnique(name, count);
            }
            // console.log(name + " --> " + newName);
            name = newName;
        }
    }
    seenThisOne[name] = checksum;
    return name;
}

function resolveZipfileFilenameUnique(name, count) {
    let parts = path.parse(name);
    return parts.name + "_" + count + parts.ext;
}

function verifyParameters() {
    var ids = (idList.length > 0);

    if (!all && !ids) {
        program.help(text => {
            var banner =    "\t--------------------------------\n";
            return banner + "\tOne of --id or --all is required\n"
                + banner + text;
        })
    }

    if (ids && all) {
        console.log("WARNING: --all (or -a) was specified, but one of more id valeus were given\n"
            + "\tThe id values take precident");
    }

    if (ids) {
        all = false;
    }

}

function reportParameters() {
    console.log("use --help for list of parameter options");
    console.log("port = " + port);
    console.log("base = " + base);
    console.log("zipbase = " + zipbase);
    console.log("replace = " + replace);
    if (all) {
        console.log("process all")
    } else {
        console.log("input id(s)");
        idList.forEach(id => {
            console.log("\tid = " + id);
        });
    }
}

function getControlParameters() {
    let accumulateIds = (id,ids) => {
        ids.push(id);
        return ids;
    };

    return program
        .option('-p, --port [port]', 'The RethinkDB port; defaults to ' + defaultPort,defaultPort)
        .option('-b, --base [base]', 'The base path of the datasets directory, optional')
        .option('-z, --zipbase [zipbase]', 'The base path for the zipfile directory, optional')
        .option('-i, --id [id]', 'If given, the id of the dataset to copy, can be repeated',accumulateIds,[])
        .option('-a, --all', 'If given, and no id(s), then copy all datasets, \n\t\tone of --id or --all required')
        .option('-r, --replace','If given, then replace files already generaåted, \n\t\totherwise not; optional')
        .parse(process.argv);
}
<|endoftext|>


<commit_before>import Board from 'alekhine'

import Display from './display'
import Socket from './socket'

import logger from "./logger"

const display = Display()
const socket = new Socket()

export default function() {
  const selected = null
  let show_moves = true
  let promotion_piece = null

  // flipped with respect to fen
  const mkBoardState = flipped => {
    return {
      flipped,
      gid: null,
      obj: null,
      black: "",
      white: "",
      stash_b: "",
      stash_w: ""
    }
  }

  const boards = {
    "l" : mkBoardState(true),
    "c" : mkBoardState(false),
    "r" : mkBoardState(true)
  }

  const dispatcher = {
    hold: () => {
      display.show_hold_dialog()
    },

    game: (data) => {
      display.color = data.color

      if (data.color == "b") {
        ib.toggle_flip_board()
        display.draw(boards); // ?
      }

      const hold = $("#hold")
      if (hold.hasClass("ui-dialog-content")) { // prevent exception when trying to destroy uninitialized dialog
        hold.dialog("destroy")
        hold.addClass("hidden")
      }

      $("#play").removeClass("hidden")
      display.update(boards, data)

      // boards must be drawn at least once first
      display.squarify()
    },

    kibitz: (data) => {
      $("#kibitz").removeClass("hidden")

      display.update(boards, data)
      display.squarify()
    },

    rotate: (data) => {
      if (data.to === "l" || data.to === "r") {
        display.rotate(data)
      } else {
        display.update(boards, data)
        ib.toggle_flip_board()
        display.squarify()
      }
    }

    /*
    socket.on("message", function(data) {
      // position update
      if (data.state) {
        for (var b in boards) {
          if (boards[b].gid == data.state.gid) {
            boards[b].obj.set_fen(data.state.fen, function(message) {
              if (message == "converted") draw_board(b)
            })
          }
        }
      }
    })
    */
  }

  return {
    play() {
      init("join")
    },

    kibitz() {
      init("kibitz")
    },

    toggle_show_moves(sm) {
      show_moves = sm
      $(".droppable").removeClass("droppable")
    },

    toggle_flip_board() {
      boards["l"].flipped = boards["r"].flipped = boards["c"].flipped
      boards["c"].flipped = !boards["c"].flipped

      display.draw(boards)
    },

    toggle_promotion_piece(piece) {
      if (promotion_piece) $(`#promotion_piece${promotion_piece}`).removeClass("promotion_piece_selected")
      $(`#promotion_piece${piece}`).addClass("promotion_piece_selected")

      promotion_piece = piece
    },

    redraw_boards() {
      display.draw(boards)
    },

    head() {
      rotate("h")
    },

    prev() {
      rotate("l")
    },

    next() {
      rotate("r")
    },

    tail() {
      rotate("t")
    }
  }

  /////////////////////
  // private methods //
  /////////////////////

  // initial state

  function init(action) {
    // board is required first
    const board = new Board()

    // set name
    const name = $("#name").val() || "anonymous"

    // create and display
    for (const b in boards) boards[b].obj = new Board()

    $("#welcome").remove()

    display.draw(boards)

    socket.message((dispatcher, message) => (({action, ...args}) => {
			logger(`Dispatching ${action} with ${args}`)

      dispatcher[action](args)
    })(dispatcher, JSON.parse(message)))

    socket.send({ action, name })
  }

  function rotate(to) {
    socket.send({ action: "rotate", to })
  }

  // moving

  function registerMove(from, to_square, turn) {
    const to = parseInt(to_square.attr("id").substring(1))
    boards["c"].obj.update_state( from
                                , to
                                , (message, callback) => {
                                    if (message == "promote") display.promotion_dialog(turn, callback)
                                    else if (message == "complete") {
                                      draw_board(boards, "c")
                                      socket.send({ action: "position", from, to })
                                    }
                                  }
                                )
  }

  // helpers
  function getLocationFromPieceDiv({length}, d) {
    return parseInt(d.parent()[0].id.substring(length))
  }
}

export const __useDefault = true
<commit_msg>hide helper function<commit_after>import Board from 'alekhine'

import Display from './display'
import Socket from './socket'

import logger from "./logger"

const display = Display()
const socket = new Socket()

export default function() {
  const selected = null
  let show_moves = true
  let promotion_piece = null

  const boards = {
    "l" : mkBoardState(true),
    "c" : mkBoardState(false),
    "r" : mkBoardState(true)
  }

  const dispatcher = {
    hold: () => {
      display.show_hold_dialog()
    },

    game: (data) => {
      display.color = data.color

      if (data.color == "b") {
        ib.toggle_flip_board()
        display.draw(boards); // ?
      }

      const hold = $("#hold")
      if (hold.hasClass("ui-dialog-content")) { // prevent exception when trying to destroy uninitialized dialog
        hold.dialog("destroy")
        hold.addClass("hidden")
      }

      $("#play").removeClass("hidden")
      display.update(boards, data)

      // boards must be drawn at least once first
      display.squarify()
    },

    kibitz: (data) => {
      $("#kibitz").removeClass("hidden")

      display.update(boards, data)
      display.squarify()
    },

    rotate: (data) => {
      if (data.to === "l" || data.to === "r") {
        display.rotate(data)
      } else {
        display.update(boards, data)
        ib.toggle_flip_board()
        display.squarify()
      }
    }

    /*
    socket.on("message", function(data) {
      // position update
      if (data.state) {
        for (var b in boards) {
          if (boards[b].gid == data.state.gid) {
            boards[b].obj.set_fen(data.state.fen, function(message) {
              if (message == "converted") draw_board(b)
            })
          }
        }
      }
    })
    */
  }

  return {
    play() {
      init("join")
    },

    kibitz() {
      init("kibitz")
    },

    toggle_show_moves(sm) {
      show_moves = sm
      $(".droppable").removeClass("droppable")
    },

    toggle_flip_board() {
      boards["l"].flipped = boards["r"].flipped = boards["c"].flipped
      boards["c"].flipped = !boards["c"].flipped

      display.draw(boards)
    },

    toggle_promotion_piece(piece) {
      if (promotion_piece) $(`#promotion_piece${promotion_piece}`).removeClass("promotion_piece_selected")
      $(`#promotion_piece${piece}`).addClass("promotion_piece_selected")

      promotion_piece = piece
    },

    redraw_boards() {
      display.draw(boards)
    },

    head() {
      rotate("h")
    },

    prev() {
      rotate("l")
    },

    next() {
      rotate("r")
    },

    tail() {
      rotate("t")
    }
  }

  // flipped with respect to fen
  function mkBoardState(flipped) {
    return {
      flipped,
      gid: null,
      obj: null,
      black: "",
      white: "",
      stash_b: "",
      stash_w: ""
    }
  }

  function init(action) {
    // board is required first
    const board = new Board()

    // set name
    const name = $("#name").val() || "anonymous"

    // create and display
    for (const b in boards) boards[b].obj = new Board()

    $("#welcome").remove()

    display.draw(boards)

    socket.message((dispatcher, message) => (({action, ...args}) => {
			logger(`Dispatching ${action} with ${args}`)

      dispatcher[action](args)
    })(dispatcher, JSON.parse(message)))

    socket.send({ action, name })
  }

  function rotate(to) {
    socket.send({ action: "rotate", to })
  }

  // moving

  function registerMove(from, to_square, turn) {
    const to = parseInt(to_square.attr("id").substring(1))
    boards["c"].obj.update_state( from
                                , to
                                , (message, callback) => {
                                    if (message == "promote") display.promotion_dialog(turn, callback)
                                    else if (message == "complete") {
                                      draw_board(boards, "c")
                                      socket.send({ action: "position", from, to })
                                    }
                                  }
                                )
  }

  // helpers
  function getLocationFromPieceDiv({length}, d) {
    return parseInt(d.parent()[0].id.substring(length))
  }
}

export const __useDefault = true
<|endoftext|>