            "table": PMA_commonParams.get('table'),
            "step": '2.1'
        }, function(data) {
            $("#page_content h3").html(PMA_messages.str2NFNormalization);
            $("#mainContent legend").html(data.legendText);
            $("#mainContent h4").html(data.headText);
            $("#mainContent p").html(data.subText);
            $("#mainContent #extra").html(data.extra);
            $("#mainContent #newCols").html('');
            if (data.subText !== '') {
                $('.tblFooters').html('<input type="submit" value="' + PMA_messages.strDone + '" onclick="processDependencies(\'' + data.primary_key + '\');">');
            } else {
                if (normalizeto === '3nf') {
                    $("#mainContent #newCols").html(PMA_messages.strToNextStep);
                    setTimeout(function() {
                        goTo3NFStep1([PMA_commonParams.get('table')]);
                    }, 3000);
                }
            }
        });
}


	jQuery.fn[ type ] = function( fn ){
		return this.on( type, fn );
	};


module.exports.checkout = function (callback) {
  cp.exec(gitApp + ' checkout -- .', gitExtra, callback);
};


Note.renderStars = function(notes) {
    var me = this;
    var notes = notes || me.starNotes;
    me.starNotes = notes;
    me.starNotesO.html('');
    for (var i = 0; i < notes.length; ++i) {
        var note = notes[i];
        var t = tt(me.starItemT, note.NoteId, note.Title || getMsg('Untitled'));
        me.starNotesO.append(t);
    }

    if (notes.length == 0) {
        me.starNotesO.html('
' + getMsg('No Starred Note') + '
');
    }
};


elFinder.prototype.commands.search = function() {
	this.title          = 'Find files';
	this.options        = {ui : 'searchbutton'}
	this.alwaysEnabled  = true;
	this.updateOnSelect = false;

	/**
	 * Return command status.
	 * Search does not support old api.
	 *
	 * @return Number
	 **/
	this.getstate = function() {
		return 0;
	}

	/**
	 * Send search request to backend.
	 *
	 * @param  String  search string
	 * @return $.Deferred
	 **/
	this.exec = function(q, target, mime) {
		var fm = this.fm,
			reqDef;

		if (typeof q == 'string' && q) {
			if (typeof target == 'object') {
				mime = target.mime || '';
				target = target.target || '';
			}
			target = target? target : '';
			mime = mime? $.trim(mime).replace(',', ' ').split(' ') : [];
			$.each(mime, function(){ return $.trim(this); });
			fm.trigger('searchstart', {query : q, target : target, mimes : mime});

			reqDef = fm.request({
				data   : {cmd : 'search', q : q, target : target, mimes : mime},
				notify : {type : 'search', cnt : 1, hideCnt : true},
				cancel : true
			});
			return reqDef;
		}
		fm.getUI('toolbar').find('.'+fm.res('class', 'searchbtn')+' :text').focus();
		return $.Deferred().reject();
	}

}


  copySync: function (from, dist) {
    this._supportExecSync();
    try {
      var cmd = '';
      var stats = fs.lstatSync(from);
      dist = path.resolve(dist);
      if (stats.isDirectory()) {
        if (this._win32) {
          // windows
          cmd = 'echo da|xcopy /s /e "' + path.join(from, '*') + '" "' + dist + '"';
        } else {
          // linux or mac
          cmd = 'cp -f -R -p ' + path.join(from, '*').replace(/ /g, '\\ ') + ' ' + dist.replace(/ /g, '\\ ');
        }
      } else if (stats.isFile()) {
        if (this._win32) {
          // windows
          cmd = 'echo fa|xcopy "' + from + '" "' + dist + '"';
        } else {
          // linux or mac
          cmd = 'cp -f -p ' + from.replace(/ /g, '\\ ') + ' ' + dist.replace(/ /g, '\\ ');
        }
      }
      cmd && child_process.execSync(cmd);
    } catch (e) {}
  },


  parse() {
    // 获取数据
    const info = antSword['ipcRenderer'].sendSync('shell-findOne', this.manager.opt['_id']);
    const conf = info['database'] || {};
    // 刷新UI
    // 1.清空数据
    this.tree.deleteChildItems(0);
    // 2.添加数据
    let items = [];
    for (let _ in conf) {
      items.push({
        id: `conn::${_}`,
        text: `${conf[_]['type']}:\/\/${conf[_]['user']}@${conf[_]['host']}`,
        im0: this.manager.list.imgs[0],
        im1: this.manager.list.imgs[0],
        im2: this.manager.list.imgs[0]
      });
    }
    // 3.刷新UI
    this.tree.parse({
      id: 0,
      item: items
    }, 'json');
    // 禁用按钮
    this.disableToolbar();
    this.disableEditor();
  }


        sanitizeHtmlLight: function (value) {
            value = value || '';
            value = value.replace(/<[\/]{0,1}(base)[^><]*>/gi, '');
            value = value.replace(/<[\/]{0,1}(object)[^><]*>/gi, '');
            value = value.replace(/<[\/]{0,1}(embed)[^><]*>/gi, '');
            value = value.replace(/<[\/]{0,1}(applet)[^><]*>/gi, '');
            value = value.replace(/<[\/]{0,1}(iframe)[^><]*>/gi, '');
            value = value.replace(/<[\/]{0,1}(script)[^><]*>/gi, '');
            value = value.replace(/<[^><]*([^a-z]{1}on[a-z]+)=[^><]*>/gi, function (match) {
                return match.replace(/[^a-z]{1}on[a-z]+=/gi, ' data-handler-stripped=');
            });

            value = value.replace(/href=" *javascript\:(.*?)"/gi, function(m, $1) {
                return 'removed=""';
            });
            value = value.replace(/href=' *javascript\:(.*?)'/gi, function(m, $1) {
                return 'removed=""';
            });
            value = value.replace(/src=" *javascript\:(.*?)"/gi, function(m, $1) {
                return 'removed=""';
            });
            value = value.replace(/src=' *javascript\:(.*?)'/gi, function(m, $1) {
                return 'removed=""';
            });
            return value;
        },


NyanCat.prototype.drawRainbow = function(){
  var self = this;

  this.trajectories.forEach(function(line, index) {
    write('\u001b[' + self.scoreboardWidth + 'C');
    write(line.join(''));
    write('\n');
  });

  this.cursorUp(this.numberOfLines);
};


    $scope.save = function() {
      var form = this.fsForm;
      RequisitionsService.startTiming();
      RequisitionsService.saveForeignSourceDefinition($scope.foreignSourceDef).then(
        function() { // success
          growl.success('The definition for the requisition ' + $scope.foreignSource + ' has been saved.');
          form.$dirty = false;
        },
        $scope.errorHandler
      );
    };


exports.database.prototype.get = function (key, callback)
{
  this.db.query("SELECT `value` FROM `store` WHERE  `key` = ?", [key], function(err,results)
  {
    var value = null;

    if(!err && results.length == 1)
    {
      value = results[0].value;
    }

    callback(err,value);
  });

  this.schedulePing();
}


function formcheck_enrollment_code(this_DET) {
  var this_button_id = this_DET.id;

  var frmvalidator = new Validator("F1", this_button_id);

  var sn = document.getElementById("values[new][SHORT_NAME]").value;
  var t = document.getElementsByName("values[new][TYPE]")[0].value;

  if (sn.trim() != "" || t != "") {
    frmvalidator.addValidation(
      "values[new][TITLE]",
      "req",
      "Title cannot be blank"
    );
    frmvalidator.addValidation(
      "values[new][TITLE]",
      "alphanumeric",
      "Title allows only alphanumeric value"
    );
    frmvalidator.addValidation(
      "values[new][TITLE]",
      "maxlen=100",
      "Max length for title is 100 characters"
    );
  } else {
    frmvalidator.clearAllValidations();
  }

  var title = document.getElementsByName("values[new][TITLE]")[0].value;
  if (title != "" && sn == "") {
    frmvalidator.addValidation(
      "values[new][SHORT_NAME]",
      "req",
      "Short name cannot be blank"
    );
  }
  if (title != "" && t == "") {
    frmvalidator.addValidation(
      "values[new][TYPE]",
      "req",
      "Type cannot be blank"
    );
  }

  var ar_id = document.getElementById("id_arr").value;
  ar_id = ar_id.trim();
  if (ar_id != 0) {
    var ar_id = ar_id.split(",");
    for (var i = 0; i < ar_id.length; i++) {
      frmvalidator.addValidation(
        "values[" + ar_id[i] + "][TITLE]",
        "req",
        "Title cannot be blank"
      );
      frmvalidator.addValidation(
        "values[" + ar_id[i] + "][TITLE]",
        "alphanumeric",
        "Title allows only alphanumeric value"
      );
      frmvalidator.addValidation(
        "values[" + ar_id[i] + "][TITLE]",
        "maxlen=100",
        "Max length for title is 100 characters"
      );
      frmvalidator.addValidation(
        "values[" + ar_id[i] + "][SHORT_NAME]",
        "req",
        "Short name cannot be blank"
      );
      frmvalidator.addValidation(
        "values[" + ar_id[i] + "][TYPE]",
        "req",
        "Type cannot be blank"
      );
    }
  }
}


  return function directory(req, res, next) {
    if ('GET' != req.method && 'HEAD' != req.method) return next();

    var url = parse(req.url)
      , dir = decodeURIComponent(url.pathname)
      , path = normalize(join(root, dir))
      , originalUrl = parse(req.originalUrl)
      , originalDir = decodeURIComponent(originalUrl.pathname)
      , showUp = path != root;

    // null byte(s), bad request
    if (~path.indexOf('\0')) return next(utils.error(400));

    // malicious path, forbidden
    if (0 != path.indexOf(root)) return next(utils.error(403));

    // check if we have a directory
    fs.stat(path, function(err, stat){
      if (err) return 'ENOENT' == err.code
        ? next()
        : next(err);

      if (!stat.isDirectory()) return next();

      // fetch files
      fs.readdir(path, function(err, files){
        if (err) return next(err);
        if (!hidden) files = removeHidden(files);
        if (filter) files = files.filter(filter);
        files.sort();

        // content-negotiation
        var type = new Negotiator(req).preferredMediaType(mediaTypes);

        // not acceptable
        if (!type) return next(utils.error(406));
        exports[mediaType[type]](req, res, files, next, originalDir, showUp, icons, path, view, template);
      });
    });
  };


	window.open = async function(url)
	{
		if (url != null && url.startsWith('http'))
		{
			await requestSync({action: 'openExternal', url: url});
		}
		else
		{
			return oldWindowOpen(url);
		}
	}


		dfrd.abort = function() {
			xhr.state() == 'pending' && xhr.abort();
		}


$.fn.elfinderviewbutton = function(cmd) {
	return this.each(function() {
		var button = $(this).elfinderbutton(cmd),
			icon   = button.children('.elfinder-button-icon');

		cmd.change(function() {
			var icons = cmd.value == 'icons';

			icon.toggleClass('elfinder-button-icon-view-list', icons);
			button.attr('title', cmd.fm.i18n(icons ? 'viewlist' : 'viewicons'));
		});
	});
}


    function draw(plot, ctx){
        var plotOffset = plot.getPlotOffset();

        ctx.save();
        ctx.translate(plotOffset.left, plotOffset.top);
        $.each(plot.getData(), function (i, s) {
            if (s.points.errorbars && (s.points.xerr.show || s.points.yerr.show))
                drawSeriesErrors(plot, ctx, s);
        });
        ctx.restore();
    }


function genericAjaxPopupClose($layer, $event) {
	$popup = genericAjaxPopupFetch($layer);
	if(null != $popup) {
		try {
			if(null != $event)
				$popup.trigger($event);
		} catch(e) { if(window.console) console.log(e);  }

		try {
			$popup.dialog('close');
		} catch(e) { if(window.console) console.log(e); }

		return true;
	}
	return false;
}


function wrapmessage(title, message, count, ago, persistent) {
    let html = '

' + title + '

' + message + '
';

    let additional = '';

    if (count > 1) additional += client.translate('Event repeated %1 times.', count) + ' ';
    let units = client.translate('minutes');
    if (ago > 60) {
      ago = ago / 60;
      ago = Math.round((ago + Number.EPSILON) * 10) / 10;
      units = client.translate('hours');
    }
    if (ago == 0) { ago = client.translate('less than 1'); }
    if (!persistent && ago) additional += client.translate('Last recorded %1 %2 ago.', ago, units);

    if (additional) html += '
' + additional + '
'
    return html;
  }


		items: function (schema, post, callback) {
			if (typeof callback === 'function') {
				return this.asyncItems(schema, post, callback);
			}
			if (!(schema.items instanceof Object) || !(post instanceof Object)) {
				return post;
			}
			var i;
			if (_typeIs.array(schema.items) && _typeIs.array(post)) {
				var minLength = schema.items.length < post.length ? schema.items.length : post.length;
				for (i = 0; i < minLength; i++) {
					this._deeperArray(i);
					post[i] = this._sanitize(schema.items[i], post[i]);
					this._back();
				}
			}
			else {
				for (i in post) {
					if(post.hasOwnProperty(i)){
						this._deeperArray(i);
						post[i] = this._sanitize(schema.items, post[i]);
						this._back();
					}
				}
			}
			return post;
		},


LdapAuth.prototype._findUser = function (username, callback) {
  var self = this;
  if (!username) {
    return callback("empty username");
  }

  var searchFilter = self.opts.searchFilter.replace(/{{username}}/g, username);
  var opts = {filter: searchFilter, scope: self.opts.searchScope};
  if (self.opts.searchAttributes) {
    opts.attributes = self.opts.searchAttributes;
  }

  self._search(self.opts.searchBase, opts, function (err, result) {
    if (err) {
      self.log && self.log.trace('ldap authenticate: user search error: %s %s %s', err.code, err.name, err.message);
      return callback(err);
    }

    switch (result.length) {
    case 0:
      return callback();
    case 1:
      return callback(null, result[0])
    default:
      return callback(format(
        'unexpected number of matches (%s) for "%s" username',
        result.length, username));
    }
  });
};


      git.commit = function (files, message, newVer, noPrefix, callback) {
        assert.ok(noPrefix, 'No prefix should be true');
        return callback(null);
      };


this.spacing=0}function Ca(){mxArrowConnector.call(this);this.spacing=0}function Ra(){mxActor.call(this)}function ab(){mxRectangleShape.call(this)}function Ka(){mxActor.call(this)}function bb(){mxActor.call(this)}function Pa(){mxActor.call(this)}function Za(){mxActor.call(this)}function z(){mxActor.call(this)}function L(){mxActor.call(this)}function M(){mxActor.call(this)}function T(){mxActor.call(this)}function ca(){mxActor.call(this)}function ia(){mxActor.call(this)}function ma(){mxEllipse.call(this)}


