<commit_before>/*
 * QueueCommand.cpp
 *
 *  Created on: 22/05/2010
 *      Author: victor
 */

#include "QueueCommand.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/objects/player/PlayerObject.h"
#include "server/zone/objects/player/FactionStatus.h"
#include "server/zone/objects/tangible/weapon/WeaponObject.h"
#include "server/zone/managers/combat/CombatManager.h"

QueueCommand::QueueCommand(const String& skillname, ZoneProcessServer* serv) : Logger() {
	server = serv;

	name = skillname;
	nameCRC = skillname.hashCode();

	maxRangeToTarget = 0;

	commandGroup = 0;

	stateMask = 0;
	targetType = 0;
	disabled = false;
	addToQueue = false;
	admin = false;

	defaultTime = 0.f;

	cooldown = 0;

	defaultPriority = NORMAL;

	setLogging(true);
	setGlobalLogging(true);
	setLoggingName("QueueCommand " + skillname);
}

/*
 * Sets the invalid locomotion for this command.
 * Parses the string from LUA's. Format: "4,12,13,"
 */
void QueueCommand::setInvalidLocomotions(const String& lStr) {
	StringTokenizer tokenizer(lStr);
	tokenizer.setDelimeter(",");

	String token = "";
	while (tokenizer.hasMoreTokens()) {
		tokenizer.getStringToken(token);

		if(!token.isEmpty())
			invalidLocomotion.add(Integer::valueOf(token));
	}
}

/*
 * Checks each invalid locomotion with the player's current locomotion
 */
bool QueueCommand::checkInvalidLocomotions(CreatureObject* creature) const {
	for (int i = 0; i < invalidLocomotion.size(); ++i) {
		if (invalidLocomotion.get(i) == creature->getLocomotion())
			return false;
	}

	return true;
}

void QueueCommand::onStateFail(CreatureObject* creature, uint32 actioncntr) const {
	if (!addToQueue)
		return;

	uint64 states = stateMask & creature->getStateBitmask();

	uint64 state = 1;
	int num = 0;

	while (num < 34) {
		if (states & state) {

			creature->clearQueueAction(actioncntr, 0, 5, num);
			return;

		}

		state *= 2;
		++num;
	}

	creature->error("unknown invalid state in onStateFail");
}

void QueueCommand::onLocomotionFail(CreatureObject* creature, uint32 actioncntr) const {
	if (!checkInvalidLocomotions(creature))
		creature->clearQueueAction(actioncntr, 0, 1, creature->getLocomotion());
}

/*
 * Unsuccessful command completion alerts the player of the invalid state
 */
void QueueCommand::onFail(uint32 actioncntr, CreatureObject* creature, uint32 errorNumber) const {
	StringIdChatParameter prm;
	switch (errorNumber) {
	case INVALIDSYNTAX:
		creature->sendSystemMessage(getSyntax());
		if (addToQueue)
			creature->clearQueueAction(actioncntr);
		break;
	case INVALIDSTATE:
		onStateFail(creature, actioncntr);
		break;
	case INVALIDLOCOMOTION:
		onLocomotionFail(creature, actioncntr);
		break;
	case INVALIDTARGET:
		if (addToQueue)
			creature->clearQueueAction(actioncntr, 0, 3, 0);
		break;
	case INVALIDWEAPON: // this only gets returned from combat commands
		switch (creature->getWeapon()->getAttackType()) {
		case WeaponObject::RANGEDATTACK:
			creature->sendSystemMessage("@cbt_spam:no_attack_ranged_single");
			break;
		case WeaponObject::MELEEATTACK:
			creature->sendSystemMessage("@cbt_spam:no_attack_melee_single");
			break;
		default:
			creature->sendSystemMessage("@cbt_spam:no_attack_wrong_weapon"); // Can't be done with this weapon
			break;
		}

		if (addToQueue)
			creature->clearQueueAction(actioncntr);
		break;

	case TOOFAR:
		if (addToQueue)
			creature->clearQueueAction(actioncntr, 0, 4, 0);
		break;

	case NOJEDIARMOR:
		creature->sendSystemMessage("@jedi_spam:not_with_armor"); // You cannot use Force powers or lightsaber abilities while wearing armor.
		if (addToQueue)
			creature->clearQueueAction(actioncntr);

		break;

	case NOPRONE:
		if (addToQueue)
			creature->clearQueueAction(actioncntr, 0, 1, 7);

		break;

	case NOKNEELING:
		if (addToQueue)
			creature->clearQueueAction(actioncntr, 0, 1, 4);

		break;
	case INSUFFICIENTPERMISSION:
		creature->sendSystemMessage("@error_message:insufficient_permissions"); //You do not have sufficient permissions to perform the requested action.

		if (addToQueue)
			creature->clearQueueAction(actioncntr);
		break;
	case TOOCLOSE:
		prm.setStringId("combat_effects", "prone_ranged_too_close");
		creature->sendSystemMessage(prm);

		if (addToQueue)
			creature->clearQueueAction(actioncntr);
		break;
	default:
		if (addToQueue)
			creature->clearQueueAction(actioncntr);
		break;
	}
}

void QueueCommand::onComplete(uint32 actioncntr, CreatureObject* player, float commandDuration) const {
	if (!player->isPlayerCreature())
		return;

	if (addToQueue)
		player->clearQueueAction(actioncntr, commandDuration);
}

int QueueCommand::doCommonMedicalCommandChecks(CreatureObject* creature) const {
	if (!checkStateMask(creature))
		return INVALIDSTATE;

	if (!checkInvalidLocomotions(creature))
		return INVALIDLOCOMOTION;

	if (creature->hasAttackDelay() || !creature->checkPostureChangeDelay()) // no message associated with this
		return GENERALERROR;

	if (creature->isProne() || creature->isMeditating() || creature->isSwimming()) {
		creature->sendSystemMessage("@error_message:wrong_state"); //You cannot complete that action while in your current state.
		return GENERALERROR;
	}

	if (creature->isRidingMount()) {
		creature->sendSystemMessage("@error_message:survey_on_mount"); //You cannot perform that action while mounted on a creature or driving a vehicle.
		return GENERALERROR;
	}

	return SUCCESS;
}

void QueueCommand::checkForTef(CreatureObject* creature, CreatureObject* target) const {
	if (!creature->isPlayerCreature() || creature == target)
		return;

	PlayerObject* ghost = creature->getPlayerObject().get();
	if (ghost == NULL)
		return;

	if (target->isPlayerCreature()) {
		PlayerObject* targetGhost = target->getPlayerObject().get();

		if (!CombatManager::instance()->areInDuel(creature, target)
				&& targetGhost != NULL && targetGhost->getFactionStatus() == FactionStatus::OVERT) {
			ghost->updateLastPvpCombatActionTimestamp();
		}
	} else if (target->isPet()) {
		ManagedReference<CreatureObject*> owner = target->getLinkedCreature().get();

		if (owner != NULL && owner->isPlayerCreature()) {
			PlayerObject* ownerGhost = owner->getPlayerObject().get();

			if (!CombatManager::instance()->areInDuel(creature, owner)
					&& ownerGhost != NULL && ownerGhost->getFactionStatus() == FactionStatus::OVERT) {
				ghost->updateLastPvpCombatActionTimestamp();
			}
		}
	}
}
<commit_msg>[Fixed] pvp healing only causes a tef if the target has a tef - mantis 6255<commit_after>/*
 * QueueCommand.cpp
 *
 *  Created on: 22/05/2010
 *      Author: victor
 */

#include "QueueCommand.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/objects/player/PlayerObject.h"
#include "server/zone/objects/player/FactionStatus.h"
#include "server/zone/objects/tangible/weapon/WeaponObject.h"
#include "server/zone/managers/combat/CombatManager.h"

QueueCommand::QueueCommand(const String& skillname, ZoneProcessServer* serv) : Logger() {
	server = serv;

	name = skillname;
	nameCRC = skillname.hashCode();

	maxRangeToTarget = 0;

	commandGroup = 0;

	stateMask = 0;
	targetType = 0;
	disabled = false;
	addToQueue = false;
	admin = false;

	defaultTime = 0.f;

	cooldown = 0;

	defaultPriority = NORMAL;

	setLogging(true);
	setGlobalLogging(true);
	setLoggingName("QueueCommand " + skillname);
}

/*
 * Sets the invalid locomotion for this command.
 * Parses the string from LUA's. Format: "4,12,13,"
 */
void QueueCommand::setInvalidLocomotions(const String& lStr) {
	StringTokenizer tokenizer(lStr);
	tokenizer.setDelimeter(",");

	String token = "";
	while (tokenizer.hasMoreTokens()) {
		tokenizer.getStringToken(token);

		if(!token.isEmpty())
			invalidLocomotion.add(Integer::valueOf(token));
	}
}

/*
 * Checks each invalid locomotion with the player's current locomotion
 */
bool QueueCommand::checkInvalidLocomotions(CreatureObject* creature) const {
	for (int i = 0; i < invalidLocomotion.size(); ++i) {
		if (invalidLocomotion.get(i) == creature->getLocomotion())
			return false;
	}

	return true;
}

void QueueCommand::onStateFail(CreatureObject* creature, uint32 actioncntr) const {
	if (!addToQueue)
		return;

	uint64 states = stateMask & creature->getStateBitmask();

	uint64 state = 1;
	int num = 0;

	while (num < 34) {
		if (states & state) {

			creature->clearQueueAction(actioncntr, 0, 5, num);
			return;

		}

		state *= 2;
		++num;
	}

	creature->error("unknown invalid state in onStateFail");
}

void QueueCommand::onLocomotionFail(CreatureObject* creature, uint32 actioncntr) const {
	if (!checkInvalidLocomotions(creature))
		creature->clearQueueAction(actioncntr, 0, 1, creature->getLocomotion());
}

/*
 * Unsuccessful command completion alerts the player of the invalid state
 */
void QueueCommand::onFail(uint32 actioncntr, CreatureObject* creature, uint32 errorNumber) const {
	StringIdChatParameter prm;
	switch (errorNumber) {
	case INVALIDSYNTAX:
		creature->sendSystemMessage(getSyntax());
		if (addToQueue)
			creature->clearQueueAction(actioncntr);
		break;
	case INVALIDSTATE:
		onStateFail(creature, actioncntr);
		break;
	case INVALIDLOCOMOTION:
		onLocomotionFail(creature, actioncntr);
		break;
	case INVALIDTARGET:
		if (addToQueue)
			creature->clearQueueAction(actioncntr, 0, 3, 0);
		break;
	case INVALIDWEAPON: // this only gets returned from combat commands
		switch (creature->getWeapon()->getAttackType()) {
		case WeaponObject::RANGEDATTACK:
			creature->sendSystemMessage("@cbt_spam:no_attack_ranged_single");
			break;
		case WeaponObject::MELEEATTACK:
			creature->sendSystemMessage("@cbt_spam:no_attack_melee_single");
			break;
		default:
			creature->sendSystemMessage("@cbt_spam:no_attack_wrong_weapon"); // Can't be done with this weapon
			break;
		}

		if (addToQueue)
			creature->clearQueueAction(actioncntr);
		break;

	case TOOFAR:
		if (addToQueue)
			creature->clearQueueAction(actioncntr, 0, 4, 0);
		break;

	case NOJEDIARMOR:
		creature->sendSystemMessage("@jedi_spam:not_with_armor"); // You cannot use Force powers or lightsaber abilities while wearing armor.
		if (addToQueue)
			creature->clearQueueAction(actioncntr);

		break;

	case NOPRONE:
		if (addToQueue)
			creature->clearQueueAction(actioncntr, 0, 1, 7);

		break;

	case NOKNEELING:
		if (addToQueue)
			creature->clearQueueAction(actioncntr, 0, 1, 4);

		break;
	case INSUFFICIENTPERMISSION:
		creature->sendSystemMessage("@error_message:insufficient_permissions"); //You do not have sufficient permissions to perform the requested action.

		if (addToQueue)
			creature->clearQueueAction(actioncntr);
		break;
	case TOOCLOSE:
		prm.setStringId("combat_effects", "prone_ranged_too_close");
		creature->sendSystemMessage(prm);

		if (addToQueue)
			creature->clearQueueAction(actioncntr);
		break;
	default:
		if (addToQueue)
			creature->clearQueueAction(actioncntr);
		break;
	}
}

