<commit_before>#include "phune_rest_jamp.h"

static s3eCallback onResultPending;
static PhuneMatch *currentMatch = NULL;

static int32 onNullReturn(void *, void*){
	return 0;
}

static int32 onStartMatchReturn(void *data, void* userData){
	currentMatch = static_cast<PhuneMatch*>(data);
	onResultPending(NULL, userData);
	return 0;
}

int32 PhuneRestJamp::Init(s3eCallback onResult, s3eCallback onError, void *userData){
	return PhuneRest::Init(onResult, onError, userData);
}

int32 PhuneRestJamp::Login(s3eWebView* g_WebView, s3eCallback onResult, s3eCallback onError, void *userData){
	return PhuneRest::Login(g_WebView, onResult, onError, userData);
}

int32 PhuneRestJamp::GetMe(s3eCallback onResult, s3eCallback onError, void *userData){
	return PhuneRest::GetMe(onResult, onError, userData);
}

int32 PhuneRestJamp::StartMatch(JampGameId gameId, s3eCallback onResult, s3eCallback onError, void *userData){
	char buffer[50];
	sprintf(buffer, "%d", gameId);
	std::string s = std::string(buffer);
	onResultPending = onResult;
	return PhuneRest::StartMatch(s.c_str(), onStartMatchReturn, onError, userData);
}

int32 PhuneRestJamp::EndMatch(JampGameId gameId, std::string level, JampScore score, PlayerStatus status, s3eCallback onResult, s3eCallback onError, void *userData){
	if (currentMatch == NULL){
		onError(NULL, NULL);
		return 0;
	}
	char buffer[50];
	sprintf(buffer, "%d", gameId);
	std::string s = std::string(buffer);

	std::string s3 = std::string(SCORE_LEVEL_KEY_PREFIX);
	s3.append(level);

	score.matchId = currentMatch->matchId;

	PhunePlayer player;
	player.score = score.score;
	player.status = status;
	player.id = currentMatch->playerId;

	int64 t = getCurrentTime();

	//Send the result of the match
	PhuneRest::EndMatch(score.matchId, player, onNullReturn, onError);

    IwTrace(PHUNE, ("Creating map begin"));
    std::map<int64, JsonListObject<JsonString> > map;
    int consecutivePerfects = 0;
    int bestSequence = -1;
    bool allPerfects = true;
	//aggregate cells performance
    for (std::vector<JampCellPerformance>::iterator it = score.cellsPerformance.elements.begin(); it != score.cellsPerformance.elements.end(); it++){

        //Use the notes for events
        if(it->useNoteEvaluation){
            for (std::vector<JampNotePerformance>::iterator it2 = it->notesPerformance.elements.begin(); it2 != it->notesPerformance.elements.end(); it2++){
                if (it2->classification == PERFECT) {
                    consecutivePerfects++;
                }
                else{
                    allPerfects = false;
                    if(consecutivePerfects > 3 && consecutivePerfects > bestSequence){
                        bestSequence = consecutivePerfects;
                    }
                    consecutivePerfects = 0;
                }
            }

        }
        //use the cell for events
        else{
            if (it->classification == PERFECT) {
                consecutivePerfects++;
            }
            else{
                allPerfects = false;
                if(consecutivePerfects > 3 && consecutivePerfects > bestSequence){
                    bestSequence = consecutivePerfects;
                }
                consecutivePerfects = 0;
            }
        }

        //found
        if (map.find(it->cellId) == map.end()) {
            JsonListObject<JsonString> list;
            it->timeStamp = t;
            JsonString js;
            js.Deserialize(it->Serialize());
            list.pushElement(js);
            map.insert(std::make_pair(it->cellId,list));
        }
        else {
            it->timeStamp = t;
            std::string aux2;
            JsonString js2;
            js2.Deserialize(it->Serialize());
            map.find(it->cellId)->second.pushElement(js2);
        }
    }
    IwTrace(PHUNE, ("Creating map end"));
    IwTrace(PHUNE, ("Sending cells begin"));
    //store the Cell performances
    for (std::map<int64, JsonListObject<JsonString> >::iterator itMap = map.begin(); itMap != map.end(); itMap++){

        if (itMap->first > 0) {

            char buffer4[50];
            sprintf(buffer4, "%s%lld", CELL_PERFORMACE_PREFIX, itMap->first);
            std::string key_cell = std::string(buffer4);

            std::string out = itMap->second.Serialize();

            IwTrace(PHUNE, ("Sending cell %lld begin", itMap->first));

            PhuneRestBase::StoreGameDataJsonBatch(s.c_str(), key_cell.c_str(), itMap->second.Serialize().c_str(), onNullReturn, onError, userData, true);

            IwTrace(PHUNE, ("Sending cell %lld end", itMap->first));
        }
        else{
            IwTrace(PHUNE, ("Cell with invalid id:%lld. Ignoring...", itMap->first));
        }

    }
    IwTrace(PHUNE, ("Sending cells end"));

    //Send the events

    JsonListObject<GameTriggerdEvent> events;

    //consecutive perfects
    if(bestSequence != -1){
        ConsecutivePerfectsEvent cpe(bestSequence, gameId);

        cpe.playerId = currentMatch->playerId;

        events.pushElement(cpe);
    }

    //all perfects
    if(allPerfects){
        AllPerfectsEvent ape(gameId, level);
        ape.playerId = currentMatch->playerId;

        events.pushElement(ape);
    }

    if(events.elements.size() > 0){
        PhuneRest::StoreMatchEvents(events, score.matchId, onNullReturn, onError);
    }

	//store the score for the match
	score.timeStamp = t;
	PhuneRestBase::StoreGameDataJson(s.c_str(), s3.c_str(), score.Serialize().c_str(), onResult, onError, userData, true);

	currentMatch = NULL;

	return 0;
}

int32 PhuneRestJamp::GetHistoricScoreForLevelInGame(JampGameId gameId, const char *level, s3eCallback onResult, s3eCallback onError, void *userData){
	char buffer[50];
	sprintf(buffer, "%d", gameId);
	std::string s = std::string(buffer);

	std::string key_score = std::string(SCORE_LEVEL_KEY_PREFIX);
	key_score.append(level);
	return PhuneRestBase::GetGameDataJsonList(s.c_str(), key_score.c_str(), onResult, onError, userData);
}

int32 PhuneRestJamp::StorePackInfoInGame(JampGameId gameId, JampPack pack, s3eCallback onResult, s3eCallback onError, void *userData){
	char buffer[50];
	sprintf(buffer, "%d", gameId);
	std::string s = std::string(buffer);

	char buffer2[50];
	sprintf(buffer2, "%s%d", PACK_PREFIX, gameId);
	std::string s2 = std::string(buffer2);

	return PhuneRestBase::StoreGameDataJson(s.c_str(), s2.c_str(), pack.Serialize().c_str(), onResult, onError, userData);
}

int32 PhuneRestJamp::GetPackInfoInGame(JampGameId gameId, int64 packid, s3eCallback onResult, s3eCallback onError, void *userData){
	char buffer[50];
	sprintf(buffer, "%d", gameId);
	std::string s = std::string(buffer);

	char buffer2[50];
	sprintf(buffer2, "%s%d", PACK_PREFIX, gameId);
	std::string s2 = std::string(buffer2);

	return PhuneRestBase::GetGameDataJson(s.c_str(), s2.c_str(), onResult, onError, userData);
}

int32 PhuneRestJamp::StorePacksInGame(JampGameId gameId, JsonListObject<JampPack> packs, s3eCallback onResult, s3eCallback onError, void *userData){
	char buffer[50];
	sprintf(buffer, "%d", gameId);
	std::string s = std::string(buffer);

    int64 totalStars = 0;
    int64 starsWon = 0;

    for (std::vector<JampPack>::iterator it = packs.elements.begin(); it != packs.elements.end(); it++){
        totalStars += it->starsMax;
        starsWon += it->starsWon;
    }

    JampGameProgress gp;

    gp.progress = (starsWon/(float)totalStars)*100;

    PhuneRestBase::StoreGameDataJson(s.c_str(), GAME_PROGRESS_KEY, gp.Serialize().c_str(), onNullReturn, onError, NULL);

	return PhuneRestBase::StoreGameDataJsonList(s.c_str(), PACKS_KEY, packs, onResult, onError, userData);
}

int32 PhuneRestJamp::GetPacksInGame(JampGameId gameId, s3eCallback onResult, s3eCallback onError, void *userData){
	char buffer[50];
	sprintf(buffer, "%d", gameId);
	std::string s = std::string(buffer);

	return PhuneRestBase::GetGameDataJsonList(s.c_str(), PACKS_KEY, onResult, onError, userData);
}
<commit_msg>JAMP: Consecutive perfects corretion<commit_after>#include "phune_rest_jamp.h"

static s3eCallback onResultPending;
static PhuneMatch *currentMatch = NULL;

static int32 onNullReturn(void *, void*){
	return 0;
}

static int32 onStartMatchReturn(void *data, void* userData){
	currentMatch = static_cast<PhuneMatch*>(data);
	onResultPending(NULL, userData);
	return 0;
}

int32 PhuneRestJamp::Init(s3eCallback onResult, s3eCallback onError, void *userData){
	return PhuneRest::Init(onResult, onError, userData);
}

int32 PhuneRestJamp::Login(s3eWebView* g_WebView, s3eCallback onResult, s3eCallback onError, void *userData){
	return PhuneRest::Login(g_WebView, onResult, onError, userData);
}

int32 PhuneRestJamp::GetMe(s3eCallback onResult, s3eCallback onError, void *userData){
	return PhuneRest::GetMe(onResult, onError, userData);
}

int32 PhuneRestJamp::StartMatch(JampGameId gameId, s3eCallback onResult, s3eCallback onError, void *userData){
	char buffer[50];
	sprintf(buffer, "%d", gameId);
	std::string s = std::string(buffer);
	onResultPending = onResult;
	return PhuneRest::StartMatch(s.c_str(), onStartMatchReturn, onError, userData);
}

int32 PhuneRestJamp::EndMatch(JampGameId gameId, std::string level, JampScore score, PlayerStatus status, s3eCallback onResult, s3eCallback onError, void *userData){
	if (currentMatch == NULL){
		onError(NULL, NULL);
		return 0;
	}
	char buffer[50];
	sprintf(buffer, "%d", gameId);
	std::string s = std::string(buffer);

	std::string s3 = std::string(SCORE_LEVEL_KEY_PREFIX);
	s3.append(level);

	score.matchId = currentMatch->matchId;

	PhunePlayer player;
	player.score = score.score;
	player.status = status;
	player.id = currentMatch->playerId;

	int64 t = getCurrentTime();

	//Send the result of the match
	PhuneRest::EndMatch(score.matchId, player, onNullReturn, onError);

    IwTrace(PHUNE, ("Creating map begin"));
    std::map<int64, JsonListObject<JsonString> > map;
    int consecutivePerfects = 0;
    int bestSequence = -1;
    bool allPerfects = true;
	//aggregate cells performance
    for (std::vector<JampCellPerformance>::iterator it = score.cellsPerformance.elements.begin(); it != score.cellsPerformance.elements.end(); it++){

        //Use the notes for events
        if(it->useNoteEvaluation){
            for (std::vector<JampNotePerformance>::iterator it2 = it->notesPerformance.elements.begin(); it2 != it->notesPerformance.elements.end(); it2++){
                if (it2->classification == PERFECT) {
                    consecutivePerfects++;
                }
                else{
                    allPerfects = false;
                    if(consecutivePerfects > 3 && consecutivePerfects > bestSequence){
                        bestSequence = consecutivePerfects;
                    }
                    consecutivePerfects = 0;
                }
            }

        }
        //use the cell for events
        else{
            if (it->classification == PERFECT) {
                consecutivePerfects++;
            }
            else{
                allPerfects = false;
                if(consecutivePerfects > 3 && consecutivePerfects > bestSequence){
                    bestSequence = consecutivePerfects;
                }
                consecutivePerfects = 0;
            }
        }

        //found
        if (map.find(it->cellId) == map.end()) {
            JsonListObject<JsonString> list;
            it->timeStamp = t;
            JsonString js;
            js.Deserialize(it->Serialize());
            list.pushElement(js);
            map.insert(std::make_pair(it->cellId,list));
        }
        else {
            it->timeStamp = t;
            std::string aux2;
            JsonString js2;
            js2.Deserialize(it->Serialize());
            map.find(it->cellId)->second.pushElement(js2);
        }
    }

    if(consecutivePerfects > 3 && consecutivePerfects > bestSequence){
        bestSequence = consecutivePerfects;
    }

    IwTrace(PHUNE, ("Creating map end"));
    IwTrace(PHUNE, ("Sending cells begin"));
    //store the Cell performances
    for (std::map<int64, JsonListObject<JsonString> >::iterator itMap = map.begin(); itMap != map.end(); itMap++){

        if (itMap->first > 0) {

            char buffer4[50];
            sprintf(buffer4, "%s%lld", CELL_PERFORMACE_PREFIX, itMap->first);
            std::string key_cell = std::string(buffer4);

            std::string out = itMap->second.Serialize();

            IwTrace(PHUNE, ("Sending cell %lld begin", itMap->first));

            PhuneRestBase::StoreGameDataJsonBatch(s.c_str(), key_cell.c_str(), itMap->second.Serialize().c_str(), onNullReturn, onError, userData, true);

            IwTrace(PHUNE, ("Sending cell %lld end", itMap->first));
        }
        else{
            IwTrace(PHUNE, ("Cell with invalid id:%lld. Ignoring...", itMap->first));
        }

    }
    IwTrace(PHUNE, ("Sending cells end"));

    //Send the events

    JsonListObject<GameTriggerdEvent> events;

    //consecutive perfects
    if(bestSequence != -1){
        ConsecutivePerfectsEvent cpe(bestSequence, gameId);

        cpe.playerId = currentMatch->playerId;

        events.pushElement(cpe);
    }

    //all perfects
    if(allPerfects){
        AllPerfectsEvent ape(gameId, level);
        ape.playerId = currentMatch->playerId;

        events.pushElement(ape);
    }

    if(events.elements.size() > 0){
        PhuneRest::StoreMatchEvents(events, score.matchId, onNullReturn, onError);
    }

	//store the score for the match
	score.timeStamp = t;
	PhuneRestBase::StoreGameDataJson(s.c_str(), s3.c_str(), score.Serialize().c_str(), onResult, onError, userData, true);

	currentMatch = NULL;

	return 0;
}

