Updates user preferences.

@param   req     The HTTP request.

@param   userId  The ID of the user to update.
@param   prefs   The updated preferences.

@return  The updated user DTO.

@throws  WebApplicationException  If an error occurs.
189532
@PUT
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @Path("{userId}/preferences")
    @Description("Update user preferences.")
    public PrincipalUserDto updateUserPreferences(@Context HttpServletRequest req,
        @PathParam("userId") final BigInteger userId, final Map<Preference, String> prefs) {
        if (userId == null || userId.compareTo(BigInteger.ZERO) < 1) {
            throw new WebApplicationException("User Id cannot be null and must be a positive non-zero number.", Status.BAD_REQUEST);
        }
        if (prefs == null) {
            throw new WebApplicationException("Cannot update with null prefs.", Status.BAD_REQUEST);
        }

        PrincipalUser remoteUser = getRemoteUser(req);
        PrincipalUser user = _uService.findUserByPrimaryKey(userId);

        validateResourceAuthorization(req, user, remoteUser);
        if (user == null) {
            throw new WebApplicationException(Response.Status.NOT_FOUND.getReasonPhrase(), Response.Status.NOT_FOUND);
        }
        user.getPreferences().putAll(prefs);
        user = _uService.updateUser(user);
        return PrincipalUserDto.transformToDto(user);
    }
79380
public FutureAPIResponse setUserAsFuture(String uid, Map<String, Object> properties)
      throws IOException {
    return setUserAsFuture(uid, properties, new DateTime());
  }
1348004
@Programmatic
    public ApplicationUser newDelegateUser(
            final String username,
            final ApplicationRole initialRole,
            final Boolean enabled) {
        final ApplicationUser user = getApplicationUserFactory().newApplicationUser();
        user.setUsername(username);
        user.setStatus(ApplicationUserStatus.parse(enabled));
        user.setAccountType(AccountType.DELEGATED);
        if (initialRole != null) {
            user.addRole(initialRole);
        }
        container.persistIfNotAlready(user);
        return user;
    }
354282
protected ApplicationUser findApplicationUser(final String userName) {
        return queryResultsCache.execute(new Callable<ApplicationUser>() {
            @Override
            public ApplicationUser call() throws Exception {
                return findApplicationUserNoCache(userName);
            }
        }, TenantedAuthorizationFacetDefault.class, "findApplicationUser", userName);
    }
580221
@Override
    public void addPreference(final U u, final I i, final Double d) {
        // update direct map
        Map<I, Double> userPreferences = userItemPreferences.get(u);
        if (userPreferences == null) {
            userPreferences = new HashMap<>();
            userItemPreferences.put(u, userPreferences);
        }
        Double preference = userPreferences.get(i);
        if (preference == null) {
            preference = 0.0;
        } else if (ignoreDuplicatePreferences) {
            // if duplicate preferences should be ignored, then we do not take into account the new value
            preference = null;
        }
        if (preference != null) {
            preference += d;
            userPreferences.put(i, preference);
        }
        // update items
        items.add(i);
    }
987700
public StorageBuilder setUserCredentialsRepository( UserCredentialsRepository userCredentialsRepo, String userId )
    {
        this.userCredentialsRepo = userCredentialsRepo;
        this.userId = userId;

        return this;
    }
1042526
public void updateUser(String userDBID, User user) throws ProvisioningApiException {
		try {
			ApiSuccessResponse resp = usersApi.updateUser(userDBID, new UpdateUserData().data(Converters.convertUserToUpdateUserDataData(user)));

			if (!resp.getStatus().getCode().equals(0)) {
				throw new ProvisioningApiException("Error updating user. Code: " + resp.getStatus().getCode());
			}
        } catch(ApiException e) {
        	throw new ProvisioningApiException("Error updating user", e);
        }
	}
1310640
def user_update(object_id, input_params={}, always_retry=False, **kwargs):
    
    return DXHTTPRequest('/%s/update' % object_id, input_params, always_retry=always_retry, **kwargs)