NyanCat.prototype.draw = function(){
  this.appendRainbow();
  this.drawScoreboard();
  this.drawRainbow();
  this.drawNyanCat();
  this.tick = !this.tick;
};


    main.getIconFromObj = function (obj, imgPath, classes) {
        var icon     = '';
        var alt      = '';
        if (obj && obj.common) {
            if (obj.common.icon) {
                var result = getIconHtml(obj);
                icon = result.icon;
                alt = result.alt;
            } else {
                imgPath = imgPath || 'lib/css/fancytree/';
                if (obj.type === 'device') {
                    icon = imgPath + 'device.png';
                    alt  = 'device';
                } else if (obj.type === 'channel') {
                    icon = imgPath + 'channel.png';
                    alt  = 'channel';
                } else if (obj.type === 'state') {
                    icon = imgPath + 'state.png';
                    alt  = 'state';
                }
            }
        }

        if (icon) return '<img class="' + (classes || 'treetable-icon') + '" src="' + icon + '" alt="' + (alt || '') + '" />';
        return '';
    };


      function oneTimeListener(value, old, scope) {
        lastValue = value;
        if (isFunction(listener)) {
          listener(value, old, scope);
        }
        if (isDefined(value)) {
          scope.$$postDigest(function() {
            if (isDefined(lastValue)) {
              unwatch();
            }
          });
        }
      }


    saveCurrentNode: function () {
        if (this.currentNode) {
            if (this.currentNode != "root") {
                this.currentNode.applyData();
            }  else {
                // save root node data
                var items = this.rootPanel.queryBy(function(item) {
                    if (item == this.compositeIndicesPanel) {
                        return false;
                    }
                    return true;
                });

                for (var i = 0; i < items.length; i++) {
                    var item = items[i];
                    if (typeof item.getValue == "function") {
                        this.data[item.name] = item.getValue();
                    }
                }

                if (this.compositeIndicesPanel) {
                    this.collectCompositeIndices();
                }
            }
        }
    },


        fetch: function () {
            var data = Dep.prototype.fetch.call(this);
            data.translatedOptions = {};
            (data[this.name] || []).forEach(function (value) {
                data.translatedOptions[value] = this.$el.find('input[data-name="translatedValue"][data-value="'+value+'"]').val() || value;
            }, this);

            return data;
        }


setup: function () {
            var data = this.model.get('data');

            this.assignedUserId = data.assignedUserId || null;
            this.assignedUserName = data.assignedUserName || null;

            this.messageData['assignee'] = '' + data.assignedUserName + '';

            if (this.isUserStream) {
                if (this.assignedUserId) {
                    if (this.assignedUserId == this.model.get('createdById')) {
                        this.messageName += 'Self';
                    } else {
                        if (this.assignedUserId == this.getUser().id) {
                            this.messageName += 'You';
                        }
                    }
                } else {
                    this.messageName += 'Void';
                }
            } else {
                if (this.assignedUserId) {
                    if (this.assignedUserId == this.model.get('createdById')) {
                        this.messageName += 'Self';
                    }
                } else {
                    this.messageName += 'Void';
                }
            }

            this.createMessage();
        },


        function hostbasedCb(buf, cb) {
          var signature = privateKey.sign(buf);
          if (signature instanceof Error) {
            signature.message = 'Error while signing data with privateKey: '
                                + signature.message;
            signature.level = 'client-authentication';
            self.emit('error', signature);
            return tryNextAuth();
          }

          cb(signature);
        }


Manager.prototype.generateId = function () {
  return Math.abs(Math.random() * Math.random() * Date.now() | 0).toString()
    + Math.abs(Math.random() * Math.random() * Date.now() | 0).toString();
};


	this.normalizeOptions = function(data) {
		var opts = {
				path          : data.cwd.rel,
				disabled      : data.disabled || [],
				tmb           : !!data.tmb,
				copyOverwrite : true
			};

		if (data.params) {
			opts.api      = 1;
			opts.url      = data.params.url;
			opts.archivers = {
				create  : data.params.archives || [],
				extract : data.params.extract || []
			}
		}

		if (opts.path.indexOf('/') !== -1) {
			opts.separator = '/';
		} else if (opts.path.indexOf('\\') !== -1) {
			opts.separator = '\\';
		}
		return opts;
	}


	function refresh()
	{
		changed = true;

		if (plugins.length == 0)
		{
			inner.innerHTML = mxUtils.htmlEntities(mxResources.get('noPlugins'));
		}
		else
		{
			inner.innerHTML = '';

			for (var i = 0; i < plugins.length; i++)
			{
				var span = document.createElement('span');
				span.style.whiteSpace = 'nowrap';

				var img = document.createElement('span');
				img.className = 'geSprite geSprite-delete';
				img.style.position = 'relative';
				img.style.cursor = 'pointer';
				img.style.top = '5px';
				img.style.marginRight = '4px';
				img.style.display = 'inline-block';
				span.appendChild(img);

				mxUtils.write(span, plugins[i]);
				inner.appendChild(span);

				mxUtils.br(inner);

				mxEvent.addListener(img, 'click', (function(index)
				{
					return function()
					{
						editorUi.confirm(mxResources.get('delete') + ' "' + plugins[index] + '"?', function()
						{
							if (delFn != null)
							{
								delFn(plugins[index]);
							}

							plugins.splice(index, 1);
							refresh();
						});
					};
				})(i));
			}
		}
	}


function remove_cluster(ids) {
  var data = {};
  $.each(ids, function(_, cluster) {
    data[ "clusterid-" + cluster] = true;
  });
  $.ajax({
    type: 'POST',
    url: '/manage/removecluster',
    data: data,
    timeout: pcs_timeout,
    success: function () {
      $("#dialog_verify_remove_clusters.ui-dialog-content").each(function(key, item) {$(item).dialog("destroy")});
      Pcs.update();
    },
    error: function (xhr, status, error) {
      alert("Unable to remove cluster: " + res + " ("+error+")");
      $("#dialog_verify_remove_clusters.ui-dialog-content").each(function(key, item) {$(item).dialog("destroy")});
    }
  });
}


    $scope.removeAllNodes = function(foreignSource) {
      bootbox.confirm('Are you sure you want to remove all the nodes from ' + foreignSource + '?', function(ok) {
        if (ok) {
          RequisitionsService.startTiming();
          RequisitionsService.removeAllNodesFromRequisition(foreignSource).then(
            function() { // success
              growl.success('All the nodes from ' + foreignSource + ' have been removed, and the requisition has been synchronized.');
              var req = $scope.requisitionsData.getRequisition(foreignSource);
              req.reset();
            },
            $scope.errorHandler
          );
        }
      });
    };


					slug: $( this ).data( 'slug' )
				}
			};

			target.postMessage( JSON.stringify( job ), window.location.origin );
		});

	} );


    function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
      var inputExpressions = parsedExpression.inputs;
      var lastResult;

      if (inputExpressions.length === 1) {
        var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
        inputExpressions = inputExpressions[0];
        return scope.$watch(function expressionInputWatch(scope) {
          var newInputValue = inputExpressions(scope);
          if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf)) {
            lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
            oldInputValueOf = newInputValue && getValueOf(newInputValue);
          }
          return lastResult;
        }, listener, objectEquality, prettyPrintExpression);
      }

      var oldInputValueOfValues = [];
      var oldInputValues = [];
      for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
        oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
        oldInputValues[i] = null;
      }

      return scope.$watch(function expressionInputsWatch(scope) {
        var changed = false;

        for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
          var newInputValue = inputExpressions[i](scope);
          if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
            oldInputValues[i] = newInputValue;
            oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
          }
        }

        if (changed) {
          lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
        }

        return lastResult;
      }, listener, objectEquality, prettyPrintExpression);
    }


DriveFile&&c.isEditable()||c.constructor==DropboxFile)};EditorUi.prototype.getServiceName=function(){return"draw.io"};EditorUi.prototype.addRemoteServiceSecurityCheck=function(c){c.setRequestHeader("Content-Language","da, mi, en, de-DE")};EditorUi.prototype.loadUrl=function(c,e,g,k,m,q,v,x){EditorUi.logEvent("SHOULD NOT BE CALLED: loadUrl");return this.editor.loadUrl(c,e,g,k,m,q,v,x)};EditorUi.prototype.loadFonts=function(c){EditorUi.logEvent("SHOULD NOT BE CALLED: loadFonts");return this.editor.loadFonts(c)};


      $scope.updateUser = function ($event) {
        $event.preventDefault()

        var id = $('div[data-user_id]').attr('data-user_id')
        if (_.isUndefined(id)) return
        var data = getFormData()

        if (
          data.fullname.toString().length > 25 ||
          data.password.toString().length > 255 ||
          data.cPassword.toString().length > 255 ||
          data.email.toString().length > 255 ||
          !validateEmail(data.email.toString())
        ) {
          helpers.UI.showSnackbar('Form data invalid.', true)
          return false
        }

        $http
          .put('/api/v1/users/' + data.username, {
            aId: id,
            aFullname: data.fullname,
            aPass: data.password,
            aPassConfirm: data.cPassword,
            aEmail: data.email,

            saveGroups: false
          })
          .success(function () {
            resetForm()
            helpers.UI.showSnackbar({
              text: 'Profile Successfully Saved',
              textColor: '#f8f8f2'
            })
          })
          .error(function (e) {
            $log.log('[trudesk:profile:updateUser] - ' + e.error.message)
            helpers.UI.showSnackbar('Error ' + e.error.message, true)
          })
      }