int32 PhuneRestJamp::GetHistoricScoreForLevelInGame(JampGameId gameId, const char *level, s3eCallback onResult, s3eCallback onError, void *userData){
	char buffer[50];
	sprintf(buffer, "%d", gameId);
	std::string s = std::string(buffer);

	std::string key_score = std::string(SCORE_LEVEL_KEY_PREFIX);
	key_score.append(level);
	return PhuneRestBase::GetGameDataJsonList(s.c_str(), key_score.c_str(), onResult, onError, userData);
}

int32 PhuneRestJamp::StorePackInfoInGame(JampGameId gameId, JampPack pack, s3eCallback onResult, s3eCallback onError, void *userData){
	char buffer[50];
	sprintf(buffer, "%d", gameId);
	std::string s = std::string(buffer);

	char buffer2[50];
	sprintf(buffer2, "%s%d", PACK_PREFIX, gameId);
	std::string s2 = std::string(buffer2);

	return PhuneRestBase::StoreGameDataJson(s.c_str(), s2.c_str(), pack.Serialize().c_str(), onResult, onError, userData);
}

int32 PhuneRestJamp::GetPackInfoInGame(JampGameId gameId, int64 packid, s3eCallback onResult, s3eCallback onError, void *userData){
	char buffer[50];
	sprintf(buffer, "%d", gameId);
	std::string s = std::string(buffer);

	char buffer2[50];
	sprintf(buffer2, "%s%d", PACK_PREFIX, gameId);
	std::string s2 = std::string(buffer2);

	return PhuneRestBase::GetGameDataJson(s.c_str(), s2.c_str(), onResult, onError, userData);
}

int32 PhuneRestJamp::StorePacksInGame(JampGameId gameId, JsonListObject<JampPack> packs, s3eCallback onResult, s3eCallback onError, void *userData){
	char buffer[50];
	sprintf(buffer, "%d", gameId);
	std::string s = std::string(buffer);

    int64 totalStars = 0;
    int64 starsWon = 0;

    for (std::vector<JampPack>::iterator it = packs.elements.begin(); it != packs.elements.end(); it++){
        totalStars += it->starsMax;
        starsWon += it->starsWon;
    }

    JampGameProgress gp;

    gp.progress = (starsWon/(float)totalStars)*100;

    PhuneRestBase::StoreGameDataJson(s.c_str(), GAME_PROGRESS_KEY, gp.Serialize().c_str(), onNullReturn, onError, NULL);

	return PhuneRestBase::StoreGameDataJsonList(s.c_str(), PACKS_KEY, packs, onResult, onError, userData);
}

int32 PhuneRestJamp::GetPacksInGame(JampGameId gameId, s3eCallback onResult, s3eCallback onError, void *userData){
	char buffer[50];
	sprintf(buffer, "%d", gameId);
	std::string s = std::string(buffer);

	return PhuneRestBase::GetGameDataJsonList(s.c_str(), PACKS_KEY, onResult, onError, userData);
}
<|endoftext|>


<commit_before>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc. 51 Franklin Street, Fifth Floor,
// Boston, MA  02110-1301  USA
//
//-----------------------------------------------------------------------el-

// This class
#include "grins/velocity_penalty_base.h"

// GRINS
#include "grins/inc_nav_stokes_macro.h"

// libMesh
#include "libmesh/parsed_function.h"
#include "libmesh/zero_function.h"

namespace GRINS
{

  template<class Mu>
  VelocityPenaltyBase<Mu>::VelocityPenaltyBase( const std::string& physics_name, const GetPot& input )
    : IncompressibleNavierStokesBase<Mu>(physics_name,
                                         incompressible_navier_stokes, /* "core" Physics name */
                                         input),
    _quadratic_scaling(false)
  {
    this->read_input_options(input);

    return;
  }

  template<class Mu>
  VelocityPenaltyBase<Mu>::~VelocityPenaltyBase()
  {
    return;
  }

  template<class Mu>
  void VelocityPenaltyBase<Mu>::read_input_options( const GetPot& input )
  {
    std::string base_physics_name = "VelocityPenalty";
    if (this->_physics_name == velocity_penalty2 ||
        this->_physics_name == velocity_penalty2_adjoint_stab)
      base_physics_name.push_back('2');

    std::string penalty_function =
      input("Physics/"+base_physics_name+"/penalty_function",
        std::string("0"));

    if (penalty_function == "0")
      this->normal_vector_function.reset
        (new libMesh::ZeroFunction<libMesh::Number>());
    else
      this->normal_vector_function.reset
        (new libMesh::ParsedFunction<libMesh::Number>(penalty_function));

    std::string base_function =
      input("Physics/"+base_physics_name+"/base_velocity",
        std::string("0"));

    if (penalty_function == "0" && base_function == "0")
      std::cout << "Warning! Zero VelocityPenalty specified!" << std::endl;

    if (base_function == "0")
      this->base_velocity_function.reset
        (new libMesh::ZeroFunction<libMesh::Number>());
    else
      this->base_velocity_function.reset
        (new libMesh::ParsedFunction<libMesh::Number>(base_function));

    _quadratic_scaling =
      input("Physics/"+base_physics_name+"/quadratic_scaling", false);
  }

  template<class Mu>
  bool VelocityPenaltyBase<Mu>::compute_force
    ( const libMesh::Point& point,
      const libMesh::Real time,
      const libMesh::NumberVectorValue& U,
      libMesh::NumberVectorValue& F,
      libMesh::NumberTensorValue *dFdU)
  {
    // Velocity discrepancy (current velocity minus base velocity)
    // normal to constraint plane, scaled by constraint penalty
    // value
    libmesh_assert(normal_vector_function.get());
    libmesh_assert(base_velocity_function.get());

    libMesh::DenseVector<libMesh::Number> output_vec(3);

    (*normal_vector_function)(point, time,
                              output_vec);

    libMesh::NumberVectorValue U_N(output_vec(0),
                                   output_vec(1),
                                   output_vec(2));

    (*base_velocity_function)(point, time,
                              output_vec);

    const libMesh::NumberVectorValue U_B(output_vec(0),
                                         output_vec(1),
                                         output_vec(2));

    const libMesh::NumberVectorValue U_Rel = U-U_B;

    // Old code
    // const libMesh::NumberVectorValue F1 = (U_Rel*U_N)*U_N; //

    // With correct sign and more natural normalization
    const libMesh::Number U_N_mag = std::sqrt(U_N*U_N);

    if (!U_N_mag)
      return false;

    const libMesh::NumberVectorValue U_N_unit = U_N/U_N_mag;

    F = -(U_Rel*U_N)*U_N_unit;

    if (dFdU)
      for (unsigned int i=0; i != 3; ++i)
        for (unsigned int j=0; j != 3; ++j)
          (*dFdU)(i,j) = -(U_N(j))*U_N_unit(i);

    // With quadratic scaling
    if (_quadratic_scaling)
      {
        const libMesh::Number U_Rel_mag = std::sqrt(U_Rel * U_Rel);

        // Modify dFdU first so as to reuse the old value of F
        if (dFdU)
          {
            // dU_Rel/dU = I
            // d(U_Rel*U_Rel)/dU = 2*U_Rel
            // d|U_Rel|/dU = U_Rel/|U_Rel|

            const libMesh::NumberVectorValue U_Rel_unit = U_Rel/U_Rel_mag;

            (*dFdU) *= U_Rel_mag;

            if (U_Rel_mag)
              for (unsigned int i=0; i != 3; ++i)
                for (unsigned int j=0; j != 3; ++j)
                  (*dFdU)(i,j) += F(i)*U_Rel_unit(j);
          }

        F *= U_Rel_mag;
      }

    // With correction term to avoid doing work on flow
    bool do_correction = false;
    if (do_correction)
      {
        if (dFdU)
          libmesh_not_implemented();

        const libMesh::Number U_Rel_mag_sq = U_Rel * U_Rel;
        if (U_Rel_mag_sq)
          {
            F -= (U_Rel*F)*U_Rel/U_Rel_mag_sq;
          }
      }
    return true;
  }

} // namespace GRINS

// Instantiate
INSTANTIATE_INC_NS_SUBCLASS(VelocityPenaltyBase);
<commit_msg>[grins]: missed pushing back velocity penalty 3 vector<commit_after>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc. 51 Franklin Street, Fifth Floor,
// Boston, MA  02110-1301  USA
//
//-----------------------------------------------------------------------el-

// This class
#include "grins/velocity_penalty_base.h"

// GRINS
#include "grins/inc_nav_stokes_macro.h"

// libMesh
#include "libmesh/parsed_function.h"
#include "libmesh/zero_function.h"

namespace GRINS
{

  template<class Mu>
  VelocityPenaltyBase<Mu>::VelocityPenaltyBase( const std::string& physics_name, const GetPot& input )
    : IncompressibleNavierStokesBase<Mu>(physics_name,
                                         incompressible_navier_stokes, /* "core" Physics name */
                                         input),
    _quadratic_scaling(false)
  {
    this->read_input_options(input);

    return;
  }

  template<class Mu>
  VelocityPenaltyBase<Mu>::~VelocityPenaltyBase()
  {
    return;
  }

  template<class Mu>
  void VelocityPenaltyBase<Mu>::read_input_options( const GetPot& input )
  {
    std::string base_physics_name = "VelocityPenalty";
    if (this->_physics_name == velocity_penalty2 ||
        this->_physics_name == velocity_penalty2_adjoint_stab)
      base_physics_name.push_back('2');

    if (this->_physics_name == velocity_penalty3 ||
        this->_physics_name == velocity_penalty3_adjoint_stab)
      base_physics_name.push_back('3');

    std::string penalty_function =
      input("Physics/"+base_physics_name+"/penalty_function",
        std::string("0"));

    if (penalty_function == "0")
      this->normal_vector_function.reset
        (new libMesh::ZeroFunction<libMesh::Number>());
    else
      this->normal_vector_function.reset
        (new libMesh::ParsedFunction<libMesh::Number>(penalty_function));

    std::string base_function =
      input("Physics/"+base_physics_name+"/base_velocity",
        std::string("0"));

    if (penalty_function == "0" && base_function == "0")
      std::cout << "Warning! Zero VelocityPenalty specified!" << std::endl;

    if (base_function == "0")
      this->base_velocity_function.reset
        (new libMesh::ZeroFunction<libMesh::Number>());
    else
      this->base_velocity_function.reset
        (new libMesh::ParsedFunction<libMesh::Number>(base_function));

    _quadratic_scaling =
      input("Physics/"+base_physics_name+"/quadratic_scaling", false);
  }

