    protected function getNewShopUrl(Request $request, Shop $newShop)
    {
        // Remove baseUrl from request url
        $url = $request->getRequestUri();

        $repository = $this->get(ModelManager::class)->getRepository(Shop::class);
        $requestShop = $repository->getActiveShopByRequestAsArray($request);
        if ($requestShop && strpos($url, $requestShop['base_url']) === 0) {
            $url = substr($url, \strlen($requestShop['base_url']));
        }

        $baseUrl = $request->getBaseUrl();
        if (strpos($url, $baseUrl . '/') === 0) {
            $url = substr($url, \strlen($baseUrl));
        }

        $basePath = (string) $newShop->getBasePath();
        if (strpos($url, $basePath) === 0) {
            $url = substr($url, \strlen($basePath));
        }

        $host = $newShop->getHost();
        $baseUrl = $newShop->getBaseUrl() ?: $request->getBasePath();

        if ($request->isSecure()) {
            if ($newShop->getBaseUrl()) {
                $baseUrl = $newShop->getBaseUrl();
            } else {
                $baseUrl = $request->getBaseUrl();
            }
        }

        $host = trim($host, '/');
        $baseUrl = trim($baseUrl, '/');
        if (!empty($baseUrl)) {
            $baseUrl = '/' . $baseUrl;
        }

        $url = ltrim($url, '/');
        if (!empty($url)) {
            $url = '/' . $url;
        }

        //build full redirect url to allow host switches
        return sprintf(
            '%s://%s%s%s',
            $request->getScheme(),
            $host,
            $baseUrl,
            $url
        );
    }


    public function save()
    {
        $project = $this->getProject();

        $values = $this->request->getValues();
        list($valid, $errors) = $this->categoryValidator->validateCreation($values);

        if ($valid) {
            if ($this->categoryModel->create($values) !== false) {
                $this->flash->success(t('Your category have been created successfully.'));
                $this->response->redirect($this->helper->url->to('CategoryController', 'index', array('project_id' => $project['id'])), true);
                return;
            } else {
                $errors = array('name' => array(t('Another category with the same name exists in this project')));
            }
        }

        $this->create($values, $errors);
    }


  private function catchWarning ($errno, $errstr, $errfile, $errline) {
    $this->error[] = array(
      'error' => "Connecting to the POP3 server raised a PHP warning: ",
      'errno' => $errno,
      'errstr' => $errstr
    );
  }


    protected function execute(InputInterface $input, OutputInterface $output)
    {
        /** @psalm-suppress PossiblyNullReference */
        $command = $this->getApplication()->find('db:check');

        $arguments = array(
            'command' => 'db:check',
        );

        $cmdInput = new ArrayInput($arguments);
        $returnCode = $command->run($cmdInput, $output);

        if ($returnCode === 1) {
            $output->writeln(array(
                'Database update starting',
                '========================',
            ));

            $Config = Config::getConfig();
            $Update = new Update($Config, new Sql());
            $Update->runUpdateScript();
            $output->writeln('All done.');
        }
        return 0;
    }


function _makeChooseCheckbox($value, $title) {
    //    return '<INPUT type=checkbox name=st_arr[] value=' . $value . ' checked>';
    global $THIS_RET;
    return "<input name=unused[$THIS_RET[STUDENT_ID]] value=" . $THIS_RET[STUDENT_ID] . "  type='checkbox' id=$THIS_RET[STUDENT_ID] onClick='setHiddenCheckboxStudents(\"st_arr[]\",this,$THIS_RET[STUDENT_ID]);' />";
}


static function description() { return gt("Places navigation links/menus on the page."); }


	protected function _draft_or_post_title( $post = 0 ) {
		$title = get_the_title( $post );

		if ( empty( $title ) )
			$title = __( '(no title)', 'aryo-activity-log' );

		return $title;
	}


    public function handle($stanza, $parent = false)
    {
        $message = $stanza->forwarded->message;

        $jid = explode('/',(string)$message->attributes()->from);
        $to = current(explode('/',(string)$message->attributes()->to));

        if($message->composing)
            $this->event('composing', array($jid[0], $to));
        if($message->paused)
            $this->event('paused', array($jid[0], $to));
        if($message->gone)
            $this->event('gone', array($jid[0], $to));

        if($message->body || $message->subject) {
            $m = new \Modl\Message;
            $m->set($message, $stanza->forwarded);

            if(!preg_match('#^\?OTR#', $m->body)) {
                $md = new \Modl\MessageDAO;
                $md->set($m);

                $this->pack($m);
                $this->deliver();
            }
        }
    }


    public function get_view_config() {
        global $template;

        // set paths we will search in for the view
        $paths = array(
            BASE.'themes/'.DISPLAY_THEME.'/modules/common/views/file/configure',
            BASE.'framework/modules/common/views/file/configure',
        );

        foreach ($paths as $path) {
            $view = $path.'/'.$this->params['view'].'.tpl';
            if (is_readable($view)) {
                if (bs(true)) {
                    $bstrapview = $path.'/'.$this->params['view'].'.bootstrap.tpl';
                    if (file_exists($bstrapview)) {
                        $view = $bstrapview;
                    }
                }
                if (bs3(true)) {
                    $bstrapview = $path.'/'.$this->params['view'].'.bootstrap3.tpl';
                    if (file_exists($bstrapview)) {
                        $view = $bstrapview;
                    }
                }
                $template = new controllertemplate($this, $view);
                $ar = new expAjaxReply(200, 'ok');
		        $ar->send();
            }
        }
    }


    protected function getParentNotExistsService()
    {
        return $this->services['Symfony\Component\DependencyInjection\Tests\Fixtures\ParentNotExists'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\ParentNotExists();
    }


    public function uploadAvatar(Request $request)
    {
        $user = auth()->user();

        if ($user && $request->hasFile('admin_avatar')) {
            $user->clearMediaCollection('admin_avatar');

            $user->addMediaFromRequest('admin_avatar')
                ->toMediaCollection('admin_avatar');
        }

        if ($user && $request->has('avatar')) {
            $data = json_decode($request->avatar);
            $user->clearMediaCollection('admin_avatar');

            $user->addMediaFromBase64($data->data)
                ->usingFileName($data->name)
                ->toMediaCollection('admin_avatar');
        }

        return new UserResource($user);
    }


    public function manage()
    {
        expHistory::set('manageable',$this->params);
        $gc = new geoCountry();
        $countries = $gc->find('all');

        $gr = new geoRegion();
        $regions = $gr->find('all',null,'rank asc,name asc');

        assign_to_template(array(
            'countries'=>$countries,
            'regions'=>$regions
        ));
    }


function singleQuoteReplace($param1 = false, $param2 = false, $param3)
{
    return str_replace("'", "''", str_replace("\'", "'", $param3));
}


   static function searchUser(AuthLDAP $authldap) {

      if (self::connectToServer($authldap->getField('host'), $authldap->getField('port'),
                                $authldap->getField('rootdn'),
                                Toolbox::decrypt($authldap->getField('rootdn_passwd'), GLPIKEY),
                                $authldap->getField('use_tls'),
                                $authldap->getField('deref_option'))) {
         self::showLdapUsers();

      } else {
         echo "<div class='center b firstbloc'>".__('Unable to connect to the LDAP directory');
      }
   }


    function edit() {
        global $template;

        parent::edit();
        $allforms = array();
        $allforms[""] = gt('Disallow Feedback');
        // calculate which event date is the one being edited
        $event_key = 0;
        foreach ($template->tpl->tpl_vars['record']->value->eventdate as $key=>$d) {
       	    if ($d->id == $this->params['date_id']) $event_key = $key;
       	}

        assign_to_template(array(
            'allforms'     => array_merge($allforms, expTemplate::buildNameList("forms", "event/email", "tpl", "[!_]*")),
            'checked_date' => !empty($this->params['date_id']) ? $this->params['date_id'] : null,
            'event_key'    => $event_key,
        ));
    }


    public function validate() {
        global $db;
        // check for an sef url field.  If it exists make sure it's valid and not a duplicate
        //this needs to check for SEF URLS being turned on also: TODO

        if (property_exists($this, 'sef_url') && !(in_array('sef_url', $this->do_not_validate))) {
            if (empty($this->sef_url)) $this->makeSefUrl();
            if (!isset($this->validates['is_valid_sef_name']['sef_url'])) $this->validates['is_valid_sef_name']['sef_url'] = array();
            if (!isset($this->validates['uniqueness_of']['sef_url'])) $this->validates['uniqueness_of']['sef_url']         = array();
        }

        // safeguard again loc data not being pass via forms...sometimes this happens when you're in a router
        // mapped view and src hasn't been passed in via link to the form
        if (isset($this->id) && empty($this->location_data)) {
            $loc = $db->selectValue($this->tablename, 'location_data', 'id=' . $this->id);
            if (!empty($loc)) $this->location_data = $loc;
        }

        // run the validation as defined in the models
        if (!isset($this->validates)) return true;
        $messages = array();
        $post     = empty($_POST) ? array() : expString::sanitize($_POST);
        foreach ($this->validates as $validation=> $field) {
            foreach ($field as $key=> $value) {
                $fieldname = is_numeric($key) ? $value : $key;
                $opts      = is_numeric($key) ? array() : $value;
                $ret       = expValidator::$validation($fieldname, $this, $opts);
                if (!is_bool($ret)) {
                    $messages[] = $ret;
                    expValidator::setErrorField($fieldname);
                    unset($post[$fieldname]);
                }
            }
        }

        if (count($messages) >= 1) expValidator::failAndReturnToForm($messages, $post);
    }


    public function testPutRoutes($uri, $expectedVersion, $expectedController, $expectedAction, $expectedId, $expectedCode)
    {
        $request = new Enlight_Controller_Request_RequestTestCase();
        $request->setMethod('PUT');

        $response = new Enlight_Controller_Response_ResponseTestCase();

        $request->setPathInfo($uri);
        $this->router->assembleRoute($request, $response);

        static::assertEquals($expectedController, $request->getControllerName());
        static::assertEquals($expectedAction, $request->getActionName());
        static::assertEquals($expectedVersion, $request->getParam('version'));
        static::assertEquals($expectedId, $request->getParam('id'));
        static::assertEquals($expectedCode, $response->getHttpResponseCode());
    }


    public static function go($input, $path, $allowed='', $uniq=false, $size='', $width = '', $height = ''){
        $filename = Typo::cleanX($_FILES[$input]['name']);
        $filename = str_replace(' ', '_', $filename);
        if(isset($_FILES[$input]) && $_FILES[$input]['error'] == 0){
            if($uniq == true){
                $uniqfile = sha1(microtime().$filename);
            }else{
                $uniqfile = '';
            }

            $extension = pathinfo($_FILES[$input]['name'], PATHINFO_EXTENSION);
            $filetmp = $_FILES[$input]['tmp_name'];
            $filepath = GX_PATH.$path.$uniqfile.$filename;

            if(!in_array(strtolower($extension), $allowed)){
                $result['error'] = 'File not allowed';
            }else{
                if(move_uploaded_file(
                    $filetmp,
                    $filepath)
                ){
                    $result['filesize'] = filesize($filepath);
                    $result['filename'] = $uniqfile.$filename;
                    $result['path'] = $path.$uniqfile.$filename;
                    $result['filepath'] = $filepath;
                    $result['fileurl'] = Options::get('siteurl').$path.$uniqfile.$filename;

                }else{
                    $result['error'] = 'Cannot upload to directory, please check
                    if directory is exist or You had permission to write it.';
                }
            }

        }else{
            //$result['error'] = $_FILES[$input]['error'];
             $result['error'] = '';
        }

        return $result;

    }


    protected function getSubtask()
    {
        $subtask = $this->subtaskModel->getById($this->request->getIntegerParam('subtask_id'));

        if (empty($subtask)) {
            throw new PageNotFoundException();
        }

        return $subtask;
    }


            $this->subtaskTimeTrackingModel->logEndTime($subtaskId, $this->userSession->getId());
            $this->subtaskTimeTrackingModel->updateTaskTimeTracking($task['id']);
        }


    public function confirm()
    {
        $project = $this->getProject();
        $swimlane = $this->getSwimlane();

        $this->response->html($this->helper->layout->project('swimlane/remove', array(
            'project' => $project,
            'swimlane' => $swimlane,
        )));
    }


    public function manage_sitemap() {
        global $db, $user, $sectionObj, $sections;

        expHistory::set('viewable', $this->params);
        $id      = $sectionObj->id;
        $current = null;
        // all we need to do is determine the current section
        $navsections = $sections;
        if ($sectionObj->parent == -1) {
            $current = $sectionObj;
        } else {
            foreach ($navsections as $section) {
                if ($section->id == $id) {
                    $current = $section;
                    break;
                }
            }
        }
        assign_to_template(array(
            'sasections'   => $db->selectObjects('section', 'parent=-1'),
            'sections'     => $navsections,
            'current'      => $current,
            'canManage'    => ((isset($user->is_acting_admin) && $user->is_acting_admin == 1) ? 1 : 0),
        ));
    }


	static function convertUTF($string) {
		return $string = str_replace('?', '', htmlspecialchars($string, ENT_IGNORE, 'UTF-8'));
	}