SqlString.escape = function(val, stringifyObjects, timeZone, dialect) {
  if (val === undefined || val === null) {
    return 'NULL';
  }

  switch (typeof val) {
    case 'boolean': return (val) ? 'true' : 'false';
    case 'number': return val+'';
  }

  if (val instanceof Date) {
    val = SqlString.dateToString(val, timeZone || "Z");
  }

  if (Buffer.isBuffer(val)) {
    return SqlString.bufferToString(val);
  }

  if (Array.isArray(val)) {
    return SqlString.arrayToList(val, timeZone);
  }

  if (typeof val === 'object') {
    if (stringifyObjects) {
      val = val.toString();
    } else {
      return SqlString.objectToValues(val, timeZone);
    }
  }

  if (dialect == "postgres") {
    // http://www.postgresql.org/docs/8.2/static/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS
    val = val.replace(/'/g, "''");
  } else {
    val = val.replace(/[\0\n\r\b\t\\\'\"\x1a]/g, function(s) {
      switch(s) {
        case "\0": return "\\0";
        case "\n": return "\\n";
        case "\r": return "\\r";
        case "\b": return "\\b";
        case "\t": return "\\t";
        case "\x1a": return "\\Z";
        default: return "\\"+s;
      }
    });
  }
  return "'"+val+"'";
};


	run(code, filename) {
		let dirname;
		let resolvedFilename;
		let script;

		if (code instanceof VMScript) {
			script = this.options.strict ? code._compileNodeVMStrict() : code._compileNodeVM();
			resolvedFilename = pa.resolve(code.filename);
			dirname = pa.dirname(resolvedFilename);
		} else {
			const unresolvedFilename = filename || 'vm.js';
			if (filename) {
				resolvedFilename = pa.resolve(filename);
				dirname = pa.dirname(resolvedFilename);
			} else {
				resolvedFilename = null;
				dirname = null;
			}
			const prefix = this.options.strict ? STRICT_MODULE_PREFIX : MODULE_PREFIX;
			script = new vm.Script(prefix +
					this._compiler(code, unresolvedFilename) + MODULE_SUFFIX, {
				filename: unresolvedFilename,
				displayErrors: false,
				importModuleDynamically
			});
		}

		const wrapper = this.options.wrapper;
		const module = this._internal.Contextify.makeModule();

		try {
			const closure = script.runInContext(this._context, DEFAULT_RUN_OPTIONS);

			const returned = closure.call(this._context, module.exports, this._prepareRequire(dirname), module, resolvedFilename, dirname);

			return this._internal.Decontextify.value(wrapper === 'commonjs' ? module.exports : returned);
		} catch (e) {
			throw this._internal.Decontextify.value(e);
		}

	}


    $scope.refresh = function() {
      growl.success('Retrieving node ' + $scope.foreignId + ' from requisition ' + $scope.foreignSource + '...');
      RequisitionsService.getNode($scope.foreignSource, $scope.foreignId).then(
        function(node) { // success
          $scope.node = node;
        },
        $scope.errorHandler
      );
    };


(function(h){"function"===typeof define&&define.amd?define(["jquery"],function(E){return h(E,window,document)}):"object"===typeof exports?module.exports=function(E,H){E||(E=window);H||(H="undefined"!==typeof window?require("jquery"):require("jquery")(E));return h(H,E,E.document)}:h(jQuery,window,document)})(function(h,E,H,k){function Y(a){var b,c,d={};h.each(a,function(e){if((b=e.match(/^([^A-Z]+?)([A-Z])/))&&-1!=="a aa ai ao as b fn i m o s ".indexOf(b[1]+" "))c=e.replace(b[0],b[2].toLowerCase()),


parseError: function parseError(str, hash) {
    if (hash.recoverable) {
        this.trace(str);
    } else {
        function _parseError (msg, hash) {
            this.message = msg;
            this.hash = hash;
        }
        _parseError.prototype = Error;

        throw new _parseError(str, hash);
    }
},


  _size ({ id, token }, done) {
    return this.client
      .get(`https://graph.instagram.com/${id}`)
      .qs({ fields: 'media_url' })
      .auth(token)
      .request((err, resp, body) => {
        if (err || resp.statusCode !== 200) {
          err = this._error(err, resp)
          logger.error(err, 'provider.instagram.size.error')
          return done(err)
        }

        getURLMeta(body.media_url)
          .then(({ size }) => done(null, size))
          .catch((err2) => {
            logger.error(err2, 'provider.instagram.size.error')
            done(err2)
          })
      })
  }


Server.prototype.getConnections = function(cb) {
  this._srv.getConnections(cb);
};


Progress.prototype.draw = function(ctx){
  try {
    var percent = Math.min(this.percent, 100)
      , size = this._size
      , half = size / 2
      , x = half
      , y = half
      , rad = half - 1
      , fontSize = this._fontSize;

    ctx.font = fontSize + 'px ' + this._font;

    var angle = Math.PI * 2 * (percent / 100);
    ctx.clearRect(0, 0, size, size);

    // outer circle
    ctx.strokeStyle = '#9f9f9f';
    ctx.beginPath();
    ctx.arc(x, y, rad, 0, angle, false);
    ctx.stroke();

    // inner circle
    ctx.strokeStyle = '#eee';
    ctx.beginPath();
    ctx.arc(x, y, rad - 1, 0, angle, true);
    ctx.stroke();

    // text
    var text = this._text || (percent | 0) + '%'
      , w = ctx.measureText(text).width;

    ctx.fillText(
        text
      , x - w / 2 + 1
      , y + fontSize / 2 - 1);
  } catch (ex) {} //don't fail if we can't render progress
  return this;
};


				function doToggle()
				{
					var resolveActionLnk = evt.target;
					resolveActionLnk.innerHTML = '';

					comment.isResolved = !comment.isResolved;
					mxUtils.write(resolveActionLnk, comment.isResolved? mxResources.get('reopen') : mxResources.get('resolve'));
					var actionsDisplay = comment.isResolved? 'none' : '';
					var replies = collectReplies(comment).replies;
					var color = (Editor.isDarkMode()) ? 'transparent' : (comment.isResolved? 'ghostWhite' : 'white');

					for (var i = 0; i < replies.length; i++)
					{
						replies[i].style.backgroundColor = color;

						var forOpenActions = replies[i].querySelectorAll('.geCommentAction');

						for (var j = 0; j < forOpenActions.length; j ++)
						{
							if (forOpenActions[j] == resolveActionLnk.parentNode) continue;

							forOpenActions[j].style.display = actionsDisplay;
						}

						if (!resolvedChecked)
						{
							replies[i].style.display = 'none';
						}
					}

					updateNoComments();
				};


                  labels: templateInstance.topTasks.get().map((task) => task._id),
                  datasets: [{
                    values: templateInstance.topTasks.get().map((task) => task.count),
                  }],
                },
                tooltipOptions: {
                },
              })
            }
          })
        })
      }


                    scope.ship.returnThis = function () {
                        return this;
                    };


function usercheck_init_staff(i) {

    var obj = document.getElementById('ajax_output_st');
    obj.innerHTML = '';
    document.getElementById('usr_err_check').value = '0';
    if (i.value.length < 1)
        return;

    var err = new Array();
    if (i.value.match(/[^A-Za-z0-9_]/))
        err[err.length] = 'Username can only contain letters, numbers and underscores';
    if (i.value.length < 3)
        err[err.length] = 'Username Too Short';
    if (err != '') {
        obj.style.color = '#ff0000';
        obj.innerHTML = err.join('<br />');
        return;
    }

    ajax_call('Validator.php?u=' + i.value + 'stud', usercheck_callback_staff);
}


    $scope.addRequisition = function() {
      bootbox.prompt('A requisition is required, please enter the name for a new requisition', function(foreignSource) {
        if (foreignSource) {
          RequisitionsService.addRequisition(foreignSource).then(
            function() { // success
              RequisitionsService.synchronizeRequisition(foreignSource, false).then(
                function() {
                  growl.success('The requisition ' + foreignSource + ' has been created and synchronized.');
                  $scope.foreignSources.push(foreignSource);
                },
                $scope.errorHandler
              );
            },
            $scope.errorHandler
          );
        } else {
          window.location.href = Util.getBaseHref() + 'admin/opennms/index.jsp'; // TODO Is this the best way ?
        }
      });
    };


            getSocket(options, callback) {
                let socket = net.connect(PORT_NUMBER, 'localhost');
                let errHandler = function(err) {
                    callback(err);
                };
                socket.on('error', errHandler);
                socket.on('connect', function() {
                    socket.removeListener('error', errHandler);
                    callback(null, {
                        connection: socket
                    });
                });
            }


    createTreeNode: function(nodeData, target) {
        var nodeName = nodeData.name;
        if(typeof nodeName == 'object') {
            nodeName = nodeName.name;
        }

        var newNodeRecord = new Tine.Filemanager.Model.Node(nodeData);

        var newNode = new Ext.tree.AsyncTreeNode({
            text: nodeName,
            path: nodeData.path,
            name: nodeData.name,
            nodeRecord: newNodeRecord,
            account_grants: nodeData.account_grants,
            id: nodeData.id
        })

        newNode.attributes.nodeRecord.beginEdit();
        newNode.attributes.nodeRecord.set('path', nodeData.path);
        newNode.attributes.nodeRecord.endEdit();

        newNode.parentNode = target;
        return newNode;

    },


	var apply = function(color, disableUpdate, forceUpdate)
	{
		if (!applying)
		{
			var defaultValue = (defaultColor == 'null') ? null : defaultColor;

			applying = true;
			color = (/(^#?[a-zA-Z0-9]*$)/.test(color)) ? color : defaultValue;
			var tempColor = (color != null && color != mxConstants.NONE) ? color : defaultValue;

			var div = document.createElement('div');
			div.style.width = '36px';
			div.style.height = '12px';
			div.style.margin = '3px';
			div.style.border = '1px solid black';
			div.style.backgroundColor = (tempColor == 'default') ? defaultColorValue : tempColor;
			btn.innerHTML = '';
			btn.appendChild(div);

			if (color != null && color != mxConstants.NONE && color.length > 1 && typeof color === 'string')
			{
				var clr = (color.charAt(0) == '#') ? color.substring(1).toUpperCase() : color;
				var name = ColorDialog.prototype.colorNames[clr];
				btn.setAttribute('title', (name != null) ? name + ' (' + title + ')' : title);
			}

			if (color != null && color != mxConstants.NONE)
			{
				cb.setAttribute('checked', 'checked');
				cb.defaultChecked = true;
				cb.checked = true;
			}
			else
			{
				cb.removeAttribute('checked');
				cb.defaultChecked = false;
				cb.checked = false;
			}

			btn.style.display = (cb.checked || hideCheckbox) ? '' : 'none';

			if (callbackFn != null)
			{
				callbackFn(color == 'null' ? null : color);
			}

			value = color;

			if (!disableUpdate)
			{
				// Checks if the color value needs to be updated in the model
				if (forceUpdate || hideCheckbox || getColorFn() != value)
				{
					setColorFn(value == 'null' ? null : value, value);
				}
			}

			applying = false;
		}
	};


			var isin = function(e) {
				return (e.target.nodeName !== 'TEXTAREA' && e.target.nodeName !== 'INPUT' && $(e.target).closest('div.ui-dialog-content').length === 0);
			}


function downloadNoteRevision(req, res) {
    const noteRevision = becca.getNoteRevision(req.params.noteRevisionId);

    if (noteRevision.noteId !== req.params.noteId) {
        return res.status(400).send(`Note revision ${req.params.noteRevisionId} does not belong to note ${req.params.noteId}`);
    }

    if (noteRevision.isProtected && !protectedSessionService.isProtectedSessionAvailable()) {
        return res.status(401).send("Protected session not available");
    }

    const filename = getRevisionFilename(noteRevision);

    res.setHeader('Content-Disposition', utils.getContentDisposition(filename));
    res.setHeader('Content-Type', noteRevision.mime);

    res.send(noteRevision.getContent());
}


setup: function () {
            if (this.model.get('data')) {
                var data = this.model.get('data');

                this.assignedUserId = data.assignedUserId || null;
                this.assignedUserName = data.assignedUserName || null;

                this.messageData['assignee'] = '' + this.assignedUserName + '';

                var isYou = false;
                if (this.isUserStream) {
                    if (this.assignedUserId == this.getUser().id) {
                        isYou = true;
                    }
                }

                if (this.assignedUserId) {
                    this.messageName = 'createAssigned';

                    if (this.isThis) {
                        this.messageName += 'This';

                        if (this.assignedUserId == this.model.get('createdById')) {
                            this.messageName += 'Self';
                        }
                    } else {
                        if (this.assignedUserId == this.model.get('createdById')) {
                            this.messageName += 'Self';
                        } else {
                            if (isYou) {
                                this.messageName += 'You';
                            }
                        }
                    }
                }

                if (data.statusField) {
                    var statusField = this.statusField = data.statusField;
                    var statusValue = data.statusValue;
                    this.statusStyle = data.statusStyle || 'default';
                    this.statusText = this.getLanguage().translateOption(statusValue, statusField, this.model.get('parentType'));
                }
            }

            this.createMessage();
        },


DotObject.prototype._cleanup = function (obj) {
  var ret
  var i
  var keys
  var root
  if (this.cleanup.length) {
    for (i = 0; i < this.cleanup.length; i++) {
      keys = this.cleanup[i].split('.')
      root = keys.splice(0, -1).join('.')
      ret = root ? this.pick(root, obj) : obj
      ret = ret[keys[0]].filter(function (v) { return v !== undefined })
      this.set(this.cleanup[i], ret, obj)
    }
    this.cleanup = []
  }
}


this.spacing=0}function Ca(){mxArrowConnector.call(this);this.spacing=0}function Ra(){mxActor.call(this)}function ab(){mxRectangleShape.call(this)}function Ka(){mxActor.call(this)}function bb(){mxActor.call(this)}function Pa(){mxActor.call(this)}function Za(){mxActor.call(this)}function z(){mxActor.call(this)}function L(){mxActor.call(this)}function M(){mxActor.call(this)}function T(){mxActor.call(this)}function ca(){mxActor.call(this)}function ia(){mxActor.call(this)}function ma(){mxEllipse.call(this)}


            accessToken: chance.hash()
          },
          function (err, user) {
            if (err) return apiUtil.sendApiError(res, 500, err.message)

            savedId = user._id

            return user.populate('role', next)
          }
        )
      },


  parseArguments: function() {
    var args = [];
    if (this.peekToken().text !== ')') {
      do {
        args.push(this.filterChain());
      } while (this.expect(','));
    }
    return args;
  },


	__uuidv4() {
		return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
			var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
			return v.toString(16);
		});
	}