  template<class Mu>
  bool VelocityPenaltyBase<Mu>::compute_force
    ( const libMesh::Point& point,
      const libMesh::Real time,
      const libMesh::NumberVectorValue& U,
      libMesh::NumberVectorValue& F,
      libMesh::NumberTensorValue *dFdU)
  {
    // Velocity discrepancy (current velocity minus base velocity)
    // normal to constraint plane, scaled by constraint penalty
    // value
    libmesh_assert(normal_vector_function.get());
    libmesh_assert(base_velocity_function.get());

    libMesh::DenseVector<libMesh::Number> output_vec(3);

    (*normal_vector_function)(point, time,
                              output_vec);

    libMesh::NumberVectorValue U_N(output_vec(0),
                                   output_vec(1),
                                   output_vec(2));

    (*base_velocity_function)(point, time,
                              output_vec);

    const libMesh::NumberVectorValue U_B(output_vec(0),
                                         output_vec(1),
                                         output_vec(2));

    const libMesh::NumberVectorValue U_Rel = U-U_B;

    // Old code
    // const libMesh::NumberVectorValue F1 = (U_Rel*U_N)*U_N; //

    // With correct sign and more natural normalization
    const libMesh::Number U_N_mag = std::sqrt(U_N*U_N);

    if (!U_N_mag)
      return false;

    const libMesh::NumberVectorValue U_N_unit = U_N/U_N_mag;

    F = -(U_Rel*U_N)*U_N_unit;

    if (dFdU)
      for (unsigned int i=0; i != 3; ++i)
        for (unsigned int j=0; j != 3; ++j)
          (*dFdU)(i,j) = -(U_N(j))*U_N_unit(i);

    // With quadratic scaling
    if (_quadratic_scaling)
      {
        const libMesh::Number U_Rel_mag = std::sqrt(U_Rel * U_Rel);

        // Modify dFdU first so as to reuse the old value of F
        if (dFdU)
          {
            // dU_Rel/dU = I
            // d(U_Rel*U_Rel)/dU = 2*U_Rel
            // d|U_Rel|/dU = U_Rel/|U_Rel|

            const libMesh::NumberVectorValue U_Rel_unit = U_Rel/U_Rel_mag;

            (*dFdU) *= U_Rel_mag;

            if (U_Rel_mag)
              for (unsigned int i=0; i != 3; ++i)
                for (unsigned int j=0; j != 3; ++j)
                  (*dFdU)(i,j) += F(i)*U_Rel_unit(j);
          }

        F *= U_Rel_mag;
      }

    // With correction term to avoid doing work on flow
    bool do_correction = false;
    if (do_correction)
      {
        if (dFdU)
          libmesh_not_implemented();

        const libMesh::Number U_Rel_mag_sq = U_Rel * U_Rel;
        if (U_Rel_mag_sq)
          {
            F -= (U_Rel*F)*U_Rel/U_Rel_mag_sq;
          }
      }
    return true;
  }

} // namespace GRINS

// Instantiate
INSTANTIATE_INC_NS_SUBCLASS(VelocityPenaltyBase);
<|endoftext|>


<commit_before>#ifndef __FRAMEWORK_CLASSES_EVENTSCONFIGURATION_HXX_
#define __FRAMEWORK_CLASSES_EVENTSCONFIGURATION_HXX_

#ifndef _SVARRAY_HXX
#include <svtools/svarray.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif

// #110897#
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

namespace framework
{

struct EventsConfig
{
    ::com::sun::star::uno::Sequence< ::rtl::OUString >              aEventNames;
    ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >   aEventsProperties;
};

class EventsConfiguration
{
    public:

        // #110897#
        static sal_Bool LoadEventsConfig(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory,
            SvStream& rInStream, EventsConfig& aItems );

        // #110897#
        static sal_Bool StoreEventsConfig(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory,
            SvStream& rOutStream, const EventsConfig& aItems );
};

} // namespace framework

#endif // __FRAMEWORK_CLASSES_EVENTSCONFIGURATION_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.2.758); FILE MERGED 2008/04/01 15:18:14 thb 1.2.758.2: #i85898# Stripping all external header guards 2008/04/01 10:57:43 thb 1.2.758.1: #i85898# Stripping all external header guards<commit_after>#ifndef __FRAMEWORK_CLASSES_EVENTSCONFIGURATION_HXX_
#define __FRAMEWORK_CLASSES_EVENTSCONFIGURATION_HXX_

#include <svtools/svarray.hxx>
#include <tools/string.hxx>
#include <tools/stream.hxx>
#include <com/sun/star/uno/Sequence.hxx>
#include <com/sun/star/beans/PropertyValue.hpp>

// #110897#
#include <com/sun/star/lang/XMultiServiceFactory.hpp>

namespace framework
{

struct EventsConfig
{
    ::com::sun::star::uno::Sequence< ::rtl::OUString >              aEventNames;
    ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >   aEventsProperties;
};

class EventsConfiguration
{
    public:

        // #110897#
        static sal_Bool LoadEventsConfig(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory,
            SvStream& rInStream, EventsConfig& aItems );

        // #110897#
        static sal_Bool StoreEventsConfig(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory,
            SvStream& rOutStream, const EventsConfig& aItems );
};

} // namespace framework

#endif // __FRAMEWORK_CLASSES_EVENTSCONFIGURATION_HXX_
<|endoftext|>


<commit_before>/*
 */
#include "crate.hpp"
#include "ast.hpp"
#include "../parse/parseerror.hpp"

#include <serialiser_texttree.hpp>

namespace {
    void iterate_module(::AST::Module& mod, ::std::function<void(::AST::Module& mod)> fcn)
    {
        fcn(mod);
        for( auto& sm : mod.items() )
        {
            TU_MATCH_DEF(::AST::Item, (sm.data), (e),
            ( ),
            (Module,
                iterate_module(e, fcn);
                )
            )
        }
    }
}

namespace AST {

Crate::Crate():
    m_root_module(::AST::Path("",{})),
    m_load_std(LOAD_STD)
{
}

void Crate::load_externs()
{
    auto cb = [this](Module& mod) {
        for( const auto& it : mod.items() )
        {
            TU_IFLET(AST::Item, it.data, Crate, c,
                const auto& name = c.name;
                TODO(it.data.span, "Load crate '" << name << "' as '" << it.name << "'");
            )
        }
        };
    iterate_module(m_root_module, cb);
}

Module& Crate::get_root_module(const ::std::string& name) {
    return const_cast<Module&>( const_cast<const Crate*>(this)->get_root_module(name) );
}
const Module& Crate::get_root_module(const ::std::string& name) const {
    if( name == "" )
        return m_root_module;
    auto it = m_extern_crates.find(name);
    if( it != m_extern_crates.end() )
        throw ::std::runtime_error("TODO: Get root module for extern crate");
//        return it->second.root_module();
    throw ParseError::Generic("crate name unknown");
}

void Crate::load_extern_crate(::std::string name)
{
    ::std::ifstream is("output/"+name+".ast");
    if( !is.is_open() )
    {
        throw ParseError::Generic("Can't open crate '" + name + "'");
    }
    //Deserialiser_TextTree   ds(is);
    //Deserialiser&   d = ds;

    ExternCrate ret;

    // TODO: ...

    m_extern_crates.insert( make_pair(::std::move(name), ::std::move(ret)) );
}

ExternCrate::ExternCrate()
{
}

ExternCrate::ExternCrate(const char *path)
{
    throw ParseError::Todo( FMT("Load extern crate from a file - '" << path << "'") );
}

const MacroRules* ExternCrate::find_macro_rules(const ::std::string& name)
{
    auto i = m_mr_macros.find(name);
    if(i != m_mr_macros.end())
        return &*i->second;
    return nullptr;
}

}   // namespace AST

<commit_msg>AST - Use cfg when loading crates<commit_after>/*
 */
#include "crate.hpp"
#include "ast.hpp"
#include "../parse/parseerror.hpp"
#include "../expand/cfg.hpp"

#include <serialiser_texttree.hpp>

namespace {
    bool check_item_cfg(const ::AST::MetaItems& attrs)
    {
        for(const auto& at : attrs.m_items) {
            if( at.name() == "cfg" && !check_cfg(attrs.m_span, at) ) {
                return false;
            }
        }
        return true;
    }
    void iterate_module(::AST::Module& mod, ::std::function<void(::AST::Module& mod)> fcn)
    {
        fcn(mod);
        for( auto& sm : mod.items() )
        {
            TU_IFLET(::AST::Item, sm.data, Module, e,
                if( check_item_cfg(sm.data.attrs) )
                {
                    iterate_module(e, fcn);
                }
            )
        }
    }
}

namespace AST {

Crate::Crate():
    m_root_module(::AST::Path("",{})),
    m_load_std(LOAD_STD)
{
}

void Crate::load_externs()
{
    auto cb = [this](Module& mod) {
        for( const auto& it : mod.items() )
        {
            TU_IFLET(AST::Item, it.data, Crate, c,
                const auto& name = c.name;
                if( check_item_cfg(it.data.attrs) )
                {
                    TODO(it.data.span, "Load crate '" << name << "' as '" << it.name << "'");
                }
            )
        }
        };
    iterate_module(m_root_module, cb);
}

Module& Crate::get_root_module(const ::std::string& name) {
    return const_cast<Module&>( const_cast<const Crate*>(this)->get_root_module(name) );
}
const Module& Crate::get_root_module(const ::std::string& name) const {
    if( name == "" )
        return m_root_module;
    auto it = m_extern_crates.find(name);
    if( it != m_extern_crates.end() )
        throw ::std::runtime_error("TODO: Get root module for extern crate");
//        return it->second.root_module();
    throw ParseError::Generic("crate name unknown");
}

void Crate::load_extern_crate(::std::string name)
{
    ::std::ifstream is("output/"+name+".ast");
    if( !is.is_open() )
    {
        throw ParseError::Generic("Can't open crate '" + name + "'");
    }
    //Deserialiser_TextTree   ds(is);
    //Deserialiser&   d = ds;

    ExternCrate ret;

    // TODO: ...

    m_extern_crates.insert( make_pair(::std::move(name), ::std::move(ret)) );
}

ExternCrate::ExternCrate()
{
}

ExternCrate::ExternCrate(const char *path)
{
    throw ParseError::Todo( FMT("Load extern crate from a file - '" << path << "'") );
}

const MacroRules* ExternCrate::find_macro_rules(const ::std::string& name)
{
    auto i = m_mr_macros.find(name);
    if(i != m_mr_macros.end())
        return &*i->second;
    return nullptr;
}

}   // namespace AST

<|endoftext|>


<commit_before>/*-------------------------------------------------------------------------
 * drawElements Quality Program Tester Core
 * ----------------------------------------
 *
 * Copyright 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *//*!
 * \file
 * \brief Android activity constructors.
 *//*--------------------------------------------------------------------*/

#include "deDefs.h"

#if (DE_OS != DE_OS_ANDROID)
#	error Unsupported OS
#endif

#if (DE_ANDROID_API >= 9)
// Add NativeActivity entry point

#include "tcuAndroidTestActivity.hpp"

DE_BEGIN_EXTERN_C

void createTestActivity (ANativeActivity* activity, void* savedState, size_t savedStateSize)
{
	DE_UNREF(savedState && savedStateSize);
	try
	{
		tcu::Android::TestActivity* obj = new tcu::Android::TestActivity(activity);
		DE_UNREF(obj);
	}
	catch (const std::exception& e)
	{
		tcu::die("Failed to create activity: %s", e.what());
	}
}

DE_END_EXTERN_C

#endif // DE_ANDROID_API >= 9
<commit_msg>Add missing JNIEXPORT and JNICALL to createTestActivity() JNI call am: 1e7c5746fb<commit_after>/*-------------------------------------------------------------------------
 * drawElements Quality Program Tester Core
 * ----------------------------------------
 *
 * Copyright 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *//*!
 * \file
 * \brief Android activity constructors.
 *//*--------------------------------------------------------------------*/