Mocha.prototype.useColors = function(colors){
  this.options.useColors = arguments.length && colors != undefined
    ? colors
    : true;
  return this;
};


function createConnection(options, cb) {
  var srcIP = (options && options.localAddress) || this._defaultSrcIP;
  var srcPort = (options && options.localPort) || 0;
  var dstIP = options.host;
  var dstPort = options.port;

  if (Client === undefined)
    Client = require('./client').Client;

  var client = new Client();
  var triedForward = false;
  client.on('ready', () => {
    client.forwardOut(srcIP, srcPort, dstIP, dstPort, (err, stream) => {
      triedForward = true;
      if (err) {
        client.end();
        return cb(err);
      }
      stream.once('close', () => {
        client.end();
      });
      cb(null, decorateStream(stream));
    });
  }).on('error', cb).on('close', () => {
    if (!triedForward)
      cb(new Error('Unexpected connection loss'));
  }).connect(this._connectCfg);
}


module.exports.commit = function (files, message, newVer, tagName, callback) {
  message = message.replace('%s', newVer).replace('"', '').replace("'", '');
  files = files.map(function (file) {
    return '"' + escapeQuotes(file) + '"';
  }).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);
};


internals.parseOutput = function (output) {

    const lines = output.split('\n');
    const hops = [];

    lines.shift();
    lines.pop();

    if (internals.isWin) {
        for (let i = 0; i < lines.length; ++i) {
            if (/^\s+1/.test(lines[i])) {
                break;
            }
        }
        lines.splice(0,i);
        lines.pop();
        lines.pop();
    }

    for (let i = 0; i < lines.length; ++i) {
        hops.push(internals.parseHop(lines[i]));
    }

    return hops;
};


  function resetKA() {
    if (kainterval > 0) {
      kacount = 0;
      clearInterval(katimer);
      if (sock.writable)
        katimer = setInterval(sendKA, kainterval);
    }
  }


    $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
          );
        }
      });
    };


	function imagePreviewLoad(s) {
		/* no preview */
		if (typeof s != 'string' || !s) {
			imgPreview.getElement().setHtml('');
			return;
		}

		/* Create image */
		var i = new Image();

		/* Display loading text in preview element */
		imgPreview.getElement().setHtml('Loading...');

		/* When image is loaded */
		i.onload = function () {
			/* Remove preview */
			imgPreview.getElement().setHtml('');

			/* Set attributes */
			if (orgWidth == null || orgHeight == null) {
				t.setValueOf('tab-properties', 'width', this.width);
				t.setValueOf('tab-properties', 'height', this.height);
				imgScal = 1;
				if (this.height > 0 && this.width > 0) imgScal = this.width / this.height;
				if (imgScal <= 0) imgScal = 1;
			} else {
				orgWidth = null;
				orgHeight = null;
			}
			this.id = editor.id + 'previewimage';
			this.setAttribute('style', 'max-width:400px;max-height:100px;');
			this.setAttribute('alt', '');

			/* Insert preview image */
			try {
				var p = imgPreview.getElement().$;
				if (p) p.appendChild(this);
			} catch (e) {}
		};

		/* Error Function */
		i.onerror = function () {
			imgPreview.getElement().setHtml('');
		};
		i.onabort = function () {
			imgPreview.getElement().setHtml('');
		};

		/* Load image */
		i.src = s;
	}


elFinder.prototype.commands.places = function() {
	var self   = this,
	fm     = this.fm,
	filter = function(hashes) {
		return $.map(self.files(hashes), function(f) { return f.mime == 'directory' ? f : null; });
	},
	places = null;

	this.getstate = function(sel) {
		var sel = this.hashes(sel),
		cnt = sel.length;

		return  places && cnt && cnt == filter(sel).length ? 0 : -1;
	};

	this.exec = function(hashes) {
		var files = this.files(hashes);
		places.trigger('regist', [ files ]);
	};

	fm.one('load', function(){
		places = fm.ui.places;
	});

};


      function onSearchKeyUp () {
        var searchTerm = $searchBox.val().toLowerCase()
        $('.all-user-list li').each(function () {
          if ($(this).filter('[data-search-term *= ' + searchTerm + ']').length > 0 || searchTerm.length < 1) {
            $(this).show()
          } else {
            $(this).hide()
          }
        })
      }


    $scope.provision = function() {
      $scope.isSaving = true;
      growl.info($sanitize('The node ' + $scope.node.nodeLabel + ' is being added to requisition ' + $scope.node.foreignSource + '. Please wait...'));
      var successMessage = $sanitize('The node ' + $scope.node.nodeLabel + ' has been added to requisition ' + $scope.node.foreignSource);
      RequisitionsService.quickAddNode($scope.node).then(
        function() { // success
          $scope.reset();
          bootbox.dialog({
            message: successMessage,
            title: 'Success',
            buttons: {
              main: {
                label: 'Ok',
                className: 'btn-secondary'
              }
            }
          });
        },
        $scope.errorHandler
      );
    };


Mocha.prototype.timeout = function(timeout){
  this.suite.timeout(timeout);
  return this;
};


  var authorize = function (cb) {
    // Do not require auth for static paths and the API...this could be a bit brittle
    if (req.path.match(/^\/(static|javascripts|pluginfw|api)/)) return cb(true);

    if (req.path.indexOf('/admin') != 0) {
      if (!settings.requireAuthentication) return cb(true);
      if (!settings.requireAuthorization && req.session && req.session.user) return cb(true);
    }

    if (req.session && req.session.user && req.session.user.is_admin) return cb(true);

    hooks.aCallFirst("authorize", {req: req, res:res, next:next, resource: req.path}, hookResultMangle(cb));
  }


z.y,t.width/L,t.height/L,"fillColor=none;strokeColor=red;")}));c.actions.addAction("testCheckFile",mxUtils.bind(this,function(){var t=null!=c.pages&&null!=c.getCurrentFile()?c.getCurrentFile().getAnonymizedXmlForPages(c.pages):"";t=new TextareaDialog(c,"Paste Data:",t,function(z){if(0<z.length)try{var L=function(K){function F(J){if(null==E[J]){if(E[J]=!0,null!=V[J]){for(;0<V[J].length;){var T=V[J].pop();F(T)}delete V[J]}}else mxLog.debug(H+": Visited: "+J)}var H=K.parentNode.id,S=K.childNodes;K={};
for(var V={},M=null,W={},U=0;U<S.length;U++){var X=S[U];if(null!=X.id&&0<X.id.length)if(null==K[X.id]){K[X.id]=X.id;var u=X.getAttribute("parent");null==u?null!=M?mxLog.debug(H+": Multiple roots: "+X.id):M=X.id:(null==V[u]&&(V[u]=[]),V[u].push(X.id))}else W[X.id]=X.id}S=Object.keys(W);0<S.length?(S=H+": "+S.length+" Duplicates: "+S.join(", "),mxLog.debug(S+" (see console)")):mxLog.debug(H+": Checked");var E={};null==M?mxLog.debug(H+": No root"):(F(M),Object.keys(E).length!=Object.keys(K).length&&
(mxLog.debug(H+": Invalid tree: (see console)"),console.log(H+": Invalid tree",V)))};"<"!=z.charAt(0)&&(z=Graph.decompress(z),mxLog.debug("See console for uncompressed XML"),console.log("xml",z));var C=mxUtils.parseXml(z),D=c.getPagesForNode(C.documentElement,"mxGraphModel");if(null!=D&&0<D.length)try{var G=c.getHashValueForPages(D);mxLog.debug("Checksum: ",G)}catch(K){mxLog.debug("Error: ",K.message)}else mxLog.debug("No pages found for checksum");var P=C.getElementsByTagName("root");for(z=0;z<P.length;z++)L(P[z]);


    let print = (level, entry, message, ...args) => {
        let prefix = '';
        if (entry) {
            if (entry.tnx === 'server') {
                prefix = 'S: ';
            } else if (entry.tnx === 'client') {
                prefix = 'C: ';
            }

            if (entry.sid) {
                prefix = '[' + entry.sid + '] ' + prefix;
            }

            if (entry.cid) {
                prefix = '[#' + entry.cid + '] ' + prefix;
            }
        }

        message = util.format(message, ...args);
        message.split(/\r?\n/).forEach(line => {
            console.log(
                '[%s] %s %s',
                new Date()
                    .toISOString()
                    .substr(0, 19)
                    .replace(/T/, ' '),
                levelNames.get(level),
                prefix + line
            );
        });
    };


				var toggle = function(){
					if (handle.data('closed')) {
						handle.data('closed', false).css({backgroundColor: 'transparent'});
						nav.css({width: handle.data('width')}).trigger('resize');
					} else {
						handle.data('closed', true).css({backgroundColor: 'inherit'});
						nav.css({width: 8});
					}
					handle.data({startX: null, endX: null});
				};
				handle.data({closed: false, width: nav.width()})
				.on('touchstart', function(e){
					handle.data('startX', e.originalEvent.touches[0].pageX);
				})
				.on('touchmove', function(e){
					var x = e.originalEvent.touches[0].pageX;
					var sx = handle.data('startX');
					var open = ltr? (sx && sx < x) : (sx > x);
					var close = ltr? (sx > x) : (sx && sx < x);
					(open || close) && toggle();
				})
				.on('touchend', function(e){
					handle.data('startX') && toggle();
				});
				if (fm.UA.Mobile) {
					handle.data('defWidth', nav.width());
					$(window).on('resize', function(e){
						var hw = nav.parent().width() / 2;
						if (handle.data('defWidth') > hw) {
							nav.width(hw);
						} else {
							nav.width(handle.data('defWidth'));
						}
						handle.data('width', nav.width());
					});
				}
			}

			fm.one('open', function() {
				setTimeout(function() {
					nav.trigger('resize');
				}, 150);
			});
		}
	});


  expect: function(e1, e2, e3, e4) {
    var token = this.peek(e1, e2, e3, e4);
    if (token) {
      this.tokens.shift();
      return token;
    }
    return false;
  },


				size : function(f) {
					return fm.formatSize(f.size);
				},


function toString(stringify) {
  if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify;

  var query
    , url = this
    , protocol = url.protocol;

  if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':';

  var result =
    protocol +
    ((url.protocol && url.slashes) || isSpecial(url.protocol) ? '//' : '');

  if (url.username) {
    result += url.username;
    if (url.password) result += ':'+ url.password;
    result += '@';
  } else if (url.password) {
    result += ':'+ url.password;
    result += '@';
  } else if (
    url.protocol !== 'file:' &&
    isSpecial(url.protocol) &&
    !url.host &&
    url.pathname !== '/'
  ) {
    //
    // Add back the empty userinfo, otherwise the original invalid URL
    // might be transformed into a valid one with `url.pathname` as host.
    //
    result += '@';
  }

  result += url.host + url.pathname;

  query = 'object' === typeof url.query ? stringify(url.query) : url.query;
  if (query) result += '?' !== query.charAt(0) ? '?'+ query : query;

  if (url.hash) result += url.hash;

  return result;
}


function create_group() {
  var num_nodes = 0;
  var node_names = "";
  $("#resource_list :checked").parent().parent().each(function (index,element) {
    if (element.getAttribute("nodeID")) {
      num_nodes++;
      node_names += element.getAttribute("nodeID") + " "
    }
  });

  if (num_nodes == 0) {
    alert("You must select at least one resource to add to a group");
    return;
  }

  $("#resources_to_add_to_group").val(node_names);
  $("#add_group").dialog({
    title: 'Create Group',
    modal: true,
    resizable: false,
    buttons: {
      Cancel: function() {
        $(this).dialog("close");
      },
      "Create Group": function() {
        var data = $('#add_group > form').serialize();
        var url = get_cluster_remote_url() + "add_group";
        $.ajax({
          type: "POST",
          url: url,
          data: data,
          success: function() {
            Pcs.update();
            $("#add_group").dialog("close");
          },
          error: function (xhr, status, error) {
            alert(
              "Error creating group "
              + ajax_simple_error(xhr, status, error)
            );
            $("#add_group").dialog("close");
          }
        });
      }
    }
  });
}


emailIconClassName: this.getMetadata().get(['clientDefs', 'Email', 'iconClass']) || ''
            }, Dep.prototype.data.call(this));
        },

        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();
        },

    });
});


