code:
		function uninstallPage()
		{
			$id = $this->getId();

			if(empty($_POST['uninstall_confirm']))
			{

				$plug_vars = e107::getPlug()->load($id)->getMeta();

				$name = e107::getPlug()->getName();
				$this->addTitle(EPL_ADLAN_63);
				$this->addTitle($name);

				return $this->pluginConfirmUninstall($plug_vars);
			}

			$post = e107::getParser()->filter($_POST);

		//	$id = e107::getPlugin

			$text = e107::getPlugin()->uninstall($id, $post);

			e107::getMessage()->add($text, E_MESSAGE_SUCCESS);
			$log = e107::getPlugin()->getLog();
			e107::getDebug()->log($log);

			$this->redirectAction('list');
		}


code:
    function restart($sMessage = '')
    {
        $_COOKIE['sessionID'] = phpAds_SessionStart();
        OA_Auth::displayLogin($sMessage, $_COOKIE['sessionID']);
    }


code:
function select_atversion(){
    global $sort_versions;
    $menu = '<form action="'.$_SERVER['PHP_SELF'].'" method="post">';
    $menu.= '<select name="atversions">';
    $menu.= '<option value="0">'._AT("all").'</option>';
    foreach($sort_versions as $version){
        if($version == VERSION){
            $menu .= '<option value="'.$version.'" selected="selected">'.$version.'</option>';
        }else{
            $menu .= '<option value="'.$version.'" >'.$version.'</option>';
        }
    }
    $menu .='</select>';
    $menu .='<input type="submit"  value="'. _AT('filter').'"/></form>';
    return $menu;
}


code:
    public static function dropdown($vars) {
        if(is_array($vars)){
            //print_r($vars);
            $name = $vars['name'];
            $where = "WHERE ";
            if(isset($vars['parent'])) {
                $where .= " `parent` = '{$vars['parent']}' ";
            }else{
                $where .= "1 ";
            }
            $order_by = "ORDER BY ";
            if(isset($vars['order_by'])) {
                $order_by .= " {$vars['order_by']} ";
            }else{
                $order_by .= " `name` ";
            }
            if (isset($vars['sort'])) {
                $sort = " {$vars['sort']}";
            }
        }
        $cat = Db::result("SELECT * FROM `cat` {$where} {$order_by} {$sort}");
        $drop = "<select name=\"{$name}\" class=\"form-control\"><option></option>";
        if(Db::$num_rows > 0 ){
            foreach ($cat as $c) {
                # code...
                if($c->parent == ''){
                    if(isset($vars['selected']) && $c->id == $vars['selected']) $sel = "SELECTED"; else $sel = "";
                    $drop .= "<option value=\"{$c->id}\" $sel style=\"padding-left: 10px;\">{$c->name}</option>";
                    foreach ($cat as $c2) {
                        # code...
                        if($c2->parent == $c->id){
                            if(isset($vars['selected']) && $c2->id == $vars['selected']) $sel = "SELECTED"; else $sel = "";
                            $drop .= "<option value=\"{$c2->id}\" $sel style=\"padding-left: 10px;\">   {$c2->name}</option>";
                        }
                    }
                }

            }
        }
        $drop .= "</select>";

        return $drop;
    }


code:
            self::$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
            return self::$mysqli;
        }
    }


code:
    public static function makeConfig ($file) {
        $config = "<?php if(!defined('GX_LIB')) die(\"Direct Access Not Allowed!\");
/**
* GeniXCMS - Content Management System
*
* PHP Based Content Management System and Framework
*
* @package GeniXCMS
* @since 0.0.1 build date 20140925
* @version 0.0.1
* @link https://github.com/semplon/GeniXCMS
* @author Puguh Wijayanto (www.metalgenix.com)
* @copyright 2014-2015 Puguh Wijayanto
* @license http://www.opensource.org/licenses/mit-license.php MIT
*
*/

// DB CONFIG
define('DB_HOST', '".Session::val('dbhost')."');
define('DB_NAME', '".Session::val('dbname')."');
define('DB_PASS', '".Session::val('dbpass')."');
define('DB_USER', '".Session::val('dbuser')."');
define('DB_DRIVER', 'mysqli');

define('THEME', 'default');
define('GX_LANG', 'english');
define('SMART_URL', false); //set 'true' if you want use SMART URL (SEO Friendly URL)
define('GX_URL_PREFIX', '.html');
define('SECURITY', '".Typo::getToken(200)."'); // for security purpose, will be used for creating password

        ";
        try{
            $f = fopen($file, "w");
            $c = fwrite($f, $config);
            fclose($f);
        }catch (Exception $e) {
            echo $e->getMessage();
        }

        return $config;
    }