#include "deDefs.h"

#if (DE_OS != DE_OS_ANDROID)
#	error Unsupported OS
#endif

#if (DE_ANDROID_API >= 9)
// Add NativeActivity entry point

#include "tcuAndroidTestActivity.hpp"

DE_BEGIN_EXTERN_C

JNIEXPORT void JNICALL createTestActivity (ANativeActivity* activity, void* savedState, size_t savedStateSize)
{
	DE_UNREF(savedState && savedStateSize);
	try
	{
		tcu::Android::TestActivity* obj = new tcu::Android::TestActivity(activity);
		DE_UNREF(obj);
	}
	catch (const std::exception& e)
	{
		tcu::die("Failed to create activity: %s", e.what());
	}
}

DE_END_EXTERN_C

#endif // DE_ANDROID_API >= 9
<|endoftext|>


<commit_before>/*
 */
#include "crate.hpp"
#include "ast.hpp"
#include "../parse/parseerror.hpp"

#include <serialiser_texttree.hpp>

namespace {
    void iterate_module(::AST::Module& mod, ::std::function<void(::AST::Module& mod)> fcn)
    {
        fcn(mod);
        for( auto& sm : mod.items() )
        {
            TU_MATCH_DEF(::AST::Item, (sm.data), (e),
            ( ),
            (Module,
                iterate_module(e, fcn);
                )
            )
        }
    }
}

namespace AST {

Crate::Crate():
    m_root_module(::AST::Path("",{})),
    m_load_std(LOAD_STD)
{
}

void Crate::load_externs()
{
    auto cb = [this](Module& mod) {
        for( const auto& it : mod.items() )
        {
            if( it.data.is_Crate() ) {
                const auto& name = it.data.as_Crate().name;
                throw ::std::runtime_error( FMT("TODO: Load crate '" << name << "' as '" << it.name << "'") );
            }
        }
        };
    iterate_module(m_root_module, cb);
}

Module& Crate::get_root_module(const ::std::string& name) {
    return const_cast<Module&>( const_cast<const Crate*>(this)->get_root_module(name) );
}
const Module& Crate::get_root_module(const ::std::string& name) const {
    if( name == "" )
        return m_root_module;
    auto it = m_extern_crates.find(name);
    if( it != m_extern_crates.end() )
        throw ::std::runtime_error("TODO: Get root module for extern crate");
//        return it->second.root_module();
    throw ParseError::Generic("crate name unknown");
}

void Crate::load_extern_crate(::std::string name)
{
    ::std::ifstream is("output/"+name+".ast");
    if( !is.is_open() )
    {
        throw ParseError::Generic("Can't open crate '" + name + "'");
    }
    Deserialiser_TextTree   ds(is);
    Deserialiser&   d = ds;

    ExternCrate ret;
    ret.deserialise( d );

    m_extern_crates.insert( make_pair(::std::move(name), ::std::move(ret)) );
}
SERIALISE_TYPE(Crate::, "AST_Crate", {
    unsigned ls = m_load_std;
    s.item(ls);
    s.item(m_extern_crates);
    s.item(m_root_module);
},{
    unsigned ls = m_load_std;
    s.item(ls);
    m_load_std = (::AST::Crate::LoadStd)ls;
    s.item(m_extern_crates);
    s.item(m_root_module);
})

ExternCrate::ExternCrate()
{
}

ExternCrate::ExternCrate(const char *path)
{
    throw ParseError::Todo( FMT("Load extern crate from a file - '" << path << "'") );
}

// Fill runtime-generated structures in the crate
#if 0
void ExternCrate::prescan()
{
    TRACE_FUNCTION;

    Crate& cr = m_crate;

    cr.m_root_module.prescan();

    for( const auto& mi : cr.m_root_module.macro_imports_res() )
    {
        DEBUG("Macro (I) '"<<mi.name<<"' is_pub="<<mi.is_pub);
        if( mi.is_pub )
        {
            m_crate.m_exported_macros.insert( ::std::make_pair(mi.name, mi.data) );
        }
    }
    for( const auto& mi : cr.m_root_module.macros() )
    {
        DEBUG("Macro '"<<mi.name<<"' is_pub="<<mi.is_pub);
        if( mi.is_pub )
        {
            m_crate.m_exported_macros.insert( ::std::make_pair(mi.name, &mi.data) );
        }
    }
}
#endif

const MacroRules* ExternCrate::find_macro_rules(const ::std::string& name)
{
    auto i = m_mr_macros.find(name);
    if(i != m_mr_macros.end())
        return &*i->second;
    return nullptr;
}

SERIALISE_TYPE(ExternCrate::, "AST_ExternCrate", {
    (void)s;
},{
    (void)s;
})

}   // namespace AST

<commit_msg>AST - Nicer TODO for `extern crate`<commit_after>/*
 */
#include "crate.hpp"
#include "ast.hpp"
#include "../parse/parseerror.hpp"

#include <serialiser_texttree.hpp>

namespace {
    void iterate_module(::AST::Module& mod, ::std::function<void(::AST::Module& mod)> fcn)
    {
        fcn(mod);
        for( auto& sm : mod.items() )
        {
            TU_MATCH_DEF(::AST::Item, (sm.data), (e),
            ( ),
            (Module,
                iterate_module(e, fcn);
                )
            )
        }
    }
}

namespace AST {

Crate::Crate():
    m_root_module(::AST::Path("",{})),
    m_load_std(LOAD_STD)
{
}

void Crate::load_externs()
{
    auto cb = [this](Module& mod) {
        for( const auto& it : mod.items() )
        {
            TU_IFLET(AST::Item, it.data, Crate, c,
                const auto& name = c.name;
                TODO(it.data.span, "Load crate '" << name << "' as '" << it.name << "'");
            )
        }
        };
    iterate_module(m_root_module, cb);
}

Module& Crate::get_root_module(const ::std::string& name) {
    return const_cast<Module&>( const_cast<const Crate*>(this)->get_root_module(name) );
}
const Module& Crate::get_root_module(const ::std::string& name) const {
    if( name == "" )
        return m_root_module;
    auto it = m_extern_crates.find(name);
    if( it != m_extern_crates.end() )
        throw ::std::runtime_error("TODO: Get root module for extern crate");
//        return it->second.root_module();
    throw ParseError::Generic("crate name unknown");
}

void Crate::load_extern_crate(::std::string name)
{
    ::std::ifstream is("output/"+name+".ast");
    if( !is.is_open() )
    {
        throw ParseError::Generic("Can't open crate '" + name + "'");
    }
    Deserialiser_TextTree   ds(is);
    Deserialiser&   d = ds;

    ExternCrate ret;
    ret.deserialise( d );

    m_extern_crates.insert( make_pair(::std::move(name), ::std::move(ret)) );
}
SERIALISE_TYPE(Crate::, "AST_Crate", {
    unsigned ls = m_load_std;
    s.item(ls);
    s.item(m_extern_crates);
    s.item(m_root_module);
},{
    unsigned ls = m_load_std;
    s.item(ls);
    m_load_std = (::AST::Crate::LoadStd)ls;
    s.item(m_extern_crates);
    s.item(m_root_module);
})

ExternCrate::ExternCrate()
{
}

ExternCrate::ExternCrate(const char *path)
{
    throw ParseError::Todo( FMT("Load extern crate from a file - '" << path << "'") );
}

// Fill runtime-generated structures in the crate
#if 0
void ExternCrate::prescan()
{
    TRACE_FUNCTION;

    Crate& cr = m_crate;

    cr.m_root_module.prescan();

    for( const auto& mi : cr.m_root_module.macro_imports_res() )
    {
        DEBUG("Macro (I) '"<<mi.name<<"' is_pub="<<mi.is_pub);
        if( mi.is_pub )
        {
            m_crate.m_exported_macros.insert( ::std::make_pair(mi.name, mi.data) );
        }
    }
    for( const auto& mi : cr.m_root_module.macros() )
    {
        DEBUG("Macro '"<<mi.name<<"' is_pub="<<mi.is_pub);
        if( mi.is_pub )
        {
            m_crate.m_exported_macros.insert( ::std::make_pair(mi.name, &mi.data) );
        }
    }
}
#endif

const MacroRules* ExternCrate::find_macro_rules(const ::std::string& name)
{
    auto i = m_mr_macros.find(name);
    if(i != m_mr_macros.end())
        return &*i->second;
    return nullptr;
}

SERIALISE_TYPE(ExternCrate::, "AST_ExternCrate", {
    (void)s;
},{
    (void)s;
})

}   // namespace AST

<|endoftext|>


<commit_before>#ifndef DEF_RANKNET_LAMBDA_H
#define DEF_RANKNET_LAMBDA_H
/**
 * @file
 * @author  David Nemeskey
 * @version 0.1
 *
 * @section LICENSE
 *
 * Copyright [2013] [MTA SZTAKI]
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * The sped-up RankNet algorithm, as described in Christopher J.C. Burges.
 * From RankNet to LambdaRank to LambdaMART: An Overview. 2010. In the paper, it
 * is adviced that this implementation is used for mini-batch learning, though I
 * don't know if the arguments are valid in our case.
 */

#include <cmath>

#include "ltr_algorithm.hpp"

class RankNetLambda : public LtrAlgorithm {
public:
  /** @param[in] sigma parameter of the sigmoid. */
  RankNetLambda(MlModel* model, EvaluationMeasure* eval,
                LtrRunningPhase phase=TRAINING, double sigma=1)
      : LtrAlgorithm(model, eval, phase), sigma(sigma) {
  }

  /**************************** Mathematics stuff *****************************/

  /**
   * The P_ij in the paper; a sigmoid function of s_i - s_j.
   * @param[in] s_i the score given to the first document.
   * @param[in] s_j the score given to the second document.
   * @return P_ij.
   */
  double prob_ij(double s_i, double s_j) {
    return 1 / (1 + exp(-sigma * (s_i - s_j)));
  }

  /**
   * The cross-entropy cost function in its raw form. This and the sigmoid
   * functions can actually be merged into a much simpler method.
   * @param[in] P_ij the estimated probability that U_i > U_j.
   * @param[in] T_ij the known probability that U_i > U_j.
   * @return C.
   */
  double cost(double P_ij, double T_ij) {
    return -T_ij * log(P_ij) - (1 - T_ij) * log(1 - P_ij);
  }

  /** The derivative of C over s_i. */
  // TODO: is this correct?
  double dC_per_ds_i(const double S_ij, const double s_i, const double s_j) {
    return sigma * ((0.5 - 0.5 * S_ij) - 1 / (1 + exp(sigma * (s_i - s_j))));
  }

  /****************************** GraphChi stuff ******************************/

  /** The actual RankNet implementation. */
  virtual void compute_gradients(
      graphchi_vertex<TypeVertex, FeatureEdge> &query, Gradient* umodel) {
    std::vector<double> lambdas(query.num_outedges());
    std::vector<double> s_is(query.num_outedges());

    /* First, we compute all the outputs. */
    for (int i = 0; i < query.num_outedges(); i++) {
      s_is[i] = get_score(query.outedge(i));

    }

    /* Now, we compute the errors (lambdas). */
    for (int i = 0; i < query.num_outedges() - 1; i++) {
      int rel_i = get_relevance(query.outedge(i));
      for (int j = i + 1; j < query.num_outedges(); j++) {
        int rel_j = get_relevance(query.outedge(j));
        if (rel_i != rel_j) {
          double S_ij = rel_i > rel_j ? 1 : -1;
          double lambda_ij = dC_per_ds_i(S_ij, s_is[i], s_is[j]);
          if (rel_i > rel_j) {
            lambdas[i] += lambda_ij;
            lambdas[j] -= lambda_ij;
          } else {
            lambdas[i] -= lambda_ij;
            lambdas[j] += lambda_ij;
          }
//          std::cout << "DOC " << query.outedge(i)->vertex_id() << "(" << rel_i <<
//            ") vs " << query.outedge(j)->vertex_id() << "(" <<
//            rel_j << "), S_ij: " << S_ij << " s_i: " << s_i << ", s_j: " <<
//            s_j << ", prob_ij: " << prob_ij(s_i, s_j) << ", cost: " <<
//            cost(prob_ij(s_i, s_j), 0.5*(1 + S_ij)) << ", error: " << error << std::endl;
          //DYN umodel->update(*(query.outedge(i)->get_vector()), s_i, error);
          //DYN umodel->update(*(query.outedge(j)->get_vector()), s_j, -error);
          /* error(s_i) = -error(s_j) */
        }
      }
    }

    /* Finally, the model update. */
    for (int i = 0; i < query.num_outedges(); i++) {
      umodel->update(query.outedge(i)->get_data().features, s_is[i], lambdas[i]);
    }
  }

private:
  /** The sigma parameter of the sigmoid. */
  double sigma;
};