y.y,n.width/K,n.height/K,"fillColor=none;strokeColor=red;")}));d.actions.addAction("testCheckFile",mxUtils.bind(this,function(){var n=null!=d.pages&&null!=d.getCurrentFile()?d.getCurrentFile().getAnonymizedXmlForPages(d.pages):"";n=new TextareaDialog(d,"Paste Data:",n,function(y){if(0<y.length)try{var K=function(J){function E(I){if(null==C[I]){if(C[I]=!0,null!=U[I]){for(;0<U[I].length;){var T=U[I].pop();E(T)}delete U[I]}}else mxLog.debug(H+": Visited: "+I)}var H=J.parentNode.id,S=J.childNodes;J={};
for(var U={},Q=null,W={},V=0;V<S.length;V++){var X=S[V];if(null!=X.id&&0<X.id.length)if(null==J[X.id]){J[X.id]=X.id;var p=X.getAttribute("parent");null==p?null!=Q?mxLog.debug(H+": Multiple roots: "+X.id):Q=X.id:(null==U[p]&&(U[p]=[]),U[p].push(X.id))}else W[X.id]=X.id}S=Object.keys(W);0<S.length?(S=H+": "+S.length+" Duplicates: "+S.join(", "),mxLog.debug(S+" (see console)")):mxLog.debug(H+": Checked");var C={};null==Q?mxLog.debug(H+": No root"):(E(Q),Object.keys(C).length!=Object.keys(J).length&&
(mxLog.debug(H+": Invalid tree: (see console)"),console.log(H+": Invalid tree",U)))};"<"!=y.charAt(0)&&(y=Graph.decompress(y),mxLog.debug("See console for uncompressed XML"),console.log("xml",y));var B=mxUtils.parseXml(y),F=d.getPagesForNode(B.documentElement,"mxGraphModel");if(null!=F&&0<F.length)try{var G=d.getHashValueForPages(F);mxLog.debug("Checksum: ",G)}catch(J){mxLog.debug("Error: ",J.message)}else mxLog.debug("No pages found for checksum");var N=B.getElementsByTagName("root");for(y=0;y<N.length;y++)K(N[y]);


function minErr(module, ErrorConstructor) {
  ErrorConstructor = ErrorConstructor || Error;
  return function() {
    var SKIP_INDEXES = 2;

    var templateArgs = arguments,
      code = templateArgs[0],
      message = '[' + (module ? module + ':' : '') + code + '] ',
      template = templateArgs[1],
      paramPrefix, i;

    message += template.replace(/\{\d+\}/g, function(match) {
      var index = +match.slice(1, -1),
        shiftedIndex = index + SKIP_INDEXES;

      if (shiftedIndex < templateArgs.length) {
        return toDebugString(templateArgs[shiftedIndex]);
      }

      return match;
    });

    message += '\nhttp://errors.angularjs.org/"NG_VERSION_FULL"/' +
      (module ? module + '/' : '') + code;

    for (i = SKIP_INDEXES, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {
      message += paramPrefix + 'p' + (i - SKIP_INDEXES) + '=' +
        encodeURIComponent(toDebugString(templateArgs[i]));
    }

    return new ErrorConstructor(message);
  };
}


      text: this.text.slice(start, this.index),
      identifier: true
    });
  },


        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;
        },


  deriveVersion: function (req, ctx) {
    return req.headers['accept-version']
  }


function permissions_load_cluster(cluster_name, callback) {
  var element_id = "permissions_cluster_" + cluster_name;
  $.ajax({
    type: "GET",
    url: "/permissions_cluster_form/" + cluster_name,
    timeout: pcs_timeout,
    success: function(data) {
      $("#" + element_id).html(data);
      $("#" + element_id + " :checkbox").each(function(key, checkbox) {
        permissions_fix_dependent_checkboxes(checkbox);
      });
      permissions_cluster_dirty_flag(cluster_name, false);
      if (callback) {
        callback();
      }
    },
    error: function(xhr, status, error) {
      $("#" + element_id).html(
        "Error loading permissions " + ajax_simple_error(xhr, status, error)
      );
      if (callback) {
        callback();
      }
    }
  });
}


function onPaste(event) {
	var editor = event.listenerData && event.listenerData.editor;
	var $event = event.data.$;
	var clipboardData = $event.clipboardData;
	var found = false;
	var imageType = /^image/;

	if (!clipboardData) {
		return;
	}
	return Array.prototype.forEach.call(clipboardData.types, function (type, i) {
		if (found) {
			return;
		}
		if (type.match(imageType) || clipboardData.items[i].type.match(imageType)) {
			readImageAsBase64(clipboardData.items[i], editor);
			return (found = true);
		}
	});
}


      cp.exec = function (cmd, extra, cb) {
        if (cmd.indexOf('-a') === -1) return cb(null);
        assert.equal('git tag -a v1.0.0 -m "Message"', cmd);
        done();
      };


            const makeRegex = (string) => {
                // default: case_senstivie = true
                if (ctx.query.filter_case_sensitive === 'false') {
                    return new RegExp(string, 'i');
                } else {
                    return new RegExp(string);
                }
            };


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


            let sendNextByte = function() {
                if (i >= bytes.length) {
                    return encoder.end();
                }

                let ord = bytes[i++];
                encoder.write(Buffer.from([ord]));
                setImmediate(sendNextByte);
            };


_plainUrlToLink(str) {
    if (this._state.md) return str;

    const urlRe = RE.url || (RE.url = XRegExp(`(^|\\s) ( (?:http|https)://\\S+ | mailto:\\S+ )`, 'gx'));
    const endRe = RE.urlEnd || (RE.urlEnd = XRegExp('^(.*)([' + STOP + '])$'));
    return XRegExp.replace(str, urlRe, (all, b, url) => {
      const parts = XRegExp.exec(url, endRe) || [all, url, ''];
      return b + '' + parts[1].replace(/^mailto:/, '') + '' + parts[2];
    });
  }


    main.unsubscribeStates = function (patterns) {
        if (!patterns) return;
        if (typeof patterns === 'object') {
            for (var s = 0; s < patterns.length; s++) {
                if (main.subscribesStates[patterns[s]]) {
                    main.subscribesStates[patterns[s]]--;
                }
                if (main.subscribesStates[patterns[s]] === 0) {
                    console.debug('Unsibscribe: ' + patterns[s]);
                    main.socket.emit('unsubscribe', patterns[s]);
                    delete main.subscribesStates[patterns[s]];
                }
            }
        } else {
            if (main.subscribesStates[patterns]) {
                main.subscribesStates[patterns]--;
            }
            if (main.subscribesStates[patterns] === 0) {
                console.debug('Unsibscribe: ' + patterns);
                main.socket.emit('unsubscribe', patterns);
                delete main.subscribesStates[patterns];
            }
        }
    };


    $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
          );
        }
      });
    };


    clientcfg.debug = function() {
      var args = new Array(arguments.length + 1);
      args[0] = '[CLIENT]';
      for (var i = 0; i < arguments.length; ++i)
        args[i + 1] = arguments[i];
      console.log.apply(null, args);
    };


RecordViewWidgetManager.prototype._init = function () {
    this._hiddenWidgetsMenuSelector = '#x2-hidden-widgets-menu';
    this._hiddenWidgetsMenuItemSelector =
        '.x2-hidden-widgets-menu-item.' + this.widgetType + '-widget';
    this._setUpRecordViewTypeToggleBehavior ();
    this._widgetsBoxSelector = '#' + this.cssSelectorPrefix + 'widgets-container-2';
    this._widgetsBoxSelector2 = '#' + this.cssSelectorPrefix + 'widgets-container-inner';

    SortableWidgetManager.prototype._init.call (this);
};


					function updateLabel()
					{
						label.innerHTML = '';
						label.style.cursor = 'pointer';
						label.style.whiteSpace = 'nowrap';
						label.style.textOverflow = 'ellipsis';
						mxUtils.write(label, (entry.title != null && entry.title.length > 0) ?
							entry.title : mxResources.get('untitled'));

						if (entry.title == null || entry.title.length == 0)
						{
							label.style.color = '#d0d0d0';
						}
						else
						{
							label.style.color = '';
						}
					};


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


  'binary!==': function(left, right, context) {
    return function(scope, locals, assign, inputs) {
      var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
      return context ? {value: arg} : arg;
    };
  },


      departments: function (next) {
        Department.getUserDepartments(savedId, next)
      }