void QueueCommand::onComplete(uint32 actioncntr, CreatureObject* player, float commandDuration) const {
	if (!player->isPlayerCreature())
		return;

	if (addToQueue)
		player->clearQueueAction(actioncntr, commandDuration);
}

int QueueCommand::doCommonMedicalCommandChecks(CreatureObject* creature) const {
	if (!checkStateMask(creature))
		return INVALIDSTATE;

	if (!checkInvalidLocomotions(creature))
		return INVALIDLOCOMOTION;

	if (creature->hasAttackDelay() || !creature->checkPostureChangeDelay()) // no message associated with this
		return GENERALERROR;

	if (creature->isProne() || creature->isMeditating() || creature->isSwimming()) {
		creature->sendSystemMessage("@error_message:wrong_state"); //You cannot complete that action while in your current state.
		return GENERALERROR;
	}

	if (creature->isRidingMount()) {
		creature->sendSystemMessage("@error_message:survey_on_mount"); //You cannot perform that action while mounted on a creature or driving a vehicle.
		return GENERALERROR;
	}

	return SUCCESS;
}

void QueueCommand::checkForTef(CreatureObject* creature, CreatureObject* target) const {
	if (!creature->isPlayerCreature() || creature == target)
		return;

	PlayerObject* ghost = creature->getPlayerObject().get();
	if (ghost == NULL)
		return;

	if (target->isPlayerCreature()) {
		PlayerObject* targetGhost = target->getPlayerObject().get();

		if (!CombatManager::instance()->areInDuel(creature, target)
				&& targetGhost != NULL && targetGhost->getFactionStatus() == FactionStatus::OVERT && targetGhost->hasPvpTef()) {
			ghost->updateLastPvpCombatActionTimestamp();
		}
	} else if (target->isPet()) {
		ManagedReference<CreatureObject*> owner = target->getLinkedCreature().get();

		if (owner != NULL && owner->isPlayerCreature()) {
			PlayerObject* ownerGhost = owner->getPlayerObject().get();

			if (!CombatManager::instance()->areInDuel(creature, owner)
					&& ownerGhost != NULL && ownerGhost->getFactionStatus() == FactionStatus::OVERT && ownerGhost->hasPvpTef()) {
				ghost->updateLastPvpCombatActionTimestamp();
			}
		}
	}
}
<|endoftext|>


<commit_before>#ifdef _MSC_VER
#include <vector>
#endif
#include <omp.h>

#include "aligned_malloc.h"
#include "uvg11_full.h"
#include "mkHalideBuf.h"

#include "scatter_gridder_w_dependent_dyn_1p_1gcf_halide.h"

using namespace std;

#define __tod(a, ...) reinterpret_cast<__VA_ARGS__ double *>(a)

const int over = 8;
void gridKernel_scatter_halide(
    double scale
  , double wstep
  , int baselines
  , const BlWMap bl_wp_map[/* baselines */]
  , const int bl_supps[/* baselines */] // computed from previous
  , complexd grids[]
    // w-planes length array of pointers
    // to [over][over][gcf_supp][gcf_supp] arrays
  , const complexd * gcf[]
  , const Double3 * _uvw[]
  , const complexd * _vis[]
  , int ts_ch
  , int grid_pitch
  , int grid_size
  ) {

  auto gcf_buf = mkInterleavedHalideBufs<2, double>();

  // FIXME: add an API
  gcf_buf[0].extent[2] = gcf_buf[1].extent[2] =
  gcf_buf[0].extent[3] = gcf_buf[1].extent[3] = over;

  buffer_t uvw_buf = mkHalideBuf<3, double>(ts_ch);
  buffer_t vis_buf = mkHalideBuf<2, double>(ts_ch);

#pragma omp parallel
  {
    int siz = grid_size*grid_pitch;
    complexd * grid = grids + omp_get_thread_num() * siz;

    memset(grid, 0, sizeof(complexd) * siz);
    buffer_t grid_buf = mkHalideBufPadded<2>(__tod(grid), grid_size, grid_pitch-grid_size);

#pragma omp for schedule(dynamic,23)
    for(int bl = 0; bl < baselines; bl++){
      setHalideBuf(__tod(_uvw[bl], const), uvw_buf);
      setHalideBuf(__tod(_vis[bl], const), vis_buf);
      int curr_wp = bl_wp_map[bl].wp;
      setInterleavedHalideBufs(gcf[curr_wp], gcf_buf);
      int supp = bl_supps[curr_wp];
      // FIXME: add an API
      gcf_buf[0].extent[0] = gcf_buf[0].extent[1] =
      gcf_buf[1].extent[0] = gcf_buf[1].extent[1] = supp;
      set_strides(&gcf_buf[0]);
      set_strides(&gcf_buf[1]);

      uvg11_full(
          scale
        , wstep
        , ts_ch
        , &uvw_buf
        , &vis_buf
        , supp
        , &gcf_buf[0]
        , &gcf_buf[1]
        , &grid_buf
        );
    }
  }
}

inline
void addGrids(
    complexd dst[]
  , const complexd srcs[]
  , int nthreads
  , int grid_pitch
  , int grid_size
  )
{
  int siz = grid_size*grid_pitch;
#pragma omp parallel for
  for (int i = 0; size_t(i) < siz*sizeof(complexd)/__MMSIZE; i++) {
    __mdType sum = asMdpc(srcs)[i];
    // __m256d sum = _mm256_loadu_pd(reinterpret_cast<const double*>(as256pc(srcs)+i));

    for (int g = 1; g < nthreads; g ++)
      sum = _mm_add_pd(sum, asMdpc(srcs + g * siz)[i]);

    asMdp(dst)[i] = sum;
  }
}

void gridKernel_scatter_halide_full(
    double scale
  , double wstep
  , int baselines
  , const BlWMap bl_wp_map[/* baselines */]
  , const int bl_supps[/* baselines */] // computed from previous
  , complexd grid[]
    // w-planes length array of pointers
    // to [over][over][gcf_supp][gcf_supp] arrays
  , const complexd * gcf[]
  , const Double3 * uvw[]
  , const complexd * vis[]
  , int ts_ch
  , int grid_pitch
  , int grid_size
  ) {
  int siz = grid_size*grid_pitch;
  int nthreads;

#pragma omp parallel
#pragma omp single
  nthreads = omp_get_num_threads();

  // Nullify incoming grid, allocate thread-local grids
  memset(grid, 0, sizeof(complexd) * siz);
  complexd * tmpgrids = alignedMallocArray<complexd>(siz * nthreads, 32);

  gridKernel_scatter_halide(
      scale
    , wstep
    , baselines
    , bl_wp_map
    , bl_supps
    , tmpgrids
    , gcf
    , uvw
    , vis
    , ts_ch
    , grid_pitch
    , grid_size
    );

  addGrids(grid, tmpgrids, nthreads, grid_pitch, grid_size);
  _aligned_free(tmpgrids);
}
<commit_msg>Stupid bug in gridder wrapper.<commit_after>#ifdef _MSC_VER
#include <vector>
#endif
#include <omp.h>

#include "aligned_malloc.h"
#include "uvg11_full.h"
#include "mkHalideBuf.h"

#include "scatter_gridder_w_dependent_dyn_1p_1gcf_halide.h"

using namespace std;

#define __tod(a, ...) reinterpret_cast<__VA_ARGS__ double *>(a)

const int over = 8;
void gridKernel_scatter_halide(
    double scale
  , double wstep
  , int baselines
  , const BlWMap bl_wp_map[/* baselines */]
  , const int bl_supps[/* baselines */] // computed from previous
  , complexd grids[]
    // w-planes length array of pointers
    // to [over][over][gcf_supp][gcf_supp] arrays
  , const complexd * gcf[]
  , const Double3 * _uvw[]
  , const complexd * _vis[]
  , int ts_ch
  , int grid_pitch
  , int grid_size
  ) {

  auto gcf_buf = mkInterleavedHalideBufs<2, double>();

  // FIXME: add an API
  gcf_buf[0].extent[2] = gcf_buf[1].extent[2] =
  gcf_buf[0].extent[3] = gcf_buf[1].extent[3] = over;

  buffer_t uvw_buf = mkHalideBuf<3, double>(ts_ch);
  buffer_t vis_buf = mkHalideBuf<2, double>(ts_ch);

#pragma omp parallel
  {
    int siz = grid_size*grid_pitch;
    complexd * grid = grids + omp_get_thread_num() * siz;

    memset(grid, 0, sizeof(complexd) * siz);
    buffer_t grid_buf = mkHalideBufPadded<2>(__tod(grid), grid_size, grid_pitch-grid_size);

#pragma omp for schedule(dynamic,23)
    for(int bl = 0; bl < baselines; bl++){
      setHalideBuf(__tod(_uvw[bl], const), uvw_buf);
      setHalideBuf(__tod(_vis[bl], const), vis_buf);
      int curr_wp = bl_wp_map[bl].wp;
      setInterleavedHalideBufs(gcf[curr_wp], gcf_buf);
      int supp = bl_supps[bl];
      // FIXME: add an API
      gcf_buf[0].extent[0] = gcf_buf[0].extent[1] =
      gcf_buf[1].extent[0] = gcf_buf[1].extent[1] = supp;
      set_strides(&gcf_buf[0]);
      set_strides(&gcf_buf[1]);

      uvg11_full(
          scale
        , wstep
        , ts_ch
        , &uvw_buf
        , &vis_buf
        , supp
        , &gcf_buf[0]
        , &gcf_buf[1]
        , &grid_buf
        );
    }
  }
}

inline
void addGrids(
    complexd dst[]
  , const complexd srcs[]
  , int nthreads
  , int grid_pitch
  , int grid_size
  )
{
  int siz = grid_size*grid_pitch;
#pragma omp parallel for
  for (int i = 0; size_t(i) < siz*sizeof(complexd)/__MMSIZE; i++) {
    __mdType sum = asMdpc(srcs)[i];
    // __m256d sum = _mm256_loadu_pd(reinterpret_cast<const double*>(as256pc(srcs)+i));

    for (int g = 1; g < nthreads; g ++)
      sum = _mm_add_pd(sum, asMdpc(srcs + g * siz)[i]);

    asMdp(dst)[i] = sum;
  }
}