code:
$data .= '<input type="hidden" name="'.htmlspecialchars($key).'" value="'.htmlspecialchars($value).'" />';
    }
    echo "<title>CSRF check failed</title>

CSRF check failed. Your form session may have expired, or you may not have
        cookies enabled.

        <form method='post' action=''>$data<input type='submit' value='Try again' /></form>

Debug: $tokens

";
}


code:
    public function delete(){
        $cat_id = I("cat_id/d")? I("cat_id/d") : 0;
        $cat = D("Catalog")->where(" cat_id = '$cat_id' ")->find();
        $item_id = $cat['item_id'];

        $login_user = $this->checkLogin();
        if (!$this->checkItemEdit($login_user['uid'] , $item_id)) {
            $return['error_code'] = -1 ;
            $return['error_message'] = L('no_permissions');
            $this->sendResult($return);
            return;
        }

        if ($cat_id > 0 ) {

            $ret = D("Catalog")->deleteCat($cat_id);

        }
        if ($ret) {
           $this->sendResult($ret);
        }else{
            $return['error_code'] = -1 ;
            $return['error_message'] = 'request  fail' ;
            $this->sendResult($return);
        }
    }


code:
	public static function GetNewTransactionId()
	{
		if (!is_dir(APPROOT.'data/transactions'))
		{
			if (!is_writable(APPROOT.'data'))
			{
				throw new Exception('The directory "'.APPROOT.'data" must be writable to the application.');
			}
			/** @noinspection MkdirRaceConditionInspection */
			if (!@mkdir(APPROOT.'data/transactions'))
			{
				throw new Exception('Failed to create the directory "'.APPROOT.'data/transactions". Ajust the rights on the parent directory or let an administrator create the transactions directory and give the web sever enough rights to write into it.');
			}
		}
		if (!is_writable(APPROOT.'data/transactions'))
		{
			throw new Exception('The directory "'.APPROOT.'data/transactions" must be writable to the application.');
		}
		self::CleanupOldTransactions();
		$id = basename(tempnam(APPROOT.'data/transactions', static::GetUserPrefix()));
		self::Info('GetNewTransactionId: Created transaction: '.$id);

		return (string)$id;
	}


code:
	public static function IsTransactionValid($id, $bRemoveTransaction = true)
	{
		// Constraint the transaction file within APPROOT.'data/transactions'
		$sTransactionDir = realpath(APPROOT.'data/transactions');
		$sFilepath = utils::RealPath($sTransactionDir.'/'.$id, $sTransactionDir);
		if (($sFilepath === false) || (strlen($sTransactionDir) == strlen($sFilepath)))
		{
			return false;
		}

		clearstatcache(true, $sFilepath);
		$bResult = file_exists($sFilepath);
		if ($bResult)
		{
			if ($bRemoveTransaction)
			{
				$bResult = @unlink($sFilepath);
				if (!$bResult)
				{
					self::Error('IsTransactionValid: FAILED to remove transaction '.$id);
				}
				else
				{
					self::Info('IsTransactionValid: OK. Removed transaction: '.$id);
				}
			}
		}
		else
		{
			self::Info("IsTransactionValid: Transaction '$id' not found. Pending transactions for this user:\n".implode("\n", self::GetPendingTransactions()));
		}
		return $bResult;
	}


code:
				$this->doDelete( $type, $dump );
			}
		}

		$pager = new DataDumpPager( $this->getContext(), $this->getPageTitle() );

		$out->addModuleStyles( 'mediawiki.special' );

		$pager->getForm();
		$out->addParserOutputContent( $pager->getFullOutput() );
	}