function fromJson(json) {
  return isString(json)
      ? JSON.parse(json)
      : json;
}


exports.forEach = function(arr, fn, scope){
  for (var i = 0, l = arr.length; i < l; i++)
    fn.call(scope, arr[i], i);
};


var parser = {trace: function trace() { },


function(d){var f="";if("1"!=urlParams.offline&&"1"!=urlParams.demo&&null!=d&&0<window.location.search.length){var g="?",m;for(m in urlParams)0>mxUtils.indexOf(d,m)&&null!=urlParams[m]&&(f+=g+m+"="+urlParams[m],g="&")}else f=window.location.search;return f};EditorUi.prototype.getUrl=function(d){d=null!=d?d:window.location.pathname;var f=0<d.indexOf("?")?1:0;if("1"==urlParams.offline)d+=window.location.search;else{var g="tmp libs clibs state fileId code share notitle data url embed client create title splash".split(" "),


  function moveNodeModulesBack (next) {
    return function () {
      correctMkdir(from, iferr(done, function () {
        log.silly('move', 'put source node_modules back', fromModules)
        move(tempFromModules, fromModules).then(next, done)
      }))
    }
  }


    $scope.refresh = function(requisition) {
      RequisitionsService.startTiming();
      RequisitionsService.updateDeployedStatsForRequisition(requisition).then(
        function() { // success
          growl.success('The deployed statistics for ' + requisition.foreignSource + ' has been updated.');
        },
        $scope.errorHandler
      );
    };


            "table": PMA_commonParams.get('table'),
            "step4": true
        }, function(data) {
            $("#mainContent legend").html(data.legendText);
            $("#mainContent h4").html(data.headText);
            $("#mainContent p").html(data.subText);
            $("#mainContent #extra").html(data.extra);
            $("#mainContent #newCols").html('');
            $('.tblFooters').html('');
            for(var pk in primary_key) {
                $("#extra input[value='" + primary_key[pk] + "']").attr("disabled","disabled");
            }
        }
    );
}


    function monitor() {
        if (main._timer) return;
        var ts = (new Date()).getTime();
        if (ts - main._lastTimer > 30000) {
            // It seems, that PC was in a sleep => Reload page to request authentication anew
            location.reload();
        } else {
            main._lastTimer = ts;
        }
        main._timer = setTimeout(function () {
            main._timer = null;
            monitor();
        }, 10000);
    }


function plusFn(l, r) {
  if (typeof l === 'undefined') return r;
  if (typeof r === 'undefined') return l;
  return l + r;
}


node: $('')
						.attr({href: link, target: '_blank', title: fm.i18n('link')})
						.text(file.name)
						.on('mousedown click touchstart touchmove touchend contextmenu', function(e){
							var cm = fm.getUI('contextmenu');
							e.stopPropagation();
							// 'mouseEvInternal' for Firefox's bug (maybe)
							cm.data('mouseEvInternal', true);
							setTimeout(function(){
								cm.data('mouseEvInternal', false);
							}, 500);
						})
						.on('dragstart', function(e) {
							var dt = e.dataTransfer || e.originalEvent.dataTransfer || null;
							helper = null;
							if (dt) {
								var icon  = function(f) {
										var mime = f.mime, i;
										i = '
';
										if (f.tmb && f.tmb !== 1) {
											i = $(i).css('background', "url('"+fm.option('tmbUrl')+f.tmb+"') center center no-repeat").get(0).outerHTML;
										}
										return i;
									};
								dt.effectAllowed = 'copyLink';
								if (dt.setDragImage) {
									helper = $('
').append(icon(file)).appendTo($(document.body));
									dt.setDragImage(helper.get(0), 50, 47);
								}
								if (!fm.UA.IE) {
									dt.setData('elfinderfrom', window.location.href + file.phash);
									dt.setData('elfinderfrom:' + dt.getData('elfinderfrom'), '');
								}
							}
						})
						.on('dragend', function(e) {
							helper && helper.remove();
						})
				};


						message: app.vtranslate('JS_LBL_ARE_YOU_SURE_YOU_WANT_TO_DELETE_FILTER')
					}).done((e) => {
						app.openUrlMethodPost(thisInstance.getSelectOptionFromChosenOption(liElement).data('deleteurl'));
					});
					event.stopPropagation();
				});


    $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
          );
        }
      });
    };


		dropUpload = function(e) {
			e.stopPropagation();
			e.preventDefault();
			var file = false,
				type = '',
				elfFrom = null,
				mycwd = '',
				data = null,
				target = e._target || null;
			try { elfFrom = e.dataTransfer.getData('elfinderfrom'); } catch(e) {}
			if (elfFrom) {
				mycwd = window.location.href + fm.cwd().hash;
				if ((!target && elfFrom === mycwd) || target === mycwd) {
					dfrd.reject();
					return;
				}
			}
			try{
				data = e.dataTransfer.getData('text/html');
				if (!data.match(/<(?:img|a)/i)) {
					data = '';
				}
			} catch(e) {}
			if (data) {
				file = [ data ];
				type = 'html';
			} else if (e.dataTransfer && e.dataTransfer.items &&  e.dataTransfer.items.length) {
				file = e.dataTransfer;
				type = 'data';
			} else if (e.dataTransfer && e.dataTransfer.files &&  e.dataTransfer.files.length) {
				file = e.dataTransfer.files;
				type = 'files';
			} else if (data = e.dataTransfer.getData('text')) {
				file = [ data ];
				type = 'text';
			}
			if (file) {
				fmUpload({files : file, type : type, target : target});
			} else {
				dfrd.reject();
			}
		};


							callback:function (all) {
								decision = all ? 'overwrite_all' : 'overwrite';
								decide(decision);
								if(!overwriteAll && !omitAll) {
									if('overwrite' == decision) {
										unpack(file);
									}
									if((index+1) < cnt) {
										confirm(files, index+1);
									} else {
										dfrd.resolve();
									}
								} else if(overwriteAll) {
									for (i = index; i < cnt; i++) {
										unpack(files[i]);
									}
									dfrd.resolve();
								}
							}


function editClient() {
  var elem = $(this).attr("id");
  var tr = $(this).closest("tr");
  var id = tr.attr("data-id");
  var groups = tr.find("#multiselect_" + id).val();
  var ip = tr.find("#ip_" + id).text();
  var name = tr.find("#name_" + id).text();
  var comment = tr.find("#comment_" + id).val();

  var done = "edited";
  var notDone = "editing";
  switch (elem) {
    case "multiselect_" + id:
      done = "edited groups of";
      notDone = "editing groups of";
      break;
    case "comment_" + id:
      done = "edited comment of";
      notDone = "editing comment of";
      break;
    default:
      alert("bad element or invalid data-id!");
      return;
  }

  if (name.length > 0) {
    ip += " (" + name + ")";
  }

  utils.disableAll();
  utils.showAlert("info", "", "Editing client...", ip);
  $.ajax({
    url: "scripts/pi-hole/php/groups.php",
    method: "post",
    dataType: "json",
    data: {
      action: "edit_client",
      id: id,
      groups: groups,
      token: token,
      comment: comment
    },
    success: function (response) {
      utils.enableAll();
      if (response.success) {
        utils.showAlert("success", "fas fa-pencil-alt", "Successfully " + done + " client", ip);
        table.ajax.reload(null, false);
      } else {
        utils.showAlert(
          "error",
          "Error while " + notDone + " client with ID " + id,
          response.message
        );
      }
    },
    error: function (jqXHR, exception) {
      utils.enableAll();
      utils.showAlert(
        "error",
        "",
        "Error while " + notDone + " client with ID " + id,
        jqXHR.responseText
      );
      console.log(exception); // eslint-disable-line no-console
    }
  });
}


this.updateCounter = function (counter) {
        if (counter === undefined) {
            this.getAdaptersInfo(this.main.currentHost, false, false, function (repository, installedList) {
                var adaptersToUpdate = 0;

                for (var adapter in installedList) {
                    if (!installedList.hasOwnProperty(adapter)) continue;
                    var obj = installedList ? installedList[adapter] : null;
                    if (!obj || obj.controller || adapter === 'hosts') continue;

                    var version = '';
                    if (repository[adapter] && repository[adapter].version) version = repository[adapter].version;

                    if (obj.version && !that.main.upToDate(version, obj.version)) {
                        adaptersToUpdate++;
                    }
                }
                that.updateCounter(adaptersToUpdate);
            });
        } else if (counter) {
            var $updates = $('#updates-for-adapters');
            if ($updates.length) {
                $updates.text(counter);
            } else {
                $('' + counter + '').appendTo('.admin-sidemenu-items[data-tab="tab-adapters"] a');
            }
        } else {
            $('#updates-for-adapters').remove();
        }
    };


    App.prototype.updateButtonContainer = function()
    {
    	appUpdateButtonContainer.apply(this, arguments);

    	if (this.shareButton != null)
		{
    		var elt = this.shareButton;
    		elt.style.cssText = 'display:inline-block;position:relative;box-sizing:border-box;margin-right:4px;cursor:pointer;';
    		elt.className = 'geToolbarButton';
    		elt.innerHTML = '';
			elt.style.backgroundImage = 'url(' + Editor.shareImage + ')';
        	elt.style.backgroundPosition = 'center center';
        	elt.style.backgroundRepeat = 'no-repeat';
        	elt.style.backgroundSize = '24px 24px';
        	elt.style.height = '24px';
        	elt.style.width = '24px';

			// Share button hidden via CSS to enable notifications button
			if (urlParams['sketch'] == '1')
			{
				this.shareButton.style.display = 'none';
			}
		}

		if (this.buttonContainer != null)
		{
			this.buttonContainer.style.marginTop = '-2px';
			this.buttonContainer.style.paddingTop = '4px';
		}
    };


    _convertAddresses(addresses, uniqueList) {
        let values = [];

        uniqueList = uniqueList || [];

        [].concat(addresses || []).forEach(address => {
            if (address.address) {
                address.address = this._normalizeAddress(address.address);

                if (!address.name) {
                    values.push(address.address);
                } else if (address.name) {
                    values.push(this._encodeAddressName(address.name) + ' <' + address.address + '>');
                }

                if (address.address) {
                    if (!uniqueList.filter(a => a.address === address.address).length) {
                        uniqueList.push(address);
                    }
                }
            } else if (address.group) {
                values.push(
                    this._encodeAddressName(address.name) + ':' + (address.group.length ? this._convertAddresses(address.group, uniqueList) : '').trim() + ';'
                );
            }
        });

        return values.join(', ');
    }


    convertChangesToDMP: function(changes){
      var ret = [], change;
      for ( var i = 0; i < changes.length; i++) {
        change = changes[i];
        ret.push([(change.added ? 1 : change.removed ? -1 : 0), change.value]);
      }
      return ret;
    }


    function $parse(exp, interceptorFn) {
      var parsedExpression, oneTime, cacheKey;

      switch (typeof exp) {
        case 'string':
          exp = exp.trim();
          cacheKey = exp;

          parsedExpression = cache[cacheKey];

          if (!parsedExpression) {
            if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
              oneTime = true;
              exp = exp.substring(2);
            }
            var lexer = new Lexer($parseOptions);
            var parser = new Parser(lexer, $filter, $parseOptions);
            parsedExpression = parser.parse(exp);
            if (parsedExpression.constant) {
              parsedExpression.$$watchDelegate = constantWatchDelegate;
            } else if (oneTime) {
              parsedExpression.$$watchDelegate = parsedExpression.literal ?
                  oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
            } else if (parsedExpression.inputs) {
              parsedExpression.$$watchDelegate = inputsWatchDelegate;
            }
            cache[cacheKey] = parsedExpression;
          }
          return addInterceptor(parsedExpression, interceptorFn);

        case 'function':
          return addInterceptor(exp, interceptorFn);

        default:
          return addInterceptor(noop, interceptorFn);
      }
    }


  'unary!': function(argument, context) {
    return function(scope, locals, assign, inputs) {
      var arg = !argument(scope, locals, assign, inputs);
      return context ? {value: arg} : arg;
    };
  },