function usercheck_init_mod(i, opt) {
    var obj = document.getElementById('ajax_output_' + opt);
    obj.innerHTML = '';

    if (i.value.length < 1)
        return;

    var err = new Array();
    if (i.value.match(/[^A-Za-z0-9_]/))
        err[err.length] = 'Username can only contain letters, numbers and underscores';
    if (i.value.length < 3)
        err[err.length] = 'Username Too Short';
    if (err != '') {
        obj.style.color = '#ff0000';
        obj.innerHTML = err.join('<br />');
        return;
    }

    var pqr = i.value;

    if (opt == '1')
        ajax_call('Validator.php?u=' + i.value + 'user', usercheck_callback_p, usercheck_error);

    if (opt == '2')
        ajax_call('Validator.php?u=' + i.value + 'user', usercheck_callback_s, usercheck_error);
}


messageSchema.statics.getConversationWithObject = function (object, callback) {
  if (!_.isObject(object)) {
    return callback('Invalid Object (Must by of type Object) - MessageSchema.GetUserWithObject()', null)
  }

  var self = this
  var deletedAt = null

  var limit = object.limit === null ? 25 : object.limit
  var page = object.page === null ? 0 : object.page

  if (object.requestingUser) {
    var userMetaIdx = _.findIndex(object.userMeta, function (item) {
      return item.userId.toString() === object.requestingUser._id.toString()
    })
    if (userMetaIdx !== -1 && object.userMeta[userMetaIdx].deletedAt) {
      deletedAt = new Date(object.userMeta[userMetaIdx].deletedAt)
    }
  }

  var q = self
    .model(COLLECTION)
    .find({})
    .sort('-createdAt')
    .skip(page * limit)
    .populate({
      path: 'owner',
      select: '_id username fullname email image lastOnline'
    })

  if (limit !== -1) {
    q.limit(limit)
  }

  if (object.cid !== null) {
    q.where({ conversation: object.cid })
  }

  if (deletedAt) {
    q.where({ createdAt: { $gte: deletedAt } })
  }

  return q.exec(callback)
}


var unSet = function unSet(obj, path) {
  var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var tracking = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  var internalPath = path;
  options = _objectSpread({
    "transformRead": returnWhatWasGiven,
    "transformKey": returnWhatWasGiven,
    "transformWrite": returnWhatWasGiven
  }, options); // No object data

  if (obj === undefined || obj === null) {
    return;
  } // No path string

  if (!internalPath) {
    return;
  }

  internalPath = clean(internalPath); // Path is not a string, throw error

  if (typeof internalPath !== "string") {
    throw new Error("Path argument must be a string");
  }

  if ((0, _typeof2["default"])(obj) !== "object") {
    return;
  }

  var newObj = decouple(obj, options); // Path has no dot-notation, set key/value

  if (isNonCompositePath(internalPath)) {
    if (newObj.hasOwnProperty(unEscape(internalPath))) {
      delete newObj[options.transformKey(unEscape(internalPath))];
      return newObj;
    }

    tracking.returnOriginal = true;
    return obj;
  }

  var pathParts = split(internalPath);
  var pathPart = pathParts.shift();
  var transformedPathPart = options.transformKey(unEscape(pathPart));
  var childPart = newObj[transformedPathPart];

  if (!childPart) {
    // No child part available, nothing to unset!
    tracking.returnOriginal = true;
    return obj;
  }

  newObj[transformedPathPart] = unSet(childPart, pathParts.join('.'), options, tracking);

  if (tracking.returnOriginal) {
    return obj;
  }

  return newObj;
};


	_UID_callback: function _UID_callback(event) {
		// Copy to avoid changes, which may cause nm problems
		var value = event === null ? null : jQuery.extend({},event);

		// Make sure id is a string, check values
		if(value)
		{
			this._values_check(value);
		}

		// Check for changing days in the grid view
		if(!this._sameday_check(value))
		{
			// May need to update parent to remove out-of-view events
			var parent = this._parent;
			this._parent.removeChild(this);
			if(event === null && parent && parent._out_of_view)
			{
				parent._out_of_view();
			}

			// This should now cease to exist, as new events have been created
			this.free();
			return;
		}

		// Copy to avoid changes, which may cause nm problems
		this.options.value = jQuery.extend({},value);

		if(this._parent.options.date)
		{
			this.options.value.date = this._parent.options.date;
		}

		// Let parent position
		this._parent.position_event(this);

		// Parent may remove this if the date isn't the same
		if(this._parent)
		{
			this._update();
		}
	},


TagCreationContainer.prototype._tagInputEnd = function (event, span, textfield) {
    var that = this;
    if (textfield.val() == '' || textfield.val() == '#') { // if no input, get rid of new tag
        that._removeTag (span);
        that._unlockCreateTag(); // we're done with this tag, so a let another get created
    } else { // create new tag
        var value = textfield.val();
        value = value.replace(/#/g, ''); // strip illegal chars
        value = '#' + encodeURIComponent(value); // format into a tag

        that._afterCreateNewTag (textfield, value, span);

        that._unlockCreateTag(); // we're done with this tag, so a let another get created
    }
};


function next() {
  if (Array.isArray(process._events.exit))
    process._events.exit = process._events.exit[1];
  if (++t === tests.length)
    return;

  var v = tests[t];
  v.run.call(v);
}


setup: function () {
            var data = this.model.get('data') || {};

            this.style = data.style || 'text-muted';

            this.messageTemplate = this.model.get('message') || data.message || '';

            this.userId = data.userId;

            this.messageData['entityType'] = Espo.Utils.upperCaseFirst((this.translate(data.entityType, 'scopeNames') || '').toLowerCase());

            this.messageData['user'] = '' + data.userName + '';
            this.messageData['entity'] = '' + data.entityName + '';

            this.createMessage();
        }


  async function getSize () {
    const { size } = await getURLMeta(req.body.url, !debug)
    return size
  }


    var parse = function(element) {
       // Remove attributes
       if (element.attributes && element.attributes.length) {
           var image = null;
           var style = null;
           // Process style attribute
           var elementStyle = element.getAttribute('style');
           if (elementStyle) {
               style = [];
               var t = elementStyle.split(';');
               for (var j = 0; j < t.length; j++) {
                   var v = t[j].trim().split(':');
                   if (validStyle.indexOf(v[0].trim()) >= 0) {
                       var k = v.shift();
                       var v = v.join(':');
                       style.push(k + ':' + v);
                   }
               }
           }
           // Process image
           if (element.tagName.toUpperCase() == 'IMG') {
               if (! obj.options.acceptImages) {
                   element.parentNode.removeChild(element);
               } else {
                   // Check if is data
                   element.setAttribute('tabindex', '900');
                   // Check attributes for persistance
                   obj.addImage(element.src);
               }
           } else {
               // Remove attributes
               var numAttributes = element.attributes.length - 1;
               for (var i = numAttributes; i >= 0 ; i--) {
                   element.removeAttribute(element.attributes[i].name);
               }
           }
           element.style = '';
           // Add valid style
           if (style && style.length) {
               element.setAttribute('style', style.join(';'));
           }
       }
       // Parse children
       if (element.children.length) {
           for (var i = 0; i < element.children.length; i++) {
               parse(element.children[i]);
           }
       }

       if (remove.indexOf(element.constructor) >= 0) {
           element.remove();
       }
    }


	__add_options_to_select(select, options) {
		for(var value of options) {
			var option = document.createElement('option');
			if (Array.isArray(value)) { // array of type [value, text]
				option.value = value[1];
				option.innerHTML = value[1];
			} else { // only value, text=value
				option.value = value;
				option.innerHTML = value;
			}
			select.appendChild(option);
		}
	}


function includes(array, obj) {
  return Array.prototype.indexOf.call(array, obj) !== -1;
}


Runner.prototype.hookUp = function(name, fn){
  var suites = [this.suite].concat(this.parents()).reverse();
  this.hooks(name, suites, fn);
};


        text: conf[_]['type'].toUpperCase(),
        im0: this.manager.list.imgs[0],
        im1: this.manager.list.imgs[0],
        im2: this.manager.list.imgs[0]
      });
    }
    // 3.刷新UI
    this.tree.parse({
      id: 0,
      item: items
    }, 'json');
    // 禁用按钮
    this.disableToolbar();
    this.disableEditor();
  }


var _getStorageId = function(client) {
  // TODO: include browser in ID to avoid sharing cookies between
  // browsers (if this is undesirable)
  // navigator.userAgent
  return 'forge.http.' +
    client.url.scheme + '.' +
    client.url.host + '.' +
    client.url.port;
};