#endif
<commit_msg>Cost computation error fixed in ranknet_lambda.hpp. 	modified:   ranknet_lambda.hpp<commit_after>#ifndef DEF_RANKNET_LAMBDA_H
#define DEF_RANKNET_LAMBDA_H
/**
 * @file
 * @author  David Nemeskey
 * @version 0.1
 *
 * @section LICENSE
 *
 * Copyright [2013] [MTA SZTAKI]
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * The sped-up RankNet algorithm, as described in Christopher J.C. Burges.
 * From RankNet to LambdaRank to LambdaMART: An Overview. 2010. In the paper, it
 * is adviced that this implementation is used for mini-batch learning, though I
 * don't know if the arguments are valid in our case.
 */

#include <cmath>

#include "ltr_algorithm.hpp"

class RankNetLambda : public LtrAlgorithm {
public:
  /** @param[in] sigma parameter of the sigmoid. */
  RankNetLambda(MlModel* model, EvaluationMeasure* eval,
                LtrRunningPhase phase=TRAINING, double sigma=1)
      : LtrAlgorithm(model, eval, phase), sigma(sigma) {
  }

  /**************************** Mathematics stuff *****************************/

  /**
   * The P_ij in the paper; a sigmoid function of s_i - s_j.
   * @param[in] s_i the score given to the first document.
   * @param[in] s_j the score given to the second document.
   * @return P_ij.
   */
  double prob_ij(double s_i, double s_j) {
    return 1 / (1 + exp(-sigma * (s_i - s_j)));
  }

  /**
   * The cross-entropy cost function in its raw form. This and the sigmoid
   * functions can actually be merged into a much simpler method.
   * @param[in] P_ij the estimated probability that U_i > U_j.
   * @param[in] T_ij the known probability that U_i > U_j.
   * @return C.
   */
  double cost(double P_ij, double T_ij) {
    return -T_ij * log(P_ij) - (1 - T_ij) * log(1 - P_ij);
  }

  /** The derivative of C over s_i. */
  // TODO: is this correct?
  double dC_per_ds_i(const double S_ij, const double s_i, const double s_j) {
    return sigma * ((0.5 - 0.5 * S_ij) - 1 / (1 + exp(sigma * (s_i - s_j))));
  }

  /****************************** GraphChi stuff ******************************/

  /** The actual RankNet implementation. */
  virtual void compute_gradients(
      graphchi_vertex<TypeVertex, FeatureEdge> &query, Gradient* umodel) {
    std::vector<double> lambdas(query.num_outedges());
    std::vector<double> s_is(query.num_outedges());

    /* First, we compute all the outputs. */
    for (int i = 0; i < query.num_outedges(); i++) {
      s_is[i] = get_score(query.outedge(i));

    }

    /* Now, we compute the errors (lambdas). */
    for (int i = 0; i < query.num_outedges() - 1; i++) {
      int rel_i = get_relevance(query.outedge(i));
      for (int j = i + 1; j < query.num_outedges(); j++) {
        int rel_j = get_relevance(query.outedge(j));
        if (rel_i != rel_j) {
          double S_ij = rel_i > rel_j ? 1 : -1;
          double lambda_ij = dC_per_ds_i(S_ij, s_is[i], s_is[j]);
          lambdas[i] += lambda_ij;
          lambdas[j] -= lambda_ij;
//          std::cout << "DOC " << query.outedge(i)->vertex_id() << "(" << rel_i <<
//            ") vs " << query.outedge(j)->vertex_id() << "(" <<
//            rel_j << "), S_ij: " << S_ij << " s_i: " << s_i << ", s_j: " <<
//            s_j << ", prob_ij: " << prob_ij(s_i, s_j) << ", cost: " <<
//            cost(prob_ij(s_i, s_j), 0.5*(1 + S_ij)) << ", error: " << error << std::endl;
          //DYN umodel->update(*(query.outedge(i)->get_vector()), s_i, error);
          //DYN umodel->update(*(query.outedge(j)->get_vector()), s_j, -error);
          /* error(s_i) = -error(s_j) */
        }
      }
    }

    /* Finally, the model update. */
    for (int i = 0; i < query.num_outedges(); i++) {
      umodel->update(query.outedge(i)->get_data().features, s_is[i], lambdas[i]);
    }
  }

private:
  /** The sigma parameter of the sigmoid. */
  double sigma;
};

#endif
<|endoftext|>


<commit_before>#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>

//Criao da estrutura para AP2
typedef struct
{
	int codigo;
	char raca[30], nome[100];
} registro;

typedef struct
{
	int codigo, offset;
} indice1;

typedef struct
{
	char vacina[30];
	int offset;
} indice2;

int Menu();
void AbreArquivos(FILE **AP1, FILE **AP2, FILE **IndPrim, FILE **IndSec1, FILE **IndSec2);
void CadastraVacina(FILE **AP1, FILE **AP2);
void CadastraCachorro(FILE **AP2);
void AtualizaInfoIndice(char status, FILE **arq);
int ExisteCachorro(int codigo, FILE **AP2);
int ProcuraEspacoVazio(FILE **AP1, int tam_reg);
void AlteraCachorro(FILE **AP2);

int main()
{
    int opcao;
	FILE *AP1, *AP2, *IndPrim, *IndSec1, *IndSec2;

	AbreArquivos(&AP1, &AP2, &IndPrim, &IndSec1, &IndSec2);
	opcao = Menu();
	while (1)
	{
	    switch(opcao)
	    {
	        case 1: CadastraCachorro(&AP2); break;
	        case 2: CadastraVacina(&AP1, &AP2); break;
			case 3: AlteraCachorro(&AP2);
                    break;
	        case 0: printf("\nSaindo do Programa...");
        	        fclose(AP1); fclose(AP2); //fecha arquivos principais
                    fclose(IndPrim); fclose(IndSec1); fclose(IndSec2); //fecha ndices
                    getch(); break;
	        default: printf("\nOpcao invalida!"); getch(); break;
        }
        opcao = Menu();
    }
    return 0;
}

/*
DESCRIO: Exibe as opes do menu.
RETORNO: O nmero da opo escolhida pelo usurio
*/
int Menu()
{
	int opcao;

	system("CLS");
    printf("\n 1 - Cadastra Cachorro");
    printf("\n 2 - Cadastra Vacina");
	printf("\n3 - Altera Cachorro");
	printf("\n 0 - Sair");
	printf("\n\nEscolha a opcao: ");
    scanf("%d", &opcao);

	return opcao;
}

/*
DESCRIO: Verifica esssss os arquivos j foram criados.
           Se no, cria-os.
PARMETROS: AP1 - Arquivo Principal 1
            AP2 - Arquivo Principal 2
	        IndPrim - Arquivo de ndice (busca por chave primria)
			IndSec1 - Arquivo de ndice 1 (busca por chave secundria)
			IndSec2 - Arquivo de ndice 2 (busca por chave secundria)
*/
void AbreArquivos(FILE **AP1, FILE **AP2, FILE **IndPrim, FILE **IndSec1, FILE **IndSec2)
{
    int header = -1;
    /*No primeiro caso, ele entra no if pois o arquivo ainda no existe
    (Com o uso do r+b o arquivo tem que existir).
    A ento ele cria o arquivo com w+b*/
    if ((*AP1 = fopen("AP1.bin", "r+b")) == NULL) //se o arquivo no exisitr
    {
        *AP1 = fopen("AP1.bin", "w+b"); //cria um novo arquivo vazio (AP1)
    	fwrite(&header, sizeof(int), 1, *AP1);
    	*IndPrim = fopen("IndPrim.bin", "w+b");
    	AtualizaInfoIndice('!', IndPrim);
    	*IndSec1 = fopen("IndSec1.bin", "w+b");
    	AtualizaInfoIndice('!', IndSec1);
    	*IndSec2 = fopen("IndSec2.bin", "w+b");
    	AtualizaInfoIndice('!', IndSec2);
	}
	/*else if (ExigeRecriaIndice(IndPrim))
	{
		RecriaIndicePrim(AP1);
		QuickSortInd1(INDEX1, 0, tam1);
	}
	else
	{
		IndPrim = fopen("IndPrim.bin", "r+b");
		CarregaIndice(IndPrim, 1);
    	IndSec1 = fopen("IndSec1.bin", "r+b");
    	CarregaIndice(IndSec1, 2);
    	IndSec2 = fopen("IndSec2.bin", "r+b");
    	CarregaIndice(IndSec2, 1);
	}*/

    if ((*AP2 = fopen("AP2.bin", "r+b")) == NULL) //se o arquivo no existir
        *AP2 = fopen("AP2.bin", "w+b"); //cria um novo arquivo vazio (AP2)
}

/*
DESCRIO: Cadastra informaes de um cachorro no Arquivo Principal 2
PARMETROS: AP2 - Arquivo Principal 2
*/
void CadastraCachorro(FILE **AP2)
{
	registro reg;

	system("CLS");
	printf("\nCodigo: ");
	scanf("%d", &reg.codigo);
	while (ExisteCachorro(reg.codigo, AP2))
	{
		system("CLS");
		printf("\nCodigo ja cadastrado. Digite novamente!");
		getch(); system("CLS");
		printf("\nCodigo: ");
        scanf("%d", &reg.codigo);
	}
	fflush(stdin);
	printf("Raca: ");
	gets(reg.raca);
	printf("Nome do Cachorro: ");
	gets(reg.nome);

	fseek(*AP2, 0, SEEK_END); //seta a posio para o fim do arquivo.
	fwrite(&reg, sizeof(reg), 1, *AP2); //escreve no fim do arquivo.
}

/*
DESCRIO: Atualiza o header do ndice com o status de atualizao
PARMETROS: status - '*' - ndice atualizado
                     '!' - ndice desatualizado
            arq - ndice a ser atualizado
*/
void AtualizaInfoIndice(char status, FILE **arq)
{
	fseek(*arq, 0, SEEK_SET);
	fputc(status, *arq);
}

/*
DESCRIO: Verifica se o cdigo j existe no arquivo.
PARMETROS: codigo - Cdigo a ser verificado
            AP2 - Arquivo Principal 2
RETORNOS: 0 - No existe um cachorro com o cdigo passado por parmetro
          1 - Existe um cachorro com o cdigo passado por parmetro
*/
int ExisteCachorro(int codigo, FILE **AP2)
{
	registro reg;

	rewind(*AP2);
	while (fread(&reg, sizeof(registro), 1, *AP2))
	{
		if (reg.codigo == codigo)
		{
			return 1;
			break;
		}
	}
    return 0;
}

/*
DESCRIO: Realiza o cadastro de vacinas
PARMETROS: AP1 - Arquivo principal 1
            AP2 - Arquivo principal 2
*/
void CadastraVacina(FILE **AP1, FILE **AP2)
{
    int cod_controle = 0, cod_cachorro, tam_reg, posicao, aux = 0;
    char verificador = '*', vacina[30], data[6], respo[100], registro[255];

    system("CLS");
    printf("\n Digite o codigo do cachorro <-1 para cadastrar um cachorro>: ");
    scanf("%d", &cod_cachorro);
    if (cod_cachorro == -1)
      CadastraCachorro(AP2);
    else
    {
        while (!ExisteCachorro(cod_cachorro, AP2))
        {
            if (!aux)
                printf("\n Cachorro inexistente. Digite novamente!");
            else
                printf("\n Nova busca..." );
            getch(); system("CLS");
            printf("\n Digite o codigo do cachorro <-1 para cadastrar um cachorro>: ");
            scanf("%d", &cod_cachorro);
            if (cod_cachorro == -1)
            {
                CadastraCachorro(AP2);
                aux = 1;
            }
        }
        system("CLS");
        cod_controle++;//cod_controle = pegar do INDEX1 ordenado;
        printf("\n Codigo do cachorro: %d", cod_cachorro);
        fflush(stdin);
        printf("\n\n Nome da vacina: ");
        gets(vacina);
        printf("\n Data de vacinacao <MM/AA>: ");
        gets(data);
        printf("\n Responsavel pela aplicacao: ");
        gets(respo);

        sprintf(registro, "%d|%d|%s|%s|%s|", cod_controle, cod_cachorro, vacina, data, respo);
        tam_reg = strlen(registro);
        posicao = ProcuraEspacoVazio(AP1, tam_reg);
        if (posicao != -1)
          fseek(*AP1, posicao, SEEK_SET);
        else
          fseek(*AP1, 0, SEEK_END);
        fwrite(&tam_reg, sizeof(int), 1, *AP1);
        fwrite(&verificador, sizeof(char), 1, *AP1);
        fwrite(registro, sizeof(char), tam_reg, *AP1);
    }
}