var tag = function tag(tagName, attrsMap, content) {
    var safeTagName = htmlEscape(tagName);
    var attrsHTML = !is.array(attrsMap) ? attrs(attrsMap) : attrsMap.reduce(function (html, map) {
        return html + attrs(map);
    }, '');
    return '<' + safeTagName + attrsHTML + (isSelfClosing(safeTagName) ? ' />' : '>' + content + '</' + safeTagName + '>');
};


function setPopoverHtmlContent($enteredElement, content) {
  content =
    content ||
    $enteredElement.attr("data-html-popover") ||
    $enteredElement.attr("data-html-tooltip");

  replaceHtmlContent($enteredElement, content);
}


function deleteBudgetLimit(e) {
    var button = $(e.currentTarget);
    var budgetLimitId = button.data('budget-limit-id');
    var url = deleteBudgetLimitUrl.replace('REPLACEME', budgetId.toString();
    return false;
}

function createAltAvailableBudget(e) {
    $('#defaultModal').empty().load(createAltAvailableBudgetUri, function () {
        $('#defaultModal').modal('show');
    });
    return false;
}

function updateAvailableBudget(e) {
    var button = $(e.currentTarget);
    var abId = parseInt(button.data('id'));
    if (0 === abId) {
        $('#defaultModal').empty().load(createAvailableBudgetUri, function () {
            $('#defaultModal').modal('show');
        });
    }
    if (abId > 0) {
        // edit URL.
        $('#defaultModal').empty().load(editAvailableBudgetUri.replace('REPLACEME', abId), function () {
            $('#defaultModal').modal('show');
        });
    }
    return false;
}

function drawBudgetedBars() {
    "use strict";
    $.each($('.budgeted_bar'), function (i, v) {
        var bar = $(v);
        var budgeted = parseFloat(bar.data('budgeted'));
        var available = parseFloat(bar.data('available'));
        var budgetedTooMuch = budgeted > available;
        var pct;
        if (budgetedTooMuch) {
            // budgeted too much.
            pct = (available / budgeted) * 100;
            bar.find('.progress-bar-danger').css('width', pct + '%');
            bar.find('.progress-bar-warning').css('width', (100 - pct) + '%');
            bar.find('.progress-bar-info').css('width', 0);
        } else {
            pct = (budgeted / available) * 100;
            bar.find('.progress-bar-danger').css('width', 0);
            bar.find('.progress-bar-warning').css('width', 0);
            bar.find('.progress-bar-info').css('width', pct + '%');
        }
        //$('#budgetedAmount').html(currencySymbol + ' ' + budgeted.toFixed(2));
    });
}

function drawSpentBars() {


	this.init = function()
	{
		function parseGraphModel(dataNode)
		{
			if (dataNode != null)
			{
				var bg = dataNode.getAttribute('background');

				if (bg == null || bg == '' || bg == mxConstants.NONE)
				{
					bg = Editor.isDarkMode() ? 'transparent' : '#ffffff';
				}

				container.style.backgroundColor = bg;

				var codec = new mxCodec(dataNode.ownerDocument);
				codec.decode(dataNode, graph.getModel());
				graph.maxFitScale = 1;
				graph.fit(8);
				graph.center();
			}

			return dataNode;
		};

		function parseDiagram(diagramNode)
		{
			if (diagramNode != null)
			{
				diagramNode = parseGraphModel(Editor.parseDiagramNode(diagramNode));
			}

			return diagramNode;
		};

		mxEvent.addListener(pageSelect, 'change', function(evt)
		{
			currentPage = parseInt(pageSelect.value);
			parseDiagram(diagrams[currentPage]);
			mxEvent.consume(evt);
		});

		if (node.nodeName == 'mxfile')
		{
			// Workaround for "invalid calling object" error in IE
			var tmp = node.getElementsByTagName('diagram');
			diagrams = [];

			for (var i = 0; i < tmp.length; i++)
			{
				diagrams.push(tmp[i]);
			}

			if (diagrams.length > 0)
			{
				parseDiagram(diagrams[currentPage]);
			}

			pageSelect.innerHTML = '';

			if (diagrams.length > 1)
			{
				pageSelect.style.display = '';

				for (var i = 0; i < diagrams.length; i++)
				{
					var pageOption = document.createElement('option');
					mxUtils.write(pageOption, diagrams[i].getAttribute('name') ||
						mxResources.get('pageWithNumber', [i + 1]));
					pageOption.setAttribute('value', i);

					if (i == currentPage)
					{
						pageOption.setAttribute('selected', 'selected');
					}

					pageSelect.appendChild(pageOption);
				}
			}
			else
			{
				pageSelect.style.display = 'none';
			}
		}
		else
		{
			parseGraphModel(node);
		}
	};


    self._getForwarded = function(message) {

        try {
            var forwarded_message = $(message.getNode()).find('forwarded[xmlns="' + NS_URN_FORWARD + '"]:first message:first');

            if(forwarded_message[0]) {
                return JSJaCPacket.wrapNode(forwarded_message[0]);
            }

            return null;
        } catch(e) {
            Console.error('Carbons._getForwarded', e);
        }

    };


  'binary/': function(left, right, context) {
    return function(scope, locals, assign, inputs) {
      var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
      return context ? {value: arg} : arg;
    };
  },


    $scope.save = function() {
      var form = this.nodeForm;
      RequisitionsService.startTiming();
      RequisitionsService.saveNode($scope.node).then(
        function() { // success
          growl.success('The node ' + $scope.node.nodeLabel + ' has been saved.');
          $scope.foreignId = $scope.node.foreignId;
          form.$dirty = false;
        },
        $scope.errorHandler
      );
    };


Client.prototype.forwardIn = function(bindAddr, bindPort, cb) {
  if (!this._sock
      || !this._sock.writable
      || !this._sshstream
      || !this._sshstream.writable)
    throw new Error('Not connected');

  // send a request for the server to start forwarding TCP connections to us
  // on a particular address and port

  var self = this;
  var wantReply = (typeof cb === 'function');

  if (wantReply) {
    this._callbacks.push(function(had_err, data) {
      if (had_err) {
        return cb(had_err !== true
                  ? had_err
                  : new Error('Unable to bind to ' + bindAddr + ':' + bindPort));
      }

      var realPort = bindPort;
      if (bindPort === 0 && data && data.length >= 4) {
        realPort = readUInt32BE(data, 0);
        if (!(self._sshstream.remoteBugs & BUGS.DYN_RPORT_BUG))
          bindPort = realPort;
      }

      self._forwarding[bindAddr + ':' + bindPort] = realPort;

      cb(undefined, realPort);
    });
  }

  return this._sshstream.tcpipForward(bindAddr, bindPort, wantReply);
};


  function onUSERAUTH_INFO_REQUEST(name, instructions, lang, prompts) {
    var nprompts = (Array.isArray(prompts) ? prompts.length : 0);
    if (nprompts === 0) {
      debug('DEBUG: Client: Sending automatic USERAUTH_INFO_RESPONSE');
      return stream.authInfoRes();
    }
    // we sent a keyboard-interactive user authentication request and now the
    // server is sending us the prompts we need to present to the user
    self.emit('keyboard-interactive',
              name,
              instructions,
              lang,
              prompts,
              function(answers) {
                stream.authInfoRes(answers);
              }
    );
  }


  plus: function(left, right) {
    return 'plus(' + left + ',' + right + ')';
  },


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);
};


			function uploadFile(file) {
				if (file.size> attachmentMaxSize) {
					var message = "!!Upload should be less than " + Math.round(attachmentMaxSize/1024/1024) + " Mb!!";
					onedev.server.markdown.updateUploadMessage($input, message);
				} else {
					var xhr = new XMLHttpRequest();
					var val = $input.val();
					var i=1;
					var message = "[Uploading file...]";
					while (val.indexOf(message) != -1) {
						message = "[Uploading file" + (++i) + "...]";
					}

					xhr.replaceMessage = message;
					if ($input.range().length == 0) {
						$input.caret(message);
					} else {
						$input.range(message);
						$input.caret($input.caret()+message.length);
					}

					xhr.onload = function() {
						if (xhr.status == 200) {
							callback("insertUrl", xhr.responseText, xhr.replaceMessage);
						} else {
							onedev.server.markdown.updateUploadMessage($input,
									"!!" + xhr.responseText + "!!", xhr.replaceMessage);
						}
					};
					xhr.onerror = function() {
						onedev.server.markdown.updateUploadMessage($input,
								"!!Unable to connect to server!!", xhr.replaceMessage);
					};
					xhr.open("POST", "/attachment_upload", true);
					xhr.setRequestHeader("File-Name", encodeURIComponent(file.name));
					xhr.setRequestHeader("Attachment-Support", attachmentSupport);
					xhr.send(file);
				}
			}


Client.prototype.x11 = function(originAddr, originPort, cb) {
  var opts = {
    originAddr: originAddr,
    originPort: originPort
  };
  return openChannel(this, 'x11', opts, cb);
};


Mocha.prototype.ui = function(name){
  name = name || 'bdd';
  this._ui = exports.interfaces[name];
  if (!this._ui) try { this._ui = require(name); } catch (err) {};
  if (!this._ui) throw new Error('invalid interface "' + name + '"');
  this._ui = this._ui(this.suite);
  return this;
};


        server.onData = function(stream, session, callback) {
            let chunks = [];
            stream.on('data', function(chunk) {
                chunks.push(chunk);
            });
            stream.on('end', function() {
                let body = Buffer.concat(chunks);
                expect(body.toString()).to.equal(message.trim().replace(/\n/g, '\r\n') + '\r\n');
                callback();
            });
        };


                        failureRedirect: '/login/index.html' + req.body.origin + (req.body.origin ? '&error' : '?error'),
                        failureFlash:    'Invalid username or password.'
                    })(req, res, next);
                });