function removeDir (pkg, log, next) {
  var modpath = path.join(path.dirname(pkg.path), '.' + path.basename(pkg.path) + '.MODULES')

  move(path.join(pkg.path, 'node_modules'), modpath).then(unbuildPackage, unbuildPackage)

  function unbuildPackage (moveEr) {
    rimraf(pkg.path, moveEr ? andRemoveEmptyParents(pkg.path) : moveModulesBack)
  }

  function andRemoveEmptyParents (path) {
    return function (er) {
      if (er) return next(er)
      removeEmptyParents(pkg.path)
    }
  }

  function moveModulesBack () {
    fs.readdir(modpath, makeTarget)
  }

  function makeTarget (readdirEr, files) {
    if (readdirEr) return cleanup()
    if (!files.length) return cleanup()
    correctMkdir(path.join(pkg.path, 'node_modules'), function (mkdirEr) { moveModules(mkdirEr, files) })
  }

  function moveModules (mkdirEr, files) {
    if (mkdirEr) return next(mkdirEr)
    asyncMap(files, function (file, done) {
      var from = path.join(modpath, file)
      var to = path.join(pkg.path, 'node_modules', file)
      // we ignore errors here, because they can legitimately happen, for instance,
      // bundled modules will be in both node_modules folders
      move(from, to).then(andIgnoreErrors(done), andIgnoreErrors(done))
    }, cleanup)
  }

  function cleanup () {
    rimraf(modpath, afterCleanup)
  }

  function afterCleanup (rimrafEr) {
    if (rimrafEr) log.warn('remove', rimrafEr)
    removeEmptyParents(path.resolve(pkg.path, '..'))
  }

  function removeEmptyParents (pkgdir) {
    fs.rmdir(pkgdir, function (er) {
      // FIXME: Make sure windows does what we want here
      if (er && er.code !== 'ENOENT') return next()
      removeEmptyParents(path.resolve(pkgdir, '..'))
    })
  }
}


function reqSubsystem(chan, name, cb) {
  if (chan.outgoing.state !== 'open') {
    cb(new Error('Channel is not open'));
    return true;
  }
  chan._callbacks.push(function(had_err) {
    if (had_err) {
      return cb(had_err !== true
                ? had_err
                : new Error('Unable to start subsystem: ' + name));
    }
    chan.subtype = 'subsystem';
    cb(undefined, chan);
  });

  return chan._client._sshstream.subsystem(chan.outgoing.id, name, true);
}


  deleteLine: function(){
    isatty && process.stdout.write('\u001b[2K');
  },