code:
    public function setPassword(Request $request, string $token)
    {
        $this->validate($request, [
            'password' => ['required', 'min:8'],
        ]);

        try {
            $userId = $this->inviteService->checkTokenAndGetUserId($token);
        } catch (Exception $exception) {
            return $this->handleTokenException($exception);
        }

        $user = $this->userRepo->getById($userId);
        $user->password = bcrypt($request->get('password'));
        $user->email_confirmed = true;
        $user->save();

        $this->inviteService->deleteByUser($user);
        $this->showSuccessNotification(trans('auth.user_invite_success', ['appName' => setting('app-name')]));
        $this->loginService->login($user, auth()->getDefaultDriver());

        return redirect('/');
    }


code:
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        if (!isset($options['api_data'])) {
            return;
        }

        $apiData = $options['api_data'];

        if (!\is_array($apiData)) {
            throw new \InvalidArgumentException('Option "api_data" must be an array for form "' . $form->getName() . '"');
        }

        if (!isset($apiData['select'])) {
            return;
        }

        if (!isset($apiData['route'])) {
            throw new \InvalidArgumentException('Missing "route" option for "api_data" option for form "' . $form->getName() . '"');
        }

        if (!isset($apiData['route_params'])) {
            $apiData['route_params'] = [];
        }

        $formPrefixes = [];
        $parent = $form->getParent();
        do {
            $formPrefixes[] = $parent->getName();
        } while (($parent = $parent->getParent()) !== null);

        $formPrefix = implode('_', array_reverse($formPrefixes));

        $formField = $formPrefix . '_' . $apiData['select'];

        $view->vars['attr'] = array_merge($view->vars['attr'], [
            'data-form-prefix' => $formPrefix,
            'data-related-select' => $formField,
            'data-api-url' => $this->router->generate($apiData['route'], $apiData['route_params']),
        ]);

        if (isset($apiData['empty_route_params'])) {
            $view->vars['attr'] = array_merge($view->vars['attr'], [
                'data-empty-url' => $this->router->generate($apiData['route'], $apiData['empty_route_params']),
            ]);
        }
    }


code:
rcube_webmail.prototype.enigma_export = function(selected)
{
    var keys = selected ? this.keys_list.get_selection().join(',') : '*';

    if (!keys.length)
        return;

    this.goto_url('plugin.enigmakeys', {_a: 'export', _keys: keys});
};


code:
	deleteTheme: function() {
		return confirm( themes.data.settings.confirmDelete );
	},


code:
	wp.updates.beforeunload = function() {
		if ( wp.updates.updateLock ) {
			return wp.updates.l10n.beforeunload;
		}
	};


code:
	wp.updates.credentialError = function( response, type ) {
		wp.updates.updateQueue.push( {
			'type': type,
			'data': {
				// Not cool that we're depending on response for this data.
				// This would feel more whole in a view all tied together.
				plugin: response.plugin,
				slug: response.slug
			}
		} );
		wp.updates.showErrorInCredentialsForm( response.error );
		wp.updates.requestFilesystemCredentials();
	};


code:
        success:function (data, textStatus) {
            showMessage('success', 'Homepage set.');
            $('#setHomePage').addClass('orange');
        },


code:
function checkAddingNode(){
  var nodeName = $("#add_node").children("form").find("[name='new_nodename']").val().trim();
  if (nodeName == "") {
    $("#add_node_submit_btn").button("option", "disabled", false);
    return false;
  }

  $.ajax({
    type: 'GET',
    url: '/manage/check_pcsd_status',
    data: {"nodes": nodeName},
    timeout: pcs_timeout,
    success: function (data) {
      var mydata = jQuery.parseJSON(data);
      if (mydata[nodeName] == "Unable to authenticate") {
        auth_nodes_dialog([nodeName], function(){$("#add_node_submit_btn").trigger("click");});
        $("#add_node_submit_btn").button("option", "disabled", false);
      } else if (mydata[nodeName] == "Offline") {
        alert("Unable to contact node '" + nodeName + "'");
        $("#add_node_submit_btn").button("option", "disabled", false);
      } else {
        create_node($("#add_node").children("form"));
      }
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      alert("ERROR: Unable to contact server");
      $("#add_node_submit_btn").button("option", "disabled", false);
    }
  });
}


code:
    $scope.initialize = function(customHandler) {
      var value = $cookies.get('requisitions_page_size');
      if (value) {
        $scope.pageSize = value;
      }
      growl.success('Retrieving requisition ' + $scope.foreignSource + '...');
      RequisitionsService.getRequisition($scope.foreignSource).then(
        function(requisition) { // success
          $scope.requisition = requisition;
          $scope.filteredNodes = requisition.nodes;
          $scope.updateFilteredNodes();
          if (customHandler) {
            customHandler();
          }
        },
        $scope.errorHandler
      );
    };