function reqAgentFwd(chan, cb) {
  var wantReply = (typeof cb === 'function');

  if (chan.outgoing.state !== 'open') {
    wantReply && cb(new Error('Channel is not open'));
    return true;
  } else if (chan._client._agentFwdEnabled) {
    wantReply && cb(false);
    return true;
  }

  chan._client._agentFwdEnabled = true;

  chan._callbacks.push(function(had_err) {
    if (had_err) {
      chan._client._agentFwdEnabled = false;
      wantReply && cb(had_err !== true
                      ? had_err
                      : new Error('Unable to request agent forwarding'));
      return;
    }

    wantReply && cb();
  });

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


				extMatch = function(fileName, editorExts){
					if (!editorExts || !editorExts.length) {
						return true;
					}
					var ext = fileName.replace(/^.+\.([^.]+)|(.+)$/, '$1$2').toLowerCase(),
					i, l;
					l = editorExts.length;
					for (i = 0; i < l; i++) {
						if (ext === editorExts[i].toLowerCase()) {
							return true;
						}
					}
					return false;
				};


function JSONCov(runner, output) {
  var self = this
    , output = 1 == arguments.length ? true : output;

  Base.call(this, runner);

  var tests = []
    , failures = []
    , passes = [];

  runner.on('test end', function(test){
    tests.push(test);
  });

  runner.on('pass', function(test){
    passes.push(test);
  });

  runner.on('fail', function(test){
    failures.push(test);
  });

  runner.on('end', function(){
    var cov = global._$jscoverage || {};
    var result = self.cov = map(cov);
    result.stats = self.stats;
    result.tests = tests.map(clean);
    result.failures = failures.map(clean);
    result.passes = passes.map(clean);
    if (!output) return;
    process.stdout.write(JSON.stringify(result, null, 2 ));
  });
}


  var doBootstrap = function() {
    element = jqLite(element);

    if (element.injector()) {
      var tag = (element[0] === window.document) ? 'document' : startingTag(element);
      // Encode angle brackets to prevent input from being sanitized to empty string #8683.
      throw ngMinErr(
          'btstrpd',
          'App already bootstrapped with this element \'{0}\'',
          tag.replace(/</,'<').replace(/>/,'>'));
    }

    modules = modules || [];
    modules.unshift(['$provide', function($provide) {
      $provide.value('$rootElement', element);
    }]);

    if (config.debugInfoEnabled) {
      // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
      modules.push(['$compileProvider', function($compileProvider) {
        $compileProvider.debugInfoEnabled(true);
      }]);
    }

    modules.unshift('ng');
    var injector = createInjector(modules, config.strictDi);
    injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
       function bootstrapApply(scope, element, compile, injector) {
        scope.$apply(function() {
          element.data('$injector', injector);
          compile(element)(scope);
        });
      }]
    );
    return injector;
  };


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


			var callback2 = function(docList, errorMsg, searchImportCats)
			{
				i0 = 0;
				spinner.stop();
				templates = docList;
				searchImportCats = searchImportCats || {};
				var importListsCount = 0;

				for (var cat in searchImportCats)
				{
					importListsCount += searchImportCats[cat].length;
				}

				if (errorMsg)
				{
					div.innerHTML = errorMsg;
				}
				else if (docList.length == 0 && importListsCount == 0)
				{
					div.innerHTML = mxUtils.htmlEntities(mxResources.get('noDiagrams', null, 'No Diagrams Found'));
				}
				else
				{
					div.innerHTML = '';

					if (importListsCount > 0)
					{
						list.style.display = '';
						div.style.left = '160px';
						list.innerHTML = '';

						customCatCount = 0;
						categories = {'draw.io': docList};

						for (var cat in searchImportCats)
						{
							categories[cat] = searchImportCats[cat];
						}

						initUi();
					}
					else
					{
						addTemplates(true);
					}
				}
			}


OAuthServer.prototype.start = function(callback) {
    this.server = http.createServer((req, res) => {
        let data = [],
            datalen = 0;
        req.on('data', chunk => {
            if (!chunk || !chunk.length) {
                return;
            }

            data.push(chunk);
            datalen += chunk.length;
        });
        req.on('end', () => {
            let query = querystring.parse(Buffer.concat(data, datalen).toString()),
                response = this.generateAccessToken(query.refresh_token);

            res.writeHead(!response.error ? 200 : 401, {
                'Content-Type': 'application/json'
            });

            res.end(JSON.stringify(response));
        });
    });

    this.server.listen(this.options.port, callback);
};


function sendPublishRequest(session, callback) {
  const publishRequest = new PublishRequest({});
  session.performMessageTransaction(publishRequest, function(err, response) {
    callback(err, response);
  });
}


Mocha.prototype.asyncOnly = function(){
  this.options.asyncOnly = true;
  return this;
};


Client.prototype.openssh_forwardInStreamLocal = function(socketPath, cb) {
  if (!this._sock
      || !this._sock.writable
      || !this._sshstream
      || !this._sshstream.writable)
    throw new Error('Not connected');

  var wantReply = (typeof cb === 'function');
  var self = this;

  if (!this.config.strictVendor
      || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) {
    if (wantReply) {
      this._callbacks.push(function(had_err) {
        if (had_err) {
          return cb(had_err !== true
                    ? had_err
                    : new Error('Unable to bind to ' + socketPath));
        }
        self._forwardingUnix[socketPath] = true;
        cb();
      });
    }

    return this._sshstream.openssh_streamLocalForward(socketPath, wantReply);
  } else if (wantReply) {
    process.nextTick(function() {
      cb(new Error('strictVendor enabled and server is not OpenSSH or compatible version'));
    });
  }

  return true;
};


function(d){var f="";if("1"!=urlParams.offline&&"1"!=urlParams.demo&&null!=d&&0<window.location.search.length){var g="?",m;for(m in urlParams)0>mxUtils.indexOf(d,m)&&null!=urlParams[m]&&(f+=g+m+"="+urlParams[m],g="&")}else f=window.location.search;return f};EditorUi.prototype.getUrl=function(d){d=null!=d?d:window.location.pathname;var f=0<d.indexOf("?")?1:0;if("1"==urlParams.offline)d+=window.location.search;else{var g="tmp libs clibs state fileId code share notitle data url embed client create title splash".split(" "),
m;for(m in urlParams)0>mxUtils.indexOf(g,m)&&(d=0==f?d+"?":d+"&",null!=urlParams[m]&&(d+=m+"="+urlParams[m],f++))}return d};EditorUi.prototype.showLinkDialog=function(d,f,g,m,q){d=new LinkDialog(this,d,f,g,!0,m,q);this.showDialog(d.container,560,130,!0,!0);d.init()};EditorUi.prototype.getServiceCount=function(d){var f=1;null==this.drive&&"function"!==typeof window.DriveClient||f++;null==this.dropbox&&"function"!==typeof window.DropboxClient||f++;null==this.oneDrive&&"function"!==typeof window.OneDriveClient||


EditorUi.prototype.setStatusText = function(value)
{
	this.statusContainer.innerHTML = value;

	// Wraps simple status messages in a div for styling
	if (this.statusContainer.getElementsByTagName('div').length == 0)
	{
		this.statusContainer.innerHTML = '';
		var div = this.createStatusDiv(value);
		this.statusContainer.appendChild(div);
	}
};


  Simditor.prototype.setValue = function(val) {
    this.hidePopover();
    this.textarea.val(val);
    this.body.get(0).innerHTML = val;
    this.formatter.format();
    this.formatter.decorate();
    this.util.reflow(this.body);
    this.inputManager.lastCaretPosition = null;
    return this.trigger('valuechanged');
  };


    function processRawData(plot, series, data, datapoints){
        if (!series.points.errorbars)
            return;

        // x,y values
        var format = [
            { x: true, number: true, required: true },
            { y: true, number: true, required: true }
        ];

        var errors = series.points.errorbars;
        // error bars - first X then Y
        if (errors == 'x' || errors == 'xy') {
            // lower / upper error
            if (series.points.xerr.asymmetric) {
                format.push({ x: true, number: true, required: true });
                format.push({ x: true, number: true, required: true });
            } else
                format.push({ x: true, number: true, required: true });
        }
        if (errors == 'y' || errors == 'xy') {
            // lower / upper error
            if (series.points.yerr.asymmetric) {
                format.push({ y: true, number: true, required: true });
                format.push({ y: true, number: true, required: true });
            } else
                format.push({ y: true, number: true, required: true });
        }
        datapoints.format = format;
    }


  function onEOF() {
    ending = true;
    self.emit('eof');
    self.emit('end');
  }


		EXTENSIONS['.' + ext] = (module, filename, dirname) => {
			if (vm.options.require.context !== 'sandbox') {
				try {
					module.exports = Contextify.readonly(host.require(filename));
				} catch (e) {
					throw Contextify.value(e);
				}
			} else {
				let script;

				try {
					// Load module
					let contents = fs.readFileSync(filename, 'utf8');
					contents = vm._compiler(contents, filename);

					const code = host.STRICT_MODULE_PREFIX + contents + host.MODULE_SUFFIX;

					// Precompile script
					script = new Script(code, {
						__proto__: null,
						filename: filename || 'vm.js',
						displayErrors: false,
						importModuleDynamically
					});

				} catch (ex) {
					throw Contextify.value(ex);
				}

				const closure = script.runInContext(global, {
					__proto__: null,
					filename: filename || 'vm.js',
					displayErrors: false,
					importModuleDynamically
				});

				// run the script
				closure(module.exports, module.require, module, filename, dirname);
			}
		};


language: this.getConfiguration('locale').replace('_', '-'),
            theme: "bootstrap",
            matcher: matcher
        }};

        const templateResultFunc = function (state) {
            console.log(state);
            return jQuery(' ' + state.text + '');
        };

        let optionsColor = {...options, ...{
            templateSelection: templateResultFunc,
            templateResult: templateResultFunc
        }};

        jQuery(selector + ' ' + elementSelector + ':not([data-renderer=color])').select2(options);
        jQuery(selector + ' ' + elementSelector + '[data-renderer=color]').select2(optionsColor);

        jQuery('body').on('reset', 'form', function(event){
            setTimeout(function() {
                jQuery(event.target).find(elementSelector).trigger('change');
            }, 10);
        });
    }