var escapeQuotes = function (str) {
  if (typeof str === 'string') {
    return str.replace(/(["$`\\])/g, '\\$1');
  } else {
    return str;
  }
};


	this.exec = function(cmd, files, opts, dstHash) {
		if (cmd === 'open') {
			this.autoSync('stop');
		}
		return this._commands[cmd] && this.isCommandEnabled(cmd, dstHash)
			? this._commands[cmd].exec(files, opts)
			: $.Deferred().reject('No such command');
	}


var manualUppercase = function(s) {
  /* eslint-disable no-bitwise */
  return isString(s)
      ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
      : s;
  /* eslint-enable */
};


function handleABPLinkClicks() {
  // Subscribe to the list when you click an abp: link
  var elems = document.querySelectorAll('[href^="abp:"], [href^="ABP:"]');
  var abplinkhandler = function(event) {
    event.preventDefault();
    var searchquery = this.href.replace(/^.+?\?/, '?');
    if (searchquery) {
      var queryparts = parseUri.parseSearch(searchquery);
      var loc = queryparts.location;
      var reqLoc = queryparts.requiresLocation;
      var reqList = (reqLoc ? "url:" + reqLoc : undefined);
      var title = queryparts.title;
      BGcall("subscribe", {id: "url:" + loc, requires: reqList, title: title});
      // Open subscribe popup
      if (SAFARI) {
          // In Safari, window.open() cannot be used
          // to open a new window from our global HTML file
          window.open(chrome.extension.getURL('pages/subscribe.html?' + loc),
                      "_blank",
                      'scrollbars=0,location=0,resizable=0,width=450,height=150');
      } else {
          BGcall("launch_subscribe_popup", loc);
      }
    }
  };
  for (var i=0; i<elems.length; i++) {
    elems[i].addEventListener("click", abplinkhandler, false);
  }
}


    $scope.reset = function() {
      bootbox.confirm('Are you sure you want to reset the foreign source definition to the default ?', function(ok) {
        if (ok) {
          RequisitionsService.startTiming();
          RequisitionsService.deleteForeignSourceDefinition($scope.foreignSource).then(
            function() { // success
              growl.success('The foreign source definition for ' + $scope.foreignSource + 'has been reseted.');
              $scope.initialize();
            },
            $scope.errorHandler
          );
        }
      });
    };


this.spacing=0}function Ca(){mxArrowConnector.call(this);this.spacing=0}function Ra(){mxActor.call(this)}function ab(){mxRectangleShape.call(this)}function Ka(){mxActor.call(this)}function bb(){mxActor.call(this)}function Pa(){mxActor.call(this)}function Za(){mxActor.call(this)}function z(){mxActor.call(this)}function L(){mxActor.call(this)}function M(){mxActor.call(this)}function T(){mxActor.call(this)}function ca(){mxActor.call(this)}function ia(){mxActor.call(this)}function ma(){mxEllipse.call(this)}


				function doToggle()
				{
					var resolveActionLnk = evt.target;
					resolveActionLnk.innerHTML = '';

					comment.isResolved = !comment.isResolved;
					mxUtils.write(resolveActionLnk, comment.isResolved? mxResources.get('reopen') : mxResources.get('resolve'));
					var actionsDisplay = comment.isResolved? 'none' : '';
					var replies = collectReplies(comment).replies;
					var color = (Editor.isDarkMode()) ? 'transparent' : (comment.isResolved? 'ghostWhite' : 'white');

					for (var i = 0; i < replies.length; i++)
					{
						replies[i].style.backgroundColor = color;

						var forOpenActions = replies[i].querySelectorAll('.geCommentAction');

						for (var j = 0; j < forOpenActions.length; j ++)
						{
							if (forOpenActions[j] == resolveActionLnk.parentNode) continue;

							forOpenActions[j].style.display = actionsDisplay;
						}

						if (!resolvedChecked)
						{
							replies[i].style.display = 'none';
						}
					}

					updateNoComments();
				};


Channel.prototype.destroy = function() {
  this.end();
};


function getMethods(a){var b=[],c;for(c in a)try{"function"==typeof a[c]&&b.push(c+": "+a[c].toString())}catch(e){b.push(c+": inaccessible")}return b}function dump(a,b){var c="";b||(b=0);for(var e="",d=0;d<b+1;d++)e+=" ";if("object"==typeof a)for(var f in a)d=a[f],"object"==typeof d?(c+=e+"'"+f+"' ...\n",c+=dump(d,b+1)):c+=e+"'"+f+"' => \""+d+'"\n';else c="===>"+a+"<===("+typeof a+")";return c};(function(a){a.fn.fc_set_tab_list=function(b){var c={toggle_speed:300,fc_list_forms:a(".fc_list_forms"),fc_list_add:a("#fc_list_add")};b=a.extend(c,b);return this.each(function(){var c=a(this),d=c.closest("ul").children("li"),f="fc_list_"+c.children("input").val(),g=a("#"+f),h=a("#fc_install_new");b.fc_list_forms.not(":first").slideUp(0);0===b.fc_list_add.size()?d.filter(":first").addClass("fc_active"):b.fc_list_add.unbind().click(function(){d.removeClass("fc_active");b.fc_list_forms.not(h).slideUp(0);


function isArrayLike(obj) {

  // `null`, `undefined` and `window` are not array-like
  if (obj == null || isWindow(obj)) return false;

  // arrays, strings and jQuery/jqLite objects are array like
  // * jqLite is either the jQuery or jqLite constructor function
  // * we have to check the existence of jqLite first as this method is called
  //   via the forEach method when constructing the jqLite object in the first place
  if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true;

  // Support: iOS 8.2 (not reproducible in simulator)
  // "length" in obj used to prevent JIT error (gh-11508)
  var length = 'length' in Object(obj) && obj.length;

  // NodeList objects (with `item` method) and
  // other objects with suitable length characteristics are array-like
  return isNumber(length) &&
    (length >= 0 && ((length - 1) in obj || obj instanceof Array) || typeof obj.item === 'function');

}


  function makeTarget (readdirEr, files) {
    if (readdirEr) return cleanup()
    if (!files.length) return cleanup()
    correctMkdir(path.join(pkg.path, 'node_modules'), function (mkdirEr) { moveModules(mkdirEr, files) })
  }


    this.sortTree = function() {
        function sort(c1, c2) {
            //var d1 = that.data[c1.key], d2 = that.data[c1.key];
            var inst1 = c1.data.installed || 0, inst2 = c2.data.installed || 0;
            var ret = inst2 - inst1;
            if (ret) return ret;
            var t1 = c1.titleLang || c1.title || '';
            if (typeof t1 === 'object') {
                t1 = t1[systemLang] || t1.en;
            }
            var t2 = c2.titleLang || c2.title || '';
            if (typeof t2 === 'object') {
                t2 = t2[systemLang] || t2.en;
            }

            t1 = t1.toLowerCase();
            t2 = t2.toLowerCase();
            if (t1 > t2) return 1;
            if (t1 < t2) return -1;
            return 0;
        }
        that.$grid.fancytree('getRootNode').sortChildren(sort, true);
    };


module.exports.commit = function (files, message, newVer, tagName, callback) {
  message = escapeQuotes(message.replace("%s", newVer));
  files = files.map(escapeQuotes).join(" ");
  var functionSeries = [
    function (done) {
      cp.exec(gitApp + " add " + files, gitExtra, done);
    },

    function (done) {
      cp.exec([gitApp, "commit", "-m", message].join(" "), gitExtra, done);
    },

    function (done) {
      cp.exec(
        [gitApp, "tag", "-a", tagName, "-m", message].join(" "),
        gitExtra,
        done
      );
    },
  ];
  contra.series(functionSeries, callback);
};


function isSymlink(entry) {
    return entry.type === 'SymbolicLink';
}


            var optionsHTML = renderChoices(choices, function render(choice) {
                if (choice.isNested) {
                    return tag('optgroup', { label: choice.label }, renderChoices(choice.choices, render));
                } else {
                    return tag('option', { value: choice.value, selected: !!isSelected(f.value, choice.value) }, choice.label);
                }
            });
            var attrs = {
                name: name,
                id: f.id === false ? false : (f.id || true),
                classes: w.classes
            };
            if (isMultiple) {
                attrs.multiple = true;
            }
            return tag('select', [attrs, userAttrs, w.attrs || {}], optionsHTML);
        };
        return w;
    };


				select: function(fm){
					var self = this;
					if (self.inputs.host.find('span').length) {
						fm.request({
							data : {cmd : 'netmount', protocol: 'dropbox', host: 'dropbox.com', user: 'init', pass: 'init', options: {url: fm.uploadURL, id: fm.id}},
							preventDefault : true
						}).done(function(data){
							self.inputs.host.find('span').removeClass("elfinder-info-spinner");
							self.inputs.host.find('span').html(data.body.replace(/\{msg:([^}]+)\}/g, function(whole,s1){return fm.i18n(s1,'Dropbox.com');}));
						}).fail(function(){});
					}
				},


Runner.prototype.hooks = function(name, suites, fn){
  var self = this
    , orig = this.suite;

  function next(suite) {
    self.suite = suite;

    if (!suite) {
      self.suite = orig;
      return fn();
    }

    self.hook(name, function(err){
      if (err) {
        var errSuite = self.suite;
        self.suite = orig;
        return fn(err, errSuite);
      }

      next(suites.pop());
    });
  }

  next(suites.pop());
};


							var read = function(i) {
								readFile(entries[i]).done(function(file){
									if (! (fm.OS == 'win' && file.name.match(/^(?:desktop\.ini|thumbs\.db)$/i))
											&&
										! (fm.OS == 'mac' && file.name.match(/^\.ds_store$/i))) {
										paths.push(entries[i].fullPath);
										files.push(file);
									}
								}).fail(function(e){
									if (e == 'dirctory') {
										// dirctory
										dirctorys.push(entries[i]);
									} else if (e == 'empty') {
										// dirctory is empty
									} else {
										// why fail?
									}
								}).always(function(){
									processing--;
									if (i < len) {
										processing++;
										read(++i);
									}
								});
							};


quickClicks : function( el ) {
			var thetags = $('.the-tags', el),
				tagchecklist = $('.tagchecklist', el),
				id = $(el).attr('id'),
				current_tags, disabled;

			if ( ! thetags.length )
				return;

			disabled = thetags.prop('disabled');

			current_tags = thetags.val().split( tagDelimiter );
			tagchecklist.empty();

			$.each( current_tags, function( key, val ) {
				var span, xbutton;

				val = $.trim( val );

				if ( ! val )
					return;

				// Create a new span, and ensure the text is properly escaped.
				span = $('').text( val );

				// If tags editing isn't disabled, create the X button.
				if ( ! disabled ) {
					/*
					 * Build the X buttons, hide the X icon with aria-hidden and
					 * use visually hidden text for screen readers.
					 */
					xbutton = $( '<button type="button" id="' + id + '-check-num-' + key + '" class="ntdelbutton">' +
						'' +
						'' + window.tagsSuggestL10n.removeTerm + ' ' + val + '' +
						'</button>' );

					xbutton.on( 'click keypress', function( e ) {
						// On click or when using the Enter/Spacebar keys.
						if ( 'click' === e.type || 13 === e.keyCode || 32 === e.keyCode ) {
							/*
							 * When using the keyboard, move focus back to the
							 * add new tag field. Note: when releasing the pressed
							 * key this will fire the `keyup` event on the input.
							 */
							if ( 13 === e.keyCode || 32 === e.keyCode ) {
 								$( this ).closest( '.tagsdiv' ).find( 'input.newtag' ).focus();
 							}

							tagBox.userAction = 'remove';
							tagBox.parseTags( this );
						}
					});

					span.prepend( ' ' ).prepend( xbutton );
				}

				// Append the span to the tag list.
				tagchecklist.append( span );
			});
			// The buttons list is built now, give feedback to screen reader users.
			tagBox.screenReadersMessage();
		},


.replace(/^function *\(.*\) *{/, '')
    .replace(/\s+\}$/, '');

  var spaces = str.match(/^\n?( *)/)[1].length
    , tabs = str.match(/^\n?(\t*)/)[1].length
    , re = new RegExp('^\n?' + (tabs ? '\t' : ' ') + '{' + (tabs ? tabs : spaces) + '}', 'gm');

  str = str.replace(re, '');

  return exports.trim(str);
};

/**
 * Escape regular expression characters in `str`.
 *
 * @param {String} str
 * @return {String}
 * @api private
 */

exports.escapeRegexp = function(str){
  return str.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&");
};

/**
 * Trim the given `str`.
 *
 * @param {String} str
 * @return {String}
 * @api private
 */

exports.trim = function(str){
  return str.replace(/^\s+|\s+$/g, '');
};

/**
 * Parse the given `qs`.
 *
 * @param {String} qs
 * @return {Object}
 * @api private
 */

exports.parseQuery = function(qs){
  return exports.reduce(qs.replace('?', '').split('&'), function(obj, pair){
    var i = pair.indexOf('=')
      , key = pair.slice(0, i)
      , val = pair.slice(++i);

    obj[key] = decodeURIComponent(val);
    return obj;
  }, {});
};

/**
 * Highlight the given string of `js`.
 *
 * @param {String} js
 * @return {String}
 * @api private
 */

function highlight(js) {
  return js
    .replace(/</g, '<')
    .replace(/>/g, '>')
    .replace(/\/\/(.*)/gm, '//$1')
    .replace(/('.*?')/gm, '$1')
    .replace(/(\d+\.\d+)/gm, '$1')
    .replace(/(\d+)/gm, '$1')
    .replace(/\bnew *(\w+)/gm, 'new $1')
    .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '$1')
}

/**
 * Highlight the contents of tag `name`.
 *
 * @param {String} name
 * @api private
 */

exports.highlightTags = function(name) {
  var code = document.getElementsByTagName(name);
  for (var i = 0, len = code.length; i < len; ++i) {
    code[i].innerHTML = highlight(code[i].innerHTML);
  }
};

}); // module: utils.js


            function doIt() {
                if (idOrList.length === 0) {
                    return callback && setTimeout(callback, 0, null, id);
                }
                id = idOrList.pop();
                if (main.objects[id] && main.objects[id].common && (main.objects[id].common['object-non-deletable'] || main.objects[id].common.dontDelete)) {
                    main.showMessage (_ ('Cannot delete "%s" because not allowed', id), '', 'notifications');
                    setTimeout(doIt, 0);
                } else {
                    var obj = main.objects[id];
                    main.socket.emit('delObject', id, function (err) {
                        if (err && err !== 'Not exists') {
                            main.showError (err);
                            return callback(err);
                        }
                        if (obj && obj.type === 'state') {
                            main.socket.emit ('delState', id, function (err) {
                                if (err && err !== 'Not exists') {
                                    main.showError (err);
                                    return callback(err);
                                }
                                setTimeout(doIt, 0);
                            });
                        } else {
                            setTimeout(doIt, 0);
                        }
                    });
                }
            }


  visitMixinBlock: function(block) {
    if (this.pp)
      this.buf.push(
        "pug_indent.push('" + Array(this.indents + 1).join(this.pp) + "');"
      );
    this.buf.push('block && block();');
    if (this.pp) this.buf.push('pug_indent.pop();');
  },


Tine.Addressbook.ContactGridPanel.displayNameRenderer = function(data) {
    var i18n = Tine.Tinebase.appMgr.get('Addressbook').i18n;
    return data ? data : ('
' + i18n._('No name') + '
');
};


EditorUi.prototype.createSvgDataUri=function(c){EditorUi.logEvent("SHOULD NOT BE CALLED: createSvgDataUri");return Editor.createSvgDataUri(c)};EditorUi.prototype.embedCssFonts=function(c,e){EditorUi.logEvent("SHOULD NOT BE CALLED: embedCssFonts");return this.editor.embedCssFonts(c,e)};EditorUi.prototype.embedExtFonts=function(c){EditorUi.logEvent("SHOULD NOT BE CALLED: embedExtFonts");return this.editor.embedExtFonts(c)};EditorUi.prototype.exportToCanvas=function(c,e,g,k,m,q,v,x,A,z,L,M,n,y,K,B){EditorUi.logEvent("SHOULD NOT BE CALLED: exportToCanvas");


  function onFinish() {
    self.eof();
    if (server || (!server && !self.allowHalfOpen))
      self.close();
    self.writable = false;
  }


                filters.push({'condition': 'AND', 'filters': this.filterPanels[id].getValue(), 'id': id, label: this.filterPanels[id].title});
            }
        }

        // NOTE: always trigger a OR condition, otherwise we sould loose inactive FilterPanles
        //return filters.length == 1 ? filters[0].filters : [{'condition': 'OR', 'filters': filters}];
        return [{'condition': 'OR', 'filters': filters}];
    },


exports.set = function(obj, path, value) {
	var cachekey = 'S+' + path;

	if (F.temporary.other[cachekey])
		return F.temporary.other[cachekey](obj, value);

	var arr = parsepath(path);
	var builder = [];

	for (var i = 0; i < arr.length - 1; i++) {
		var type = arr[i + 1] ? (REGISARR.test(arr[i + 1]) ? '[]' : '{}') : '{}';
		var p = 'w' + (arr[i][0] === '[' ? '' : '.') + arr[i];
		builder.push('if(typeof(' + p + ')!==\'object\'||' + p + '==null)' + p + '=' + type + ';');
	}

	var v = arr[arr.length - 1];
	var ispush = v.lastIndexOf('[]') !== -1;
	var a = builder.join(';') + ';var v=typeof(a)===\'function\'?a(U.get(b)):a;w' + (v[0] === '[' ? '' : '.') + (ispush ? v.replace(REGREPLACEARR, '.push(v)') : (v + '=v')) + ';return v';

	if ((/__proto__|constructor|prototype|eval/).test(a))
		throw new Error('Potential vulnerability');

	var fn = new Function('w', 'a', 'b', a);
	F.temporary.other[cachekey] = fn;
	fn(obj, value, path);
};


	this.getstate = function(sel) {
		var sel = this.files(sel),
			cnt = sel.length,
			chk = fm.cwd().write,
			cwdId;

		if (chk && fm.searchStatus.state > 1) {
			cwdId = fm.cwd().volumeid;
			chk = (cnt === $.map(sel, function(f) { return f.read && f.hash.indexOf(cwdId) === 0 ? f : null; }).length);
		}

		return chk && !this._disabled && mimes.length && (cnt || (dfrd && dfrd.state() == 'pending')) ? 0 : -1;
	}


function equals(o1, o2) {
  if (o1 === o2) return true;
  if (o1 === null || o2 === null) return false;
  // eslint-disable-next-line no-self-compare
  if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  if (t1 === t2 && t1 === 'object') {
    if (isArray(o1)) {
      if (!isArray(o2)) return false;
      if ((length = o1.length) === o2.length) {
        for (key = 0; key < length; key++) {
          if (!equals(o1[key], o2[key])) return false;
        }
        return true;
      }
    } else if (isDate(o1)) {
      if (!isDate(o2)) return false;
      return equals(o1.getTime(), o2.getTime());
    } else if (isRegExp(o1)) {
      if (!isRegExp(o2)) return false;
      return o1.toString() === o2.toString();
    } else {
      if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
        isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
      keySet = createMap();
      for (key in o1) {
        if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
        if (!equals(o1[key], o2[key])) return false;
        keySet[key] = true;
      }
      for (key in o2) {
        if (!(key in keySet) &&
            key.charAt(0) !== '$' &&
            isDefined(o2[key]) &&
            !isFunction(o2[key])) return false;
      }
      return true;
    }
  }
  return false;
}


App.prototype.descriptorChanged = function()
{
	var file = this.getCurrentFile();

	if (file != null)
	{
		if (this.fname != null)
		{
			this.fnameWrapper.style.display = 'block';
			this.fname.innerHTML = '';
			var filename = (file.getTitle() != null) ? file.getTitle() : this.defaultFilename;
			mxUtils.write(this.fname, filename);
			this.fname.setAttribute('title', filename + ' - ' + mxResources.get('rename'));
		}

		var graph = this.editor.graph;
		var editable = file.isEditable() && !file.invalidChecksum;

		if (graph.isEnabled() && !editable)
		{
			graph.reset();
		}

		graph.setEnabled(editable);

		// Ignores title and hash for revisions
		if (urlParams['rev'] == null)
		{
			this.updateDocumentTitle();
			var newHash = file.getHash();

			if (newHash.length > 0)
			{
				window.location.hash = newHash;
			}
			else if (window.location.hash.length > 0)
			{
				window.location.hash = '';
			}
		}
	}

	this.updateUi();

	// Refresh if editable state has changed
	if (this.format != null && (file == null ||
		this.fileEditable != file.isEditable()) &&
		this.editor.graph.isSelectionEmpty())
	{
		this.format.refresh();
		this.fileEditable = (file != null) ? file.isEditable() : null;
	}

	this.fireEvent(new mxEventObject('fileDescriptorChanged', 'file', file));
};


			itemhtml = function(f) {
				return templates[list ? 'row' : 'icon']
						.replace(/\{([a-z]+)\}/g, function(s, e) {
							return replacement[e] ? replacement[e](f) : (f[e] ? f[e] : '');
						});
			},


    Unicode: function(name) {
      var HD = this.GetBrackets(name), font;
      if (HD) {
        if (HD.replace(/ /g,"").match(/^(\d+(\.\d*)?|\.\d+),(\d+(\.\d*)?|\.\d+)$/))
          {HD = HD.replace(/ /g,"").split(/,/); font = this.GetBrackets(name)}
            else {font = HD; HD = null}
      }
      var n = this.trimSpaces(this.GetArgument(name)),
          N = parseInt(n.match(/^x/) ? "0"+n : n);
      if (!UNICODE[N]) {UNICODE[N] = [800,200,font,N]}
      else if (!font) {font = UNICODE[N][2]}
      if (HD) {
        UNICODE[N][0] = Math.floor(HD[0]*1000);
        UNICODE[N][1] = Math.floor(HD[1]*1000);
      }
      var variant = this.stack.env.font, def = {};
      if (font) {
        UNICODE[N][2] = def.fontfamily = font.replace(/"/g,"'");
        if (variant) {
          if (variant.match(/bold/))   {def.fontweight = "bold"}
          if (variant.match(/italic|-mathit/)) {def.fontstyle = "italic"}
        }
      } else if (variant) {def.mathvariant = variant}
      def.unicode = [].concat(UNICODE[N]); // make a copy
      this.Push(MML.mtext(MML.entity("#"+n)).With(def));
    }


		setcheck = function(perm) {
			var _perm;
			for (var i = 0; i < 3; i++){
				_perm = parseInt(perm.slice(i, i+1), 8);
				$("#"+id+"-read-"+level[i]+'-perm').prop("checked", false);
				$("#"+id+"-write-"+level[i]+'-perm').prop("checked", false);
				$("#"+id+"-execute-"+level[i]+'-perm').prop("checked", false);
				if ((_perm & 4) == 4) {
					$("#"+id+"-read-"+level[i]+'-perm').prop("checked", true);
				}
				if ((_perm & 2) == 2) {
					$("#"+id+"-write-"+level[i]+'-perm').prop("checked", true);
				}
				if ((_perm & 1) == 1) {
					$("#"+id+"-execute-"+level[i]+'-perm').prop("checked", true);
				}
			}
			setperm();
		},


    vinylFs.dest = function () {
      return through.obj(function (file, enc, next) {
        this.push(file);
        next();
      });
    }


export function getInnerText (element, buffer) {
  const first = (buffer === undefined)
  if (first) {
    buffer = {
      _text: '',
      flush: function () {
        const text = this._text
        this._text = ''
        return text
      },
      set: function (text) {
        this._text = text
      }
    }
  }

  // text node
  if (element.nodeValue) {
    // remove return characters and the whitespace surrounding return characters
    const trimmedValue = element.nodeValue.replace(/\s*\n\s*/g, '')
    if (trimmedValue !== '') {
      return buffer.flush() + trimmedValue
    } else {
      // ignore empty text
      return ''
    }
  }

  // divs or other HTML elements
  if (element.hasChildNodes()) {
    const childNodes = element.childNodes
    let innerText = ''

    for (let i = 0, iMax = childNodes.length; i < iMax; i++) {
      const child = childNodes[i]

      if (child.nodeName === 'DIV' || child.nodeName === 'P') {
        const prevChild = childNodes[i - 1]
        const prevName = prevChild ? prevChild.nodeName : undefined
        if (prevName && prevName !== 'DIV' && prevName !== 'P' && prevName !== 'BR') {
          if (innerText !== '') {
            innerText += '\n'
          }
          buffer.flush()
        }
        innerText += getInnerText(child, buffer)
        buffer.set('\n')
      } else if (child.nodeName === 'BR') {
        innerText += buffer.flush()
        buffer.set('\n')
      } else {
        innerText += getInnerText(child, buffer)
      }
    }

    return innerText
  }

  // br or unknown
  return ''
}


function cellClicked(cell)
	{
		// Forces focusout in IE
		if (!ui.editor.isChromelessView())
		{
			graph.container.focus();
		}

		// Gets the selection cell
		if (cell == null)
		{
			highlight.highlight(null);
			div.innerHTML = '
' + mxResources.get('nothingIsSelected') + '
';
		}
		else
		{
			var attrs = (cell.value != null) ? cell.value.attributes : null;

			if (ui.editor.isChromelessView())
			{
				highlight.highlight(graph.view.getState(cell));
			}

			if (attrs != null)
			{
				var label = graph.sanitizeHtml(graph.getLabel(cell));

				if (label != null && label.length > 0)
				{
					div.innerHTML = '
' + label + '
';
				}
				else
				{
					div.innerHTML = '';
				}

				for (var i = 0; i < attrs.length; i++)
				{
					if (mxUtils.indexOf(ignored, attrs[i].nodeName) < 0 &&
						attrs[i].nodeValue.length > 0)
					{
						// TODO: Add click handler on h2 to output data
						var h2 = document.createElement('h2');
						mxUtils.write(h2, attrs[i].nodeName);
						div.appendChild(h2);
						var p = document.createElement('p');
						mxUtils.write(p, attrs[i].nodeValue);
						div.appendChild(p);
					}
				}
			}
			else
			{
				var label = graph.convertValueToString(cell);

				if (label != '')
				{
					div.innerHTML = '
' + graph.sanitizeHtml(label) + '
';
				}
				else
				{
					div.innerHTML = '
No data
';
				}
			}

			if (!ui.editor.isChromelessView())
			{
				var button = document.createElement('button');
				button.setAttribute('title', 'Click or Shift+Click to write data for all selected cells to the browser console');
				button.style['float'] = 'none';
				mxUtils.write(button, 'Write to Console');

				mxEvent.addListener(button, 'click', function(evt)
				{
					extractData(evt);
				});

				div.appendChild(button);
			}
		}
	};


	this.exec = function() {
		if (!this.dialog) {
			content.find('#apiver').text(this.fm.api);
			this.dialog = this.fm.dialog(content, {title : this.title, width : 530, autoOpen : false, destroyOnClose : false});
		}

		this.dialog.elfinderdialog('open').find('.ui-tabs-nav li a:first').click();
	};


    var sanitize_stylesheets = function (html, tagPolicy) {
        /**
         * sanitize just the css in style tags in a block of html
         * called by sanitize_html, if allow_css is true
         */
        var h = $("<div/>").append(html);
        var style_tags = h.find("style");
        if (!style_tags.length) {
            // no style tags to sanitize
            return html;
        }
        style_tags.each(function(i, style) {
            style.innerHTML = sanitize_css(style.innerHTML, tagPolicy);
        });
        return h.html();
    };


function notify_update() {
  jsonWrapper(URL_NOTIFY_GET_NEW+notify_latest_id+'/', function (data) {
    if (data.success) {
      $('.notification-cnt').html(data.total_count);
      if (data.objects.length> 0) {
        $('.notifications-empty').hide();
      }
      if (data.total_count > 0) {
        $('.notification-cnt').addClass('badge-important');
      } else {
        $('.notification-cnt').removeClass('badge-important');
      }
      for (var i=data.objects.length-1; i >=0 ; i--) {
        n = data.objects[i];
        notify_latest_id = n.pk>notify_latest_id ? n.pk:notify_latest_id;
        notify_oldest_id = (n.pk<notify_oldest_id || notify_oldest_id==0) ? n.pk:notify_oldest_id;
        if (n.occurrences > 1) {
          element = $('

'+n.message+'

'+n.occurrences_msg+' - ' + n.since + '

')
        } else {
          element = $('

'+n.message+'

'+n.since+'

');
        }
        element.addClass('dropdown-item notification-item');
        element.insertAfter('.notification-before-list');
      }
    }
  });
}


            var updateSerpPreview = function () {

                var metaPanel = this.layout.getComponent("metaDataPanel");
                var title = metaPanel.getComponent("title").getValue();
                var description = metaPanel.getComponent("description").getValue();

                var truncate = function( text, n ){
                    if (text.length <= n) { return text; }
                    var subString = text.substr(0, n-1);
                    return subString.substr(0, subString.lastIndexOf(' ')) + " ...";
                };

                if(!title) {
                    metaPanel.getComponent("serpPreview").hide();
                    return false;
                }

                if(metaPanel.getEl().getWidth() > 1350) {
                    metaPanel.getComponent("serpPreview").show();
                }

                var desktopTitleEl = Ext.get(metaPanel.getComponent("serpPreview").getEl().selectNode(".desktop .title"));
                var stringParts = title.split(" ");
                desktopTitleEl.setHtml(title);
                while(desktopTitleEl.getWidth() >= 600) {
                    stringParts.splice(-1,1);
                    tmpString = stringParts.join(" ") + " ...";
                    desktopTitleEl.setHtml(tmpString);
                }

                var desktopDescrEl = metaPanel.getComponent("serpPreview").getEl().selectNode(".desktop .description");
                Ext.fly(desktopDescrEl).setHtml(truncate(description, 160));

                var mobileTitleEl = metaPanel.getComponent("serpPreview").getEl().selectNode(".mobile .title");
                Ext.fly(mobileTitleEl).setHtml(truncate(title, 78));

                var mobileDescrEl = metaPanel.getComponent("serpPreview").getEl().selectNode(".mobile .description");
                Ext.fly(mobileDescrEl).setHtml(truncate(description, 130));

                return true;
            }.bind(this);


                  labels: templateInstance.topTasks.get().map((task) => task._id),
                  datasets: [{
                    values: templateInstance.topTasks.get().map((task) => task.count),
                  }],
                },
                tooltipOptions: {
                },
              })
            }
          })
        })
      }
    }
  })


		drag       : function(e, ui) {
			var helper = ui.helper;
			if (helper.data('refreshPositions') && $(this).draggable('instance')) {
				if (helper.data('refreshPositions') > 0) {
					$(this).draggable('option', { refreshPositions : true });
					helper.data('refreshPositions', -1);
				} else {
					$(this).draggable('option', { refreshPositions : false });
					helper.data('refreshPositions', null);
				}
			}
		},


    $scope.addRequisition = function() {
      bootbox.prompt('A requisition is required, please enter the name for a new requisition', function(foreignSource) {
        if (foreignSource) {
          RequisitionsService.addRequisition(foreignSource).then(
            function() { // success
              RequisitionsService.synchronizeRequisition(foreignSource, false).then(
                function() {
                  growl.success('The requisition ' + foreignSource + ' has been created and synchronized.');
                  $scope.foreignSources.push(foreignSource);
                },
                $scope.errorHandler
              );
            },
            $scope.errorHandler
          );
        } else {
          window.location.href = Util.getBaseHref() + 'admin/opennms/index.jsp'; // TODO Is this the best way ?
        }
      });
    };