code:
    this.changeUserSettings = function(attr,value){
    	$.get(this.wwwDir+  'user/setsettingajax/'+attr+'/'+value);
    };


code:
    def test_reset_student_attempts_delete(self):
        """ Test delete single student state. """
        url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})
        response = self.client.get(url, {
            'problem_to_reset': self.problem_urlname,
            'unique_student_identifier': self.student.email,
            'delete_module': True,
        })
        self.assertEqual(response.status_code, 200)
        # make sure the module has been deleted
        self.assertEqual(
            StudentModule.objects.filter(
                student=self.module_to_reset.student,
                course_id=self.module_to_reset.course_id,
                # module_id=self.module_to_reset.module_id,
            ).count(),
            0
        )


code:
    def test_list_email_content_error(self, task_history_request):
        """ Test handling of error retrieving email """
        invalid_task = FakeContentTask(0, 0, 0, 'test')
        invalid_task.make_invalid_input()
        task_history_request.return_value = [invalid_task]
        url = reverse('list_email_content', kwargs={'course_id': self.course.id.to_deprecated_string()})
        response = self.client.get(url, {})
        self.assertEqual(response.status_code, 200)

        self.assertTrue(task_history_request.called)
        returned_email_info = json.loads(response.content)['emails']
        self.assertEqual(len(returned_email_info), 1)
        returned_info = returned_email_info[0]
        for info in ['created', 'sent_to', 'email', 'number_sent', 'requester']:
            self.assertEqual(returned_info[info], None)


code:
    def test_rescore_entrance_exam_with_invalid_exam(self):
        """ Test course has entrance exam id set while re-scoring. """
        url = reverse('rescore_entrance_exam', kwargs={'course_id': unicode(self.course.id)})
        response = self.client.get(url, {
            'unique_student_identifier': self.student.email,
        })
        self.assertEqual(response.status_code, 400)


code:
    def test_get_students_who_may_enroll(self):
        """
        Test whether get_students_who_may_enroll returns an appropriate
        status message when users request a CSV file of students who
        may enroll in a course.
        """
        url = reverse(
            'get_students_who_may_enroll',
            kwargs={'course_id': unicode(self.course.id)}
        )
        # Successful case:
        response = self.client.get(url, {})
        res_json = json.loads(response.content)
        self.assertIn('status', res_json)
        self.assertNotIn('currently being created', res_json['status'])
        # CSV generation already in progress:
        with patch('instructor_task.api.submit_calculate_may_enroll_csv') as submit_task_function:
            error = AlreadyRunningError()
            submit_task_function.side_effect = error
            response = self.client.get(url, {})
            res_json = json.loads(response.content)
            self.assertIn('status', res_json)
            self.assertIn('currently being created', res_json['status'])


code:
    def test_get_sale_records_features_csv(self):
        """
        Test that the response from get_sale_records is in csv format.
        """
        for i in range(2):
            course_registration_code = CourseRegistrationCode(
                code='sale_invoice{}'.format(i),
                course_id=self.course.id.to_deprecated_string(),
                created_by=self.instructor,
                invoice=self.sale_invoice_1,
                invoice_item=self.invoice_item,
                mode_slug='honor'
            )
            course_registration_code.save()

        url = reverse(
            'get_sale_records',
            kwargs={'course_id': self.course.id.to_deprecated_string()}
        )
        response = self.client.get(url + '/csv', {})
        self.assertEqual(response['Content-Type'], 'text/csv')


code:
    def test_modify_access_revoke(self):
        url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
        response = self.client.get(url, {
            'unique_student_identifier': self.other_staff.email,
            'rolename': 'staff',
            'action': 'revoke',
        })
        self.assertEqual(response.status_code, 200)


code:
    def get_email_content_response(self, num_emails, task_history_request, with_failures=False):
        """ Calls the list_email_content endpoint and returns the repsonse """
        self.setup_fake_email_info(num_emails, with_failures)
        task_history_request.return_value = self.tasks.values()
        url = reverse('list_email_content', kwargs={'course_id': self.course.id.to_deprecated_string()})
        with patch('instructor.views.api.CourseEmail.objects.get') as mock_email_info:
            mock_email_info.side_effect = self.get_matching_mock_email
            response = self.client.get(url, {})
        self.assertEqual(response.status_code, 200)
        return response