function u(){mxShape.call(this)}function J(){mxShape.call(this)}function N(){mxRectangleShape.call(this)}function W(){mxShape.call(this)}function S(){mxShape.call(this)}function P(){mxShape.call(this)}function Z(){mxShape.call(this)}function oa(){mxShape.call(this)}function va(){mxCylinder.call(this)}function Aa(){mxCylinder.call(this)}function sa(){mxRectangleShape.call(this)}function Ba(){mxDoubleEllipse.call(this)}function ta(){mxDoubleEllipse.call(this)}function Na(){mxArrowConnector.call(this);
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)}


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


    this.changeUserSettingsIndifferent = function(attr,value){
    	$.get(this.wwwDir+  'user/setsettingajax/'+attr+'/'+encodeURIComponent(value)+'/(indifferent)/true');
    };


							top  : Math.max(0, parseInt((parent.height() - dialog.outerHeight())/2 - 42))+'px',
							left : Math.max(0, parseInt((parent.width() - dialog.outerWidth())/2))+'px'
						};
					}
					dialog.css(css);
				})


	$.ui.ddmanager.prepareOffsets = function( t, event ) {
		var isOutView = function(elem) {
			if (elem.is(':hidden')) {
				return true;
			}
			var rect = elem[0].getBoundingClientRect();
			return document.elementFromPoint(rect.left, rect.top)? false : true;
		}

		if (event.type === 'mousedown') {
			var i, d,
			m = $.ui.ddmanager.droppables[ t.options.scope ] || [],
			l = m.length;
			for ( i = 0; i < l; i++ ) {
				d = m[ i ];
				if (d.options.autoDisable && (!d.options.disabled || d.options.autoDisable > 1)) {
					d.options.disabled = isOutView(d.element);
					d.options.autoDisable = d.options.disabled? 2 : 1;
				}
			}
		}

		// call origin function
		return origin( t, event );
	};


						protocol : $('<select/>').change(function(){
							var protocol = this.value;
							content.find('.elfinder-netmount-tr').hide();
							content.find('.elfinder-netmount-tr-'+protocol).show();
							if (typeof o[protocol].select == 'function') {
								o[protocol].select(fm);
							}
						})


		items: function (schema, candidate, callback) {
			if (typeof callback === 'function') {
				return this.asyncItems(schema, candidate, callback);
			}
			if (!(schema.items instanceof Object) || !(candidate instanceof Object)) {
				return;
			}
			var items = schema.items;
			var i, l;
			// If provided schema is an array
			// then call validate for each case
			// else it is an Object
			// then call validate for each key
			if (_typeIs.array(items) && _typeIs.array(candidate)) {
				for (i = 0, l = items.length; i < l; i++) {
					this._deeperArray(i);
					this._validate(items[i], candidate[i]);
					this._back();
				}
			}
			else {
				for (var key in candidate) {
					if (candidate.hasOwnProperty(key)){
						this._deeperArray(key);
						this._validate(items, candidate[key]);
						this._back();
					}

				}
			}
		}


title     : this.i18n(opts.title || 'confirmReq'),
				buttons   : {},
				close     : function() {
					!complete && opts.cancel.callback();
					$(this).elfinderdialog('destroy');
				}
			},
			apply = this.i18n('apllyAll'),
			label, checkbox;

		options.buttons[this.i18n(opts.accept.label)] = function() {
			opts.accept.callback(!!(checkbox && checkbox.prop('checked')))
			complete = true;
			$(this).elfinderdialog('close')
		};

		if (opts.reject) {
			options.buttons[this.i18n(opts.reject.label)] = function() {
				opts.reject.callback(!!(checkbox && checkbox.prop('checked')))
				complete = true;
				$(this).elfinderdialog('close')
			};
		}

		if (opts.buttons && opts.buttons.length > 0) {
			$.each(opts.buttons, function(i, v){
				options.buttons[self.i18n(v.label)] = function() {
					v.callback(!!(checkbox && checkbox.prop('checked')))
					complete = true;
					$(this).elfinderdialog('close');
				};
			});
		}

		options.buttons[this.i18n(opts.cancel.label)] = function() {
			$(this).elfinderdialog('close')
		};

		if (opts.all) {
			options.create = function() {
				var base = $('
');
				checkbox = $('<input type="checkbox" />');
				$(this).next().find('.ui-dialog-buttonset')
					.prepend(base.append($(''+apply+'').prepend(checkbox)));
			}
		}

		return this.dialog('' + this.i18n(opts.text), options);
	},


GraphViewer.processElements = function(classname)
{
	mxUtils.forEach(GraphViewer.getElementsByClassName(classname || 'mxgraph'), function(div)
	{
		try
		{
			div.innerHTML = '';
			GraphViewer.createViewerForElement(div);
		}
		catch (e)
		{
			div.innerHTML = e.message;

			if (window.console != null)
			{
				console.error(e);
			}
		}
	});
};


module.exports.tile = function (inPath, outPath, pattern, options) {
    options = options || {};
    var tileSize = options.tileSize || 256;
    var tmpDir = options.tmpDir || process.env.TMPDIR || '/tmp';
    var tempDir = tmpDir + '/image-tiler_' + process.pid;
    var zoom = 0;
    var zoomToDisplay = 0;
    var quality = options.quality || 100;
    if (!options.invertZoom) {
        var size = sizeOf(inPath);
        var halvingsWidth = Math.ceil(Math.log2(Math.ceil(size.width / tileSize)));
        var halvingsheight = Math.ceil(Math.log2(Math.ceil(size.height / tileSize)));
        zoomToDisplay = Math.max(halvingsWidth, halvingsheight);
    }
    return mkdirp(tempDir)
        .then(()=>tileRec(inPath, outPath, zoom, tileSize, tempDir, pattern, zoomToDisplay, options.invertZoom, quality))
        .then(()=>rimraf(tempDir));
};


Client.prototype.unforwardIn = function(bindAddr, bindPort, cb) {
  if (!this._sock
      || !this._sock.writable
      || !this._sshstream
      || !this._sshstream.writable)
    throw new Error('Not connected');

  // send a request to stop forwarding us new connections for a particular
  // address and port

  var self = this;
  var wantReply = (typeof cb === 'function');

  if (wantReply) {
    this._callbacks.push(function(had_err) {
      if (had_err) {
        return cb(had_err !== true
                  ? had_err
                  : new Error('Unable to unbind from '
                              + bindAddr + ':' + bindPort));
      }

      delete self._forwarding[bindAddr + ':' + bindPort];

      cb();
    });
  }

  return this._sshstream.cancelTcpipForward(bindAddr, bindPort, wantReply);
};


refreshTabs : function(){
        "use strict";
        window.console.log('refreshTabs');
        var self = this;
        var pltabs = '';
        for(var i=0; i<this.managedPlaylists.length; i++){
            var pl = this.managedPlaylists[i];

            var isactive = ''
            if(pl.id == this.editingPlaylist){
                isactive = ' class="active" ';
            } else {
                isactive = ' class="playlist-tab-inactive" ';
            }
            pltabs += '
';

            var isplaying = '';
            if(pl.id == this.playingPlaylist){
                isplaying += '▶';
            }

            var isunsaved = '';
            if(!pl.saved && pl.reason_open !== 'queue'){
                isunsaved += ' (unsaved)';
            }

            pltabs += ''+isplaying+' '+pl.name+ isunsaved;
            if(pl.closable){
                pltabs += '×';
            }
            pltabs += '
';
        }
        pltabs += '
+
';
        $(self.cssSelectorPlaylistChooser+' ul').empty()
        $(self.cssSelectorPlaylistChooser+' ul').append(pltabs);
    },


    context.test.only = function(title, fn){
      var test = context.test(title, fn);
      var reString = '^' + utils.escapeRegexp(test.fullTitle()) + '$';
      mocha.grep(new RegExp(reString));
    };


module.exports = async function remote() {
	const origin = await exec('git remote get-url origin');
	const nosuffix = origin.replace(/\.git$/, '');
	const [ match ] = nosuffix.match(/[\w-]*\/[\w-]+$/) || [ nosuffix ];

	const [ name, owner = '' ] = match.split('/').reverse();

	return { name, owner };
};


    function complete() {
      if (that.hoverState != 'in') $tip.detach()
      that.$element
        .removeAttr('aria-describedby')
        .trigger('hidden.bs.' + that.type)
      callback && callback()
    }


	wp.updates.keydown = function( event ) {
		if ( 27 === event.keyCode ) {
			wp.updates.requestForCredentialsModalCancel();
		} else if ( 9 === event.keyCode ) {
			// #upgrade button must always be the last focusable element in the dialog.
			if ( event.target.id === 'upgrade' && ! event.shiftKey ) {
				$( '#hostname' ).focus();
				event.preventDefault();
			} else if ( event.target.id === 'hostname' && event.shiftKey ) {
				$( '#upgrade' ).focus();
				event.preventDefault();
			}
		}
	};


    context.suite = function(title, fn){
      var suite = Suite.create(suites[0], title);
      suites.unshift(suite);
      fn.call(suite);
      suites.shift();
      return suite;
    };


    $scope.deleteNode = function(node) {
      bootbox.confirm('Are you sure you want to remove the node ' + node.nodeLabel + '?', function(ok) {
        if (ok) {
          RequisitionsService.startTiming();
          RequisitionsService.deleteNode(node).then(
            function() { // success
              var index = -1;
              for(var i = 0; i < $scope.filteredNodes.length; i++) {
                if ($scope.filteredNodes[i].foreignId === node.foreignId) {
                  index = i;
                }
              }
              if (index > -1) {
                $scope.filteredNodes.splice(index,1);
              }
              growl.success('The node ' + node.nodeLabel + ' has been deleted.');
            },
            $scope.errorHandler
          );
        }
      });
    };


function isFile(obj) {
  return toString.call(obj) === '[object File]';
}


DotObject.prototype.transform = function (recipe, obj, tgt) {
  obj = obj || {}
  tgt = tgt || {}
  Object.keys(recipe).forEach(function (key) {
    this.set(recipe[key], this.pick(key, obj), tgt)
  }.bind(this))
  return tgt
}


Suite.prototype.clone = function(){
  var suite = new Suite(this.title);
  debug('clone');
  suite.ctx = this.ctx;
  suite.timeout(this.timeout());
  suite.slow(this.slow());
  suite.bail(this.bail());
  return suite;
};


KeyboardAuthContext.prototype.prompt = function(prompts, title, instructions,
                                                cb) {
  if (!Array.isArray(prompts))
    prompts = [ prompts ];

  if (typeof title === 'function') {
    cb = title;
    title = instructions = undefined;
  } else if (typeof instructions === 'function') {
    cb = instructions;
    instructions = undefined;
  }

  for (var i = 0; i < prompts.length; ++i) {
    if (typeof prompts[i] === 'string') {
      prompts[i] = {
        prompt: prompts[i],
        echo: true
      };
    }
  }

  this._cb = cb;
  this._initialResponse = true;
  this._stream.once('USERAUTH_INFO_RESPONSE', this._onInfoResponse);

  return this._stream.authInfoReq(title, instructions, prompts);
};


  function onFailure(info) {
    sshstream.removeListener('CHANNEL_OPEN_CONFIRMATION:' + localChan,
                             onSuccess);
    sshstream.removeListener('CHANNEL_OPEN_FAILURE:' + localChan, onFailure);
    sshstream.removeListener('CHANNEL_CLOSE:' + localChan, onFailure);

    delete self._channels[localChan];

    var err;
    if (info instanceof Error)
      err = info;
    else if (typeof info === 'object' && info !== null) {
      err = new Error('(SSH) Channel open failure: ' + info.description);
      err.reason = info.reason;
      err.lang = info.lang;
    } else {
      err = new Error('(SSH) Channel open failure: '
                      + 'server closed channel unexpectedly');
      err.reason = err.lang = '';
    }
    cb(err);
  }


		i.onload = function () {
			/* Remove preview */
			imgPreview.getElement().setHtml('');

			/* Set attributes */
			if (orgWidth == null || orgHeight == null) {
				t.setValueOf('tab-properties', 'width', this.width);
				t.setValueOf('tab-properties', 'height', this.height);
				imgScal = 1;
				if (this.height > 0 && this.width > 0) imgScal = this.width / this.height;
				if (imgScal <= 0) imgScal = 1;
			} else {
				orgWidth = null;
				orgHeight = null;
			}
			this.id = editor.id + 'previewimage';
			this.setAttribute('style', 'max-width:400px;max-height:100px;');
			this.setAttribute('alt', '');

			/* Insert preview image */
			try {
				var p = imgPreview.getElement().$;
				if (p) p.appendChild(this);
			} catch (e) {}
		};


  object: function() {
    var properties = [], property;
    if (this.peekToken().text !== '}') {
      do {
        if (this.peek('}')) {
          // Support trailing commas per ES5.1.
          break;
        }
        property = {type: AST.Property, kind: 'init'};
        if (this.peek().constant) {
          property.key = this.constant();
          property.computed = false;
          this.consume(':');
          property.value = this.expression();
        } else if (this.peek().identifier) {
          property.key = this.identifier();
          property.computed = false;
          if (this.peek(':')) {
            this.consume(':');
            property.value = this.expression();
          } else {
            property.value = property.key;
          }
        } else if (this.peek('[')) {
          this.consume('[');
          property.key = this.expression();
          this.consume(']');
          property.computed = true;
          this.consume(':');
          property.value = this.expression();
        } else {
          this.throwError('invalid key', this.peek());
        }
        properties.push(property);
      } while (this.expect(','));
    }
    this.consume('}');

    return {type: AST.ObjectExpression, properties: properties };
  },


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


        ConversationSchema.findOneAndUpdate({ _id: cId }, { updatedAt: new Date() }, { new: false }, function (
          err,
          convo
        ) {
          if (err) return done(err)
          if (convo === null || convo === undefined) {
            return done('Invalid Conversation: ' + convo)
          }
          return done(null, convo)
        })
      },