/*
DESCRIO: Retorna o espao vazio encontrado no arquivo
PARMETROS: AP1 - Arquivo principal 1
            tam_reg - tamanho do registro a ser inserido
RETORNO: posio livre para ser escrita
*/
int ProcuraEspacoVazio(FILE **AP1, int tam_reg)
{
    int offset, tam, pos;
    char ch;

    rewind(*AP1);
    fread(&offset, sizeof(int), 1, *AP1);
    if (offset == -1)
        return -1;
    else
    {
        fseek(*AP1, offset, SEEK_SET);
        pos = ftell(*AP1);
        while (fread(&tam, sizeof(int), 1, *AP1))
        {
            if (tam == -1)
            {
                return -1;
                break;
            }
            else
            {
                ch = fgetc(*AP1);
                if ((tam > tam_reg) && (ch == '!'))
                {
                   return pos;
                   break;
                }
                else
                {
                    fread(&offset, sizeof(int), 1, *AP1);
                    fseek(*AP1, offset, SEEK_SET);
                }
            }
        }
    }
}

/*
DESCRIO: Altera dados de um cachorro
PARMETRO: AP2 - arquivo principal 2
*/
void AlteraCachorro(FILE **AP2)
{
    int op, cod, i = 0;
    char raca[30], nome[100];
    registro reg;

    system("CLS");
    printf("Digite o codigo do cachorro: ");
    scanf("%d", &cod);
    while (!ExisteCachorro(cod, AP2))
    {
        system("CLS");
        printf("\n\nCachorro inexistente. Digite novamente!");
        getch();
        system("CLS");
        printf("\n\nDigite o codigo do cachorro: ");
        scanf("%d", &cod);
    }

    rewind(*AP2);
	while (fread(&reg, sizeof(reg), 1, *AP2))
	{
		if (reg.codigo == cod)
		  break;
		i++;
	}

    system("CLS");
    printf("Qual campo deseja alterar");
    printf("\n\n1 - Raca");
    printf("\n2 - Nome");
    printf("\n\nEscolha a opcao: ");
    scanf("%d", &op);
    while ((op != 1) && (op != 2))
    {
       system("CLS");
       printf("Opcao invalida. Digite novamente!");
       getch();
       system("CLS");
       printf("Qual campo deseja alterar");
       printf("\n\n1 - Raca");
       printf("\n2 - Nome");
       printf("\n\nEscolha a opcao: ");
       scanf("%d", op);
    }

    fflush(stdin);
    system("CLS");
    switch(op)
    {
        case 1: printf("Digite a nova raca: ");
                gets(raca);
                strcpy(reg.raca, raca);
                break;
        case 2: printf("Digite o novo nome: ");
                gets(nome);
                strcpy(reg.nome, nome);
                break;
    }

    fseek(*AP2, sizeof(reg)*i, SEEK_SET);
	fwrite(&reg, sizeof(reg), 1, *AP2);
}

<commit_msg>Índices<commit_after>#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>

//Criao da estrutura para AP2
typedef struct
{
	int codigo;
	char raca[30], nome[100];
} registro;

typedef struct
{
	int codigo, offset;
} indice1;

typedef struct
{
	char vacina[30];
	int offset;
} indice2;

indice1 INDEX1[50];
indice2 INDEX2[50];
indice1 INDEX3[50];
int tam1 = 0, tam2 = 0, tam3 = 0;

int Menu();
void AbreArquivos(FILE **AP1, FILE **AP2, FILE **IndPrim, FILE **IndSec1, FILE **IndSec2);
void CadastraVacina(FILE **AP1, FILE **AP2);
void CadastraCachorro(FILE **AP2);
void AtualizaInfoIndice(char status, FILE **arq);
int ExisteCachorro(int codigo, FILE **AP2);
int ProcuraEspacoVazio(FILE **AP1, int tam_reg);
void AlteraCachorro(FILE **AP2);
int ExigeRecriaIndice(FILE **arq);
void RecriaIndicePrim(FILE **AP1);
void QuickSortInd1(indice1 aux[], int left, int right);
int ParticionarQSInd1(indice1 aux[], int left, int right, int pivo);
void TrocaQSInd1(indice1 aux[], int i, int j);
void CarregaIndice(FILE **arq, int tipo);
//void EscreveIndices(FILE **IndPrim, FILE **IndSec1, FILE **IndSec2);

int main()
{
    int opcao;
	FILE *AP1, *AP2, *IndPrim, *IndSec1, *IndSec2;

	AbreArquivos(&AP1, &AP2, &IndPrim, &IndSec1, &IndSec2);
	opcao = Menu();
	while (1)
	{
	    switch(opcao)
	    {
	        case 1: CadastraCachorro(&AP2); break;
	        case 2: CadastraVacina(&AP1, &AP2); break;
			case 3: AlteraCachorro(&AP2);
                    break;
	        case 0: printf("\nSaindo do Programa...");
        	        fclose(AP1); fclose(AP2); //fecha arquivos principais
                    fclose(IndPrim); fclose(IndSec1); fclose(IndSec2); //fecha ndices
                    getch();
                    return 0;
                    break;
	        default: printf("\nOpcao invalida!"); getch(); break;
        }
        opcao = Menu();
    }
    return 0;
}

/*
DESCRIO: Exibe as opes do menu.
RETORNO: O nmero da opo escolhida pelo usurio
*/
int Menu()
{
	int opcao;

	system("CLS");
    printf("\n 1 - Cadastra Cachorro");
    printf("\n 2 - Cadastra Vacina");
	printf("\n 3 - Altera Cachorro");
	printf("\n 0 - Sair");
	printf("\n\nEscolha a opcao: ");
    scanf("%d", &opcao);

	return opcao;
}

/*
DESCRIO: Verifica esssss os arquivos j foram criados.
           Se no, cria-os.
PARMETROS: AP1 - Arquivo Principal 1
            AP2 - Arquivo Principal 2
	        IndPrim - Arquivo de ndice (busca por chave primria)
			IndSec1 - Arquivo de ndice 1 (busca por chave secundria)
			IndSec2 - Arquivo de ndice 2 (busca por chave secundria)
*/
void AbreArquivos(FILE **AP1, FILE **AP2, FILE **IndPrim, FILE **IndSec1, FILE **IndSec2)
{
    int header = -1;
    /*No primeiro caso, ele entra no if pois o arquivo ainda no existe
    (Com o uso do r+b o arquivo tem que existir).
    A ento ele cria o arquivo com w+b*/
    if ((*AP1 = fopen("AP1.bin", "r+b")) == NULL) //se o arquivo no exisitr
    {
        *AP1 = fopen("AP1.bin", "w+b"); //cria um novo arquivo vazio (AP1)
    	fwrite(&header, sizeof(int), 1, *AP1);
    	*IndPrim = fopen("IndPrim.bin", "w+b");
    	AtualizaInfoIndice('!', IndPrim);
    	*IndSec1 = fopen("IndSec1.bin", "w+b");
    	AtualizaInfoIndice('!', IndSec1);
    	*IndSec2 = fopen("IndSec2.bin", "w+b");
    	AtualizaInfoIndice('!', IndSec2);
	}
	else
	{
	    *IndPrim = fopen("IndPrim.bin", "r+b");
    	*IndSec1 = fopen("IndSec1.bin", "r+b");
    	*IndSec2 = fopen("IndSec2.bin", "r+b");
    	if (ExigeRecriaIndice(IndPrim))
    	{
    	   RecriaIndicePrim(AP1);
		   QuickSortInd1(INDEX1, 0, tam1);
        }
        else
        {
           CarregaIndice(IndPrim, 1);
    	   CarregaIndice(IndSec1, 2);
    	   CarregaIndice(IndSec2, 1);
        }
	}

    if ((*AP2 = fopen("AP2.bin", "r+b")) == NULL) //se o arquivo no existir
        *AP2 = fopen("AP2.bin", "w+b"); //cria um novo arquivo vazio (AP2)
}

/*
DESCRIO: Cadastra informaes de um cachorro no Arquivo Principal 2
PARMETROS: AP2 - Arquivo Principal 2
*/
void CadastraCachorro(FILE **AP2)
{
	registro reg;

	system("CLS");
	printf("\nCodigo: ");
	scanf("%d", &reg.codigo);
	while (ExisteCachorro(reg.codigo, AP2))
	{
		system("CLS");
		printf("\nCodigo ja cadastrado. Digite novamente!");
		getch(); system("CLS");
		printf("\nCodigo: ");
        scanf("%d", &reg.codigo);
	}
	fflush(stdin);
	printf("Raca: ");
	gets(reg.raca);
	printf("Nome do Cachorro: ");
	gets(reg.nome);

	fseek(*AP2, 0, SEEK_END); //seta a posio para o fim do arquivo.
	fwrite(&reg, sizeof(reg), 1, *AP2); //escreve no fim do arquivo.
}

/*
DESCRIO: Atualiza o header do ndice com o status de atualizao
PARMETROS: status - '*' - ndice atualizado
                     '!' - ndice desatualizado
            arq - ndice a ser atualizado
*/
void AtualizaInfoIndice(char status, FILE **arq)
{
	fseek(*arq, 0, SEEK_SET);
	fputc(status, *arq);
}

/*
DESCRIO: Verifica se o cdigo j existe no arquivo.
PARMETROS: codigo - Cdigo a ser verificado
            AP2 - Arquivo Principal 2
RETORNOS: 0 - No existe um cachorro com o cdigo passado por parmetro
          1 - Existe um cachorro com o cdigo passado por parmetro
*/
int ExisteCachorro(int codigo, FILE **AP2)
{
	registro reg;

	rewind(*AP2);
	while (fread(&reg, sizeof(registro), 1, *AP2))
	{
		if (reg.codigo == codigo)
		{
			return 1;
			break;
		}
	}
    return 0;
}

/*
DESCRIO: Realiza o cadastro de vacinas
PARMETROS: AP1 - Arquivo principal 1
            AP2 - Arquivo principal 2
*/
void CadastraVacina(FILE **AP1, FILE **AP2)
{
    int cod_controle, cod_cachorro, tam_reg, posicao, aux = 0;
    char verificador = '*', vacina[30], data[6], respo[100], registro[255];

    system("CLS");
    printf("\n Digite o codigo do cachorro <-1 para cadastrar um cachorro>: ");
    scanf("%d", &cod_cachorro);
    if (cod_cachorro == -1)
      CadastraCachorro(AP2);
    else
    {
        while (!ExisteCachorro(cod_cachorro, AP2))
        {
            if (!aux)
                printf("\n Cachorro inexistente. Digite novamente!");
            else
                printf("\n Nova busca..." );
            getch(); system("CLS");
            printf("\n Digite o codigo do cachorro <-1 para cadastrar um cachorro>: ");
            scanf("%d", &cod_cachorro);
            if (cod_cachorro == -1)
            {
                CadastraCachorro(AP2);
                aux = 1;
            }
        }
        system("CLS");
        if (tam1 == 0)
          cod_controle = 1;
        else
          cod_controle = INDEX1[tam1 - 1].codigo + 1; //pegar do INDEX1 ordenado;
        printf(" Codigo de Controle: %d", cod_controle);
        printf("\n\n Codigo do cachorro: %d", cod_cachorro);
        fflush(stdin);
        printf("\n\n Nome da vacina: ");
        gets(vacina);
        printf("\n Data de vacinacao <MM/AA>: ");
        gets(data);
        printf("\n Responsavel pela aplicacao: ");
        gets(respo);

        sprintf(registro, "%d|%d|%s|%s|%s|", cod_controle, cod_cachorro, vacina, data, respo);
        tam_reg = strlen(registro);
        posicao = ProcuraEspacoVazio(AP1, tam_reg);
        if (posicao != -1)
          fseek(*AP1, posicao, SEEK_SET);
        else
          fseek(*AP1, 0, SEEK_END);
        fwrite(&tam_reg, sizeof(int), 1, *AP1);
        fwrite(&verificador, sizeof(char), 1, *AP1);
        INDEX1[tam1].codigo = cod_controle;
        INDEX1[tam1].offset = ftell(*AP1);
        QuickSortInd1(INDEX1, 0, tam1);
        tam1++;
        fwrite(registro, sizeof(char), tam_reg, *AP1);
    }
}