code:
    def test_get_student_progress_url(self):
        """ Test that progress_url is in the successful response. """
        url = reverse('get_student_progress_url', kwargs={'course_id': self.course.id.to_deprecated_string()})
        url += "?unique_student_identifier={}".format(
            quote(self.students[0].email.encode("utf-8"))
        )
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        res_json = json.loads(response.content)
        self.assertIn('progress_url', res_json)


code:
    def test_reset_student_attempts_invalid_entrance_exam(self):
        """ Test reset for invalid entrance exam. """
        url = reverse('reset_student_attempts_for_entrance_exam',
                      kwargs={'course_id': unicode(self.course_with_invalid_ee.id)})
        response = self.client.get(url, {
            'unique_student_identifier': self.student.email,
        })
        self.assertEqual(response.status_code, 400)


code:
def list_forum_members(request, course_id):
    """
    Lists forum members of a certain rolename.
    Limited to staff access.

    The requesting user must be at least staff.
    Staff forum admins can access all roles EXCEPT for FORUM_ROLE_ADMINISTRATOR
        which is limited to instructors.

    Takes query parameter `rolename`.
    """
    course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id)
    course = get_course_by_id(course_id)
    has_instructor_access = has_access(request.user, 'instructor', course)
    has_forum_admin = has_forum_access(
        request.user, course_id, FORUM_ROLE_ADMINISTRATOR
    )

    rolename = request.GET.get('rolename')

    # default roles require either (staff & forum admin) or (instructor)
    if not (has_forum_admin or has_instructor_access):
        return HttpResponseBadRequest(
            "Operation requires staff & forum admin or instructor access"
        )

    # EXCEPT FORUM_ROLE_ADMINISTRATOR requires (instructor)
    if rolename == FORUM_ROLE_ADMINISTRATOR and not has_instructor_access:
        return HttpResponseBadRequest("Operation requires instructor access.")

    # filter out unsupported for roles
    if rolename not in [FORUM_ROLE_ADMINISTRATOR, FORUM_ROLE_MODERATOR, FORUM_ROLE_COMMUNITY_TA]:
        return HttpResponseBadRequest(strip_tags(
            "Unrecognized rolename '{}'.".format(rolename)
        ))

    try:
        role = Role.objects.get(name=rolename, course_id=course_id)
        users = role.users.all().order_by('username')
    except Role.DoesNotExist:
        users = []

    def extract_user_info(user):
        """ Convert user to dict for json rendering. """
        return {
            'username': user.username,
            'email': user.email,
            'first_name': user.first_name,
            'last_name': user.last_name,
        }

    response_payload = {
        'course_id': course_id.to_deprecated_string(),
        rolename: map(extract_user_info, users),
    }
    return JsonResponse(response_payload)


code:
    def decorator(func):  # pylint: disable=missing-docstring
        def wrapped(*args, **kwargs):  # pylint: disable=missing-docstring
            request = args[0]

            error_response_data = {
                'error': 'Missing required query parameter(s)',
                'parameters': [],
                'info': {},
            }

            for (param, extra) in required_params:
                default = object()
                if request.GET.get(param, default) == default:
                    error_response_data['parameters'].append(param)
                    error_response_data['info'][param] = extra

            if len(error_response_data['parameters']) > 0:
                return JsonResponse(error_response_data, status=400)
            else:
                return func(*args, **kwargs)
        return wrapped


code:
    def test_file(self, tmpdir):
        filename = tmpdir / 'foo'
        filename.ensure()
        url = QUrl.fromLocalFile(str(filename))
        req = QNetworkRequest(url)
        reply = filescheme.handler(req)
        assert reply is None


code:
  public void onSubmit()
  {
    final String sessionCsrfToken = getCsrfSessionToken();
    final String postedCsrfToken = this.csrfTokenField.getInput();
    if (StringUtils.equals(sessionCsrfToken, postedCsrfToken) == false) {
      log.error("Cross site request forgery alert. csrf token doesn't match! session csrf token="
          + sessionCsrfToken
          + ", posted csrf token="
          + postedCsrfToken);
      throw new InternalErrorException("errorpage.csrfError");
    }
  }