void gridKernel_scatter_halide_full(
    double scale
  , double wstep
  , int baselines
  , const BlWMap bl_wp_map[/* baselines */]
  , const int bl_supps[/* baselines */] // computed from previous
  , complexd grid[]
    // w-planes length array of pointers
    // to [over][over][gcf_supp][gcf_supp] arrays
  , const complexd * gcf[]
  , const Double3 * uvw[]
  , const complexd * vis[]
  , int ts_ch
  , int grid_pitch
  , int grid_size
  ) {
  int siz = grid_size*grid_pitch;
  int nthreads;

#pragma omp parallel
#pragma omp single
  nthreads = omp_get_num_threads();

  // Nullify incoming grid, allocate thread-local grids
  memset(grid, 0, sizeof(complexd) * siz);
  complexd * tmpgrids = alignedMallocArray<complexd>(siz * nthreads, 32);

  gridKernel_scatter_halide(
      scale
    , wstep
    , baselines
    , bl_wp_map
    , bl_supps
    , tmpgrids
    , gcf
    , uvw
    , vis
    , ts_ch
    , grid_pitch
    , grid_size
    );

  addGrids(grid, tmpgrids, nthreads, grid_pitch, grid_size);
  _aligned_free(tmpgrids);
}
<|endoftext|>


<commit_before><commit_msg>Fallback to RSockets if cert exchange fails<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/prefs/pref_value_store.h"

#include "chrome/browser/prefs/pref_notifier.h"

PrefValueStore::PrefStoreKeeper::PrefStoreKeeper()
    : pref_value_store_(NULL),
      type_(PrefValueStore::INVALID_STORE) {
}

PrefValueStore::PrefStoreKeeper::~PrefStoreKeeper() {
  if (pref_store_.get())
    pref_store_->RemoveObserver(this);
}

void PrefValueStore::PrefStoreKeeper::Initialize(
    PrefValueStore* store,
    PrefStore* pref_store,
    PrefValueStore::PrefStoreType type) {
  if (pref_store_.get())
    pref_store_->RemoveObserver(this);
  type_ = type;
  pref_value_store_ = store;
  pref_store_ = pref_store;
  if (pref_store_.get())
    pref_store_->AddObserver(this);
}

void PrefValueStore::PrefStoreKeeper::OnPrefValueChanged(
    const std::string& key) {
  pref_value_store_->OnPrefValueChanged(type_, key);
}

void PrefValueStore::PrefStoreKeeper::OnInitializationCompleted() {
  pref_value_store_->OnInitializationCompleted(type_);
}

PrefValueStore::PrefValueStore(PrefStore* managed_platform_prefs,
                               PrefStore* device_management_prefs,
                               PrefStore* extension_prefs,
                               PrefStore* command_line_prefs,
                               PrefStore* user_prefs,
                               PrefStore* recommended_prefs,
                               PrefStore* default_prefs,
                               PrefNotifier* pref_notifier)
    : pref_notifier_(pref_notifier) {
  InitPrefStore(MANAGED_PLATFORM_STORE, managed_platform_prefs);
  InitPrefStore(DEVICE_MANAGEMENT_STORE, device_management_prefs);
  InitPrefStore(EXTENSION_STORE, extension_prefs);
  InitPrefStore(COMMAND_LINE_STORE, command_line_prefs);
  InitPrefStore(USER_STORE, user_prefs);
  InitPrefStore(RECOMMENDED_STORE, recommended_prefs);
  InitPrefStore(DEFAULT_STORE, default_prefs);

  CheckInitializationCompleted();
}

PrefValueStore::~PrefValueStore() {}

PrefValueStore* PrefValueStore::CloneAndSpecialize(
    PrefStore* managed_platform_prefs,
    PrefStore* device_management_prefs,
    PrefStore* extension_prefs,
    PrefStore* command_line_prefs,
    PrefStore* user_prefs,
    PrefStore* recommended_prefs,
    PrefStore* default_prefs,
    PrefNotifier* pref_notifier) {
  DCHECK(pref_notifier);
  if (!managed_platform_prefs)
    managed_platform_prefs = GetPrefStore(MANAGED_PLATFORM_STORE);
  if (!device_management_prefs)
    device_management_prefs = GetPrefStore(DEVICE_MANAGEMENT_STORE);
  if (!extension_prefs)
    extension_prefs = GetPrefStore(EXTENSION_STORE);
  if (!command_line_prefs)
    command_line_prefs = GetPrefStore(COMMAND_LINE_STORE);
  if (!user_prefs)
    user_prefs = GetPrefStore(USER_STORE);
  if (!recommended_prefs)
    recommended_prefs = GetPrefStore(RECOMMENDED_STORE);
  if (!default_prefs)
    default_prefs = GetPrefStore(DEFAULT_STORE);

  return new PrefValueStore(
      managed_platform_prefs, device_management_prefs, extension_prefs,
      command_line_prefs, user_prefs, recommended_prefs, default_prefs,
      pref_notifier);
}

bool PrefValueStore::GetValue(const std::string& name,
                              Value::ValueType type,
                              Value** out_value) const {
  *out_value = NULL;
  // Check the |PrefStore|s in order of their priority from highest to lowest
  // to find the value of the preference described by the given preference name.
  for (size_t i = 0; i <= PREF_STORE_TYPE_MAX; ++i) {
    if (GetValueFromStore(name.c_str(), static_cast<PrefStoreType>(i),
                          out_value)) {
      if (!(*out_value)->IsType(type)) {
        LOG(WARNING) << "Expected type for " << name << " is " << type
                     << " but got " << (*out_value)->GetType()
                     << " in store " << i;
        continue;
      }
      return true;
    }
  }
  return false;
}

void PrefValueStore::NotifyPrefChanged(
    const char* path,
    PrefValueStore::PrefStoreType new_store) {
  DCHECK(new_store != INVALID_STORE);

  bool changed = true;
  // Replying that the pref has changed in case the new store is invalid may
  // cause problems, but it's the safer choice.
  if (new_store != INVALID_STORE) {
    PrefStoreType controller = ControllingPrefStoreForPref(path);
    DCHECK(controller != INVALID_STORE);
    // If the pref is controlled by a higher-priority store, its effective value
    // cannot have changed.
    if (controller != INVALID_STORE &&
        controller < new_store) {
      changed = false;
    }
  }

  if (changed)
    pref_notifier_->OnPreferenceChanged(path);
}

bool PrefValueStore::PrefValueInManagedPlatformStore(const char* name) const {
  return PrefValueInStore(name, MANAGED_PLATFORM_STORE);
}

bool PrefValueStore::PrefValueInDeviceManagementStore(const char* name) const {
  return PrefValueInStore(name, DEVICE_MANAGEMENT_STORE);
}

bool PrefValueStore::PrefValueInExtensionStore(const char* name) const {
  return PrefValueInStore(name, EXTENSION_STORE);
}

bool PrefValueStore::PrefValueInUserStore(const char* name) const {
  return PrefValueInStore(name, USER_STORE);
}

bool PrefValueStore::PrefValueFromExtensionStore(const char* name) const {
  return ControllingPrefStoreForPref(name) == EXTENSION_STORE;
}

bool PrefValueStore::PrefValueFromUserStore(const char* name) const {
  return ControllingPrefStoreForPref(name) == USER_STORE;
}

bool PrefValueStore::PrefValueFromDefaultStore(const char* name) const {
  return ControllingPrefStoreForPref(name) == DEFAULT_STORE;
}

bool PrefValueStore::PrefValueUserModifiable(const char* name) const {
  PrefStoreType effective_store = ControllingPrefStoreForPref(name);
  return effective_store >= USER_STORE ||
         effective_store == INVALID_STORE;
}

bool PrefValueStore::PrefValueInStore(
    const char* name,
    PrefValueStore::PrefStoreType store) const {
  // Declare a temp Value* and call GetValueFromStore,
  // ignoring the output value.
  Value* tmp_value = NULL;
  return GetValueFromStore(name, store, &tmp_value);
}

bool PrefValueStore::PrefValueInStoreRange(
    const char* name,
    PrefValueStore::PrefStoreType first_checked_store,
    PrefValueStore::PrefStoreType last_checked_store) const {
  if (first_checked_store > last_checked_store) {
    NOTREACHED();
    return false;
  }

  for (size_t i = first_checked_store;
       i <= static_cast<size_t>(last_checked_store); ++i) {
    if (PrefValueInStore(name, static_cast<PrefStoreType>(i)))
      return true;
  }
  return false;
}

PrefValueStore::PrefStoreType PrefValueStore::ControllingPrefStoreForPref(
    const char* name) const {
  for (size_t i = 0; i <= PREF_STORE_TYPE_MAX; ++i) {
    if (PrefValueInStore(name, static_cast<PrefStoreType>(i)))
      return static_cast<PrefStoreType>(i);
  }
  return INVALID_STORE;
}

bool PrefValueStore::GetValueFromStore(const char* name,
                                       PrefValueStore::PrefStoreType store_type,
                                       Value** out_value) const {
  // Only return true if we find a value and it is the correct type, so stale
  // values with the incorrect type will be ignored.
  const PrefStore* store = GetPrefStore(static_cast<PrefStoreType>(store_type));
  if (store) {
    switch (store->GetValue(name, out_value)) {
      case PrefStore::READ_USE_DEFAULT:
        store = GetPrefStore(DEFAULT_STORE);
        if (!store || store->GetValue(name, out_value) != PrefStore::READ_OK) {
          *out_value = NULL;
          return false;
        }
        // Fall through...
      case PrefStore::READ_OK:
        return true;
      case PrefStore::READ_NO_VALUE:
        break;
    }
  }

  // No valid value found for the given preference name: set the return false.
  *out_value = NULL;
  return false;
}

void PrefValueStore::OnPrefValueChanged(PrefValueStore::PrefStoreType type,
                                        const std::string& key) {
  NotifyPrefChanged(key.c_str(), type);
}

void PrefValueStore::OnInitializationCompleted(
    PrefValueStore::PrefStoreType type) {
  CheckInitializationCompleted();
}

void PrefValueStore::InitPrefStore(PrefValueStore::PrefStoreType type,
                                   PrefStore* pref_store) {
  pref_stores_[type].Initialize(this, pref_store, type);
}

void PrefValueStore::CheckInitializationCompleted() {
  for (size_t i = 0; i <= PREF_STORE_TYPE_MAX; ++i) {
    scoped_refptr<PrefStore> store =
        GetPrefStore(static_cast<PrefStoreType>(i));
    if (store && !store->IsInitializationComplete())
      return;
  }
  pref_notifier_->OnInitializationCompleted();
}
<commit_msg>Simplified PrefValueStore::NotifyPrefChanged.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/prefs/pref_value_store.h"

#include "chrome/browser/prefs/pref_notifier.h"

PrefValueStore::PrefStoreKeeper::PrefStoreKeeper()
    : pref_value_store_(NULL),
      type_(PrefValueStore::INVALID_STORE) {
}

PrefValueStore::PrefStoreKeeper::~PrefStoreKeeper() {
  if (pref_store_.get())
    pref_store_->RemoveObserver(this);
}

void PrefValueStore::PrefStoreKeeper::Initialize(
    PrefValueStore* store,
    PrefStore* pref_store,
    PrefValueStore::PrefStoreType type) {
  if (pref_store_.get())
    pref_store_->RemoveObserver(this);
  type_ = type;
  pref_value_store_ = store;
  pref_store_ = pref_store;
  if (pref_store_.get())
    pref_store_->AddObserver(this);
}

void PrefValueStore::PrefStoreKeeper::OnPrefValueChanged(
    const std::string& key) {
  pref_value_store_->OnPrefValueChanged(type_, key);
}

void PrefValueStore::PrefStoreKeeper::OnInitializationCompleted() {
  pref_value_store_->OnInitializationCompleted(type_);
}