808601
public function Preferences($UserReference = '', $Username = '', $UserID = '') {
      $this->AddJsFile('profile.js');
      $Session = Gdn::Session();
      $this->Permission('Garden.SignIn.Allow');
      
      // Get user data
      $this->GetUserInfo($UserReference, $Username, $UserID, TRUE);
      $UserPrefs = Gdn_Format::Unserialize($this->User->Preferences);
      if ($this->User->UserID != $Session->UserID)
         $this->Permission('Garden.Users.Edit');
      
      if (!is_array($UserPrefs))
         $UserPrefs = array();
      $MetaPrefs = UserModel::GetMeta($this->User->UserID, 'Preferences.%', 'Preferences.');

      // Define the preferences to be managed
      $this->Preferences = array(
         'Notifications' => array(
            'Email.WallComment' => T('Notify me when people write on my wall.'),
            'Email.ActivityComment' => T('Notify me when people reply to my wall comments.'),
            'Popup.WallComment' => T('Notify me when people write on my wall.'),
            'Popup.ActivityComment' => T('Notify me when people reply to my wall comments.')
         )
      );
      
      // Allow email notification of applicants (if they have permission & are using approval registration)
      if (CheckPermission('Garden.Users.Approve') && C('Garden.Registration.Method') == 'Approval')
         $this->Preferences['Notifications']['Email.Applicant'] = array(T('NotifyApplicant', 'Notify me when anyone applies for membership.'), 'Meta');
      
      $this->FireEvent('AfterPreferencesDefined');
      
      // Loop through the preferences looking for duplicates, and merge into a single row
      $this->PreferenceGroups = array();
      $this->PreferenceTypes = array();
      foreach ($this->Preferences as $PreferenceGroup => $Preferences) {
         $this->PreferenceGroups[$PreferenceGroup] = array();
         $this->PreferenceTypes[$PreferenceGroup] = array();
         foreach ($Preferences as $Name => $Description) {
            $Location = 'Prefs';
            if (is_array($Description))
               list($Description, $Location) = $Description;

            $NameParts = explode('.', $Name);
            $PrefType = GetValue('0', $NameParts);
            $SubName = GetValue('1', $NameParts);
            if ($SubName != FALSE) {
               // Save an array of all the different types for this group
               if (!in_array($PrefType, $this->PreferenceTypes[$PreferenceGroup]))
                  $this->PreferenceTypes[$PreferenceGroup][] = $PrefType;
               
               // Store all the different subnames for the group   
               if (!array_key_exists($SubName, $this->PreferenceGroups[$PreferenceGroup])) {
                  $this->PreferenceGroups[$PreferenceGroup][$SubName] = array($Name);
               } else {
                  $this->PreferenceGroups[$PreferenceGroup][$SubName][] = $Name;
               }
            } else {
               $this->PreferenceGroups[$PreferenceGroup][$Name] = array($Name);
            }
         }
      }

      // Loop the preferences, setting defaults from the configuration.
      $CurrentPrefs = array();
      foreach ($this->Preferences as $PrefGroup => $Prefs) {
         foreach ($Prefs as $Pref => $Desc) {
            $Location = 'Prefs';
            if (is_array($Desc))
               list($Desc, $Location) = $Desc;

            if ($Location == 'Meta')
               $CurrentPrefs[$Pref] = GetValue($Pref, $MetaPrefs, FALSE);
            else
               $CurrentPrefs[$Pref] = GetValue($Pref, $UserPrefs, C('Preferences.'.$Pref, '0'));
            
            unset($MetaPrefs[$Pref]);
         }
      }
      $CurrentPrefs = array_merge($CurrentPrefs, $MetaPrefs);
      $CurrentPrefs = array_map('intval', $CurrentPrefs);
      $this->SetData('Preferences', $CurrentPrefs);
      
      if (UserModel::NoEmail()) {
         $this->PreferenceGroups = self::_RemoveEmailPreferences($this->PreferenceGroups);
         $this->PreferenceTypes = self::_RemoveEmailPreferences($this->PreferenceTypes);
         $this->SetData('NoEmail', TRUE);
      }
      
      $this->SetData('PreferenceGroups', $this->PreferenceGroups);
      $this->SetData('PreferenceTypes', $this->PreferenceTypes);
      $this->SetData('PreferenceList', $this->Preferences);
      
      if ($this->Form->AuthenticatedPostBack()) {
         // Get, assign, and save the preferences.
         $NewMetaPrefs = array();
         foreach ($this->Preferences as $PrefGroup => $Prefs) {
            foreach ($Prefs as $Pref => $Desc) {
               $Location = 'Prefs';
               if (is_array($Desc))
                  list($Desc, $Location) = $Desc;

               $Value = $this->Form->GetValue($Pref, NULL);
               if (is_null($Value)) continue;

               if ($Location == 'Meta') {
                  $NewMetaPrefs[$Pref] = $Value ? $Value : NULL;
                  if ($Value)
                     $UserPrefs[$Pref] = $Value; // dup for notifications code.
               } else {
                  if (!$CurrentPrefs[$Pref] && !$Value)
                     unset($UserPrefs[$Pref]); // save some space
                  else
                     $UserPrefs[$Pref] = $Value;
               }
            }
         }
         
         $this->UserModel->SavePreference($this->User->UserID, $UserPrefs);
         UserModel::SetMeta($this->User->UserID, $NewMetaPrefs, 'Preferences.');
         
         $this->SetData('Preferences', array_merge($this->Data('Preferences', array()), $UserPrefs, $NewMetaPrefs));
         
         if (count($this->Form->Errors() == 0))
            $this->InformMessage(Sprite('Check', 'InformSprite').T('Your preferences have been saved.'), 'Dismissable AutoDismiss HasSprite');
      } else {
         $this->Form->SetData($CurrentPrefs);
      }
      
      $this->Title(T('Notification Preferences'));
      $this->_SetBreadcrumbs($this->Data('Title'), $this->CanonicalUrl());
      $this->Render();
   }