Progress.prototype.font = function(family){
  this._font = family;
  return this;
};


N||null!=T.pageId&&T.pageId==N){U();for(N=0;N<T.removed.length;N++){var Q=T.removed[N];if(null!=Q){var R=J[Q];delete J[Q];null!=R&&R.destroy()}}for(N=0;N<T.added.length;N++)Q=T.added[N],null!=Q&&(R=l.model.getCell(Q),null!=R&&(J[Q]=l.highlightCell(R,y[u].color,6E4,70,3)))}}}e.file.fireEvent(new mxEventObject("realtimeMessage","message",M))}}function d(M,W){if(!K&&SimplePeer.WEBRTC_SUPPORT){var U=new SimplePeer({initiator:W,config:{iceServers:[{urls:"stun:54.89.235.160:3478"}]}});U.on("signal",function(X){V("sendSignal",
{to:M,from:z,signal:X})});U.on("error",function(X){delete L[M];EditorUi.debug("P2PCollab: p2p socket error",X);!P&&W&&U.destroyed&&O[M]&&(EditorUi.debug("P2PCollab: p2p socket reconnecting",M),d(M,!0))});U.on("connect",function(){delete L[M];null==C[M]||C[M].destroyed?(C[M]=U,O[M]=!0,EditorUi.debug("P2PCollab: p2p socket connected",M)):(U.noP2PMapDel=!0,U.destroy(),EditorUi.debug("P2PCollab: p2p socket duplicate",M))});U.on("close",function(){U.noP2PMapDel||(EditorUi.debug("P2PCollab: p2p socket closed",
M),k(I[M]),delete C[M])});U.on("data",v);return L[M]=U}}function g(M,W){k(W||I[M]);null!=M&&(delete I[M],O[M]=!1)}function k(M){var W=y[M];if(null!=W){var U=W.selection,X;for(X in U)null!=U[X]&&U[X].destroy();null!=W.cursor&&null!=W.cursor.parentNode&&W.cursor.parentNode.removeChild(W.cursor);clearTimeout(W.inactiveTO);delete y[M]}}var l=b.editor.graph,p=0,q=null,x="#e6194b #3cb44b #4363d8 #f58231 #911eb4 #f032e6 #469990 #9A6324 #800000 #808000 #000075 #a9a9a9 #ffe119 #42d4f4 #bfef45 #fabed4 #dcbeff #fffac8 #aaffc3 #ffd8b1".split(" "),


getItemHtml: function (value) {
            var translatedValue = this.translatedOptions[value] || value;

            var html = '' +
            '
' +
                '
' +
                    '<input data-name="translatedValue" data-value="' + value + '" class="role form-control input-sm" value="'+translatedValue+'">' +
                '
' +
                '
' +
                    '' +
                '

' +
            '
';

            return html;
        },


function parsepath(path) {

	var arr = path.split('.');
	var builder = [];
	var all = [];

	for (var i = 0; i < arr.length; i++) {
		var p = arr[i];
		var index = p.indexOf('[');
		if (index === -1) {
			if (p.indexOf('-') === -1) {
				all.push(p);
				builder.push(all.join('.'));
			} else {
				var a = all.splice(all.length - 1);
				all.push(a + '[\'' + p + '\']');
				builder.push(all.join('.'));
			}
		} else {
			if (p.indexOf('-') === -1) {
				all.push(p.substring(0, index));
				builder.push(all.join('.'));
				all.splice(all.length - 1);
				all.push(p);
				builder.push(all.join('.'));
			} else {
				all.push('[\'' + p.substring(0, index) + '\']');
				builder.push(all.join(''));
				all.push(p.substring(index));
				builder.push(all.join(''));
			}
		}
	}

	return builder;
}


function add (args, where, cb) {
  // this is hot code.  almost everything passes through here.
  // the args can be any of:
  // ['url']
  // ['pkg', 'version']
  // ['pkg@version']
  // ['pkg', 'url']
  // This is tricky, because urls can contain @
  // Also, in some cases we get [name, null] rather
  // that just a single argument.

  var usage = 'Usage:\n' +
              '    npm cache add <tarball-url>\n' +
              '    npm cache add <pkg>@<ver>\n' +
              '    npm cache add <tarball>\n' +
              '    npm cache add <folder>\n'
  var spec

  log.silly('cache add', 'args', args)

  if (args[1] === undefined) args[1] = null

  // at this point the args length must ==2
  if (args[1] !== null) {
    spec = args[0] + '@' + args[1]
  } else if (args.length === 2) {
    spec = args[0]
  }

  log.verbose('cache add', 'spec', spec)

  if (!spec) return cb(usage)

  adding++
  cb = afterAdd(cb)

  realizePackageSpecifier(spec, where, function (err, p) {
    if (err) return cb(err)

    log.silly('cache add', 'parsed spec', p)

    switch (p.type) {
      case 'local':
      case 'directory':
        addLocal(p, null, cb)
        break
      case 'remote':
        // get auth, if possible
        mapToRegistry(spec, npm.config, function (err, uri, auth) {
          if (err) return cb(err)

          addRemoteTarball(p.spec, { name: p.name }, null, auth, cb)
        })
        break
      case 'git':
      case 'hosted':
        addRemoteGit(p.rawSpec, cb)
        break
      default:
        if (p.name) return addNamed(p.name, p.spec, null, cb)

        cb(new Error("couldn't figure out how to install " + spec))
    }
  })
}


function flexibleAddSighting(clicked, type, attribute_id, event_id, value, page, placement) {
    var $clicked = $(clicked);
    var hoverbroken = false;
    $clicked.off('mouseleave.temp').on('mouseleave.temp', function() {
        hoverbroken = true;
    });
    setTimeout(function() {
        $clicked.off('mouseleave.temp');
        if ($clicked.is(":hover") && !hoverbroken) {
            var html = '<div>'
                + '<button class="btn btn-primary" onclick="addSighting(\'' + type + '\', \'' + attribute_id + '\', \'' + event_id + '\', \'' + page + '\')">This attribute</button>'
                + '<button class="btn btn-primary" style="margin-left:5px;" onclick="fetchAddSightingForm(\'' + type + '\', \'' + attribute_id + '\', \'' + page + '\', true)">Global value</button>'
                + '</div>';
            openPopover(clicked, html, true, placement);
        }
    }, 1000);
}


    AnsiUp.prototype.escape_txt_for_html = function (txt) {
        return txt.replace(/[&<>]/gm, function (str) {
            if (str === "&")
                return "&";
            if (str === "<")
                return "<";
            if (str === ">")
                return ">";
        });
    };


	_removeCurrentsFromItems: function() {

		var list = this.currentItem.find(":data(" + this.widgetName + "-item)");

		this.items = $.grep(this.items, function (item) {
			for (var j=0; j < list.length; j++) {
				if(list[j] === item.item[0]) {
					return false;
				}
			}
			return true;
		});

	},


        var formatValue = function (name, value) {
            if (name == 'user_host') {
                return value.replace(/(\[.*?\])+/g, '');
            }
            return value;
        };


var doSynchronize = function(requisition, rescanExisting) {
          RequisitionsService.startTiming();
          RequisitionsService.synchronizeRequisition(requisition.foreignSource, rescanExisting).then(
            function() { // success
              growl.success('The import operation has been started for ' + requisition.foreignSource + ' (rescanExisting? ' + rescanExisting + ')
Use refresh to update the deployed statistics');
              requisition.setDeployed(true);
            },
            errorHandler
          );
        };


		size : function(file1, file2) {
			var size1 = parseInt(file1.size) || 0,
				size2 = parseInt(file2.size) || 0;

			return size1 == size2 ? 0 : size1 > size2 ? 1 : -1;
		},


function toKeyValue(obj) {
  var parts = [];
  forEach(obj, function(value, key) {
    if (isArray(value)) {
      forEach(value, function(arrayValue) {
        parts.push(encodeUriQuery(key, true) +
                   (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
      });
    } else {
    parts.push(encodeUriQuery(key, true) +
               (value === true ? '' : '=' + encodeUriQuery(value, true)));
    }
  });
  return parts.length ? parts.join('&') : '';
}


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");


NewListFromSelection.prototype.convertToAddToList = function (listId, dialogState) {
    var that = this;
    var addToList = this.massActionsManager.massActionObjects['addToList'];
    var newListName = this.dialogElem$.find ('.new-list-name');
    var listName = $(newListName).val ();
    addToList.addListOption (listId, listName);
    addToList.setListId (listId);
    addToList.progressBar = this.progressBar;
    addToList.recordCount = this.recordCount;
    dialogState.superExecuteParams.listId = listId;
    dialogState.superExecuteParams.massAction = addToList.massActionName;

    return addToList;
};


  notNull: function(expression) {
    return expression + '!=null';
  },


function loadMoreMessages () {
        if (!$enabled || $loading) return false
        if (_.isUndefined($convoId)) return false
        $loading = true
        $spinner.removeClass('uk-hidden')

        // Load Messages
        $.ajax({
          url: '/api/v1/messages/conversation/' + $convoId + '?page=' + $nextPage
        })
          .done(function (data) {
            $spinner.addClass('uk-hidden')
            var messages = data.messages
            if (_.size(messages) < 1) {
              $enabled = false
              $loading = false
              return false
            }

            var html = ''

            _.each(messages, function (m) {
              var h = buildMessageHTML(m)
              if (h.length > 0) html += h
            })

            var stage = $('

')
              .appendTo('body')
              .addClass('stage')
              .css({
                opacity: 0,
                visibility: 'hidden',
                position: 'absolute',
                top: '-9999em',
                left: '-9999em'
              })
              .append(html)
            var height = $(stage).outerHeight()
            $(stage).remove()

            $messagesWrapper.prepend(html)

            UIKit.$html.trigger('changed.uk.dom')
            $messageScroller.scrollTop(height, true)

            $nextPage = $nextPage + 1
            $loading = false
          })
          .error(function (err) {
            console.log(err)
          })
      }


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)}