/*
DESCRIO: Retorna o espao vazio encontrado no arquivo
PARMETROS: AP1 - Arquivo principal 1
            tam_reg - tamanho do registro a ser inserido
RETORNO: posio livre para ser escrita
*/
int ProcuraEspacoVazio(FILE **AP1, int tam_reg)
{
    int offset, tam, pos;
    char ch;

    rewind(*AP1);
    fread(&offset, sizeof(int), 1, *AP1);
    if (offset == -1)
        return -1;
    else
    {
        fseek(*AP1, offset, SEEK_SET);
        pos = ftell(*AP1);
        while (fread(&tam, sizeof(int), 1, *AP1))
        {
            if (tam == -1)
            {
                return -1;
                break;
            }
            else
            {
                ch = fgetc(*AP1);
                if ((tam > tam_reg) && (ch == '!'))
                {
                   return pos;
                   break;
                }
                else
                {
                    fread(&offset, sizeof(int), 1, *AP1);
                    fseek(*AP1, offset, SEEK_SET);
                }
            }
        }
    }
}

/*
DESCRIO: Altera dados de um cachorro
PARMETRO: AP2 - arquivo principal 2
*/
void AlteraCachorro(FILE **AP2)
{
    int op, cod, i = 0;
    char raca[30], nome[100];
    registro reg;

    system("CLS");
    printf("Digite o codigo do cachorro: ");
    scanf("%d", &cod);
    while (!ExisteCachorro(cod, AP2))
    {
        system("CLS");
        printf("\n\nCachorro inexistente. Digite novamente!");
        getch();
        system("CLS");
        printf("\n\nDigite o codigo do cachorro: ");
        scanf("%d", &cod);
    }

    rewind(*AP2);
	while (fread(&reg, sizeof(reg), 1, *AP2))
	{
		if (reg.codigo == cod)
		  break;
		i++;
	}

    system("CLS");
    printf("Qual campo deseja alterar");
    printf("\n\n1 - Raca");
    printf("\n2 - Nome");
    printf("\n\nEscolha a opcao: ");
    scanf("%d", &op);
    while ((op != 1) && (op != 2))
    {
       system("CLS");
       printf("Opcao invalida. Digite novamente!");
       getch();
       system("CLS");
       printf("Qual campo deseja alterar");
       printf("\n\n1 - Raca");
       printf("\n2 - Nome");
       printf("\n\nEscolha a opcao: ");
       scanf("%d", op);
    }

    fflush(stdin);
    system("CLS");
    switch(op)
    {
        case 1: printf("Digite a nova raca: ");
                gets(raca);
                strcpy(reg.raca, raca);
                break;
        case 2: printf("Digite o novo nome: ");
                gets(nome);
                strcpy(reg.nome, nome);
                break;
    }

    fseek(*AP2, sizeof(reg)*i, SEEK_SET);
	fwrite(&reg, sizeof(reg), 1, *AP2);
}

/*
DESCRIO: Verifica se  necessrio recriar um ndice a partir de um arquivo
PARMETRO: ind - ndice a ser verificado
RETORNOS: 0 - No  necessrio recriar o ndice
          1 -  necessrio recriar o ndice
*/
int ExigeRecriaIndice(FILE **arq)
{
	char ch;

	rewind(*arq);
	ch = fgetc(*arq);
	if (ch == '!')
	  return 1;
	else
	  return 0;
}

/*
DESCRIO: Recria o ndice primrio a partir do arquivo e carrega em memria principal
PARMETRO: AP1 - Arquivo Principal 1
*/
void RecriaIndicePrim(FILE **AP1)
{
	int deslocamento, aux;
	char ch;

	fseek(*AP1, sizeof(int), SEEK_SET); //header
	aux = ftell(*AP1);
	ch = fgetc(*AP1);
	if (ch == EOF)
		return;
	else
	{
		fseek(*AP1, 2*sizeof(int), SEEK_SET); //primeiro registro
		ch = fgetc(*AP1);
		while (ch != EOF)
		{
			if (ch != '!')
			{
				INDEX1[tam1].offset = ftell(*AP1);
				fseek(*AP1, INDEX1[tam1].offset, SEEK_SET);
				fscanf(*AP1, "%d", INDEX1[tam1].codigo);
				tam1++;
			}
			fseek(*AP1, 0, aux);
			fread(&deslocamento, sizeof(int), 1, *AP1);
			//fscanf(*AP1, "%d", deslocamento);
			aux += deslocamento;
			fseek(*AP1, sizeof(int), aux);
			ch = fgetc(*AP1);
		}
	}
}

//QuickSort
void TrocaQSInd1(indice1 aux[], int i, int j)
{
    indice1 t = aux[i];
    aux[i] = aux[j];
    aux[j] = t;
}

int ParticionarQSInd1(indice1 aux[], int left,int right,int pivo)
{
    int pos, i;
    TrocaQSInd1(aux, pivo, right);
    pos = left;
    for(i = left; i < right; i++)
    {
        if (aux[i].codigo < aux[right].codigo)
        {
            TrocaQSInd1(aux, i, pos);
            pos++;
        }
    }
    TrocaQSInd1(aux, right, pos);
    return pos;
}

void QuickSortInd1(indice1 aux[], int left, int right)
{
	int pivo, pos;

    if (left < right)
    {
        pivo = (left + right) / 2;
        pos = ParticionarQSInd1(aux,left,right,pivo);
        QuickSortInd1(aux, left, pos - 1);
        QuickSortInd1(aux, pos + 1, right);
    }
}

void CarregaIndice(FILE **arq, int tipo)
{
	indice1 ind1;
	indice2 ind2;

	if (tipo != 2)
	{
		rewind(*arq);
		while (fgetc(*arq) != EOF)
		{
			fread(&ind1, sizeof(indice1), 1, *arq);
			if (tipo == 1)
			{
				INDEX1[tam1] = ind1;
				tam1++;
			}
			else
			{
				INDEX3[tam3] = ind1;
				tam3++;
			}

		}
	}
}

<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "searchresultwindow.h"
#include "searchresulttreemodel.h"

#include <coreplugin/icore.h>

#include <QtCore/QFile>
#include <QtCore/QTextStream>
#include <QtCore/QSettings>
#include <QtCore/QDebug>
#include <QtGui/QListWidget>
#include <QtGui/QToolButton>
#include <QtGui/QLineEdit>

using namespace Find;
using namespace Find::Internal;

static const QString SETTINGSKEYSECTIONNAME("SearchResults");
static const QString SETTINGSKEYEXPANDRESULTS("ExpandResults");

void ResultWindowItem::setData(const QVariant &data)
{
    m_data = data;
}

QVariant ResultWindowItem::data() const
{
    return m_data;
}

SearchResultWindow::SearchResultWindow()
    : m_isShowingReplaceUI(false)
{
    m_widget = new QStackedWidget;
    m_widget->setWindowTitle(name());

    m_searchResultTreeView = new SearchResultTreeView(m_widget);
    m_searchResultTreeView->setFrameStyle(QFrame::NoFrame);
    m_searchResultTreeView->setAttribute(Qt::WA_MacShowFocusRect, false);
    m_widget->addWidget(m_searchResultTreeView);

    m_noMatchesFoundDisplay = new QListWidget(m_widget);
    m_noMatchesFoundDisplay->addItem(tr("No matches found!"));
    m_noMatchesFoundDisplay->setFrameStyle(QFrame::NoFrame);
    m_widget->addWidget(m_noMatchesFoundDisplay);

    m_expandCollapseToolButton = new QToolButton(m_widget);
    m_expandCollapseToolButton->setAutoRaise(true);
    m_expandCollapseToolButton->setCheckable(true);
    m_expandCollapseToolButton->setIcon(QIcon(":/find/images/expand.png"));
    m_expandCollapseToolButton->setToolTip(tr("Expand All"));

    m_replaceLabel = new QLabel(tr("Replace with:"), m_widget);
    m_replaceLabel->setContentsMargins(12, 0, 5, 0);
    m_replaceTextEdit = new QLineEdit(m_widget);
    m_replaceButton = new QToolButton(m_widget);
    m_replaceButton->setToolTip(tr("Replace all occurances"));
    m_replaceButton->setText(tr("Replace"));
    m_replaceButton->setToolButtonStyle(Qt::ToolButtonTextOnly);
    m_replaceButton->setAutoRaise(true);

    connect(m_searchResultTreeView, SIGNAL(jumpToSearchResult(int,const QString&,int,int,int)),
            this, SLOT(handleJumpToSearchResult(int,const QString&,int,int,int)));
    connect(m_expandCollapseToolButton, SIGNAL(toggled(bool)), this, SLOT(handleExpandCollapseToolButton(bool)));
    connect(m_replaceButton, SIGNAL(clicked()), this, SLOT(handleReplaceButton()));

    readSettings();
    setShowReplaceUI(false);
}

SearchResultWindow::~SearchResultWindow()
{
    writeSettings();
    delete m_widget;
    m_widget = 0;
    qDeleteAll(m_items);
    m_items.clear();
}

void SearchResultWindow::setShowReplaceUI(bool show)
{
    m_replaceLabel->setVisible(show);
    m_replaceTextEdit->setVisible(show);
    m_replaceButton->setVisible(show);
//  TODO  m_searchResultTreeView->setShowCheckboxes(show);
    m_isShowingReplaceUI = show;
}

bool SearchResultWindow::isShowingReplaceUI() const
{
    return m_isShowingReplaceUI;
}

void SearchResultWindow::handleReplaceButton()
{
    emit replaceButtonClicked(m_replaceTextEdit->text());
}

QList<ResultWindowItem *> SearchResultWindow::selectedItems() const
{
    QList<ResultWindowItem *> items;
    // TODO
//    foreach (ResultWindowItem *item, m_items) {
//        if (item->isSelected)
//            items << item;
//    }
    return items;
}

void SearchResultWindow::visibilityChanged(bool /*visible*/)
{
}

QWidget *SearchResultWindow::outputWidget(QWidget *)
{
    return m_widget;
}

QList<QWidget*> SearchResultWindow::toolBarWidgets() const
{
    return QList<QWidget*>() << m_expandCollapseToolButton << m_replaceLabel << m_replaceTextEdit << m_replaceButton;
}

void SearchResultWindow::clearContents()
{
    m_widget->setCurrentWidget(m_searchResultTreeView);
    m_searchResultTreeView->clear();
    qDeleteAll(m_items);
    m_items.clear();
    navigateStateChanged();
}

void SearchResultWindow::showNoMatchesFound()
{
    m_widget->setCurrentWidget(m_noMatchesFoundDisplay);
}

bool SearchResultWindow::isEmpty() const
{
    return (m_searchResultTreeView->model()->rowCount() < 1);
}

int SearchResultWindow::numberOfResults() const
{
    return m_searchResultTreeView->model()->rowCount();
}

bool SearchResultWindow::hasFocus()
{
    return m_searchResultTreeView->hasFocus();
}

bool SearchResultWindow::canFocus()
{
    return !m_items.isEmpty();
}

void SearchResultWindow::setFocus()
{
    if (!m_items.isEmpty())
        m_searchResultTreeView->setFocus();
}

void SearchResultWindow::setTextEditorFont(const QFont &font)
{
    m_searchResultTreeView->setTextEditorFont(font);
}

void SearchResultWindow::handleJumpToSearchResult(int index, const QString &fileName, int lineNumber,
    int searchTermStart, int searchTermLength)
{
    Q_UNUSED(searchTermLength)
    ResultWindowItem *item = m_items.at(index);
    emit item->activated(fileName, lineNumber, searchTermStart);
}