PrefValueStore::PrefValueStore(PrefStore* managed_platform_prefs,
                               PrefStore* device_management_prefs,
                               PrefStore* extension_prefs,
                               PrefStore* command_line_prefs,
                               PrefStore* user_prefs,
                               PrefStore* recommended_prefs,
                               PrefStore* default_prefs,
                               PrefNotifier* pref_notifier)
    : pref_notifier_(pref_notifier) {
  InitPrefStore(MANAGED_PLATFORM_STORE, managed_platform_prefs);
  InitPrefStore(DEVICE_MANAGEMENT_STORE, device_management_prefs);
  InitPrefStore(EXTENSION_STORE, extension_prefs);
  InitPrefStore(COMMAND_LINE_STORE, command_line_prefs);
  InitPrefStore(USER_STORE, user_prefs);
  InitPrefStore(RECOMMENDED_STORE, recommended_prefs);
  InitPrefStore(DEFAULT_STORE, default_prefs);

  CheckInitializationCompleted();
}

PrefValueStore::~PrefValueStore() {}

PrefValueStore* PrefValueStore::CloneAndSpecialize(
    PrefStore* managed_platform_prefs,
    PrefStore* device_management_prefs,
    PrefStore* extension_prefs,
    PrefStore* command_line_prefs,
    PrefStore* user_prefs,
    PrefStore* recommended_prefs,
    PrefStore* default_prefs,
    PrefNotifier* pref_notifier) {
  DCHECK(pref_notifier);
  if (!managed_platform_prefs)
    managed_platform_prefs = GetPrefStore(MANAGED_PLATFORM_STORE);
  if (!device_management_prefs)
    device_management_prefs = GetPrefStore(DEVICE_MANAGEMENT_STORE);
  if (!extension_prefs)
    extension_prefs = GetPrefStore(EXTENSION_STORE);
  if (!command_line_prefs)
    command_line_prefs = GetPrefStore(COMMAND_LINE_STORE);
  if (!user_prefs)
    user_prefs = GetPrefStore(USER_STORE);
  if (!recommended_prefs)
    recommended_prefs = GetPrefStore(RECOMMENDED_STORE);
  if (!default_prefs)
    default_prefs = GetPrefStore(DEFAULT_STORE);

  return new PrefValueStore(
      managed_platform_prefs, device_management_prefs, extension_prefs,
      command_line_prefs, user_prefs, recommended_prefs, default_prefs,
      pref_notifier);
}

bool PrefValueStore::GetValue(const std::string& name,
                              Value::ValueType type,
                              Value** out_value) const {
  *out_value = NULL;
  // Check the |PrefStore|s in order of their priority from highest to lowest
  // to find the value of the preference described by the given preference name.
  for (size_t i = 0; i <= PREF_STORE_TYPE_MAX; ++i) {
    if (GetValueFromStore(name.c_str(), static_cast<PrefStoreType>(i),
                          out_value)) {
      if (!(*out_value)->IsType(type)) {
        LOG(WARNING) << "Expected type for " << name << " is " << type
                     << " but got " << (*out_value)->GetType()
                     << " in store " << i;
        continue;
      }
      return true;
    }
  }
  return false;
}

void PrefValueStore::NotifyPrefChanged(
    const char* path,
    PrefValueStore::PrefStoreType new_store) {
  DCHECK(new_store != INVALID_STORE);

  // If the pref is controlled by a higher-priority store, its effective value
  // cannot have changed.
  PrefStoreType controller = ControllingPrefStoreForPref(path);
  if (controller == INVALID_STORE || controller >= new_store)
    pref_notifier_->OnPreferenceChanged(path);
}

bool PrefValueStore::PrefValueInManagedPlatformStore(const char* name) const {
  return PrefValueInStore(name, MANAGED_PLATFORM_STORE);
}

bool PrefValueStore::PrefValueInDeviceManagementStore(const char* name) const {
  return PrefValueInStore(name, DEVICE_MANAGEMENT_STORE);
}

bool PrefValueStore::PrefValueInExtensionStore(const char* name) const {
  return PrefValueInStore(name, EXTENSION_STORE);
}

bool PrefValueStore::PrefValueInUserStore(const char* name) const {
  return PrefValueInStore(name, USER_STORE);
}

bool PrefValueStore::PrefValueFromExtensionStore(const char* name) const {
  return ControllingPrefStoreForPref(name) == EXTENSION_STORE;
}

bool PrefValueStore::PrefValueFromUserStore(const char* name) const {
  return ControllingPrefStoreForPref(name) == USER_STORE;
}

bool PrefValueStore::PrefValueFromDefaultStore(const char* name) const {
  return ControllingPrefStoreForPref(name) == DEFAULT_STORE;
}

bool PrefValueStore::PrefValueUserModifiable(const char* name) const {
  PrefStoreType effective_store = ControllingPrefStoreForPref(name);
  return effective_store >= USER_STORE ||
         effective_store == INVALID_STORE;
}

bool PrefValueStore::PrefValueInStore(
    const char* name,
    PrefValueStore::PrefStoreType store) const {
  // Declare a temp Value* and call GetValueFromStore,
  // ignoring the output value.
  Value* tmp_value = NULL;
  return GetValueFromStore(name, store, &tmp_value);
}

bool PrefValueStore::PrefValueInStoreRange(
    const char* name,
    PrefValueStore::PrefStoreType first_checked_store,
    PrefValueStore::PrefStoreType last_checked_store) const {
  if (first_checked_store > last_checked_store) {
    NOTREACHED();
    return false;
  }

  for (size_t i = first_checked_store;
       i <= static_cast<size_t>(last_checked_store); ++i) {
    if (PrefValueInStore(name, static_cast<PrefStoreType>(i)))
      return true;
  }
  return false;
}

PrefValueStore::PrefStoreType PrefValueStore::ControllingPrefStoreForPref(
    const char* name) const {
  for (size_t i = 0; i <= PREF_STORE_TYPE_MAX; ++i) {
    if (PrefValueInStore(name, static_cast<PrefStoreType>(i)))
      return static_cast<PrefStoreType>(i);
  }
  return INVALID_STORE;
}

bool PrefValueStore::GetValueFromStore(const char* name,
                                       PrefValueStore::PrefStoreType store_type,
                                       Value** out_value) const {
  // Only return true if we find a value and it is the correct type, so stale
  // values with the incorrect type will be ignored.
  const PrefStore* store = GetPrefStore(static_cast<PrefStoreType>(store_type));
  if (store) {
    switch (store->GetValue(name, out_value)) {
      case PrefStore::READ_USE_DEFAULT:
        store = GetPrefStore(DEFAULT_STORE);
        if (!store || store->GetValue(name, out_value) != PrefStore::READ_OK) {
          *out_value = NULL;
          return false;
        }
        // Fall through...
      case PrefStore::READ_OK:
        return true;
      case PrefStore::READ_NO_VALUE:
        break;
    }
  }

  // No valid value found for the given preference name: set the return false.
  *out_value = NULL;
  return false;
}

void PrefValueStore::OnPrefValueChanged(PrefValueStore::PrefStoreType type,
                                        const std::string& key) {
  NotifyPrefChanged(key.c_str(), type);
}

void PrefValueStore::OnInitializationCompleted(
    PrefValueStore::PrefStoreType type) {
  CheckInitializationCompleted();
}

void PrefValueStore::InitPrefStore(PrefValueStore::PrefStoreType type,
                                   PrefStore* pref_store) {
  pref_stores_[type].Initialize(this, pref_store, type);
}

void PrefValueStore::CheckInitializationCompleted() {
  for (size_t i = 0; i <= PREF_STORE_TYPE_MAX; ++i) {
    scoped_refptr<PrefStore> store =
        GetPrefStore(static_cast<PrefStoreType>(i));
    if (store && !store->IsInitializationComplete())
      return;
  }
  pref_notifier_->OnInitializationCompleted();
}
<|endoftext|>


<commit_before>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "QmitkHistogramVisualizationWidget.h"

#include <QClipboard>

QmitkHistogramVisualizationWidget::QmitkHistogramVisualizationWidget(QWidget* parent) : QWidget(parent)
{
	m_Controls.setupUi(this);
  m_Controls.checkBoxShowSubchart->setChecked(false);
  m_Controls.spinBoxNBins->setValue(m_DefaultNBins);
  m_Controls.spinBoxNBins->setMinimum(m_MinNBins);
  m_Controls.spinBoxNBins->setMaximum(m_MaxNBins);
  CreateConnections();
}

void QmitkHistogramVisualizationWidget::SetHistogram(itk::Statistics::Histogram<double>::ConstPointer histogram, const std::string& dataLabel)
{
	if (histogram == nullptr)
		return;

	m_Histogram = histogram;
	m_Controls.chartWidget->AddData2D(ConvertHistogramToMap(m_Histogram), dataLabel);
	m_Controls.chartWidget->SetChartType(dataLabel, QmitkChartWidget::ChartType::bar);
	m_Controls.chartWidget->SetXAxisLabel("Gray value");
	m_Controls.chartWidget->SetYAxisLabel("Frequency");
  m_Controls.chartWidget->Show(m_Controls.checkBoxShowSubchart->isChecked());
	SetGUIElementsEnabled(true);
}

void QmitkHistogramVisualizationWidget::Reset()
{
  m_Controls.chartWidget->Clear();
	SetGUIElementsEnabled(false);
}

void QmitkHistogramVisualizationWidget::SetTheme(QmitkChartWidget::ColorTheme style)
{
  m_Controls.chartWidget->SetTheme(style);
}

void QmitkHistogramVisualizationWidget::CreateConnections()
{
	connect(m_Controls.buttonCopyHistogramToClipboard, &QPushButton::clicked, this, &QmitkHistogramVisualizationWidget::OnClipboardButtonClicked);
	connect(m_Controls.checkBoxUseDefaultNBins, &QCheckBox::clicked, this, &QmitkHistogramVisualizationWidget::OnDefaultNBinsCheckBoxChanged);
	connect(m_Controls.spinBoxNBins, &QSpinBox::editingFinished, this, &QmitkHistogramVisualizationWidget::OnNBinsSpinBoxValueChanged);
	connect(m_Controls.checkBoxShowSubchart, &QCheckBox::clicked, this, &QmitkHistogramVisualizationWidget::OnShowSubchartCheckBoxChanged);
	connect(m_Controls.checkBoxViewMinMax, &QCheckBox::clicked, this, &QmitkHistogramVisualizationWidget::OnViewMinMaxCheckBoxChanged);
	connect(m_Controls.doubleSpinBoxMaxValue, &QSpinBox::editingFinished, this, &QmitkHistogramVisualizationWidget::OnMaxValueSpinBoxValueChanged);
	connect(m_Controls.doubleSpinBoxMinValue, &QSpinBox::editingFinished, this, &QmitkHistogramVisualizationWidget::OnMinValueSpinBoxValueChanged);
}

void QmitkHistogramVisualizationWidget::SetGUIElementsEnabled(bool enabled)
{
	this->setEnabled(enabled);
	m_Controls.tabWidgetPlot->setEnabled(enabled);
	m_Controls.checkBoxShowSubchart->setEnabled(enabled);
	m_Controls.checkBoxUseDefaultNBins->setEnabled(enabled);
	m_Controls.spinBoxNBins->setEnabled(!m_Controls.checkBoxUseDefaultNBins->isChecked());
	m_Controls.buttonCopyHistogramToClipboard->setEnabled(enabled);
	m_Controls.checkBoxViewMinMax->setEnabled(enabled);
	m_Controls.doubleSpinBoxMaxValue->setEnabled(m_Controls.checkBoxViewMinMax->isChecked());
	m_Controls.doubleSpinBoxMinValue->setEnabled(m_Controls.checkBoxViewMinMax->isChecked());
}