328337
public static void saveUserPreferences(IProject project, final UserPreferences userPrefs) throws CoreException {

        FileOutput userPrefsOutput = new FileOutput() {
            @Override
            public void writeFile(OutputStream os) throws IOException {
                userPrefs.write(os);
            }

            @Override
            public String getTaskDescription() {
                return "writing user preferences";
            }
        };

        if (project != null) {
            // Make the new user preferences current for the project
            project.setSessionProperty(SESSION_PROPERTY_USERPREFS, userPrefs);
            IFile userPrefsFile = getUserPreferencesFile(project);
            ensureReadWrite(userPrefsFile);
            IO.writeFile(userPrefsFile, userPrefsOutput, null);
            if (project.getFile(DEPRECATED_PREFS_PATH).equals(userPrefsFile)) {
                String message = "Found old style FindBugs preferences for project '" + project.getName()
                        + "'. This preferences are not at the default location: '" + DEFAULT_PREFS_PATH + "'." + " Please move '"
                        + DEPRECATED_PREFS_PATH + "' to '" + DEFAULT_PREFS_PATH + "'.";
                getDefault().logWarning(message);
            }
        } else {
            // write the workspace preferences to the eclipse preference store
            ByteArrayOutputStream bos = new ByteArrayOutputStream(10000);
            try {
                userPrefs.write(bos);
            } catch (IOException e) {
                getDefault().logException(e, "Failed to write user preferences");
                return;
            }
            Properties props = new Properties();
            try {
                props.load(new ByteArrayInputStream(bos.toByteArray()));
            } catch (IOException e) {
                getDefault().logException(e, "Failed to save user preferences");
                return;
            }
            IPreferenceStore store = getDefault().getPreferenceStore();
            // Reset any existing custom group entries
            resetStore(store, UserPreferences.KEY_PLUGIN);
            resetStore(store, UserPreferences.KEY_EXCLUDE_BUGS);
            resetStore(store, UserPreferences.KEY_EXCLUDE_FILTER);
            resetStore(store, UserPreferences.KEY_INCLUDE_FILTER);
            for (Entry<Object, Object> entry : props.entrySet()) {
                store.putValue((String) entry.getKey(), (String) entry.getValue());
            }
            if(store instanceof IPersistentPreferenceStore){
                IPersistentPreferenceStore store2 = (IPersistentPreferenceStore) store;
                try {
                    store2.save();
                } catch (IOException e) {
                    getDefault().logException(e, "Failed to save user preferences");
                }
            }
        }
    }