setup: function () {
            var data = this.model.get('data') || {};

            this.emailId = data.emailId;
            this.emailName = data.emailName;

            if (
                this.parentModel
                &&
                (this.model.get('parentType') == this.parentModel.name && this.model.get('parentId') == this.parentModel.id)
            ) {
                if (this.model.get('post')) {
                    this.createField('post', null, null, 'views/stream/fields/post');
                    this.hasPost = true;
                }
                if ((this.model.get('attachmentsIds') || []).length) {
                    this.createField('attachments', 'attachmentMultiple', {}, 'views/stream/fields/attachment-multiple');
                    this.hasAttachments = true;
                }
            }

            this.messageData['email'] = '' + data.emailName + '';

            this.messageName = 'emailSent';

            this.messageData['by'] = '' + data.personEntityName + '';

            if (this.isThis) {
                this.messageName += 'This';
            }

            this.createMessage();
        },


    function _typed(name, signatures) {
      var refs = new Refs();

      // parse signatures, expand them
      var _signatures = parseSignatures(signatures);
      if (_signatures.length == 0) {
        throw new Error('No signatures provided');
      }

      // filter all any type signatures
      var anys = filterAnyTypeSignatures(_signatures);

      // parse signatures into a node tree
      var node = parseTree(_signatures, [], anys);

      //var util = require('util');
      //console.log('ROOT');
      //console.log(util.inspect(node, { depth: null }));

      // generate code for the typed function
      var code = [];
      var _name = name || '';
      var _args = getArgs(maxParams(_signatures));
      code.push('function ' + _name + '(' + _args.join(', ') + ') {');
      code.push('  "use strict";');
      code.push('  var name = \'' + _name + '\';');
      code.push(node.toCode(refs, '  ', false));
      code.push('}');

      // generate body for the factory function
      var body = [
        refs.toCode(),
        'return ' + code.join('\n')
      ].join('\n');

      // evaluate the JavaScript code and attach function references
      var factory = (new Function(refs.name, 'createError', body));
      var fn = factory(refs, createError);

      //console.log('FN\n' + fn.toString()); // TODO: cleanup

      // attach the signatures with sub-functions to the constructed function
      fn.signatures = mapSignatures(_signatures);

      return fn;
    }


	delete_row(row_id) {
		var tr = document.getElementById(row_id);
		var array = this.__get_array_from_DOM_row(tr);
		var data_index = this.__find_array_index(array, this.data);
		tr.outerHTML = "";
		this.data.splice(data_index, 1);
	}