std::map<double, double> QmitkHistogramVisualizationWidget::ConvertHistogramToMap(itk::Statistics::Histogram<double>::ConstPointer histogram) const
{
	std::map<double, double> histogramMap;
	if (histogram)
	{
		auto endIt = histogram->End();
		auto it = histogram->Begin();

		// generating Lists of measurement and frequencies
		for (; it != endIt; ++it)
		{
			double frequency = it.GetFrequency();
			double measurement = it.GetMeasurementVector()[0];
			histogramMap.emplace(measurement, frequency);
		}

	}
	return histogramMap;
}

void QmitkHistogramVisualizationWidget::OnClipboardButtonClicked()
{
	if (m_Histogram)
	{
		QApplication::clipboard()->clear();
		QString clipboard("Measurement \t Frequency\n");
		auto iter = m_Histogram->Begin();
		auto iterEnd = m_Histogram->End();
		for (; iter != iterEnd; ++iter)
		{
			clipboard = clipboard.append("%L1 \t %L2\n")
				.arg(iter.GetMeasurementVector()[0], 0, 'f', 2)
				.arg(iter.GetFrequency());
		}

		QApplication::clipboard()->setText(clipboard, QClipboard::Clipboard);
	}
}

void QmitkHistogramVisualizationWidget::OnDefaultNBinsCheckBoxChanged()
{
	if (m_Controls.checkBoxUseDefaultNBins->isChecked())
	{
		m_Controls.spinBoxNBins->setEnabled(false);
    if (m_Controls.spinBoxNBins->value() != static_cast<int>(m_DefaultNBins) ) {
      m_Controls.spinBoxNBins->setValue(m_DefaultNBins);
      OnNBinsSpinBoxValueChanged();
    }
	}
	else
	{
		m_Controls.spinBoxNBins->setEnabled(true);
	}
}

void QmitkHistogramVisualizationWidget::OnNBinsSpinBoxValueChanged()
{
	emit RequestHistogramUpdate(m_Controls.spinBoxNBins->value());
}

void QmitkHistogramVisualizationWidget::OnShowSubchartCheckBoxChanged()
{
	m_Controls.chartWidget->Show(m_Controls.checkBoxShowSubchart->isChecked());
}

void QmitkHistogramVisualizationWidget::OnViewMinMaxCheckBoxChanged()
{
	double min = m_Histogram->GetBinMin(0, 0);
	auto maxVector = m_Histogram->GetDimensionMaxs(0);
	double max;
	if (m_Controls.checkBoxUseDefaultNBins->isChecked())
		max = maxVector[m_DefaultNBins - 1];
	else
		max = maxVector[m_Controls.spinBoxNBins->value() - 1];

	if (!m_Controls.checkBoxViewMinMax->isChecked())
	{
		m_Controls.doubleSpinBoxMaxValue->setEnabled(false);
		m_Controls.doubleSpinBoxMinValue->setEnabled(false);
		m_Controls.chartWidget->Reload();
	}
	else
	{
		m_Controls.doubleSpinBoxMinValue->setMinimum(min);
		m_Controls.doubleSpinBoxMaxValue->setMaximum(max);
		m_Controls.doubleSpinBoxMaxValue->setEnabled(true);
		m_Controls.doubleSpinBoxMinValue->setEnabled(true);
	}
}

void QmitkHistogramVisualizationWidget::OnMinValueSpinBoxValueChanged()
{
	m_Controls.doubleSpinBoxMaxValue->setMinimum(m_Controls.doubleSpinBoxMinValue->value()+1);
  m_Controls.chartWidget->UpdateMinMaxValueXView(m_Controls.doubleSpinBoxMinValue->value(),m_Controls.doubleSpinBoxMaxValue->value());
}

void QmitkHistogramVisualizationWidget::OnMaxValueSpinBoxValueChanged()
{
	m_Controls.doubleSpinBoxMinValue->setMaximum(m_Controls.doubleSpinBoxMaxValue->value()-1);
  m_Controls.chartWidget->UpdateMinMaxValueXView(m_Controls.doubleSpinBoxMinValue->value(),m_Controls.doubleSpinBoxMaxValue->value());
}<commit_msg>Setting min/max values directly on start<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "QmitkHistogramVisualizationWidget.h"

#include <QClipboard>

QmitkHistogramVisualizationWidget::QmitkHistogramVisualizationWidget(QWidget* parent) : QWidget(parent)
{
	m_Controls.setupUi(this);
  m_Controls.checkBoxShowSubchart->setChecked(false);
  m_Controls.spinBoxNBins->setValue(m_DefaultNBins);
  m_Controls.spinBoxNBins->setMinimum(m_MinNBins);
  m_Controls.spinBoxNBins->setMaximum(m_MaxNBins);
  CreateConnections();
}

void QmitkHistogramVisualizationWidget::SetHistogram(itk::Statistics::Histogram<double>::ConstPointer histogram, const std::string& dataLabel)
{
	if (histogram == nullptr)
		return;

	m_Histogram = histogram;
	m_Controls.chartWidget->AddData2D(ConvertHistogramToMap(m_Histogram), dataLabel);
	m_Controls.chartWidget->SetChartType(dataLabel, QmitkChartWidget::ChartType::bar);
	m_Controls.chartWidget->SetXAxisLabel("Gray value");
	m_Controls.chartWidget->SetYAxisLabel("Frequency");
  m_Controls.chartWidget->Show(m_Controls.checkBoxShowSubchart->isChecked());
	SetGUIElementsEnabled(true);
}

void QmitkHistogramVisualizationWidget::Reset()
{
  m_Controls.chartWidget->Clear();
	SetGUIElementsEnabled(false);
}

void QmitkHistogramVisualizationWidget::SetTheme(QmitkChartWidget::ColorTheme style)
{
  m_Controls.chartWidget->SetTheme(style);
}

void QmitkHistogramVisualizationWidget::CreateConnections()
{
	connect(m_Controls.buttonCopyHistogramToClipboard, &QPushButton::clicked, this, &QmitkHistogramVisualizationWidget::OnClipboardButtonClicked);
	connect(m_Controls.checkBoxUseDefaultNBins, &QCheckBox::clicked, this, &QmitkHistogramVisualizationWidget::OnDefaultNBinsCheckBoxChanged);
	connect(m_Controls.spinBoxNBins, &QSpinBox::editingFinished, this, &QmitkHistogramVisualizationWidget::OnNBinsSpinBoxValueChanged);
	connect(m_Controls.checkBoxShowSubchart, &QCheckBox::clicked, this, &QmitkHistogramVisualizationWidget::OnShowSubchartCheckBoxChanged);
	connect(m_Controls.checkBoxViewMinMax, &QCheckBox::clicked, this, &QmitkHistogramVisualizationWidget::OnViewMinMaxCheckBoxChanged);
	connect(m_Controls.doubleSpinBoxMaxValue, &QSpinBox::editingFinished, this, &QmitkHistogramVisualizationWidget::OnMaxValueSpinBoxValueChanged);
	connect(m_Controls.doubleSpinBoxMinValue, &QSpinBox::editingFinished, this, &QmitkHistogramVisualizationWidget::OnMinValueSpinBoxValueChanged);
}

void QmitkHistogramVisualizationWidget::SetGUIElementsEnabled(bool enabled)
{
	this->setEnabled(enabled);
	m_Controls.tabWidgetPlot->setEnabled(enabled);
	m_Controls.checkBoxShowSubchart->setEnabled(enabled);
	m_Controls.checkBoxUseDefaultNBins->setEnabled(enabled);
	m_Controls.spinBoxNBins->setEnabled(!m_Controls.checkBoxUseDefaultNBins->isChecked());
	m_Controls.buttonCopyHistogramToClipboard->setEnabled(enabled);
	m_Controls.checkBoxViewMinMax->setEnabled(enabled);
	m_Controls.doubleSpinBoxMaxValue->setEnabled(m_Controls.checkBoxViewMinMax->isChecked());
	m_Controls.doubleSpinBoxMinValue->setEnabled(m_Controls.checkBoxViewMinMax->isChecked());
}

std::map<double, double> QmitkHistogramVisualizationWidget::ConvertHistogramToMap(itk::Statistics::Histogram<double>::ConstPointer histogram) const
{
	std::map<double, double> histogramMap;
	if (histogram)
	{
		auto endIt = histogram->End();
		auto it = histogram->Begin();

		// generating Lists of measurement and frequencies
		for (; it != endIt; ++it)
		{
			double frequency = it.GetFrequency();
			double measurement = it.GetMeasurementVector()[0];
			histogramMap.emplace(measurement, frequency);
		}

	}
	return histogramMap;
}

void QmitkHistogramVisualizationWidget::OnClipboardButtonClicked()
{
	if (m_Histogram)
	{
		QApplication::clipboard()->clear();
		QString clipboard("Measurement \t Frequency\n");
		auto iter = m_Histogram->Begin();
		auto iterEnd = m_Histogram->End();
		for (; iter != iterEnd; ++iter)
		{
			clipboard = clipboard.append("%L1 \t %L2\n")
				.arg(iter.GetMeasurementVector()[0], 0, 'f', 2)
				.arg(iter.GetFrequency());
		}

		QApplication::clipboard()->setText(clipboard, QClipboard::Clipboard);
	}
}

void QmitkHistogramVisualizationWidget::OnDefaultNBinsCheckBoxChanged()
{
	if (m_Controls.checkBoxUseDefaultNBins->isChecked())
	{
		m_Controls.spinBoxNBins->setEnabled(false);
    if (m_Controls.spinBoxNBins->value() != static_cast<int>(m_DefaultNBins) ) {
      m_Controls.spinBoxNBins->setValue(m_DefaultNBins);
      OnNBinsSpinBoxValueChanged();
    }
	}
	else
	{
		m_Controls.spinBoxNBins->setEnabled(true);
	}
}

void QmitkHistogramVisualizationWidget::OnNBinsSpinBoxValueChanged()
{
	emit RequestHistogramUpdate(m_Controls.spinBoxNBins->value());
}

void QmitkHistogramVisualizationWidget::OnShowSubchartCheckBoxChanged()
{
	m_Controls.chartWidget->Show(m_Controls.checkBoxShowSubchart->isChecked());
}

void QmitkHistogramVisualizationWidget::OnViewMinMaxCheckBoxChanged()
{
	double min = m_Histogram->GetBinMin(0, 0);
	auto maxVector = m_Histogram->GetDimensionMaxs(0);
	double max;
	if (m_Controls.checkBoxUseDefaultNBins->isChecked())
		max = maxVector[m_DefaultNBins - 1];
	else
		max = maxVector[m_Controls.spinBoxNBins->value() - 1];

	if (!m_Controls.checkBoxViewMinMax->isChecked())
	{
		m_Controls.doubleSpinBoxMaxValue->setEnabled(false);
		m_Controls.doubleSpinBoxMinValue->setEnabled(false);
		m_Controls.chartWidget->Reload();
	}
	else
	{
		m_Controls.doubleSpinBoxMinValue->setMinimum(min);
    m_Controls.doubleSpinBoxMinValue->setValue(min);
		m_Controls.doubleSpinBoxMaxValue->setMaximum(max);
    m_Controls.doubleSpinBoxMaxValue->setValue(max);
		m_Controls.doubleSpinBoxMaxValue->setEnabled(true);
		m_Controls.doubleSpinBoxMinValue->setEnabled(true);
	}
}

