// Update the fields of the device profile
// to - the device profile that was already in Mongo (whose fields we're updating)
// from - the device profile that was passed in with the request
422264
func updateDeviceProfileFields(from models.DeviceProfile, to *models.DeviceProfile, w http.ResponseWriter) error {
	if from.Description != "" {
		to.Description = from.Description
	}
	if from.Labels != nil {
		to.Labels = from.Labels
	}
	if from.Manufacturer != "" {
		to.Manufacturer = from.Manufacturer
	}
	if from.Model != "" {
		to.Model = from.Model
	}
	if from.Origin != 0 {
		to.Origin = from.Origin
	}
	if from.Name != "" {
		to.Name = from.Name
		// Names must be unique for each device profile
		if err := checkDuplicateProfileNames(*to, w); err != nil {
			return err
		}
	}
	if from.DeviceResources != nil {
		to.DeviceResources = from.DeviceResources
	}
	if from.DeviceCommands != nil {
		to.DeviceCommands = from.DeviceCommands
	}
	if from.CoreCommands != nil {
		// Check for duplicates by command name
		if err := checkDuplicateCommands(from, w); err != nil {
			return err
		}

		// taking lazy approach to commands - remove them all and add them
		// all back in. TODO - someday make this a two phase commit so
		// commands don't get wiped out before profile

		// Delete the old commands
		if err := deleteCommands(*to, w); err != nil {
			return err
		}

		to.CoreCommands = from.CoreCommands

		// Add the new commands
		if err := addCommands(to, w); err != nil {
			return err
		}
	}

	return nil
}
988566
func (c *UsersController) Update(ctx *app.UpdateUsersContext) error {

	loggedInIdentity, err := c.app.UserService().LoadContextIdentityIfNotBanned(ctx)
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, err)
	}

	var isEmailVerificationNeeded bool

	var identity *accountrepo.Identity
	var user *accountrepo.User

	err = transaction.Transactional(c.app, func(tr transaction.TransactionalResources) error {
		identity, err = tr.Identities().Load(ctx, loggedInIdentity.ID)
		if err != nil {
			return errors.NewUnauthorizedError(fmt.Sprintf("auth token contains id %s of unknown Identity\n", loggedInIdentity.ID))
		}

		if identity.UserID.Valid {
			user, err = tr.Users().Load(ctx.Context, identity.UserID.UUID)
			if err != nil {
				return errs.Wrap(err, fmt.Sprintf("Can't load user with id %s", identity.UserID.UUID))
			}
		}

		updatedEmail := ctx.Payload.Data.Attributes.Email
		if updatedEmail != nil && *updatedEmail != user.Email {
			isValid := isEmailValid(*updatedEmail)
			if !isValid {
				return errors.NewBadParameterError("email", *updatedEmail).Expected("valid email")
			}
			isUnique, err := isEmailUnique(ctx, tr, *updatedEmail, *user)
			if err != nil {
				return errs.Wrap(err, fmt.Sprintf("error updating identitity with id %s and user with id %s", identity.ID, identity.UserID.UUID))
			}
			if !isUnique {
				// TODO: Add errors.NewConflictError(..)
				return errs.Wrap(errors.NewBadParameterError("email", *updatedEmail).Expected("unique email"), fmt.Sprintf("email : %s is already in use", *updatedEmail))
			}
			user.Email = *updatedEmail

			isEmailVerificationNeeded = true
			user.EmailVerified = false
		}

		updatedUserName := ctx.Payload.Data.Attributes.Username
		if updatedUserName != nil && *updatedUserName != identity.Username {
			isValid := isUsernameValid(*updatedUserName)
			if !isValid {
				return errs.Wrap(errors.NewBadParameterError("username", "required"), fmt.Sprintf("invalid value assigned to username for identity with id %s and user with id %s", identity.ID, identity.UserID.UUID))
			}
			if identity.RegistrationCompleted {
				return errors.NewForbiddenError(fmt.Sprintf("username cannot be updated more than once for identity id %s ", loggedInIdentity.ID))
			}
			isUnique, err := isUsernameUnique(ctx, tr, *updatedUserName, *identity)
			if err != nil {
				return errs.Wrap(err, fmt.Sprintf("error updating identitity with id %s and user with id %s", identity.ID, identity.UserID.UUID))
			}
			if !isUnique {
				// TODO : Add errors.NewConflictError(..)
				return errs.Wrap(errors.NewBadParameterError("username", *updatedUserName).Expected("unique username"), fmt.Sprintf("username : %s is already in use", *updatedUserName))
			}
			identity.Username = *updatedUserName
		}

		updatedRegistratedCompleted := ctx.Payload.Data.Attributes.RegistrationCompleted
		if updatedRegistratedCompleted != nil {
			if !*updatedRegistratedCompleted {
				log.Error(ctx, map[string]interface{}{
					"registration_completed": *updatedRegistratedCompleted,
					"user_id":                identity.UserID.UUID,
					"identity_id":            identity.ID,
				}, "invalid parameter assignment")

				return errs.Wrap(errors.NewBadParameterError("registration_completed", *updatedRegistratedCompleted).Expected("should be true or nil"), fmt.Sprintf("invalid value assigned to registration_completed for identity with id %s and user with id %s", identity.ID, identity.UserID.UUID))
			}
			identity.RegistrationCompleted = true
		}

		updatedBio := ctx.Payload.Data.Attributes.Bio
		if updatedBio != nil && *updatedBio != user.Bio {
			user.Bio = *updatedBio
		}
		updatedFullName := ctx.Payload.Data.Attributes.FullName
		if updatedFullName != nil && *updatedFullName != user.FullName {
			*updatedFullName = standardizeSpaces(*updatedFullName)
			user.FullName = *updatedFullName
		}
		updatedImageURL := ctx.Payload.Data.Attributes.ImageURL
		if updatedImageURL != nil && *updatedImageURL != user.ImageURL {
			user.ImageURL = *updatedImageURL

		}
		updateURL := ctx.Payload.Data.Attributes.URL
		if updateURL != nil && *updateURL != user.URL {
			user.URL = *updateURL
		}

		updatedEmailPrivate := ctx.Payload.Data.Attributes.EmailPrivate
		if updatedEmailPrivate != nil {
			user.EmailPrivate = *updatedEmailPrivate
		}

		updatedCompany := ctx.Payload.Data.Attributes.Company
		if updatedCompany != nil && *updatedCompany != user.Company {
			user.Company = *updatedCompany
		}

		updatedContextInformation := ctx.Payload.Data.Attributes.ContextInformation
		if updatedContextInformation != nil {
			// if user.ContextInformation , we get to PATCH the ContextInformation field,
			// instead of over-writing it altogether. Note: The PATCH-ing is only for the
			// 1st level of JSON.
			if user.ContextInformation == nil {
				user.ContextInformation = make(map[string]interface{})
			}
			for fieldName, fieldValue := range updatedContextInformation {
				// Save it as is, for short-term.
				user.ContextInformation[fieldName] = fieldValue
			}
		}

		err := c.updateFeatureLevel(ctx, user, ctx.Payload.Data.Attributes.FeatureLevel)
		if err != nil {
			return err
		}

		err = tr.Users().Save(ctx, user)
		if err != nil {
			return err
		}

		err = tr.Identities().Save(ctx, identity)
		if err != nil {
			return err
		}

		identity.User = *user

		return nil
	})

	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"identity_id": loggedInIdentity.ID.String(),
			"err":         err,
		}, "failed to update user/identity")
		return jsonapi.JSONErrorResponse(ctx, err)
	}

	if isEmailVerificationNeeded {
		_, err = c.EmailVerificationService.SendVerificationCode(ctx, ctx.RequestData, *identity)
		if err != nil {
			log.Error(ctx, map[string]interface{}{
				"identity_id": loggedInIdentity.ID.String(),
				"err":         err,
				"username":    identity.Username,
				"email":       user.Email,
			}, "failed to send verification email for update on email")
		}
	}

	err = c.updateWITUser(ctx, identity.ID.String())
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"user_id":     user.ID,
			"identity_id": identity.ID,
			"username":    identity.Username,
			"err":         err,
		}, "failed to update WIT user/identity")
		// Let's not disrupt the response if there was an issue with updating WIT.
	}

	return ctx.OK(ConvertToAppUser(ctx.RequestData, user, identity, true))
}
962041
func (s *persistentStorage) Update(c context.Context, identity *ProjectIdentity) (*ProjectIdentity, error) {
	logging.Debugf(c, "update project scoped identity %v", identity)
	tmp, err := s.lookup(c, identity)
	switch {
	case err == nil && *tmp == *identity: // Doesn't need update
		return identity, nil
	case err != nil && err != ErrNotFound: // Lookup error to propagate
		return nil, err
	}

	if err := ds.Put(c, identity); err != nil {
		return nil, err
	}
	return identity, nil
}
1201221
func (ac *APIController) AppProfileUpdate(oldProf, newProf *contivModel.AppProfile) error {
	log.Infof("Received AppProfileUpdate: %+v, newProf: %+v", oldProf, newProf)

	// handle any epg addition
	for _, epg := range newProf.EndpointGroups {
		epgKey := newProf.TenantName + ":" + epg
		log.Infof("Add %s to %s", epgKey, newProf.AppProfileName)
		epgObj := contivModel.FindEndpointGroup(epgKey)
		if epgObj == nil {
			return core.Errorf("EndpointGroup %s not found", epgKey)
		}
		modeldb.AddLinkSet(&newProf.LinkSets.EndpointGroups, epgObj)

		// workaround for objdb update problem
		modeldb.AddLinkSet(&oldProf.LinkSets.EndpointGroups, epgObj)

		modeldb.AddLink(&epgObj.Links.AppProfile, newProf)
		err := epgObj.Write()
		if err != nil {
			log.Errorf("Error updating epg state(%+v). Err: %v", epgObj, err)
			return err
		}
	}

	// handle any epg removal
	for _, epg := range oldProf.EndpointGroups {
		if !stringInSlice(epg, newProf.EndpointGroups) {
			epgKey := newProf.TenantName + ":" + epg
			log.Infof("Remove %s from %s", epgKey, newProf.AppProfileName)
			epgObj := contivModel.FindEndpointGroup(epgKey)
			if epgObj == nil {
				return core.Errorf("EndpointGroup %s not found", epgKey)
			}
			modeldb.RemoveLink(&epgObj.Links.AppProfile, oldProf)
			err := epgObj.Write()
			if err != nil {
				log.Errorf("Error updating epg state(%+v). Err: %v",
					epgObj, err)
				return err
			}

			// workaround for objdb update problem
			modeldb.RemoveLinkSet(&oldProf.LinkSets.EndpointGroups, epgObj)
		}
	}

	// workaround for objdb update problem -- should fix model
	oldProf.EndpointGroups = newProf.EndpointGroups

	// update the app nw
	DeleteAppNw(oldProf)
	lErr := CreateAppNw(oldProf)
	return lErr
}
724896
func (b *batchNodeUpdates) batchDevicesUpdates(f devicemanager.UpdateNodeDevicesFn) error {
	b.devicesMu.Lock()
	defer b.devicesMu.Unlock()
	if b.devicesBatched {
		return fmt.Errorf("devices updates already batched")
	}

	b.devicesBatched = true
	f(b.devices)
	return nil
}
939617
func (p *deviceFolderDownloadState) Update(updates []protocol.FileDownloadProgressUpdate) {
	p.mut.Lock()
	defer p.mut.Unlock()

	for _, update := range updates {
		local, ok := p.files[update.Name]
		if update.UpdateType == protocol.UpdateTypeForget && ok && local.version.Equal(update.Version) {
			delete(p.files, update.Name)
		} else if update.UpdateType == protocol.UpdateTypeAppend {
			if !ok {
				local = deviceFolderFileDownloadState{
					blockIndexes: update.BlockIndexes,
					version:      update.Version,
				}
			} else if !local.version.Equal(update.Version) {
				local.blockIndexes = append(local.blockIndexes[:0], update.BlockIndexes...)
				local.version = update.Version
			} else {
				local.blockIndexes = append(local.blockIndexes, update.BlockIndexes...)
			}
			p.files[update.Name] = local
		}
	}
}
615752
func (a *Client) UpdateOne(params *UpdateOneParams, authInfo runtime.ClientAuthInfoWriter) (*UpdateOneOK, error) {
	// TODO: Validate the params before sending
	if params == nil {
		params = NewUpdateOneParams()
	}

	result, err := a.transport.Submit(&runtime.ClientOperation{
		ID:                 "updateOne",
		Method:             "PUT",
		PathPattern:        "/{id}",
		ProducesMediaTypes: []string{"application/io.swagger.examples.todo-list.v1+json"},
		ConsumesMediaTypes: []string{"application/io.swagger.examples.todo-list.v1+json"},
		Schemes:            []string{"http", "https"},
		Params:             params,
		Reader:             &UpdateOneReader{formats: a.formats},
		AuthInfo:           authInfo,
		Context:            params.Context,
		Client:             params.HTTPClient,
	})
	if err != nil {
		return nil, err
	}
	return result.(*UpdateOneOK), nil

}
1197885
func (d *device) update() error {
	if d.advParam != nil {
		if err := d.hci.SendCmdWithAdvOff(d.advParam); err != nil {
			return err
		}
		d.advParam = nil
	}
	if d.scanResp != nil {
		if err := d.hci.SendCmdWithAdvOff(d.scanResp); err != nil {
			return err
		}
		d.scanResp = nil
	}
	if d.advData != nil {
		if err := d.hci.SendCmdWithAdvOff(d.advData); err != nil {
			return err
		}
		d.advData = nil
	}
	return nil
}
3739
func (mc MongoClient) getDeviceProfiles(q bson.M) ([]contract.DeviceProfile, error) {
	s := mc.session.Copy()
	defer s.Close()

	var dps []models.DeviceProfile
	err := s.DB(mc.database.Name).C(db.DeviceProfile).Find(q).Sort("queryts").All(&dps)
	if err != nil {
		return []contract.DeviceProfile{}, errorMap(err)
	}

	cdps := make([]contract.DeviceProfile, 0)
	for _, dp := range dps {
		c, err := dp.ToContract(mc)
		if err != nil {
			return []contract.DeviceProfile{}, err
		}
		cdps = append(cdps, c)
	}
	return cdps, nil
}
810048
func (c *UsersClient) Update(ctx context.Context, id ID, updateUser *UpdateUser) (*User, error) {
	idBytes, err := id.MarshalText()
	if err != nil {
		return nil, err
	}

	p := fmt.Sprintf("/users/%s", string(idBytes))

	req, err := c.backend.NewRequest(http.MethodPatch, p, nil, updateUser)
	if err != nil {
		return nil, err
	}

	var resp User
	_, err = c.backend.Do(ctx, req, &resp, func(code int) error {
		return &Error{}
	})
	if err != nil {
		return nil, err
	}

	return &resp, nil
}
985734
func updateDeviceReportFields(from models.DeviceReport, to *models.DeviceReport, w http.ResponseWriter) error {
	if from.Device != "" {
		to.Device = from.Device
		if err := validateDevice(to.Device, w); err != nil {
			return err
		}
	}
	if from.Action != "" {
		to.Action = from.Action
	}
	if from.Expected != nil {
		to.Expected = from.Expected
		// TODO: Someday find a way to check the value descriptors
	}
	if from.Name != "" {
		to.Name = from.Name
	}
	if from.Origin != 0 {
		to.Origin = from.Origin
	}

	return nil
}
804820
func (n *NetworkServerAPI) UpdateGatewayProfile(ctx context.Context, req *ns.UpdateGatewayProfileRequest) (*empty.Empty, error) {
	if req.GatewayProfile == nil {
		return nil, grpc.Errorf(codes.InvalidArgument, "gateway_profile must not be nil")
	}

	var gpID uuid.UUID
	copy(gpID[:], req.GatewayProfile.Id)

	gc, err := storage.GetGatewayProfile(storage.DB(), gpID)
	if err != nil {
		return nil, errToRPCError(err)
	}

	gc.Channels = []int64{}
	for _, c := range req.GatewayProfile.Channels {
		gc.Channels = append(gc.Channels, int64(c))
	}

	gc.ExtraChannels = []storage.ExtraChannel{}
	for _, ec := range req.GatewayProfile.ExtraChannels {
		c := storage.ExtraChannel{
			Frequency: int(ec.Frequency),
			Bandwidth: int(ec.Bandwidth),
			Bitrate:   int(ec.Bitrate),
		}

		switch ec.Modulation {
		case common.Modulation_FSK:
			c.Modulation = storage.ModulationFSK
		default:
			c.Modulation = storage.ModulationLoRa
		}

		for _, sf := range ec.SpreadingFactors {
			c.SpreadingFactors = append(c.SpreadingFactors, int64(sf))
		}

		gc.ExtraChannels = append(gc.ExtraChannels, c)
	}

	err = storage.Transaction(func(tx sqlx.Ext) error {
		return storage.UpdateGatewayProfile(tx, &gc)
	})
	if err != nil {
		return nil, errToRPCError(err)
	}

	return &empty.Empty{}, nil
}
1007150
func (b *UpdateService) Fields(fields ...string) *UpdateService {
	b.fields = make([]string, 0, len(fields))
	b.fields = append(b.fields, fields...)
	return b
}
434136
func (m *Manager) Update(see *See) error {
	return m.collection.UpdateId(see.ID, see)
}
1039811
func (m *podManager) update(req *cniserver.PodRequest) (uint32, error) {
	vnid, err := m.policy.GetVNID(req.PodNamespace)
	if err != nil {
		return 0, err
	}

	if err := m.ovs.UpdatePod(req.SandboxID, vnid); err != nil {
		return 0, err
	}
	return vnid, nil
}
1225206
func (c *FakePodPresets) Update(podPreset *v1alpha1.PodPreset) (result *v1alpha1.PodPreset, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewUpdateAction(podpresetsResource, c.ns, podPreset), &v1alpha1.PodPreset{})

	if obj == nil {
		return nil, err
	}
	return obj.(*v1alpha1.PodPreset), err
}
1201670
func (c *Client) UpdateRecord(domainID string, recordID string, cr map[string]interface{}) (string, error) {

	current, err := c.ReadRecord(domainID, recordID)
	if err != nil {
		return "", err
	}

	err = mergo.Map(current, cr)
	if err != nil {
		return "", err
	}

	buf := bytes.NewBuffer(nil)
	enc := json.NewEncoder(buf)
	if err := enc.Encode(current); err != nil {
		return "", err
	}

	path := update.endpoint(domainID, recordID)
	req, err := c.NewRequest("PUT", path, buf, "")
	if err != nil {
		return "", err
	}

	_, err = checkResp(c.HTTP.Do(req))
	if err != nil {
		return "", fmt.Errorf("Error updating record: %s", err)
	}

	// The request was successful
	return recordID, nil
}