code:
  public DropFileContainer(final String id, final String mimeType) {
    super(id);
    this.mimeType = mimeType;
    main = new WebMarkupContainer("main");
    add(main);
  }


code:
    public void accessAllowed() {
        expect(backend.isRemoteAccessAllowed("localhost","127.0.0.1")).andReturn(true);
        replay(backend);

        handler.checkClientIPAccess("localhost","127.0.0.1");
    }


code:
    public void handle(HttpExchange pExchange) throws IOException {
        if (requestHandler == null) {
            throw new IllegalStateException("Handler not yet started");
        }

        JSONAware json = null;
        URI uri = pExchange.getRequestURI();
        ParsedUri parsedUri = new ParsedUri(uri,context);
        try {
            // Check access policy
            InetSocketAddress address = pExchange.getRemoteAddress();
            requestHandler.checkClientIPAccess(address.getHostName(),address.getAddress().getHostAddress());
            String method = pExchange.getRequestMethod();

            // Dispatch for the proper HTTP request method
            if ("GET".equalsIgnoreCase(method)) {
                setHeaders(pExchange);
                json = executeGetRequest(parsedUri);
            } else if ("POST".equalsIgnoreCase(method)) {
                setHeaders(pExchange);
                json = executePostRequest(pExchange, parsedUri);
            } else if ("OPTIONS".equalsIgnoreCase(method)) {
                performCorsPreflightCheck(pExchange);
            } else {
                throw new IllegalArgumentException("HTTP Method " + method + " is not supported.");
            }
        } catch (Throwable exp) {
            json = requestHandler.handleThrowable(
                    exp instanceof RuntimeMBeanException ? ((RuntimeMBeanException) exp).getTargetException() : exp);
        } finally {
            sendResponse(pExchange,parsedUri,json);
        }
    }


code:
    private static final RestrictorCheck CORS_CHECK = new RestrictorCheck() {
        /** {@inheritDoc} */
        public boolean check(Restrictor restrictor, Object... args) {
            return restrictor.isCorsAccessAllowed((String) args[0]);
        }
    };


code:
    public boolean isCorsAccessAllowed(String pOrigin) {
        return checkRestrictorService(CORS_CHECK,pOrigin);
    }


code:
        public boolean isCorsAccessAllowed(String pOrigin) {
            return cors;
        }


code:
    def initialize(session, config_classes, nodes, cluster_name)
      @config_classes = config_classes
      @nodes = nodes
      @cluster_name = cluster_name
      @session = session
    end


code:
    def send(force=false)
      nodes_txt = @nodes.join(', ')
      @configs.each { |cfg|
        $logger.info(
          "Sending config '#{cfg.class.name}' version #{cfg.version} #{cfg.hash}"\
          + " to nodes: #{nodes_txt}"
        )
      }

      data = self.prepare_request_data(@configs, @cluster_name, force)
      node_response = {}
      threads = []
      @nodes.each { |node|
        threads << Thread.new {
          code, out = send_request_with_token(
            @session, node, 'set_configs', true, data, true, nil, 30,
            @additional_tokens
          )
          if 200 == code
            begin
              node_response[node] = JSON.parse(out)
            rescue JSON::ParserError
            end
          elsif 404 == code
            node_response[node] = {'status' => 'not_supported'}
          else
            begin
              response = JSON.parse(out)
              if true == response['notauthorized'] or true == response['notoken']
                node_response[node] = {'status' => 'notauthorized'}
              end
            rescue JSON::ParserError
            end
          end
          if not node_response.key?(node)
            node_response[node] = {'status' => 'error'}
          end
          # old pcsd returns this instead of 404 if pacemaker isn't running there
          if node_response[node]['pacemaker_not_running']
            node_response[node] = {'status' => 'not_supported'}
          end
        }
      }
      threads.each { |t| t.join }

      node_response.each { |node, response|
        $logger.info("Sending config response from #{node}: #{response}")
      }

      return node_response
    end