void QmitkHistogramVisualizationWidget::OnMinValueSpinBoxValueChanged()
{
	m_Controls.doubleSpinBoxMaxValue->setMinimum(m_Controls.doubleSpinBoxMinValue->value()+1);
  m_Controls.chartWidget->UpdateMinMaxValueXView(m_Controls.doubleSpinBoxMinValue->value(),m_Controls.doubleSpinBoxMaxValue->value());
}

void QmitkHistogramVisualizationWidget::OnMaxValueSpinBoxValueChanged()
{
	m_Controls.doubleSpinBoxMinValue->setMaximum(m_Controls.doubleSpinBoxMaxValue->value()-1);
  m_Controls.chartWidget->UpdateMinMaxValueXView(m_Controls.doubleSpinBoxMinValue->value(),m_Controls.doubleSpinBoxMaxValue->value());
}<|endoftext|>


<commit_before><commit_msg>Refactor the graphics example for common material loading<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/http/http_auth_handler_ntlm.h"

#if !defined(NTLM_SSPI)
#include "base/base64.h"
#endif
#include "base/logging.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "net/base/net_errors.h"
#include "net/base/net_util.h"

namespace net {

int HttpAuthHandlerNTLM::GenerateAuthTokenImpl(
    const string16* username,
    const string16* password,
    const HttpRequestInfo* request,
    CompletionCallback* callback,
    std::string* auth_token) {
#if defined(NTLM_SSPI)
  return auth_sspi_.GenerateAuthToken(
      username,
      password,
      CreateSPN(origin_),
      auth_token);
#else  // !defined(NTLM_SSPI)
  // TODO(wtc): See if we can use char* instead of void* for in_buf and
  // out_buf.  This change will need to propagate to GetNextToken,
  // GenerateType1Msg, and GenerateType3Msg, and perhaps further.
  const void* in_buf;
  void* out_buf;
  uint32 in_buf_len, out_buf_len;
  std::string decoded_auth_data;

  // |username| may be in the form "DOMAIN\user".  Parse it into the two
  // components.
  string16 domain;
  string16 user;
  const char16 backslash_character = '\\';
  size_t backslash_idx = username->find(backslash_character);
  if (backslash_idx == string16::npos) {
    user = *username;
  } else {
    domain = username->substr(0, backslash_idx);
    user = username->substr(backslash_idx + 1);
  }
  domain_ = domain;
  username_ = user;
  password_ = *password;

  // Initial challenge.
  if (auth_data_.empty()) {
    in_buf_len = 0;
    in_buf = NULL;
    int rv = InitializeBeforeFirstChallenge();
    if (rv != OK)
      return rv;
  } else {
    if (!base::Base64Decode(auth_data_, &decoded_auth_data)) {
      LOG(ERROR) << "Unexpected problem Base64 decoding.";
      return ERR_UNEXPECTED;
    }
    in_buf_len = decoded_auth_data.length();
    in_buf = decoded_auth_data.data();
  }

  int rv = GetNextToken(in_buf, in_buf_len, &out_buf, &out_buf_len);
  if (rv != OK)
    return rv;

  // Base64 encode data in output buffer and prepend "NTLM ".
  std::string encode_input(static_cast<char*>(out_buf), out_buf_len);
  std::string encode_output;
  bool base64_rv = base::Base64Encode(encode_input, &encode_output);
  // OK, we are done with |out_buf|
  free(out_buf);
  if (!base64_rv) {
    LOG(ERROR) << "Unexpected problem Base64 encoding.";
    return ERR_UNEXPECTED;
  }
  *auth_token = std::string("NTLM ") + encode_output;
  return OK;
#endif
}

// The NTLM challenge header looks like:
//   WWW-Authenticate: NTLM auth-data
bool HttpAuthHandlerNTLM::ParseChallenge(
    HttpAuth::ChallengeTokenizer* tok) {
  scheme_ = "ntlm";
  score_ = 3;
  properties_ = ENCRYPTS_IDENTITY | IS_CONNECTION_BASED;

#if defined(NTLM_SSPI)
  return auth_sspi_.ParseChallenge(tok);
#else
  auth_data_.clear();

  // Verify the challenge's auth-scheme.
  if (!tok->valid() || !LowerCaseEqualsASCII(tok->scheme(), "ntlm"))
    return false;

  tok->set_expect_base64_token(true);
  if (tok->GetNext())
    auth_data_.assign(tok->value_begin(), tok->value_end());
  return true;
#endif  // defined(NTLM_SSPI)
}

// static
std::wstring HttpAuthHandlerNTLM::CreateSPN(const GURL& origin) {
  // The service principal name of the destination server.  See
  // http://msdn.microsoft.com/en-us/library/ms677949%28VS.85%29.aspx
  std::wstring target(L"HTTP/");
  target.append(ASCIIToWide(GetHostAndPort(origin)));
  return target;
}

}  // namespace net
<commit_msg>Fail rather than crash if username+password are unspecified for NTLM on Linux+OSX.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/http/http_auth_handler_ntlm.h"

#if !defined(NTLM_SSPI)
#include "base/base64.h"
#endif
#include "base/logging.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "net/base/net_errors.h"
#include "net/base/net_util.h"

namespace net {

int HttpAuthHandlerNTLM::GenerateAuthTokenImpl(
    const string16* username,
    const string16* password,
    const HttpRequestInfo* request,
    CompletionCallback* callback,
    std::string* auth_token) {
#if defined(NTLM_SSPI)
  return auth_sspi_.GenerateAuthToken(
      username,
      password,
      CreateSPN(origin_),
      auth_token);
#else  // !defined(NTLM_SSPI)
  // TODO(cbentzel): Shouldn't be hitting this case.
  if (!username || !password) {
    LOG(ERROR) << "Username and password are expected to be non-NULL.";
    return ERR_MISSING_AUTH_CREDENTIALS;
  }
  // TODO(wtc): See if we can use char* instead of void* for in_buf and
  // out_buf.  This change will need to propagate to GetNextToken,
  // GenerateType1Msg, and GenerateType3Msg, and perhaps further.
  const void* in_buf;
  void* out_buf;
  uint32 in_buf_len, out_buf_len;
  std::string decoded_auth_data;

  // |username| may be in the form "DOMAIN\user".  Parse it into the two
  // components.
  string16 domain;
  string16 user;
  const char16 backslash_character = '\\';
  size_t backslash_idx = username->find(backslash_character);
  if (backslash_idx == string16::npos) {
    user = *username;
  } else {
    domain = username->substr(0, backslash_idx);
    user = username->substr(backslash_idx + 1);
  }
  domain_ = domain;
  username_ = user;
  password_ = *password;

  // Initial challenge.
  if (auth_data_.empty()) {
    in_buf_len = 0;
    in_buf = NULL;
    int rv = InitializeBeforeFirstChallenge();
    if (rv != OK)
      return rv;
  } else {
    if (!base::Base64Decode(auth_data_, &decoded_auth_data)) {
      LOG(ERROR) << "Unexpected problem Base64 decoding.";
      return ERR_UNEXPECTED;
    }
    in_buf_len = decoded_auth_data.length();
    in_buf = decoded_auth_data.data();
  }

  int rv = GetNextToken(in_buf, in_buf_len, &out_buf, &out_buf_len);
  if (rv != OK)
    return rv;

  // Base64 encode data in output buffer and prepend "NTLM ".
  std::string encode_input(static_cast<char*>(out_buf), out_buf_len);
  std::string encode_output;
  bool base64_rv = base::Base64Encode(encode_input, &encode_output);
  // OK, we are done with |out_buf|
  free(out_buf);
  if (!base64_rv) {
    LOG(ERROR) << "Unexpected problem Base64 encoding.";
    return ERR_UNEXPECTED;
  }
  *auth_token = std::string("NTLM ") + encode_output;
  return OK;
#endif
}

// The NTLM challenge header looks like:
//   WWW-Authenticate: NTLM auth-data
bool HttpAuthHandlerNTLM::ParseChallenge(
    HttpAuth::ChallengeTokenizer* tok) {
  scheme_ = "ntlm";
  score_ = 3;
  properties_ = ENCRYPTS_IDENTITY | IS_CONNECTION_BASED;

#if defined(NTLM_SSPI)
  return auth_sspi_.ParseChallenge(tok);
#else
  auth_data_.clear();

  // Verify the challenge's auth-scheme.
  if (!tok->valid() || !LowerCaseEqualsASCII(tok->scheme(), "ntlm"))
    return false;

  tok->set_expect_base64_token(true);
  if (tok->GetNext())
    auth_data_.assign(tok->value_begin(), tok->value_end());
  return true;
#endif  // defined(NTLM_SSPI)
}

// static
std::wstring HttpAuthHandlerNTLM::CreateSPN(const GURL& origin) {
  // The service principal name of the destination server.  See
  // http://msdn.microsoft.com/en-us/library/ms677949%28VS.85%29.aspx
  std::wstring target(L"HTTP/");
  target.append(ASCIIToWide(GetHostAndPort(origin)));
  return target;
}

}  // namespace net
<|endoftext|>


<commit_before>/******************************************************************************//**
 * @copyright (c) RDO-Team, 2011
 * @file      choice_from.cpp
 * @authors    ,  ,
 * @date      unknown
 * @brief     RDOCalc
 * @indent    4T
 *********************************************************************************/

// **************************************************************************** PCH
#include "rdo_lib/rdo_runtime/pch.h"
// *********************************************************************** INCLUDES
#include <limits>
// *********************************************************************** SYNOPSIS
#include "rdo_lib/rdo_runtime/calc/choice_from.h"
#include "rdo_lib/rdo_runtime/rdo_runtime.h"
#include "rdo_lib/rdo_runtime/rdo_activity.h"
#include "rdo_lib/rdo_runtime/rdoprocess.h"
// ********************************************************************************

OPEN_RDO_RUNTIME_NAMESPACE

// ********************************************************************************
// ******************** RDOSelectResourceNonExistCalc
// ********************************************************************************
REF(RDOValue) RDOSelectResourceNonExistCalc::doCalc(CREF(LPRDORuntime) pRuntime)
{
	pRuntime->getCurrentActivity()->setRelRes(rel_res_id, -1);
	return m_value;
}

// ********************************************************************************
// ******************** RDOCalcCreateNumberedResource
// ********************************************************************************
RDOCalcCreateNumberedResource::RDOCalcCreateNumberedResource(int _type, rbool _traceFlag, CREF(std::vector<RDOValue>) _paramsCalcs, int _number, rbool _isPermanent)
	: m_pType    (_type       )
	, traceFlag  (_traceFlag  )
	, number     (_number     )
	, isPermanent(_isPermanent)
{}

REF(RDOValue) RDOCalcCreateNumberedResource::doCalc(CREF(LPRDORuntime) pRuntime)
{
	NEVER_REACH_HERE;
	return m_value;
}

// ********************************************************************************
// ******************** RDOCalcCreateProcessResource
// ********************************************************************************
RDOCalcCreateProcessResource::RDOCalcCreateProcessResource(int _type, rbool _traceFlag, CREF(std::vector<RDOValue>) _paramsCalcs, int _number, rbool _isPermanent)
	: m_pType    (_type       )
	, traceFlag  (_traceFlag  )
	, number     (_number     )
	, isPermanent(_isPermanent)
{}

REF(RDOValue) RDOCalcCreateProcessResource::doCalc(CREF(LPRDORuntime) pRuntime)
{
	NEVER_REACH_HERE;
	return m_value;
}