ResultWindowItem *SearchResultWindow::addResult(const QString &fileName, int lineNumber, const QString &rowText,
    int searchTermStart, int searchTermLength)
{
    //qDebug()<<"###"<<fileName;
    m_widget->setCurrentWidget(m_searchResultTreeView);
    int index = m_items.size();
    ResultWindowItem *item = new ResultWindowItem;
    m_items.append(item);
    m_searchResultTreeView->appendResultLine(index, fileName, lineNumber, rowText, searchTermStart, searchTermLength);
    if (index == 0) {
        // We didn't have an item before, set the focus to the m_searchResultTreeView
        m_searchResultTreeView->setFocus();
        m_searchResultTreeView->selectionModel()->select(m_searchResultTreeView->model()->index(0, 0, QModelIndex()), QItemSelectionModel::Select);
        emit navigateStateChanged();
    }
    return item;
}

void SearchResultWindow::handleExpandCollapseToolButton(bool checked)
{
    m_searchResultTreeView->setAutoExpandResults(checked);
    if (checked)
        m_searchResultTreeView->expandAll();
    else
        m_searchResultTreeView->collapseAll();
}

void SearchResultWindow::readSettings()
{
    QSettings *s = Core::ICore::instance()->settings();
    if (s) {
        s->beginGroup(SETTINGSKEYSECTIONNAME);
        m_expandCollapseToolButton->setChecked(s->value(SETTINGSKEYEXPANDRESULTS, m_initiallyExpand).toBool());
        s->endGroup();
    }
}

void SearchResultWindow::writeSettings()
{
    QSettings *s = Core::ICore::instance()->settings();
    if (s) {
        s->beginGroup(SETTINGSKEYSECTIONNAME);
        s->setValue(SETTINGSKEYEXPANDRESULTS, m_expandCollapseToolButton->isChecked());
        s->endGroup();
    }
}

int SearchResultWindow::priorityInStatusBar() const
{
    return 80;
}

bool SearchResultWindow::canNext()
{
    return m_searchResultTreeView->model()->rowCount();
}

bool SearchResultWindow::canPrevious()
{
    return m_searchResultTreeView->model()->rowCount();
}

void SearchResultWindow::goToNext()
{
    if (!m_searchResultTreeView->model()->rowCount())
        return;
    QModelIndex idx = m_searchResultTreeView->model()->next(m_searchResultTreeView->currentIndex());
    if (idx.isValid()) {
        m_searchResultTreeView->setCurrentIndex(idx);
        m_searchResultTreeView->emitJumpToSearchResult(idx);
    }
}
void SearchResultWindow::goToPrev()
{
    if (!m_searchResultTreeView->model()->rowCount())
        return;
    QModelIndex idx = m_searchResultTreeView->model()->prev(m_searchResultTreeView->currentIndex());
    if (idx.isValid()) {
        m_searchResultTreeView->setCurrentIndex(idx);
        m_searchResultTreeView->emitJumpToSearchResult(idx);
    }
}

bool SearchResultWindow::canNavigate()
{
    return true;
}
<commit_msg>Focus policy for search results and tab order.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "searchresultwindow.h"
#include "searchresulttreemodel.h"

#include <coreplugin/icore.h>

#include <QtCore/QFile>
#include <QtCore/QTextStream>
#include <QtCore/QSettings>
#include <QtCore/QDebug>
#include <QtGui/QListWidget>
#include <QtGui/QToolButton>
#include <QtGui/QLineEdit>

using namespace Find;
using namespace Find::Internal;

static const QString SETTINGSKEYSECTIONNAME("SearchResults");
static const QString SETTINGSKEYEXPANDRESULTS("ExpandResults");

void ResultWindowItem::setData(const QVariant &data)
{
    m_data = data;
}

QVariant ResultWindowItem::data() const
{
    return m_data;
}

SearchResultWindow::SearchResultWindow()
    : m_isShowingReplaceUI(false)
{
    m_widget = new QStackedWidget;
    m_widget->setWindowTitle(name());

    m_searchResultTreeView = new SearchResultTreeView(m_widget);
    m_searchResultTreeView->setFrameStyle(QFrame::NoFrame);
    m_searchResultTreeView->setAttribute(Qt::WA_MacShowFocusRect, false);
    m_widget->addWidget(m_searchResultTreeView);

    m_noMatchesFoundDisplay = new QListWidget(m_widget);
    m_noMatchesFoundDisplay->addItem(tr("No matches found!"));
    m_noMatchesFoundDisplay->setFrameStyle(QFrame::NoFrame);
    m_widget->addWidget(m_noMatchesFoundDisplay);

    m_expandCollapseToolButton = new QToolButton(m_widget);
    m_expandCollapseToolButton->setAutoRaise(true);
    m_expandCollapseToolButton->setCheckable(true);
    m_expandCollapseToolButton->setIcon(QIcon(":/find/images/expand.png"));
    m_expandCollapseToolButton->setToolTip(tr("Expand All"));

    m_replaceLabel = new QLabel(tr("Replace with:"), m_widget);
    m_replaceLabel->setContentsMargins(12, 0, 5, 0);
    m_replaceTextEdit = new QLineEdit(m_widget);
    m_replaceButton = new QToolButton(m_widget);
    m_replaceButton->setToolTip(tr("Replace all occurances"));
    m_replaceButton->setText(tr("Replace"));
    m_replaceButton->setToolButtonStyle(Qt::ToolButtonTextOnly);
    m_replaceButton->setAutoRaise(true);
    m_replaceTextEdit->setTabOrder(m_replaceTextEdit, m_searchResultTreeView);

    connect(m_searchResultTreeView, SIGNAL(jumpToSearchResult(int,const QString&,int,int,int)),
            this, SLOT(handleJumpToSearchResult(int,const QString&,int,int,int)));
    connect(m_expandCollapseToolButton, SIGNAL(toggled(bool)), this, SLOT(handleExpandCollapseToolButton(bool)));
    connect(m_replaceButton, SIGNAL(clicked()), this, SLOT(handleReplaceButton()));

    readSettings();
    setShowReplaceUI(false);
}

SearchResultWindow::~SearchResultWindow()
{
    writeSettings();
    delete m_widget;
    m_widget = 0;
    qDeleteAll(m_items);
    m_items.clear();
}

void SearchResultWindow::setShowReplaceUI(bool show)
{
    m_replaceLabel->setVisible(show);
    m_replaceTextEdit->setVisible(show);
    m_replaceButton->setVisible(show);
//  TODO  m_searchResultTreeView->setShowCheckboxes(show);
    m_isShowingReplaceUI = show;
}

bool SearchResultWindow::isShowingReplaceUI() const
{
    return m_isShowingReplaceUI;
}

void SearchResultWindow::handleReplaceButton()
{
    emit replaceButtonClicked(m_replaceTextEdit->text());
}

QList<ResultWindowItem *> SearchResultWindow::selectedItems() const
{
    QList<ResultWindowItem *> items;
    // TODO
//    foreach (ResultWindowItem *item, m_items) {
//        if (item->isSelected)
//            items << item;
//    }
    return items;
}

void SearchResultWindow::visibilityChanged(bool /*visible*/)
{
}

QWidget *SearchResultWindow::outputWidget(QWidget *)
{
    return m_widget;
}

QList<QWidget*> SearchResultWindow::toolBarWidgets() const
{
    return QList<QWidget*>() << m_expandCollapseToolButton << m_replaceLabel << m_replaceTextEdit << m_replaceButton;
}

void SearchResultWindow::clearContents()
{
    setShowReplaceUI(false);
    m_widget->setCurrentWidget(m_searchResultTreeView);
    m_searchResultTreeView->clear();
    qDeleteAll(m_items);
    m_items.clear();
    navigateStateChanged();
}

void SearchResultWindow::showNoMatchesFound()
{
    m_widget->setCurrentWidget(m_noMatchesFoundDisplay);
}

bool SearchResultWindow::isEmpty() const
{
    return (m_searchResultTreeView->model()->rowCount() < 1);
}

int SearchResultWindow::numberOfResults() const
{
    return m_searchResultTreeView->model()->rowCount();
}

bool SearchResultWindow::hasFocus()
{
    return m_searchResultTreeView->hasFocus() || (m_isShowingReplaceUI && m_replaceTextEdit->hasFocus());
}

bool SearchResultWindow::canFocus()
{
    return !m_items.isEmpty();
}

void SearchResultWindow::setFocus()
{
    if (!m_items.isEmpty()) {
        if (!m_isShowingReplaceUI) {
            m_searchResultTreeView->setFocus();
        } else {
            if (!m_widget->focusWidget()
                    || m_widget->focusWidget() == m_replaceTextEdit) {
                m_replaceTextEdit->setFocus();
            } else {
                m_searchResultTreeView->setFocus();
            }
        }
    }
}

void SearchResultWindow::setTextEditorFont(const QFont &font)
{
    m_searchResultTreeView->setTextEditorFont(font);
}

void SearchResultWindow::handleJumpToSearchResult(int index, const QString &fileName, int lineNumber,
    int searchTermStart, int searchTermLength)
{
    Q_UNUSED(searchTermLength)
    ResultWindowItem *item = m_items.at(index);
    emit item->activated(fileName, lineNumber, searchTermStart);
}

ResultWindowItem *SearchResultWindow::addResult(const QString &fileName, int lineNumber, const QString &rowText,
    int searchTermStart, int searchTermLength)
{
    //qDebug()<<"###"<<fileName;
    m_widget->setCurrentWidget(m_searchResultTreeView);
    int index = m_items.size();
    ResultWindowItem *item = new ResultWindowItem;
    m_items.append(item);
    m_searchResultTreeView->appendResultLine(index, fileName, lineNumber, rowText, searchTermStart, searchTermLength);
    if (index == 0) {
        // We didn't have an item before, set the focus to the m_searchResultTreeView
        setFocus();
        m_searchResultTreeView->selectionModel()->select(m_searchResultTreeView->model()->index(0, 0, QModelIndex()), QItemSelectionModel::Select);
        emit navigateStateChanged();
    }
    return item;
}

void SearchResultWindow::handleExpandCollapseToolButton(bool checked)
{
    m_searchResultTreeView->setAutoExpandResults(checked);
    if (checked)
        m_searchResultTreeView->expandAll();
    else
        m_searchResultTreeView->collapseAll();
}

void SearchResultWindow::readSettings()
{
    QSettings *s = Core::ICore::instance()->settings();
    if (s) {
        s->beginGroup(SETTINGSKEYSECTIONNAME);
        m_expandCollapseToolButton->setChecked(s->value(SETTINGSKEYEXPANDRESULTS, m_initiallyExpand).toBool());
        s->endGroup();
    }
}

void SearchResultWindow::writeSettings()
{
    QSettings *s = Core::ICore::instance()->settings();
    if (s) {
        s->beginGroup(SETTINGSKEYSECTIONNAME);
        s->setValue(SETTINGSKEYEXPANDRESULTS, m_expandCollapseToolButton->isChecked());
        s->endGroup();
    }
}

int SearchResultWindow::priorityInStatusBar() const
{
    return 80;
}

bool SearchResultWindow::canNext()
{
    return m_searchResultTreeView->model()->rowCount();
}

bool SearchResultWindow::canPrevious()
{
    return m_searchResultTreeView->model()->rowCount();
}

void SearchResultWindow::goToNext()
{
    if (!m_searchResultTreeView->model()->rowCount())
        return;
    QModelIndex idx = m_searchResultTreeView->model()->next(m_searchResultTreeView->currentIndex());
    if (idx.isValid()) {
        m_searchResultTreeView->setCurrentIndex(idx);
        m_searchResultTreeView->emitJumpToSearchResult(idx);
    }
}
void SearchResultWindow::goToPrev()
{
    if (!m_searchResultTreeView->model()->rowCount())
        return;
    QModelIndex idx = m_searchResultTreeView->model()->prev(m_searchResultTreeView->currentIndex());
    if (idx.isValid()) {
        m_searchResultTreeView->setCurrentIndex(idx);
        m_searchResultTreeView->emitJumpToSearchResult(idx);
    }
}

bool SearchResultWindow::canNavigate()
{
    return true;
}
<|endoftext|>