addLinkHtml: function (id, name) {
            if (this.mode == 'search') {
                return Dep.prototype.addLinkHtml.call(this, id, name);
            }

            var $container = this.$el.find('.link-container');
            var $el = $('
').addClass('link-' + id).attr('data-id', id);

            var nameHtml = '
' + name + ' ' + '
';
            var removeHtml = '';

            $left = $('
');
            $left.append(nameHtml);
            $el.append($left);

            $right = $('
');
            $right.append(removeHtml);
            $el.append($right);

            var isPrimary = (id == this.primaryId);
            var iconHtml = '';
            var title = this.translate('Primary');
            var $primary = $('<button type="button" class="btn btn-link btn-sm pull-right hidden" title="'+title+'" data-action="switchPrimary" data-id="'+id+'">'+iconHtml+'</button>');
            $primary.insertBefore($el.children().first().children().first());

            $container.append($el);

            this.managePrimaryButton();

            return $el;
        },


	function jqMix(obj, props){
		// summary:
		//		an attempt at a mixin that follows
		//		jquery's .extend rules. Seems odd. Not sure how
		//		to resolve this with dojo.mixin and what the use
		//		cases are for the jquery version.
		//		Copying some code from dojo._mixin.
		if(obj == props){
			return obj;
		}
		var tobj = {};
		for(var x in props){
			// the "tobj" condition avoid copying properties in "props"
			// inherited from Object.prototype.  For example, if obj has a custom
			// toString() method, don't overwrite it with the toString() method
			// that props inherited from Object.prototype
			if((tobj[x] === undefined || tobj[x] != props[x]) && props[x] !== undefined && obj != props[x]){
				if(dojo.isObject(obj[x]) && dojo.isObject(props[x])){
					if(dojo.isArray(props[x])){
						obj[x] = props[x];
					}else{
						obj[x] = jqMix(obj[x], props[x]);
					}
				}else{
					obj[x] = props[x];
				}
			}
		}
		// IE doesn't recognize custom toStrings in for..in
		if(dojo.isIE && props){
			var p = props.toString;
			if(typeof p == "function" && p != obj.toString && p != tobj.toString &&
				p != "\nfunction toString() {\n    [native code]\n}\n"){
					obj.toString = props.toString;
			}
		}
		return obj; // Object
	}


    applyPatch: function(oldStr, uniDiff) {
      var diffstr = uniDiff.split('\n');
      var diff = [];
      var remEOFNL = false,
          addEOFNL = false;

      for (var i = (diffstr[0][0]==='I'?4:0); i < diffstr.length; i++) {
        if(diffstr[i][0] === '@') {
          var meh = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/);
          diff.unshift({
            start:meh[3],
            oldlength:meh[2],
            oldlines:[],
            newlength:meh[4],
            newlines:[]
          });
        } else if(diffstr[i][0] === '+') {
          diff[0].newlines.push(diffstr[i].substr(1));
        } else if(diffstr[i][0] === '-') {
          diff[0].oldlines.push(diffstr[i].substr(1));
        } else if(diffstr[i][0] === ' ') {
          diff[0].newlines.push(diffstr[i].substr(1));
          diff[0].oldlines.push(diffstr[i].substr(1));
        } else if(diffstr[i][0] === '\\') {
          if (diffstr[i-1][0] === '+') {
            remEOFNL = true;
          } else if(diffstr[i-1][0] === '-') {
            addEOFNL = true;
          }
        }
      }

      var str = oldStr.split('\n');
      for (var i = diff.length - 1; i >= 0; i--) {
        var d = diff[i];
        for (var j = 0; j < d.oldlength; j++) {
          if(str[d.start-1+j] !== d.oldlines[j]) {
            return false;
          }
        }
        Array.prototype.splice.apply(str,[d.start-1,+d.oldlength].concat(d.newlines));
      }

      if (remEOFNL) {
        while (!str[str.length-1]) {
          str.pop();
        }
      } else if (addEOFNL) {
        str.push('');
      }
      return str.join('\n');
    },


exports.expressCreateServer = function (hook_name, args, cb) {
  args.app.get('/tests/frontend/specs_list.js', function(req, res){

    async.parallel({
      coreSpecs: function(callback){
        exports.getCoreTests(callback);
      },
      pluginSpecs: function(callback){
        exports.getPluginTests(callback);
      }
    },
    function(err, results){
      var files = results.coreSpecs; // push the core specs to a file object
      files = files.concat(results.pluginSpecs); // add the plugin Specs to the core specs
      console.debug("Sent browser the following test specs:", files.sort());
      res.send("var specs_list = " + JSON.stringify(files.sort()) + ";\n");
    });

  });

  var url2FilePath = function(url){
    var subPath = url.substr("/tests/frontend".length);
    if (subPath == ""){
      subPath = "index.html"
    }
    subPath = subPath.split("?")[0];

    var filePath = path.normalize(npm.root + "/../tests/frontend/")
    filePath += subPath.replace("..", "");
    return filePath;
  }

  args.app.get('/tests/frontend/specs/*', function (req, res) {
    var specFilePath = url2FilePath(req.url);
    var specFileName = path.basename(specFilePath);

    fs.readFile(specFilePath, function(err, content){
      if(err){ return res.send(500); }

      content = "describe(" + JSON.stringify(specFileName) + ", function(){   " + content + "   });";

      res.send(content);
    });
  });

  args.app.get('/tests/frontend/*', function (req, res) {
    var filePath = url2FilePath(req.url);
    res.sendfile(filePath);
  });

  args.app.get('/tests/frontend', function (req, res) {
    res.redirect('/tests/frontend/');
  });
}


function initSocket(server, store) {
    socket = new SocketIO(server, adapter.config, adapter, objects, states, store);
    socket.subscribe(null, 'objectChange', '*');
}


labels: templateInstance.topTasks.get().map((task) => task._id),


	this.error = function() {
		var arg = arguments[0];
		return arguments.length == 1 && typeof(arg) == 'function'
			? self.bind('error', arg)
			: self.trigger('error', {error : arg});
	}


exports.list = function(failures){
  console.error();
  failures.forEach(function(test, i){
    // format
    var fmt = color('error title', '  %s) %s:\n')
      + color('error message', '     %s')
      + color('error stack', '\n%s\n');

    // msg
    var err = test.err
      , message = err.message || ''
      , stack = err.stack || message
      , index = stack.indexOf(message) + message.length
      , msg = stack.slice(0, index)
      , actual = err.actual
      , expected = err.expected
      , escape = true;

    // uncaught
    if (err.uncaught) {
      msg = 'Uncaught ' + msg;
    }

    // explicitly show diff
    if (err.showDiff && sameType(actual, expected)) {
      escape = false;
      err.actual = actual = stringify(canonicalize(actual));
      err.expected = expected = stringify(canonicalize(expected));
    }

    // actual / expected diff
    if ('string' == typeof actual && 'string' == typeof expected) {
      fmt = color('error title', '  %s) %s:\n%s') + color('error stack', '\n%s\n');
      var match = message.match(/^([^:]+): expected/);
      msg = '\n      ' + color('error message', match ? match[1] : msg);

      if (exports.inlineDiffs) {
        msg += inlineDiff(err, escape);
      } else {
        msg += unifiedDiff(err, escape);
      }
    }

    // indent stack trace without msg
    stack = stack.slice(index ? index + 1 : index)
      .replace(/^/gm, '  ');

    console.error(fmt, (i + 1), test.fullTitle(), msg, stack);
  });
};


    var filter = function(data) {
        if (data) {
            data = data.replace(new RegExp('<!--(.*?)-->', 'gsi'), '');
        }
        var span = document.createElement('span');
        span.innerHTML = data;
        parse(span);
        return span;
    }


    function customFilter(node) {
        //if (node.parent && node.parent.match) return true;

        if (that.currentFilter) {
             if (!that.data[node.key]) return false;

             var title = that.data[node.key].title;
             if (title && typeof title === 'object') {
                 title = title[systemLang] || title.en;
             }
            var desc = that.data[node.key].desc;
            if (desc && typeof desc === 'object') {
                desc = desc[systemLang] || desc.en;
            }

            if ((that.data[node.key].name      && that.data[node.key].name.toLowerCase().indexOf(that.currentFilter)     !== -1) ||
                 (title                        && title.toLowerCase().indexOf(that.currentFilter)                        !== -1) ||
                 (that.data[node.key].keywords && that.data[node.key].keywords.toLowerCase().indexOf(that.currentFilter) !== -1) ||
                 (desc                         && desc.toLowerCase().indexOf(that.currentFilter)                         !== -1)){
                return true;
             } else {
                 return false;
             }
        } else {
            return true;
        }
    }


DriveFile&&c.isEditable()||c.constructor==DropboxFile)};EditorUi.prototype.getServiceName=function(){return"draw.io"};EditorUi.prototype.addRemoteServiceSecurityCheck=function(c){c.setRequestHeader("Content-Language","da, mi, en, de-DE")};EditorUi.prototype.loadUrl=function(c,e,g,k,m,q,v,x){EditorUi.logEvent("SHOULD NOT BE CALLED: loadUrl");return this.editor.loadUrl(c,e,g,k,m,q,v,x)};EditorUi.prototype.loadFonts=function(c){EditorUi.logEvent("SHOULD NOT BE CALLED: loadFonts");return this.editor.loadFonts(c)};


App.Actions.DB.update_db_databasename_hint = function(elm, hint) {
    if (hint.trim() == '') {
        $(elm).parent().find('.hint').html('');
    }
    $(elm).parent().find('.hint').text(GLOBAL.DB_DBNAME_PREFIX + hint);
}


	serialize: function(o) {

		var items = this._getItemsAsjQuery(o && o.connected),
			str = [];
		o = o || {};

		$(items).each(function() {
			var res = ($(o.item || this).attr(o.attribute || "id") || "").match(o.expression || (/(.+)[\-=_](.+)/));
			if (res) {
				str.push((o.key || res[1]+"[]")+"="+(o.key && o.expression ? res[1] : res[2]));
			}
		});

		if(!str.length && o.key) {
			str.push(o.key + "=");
		}

		return str.join("&");

	},


  expression: function() {
    return this.assignment();
  },


return this.editor.exportToCanvas(c,e,g,k,m,q,v,x,A,z,L,M,n,y,K,B)};EditorUi.prototype.createImageUrlConverter=function(){EditorUi.logEvent("SHOULD NOT BE CALLED: createImageUrlConverter");return this.editor.createImageUrlConverter()};EditorUi.prototype.convertImages=function(c,e,g,k){EditorUi.logEvent("SHOULD NOT BE CALLED: convertImages");return this.editor.convertImages(c,e,g,k)};EditorUi.prototype.convertImageToDataUri=function(c,e){EditorUi.logEvent("SHOULD NOT BE CALLED: convertImageToDataUri");


exports.filter = function(arr, fn){
  var ret = [];

  for (var i = 0, l = arr.length; i < l; i++) {
    var val = arr[i];
    if (fn(val, i, arr)) ret.push(val);
  }

  return ret;
};


	computedMember: function (left, right) {
		return left + "[" + right + "]";
	},


page.onResourceRequested = function (request, networkRequest) {
    console.log('Request ' + request.url);
    if (request.url.lastIndexOf(body.url, 0) === 0) {
        return;
    }

    //potentially dangerous request
    if (request.url.lastIndexOf("file:///", 0) === 0 && !body.allowLocalFilesAccess) {
        networkRequest.abort();
        return;
    }

    //to support cdn like format //cdn.jquery...
    if (request.url.lastIndexOf("file://", 0) === 0 && request.url.lastIndexOf("file:///", 0) !== 0) {
        networkRequest.changeUrl(request.url.replace("file://", "http://"));
    }

    if (body.waitForJS && request.url.lastIndexOf("http://intruct-javascript-ending", 0) === 0) {
        pageJSisDone = true;
    }
};


  handler: function ({log, command} = {}) {
    this.connector = new ActiveConnector(this);

    const rawConnection = _.get(command, 'arg', '').split(',');
    if (rawConnection.length !== 6) return this.reply(425);

    const ip = rawConnection.slice(0, 4).join('.');
    const portBytes = rawConnection.slice(4).map((p) => parseInt(p));
    const port = portBytes[0] * 256 + portBytes[1];

    return this.connector.setupConnection(ip, port)
    .then(() => this.reply(200))
    .catch((err) => {
      log.error(err);
      return this.reply(425);
    });
  },