156241
public static base_response update(nitro_service client, appfwsettings resource) throws Exception {
		appfwsettings updateresource = new appfwsettings();
		updateresource.defaultprofile = resource.defaultprofile;
		updateresource.undefaction = resource.undefaction;
		updateresource.sessiontimeout = resource.sessiontimeout;
		updateresource.learnratelimit = resource.learnratelimit;
		updateresource.sessionlifetime = resource.sessionlifetime;
		updateresource.sessioncookiename = resource.sessioncookiename;
		updateresource.clientiploggingheader = resource.clientiploggingheader;
		updateresource.importsizelimit = resource.importsizelimit;
		updateresource.signatureautoupdate = resource.signatureautoupdate;
		updateresource.signatureurl = resource.signatureurl;
		updateresource.cookiepostencryptprefix = resource.cookiepostencryptprefix;
		updateresource.logmalformedreq = resource.logmalformedreq;
		updateresource.ceflogging = resource.ceflogging;
		updateresource.entitydecoding = resource.entitydecoding;
		updateresource.useconfigurablesecretkey = resource.useconfigurablesecretkey;
		return updateresource.update_resource(client);
	}
1365378
def setAsApplication(myappid):
    

    if os.name == 'nt':
        import ctypes
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)
639506
@SneakyThrows
    protected boolean updateUserResource(final UserResource user, final Principal p, final Credential credential) {
        this.mapper.map(user, p, credential);
        return endpoint.update(user) != null;
    }
1120860
public UserEntity createNewUser(String userId) {
    checkAuthorization(Permissions.CREATE, Resources.USER, null);
    return new UserEntity(userId);
  }
1254660
public static base_response update(nitro_service client, filterhtmlinjectionvariable resource) throws Exception {
		filterhtmlinjectionvariable updateresource = new filterhtmlinjectionvariable();
		updateresource.variable = resource.variable;
		updateresource.value = resource.value;
		return updateresource.update_resource(client);
	}
275140
public Observable<ServiceResponse<UserInner>> updatePublishingUserWithServiceResponseAsync(UserInner userDetails) {
        if (userDetails == null) {
            throw new IllegalArgumentException("Parameter userDetails is required and cannot be null.");
        }
        if (this.apiVersion() == null) {
            throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null.");
        }
        Validator.validate(userDetails);
        return service.updatePublishingUser(userDetails, this.apiVersion(), this.acceptLanguage(), this.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<UserInner>>>() {
                @Override
                public Observable<ServiceResponse<UserInner>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<UserInner> clientResponse = updatePublishingUserDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }
369259
public function updateUser($userId, Request $request)
    {
        $user = $this->userService->loadUser($userId);

        $updateStruct = $this->inputDispatcher->parse(
            new Message(
                array(
                    'Content-Type' => $request->headers->get('Content-Type'),
                    // @todo Needs refactoring! Temporary solution so parser has access to URL
                    'Url' => $request->getPathInfo(),
                ),
                $request->getContent()
            )
        );

        if ($updateStruct->sectionId !== null) {
            $section = $this->sectionService->loadSection($updateStruct->sectionId);
            $this->sectionService->assignSection(
                $user->getVersionInfo()->getContentInfo(),
                $section
            );
        }

        $updatedUser = $this->userService->updateUser($user, $updateStruct->userUpdateStruct);
        $updatedContentInfo = $updatedUser->getVersionInfo()->getContentInfo();
        $mainLocation = $this->locationService->loadLocation($updatedContentInfo->mainLocationId);
        $contentType = $this->contentTypeService->loadContentType($updatedContentInfo->contentTypeId);

        return new Values\RestUser(
            $updatedUser,
            $contentType,
            $updatedContentInfo,
            $mainLocation,
            $this->contentService->loadRelations($updatedUser->getVersionInfo())
        );
    }