// ********************************************************************************
// ******************** RDOCalcCreateResource
// ********************************************************************************
RDOCalcCreateResource::RDOCalcCreateResource(CREF(LPIResourceType) pType, CREF(std::vector<RDOValue>) rParamsCalcs, rbool traceFlag, rbool permanentFlag, ruint relResID)
	: m_pResType     (pType        )
	, m_traceFlag    (traceFlag    )
	, m_permanentFlag(permanentFlag)
	, m_relResID     (relResID     )
{
	m_paramsCalcs.insert(m_paramsCalcs.begin(), rParamsCalcs.begin(), rParamsCalcs.end());
	/// @todo   ASSERT
	if (m_permanentFlag && m_relResID > 0) NEVER_REACH_HERE; //
}

REF(RDOValue) RDOCalcCreateResource::doCalc(CREF(LPRDORuntime) pRuntime)
{
	LPRDOResource pResource = m_pResType->createRes(pRuntime, m_paramsCalcs, m_traceFlag, m_permanentFlag);
	if (m_relResID)
		pRuntime->getCurrentActivity()->setRelRes(m_relResID, pResource->getTraceID());
	return m_value; // just to return something
}

// ********************************************************************************
// ******************** RDOSelectResourceCalc
// ********************************************************************************
RDOSelectResourceCalc::RDOSelectResourceCalc(int _rel_res_id, CREF(LPRDOCalc) _choice_calc, CREF(LPRDOCalc) _order_calc, Type _order_type)
	: rel_res_id (_rel_res_id )
	, choice_calc(_choice_calc)
	, order_calc (_order_calc )
	, order_type (_order_type )
{}

REF(RDOValue) RDOSelectResourceDirectCalc::doCalc(CREF(LPRDORuntime) pRuntime)
{
	pRuntime->getCurrentActivity()->setRelRes(rel_res_id, res_id);
	if (choice_calc && !choice_calc->calcValue(pRuntime).getAsBool())
	{
		pRuntime->getCurrentActivity()->setRelRes(rel_res_id, -1);
		m_value = 0;
		return m_value;
	}
	m_value = 1;
	return m_value;
}

REF(RDOValue) RDOSelectResourceByTypeCalc::doCalc(CREF(LPRDORuntime) pRuntime)
{
	RDOValue maxVal   = -DBL_MAX;
	RDOValue minVal   = DBL_MAX;
	int res_minmax_id = -1;
	RDORuntime::ResCIterator end = pRuntime->res_end();
	for (RDORuntime::ResCIterator it = pRuntime->res_begin(); it != end; it++)
	{
		if (*it && (*it)->checkType(resType))
		{
			int res_id = (*it)->getTraceID();

			switch (order_type)
			{
				case order_empty:
				case order_first:
				{
					pRuntime->getCurrentActivity()->setRelRes(rel_res_id, res_id);
					if (choice_calc && !choice_calc->calcValue(pRuntime).getAsBool())
					{
						pRuntime->getCurrentActivity()->setRelRes(rel_res_id, -1);
						continue;
					}
					m_value = 1;
					return m_value;
				}
				case order_with_min:
				{
					pRuntime->getCurrentActivity()->setRelRes(rel_res_id, res_id);
					if (choice_calc && !choice_calc->calcValue(pRuntime).getAsBool())
					{
						pRuntime->getCurrentActivity()->setRelRes(rel_res_id, -1);
						continue;
					}
					RDOValue tmp = order_calc->calcValue(pRuntime);
					if (tmp < minVal)
					{
						minVal        = tmp;
						res_minmax_id = res_id;
					}
					break;
				}
				case order_with_max:
				{
					pRuntime->getCurrentActivity()->setRelRes(rel_res_id, res_id);
					if (choice_calc && !choice_calc->calcValue(pRuntime).getAsBool())
					{
						pRuntime->getCurrentActivity()->setRelRes(rel_res_id, -1);
						continue;
					}
					RDOValue tmp = order_calc->calcValue(pRuntime);
					if (tmp > maxVal)
					{
						maxVal        = tmp;
						res_minmax_id = res_id;
					}
					break;
				}
			}
		}
	}

	if (res_minmax_id != -1)
	{
		pRuntime->getCurrentActivity()->setRelRes(rel_res_id, res_minmax_id);
		m_value = 1;
		return m_value;
	}
	m_value = 0;
	return m_value;
}

void RDOSelectResourceCommonCalc::getBest(REF(std::vector< std::vector<int> >) allNumbs, ruint level, REF(std::vector<int>) res, REF(RDOValue) bestVal, CREF(LPRDORuntime) pRuntime, REF(rbool) hasBest) const
{
	if (level >= allNumbs.size())
	{
		for (ruint i = 0; i < resSelectors.size(); i++)
		{
			if (!resSelectors.at(i)->callChoice(pRuntime))
			{
				return; // state not valid
			}
		}
		RDOValue newVal = const_cast<PTR(RDOSelectResourceCommonCalc)>(this)->choice_calc->calcValue(pRuntime);
		if (!hasBest || (useCommonWithMax && (newVal > bestVal)) ||
		   (!useCommonWithMax && (newVal < bestVal))) // found better value
		{
			for (ruint i = 0; i < resSelectors.size(); i++)
			{
				res.at(i) = pRuntime->getCurrentActivity()->getResByRelRes(i);
			}
			bestVal = newVal;
			hasBest = true;
		}
		return;
	}
	REF(std::vector<int>) ourLevel = allNumbs.at(level);
	for (ruint i = 0; i < ourLevel.size(); i++)
	{
		pRuntime->getCurrentActivity()->setRelRes(level, ourLevel.at(i));
		getBest(allNumbs, level+1, res, bestVal, pRuntime, hasBest);
	}
}

rbool RDOSelectResourceCommonCalc::getFirst(REF(std::vector< std::vector<int> >) allNumbs, ruint level, CREF(LPRDORuntime) pRuntime) const
{
	if (level >= allNumbs.size())
	{
		for (ruint i = 0; i < resSelectors.size(); i++)
		{
			if (!resSelectors.at(i)->callChoice(pRuntime))
			{
				return false;
			}
		}
		return true;
	}
	REF(std::vector<int>) ourLevel = allNumbs.at(level);
	for (ruint i = 0; i < ourLevel.size(); i++)
	{
		pRuntime->getCurrentActivity()->setRelRes(level, ourLevel.at(i));
		if (getFirst(allNumbs, level+1, pRuntime)) return true;
	}
	return false;
}

//rbool RDOSelectResourceCommonCalc::getFirst(REF(std::vector< std::vector<int> >) allNumbs, int level,CREF(LPRDORuntime) pRuntime) const
//{
//	if (level <= 0) {
//		for (int i = 0; i < resSelectors.size(); i++) {
//			if (!resSelectors.at(i)->callChoice(pRuntime)) {
//				return false;
//			}
//		}
//		return true;
//	} else {
//		level--;
//		REF(std::vector<int>) ourLevel = allNumbs.at(level);
//		for (int i = 0; i < ourLevel.size(); i++) {
//			pRuntime->setRelRes(level, ourLevel.at(i));
//			if (getFirst(allNumbs, level, pRuntime)) return true;
//		}
//	}
//	return false;
//}

REF(RDOValue) RDOSelectResourceCommonCalc::doCalc(CREF(LPRDORuntime) pRuntime)
{
	std::vector< std::vector<int> > allNumbs;
	std::vector<int> res;
	for (ruint i = 0; i < resSelectors.size(); i++)
	{
		allNumbs.push_back(resSelectors.at(i)->getPossibleNumbers(pRuntime));
		res.push_back(pRuntime->getCurrentActivity()->getResByRelRes(i));
	}
	if (!choice_calc)
	{
		// first
//		if (getFirst(allNumbs, allNumbs.size(), pRuntime)) {
//			return true;
//		}
		if (getFirst(allNumbs, 0, pRuntime))
		{
			m_value = 1;
			return m_value;
		}
	}
	else
	{
		// with_min / with_max
		RDOValue bestVal = 0;
		rbool found = false;
		getBest(allNumbs, 0, res, bestVal, pRuntime, found);
		if (found)
		{
			for (ruint i = 0; i < res.size(); i++)
			{
				pRuntime->getCurrentActivity()->setRelRes(i, res.at(i));
			}
			m_value = 1;
			return m_value;
		}
	}
	m_value = 0;
	return m_value;
}

std::vector<int> RDOSelectResourceDirectCommonCalc::getPossibleNumbers(CREF(LPRDORuntime) pRuntime) const
{
	std::vector<int> res;
	res.push_back(res_id);
	return res;
}

std::vector<int> RDOSelectResourceByTypeCommonCalc::getPossibleNumbers(CREF(LPRDORuntime) pRuntime) const
{
	std::vector<int> res;
	RDORuntime::ResCIterator end = pRuntime->res_end();
	for (RDORuntime::ResCIterator it = pRuntime->res_begin(); it != end; it++)
	{
		if (*it == NULL)
			continue;

		if (!(*it)->checkType(resType))
			continue;

		res.push_back((*it)->getTraceID());
	}
	return res;
}

rbool RDOSelectResourceDirectCommonCalc::callChoice(CREF(LPRDORuntime) pRuntime) const
{
	return (choice_calc && !const_cast<PTR(RDOSelectResourceDirectCommonCalc)>(this)->choice_calc->calcValue(pRuntime).getAsBool()) ? false : true;
}

rbool RDOSelectResourceByTypeCommonCalc::callChoice(CREF(LPRDORuntime) pRuntime) const
{
	return (choice_calc && !const_cast<PTR(RDOSelectResourceByTypeCommonCalc)>(this)->choice_calc->calcValue(pRuntime).getAsBool()) ? false : true;
}

IRDOSelectResourceCommon::IRDOSelectResourceCommon()
{}

IRDOSelectResourceCommon::~IRDOSelectResourceCommon()
{}

RDOSelectResourceDirectCommonCalc::~RDOSelectResourceDirectCommonCalc()
{}

RDOSelectResourceByTypeCommonCalc::~RDOSelectResourceByTypeCommonCalc()
{}

CLOSE_RDO_RUNTIME_NAMESPACE
<commit_msg> - форматирование  - перекомпоновка по классам<commit_after>/******************************************************************************//**
 * @copyright (c) RDO-Team, 2011
 * @file      choice_from.cpp
 * @authors    ,  ,
 * @date      unknown
 * @brief     RDOCalc
 * @indent    4T
 *********************************************************************************/

// **************************************************************************** PCH
#include "rdo_lib/rdo_runtime/pch.h"
// *********************************************************************** INCLUDES
#include <limits>
// *********************************************************************** SYNOPSIS
#include "rdo_lib/rdo_runtime/calc/choice_from.h"
#include "rdo_lib/rdo_runtime/rdo_runtime.h"
#include "rdo_lib/rdo_runtime/rdo_activity.h"
#include "rdo_lib/rdo_runtime/rdoprocess.h"
// ********************************************************************************

OPEN_RDO_RUNTIME_NAMESPACE

// ********************************************************************************
// ******************** RDOSelectResourceNonExistCalc
// ********************************************************************************
REF(RDOValue) RDOSelectResourceNonExistCalc::doCalc(CREF(LPRDORuntime) pRuntime)
{
	pRuntime->getCurrentActivity()->setRelRes(rel_res_id, -1);
	return m_value;
}

// ********************************************************************************
// ******************** RDOCalcCreateNumberedResource
// ********************************************************************************
RDOCalcCreateNumberedResource::RDOCalcCreateNumberedResource(int _type, rbool _traceFlag, CREF(std::vector<RDOValue>) _paramsCalcs, int _number, rbool _isPermanent)
	: m_pType    (_type       )
	, traceFlag  (_traceFlag  )
	, number     (_number     )
	, isPermanent(_isPermanent)
{}