code:
def remove_node(session, new_nodename, all=false)
  if all
    # we check for a quorum loss warning in remote_remove_nodes
    out, stderror, retval = run_cmd(
      session, PCS, "cluster", "node", "remove", new_nodename, "--force"
    )
  else
    out, stderror, retval = run_cmd(
      session, PCS, "cluster", "localnode", "remove", new_nodename
    )
  end
  $logger.info("Removing #{new_nodename} from pcs_settings.conf")
  corosync_nodes = get_corosync_nodes()
  pcs_config = PCSConfig.new(Cfgsync::PcsdSettings.from_file('{}').text())
  pcs_config.update_cluster($cluster_name, corosync_nodes)
  sync_config = Cfgsync::PcsdSettings.from_text(pcs_config.text())
  # on version conflict just go on, config will be corrected eventually
  # by displaying the cluster in the web UI
  Cfgsync::save_sync_new_version(
    sync_config, corosync_nodes, $cluster_name, true
  )
  return retval, out + stderror
end


code:
def remove_acl_permission(session, acl_perm_id)
  stdout, stderror, retval = run_cmd(
    session, PCS, "acl", "permission", "delete", acl_perm_id.to_s
  )
  if retval != 0
    if stderror.empty?
      return "Error removing permission"
    else
      return stderror.join("\n").strip
    end
  end
  return ""
end


code:
def get_corosync_version()
  begin
    stdout, stderror, retval = run_cmd(
      PCSAuth.getSuperuserSession, COROSYNC, "-v"
    )
  rescue
    stdout = []
  end
  if retval == 0
    match = /version\D+(\d+)\.(\d+)\.(\d+)/.match(stdout.join())
    if match
      return match[1..3].collect { | x | x.to_i }
    end
  end
  return nil
end


code:
def get_cluster_name()
  if ISRHEL6
    stdout, stderror, retval = run_cmd(
      PCSAuth.getSuperuserSession, COROSYNC_CMAPCTL, "cluster"
    )
    if retval == 0
      stdout.each { |line|
        match = /^cluster\.name=(.*)$/.match(line)
        return match[1] if match
      }
    end
    begin
      cluster_conf = Cfgsync::ClusterConf.from_file().text()
    rescue
      return ''
    end
    conf_dom = REXML::Document.new(cluster_conf)
    if conf_dom.root and conf_dom.root.name == 'cluster'
      return conf_dom.root.attributes['name']
    end
    return ''
  end

  stdout, stderror, retval = run_cmd(
    PCSAuth.getSuperuserSession, COROSYNC_CMAPCTL, "totem.cluster_name"
  )
  if retval != 0 and not ISRHEL6
    # Cluster probably isn't running, try to get cluster name from
    # corosync.conf
    begin
      corosync_conf = CorosyncConf::parse_string(
        Cfgsync::CorosyncConf.from_file().text()
      )
      # mimic corosync behavior - the last cluster_name found is used
      cluster_name = nil
      corosync_conf.sections('totem').each { |totem|
        totem.attributes('cluster_name').each { |attrib|
          cluster_name = attrib[1]
        }
      }
      return cluster_name if cluster_name
    rescue
      return ''
    end
    return ""
  else
    return stdout.join().gsub(/.*= /,"").strip
  end
end


code:
def add_node_attr(session, node, key, value)
  stdout, stderr, retval = run_cmd(
    session, PCS, "property", "set", "--node", node, key.to_s + '=' + value.to_s
  )
  return retval
end


code:
def get_wizard(params, request, session)
  if not allowed_for_local_cluster(session, Permissions::READ)
    return 403, 'Permission denied'
  end
  wizard = PCSDWizard.getWizard(params["wizard"])
  if wizard != nil
    return erb wizard.collection_page
  else
    return "Error finding Wizard - #{params["wizard"]}"
  end
end


code:
def fence_device_form(params, request, session)
  if not allowed_for_local_cluster(session, Permissions::READ)
    return 403, 'Permission denied'
  end

  @cur_resource = get_resource_by_id(params[:resource], get_cib_dom(session))

  if @cur_resource.instance_of?(ClusterEntity::Primitive) and @cur_resource.stonith
    @resource_agents = getFenceAgents(session, @cur_resource.agentname)
    @existing_resource = true
    @fenceagent = @resource_agents[@cur_resource.type]
    erb :fenceagentform
  else
    "Can't find fence device"
  end
end


