<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def set_user_role(new_user_id, role_id, **kwargs):
 """ Apply `role_id` to `new_user_id` Note this function returns the `Role` instance associated with `role_id` """

    #check_perm(kwargs.get('user_id'), 'edit_role')
    try:
        _get_user(new_user_id)
        role_i = _get_role(role_id)
        roleuser_i = RoleUser(user_id=new_user_id, role_id=role_id)
        role_i.roleusers.append(roleuser_i)
        db.DBSession.flush()
    except Exception as e: # Will occur if the foreign keys do not exist
        log.exception(e)
        raise ResourceNotFoundError("User or Role does not exist")

    return role_i