REF(RDOValue) RDOCalcCreateNumberedResource::doCalc(CREF(LPRDORuntime) pRuntime)
{
	NEVER_REACH_HERE;
	return m_value;
}

// ********************************************************************************
// ******************** RDOCalcCreateProcessResource
// ********************************************************************************
RDOCalcCreateProcessResource::RDOCalcCreateProcessResource(int _type, rbool _traceFlag, CREF(std::vector<RDOValue>) _paramsCalcs, int _number, rbool _isPermanent)
	: m_pType    (_type       )
	, traceFlag  (_traceFlag  )
	, number     (_number     )
	, isPermanent(_isPermanent)
{}

REF(RDOValue) RDOCalcCreateProcessResource::doCalc(CREF(LPRDORuntime) pRuntime)
{
	NEVER_REACH_HERE;
	return m_value;
}

// ********************************************************************************
// ******************** RDOCalcCreateResource
// ********************************************************************************
RDOCalcCreateResource::RDOCalcCreateResource(CREF(LPIResourceType) pType, CREF(std::vector<RDOValue>) rParamsCalcs, rbool traceFlag, rbool permanentFlag, ruint relResID)
	: m_pResType     (pType        )
	, m_traceFlag    (traceFlag    )
	, m_permanentFlag(permanentFlag)
	, m_relResID     (relResID     )
{
	m_paramsCalcs.insert(m_paramsCalcs.begin(), rParamsCalcs.begin(), rParamsCalcs.end());
	/// @todo   ASSERT
	if (m_permanentFlag && m_relResID > 0) NEVER_REACH_HERE; //
}

REF(RDOValue) RDOCalcCreateResource::doCalc(CREF(LPRDORuntime) pRuntime)
{
	LPRDOResource pResource = m_pResType->createRes(pRuntime, m_paramsCalcs, m_traceFlag, m_permanentFlag);
	if (m_relResID)
		pRuntime->getCurrentActivity()->setRelRes(m_relResID, pResource->getTraceID());
	return m_value; // just to return something
}

// ********************************************************************************
// ******************** RDOSelectResourceCalc
// ********************************************************************************
RDOSelectResourceCalc::RDOSelectResourceCalc(int _rel_res_id, CREF(LPRDOCalc) _choice_calc, CREF(LPRDOCalc) _order_calc, Type _order_type)
	: rel_res_id (_rel_res_id )
	, choice_calc(_choice_calc)
	, order_calc (_order_calc )
	, order_type (_order_type )
{}

// ********************************************************************************
// ******************** RDOSelectResourceDirectCalc
// ********************************************************************************
REF(RDOValue) RDOSelectResourceDirectCalc::doCalc(CREF(LPRDORuntime) pRuntime)
{
	pRuntime->getCurrentActivity()->setRelRes(rel_res_id, res_id);
	if (choice_calc && !choice_calc->calcValue(pRuntime).getAsBool())
	{
		pRuntime->getCurrentActivity()->setRelRes(rel_res_id, -1);
		m_value = 0;
		return m_value;
	}
	m_value = 1;
	return m_value;
}

// ********************************************************************************
// ******************** RDOSelectResourceByTypeCalc
// ********************************************************************************
REF(RDOValue) RDOSelectResourceByTypeCalc::doCalc(CREF(LPRDORuntime) pRuntime)
{
	RDOValue maxVal   = -DBL_MAX;
	RDOValue minVal   = DBL_MAX;
	int res_minmax_id = -1;
	RDORuntime::ResCIterator end = pRuntime->res_end();
	for (RDORuntime::ResCIterator it = pRuntime->res_begin(); it != end; it++)
	{
		if (*it && (*it)->checkType(resType))
		{
			int res_id = (*it)->getTraceID();

			switch (order_type)
			{
				case order_empty:
				case order_first:
				{
					pRuntime->getCurrentActivity()->setRelRes(rel_res_id, res_id);
					if (choice_calc && !choice_calc->calcValue(pRuntime).getAsBool())
					{
						pRuntime->getCurrentActivity()->setRelRes(rel_res_id, -1);
						continue;
					}
					m_value = 1;
					return m_value;
				}
				case order_with_min:
				{
					pRuntime->getCurrentActivity()->setRelRes(rel_res_id, res_id);
					if (choice_calc && !choice_calc->calcValue(pRuntime).getAsBool())
					{
						pRuntime->getCurrentActivity()->setRelRes(rel_res_id, -1);
						continue;
					}
					RDOValue tmp = order_calc->calcValue(pRuntime);
					if (tmp < minVal)
					{
						minVal        = tmp;
						res_minmax_id = res_id;
					}
					break;
				}
				case order_with_max:
				{
					pRuntime->getCurrentActivity()->setRelRes(rel_res_id, res_id);
					if (choice_calc && !choice_calc->calcValue(pRuntime).getAsBool())
					{
						pRuntime->getCurrentActivity()->setRelRes(rel_res_id, -1);
						continue;
					}
					RDOValue tmp = order_calc->calcValue(pRuntime);
					if (tmp > maxVal)
					{
						maxVal        = tmp;
						res_minmax_id = res_id;
					}
					break;
				}
			}
		}
	}

	if (res_minmax_id != -1)
	{
		pRuntime->getCurrentActivity()->setRelRes(rel_res_id, res_minmax_id);
		m_value = 1;
		return m_value;
	}
	m_value = 0;
	return m_value;
}

// ********************************************************************************
// ******************** RDOSelectResourceCommonCalc
// ********************************************************************************
void RDOSelectResourceCommonCalc::getBest(REF(std::vector< std::vector<int> >) allNumbs, ruint level, REF(std::vector<int>) res, REF(RDOValue) bestVal, CREF(LPRDORuntime) pRuntime, REF(rbool) hasBest) const
{
	if (level >= allNumbs.size())
	{
		for (ruint i = 0; i < resSelectors.size(); i++)
		{
			if (!resSelectors.at(i)->callChoice(pRuntime))
			{
				return; // state not valid
			}
		}
		RDOValue newVal = const_cast<PTR(RDOSelectResourceCommonCalc)>(this)->choice_calc->calcValue(pRuntime);
		if (!hasBest || (useCommonWithMax && (newVal > bestVal)) ||
		   (!useCommonWithMax && (newVal < bestVal))) // found better value
		{
			for (ruint i = 0; i < resSelectors.size(); i++)
			{
				res.at(i) = pRuntime->getCurrentActivity()->getResByRelRes(i);
			}
			bestVal = newVal;
			hasBest = true;
		}
		return;
	}
	REF(std::vector<int>) ourLevel = allNumbs.at(level);
	for (ruint i = 0; i < ourLevel.size(); i++)
	{
		pRuntime->getCurrentActivity()->setRelRes(level, ourLevel.at(i));
		getBest(allNumbs, level+1, res, bestVal, pRuntime, hasBest);
	}
}

rbool RDOSelectResourceCommonCalc::getFirst(REF(std::vector< std::vector<int> >) allNumbs, ruint level, CREF(LPRDORuntime) pRuntime) const
{
	if (level >= allNumbs.size())
	{
		for (ruint i = 0; i < resSelectors.size(); i++)
		{
			if (!resSelectors.at(i)->callChoice(pRuntime))
			{
				return false;
			}
		}
		return true;
	}
	REF(std::vector<int>) ourLevel = allNumbs.at(level);
	for (ruint i = 0; i < ourLevel.size(); i++)
	{
		pRuntime->getCurrentActivity()->setRelRes(level, ourLevel.at(i));
		if (getFirst(allNumbs, level+1, pRuntime)) return true;
	}
	return false;
}

//rbool RDOSelectResourceCommonCalc::getFirst(REF(std::vector< std::vector<int> >) allNumbs, int level,CREF(LPRDORuntime) pRuntime) const
//{
//	if (level <= 0) {
//		for (int i = 0; i < resSelectors.size(); i++) {
//			if (!resSelectors.at(i)->callChoice(pRuntime)) {
//				return false;
//			}
//		}
//		return true;
//	} else {
//		level--;
//		REF(std::vector<int>) ourLevel = allNumbs.at(level);
//		for (int i = 0; i < ourLevel.size(); i++) {
//			pRuntime->setRelRes(level, ourLevel.at(i));
//			if (getFirst(allNumbs, level, pRuntime)) return true;
//		}
//	}
//	return false;
//}

REF(RDOValue) RDOSelectResourceCommonCalc::doCalc(CREF(LPRDORuntime) pRuntime)
{
	std::vector< std::vector<int> > allNumbs;
	std::vector<int> res;
	for (ruint i = 0; i < resSelectors.size(); i++)
	{
		allNumbs.push_back(resSelectors.at(i)->getPossibleNumbers(pRuntime));
		res.push_back(pRuntime->getCurrentActivity()->getResByRelRes(i));
	}
	if (!choice_calc)
	{
		// first
//		if (getFirst(allNumbs, allNumbs.size(), pRuntime)) {
//			return true;
//		}
		if (getFirst(allNumbs, 0, pRuntime))
		{
			m_value = 1;
			return m_value;
		}
	}
	else
	{
		// with_min / with_max
		RDOValue bestVal = 0;
		rbool found = false;
		getBest(allNumbs, 0, res, bestVal, pRuntime, found);
		if (found)
		{
			for (ruint i = 0; i < res.size(); i++)
			{
				pRuntime->getCurrentActivity()->setRelRes(i, res.at(i));
			}
			m_value = 1;
			return m_value;
		}
	}
	m_value = 0;
	return m_value;
}

// ********************************************************************************
// ******************** RDOSelectResourceDirectCommonCalc
// ********************************************************************************
std::vector<int> RDOSelectResourceDirectCommonCalc::getPossibleNumbers(CREF(LPRDORuntime) pRuntime) const
{
	std::vector<int> res;
	res.push_back(res_id);
	return res;
}

rbool RDOSelectResourceDirectCommonCalc::callChoice(CREF(LPRDORuntime) pRuntime) const
{
	return (choice_calc && !const_cast<PTR(RDOSelectResourceDirectCommonCalc)>(this)->choice_calc->calcValue(pRuntime).getAsBool()) ? false : true;
}

RDOSelectResourceDirectCommonCalc::~RDOSelectResourceDirectCommonCalc()
{}

// ********************************************************************************
// ******************** RDOSelectResourceByTypeCommonCalc
// ********************************************************************************
std::vector<int> RDOSelectResourceByTypeCommonCalc::getPossibleNumbers(CREF(LPRDORuntime) pRuntime) const
{
	std::vector<int> res;
	RDORuntime::ResCIterator end = pRuntime->res_end();
	for (RDORuntime::ResCIterator it = pRuntime->res_begin(); it != end; it++)
	{
		if (*it == NULL)
			continue;

		if (!(*it)->checkType(resType))
			continue;

		res.push_back((*it)->getTraceID());
	}
	return res;
}

rbool RDOSelectResourceByTypeCommonCalc::callChoice(CREF(LPRDORuntime) pRuntime) const
{
	return (choice_calc && !const_cast<PTR(RDOSelectResourceByTypeCommonCalc)>(this)->choice_calc->calcValue(pRuntime).getAsBool()) ? false : true;
}

RDOSelectResourceByTypeCommonCalc::~RDOSelectResourceByTypeCommonCalc()
{}

// ********************************************************************************
// ******************** IRDOSelectResourceCommon
// ********************************************************************************
IRDOSelectResourceCommon::IRDOSelectResourceCommon()
{}

IRDOSelectResourceCommon::~IRDOSelectResourceCommon()
{}

CLOSE_RDO_RUNTIME_NAMESPACE
<|endoftext|>