code:
def resource_clone(params, request, session)
  if not allowed_for_local_cluster(session, Permissions::WRITE)
    return 403, 'Permission denied'
  end

  unless params[:resource_id]
    return [400, 'resource_id has to be specified.']
  end

  _, stderr, retval = run_cmd(
    session, PCS, 'resource', 'clone', params[:resource_id]
  )
  if retval != 0
    return [400, 'Unable to create clone resource from ' +
      "'#{params[:resource_id]}': #{stderr.join('')}"
    ]
  end
  return 200
end


code:
def remote_remove_nodes(params, request, session)
  if not allowed_for_local_cluster(session, Permissions::FULL)
    return 403, 'Permission denied'
  end
  count = 0
  out = ""
  node_list = []
  options = []
  while params["nodename-" + count.to_s]
    node_list << params["nodename-" + count.to_s]
    count = count + 1
  end
  options << "--force" if params["force"]

  cur_node = get_current_node_name()
  if i = node_list.index(cur_node)
    node_list.push(node_list.delete_at(i))
  end

  # stop the nodes at once in order to:
  # - prevent resources from moving pointlessly
  # - get possible quorum loss warning
  stop_params = node_list + options
  stdout, stderr, retval = run_cmd(
    session, PCS, "cluster", "stop", *stop_params
  )
  if retval != 0
    return [400, stderr.join]
  end

  node_list.each {|node|
    retval, output = remove_node(session, node, true)
    out = out + output.join("\n")
  }
  config = PCSConfig.new(Cfgsync::PcsdSettings.from_file('{}').text())
  if config.get_nodes($cluster_name) == nil or config.get_nodes($cluster_name).length == 0
    return [200,"No More Nodes"]
  end
  return out
end


code:
def get_sw_versions(params, request, session)
  versions = {
    "rhel" => get_rhel_version(),
    "pcs" => get_pcsd_version(),
    "pacemaker" => get_pacemaker_version(),
    "corosync" => get_corosync_version(),
    "cman" => get_cman_version(),
  }
  return JSON.generate(versions)
end


code:
def set_node_utilization(params, reqest, session)
  unless allowed_for_local_cluster(session, Permissions::WRITE)
    return 403, 'Permission denied'
  end

  unless params[:node] and params[:name]
    return 400, 'node and name are required'
  end

  node = params[:node]
  name = params[:name]
  value = params[:value] || ''

  _, stderr, retval = run_cmd(
    session, PCS, 'node', 'utilization', node, "#{name}=#{value}"
  )

  if retval != 0
    return [400, "Unable to set utilization '#{name}=#{value}' for node " +
      "'#{res_id}': #{stderr.join('')}"
    ]
  end
  return 200
end


code:
def resource_start(params, request, session)
  if not allowed_for_local_cluster(session, Permissions::WRITE)
    return 403, 'Permission denied'
  end
  stdout, stderr, retval = run_cmd(
    session, PCS, "resource", "enable", params[:resource]
  )
  if retval == 0
    return JSON.generate({"success" => "true"})
  else
    return JSON.generate({"error" => "true", "stdout" => stdout, "stderror" => stderr})
  end
end


code:
def cluster_destroy(params, request, session)
  if not allowed_for_local_cluster(session, Permissions::FULL)
    return 403, 'Permission denied'
  end
  out, errout, retval = run_cmd(session, PCS, "cluster", "destroy")
  if retval == 0
    return [200, "Successfully destroyed cluster"]
  else
    return [400, "Error destroying cluster:\n#{out}\n#{errout}\n#{retval}\n"]
  end
end


code:
def remote_pcsd_restart(params, request, session)
  pcsd_restart()
  return [200, 'success']
end


code:
export async function formParse(req: any): Promise<FormParseResult> {
	// It's not clear how to get mocked requests to be parsed successfully by
	// formidable so we use this small hack. If it's mocked, we are running test
	// units and the request body is already an object and can be returned.
	if (req.__isMocked) {
		const output: any = {};
		if (req.files) output.files = req.files;
		output.fields = req.body || {};
		return output;
	}

	// Note that for Formidable to work, the content-type must be set in the
	// headers
	return new Promise((resolve: Function, reject: Function) => {
		const form = formidable({ multiples: true });
		form.parse(req, (error: any, fields: any, files: any) => {
			if (error) {
				reject(error);
				return;
			}

			resolve({ fields, files });
		});
	});
}