<commit_before>/******************************************************************************
 * Copyright 2018 The Apollo Authors. All Rights Reserved.
 *
 * 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.
 *****************************************************************************/
#include "modules/perception/fusion/common/information_filter.h"

namespace apollo {
namespace perception {
namespace fusion {

InformationFilter::InformationFilter()
    : BaseFilter("InformationFilter"), last_observation_init_(false) {}

bool InformationFilter::Init(const Eigen::VectorXd &global_states,
                             const Eigen::MatrixXd &global_uncertainty) {
  if (global_uncertainty.rows() != global_uncertainty.cols()) {
    return false;
  }

  states_num_ = static_cast<int>(global_uncertainty.rows());

  if (states_num_ <= 0) {
    return false;
  }

  if (states_num_ != global_states.rows()) {
    return false;
  }

  global_states_ = global_states;
  global_uncertainty_ = global_uncertainty;
  tmp_states_ = global_uncertainty_.inverse() * global_states_;

  transform_matrix_.setIdentity(states_num_, states_num_);
  last_to_cur_transform_matrix_.setIdentity(states_num_, states_num_);

  cur_observation_.setZero(states_num_, 1);
  cur_observation_uncertainty_.setIdentity(states_num_, states_num_);

  last_observation_.setZero(states_num_, 1);
  last_observation_uncertainty_.setIdentity(states_num_, states_num_);

  c_matrix_.setIdentity(states_num_, states_num_);
  env_uncertainty_.setZero(states_num_, states_num_);

  init_ = true;
  return true;
}

bool InformationFilter::SetLastObservation(
    const Eigen::VectorXd &last_observation,
    const Eigen::MatrixXd &last_observation_uncertainty,
    const Eigen::MatrixXd &last_to_cur_transform_matrix,
    const Eigen::MatrixXd &last_to_cur_env_uncertainty) {
  if (init_ == false) {
    return false;
  }
  if (last_observation.rows() != states_num_) {
    return false;
  }
  if (last_observation_uncertainty.rows() != states_num_) {
    return false;
  }
  if (last_observation_uncertainty.cols() != states_num_) {
    return false;
  }
  if (last_to_cur_transform_matrix.rows() != states_num_) {
    return false;
  }
  if (last_to_cur_transform_matrix.cols() != states_num_) {
    return false;
  }
  if (last_to_cur_env_uncertainty.rows() != states_num_) {
    return false;
  }
  if (last_to_cur_env_uncertainty.cols() != states_num_) {
    return false;
  }

  last_observation_ = last_observation;
  last_observation_uncertainty_ = last_observation_uncertainty;
  last_to_cur_transform_matrix_ = last_to_cur_transform_matrix;
  last_to_cur_env_uncertainty_ = last_to_cur_env_uncertainty;
  last_observation_init_ = true;
  return true;
}

bool InformationFilter::Predict(const Eigen::MatrixXd &transform_matrix,
                                const Eigen::MatrixXd &env_uncertainty) {
  if (init_ == false) {
    return false;
  }
  if (transform_matrix.rows() != states_num_) {
    return false;
  }
  if (transform_matrix.cols() != states_num_) {
    return false;
  }
  if (env_uncertainty.rows() != states_num_) {
    return false;
  }
  if (env_uncertainty.cols() != states_num_) {
    return false;
  }
  transform_matrix_ = transform_matrix;
  env_uncertainty_ = env_uncertainty;
  global_states_ = transform_matrix_ * global_states_;
  global_uncertainty_ =
      transform_matrix_ * global_uncertainty_ * transform_matrix_.transpose() +
      env_uncertainty_;
  return true;
}

bool InformationFilter::Correct(
    const Eigen::VectorXd &cur_observation,
    const Eigen::MatrixXd &cur_observation_uncertainty) {
  if (init_ == false) {
    return false;
  }
  if (cur_observation.rows() != states_num_) {
    return false;
  }
  if (cur_observation_uncertainty.rows() != states_num_) {
    return false;
  }
  if (cur_observation_uncertainty.cols() != states_num_) {
    return false;
  }
  cur_observation_ = cur_observation;
  cur_observation_uncertainty_ = cur_observation_uncertainty;
  global_uncertainty_ = global_uncertainty_.inverse();
  tmp_states_ = global_uncertainty_ * global_states_;
  cur_observation_uncertainty_ = cur_observation_uncertainty_.inverse();
  if (last_observation_init_) {
    last_observation_ = last_to_cur_transform_matrix_ * last_observation_;
    last_observation_uncertainty_ =
        last_to_cur_transform_matrix_ * last_observation_uncertainty_ *
            last_to_cur_transform_matrix_.transpose() +
        last_to_cur_env_uncertainty_;
    last_observation_uncertainty_ =
        c_matrix_ * last_observation_uncertainty_ * c_matrix_.transpose();
    global_uncertainty_ =
        c_matrix_.transpose() * global_uncertainty_ +
        (c_matrix_.transpose() * cur_observation_uncertainty_ * c_matrix_ -
         c_matrix_.transpose() * last_observation_uncertainty_.inverse() *
             c_matrix_);
    tmp_states_ +=
        (c_matrix_.transpose() * cur_observation_uncertainty_ *
             cur_observation_ -
         c_matrix_.transpose() * last_observation_uncertainty_.inverse() *
             last_observation_);
  } else {
    global_uncertainty_ +=
        c_matrix_.transpose() * cur_observation_uncertainty_ * c_matrix_;
    tmp_states_ +=
        c_matrix_.transpose() * cur_observation_uncertainty_ * cur_observation_;
  }

  global_states_ = global_uncertainty_.inverse() * tmp_states_;
  last_observation_init_ = false;
  return true;
}
bool InformationFilter::SetControlMatrix(
    const Eigen::MatrixXd &control_matrix) {
  if (init_ == false) {
    return false;
  }
  if (control_matrix.rows() != states_num_ ||
      control_matrix.cols() != states_num_) {
    return false;
  }
  c_matrix_ = control_matrix;
  return true;
}

}  // namespace fusion
}  // namespace perception
}  // namespace apollo
<commit_msg>Perception: fixed a bug in information matrix update step (#6190)<commit_after>/******************************************************************************
 * Copyright 2018 The Apollo Authors. All Rights Reserved.
 *
 * 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.
 *****************************************************************************/
#include "modules/perception/fusion/common/information_filter.h"

namespace apollo {
namespace perception {
namespace fusion {

InformationFilter::InformationFilter()
    : BaseFilter("InformationFilter"), last_observation_init_(false) {}

bool InformationFilter::Init(const Eigen::VectorXd &global_states,
                             const Eigen::MatrixXd &global_uncertainty) {
  if (global_uncertainty.rows() != global_uncertainty.cols()) {
    return false;
  }

  states_num_ = static_cast<int>(global_uncertainty.rows());

  if (states_num_ <= 0) {
    return false;
  }

  if (states_num_ != global_states.rows()) {
    return false;
  }

  global_states_ = global_states;
  global_uncertainty_ = global_uncertainty;
  tmp_states_ = global_uncertainty_.inverse() * global_states_;

  transform_matrix_.setIdentity(states_num_, states_num_);
  last_to_cur_transform_matrix_.setIdentity(states_num_, states_num_);

  cur_observation_.setZero(states_num_, 1);
  cur_observation_uncertainty_.setIdentity(states_num_, states_num_);

  last_observation_.setZero(states_num_, 1);
  last_observation_uncertainty_.setIdentity(states_num_, states_num_);

  c_matrix_.setIdentity(states_num_, states_num_);
  env_uncertainty_.setZero(states_num_, states_num_);

  init_ = true;
  return true;
}

bool InformationFilter::SetLastObservation(
    const Eigen::VectorXd &last_observation,
    const Eigen::MatrixXd &last_observation_uncertainty,
    const Eigen::MatrixXd &last_to_cur_transform_matrix,
    const Eigen::MatrixXd &last_to_cur_env_uncertainty) {
  if (init_ == false) {
    return false;
  }
  if (last_observation.rows() != states_num_) {
    return false;
  }
  if (last_observation_uncertainty.rows() != states_num_) {
    return false;
  }
  if (last_observation_uncertainty.cols() != states_num_) {
    return false;
  }
  if (last_to_cur_transform_matrix.rows() != states_num_) {
    return false;
  }
  if (last_to_cur_transform_matrix.cols() != states_num_) {
    return false;
  }
  if (last_to_cur_env_uncertainty.rows() != states_num_) {
    return false;
  }
  if (last_to_cur_env_uncertainty.cols() != states_num_) {
    return false;
  }

  last_observation_ = last_observation;
  last_observation_uncertainty_ = last_observation_uncertainty;
  last_to_cur_transform_matrix_ = last_to_cur_transform_matrix;
  last_to_cur_env_uncertainty_ = last_to_cur_env_uncertainty;
  last_observation_init_ = true;
  return true;
}

bool InformationFilter::Predict(const Eigen::MatrixXd &transform_matrix,
                                const Eigen::MatrixXd &env_uncertainty) {
  if (init_ == false) {
    return false;
  }
  if (transform_matrix.rows() != states_num_) {
    return false;
  }
  if (transform_matrix.cols() != states_num_) {
    return false;
  }
  if (env_uncertainty.rows() != states_num_) {
    return false;
  }
  if (env_uncertainty.cols() != states_num_) {
    return false;
  }
  transform_matrix_ = transform_matrix;
  env_uncertainty_ = env_uncertainty;
  global_states_ = transform_matrix_ * global_states_;
  global_uncertainty_ =
      transform_matrix_ * global_uncertainty_ * transform_matrix_.transpose() +
      env_uncertainty_;
  return true;
}

bool InformationFilter::Correct(
    const Eigen::VectorXd &cur_observation,
    const Eigen::MatrixXd &cur_observation_uncertainty) {
  if (init_ == false) {
    return false;
  }
  if (cur_observation.rows() != states_num_) {
    return false;
  }
  if (cur_observation_uncertainty.rows() != states_num_) {
    return false;
  }
  if (cur_observation_uncertainty.cols() != states_num_) {
    return false;
  }
  cur_observation_ = cur_observation;
  cur_observation_uncertainty_ = cur_observation_uncertainty;
  // global_uncertainty now stores information matrix
  global_uncertainty_ = global_uncertainty_.inverse();
  // tmp_states_ is information vector
  tmp_states_ = global_uncertainty_ * global_states_;
  // cur_observation_uncertainty_ is now the inverse of covariance matrix
  cur_observation_uncertainty_ = cur_observation_uncertainty_.inverse();
  if (last_observation_init_) {
    // propate to current time
    last_observation_ = last_to_cur_transform_matrix_ * last_observation_;
    last_observation_uncertainty_ =
        last_to_cur_transform_matrix_ * last_observation_uncertainty_ *
        last_to_cur_transform_matrix_.transpose() +
        last_to_cur_env_uncertainty_;
    last_observation_uncertainty_ =  // transform to measurement space
        c_matrix_ * last_observation_uncertainty_ * c_matrix_.transpose();
    global_uncertainty_ =  // update information matrix
        global_uncertainty_ +
        (c_matrix_.transpose() * cur_observation_uncertainty_ * c_matrix_ -
         c_matrix_.transpose() * last_observation_uncertainty_.inverse() *
             c_matrix_);
    tmp_states_ +=  // update information vector
        (c_matrix_.transpose() * cur_observation_uncertainty_ *
             cur_observation_ -
         c_matrix_.transpose() * last_observation_uncertainty_.inverse() *
             last_observation_);
  } else {
    global_uncertainty_ +=
        c_matrix_.transpose() * cur_observation_uncertainty_ * c_matrix_;
    tmp_states_ +=
        c_matrix_.transpose() * cur_observation_uncertainty_ * cur_observation_;
  }

  global_states_ = global_uncertainty_.inverse() * tmp_states_;
  last_observation_init_ = false;
  return true;
}
bool InformationFilter::SetControlMatrix(
    const Eigen::MatrixXd &control_matrix) {
  if (init_ == false) {
    return false;
  }
  if (control_matrix.rows() != states_num_ ||
      control_matrix.cols() != states_num_) {
    return false;
  }
  c_matrix_ = control_matrix;
  return true;
}

}  // namespace fusion
}  // namespace perception
}  // namespace apollo
<|endoftext|>


<commit_before>/*
   C++ implementation of Bonjour services.  Code is based
   on the implementation of TBonjour* classes written by
   Fons Rademakers for the ROOT Framework.
*/

#include <arpa/inet.h>
#include <net/if.h>
#include <sys/select.h>
#include <cstdlib>
#include "Xrd/XrdConfig.hh"
#include "XrdOuc/XrdOucBonjour.hh"
#include "XrdOuc/XrdOucFactoryBonjour.hh"
#include "XrdSys/XrdSysError.hh"
#include "Xrd/XrdInet.hh"
#include "Xrd/XrdProtLoad.hh"

/******************************************************************************/
/*                      G l o b a l   V a r i a b l e s                       */
/******************************************************************************/

extern XrdConfig    XrdConf;              // Defined in XrdMain.cc
extern XrdSysError  XrdLog;               // Defined in XrdMain.cc
extern XrdInet     *XrdNetTCP[];          // Defined by config

/******************************************************************************/
/*        B o n j o u r   s e r v i c e s : r e g i s t r a t i o n           */
/******************************************************************************/

void XrdOucAppleBonjour::RegisterReply(DNSServiceRef ref, DNSServiceFlags flags,
                                       DNSServiceErrorType error, const char * name,
                                       const char * regtype, const char * domain,
                                       void * context)
{
   XrdOucBonjourRegisteredEntry * entry;
   entry = (XrdOucBonjourRegisteredEntry *)context;

   // When this callback is called, it comes with the final results of the
   // procedure and the registered names if there was a renaming due to name
   // collisions with other services.
   if (error != kDNSServiceErr_NoError) {
      ((XrdOucAppleBonjour &)getInstance()).ListOfRegistrations.remove(entry);
      delete entry->record;
      free(entry);
      XrdLog.Emsg("OucBonjour", error, "complete the registration callback");
      return;
   }

   // Update the registered information.
   entry->record->SetServiceName(name);
   entry->record->SetRegisteredType(regtype);
   entry->record->SetReplyDomain(domain);
}

int XrdOucAppleBonjour::RegisterService(XrdOucBonjourRecord &record, unsigned short port)
{
   XrdOucBonjourRegisteredEntry * entry;
   DNSServiceErrorType err;
   fd_set descriptors;
   int sockfd;
   struct timeval timeout;

   // Get the default port.
   if (port == 0)
      port = (XrdNetTCP[0] == XrdNetTCP[XrdProtLoad::ProtoMax]
              ?  -(XrdNetTCP[0]->Port()) : XrdNetTCP[0]->Port());

   // Store information on local list.
   entry = (XrdOucBonjourRegisteredEntry *)malloc(sizeof(XrdOucBonjourRegisteredEntry));
   if (!entry)
      return -1;

   entry->record = new XrdOucBonjourRecord(record);
   entry->port = port;

   // Start the registration procedure.
   err = DNSServiceRegister(&(entry->bonjourRef),
                            0, // No flags
                            0,
                            record.GetServiceName(),
                            record.GetRegisteredType(),
                            record.GetReplyDomain(),
                            NULL, // This host
                            htons(port),
                            record.GetTXTRecordLength(),
                            record.GetTXTRecordData(),
                            RegisterReply,
                            entry);

   if (err != kDNSServiceErr_NoError) {
      XrdLog.Emsg("OucBonjour", err, "rRegigster service", record.GetRegisteredType());
      XrdLog.Emsg("OucBonjour", err, "launch the registration");
      // Free memory.
      delete entry->record;
      free(entry);
      return -1;
   }

   // Wait for the callback. CAUTION: this call is blocking and may stuck you
   // thread. This will call the callback function.
   sockfd = DNSServiceRefSockFD(entry->bonjourRef);
   // Set the fd_set to start select()
   FD_ZERO(&descriptors);
   FD_SET(sockfd, &descriptors);
   timeout.tv_sec = TIMEOUT;
   timeout.tv_usec = 0;
   // Wait for the response.
   if (select(sockfd + 1, &descriptors, NULL, NULL, &timeout) > 0) {
      err = DNSServiceProcessResult(entry->bonjourRef);
      if (err != kDNSServiceErr_NoError) {
         XrdLog.Emsg("OucBonjour", err, "process the registration procedure");
         return -1;
      }
   } else {
      XrdLog.Emsg("OucBonjour", err, "wait to the registration response");
      return -1;
   }

   ListOfRegistrations.push_back(entry);
   return 0;
}

/******************************************************************************/
/*           B o n j o u r   s e r v i c e s : d i s c o v e r y              */
/******************************************************************************/

void * XrdOucAppleBonjour::BrowseEventLoopThread(void * context)
{
   int sockfd;
   int selRes;
   int stopEventLoop = 0;
   DNSServiceRef serviceRef;
   DNSServiceErrorType err;
   fd_set descriptors;
   XrdOucBonjourSubscribedEntry * callbackID;

   callbackID = (XrdOucBonjourSubscribedEntry *)context;

   // This thread is responsible for receiving the updates from the mDNS daemon.
   // We are using a select() based event-loop because is more extensible if we
   // would like to register for more services than one.
   XrdSysThread::SetCancelOn();
   XrdSysThread::SetCancelAsynchronous();

   // Start the DNS service browsing on the network.
   err = DNSServiceBrowse(&serviceRef,
                          0,
                          0,
                          callbackID->serviceType->c_str(),
                          NULL,
                          BrowseReply,
                          context);

   // If there are no errors, launch the event loop.
   if (err != kDNSServiceErr_NoError) {
      XrdLog.Emsg("OucBonjour", err, "launch the discovery process");
      return NULL; // Thread ends.
   }

   // Launch the event loop.
   sockfd = DNSServiceRefSockFD(serviceRef);

   while (!stopEventLoop) {
      // Set the fd_set to start select()
      FD_ZERO(&descriptors);
      FD_SET(sockfd, &descriptors);

      // Wait until there is something to do
      selRes = select(sockfd + 1, &descriptors, NULL, NULL, NULL);

      // Process the new result.
      if (selRes > 0) {
         if (FD_ISSET(sockfd, &descriptors)) {
            // This function will call the appropiate callback to process the
            // event, in this case the BrowseReply static method.
            err = DNSServiceProcessResult(serviceRef);
            if (err != kDNSServiceErr_NoError) {
               XrdLog.Emsg("OucBonjour", err, "process an event in event loop");
               stopEventLoop = 1;
            }
         }
      } else if (selRes == -1) {
         XrdLog.Emsg("OucBonjour", "The select() call failed");
         stopEventLoop = 1;
      }
   }

   XrdLog.Emsg("OucBonjour", "The browsing event loop has ended unexpectedly");
   return NULL; // Thread ends.
}

void XrdOucAppleBonjour::BrowseReply(DNSServiceRef ref, DNSServiceFlags flags,
                                     uint32_t interfaceIndex, DNSServiceErrorType error,
                                     const char * name, const char * regtype,
                                     const char * domain, void * context)
{
   // Comes with the context parameter to avoid abusing of getInstance()
   XrdOucAppleBonjour *instance;
   XrdOucBonjourNode *node;
   XrdOucBonjourSubscribedEntry * callbackID;

   callbackID = (XrdOucBonjourSubscribedEntry *)context;

   if (error != kDNSServiceErr_NoError) {
      XrdLog.Emsg("OucBonjour", error, "complete the browse callback");
      return;
   }

   // Get the context (the XrdOucBonjour object which holds the lists of nodes).
   instance = &XrdOucAppleBonjour::getInstance();

   // Process the node. First let us know what type of update is.
   if (flags & kDNSServiceFlagsAdd) {
      // ADD a new node to the list.
      node = new XrdOucBonjourNode(name, regtype, domain);

      // Start resolution of the name.
      instance->ResolveNodeInformation(node);

      instance->LockNodeList();
      instance->ListOfNodes.push_back(node);
      instance->UnLockNodeList();

      XrdLog.Say("------ XrdOucBonjour: discovered a new node: ", name);
   } else {
      // REMOVE this node from the list.
      XrdOucAppleBonjourSearchNode predicate(name);

      instance->LockNodeList();
      instance->ListOfNodes.remove_if(predicate);
      instance->UnLockNodeList();

      XrdLog.Say("------ XrdOucBonjour: the node ", name, " went out the network");
   }

   // Notify updates if there wont be more updates in a short period of time.
   if (!(flags & kDNSServiceFlagsMoreComing))
      callbackID->callback(callbackID->context);
}

/******************************************************************************/
/*       B o n j o u r   s e r v i c e s : n o t i f i c a t i o n s          */
/******************************************************************************/

int XrdOucAppleBonjour::SubscribeForUpdates(const char * servicetype,
                                            XrdOucBonjourUpdateCallback callback,
                                            void * context)
{
   pthread_t thread;
   XrdOucBonjourSubscribedEntry * callbackID = (XrdOucBonjourSubscribedEntry *)malloc(sizeof(XrdOucBonjourSubscribedEntry));
   callbackID->callback = callback;
   callbackID->context = context;
   callbackID->serviceType = new XrdOucString(servicetype);

   // Lauch the new browsing thread.
   return XrdSysThread::Run(&thread, BrowseEventLoopThread, callbackID);
}

/******************************************************************************/
/*          B o n j o u r   s e r v i c e s : r e s o l u t i o n             */
/******************************************************************************/

void XrdOucAppleBonjour::ResolveReply(DNSServiceRef ref, DNSServiceFlags flags,
                                      uint32_t interfaceIndex, DNSServiceErrorType error,
                                      const char * fullname, const char * hostname,
                                      uint16_t port, uint16_t txtLen,
                                      const unsigned char * txtVal, void * context)
{
   XrdOucBonjourNode * node;

   if (error != kDNSServiceErr_NoError) {
      XrdLog.Emsg("OucBonjour", error, "complete the resolve callback");
      return;
   }

   node = static_cast<XrdOucBonjourNode *>(context);

   // Copy the information of resolution results to the node.
   node->SetHostName(hostname);
   node->SetPort(ntohs(port));

   // Also, copy the TXT values.
   node->GetBonjourRecord().AddRawTXTRecord((const char *)txtVal);
}

int XrdOucAppleBonjour::ResolveNodeInformation(XrdOucBonjourNode * nodeInfo)
{
   DNSServiceErrorType err;
   DNSServiceRef serviceRef;
   fd_set descriptors;
   int sockfd;
   struct timeval timeout;

   // Launch the resolution procedure.
   err = DNSServiceResolve(&serviceRef,
                           0,
                           0,
                           nodeInfo->GetBonjourRecord().GetServiceName(),
                           nodeInfo->GetBonjourRecord().GetRegisteredType(),
                           nodeInfo->GetBonjourRecord().GetReplyDomain(),
                           ResolveReply,
                           nodeInfo);

   // Check for errors
   if (err != kDNSServiceErr_NoError) {
      XrdLog.Emsg("OucBonjour", err, "start the resolution procedure");
      return -1;
   }

   // Wait for the callback. CAUTION: this call is blocking and may stuck you
   // thread. This will call the callback function.
   sockfd = DNSServiceRefSockFD(serviceRef);
   // Set the fd_set to start select()
   FD_ZERO(&descriptors);
   FD_SET(sockfd, &descriptors);
   timeout.tv_sec = TIMEOUT;
   timeout.tv_usec = 0;
   // Wait for the response.
   if (select(sockfd + 1, &descriptors, NULL, NULL, &timeout) > 0) {
      err = DNSServiceProcessResult(serviceRef);
      // Cancel the resolution process since we must have the data yet.
      DNSServiceRefDeallocate(serviceRef);
      if (err != kDNSServiceErr_NoError) {
         XrdLog.Emsg("OucBonjour", err, "process the resolution procedure");
         return -1;
      }
   } else {
      XrdLog.Emsg("OucBonjour", err, "wait to the resolution response");
      return -1;
   }

   // We finished this OK.
   return 0;
}

/******************************************************************************/
/*        C o n s t r u c t o r s   &   S i n g l e t o n   s t u f f         */
/******************************************************************************/

bool XrdOucAppleBonjour::XrdOucAppleBonjourSearchNode::operator()(XrdOucBonjourNode * value)
{
   return strcmp(value->GetBonjourRecord().GetServiceName(), ServiceName) == 0;
}

XrdOucAppleBonjour * XrdOucAppleBonjour::_Instance = NULL;

XrdSysMutex XrdOucAppleBonjour::SingletonMutex;

XrdOucAppleBonjour::XrdOucAppleBonjour()
{
   putenv("AVAHI_COMPAT_NOWARN=1");
}

XrdOucAppleBonjour::~XrdOucAppleBonjour() { }

// In this case, to get a portable solution, we are not using any platform
// specific keyword (like volatile on Win), so, to minimize the cost of this
// function (mainly, gaining the lock) is highly recommended that any client of
// this class stores a local reference to the singleton instance in order to
// minimize the number of queries to the lock.
XrdOucAppleBonjour &XrdOucAppleBonjour::getInstance()
{
   // At the moment this object is destroyed, the singleton instance will be
   // deleted.
   static XrdOucAppleBonjourSingletonCleanup cleanGuard;

   SingletonMutex.Lock();
   if (!_Instance)
      _Instance = new XrdOucAppleBonjour();
   SingletonMutex.UnLock();

   return *_Instance;
}

XrdOucAppleBonjour::XrdOucAppleBonjourSingletonCleanup::~XrdOucAppleBonjourSingletonCleanup()
{
   SingletonMutex.Lock();
   if (_Instance) {
      delete XrdOucAppleBonjour::_Instance;
      XrdOucAppleBonjour::_Instance = NULL;
   }
   SingletonMutex.UnLock();
}
<commit_msg>fix warning on MacOS X.<commit_after>/*
   C++ implementation of Bonjour services.  Code is based
   on the implementation of TBonjour* classes written by
   Fons Rademakers for the ROOT Framework.
*/

#include <arpa/inet.h>
#include <net/if.h>
#include <sys/select.h>
#include <cstdlib>
#include "Xrd/XrdConfig.hh"
#include "XrdOuc/XrdOucBonjour.hh"
#include "XrdOuc/XrdOucFactoryBonjour.hh"
#include "XrdSys/XrdSysError.hh"
#include "Xrd/XrdInet.hh"
#include "Xrd/XrdProtLoad.hh"

/******************************************************************************/
/*                      G l o b a l   V a r i a b l e s                       */
/******************************************************************************/

extern XrdConfig    XrdConf;              // Defined in XrdMain.cc
extern XrdSysError  XrdLog;               // Defined in XrdMain.cc
extern XrdInet     *XrdNetTCP[];          // Defined by config

/******************************************************************************/
/*        B o n j o u r   s e r v i c e s : r e g i s t r a t i o n           */
/******************************************************************************/

void XrdOucAppleBonjour::RegisterReply(DNSServiceRef ref, DNSServiceFlags flags,
                                       DNSServiceErrorType error, const char * name,
                                       const char * regtype, const char * domain,
                                       void * context)
{
   XrdOucBonjourRegisteredEntry * entry;
   entry = (XrdOucBonjourRegisteredEntry *)context;

   // When this callback is called, it comes with the final results of the
   // procedure and the registered names if there was a renaming due to name
   // collisions with other services.
   if (error != kDNSServiceErr_NoError) {
      ((XrdOucAppleBonjour &)getInstance()).ListOfRegistrations.remove(entry);
      delete entry->record;
      free(entry);
      XrdLog.Emsg("OucBonjour", error, "complete the registration callback");
      return;
   }

   // Update the registered information.
   entry->record->SetServiceName(name);
   entry->record->SetRegisteredType(regtype);
   entry->record->SetReplyDomain(domain);
}

int XrdOucAppleBonjour::RegisterService(XrdOucBonjourRecord &record, unsigned short port)
{
   XrdOucBonjourRegisteredEntry * entry;
   DNSServiceErrorType err;
   fd_set descriptors;
   int sockfd;
   struct timeval timeout;

   // Get the default port.
   if (port == 0)
      port = (XrdNetTCP[0] == XrdNetTCP[XrdProtLoad::ProtoMax]
              ?  -(XrdNetTCP[0]->Port()) : XrdNetTCP[0]->Port());

   // Store information on local list.
   entry = (XrdOucBonjourRegisteredEntry *)malloc(sizeof(XrdOucBonjourRegisteredEntry));
   if (!entry)
      return -1;

   entry->record = new XrdOucBonjourRecord(record);
   entry->port = port;

   // Start the registration procedure.
   err = DNSServiceRegister(&(entry->bonjourRef),
                            0, // No flags
                            0,
                            record.GetServiceName(),
                            record.GetRegisteredType(),
                            record.GetReplyDomain(),
                            NULL, // This host
                            htons(port),
                            record.GetTXTRecordLength(),
                            record.GetTXTRecordData(),
                            RegisterReply,
                            entry);

   if (err != kDNSServiceErr_NoError) {
      XrdLog.Emsg("OucBonjour", err, "rRegigster service", record.GetRegisteredType());
      XrdLog.Emsg("OucBonjour", err, "launch the registration");
      // Free memory.
      delete entry->record;
      free(entry);
      return -1;
   }

   // Wait for the callback. CAUTION: this call is blocking and may stuck you
   // thread. This will call the callback function.
   sockfd = DNSServiceRefSockFD(entry->bonjourRef);
   // Set the fd_set to start select()
   FD_ZERO(&descriptors);
   FD_SET(sockfd, &descriptors);
   timeout.tv_sec = TIMEOUT;
   timeout.tv_usec = 0;
   // Wait for the response.
   if (select(sockfd + 1, &descriptors, NULL, NULL, &timeout) > 0) {
      err = DNSServiceProcessResult(entry->bonjourRef);
      if (err != kDNSServiceErr_NoError) {
         XrdLog.Emsg("OucBonjour", err, "process the registration procedure");
         return -1;
      }
   } else {
      XrdLog.Emsg("OucBonjour", err, "wait to the registration response");
      return -1;
   }

   ListOfRegistrations.push_back(entry);
   return 0;
}

/******************************************************************************/
/*           B o n j o u r   s e r v i c e s : d i s c o v e r y              */
/******************************************************************************/

void * XrdOucAppleBonjour::BrowseEventLoopThread(void * context)
{
   int sockfd;
   int selRes;
   int stopEventLoop = 0;
   DNSServiceRef serviceRef;
   DNSServiceErrorType err;
   fd_set descriptors;
   XrdOucBonjourSubscribedEntry * callbackID;

   callbackID = (XrdOucBonjourSubscribedEntry *)context;

   // This thread is responsible for receiving the updates from the mDNS daemon.
   // We are using a select() based event-loop because is more extensible if we
   // would like to register for more services than one.
   XrdSysThread::SetCancelOn();
   XrdSysThread::SetCancelAsynchronous();

   // Start the DNS service browsing on the network.
   err = DNSServiceBrowse(&serviceRef,
                          0,
                          0,
                          callbackID->serviceType->c_str(),
                          NULL,
                          BrowseReply,
                          context);

   // If there are no errors, launch the event loop.
   if (err != kDNSServiceErr_NoError) {
      XrdLog.Emsg("OucBonjour", err, "launch the discovery process");
      return NULL; // Thread ends.
   }

   // Launch the event loop.
   sockfd = DNSServiceRefSockFD(serviceRef);

   while (!stopEventLoop) {
      // Set the fd_set to start select()
      FD_ZERO(&descriptors);
      FD_SET(sockfd, &descriptors);

      // Wait until there is something to do
      selRes = select(sockfd + 1, &descriptors, NULL, NULL, NULL);

      // Process the new result.
      if (selRes > 0) {
         if (FD_ISSET(sockfd, &descriptors)) {
            // This function will call the appropiate callback to process the
            // event, in this case the BrowseReply static method.
            err = DNSServiceProcessResult(serviceRef);
            if (err != kDNSServiceErr_NoError) {
               XrdLog.Emsg("OucBonjour", err, "process an event in event loop");
               stopEventLoop = 1;
            }
         }
      } else if (selRes == -1) {
         XrdLog.Emsg("OucBonjour", "The select() call failed");
         stopEventLoop = 1;
      }
   }

   XrdLog.Emsg("OucBonjour", "The browsing event loop has ended unexpectedly");
   return NULL; // Thread ends.
}

void XrdOucAppleBonjour::BrowseReply(DNSServiceRef ref, DNSServiceFlags flags,
                                     uint32_t interfaceIndex, DNSServiceErrorType error,
                                     const char * name, const char * regtype,
                                     const char * domain, void * context)
{
   // Comes with the context parameter to avoid abusing of getInstance()
   XrdOucAppleBonjour *instance;
   XrdOucBonjourNode *node;
   XrdOucBonjourSubscribedEntry * callbackID;

   callbackID = (XrdOucBonjourSubscribedEntry *)context;

   if (error != kDNSServiceErr_NoError) {
      XrdLog.Emsg("OucBonjour", error, "complete the browse callback");
      return;
   }

   // Get the context (the XrdOucBonjour object which holds the lists of nodes).
   instance = &XrdOucAppleBonjour::getInstance();

   // Process the node. First let us know what type of update is.
   if (flags & kDNSServiceFlagsAdd) {
      // ADD a new node to the list.
      node = new XrdOucBonjourNode(name, regtype, domain);

      // Start resolution of the name.
      instance->ResolveNodeInformation(node);

      instance->LockNodeList();
      instance->ListOfNodes.push_back(node);
      instance->UnLockNodeList();

      XrdLog.Say("------ XrdOucBonjour: discovered a new node: ", name);
   } else {
      // REMOVE this node from the list.
      XrdOucAppleBonjourSearchNode predicate(name);

      instance->LockNodeList();
      instance->ListOfNodes.remove_if(predicate);
      instance->UnLockNodeList();

      XrdLog.Say("------ XrdOucBonjour: the node ", name, " went out the network");
   }

   // Notify updates if there wont be more updates in a short period of time.
   if (!(flags & kDNSServiceFlagsMoreComing))
      callbackID->callback(callbackID->context);
}

/******************************************************************************/
/*       B o n j o u r   s e r v i c e s : n o t i f i c a t i o n s          */
/******************************************************************************/

int XrdOucAppleBonjour::SubscribeForUpdates(const char * servicetype,
                                            XrdOucBonjourUpdateCallback callback,
                                            void * context)
{
   pthread_t thread;
   XrdOucBonjourSubscribedEntry * callbackID = (XrdOucBonjourSubscribedEntry *)malloc(sizeof(XrdOucBonjourSubscribedEntry));
   callbackID->callback = callback;
   callbackID->context = context;
   callbackID->serviceType = new XrdOucString(servicetype);

   // Lauch the new browsing thread.
   return XrdSysThread::Run(&thread, BrowseEventLoopThread, callbackID);
}

/******************************************************************************/
/*          B o n j o u r   s e r v i c e s : r e s o l u t i o n             */
/******************************************************************************/

void XrdOucAppleBonjour::ResolveReply(DNSServiceRef ref, DNSServiceFlags flags,
                                      uint32_t interfaceIndex, DNSServiceErrorType error,
                                      const char * fullname, const char * hostname,
                                      uint16_t port, uint16_t txtLen,
                                      const unsigned char * txtVal, void * context)
{
   XrdOucBonjourNode * node;

   if (error != kDNSServiceErr_NoError) {
      XrdLog.Emsg("OucBonjour", error, "complete the resolve callback");
      return;
   }

   node = static_cast<XrdOucBonjourNode *>(context);

   // Copy the information of resolution results to the node.
   node->SetHostName(hostname);
   node->SetPort(ntohs(port));

   // Also, copy the TXT values.
   node->GetBonjourRecord().AddRawTXTRecord((const char *)txtVal);
}

int XrdOucAppleBonjour::ResolveNodeInformation(XrdOucBonjourNode * nodeInfo)
{
   DNSServiceErrorType err;
   DNSServiceRef serviceRef;
   fd_set descriptors;
   int sockfd;
   struct timeval timeout;

   // Launch the resolution procedure.
   err = DNSServiceResolve(&serviceRef,
                           0,
                           0,
                           nodeInfo->GetBonjourRecord().GetServiceName(),
                           nodeInfo->GetBonjourRecord().GetRegisteredType(),
                           nodeInfo->GetBonjourRecord().GetReplyDomain(),
                           ResolveReply,
                           nodeInfo);

   // Check for errors
   if (err != kDNSServiceErr_NoError) {
      XrdLog.Emsg("OucBonjour", err, "start the resolution procedure");
      return -1;
   }

   // Wait for the callback. CAUTION: this call is blocking and may stuck you
   // thread. This will call the callback function.
   sockfd = DNSServiceRefSockFD(serviceRef);
   // Set the fd_set to start select()
   FD_ZERO(&descriptors);
   FD_SET(sockfd, &descriptors);
   timeout.tv_sec = TIMEOUT;
   timeout.tv_usec = 0;
   // Wait for the response.
   if (select(sockfd + 1, &descriptors, NULL, NULL, &timeout) > 0) {
      err = DNSServiceProcessResult(serviceRef);
      // Cancel the resolution process since we must have the data yet.
      DNSServiceRefDeallocate(serviceRef);
      if (err != kDNSServiceErr_NoError) {
         XrdLog.Emsg("OucBonjour", err, "process the resolution procedure");
         return -1;
      }
   } else {
      XrdLog.Emsg("OucBonjour", err, "wait to the resolution response");
      return -1;
   }

   // We finished this OK.
   return 0;
}

/******************************************************************************/
/*        C o n s t r u c t o r s   &   S i n g l e t o n   s t u f f         */
/******************************************************************************/

bool XrdOucAppleBonjour::XrdOucAppleBonjourSearchNode::operator()(XrdOucBonjourNode * value)
{
   return strcmp(value->GetBonjourRecord().GetServiceName(), ServiceName) == 0;
}

XrdOucAppleBonjour * XrdOucAppleBonjour::_Instance = NULL;

XrdSysMutex XrdOucAppleBonjour::SingletonMutex;

XrdOucAppleBonjour::XrdOucAppleBonjour()
{
   char *env = new char[22];
   strcpy(env, "AVAHI_COMPAT_NOWARN=1");
   putenv(env);
}

XrdOucAppleBonjour::~XrdOucAppleBonjour() { }

// In this case, to get a portable solution, we are not using any platform
// specific keyword (like volatile on Win), so, to minimize the cost of this
// function (mainly, gaining the lock) is highly recommended that any client of
// this class stores a local reference to the singleton instance in order to
// minimize the number of queries to the lock.
XrdOucAppleBonjour &XrdOucAppleBonjour::getInstance()
{
   // At the moment this object is destroyed, the singleton instance will be
   // deleted.
   static XrdOucAppleBonjourSingletonCleanup cleanGuard;

   SingletonMutex.Lock();
   if (!_Instance)
      _Instance = new XrdOucAppleBonjour();
   SingletonMutex.UnLock();

   return *_Instance;
}

XrdOucAppleBonjour::XrdOucAppleBonjourSingletonCleanup::~XrdOucAppleBonjourSingletonCleanup()
{
   SingletonMutex.Lock();
   if (_Instance) {
      delete XrdOucAppleBonjour::_Instance;
      XrdOucAppleBonjour::_Instance = NULL;
   }
   SingletonMutex.UnLock();
}
<|endoftext|>


<commit_before>/* Jim Viebke
Feb 16 2015 */

#include "parse.h"

std::map<std::string, std::string> Parse::dict; // first string maps to second string

void Parse::initialize()
{
	// map various possible user-input strings to the constant ID used throughout the engine

	using P = Parse;

	if (dict.size() == 0)
	{
		std::cout << "\nLoading parse dictionary...";

		// test commands
		P::dict["recipe"] = P::dict["recipes"] = C::PRINT_RECIPES_COMMAND;

		// verbs
		P::dict["help"] = P::dict["h"] = P::dict["q"] = P::dict["?"] = P::dict["assist"] = P::dict["command"] = P::dict["commands"] = C::SHOW_HELP_COMMAND;
		P::dict["legend"] = C::LEGEND_COMMAND;
		P::dict["i"] = P::dict["inv"] = P::dict["inventory"] = C::INVENTORY_COMMAND;
		P::dict["l"] = P::dict["look"] = C::LOOK_COMMAND;
		P::dict["save"] = P::dict["logout"] = P::dict["quit"] = P::dict["leave"] = P::dict["exit"] = C::SAVE_COMMAND;
		P::dict["move"] = P::dict["m"] = P::dict["walk"] = P::dict["run"] = P::dict["head"] = P::dict["go"] = P::dict["continue"] = P::dict["work"] = C::MOVE_COMMAND;
		P::dict["take"] = P::dict["get"] = P::dict["pick"] = P::dict["choose"] = P::dict["grab"] = P::dict["acquire"] = C::TAKE_COMMAND;
		P::dict["equip"] = P::dict["equipped"] = P::dict["weild"] = P::dict["wield"] = P::dict["ready"] = P::dict["draw"] = C::EQUIP_COMMAND;
		P::dict["item"] = C::ITEM_COMMAND; // viewing equipped item
		P::dict["dequip"] = P::dict["deequip"] = P::dict["unequip"] = P::dict["unwield"] = P::dict["unweild"] = P::dict["store"] = P::dict["sheathe"] = P::dict["sheath"] = P::dict["lower"] = C::DEQUIP_COMMAND;
		P::dict["craft"] = P::dict["make"] = P::dict["create"] = P::dict["fashion"] = C::CRAFT_COMMAND;
		P::dict["mine"] = C::MINE_COMMAND;
		P::dict["drop"] = P::dict["release"] = P::dict["unhand"] = P::dict["add"] = P::dict["place"] = P::dict["put"] = C::DROP_COMMAND;
		P::dict["into"] = P::dict["in"] = P::dict["to"] = P::dict["within"] = P::dict["on"] = P::dict["onto"] = C::INSERT_COMMAND;
		P::dict["from"] = P::dict["form"] = C::FROM_COMMAND;
		P::dict["with"] = C::WITH_COMMAND;
		P::dict["construct"] = P::dict["build"] = P::dict["erect"] = C::CONSTRUCT_COMMAND;
		P::dict["attack"] = P::dict["smash"] = P::dict["strike"] = P::dict["bash"] = P::dict["break"] = P::dict["damage"] = P::dict["stab"] = P::dict["slash"] = P::dict["chop"] = C::ATTACK_COMMAND;

		// quantity
		P::dict["all"] = P::dict["each"] = P::dict["every"] = P::dict["*"] = C::ALL_COMMAND;

		// items

		// items -> other
		P::dict["bloom"] = P::dict["blooms"] = C::BLOOM_ID;
		P::dict["bloomery"] = P::dict["bloomeries"] = C::BLOOMERY_ID;
		P::dict["forge"] = P::dict["forges"] = C::FORGE_ID;
		P::dict["anvil"] = P::dict["anvils"] = C::ANVIL_ID;
		P::dict["tree"] = P::dict["trees"] = C::TREE_ID;
		P::dict["chest"] = P::dict["chests"] = P::dict["crate"] = P::dict["crates"] = C::CHEST_ID;
		P::dict["log"] = P::dict["logs"] = C::LOG_ID;

		// items -> stackables
		P::dict["stone"] = P::dict["stones"] = P::dict["rock"] = P::dict["rocks"] = C::STONE_ID;
		P::dict["branch"] = P::dict["branches"] = C::BRANCH_ID;
		P::dict["stick"] = P::dict["sticks"] = C::STICK_ID;
		P::dict["vine"] = P::dict["vines"] = C::VINE_ID;
		P::dict["arrow"] = P::dict["arrows"] = C::ARROW_ID;
		P::dict["arrowhead"] = P::dict["arrowheads"] = C::ARROWHEAD_ID;
		P::dict["board"] = P::dict["boards"] = P::dict["plank"] = P::dict["planks"] = C::BOARD_ID;

		// items -> tools
		P::dict["bow"] = P::dict["bows"] = C::BOW_ID;
		P::dict["staff"] = P::dict["staffs"] = C::STAFF_ID;
		P::dict["axe"] = P::dict["axes"] = P::dict["ax"] = P::dict["axs"] = C::AXE_ID;
		P::dict["sword"] = P::dict["swords"] = C::SWORD_ID;
		P::dict["hammer"] = P::dict["hammers"] = C::HAMMER_ID;

		// items -> minerals
		P::dict["iron"] = P::dict["irons"] = C::IRON_ID;
		P::dict["limestone"] = P::dict["limestones"] = C::LIMESTONE_ID;

		// items -> mineral keywords (partial IDs for compound mineral names)
		P::dict["deposit"] = C::KEYWORD_DEPOSIT;

		// directions
		P::dict["n"] = P::dict["north"] = C::NORTH;
		P::dict["ne"] = P::dict["northeast"] = C::NORTH_EAST;
		P::dict["e"] = P::dict["east"] = C::EAST;
		P::dict["se"] = P::dict["southeast"] = C::SOUTH_EAST;
		P::dict["s"] = P::dict["south"] = C::SOUTH;
		P::dict["sw"] = P::dict["southwest"] = C::SOUTH_WEST;
		P::dict["w"] = P::dict["west"] = C::WEST;
		P::dict["nw"] = P::dict["northwest"] = C::NORTH_WEST;
		P::dict["u"] = P::dict["up"] = P::dict["upward"] = P::dict["upwards"] = P::dict["upstairs"] = C::UP;
		P::dict["d"] = P::dict["down"] = P::dict["downward"] = P::dict["downwards"] = P::dict["downstairs"] = C::UP;

		// surfaces not already in directions
		P::dict["floor"] = P::dict["ground"] = C::FLOOR;
		P::dict["ceiling"] = C::CEILING;

		// Look Mr. Frodo! A
		P::dict["door"] = C::DOOR;
		P::dict["wall"] = P::dict["surface"] = C::WALL;

		std::stringstream ss;
		ss << "\nLoaded parse dictionary with " << P::dict.size() << " entries.";
		std::cout << ss.str();
	}
}

std::vector<std::string> Parse::tokenize(const std::string & s)
{
	// converts an input string to vector of "engine official" keywords/commands

	std::cout << "\nDEBUG inside parse.tokenize: "; // debugging

	if (Parse::dict.size() == 0) Parse::initialize();

	// convert the space-delimited user input to a vector of strings (one word per string)
	std::stringstream ss(s);
	const std::istream_iterator<std::string> begin(ss);
	std::vector<std::string> strings(begin, std::istream_iterator<std::string>());

	U::print(strings); // debugging

	for (std::string & word : strings) // for each word
	{
		// convert the word to lowercase
		U::to_lower_case(word);

		// replace the typed word with the engine keyword if one exists
		const std::map<std::string, std::string>::const_iterator dict_it = dict.find(word);
		if (dict_it != dict.cend())
		{
			word = dict_it->second;
		}
	}

	return strings;
}
<commit_msg>correct "up" -> "down"<commit_after>/* Jim Viebke
Feb 16 2015 */

#include "parse.h"

std::map<std::string, std::string> Parse::dict; // first string maps to second string

void Parse::initialize()
{
	// map various possible user-input strings to the constant ID used throughout the engine

	using P = Parse;

	if (dict.size() == 0)
	{
		std::cout << "\nLoading parse dictionary...";

		// test commands
		P::dict["recipe"] = P::dict["recipes"] = C::PRINT_RECIPES_COMMAND;

		// verbs
		P::dict["help"] = P::dict["h"] = P::dict["q"] = P::dict["?"] = P::dict["assist"] = P::dict["command"] = P::dict["commands"] = C::SHOW_HELP_COMMAND;
		P::dict["legend"] = C::LEGEND_COMMAND;
		P::dict["i"] = P::dict["inv"] = P::dict["inventory"] = C::INVENTORY_COMMAND;
		P::dict["l"] = P::dict["look"] = C::LOOK_COMMAND;
		P::dict["save"] = P::dict["logout"] = P::dict["quit"] = P::dict["leave"] = P::dict["exit"] = C::SAVE_COMMAND;
		P::dict["move"] = P::dict["m"] = P::dict["walk"] = P::dict["run"] = P::dict["head"] = P::dict["go"] = P::dict["continue"] = P::dict["work"] = C::MOVE_COMMAND;
		P::dict["take"] = P::dict["get"] = P::dict["pick"] = P::dict["choose"] = P::dict["grab"] = P::dict["acquire"] = C::TAKE_COMMAND;
		P::dict["equip"] = P::dict["equipped"] = P::dict["weild"] = P::dict["wield"] = P::dict["ready"] = P::dict["draw"] = C::EQUIP_COMMAND;
		P::dict["item"] = C::ITEM_COMMAND; // viewing equipped item
		P::dict["dequip"] = P::dict["deequip"] = P::dict["unequip"] = P::dict["unwield"] = P::dict["unweild"] = P::dict["store"] = P::dict["sheathe"] = P::dict["sheath"] = P::dict["lower"] = C::DEQUIP_COMMAND;
		P::dict["craft"] = P::dict["make"] = P::dict["create"] = P::dict["fashion"] = C::CRAFT_COMMAND;
		P::dict["mine"] = C::MINE_COMMAND;
		P::dict["drop"] = P::dict["release"] = P::dict["unhand"] = P::dict["add"] = P::dict["place"] = P::dict["put"] = C::DROP_COMMAND;
		P::dict["into"] = P::dict["in"] = P::dict["to"] = P::dict["within"] = P::dict["on"] = P::dict["onto"] = C::INSERT_COMMAND;
		P::dict["from"] = P::dict["form"] = C::FROM_COMMAND;
		P::dict["with"] = C::WITH_COMMAND;
		P::dict["construct"] = P::dict["build"] = P::dict["erect"] = C::CONSTRUCT_COMMAND;
		P::dict["attack"] = P::dict["smash"] = P::dict["strike"] = P::dict["bash"] = P::dict["break"] = P::dict["damage"] = P::dict["stab"] = P::dict["slash"] = P::dict["chop"] = C::ATTACK_COMMAND;

		// quantity
		P::dict["all"] = P::dict["each"] = P::dict["every"] = P::dict["*"] = C::ALL_COMMAND;

		// items

		// items -> other
		P::dict["bloom"] = P::dict["blooms"] = C::BLOOM_ID;
		P::dict["bloomery"] = P::dict["bloomeries"] = C::BLOOMERY_ID;
		P::dict["forge"] = P::dict["forges"] = C::FORGE_ID;
		P::dict["anvil"] = P::dict["anvils"] = C::ANVIL_ID;
		P::dict["tree"] = P::dict["trees"] = C::TREE_ID;
		P::dict["chest"] = P::dict["chests"] = P::dict["crate"] = P::dict["crates"] = C::CHEST_ID;
		P::dict["log"] = P::dict["logs"] = C::LOG_ID;

		// items -> stackables
		P::dict["stone"] = P::dict["stones"] = P::dict["rock"] = P::dict["rocks"] = C::STONE_ID;
		P::dict["branch"] = P::dict["branches"] = C::BRANCH_ID;
		P::dict["stick"] = P::dict["sticks"] = C::STICK_ID;
		P::dict["vine"] = P::dict["vines"] = C::VINE_ID;
		P::dict["arrow"] = P::dict["arrows"] = C::ARROW_ID;
		P::dict["arrowhead"] = P::dict["arrowheads"] = C::ARROWHEAD_ID;
		P::dict["board"] = P::dict["boards"] = P::dict["plank"] = P::dict["planks"] = C::BOARD_ID;

		// items -> tools
		P::dict["bow"] = P::dict["bows"] = C::BOW_ID;
		P::dict["staff"] = P::dict["staffs"] = C::STAFF_ID;
		P::dict["axe"] = P::dict["axes"] = P::dict["ax"] = P::dict["axs"] = C::AXE_ID;
		P::dict["sword"] = P::dict["swords"] = C::SWORD_ID;
		P::dict["hammer"] = P::dict["hammers"] = C::HAMMER_ID;

		// items -> minerals
		P::dict["iron"] = P::dict["irons"] = C::IRON_ID;
		P::dict["limestone"] = P::dict["limestones"] = C::LIMESTONE_ID;

		// items -> mineral keywords (partial IDs for compound mineral names)
		P::dict["deposit"] = C::KEYWORD_DEPOSIT;

		// directions
		P::dict["n"] = P::dict["north"] = C::NORTH;
		P::dict["ne"] = P::dict["northeast"] = C::NORTH_EAST;
		P::dict["e"] = P::dict["east"] = C::EAST;
		P::dict["se"] = P::dict["southeast"] = C::SOUTH_EAST;
		P::dict["s"] = P::dict["south"] = C::SOUTH;
		P::dict["sw"] = P::dict["southwest"] = C::SOUTH_WEST;
		P::dict["w"] = P::dict["west"] = C::WEST;
		P::dict["nw"] = P::dict["northwest"] = C::NORTH_WEST;
		P::dict["u"] = P::dict["up"] = P::dict["upward"] = P::dict["upwards"] = P::dict["upstairs"] = C::UP;
		P::dict["d"] = P::dict["down"] = P::dict["downward"] = P::dict["downwards"] = P::dict["downstairs"] = C::DOWN;

		// surfaces not already in directions
		P::dict["floor"] = P::dict["ground"] = C::FLOOR;
		P::dict["ceiling"] = C::CEILING;

		// Look Mr. Frodo! A
		P::dict["door"] = C::DOOR;
		P::dict["wall"] = P::dict["surface"] = C::WALL;

		std::stringstream ss;
		ss << "\nLoaded parse dictionary with " << P::dict.size() << " entries.";
		std::cout << ss.str();
	}
}

std::vector<std::string> Parse::tokenize(const std::string & s)
{
	// converts an input string to vector of "engine official" keywords/commands

	std::cout << "\nDEBUG inside parse.tokenize: "; // debugging

	if (Parse::dict.size() == 0) Parse::initialize();

	// convert the space-delimited user input to a vector of strings (one word per string)
	std::stringstream ss(s);
	const std::istream_iterator<std::string> begin(ss);
	std::vector<std::string> strings(begin, std::istream_iterator<std::string>());

	U::print(strings); // debugging

	for (std::string & word : strings) // for each word
	{
		// convert the word to lowercase
		U::to_lower_case(word);

		// replace the typed word with the engine keyword if one exists
		const std::map<std::string, std::string>::const_iterator dict_it = dict.find(word);
		if (dict_it != dict.cend())
		{
			word = dict_it->second;
		}
	}

	return strings;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dx_linepolypolygon.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: hr $ $Date: 2007-11-01 17:56:02 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, 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., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <basegfx/tools/canvastools.hxx>
#include "dx_linepolypolygon.hxx"

using namespace ::com::sun::star;

namespace dxcanvas
{
    LinePolyPolygon::LinePolyPolygon( const ::basegfx::B2DPolyPolygon& rPolyPoly ) :
        ::canvas::LinePolyPolygonBase( rPolyPoly ),
        mpGdiPlusUser( GDIPlusUser::createInstance() ),
        mpPath()
    {
    }

    GraphicsPathSharedPtr LinePolyPolygon::getGraphicsPath() const
    {
        // generate GraphicsPath only on demand (gets deleted as soon
        // as any of the modifying methods above touches the
        // B2DPolyPolygon).
        if( !mpPath )
            mpPath = tools::graphicsPathFromB2DPolyPolygon( getPolyPolygon() );

        return mpPath;
    }

    void LinePolyPolygon::modifying() const
    {
        mpPath.reset();
    }
}
<commit_msg>INTEGRATION: CWS presenterview (1.2.14); FILE MERGED 2008/01/13 22:14:58 thb 1.2.14.1: #i85206# Respecting fill rule<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dx_linepolypolygon.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2008-04-03 13:12:26 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, 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., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <basegfx/tools/canvastools.hxx>
#include "dx_linepolypolygon.hxx"

using namespace ::com::sun::star;

namespace dxcanvas
{
    LinePolyPolygon::LinePolyPolygon( const ::basegfx::B2DPolyPolygon& rPolyPoly ) :
        ::canvas::LinePolyPolygonBase( rPolyPoly ),
        mpGdiPlusUser( GDIPlusUser::createInstance() ),
        mpPath()
    {
    }

    GraphicsPathSharedPtr LinePolyPolygon::getGraphicsPath() const
    {
        // generate GraphicsPath only on demand (gets deleted as soon
        // as any of the modifying methods above touches the
        // B2DPolyPolygon).
        if( !mpPath )
        {
            mpPath = tools::graphicsPathFromB2DPolyPolygon( getPolyPolygon() );
            mpPath->SetFillMode( const_cast<LinePolyPolygon*>(this)->getFillRule() == rendering::FillRule_EVEN_ODD ?
                                 Gdiplus::FillModeAlternate : Gdiplus::FillModeWinding );
        }

        return mpPath;
    }

    void LinePolyPolygon::modifying() const
    {
        mpPath.reset();
    }
}
<|endoftext|>


<commit_before><commit_msg>fix a bug with usertime.<commit_after><|endoftext|>


<commit_before><commit_msg>fixed gas conversion test<commit_after><|endoftext|>


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

#include "chrome/browser/autofill/autofill_download.h"

#include <algorithm>

#include "base/logging.h"
#include "base/rand_util.h"
#include "base/stl_util-inl.h"
#include "chrome/browser/autofill/autofill_xml_parser.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
#include "net/http/http_response_headers.h"

#define DISABLED_REQUEST_URL "http://disabled"

#if defined(GOOGLE_CHROME_BUILD)
#include "chrome/browser/autofill/internal/autofill_download_internal.h"
#else
#define AUTO_FILL_QUERY_SERVER_REQUEST_URL DISABLED_REQUEST_URL
#define AUTO_FILL_UPLOAD_SERVER_REQUEST_URL DISABLED_REQUEST_URL
#define AUTO_FILL_QUERY_SERVER_NAME_START_IN_HEADER "SOMESERVER/"
#endif

AutoFillDownloadManager::AutoFillDownloadManager(Profile* profile)
    : profile_(profile),
      observer_(NULL),
      next_query_request_(base::Time::Now()),
      next_upload_request_(base::Time::Now()),
      positive_upload_rate_(0),
      negative_upload_rate_(0),
      fetcher_id_for_unittest_(0),
      is_testing_(false) {
  // |profile_| could be NULL in some unit-tests.
  if (profile_) {
    PrefService* preferences = profile_->GetPrefs();
    positive_upload_rate_ =
        preferences->GetReal(prefs::kAutoFillPositiveUploadRate);
    negative_upload_rate_ =
        preferences->GetReal(prefs::kAutoFillNegativeUploadRate);
  }
}

AutoFillDownloadManager::~AutoFillDownloadManager() {
  STLDeleteContainerPairFirstPointers(url_fetchers_.begin(),
                                      url_fetchers_.end());
}

void AutoFillDownloadManager::SetObserver(
    AutoFillDownloadManager::Observer *observer) {
  if (observer) {
    DCHECK(!observer_);
    observer_ = observer;
  } else {
    observer_ = NULL;
  }
}

bool AutoFillDownloadManager::StartQueryRequest(
    const ScopedVector<FormStructure>& forms) {
  if (next_query_request_ > base::Time::Now()) {
    // We are in back-off mode: do not do the request.
    return false;
  }
  std::string form_xml;
  FormStructure::EncodeQueryRequest(forms, &form_xml);

  FormRequestData request_data;
  request_data.form_signatures.reserve(forms.size());
  for (ScopedVector<FormStructure>::const_iterator it = forms.begin();
       it != forms.end();
       ++it) {
    request_data.form_signatures.push_back((*it)->FormSignature());
  }

  request_data.request_type = AutoFillDownloadManager::REQUEST_QUERY;

  return StartRequest(form_xml, request_data);
}

bool AutoFillDownloadManager::StartUploadRequest(
    const FormStructure& form, bool form_was_matched) {
  if (next_upload_request_ > base::Time::Now()) {
    // We are in back-off mode: do not do the request.
    return false;
  }

  // Check if we need to upload form.
  double upload_rate = form_was_matched ? GetPositiveUploadRate() :
                                          GetNegativeUploadRate();
  if (base::RandDouble() > upload_rate) {
    LOG(INFO) << "AutoFillDownloadManager: Upload request is ignored";
    // If we ever need notification that upload was skipped, add it here.
    return false;
  }
  std::string form_xml;
  form.EncodeUploadRequest(form_was_matched, &form_xml);

  FormRequestData request_data;
  request_data.form_signatures.push_back(form.FormSignature());
  request_data.request_type = AutoFillDownloadManager::REQUEST_UPLOAD;

  return StartRequest(form_xml, request_data);
}

bool AutoFillDownloadManager::CancelRequest(
    const std::string& form_signature,
    AutoFillDownloadManager::AutoFillRequestType request_type) {
  for (std::map<URLFetcher *, FormRequestData>::iterator it =
       url_fetchers_.begin();
       it != url_fetchers_.end();
       ++it) {
    if (std::find(it->second.form_signatures.begin(),
        it->second.form_signatures.end(), form_signature) !=
        it->second.form_signatures.end() &&
        it->second.request_type == request_type) {
      delete it->first;
      url_fetchers_.erase(it);
      return true;
    }
  }
  return false;
}

double AutoFillDownloadManager::GetPositiveUploadRate() const {
  return positive_upload_rate_;
}

double AutoFillDownloadManager::GetNegativeUploadRate() const {
  return negative_upload_rate_;
}

void AutoFillDownloadManager::SetPositiveUploadRate(double rate) {
  if (rate == positive_upload_rate_)
    return;
  positive_upload_rate_ = rate;
  DCHECK_GE(rate, 0.0);
  DCHECK_LE(rate, 1.0);
  DCHECK(profile_);
  PrefService* preferences = profile_->GetPrefs();
  preferences->SetReal(prefs::kAutoFillPositiveUploadRate, rate);
}

void AutoFillDownloadManager::SetNegativeUploadRate(double rate) {
  if (rate == negative_upload_rate_)
    return;
  negative_upload_rate_ = rate;
  DCHECK_GE(rate, 0.0);
  DCHECK_LE(rate, 1.0);
  DCHECK(profile_);
  PrefService* preferences = profile_->GetPrefs();
  preferences->SetReal(prefs::kAutoFillNegativeUploadRate, rate);
}

bool AutoFillDownloadManager::StartRequest(
    const std::string& form_xml,
    const FormRequestData& request_data) {
  std::string request_url;
  if (request_data.request_type == AutoFillDownloadManager::REQUEST_QUERY)
    request_url = AUTO_FILL_QUERY_SERVER_REQUEST_URL;
  else
    request_url = AUTO_FILL_UPLOAD_SERVER_REQUEST_URL;

  if (!request_url.compare(DISABLED_REQUEST_URL) && !is_testing_) {
    // We have it disabled - return true as if it succeeded, but do nothing.
    return true;
  }

  // Id is ignored for regular chrome, in unit test id's for fake fetcher
  // factory will be 0, 1, 2, ...
  URLFetcher *fetcher = URLFetcher::Create(fetcher_id_for_unittest_++,
                                           GURL(request_url),
                                           URLFetcher::POST,
                                           this);
  url_fetchers_[fetcher] = request_data;
  fetcher->set_automatcally_retry_on_5xx(false);
  fetcher->set_request_context(Profile::GetDefaultRequestContext());
  fetcher->set_upload_data("text/plain", form_xml);
  fetcher->Start();
  return true;
}

void AutoFillDownloadManager::OnURLFetchComplete(const URLFetcher* source,
                                                 const GURL& url,
                                                 const URLRequestStatus& status,
                                                 int response_code,
                                                 const ResponseCookies& cookies,
                                                 const std::string& data) {
  std::map<URLFetcher *, FormRequestData>::iterator it =
      url_fetchers_.find(const_cast<URLFetcher*>(source));
  DCHECK(it != url_fetchers_.end());
  std::string type_of_request(
      it->second.request_type == AutoFillDownloadManager::REQUEST_QUERY ?
          "query" : "upload");
  const int kHttpResponseOk = 200;
  const int kHttpInternalServerError = 500;
  const int kHttpBadGateway = 502;
  const int kHttpServiceUnavailable = 503;

  DCHECK(it->second.form_signatures.size());
  if (response_code != kHttpResponseOk) {
    bool back_off = false;
    std::string server_header;
    switch (response_code) {
      case kHttpBadGateway:
        if (!source->response_headers()->EnumerateHeader(NULL, "server",
                                                         &server_header) ||
            StartsWithASCII(server_header.c_str(),
                            AUTO_FILL_QUERY_SERVER_NAME_START_IN_HEADER,
                            false) != 0)
          break;
        // Bad getaway was received from AutoFill servers. Fall through to back
        // off.
      case kHttpInternalServerError:
      case kHttpServiceUnavailable:
        back_off = true;
        break;
    }

    if (back_off) {
      base::Time back_off_time(base::Time::Now() + source->backoff_delay());
      if (it->second.request_type == AutoFillDownloadManager::REQUEST_QUERY) {
        next_query_request_ = back_off_time;
      } else {
        next_upload_request_ = back_off_time;
      }
    }

    LOG(INFO) << "AutoFillDownloadManager: " << type_of_request <<
        " request has failed with response" << response_code;
    if (observer_) {
      observer_->OnHeuristicsRequestError(it->second.form_signatures[0],
                                          it->second.request_type,
                                          response_code);
    }
  } else {
    LOG(INFO) << "AutoFillDownloadManager: " << type_of_request <<
        " request has succeeded";
    if (it->second.request_type == AutoFillDownloadManager::REQUEST_QUERY) {
      if (observer_)
        observer_->OnLoadedAutoFillHeuristics(it->second.form_signatures, data);
    } else {
      double new_positive_upload_rate = 0;
      double new_negative_upload_rate = 0;
      AutoFillUploadXmlParser parse_handler(&new_positive_upload_rate,
                                            &new_negative_upload_rate);
      buzz::XmlParser parser(&parse_handler);
      parser.Parse(data.data(), data.length(), true);
      if (parse_handler.succeeded()) {
        SetPositiveUploadRate(new_positive_upload_rate);
        SetNegativeUploadRate(new_negative_upload_rate);
      }

      if (observer_)
        observer_->OnUploadedAutoFillHeuristics(it->second.form_signatures[0]);
    }
  }
  delete it->first;
  url_fetchers_.erase(it);
}

<commit_msg>Possible fix for 40234 + changed one of the DCHECK to CHECK BUG=40234 TEST=Should not crash Review URL: http://codereview.chromium.org/1594019<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/autofill/autofill_download.h"

#include <algorithm>

#include "base/logging.h"
#include "base/rand_util.h"
#include "base/stl_util-inl.h"
#include "chrome/browser/autofill/autofill_xml_parser.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
#include "net/http/http_response_headers.h"

#define DISABLED_REQUEST_URL "http://disabled"

#if defined(GOOGLE_CHROME_BUILD)
#include "chrome/browser/autofill/internal/autofill_download_internal.h"
#else
#define AUTO_FILL_QUERY_SERVER_REQUEST_URL DISABLED_REQUEST_URL
#define AUTO_FILL_UPLOAD_SERVER_REQUEST_URL DISABLED_REQUEST_URL
#define AUTO_FILL_QUERY_SERVER_NAME_START_IN_HEADER "SOMESERVER/"
#endif

AutoFillDownloadManager::AutoFillDownloadManager(Profile* profile)
    : profile_(profile),
      observer_(NULL),
      next_query_request_(base::Time::Now()),
      next_upload_request_(base::Time::Now()),
      positive_upload_rate_(0),
      negative_upload_rate_(0),
      fetcher_id_for_unittest_(0),
      is_testing_(false) {
  // |profile_| could be NULL in some unit-tests.
  if (profile_) {
    PrefService* preferences = profile_->GetPrefs();
    positive_upload_rate_ =
        preferences->GetReal(prefs::kAutoFillPositiveUploadRate);
    negative_upload_rate_ =
        preferences->GetReal(prefs::kAutoFillNegativeUploadRate);
  }
}

AutoFillDownloadManager::~AutoFillDownloadManager() {
  STLDeleteContainerPairFirstPointers(url_fetchers_.begin(),
                                      url_fetchers_.end());
}

void AutoFillDownloadManager::SetObserver(
    AutoFillDownloadManager::Observer *observer) {
  if (observer) {
    DCHECK(!observer_);
    observer_ = observer;
  } else {
    observer_ = NULL;
  }
}

bool AutoFillDownloadManager::StartQueryRequest(
    const ScopedVector<FormStructure>& forms) {
  if (next_query_request_ > base::Time::Now()) {
    // We are in back-off mode: do not do the request.
    return false;
  }
  std::string form_xml;
  FormStructure::EncodeQueryRequest(forms, &form_xml);

  FormRequestData request_data;
  request_data.form_signatures.reserve(forms.size());
  for (ScopedVector<FormStructure>::const_iterator it = forms.begin();
       it != forms.end();
       ++it) {
    request_data.form_signatures.push_back((*it)->FormSignature());
  }

  request_data.request_type = AutoFillDownloadManager::REQUEST_QUERY;

  return StartRequest(form_xml, request_data);
}

bool AutoFillDownloadManager::StartUploadRequest(
    const FormStructure& form, bool form_was_matched) {
  if (next_upload_request_ > base::Time::Now()) {
    // We are in back-off mode: do not do the request.
    return false;
  }

  // Check if we need to upload form.
  double upload_rate = form_was_matched ? GetPositiveUploadRate() :
                                          GetNegativeUploadRate();
  if (base::RandDouble() > upload_rate) {
    LOG(INFO) << "AutoFillDownloadManager: Upload request is ignored";
    // If we ever need notification that upload was skipped, add it here.
    return false;
  }
  std::string form_xml;
  form.EncodeUploadRequest(form_was_matched, &form_xml);

  FormRequestData request_data;
  request_data.form_signatures.push_back(form.FormSignature());
  request_data.request_type = AutoFillDownloadManager::REQUEST_UPLOAD;

  return StartRequest(form_xml, request_data);
}

bool AutoFillDownloadManager::CancelRequest(
    const std::string& form_signature,
    AutoFillDownloadManager::AutoFillRequestType request_type) {
  for (std::map<URLFetcher *, FormRequestData>::iterator it =
       url_fetchers_.begin();
       it != url_fetchers_.end();
       ++it) {
    if (std::find(it->second.form_signatures.begin(),
        it->second.form_signatures.end(), form_signature) !=
        it->second.form_signatures.end() &&
        it->second.request_type == request_type) {
      delete it->first;
      url_fetchers_.erase(it);
      return true;
    }
  }
  return false;
}

double AutoFillDownloadManager::GetPositiveUploadRate() const {
  return positive_upload_rate_;
}

double AutoFillDownloadManager::GetNegativeUploadRate() const {
  return negative_upload_rate_;
}

void AutoFillDownloadManager::SetPositiveUploadRate(double rate) {
  if (rate == positive_upload_rate_)
    return;
  positive_upload_rate_ = rate;
  DCHECK_GE(rate, 0.0);
  DCHECK_LE(rate, 1.0);
  DCHECK(profile_);
  PrefService* preferences = profile_->GetPrefs();
  preferences->SetReal(prefs::kAutoFillPositiveUploadRate, rate);
}

void AutoFillDownloadManager::SetNegativeUploadRate(double rate) {
  if (rate == negative_upload_rate_)
    return;
  negative_upload_rate_ = rate;
  DCHECK_GE(rate, 0.0);
  DCHECK_LE(rate, 1.0);
  DCHECK(profile_);
  PrefService* preferences = profile_->GetPrefs();
  preferences->SetReal(prefs::kAutoFillNegativeUploadRate, rate);
}

bool AutoFillDownloadManager::StartRequest(
    const std::string& form_xml,
    const FormRequestData& request_data) {
  std::string request_url;
  if (request_data.request_type == AutoFillDownloadManager::REQUEST_QUERY)
    request_url = AUTO_FILL_QUERY_SERVER_REQUEST_URL;
  else
    request_url = AUTO_FILL_UPLOAD_SERVER_REQUEST_URL;

  if (!request_url.compare(DISABLED_REQUEST_URL) && !is_testing_) {
    // We have it disabled - return true as if it succeeded, but do nothing.
    return true;
  }

  // Id is ignored for regular chrome, in unit test id's for fake fetcher
  // factory will be 0, 1, 2, ...
  URLFetcher *fetcher = URLFetcher::Create(fetcher_id_for_unittest_++,
                                           GURL(request_url),
                                           URLFetcher::POST,
                                           this);
  url_fetchers_[fetcher] = request_data;
  fetcher->set_automatcally_retry_on_5xx(false);
  fetcher->set_request_context(Profile::GetDefaultRequestContext());
  fetcher->set_upload_data("text/plain", form_xml);
  fetcher->Start();
  return true;
}

void AutoFillDownloadManager::OnURLFetchComplete(const URLFetcher* source,
                                                 const GURL& url,
                                                 const URLRequestStatus& status,
                                                 int response_code,
                                                 const ResponseCookies& cookies,
                                                 const std::string& data) {
  std::map<URLFetcher *, FormRequestData>::iterator it =
      url_fetchers_.find(const_cast<URLFetcher*>(source));
  if (it == url_fetchers_.end()) {
    // Looks like crash on Mac is possibly caused with callback entering here
    // with unknown fetcher when network is refreshed.
    return;
  }
  std::string type_of_request(
      it->second.request_type == AutoFillDownloadManager::REQUEST_QUERY ?
          "query" : "upload");
  const int kHttpResponseOk = 200;
  const int kHttpInternalServerError = 500;
  const int kHttpBadGateway = 502;
  const int kHttpServiceUnavailable = 503;

  CHECK(it->second.form_signatures.size());
  if (response_code != kHttpResponseOk) {
    bool back_off = false;
    std::string server_header;
    switch (response_code) {
      case kHttpBadGateway:
        if (!source->response_headers()->EnumerateHeader(NULL, "server",
                                                         &server_header) ||
            StartsWithASCII(server_header.c_str(),
                            AUTO_FILL_QUERY_SERVER_NAME_START_IN_HEADER,
                            false) != 0)
          break;
        // Bad getaway was received from AutoFill servers. Fall through to back
        // off.
      case kHttpInternalServerError:
      case kHttpServiceUnavailable:
        back_off = true;
        break;
    }

    if (back_off) {
      base::Time back_off_time(base::Time::Now() + source->backoff_delay());
      if (it->second.request_type == AutoFillDownloadManager::REQUEST_QUERY) {
        next_query_request_ = back_off_time;
      } else {
        next_upload_request_ = back_off_time;
      }
    }

    LOG(INFO) << "AutoFillDownloadManager: " << type_of_request <<
        " request has failed with response" << response_code;
    if (observer_) {
      observer_->OnHeuristicsRequestError(it->second.form_signatures[0],
                                          it->second.request_type,
                                          response_code);
    }
  } else {
    LOG(INFO) << "AutoFillDownloadManager: " << type_of_request <<
        " request has succeeded";
    if (it->second.request_type == AutoFillDownloadManager::REQUEST_QUERY) {
      if (observer_)
        observer_->OnLoadedAutoFillHeuristics(it->second.form_signatures, data);
    } else {
      double new_positive_upload_rate = 0;
      double new_negative_upload_rate = 0;
      AutoFillUploadXmlParser parse_handler(&new_positive_upload_rate,
                                            &new_negative_upload_rate);
      buzz::XmlParser parser(&parse_handler);
      parser.Parse(data.data(), data.length(), true);
      if (parse_handler.succeeded()) {
        SetPositiveUploadRate(new_positive_upload_rate);
        SetNegativeUploadRate(new_negative_upload_rate);
      }

      if (observer_)
        observer_->OnUploadedAutoFillHeuristics(it->second.form_signatures[0]);
    }
  }
  delete it->first;
  url_fetchers_.erase(it);
}

<|endoftext|>


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

#include "chrome/browser/chromeos/boot_times_loader.h"

#include <vector>

#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/message_loop.h"
#include "base/process_util.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "chrome/browser/browser_process.h"
#include "chrome/common/chrome_switches.h"

namespace chromeos {

// File uptime logs are located in.
static const char kLogPath[] = "/tmp";

BootTimesLoader::BootTimesLoader() : backend_(new Backend()) {
}

BootTimesLoader::Handle BootTimesLoader::GetBootTimes(
    CancelableRequestConsumerBase* consumer,
    BootTimesLoader::GetBootTimesCallback* callback) {
  if (!g_browser_process->file_thread()) {
    // This should only happen if Chrome is shutting down, so we don't do
    // anything.
    return 0;
  }

  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  if (command_line.HasSwitch(switches::kTestType)) {
    // TODO(davemoore) This avoids boottimes for tests. This needs to be
    // replaced with a mock of BootTimesLoader.
    return 0;
  }

  scoped_refptr<CancelableRequest<GetBootTimesCallback> > request(
      new CancelableRequest<GetBootTimesCallback>(callback));
  AddRequest(request, consumer);

  g_browser_process->file_thread()->message_loop()->PostTask(
      FROM_HERE,
      NewRunnableMethod(backend_.get(), &Backend::GetBootTimes, request));
  return request->handle();
}

// Executes command within a shell, allowing IO redirection. Searches
// for a whitespace delimited string prefixed by prefix in the output and
// returns it.
static std::string ExecuteInShell(
    const std::string& command, const std::string& prefix) {
  std::vector<std::string> args;
  args.push_back("/bin/sh");
  args.push_back("-c");
  args.push_back(command);
  CommandLine cmd(args);
  std::string out;

  if (base::GetAppOutput(cmd, &out)) {
    size_t index = out.find(prefix);
    if (index != std::string::npos) {
      size_t value_index = index + prefix.size();
      size_t whitespace_index = out.find(' ', value_index);
      size_t chars_left = std::string::npos;
      if (whitespace_index == std::string::npos)
        whitespace_index = out.find('\n', value_index);
      if (whitespace_index != std::string::npos)
        chars_left = whitespace_index - value_index;
      return out.substr(value_index, chars_left);
    }
  }
  return std::string();
}

// Extracts the uptime value from files located in /tmp, returning the
// value as a double in value.
static bool GetUptime(const std::string& log, double* value) {
  FilePath log_dir(kLogPath);
  FilePath log_file = log_dir.Append(log);
  std::string contents;
  *value = 0.0;
  if (file_util::ReadFileToString(log_file, &contents)) {
    size_t space_index = contents.find(' ');
    size_t chars_left =
        space_index != std::string::npos ? space_index : std::string::npos;
    std::string value_string = contents.substr(0, chars_left);
    return StringToDouble(value_string, value);
  }
  return false;
}

void BootTimesLoader::Backend::GetBootTimes(
    scoped_refptr<GetBootTimesRequest> request) {
  const char* kInitialTSCCommand = "dmesg | grep 'Initial TSC value:'";
  const char* kInitialTSCPrefix = "TSC value: ";
  const char* kClockSpeedCommand = "dmesg | grep -e 'Detected.*processor'";
  const char* kClockSpeedPrefix = "Detected ";
  const char* kPreStartup = "uptime-pre-startup";
  const char* kChromeExec = "uptime-chrome-exec";
  const char* kChromeMain = "uptime-chrome-main";
  const char* kXStarted = "uptime-x-started";
  const char* kLoginPromptReady = "uptime-login-prompt-ready";

  if (request->canceled())
    return;

  // Wait until login_prompt_ready is output by reposting.
  FilePath log_dir(kLogPath);
  FilePath log_file = log_dir.Append(kLoginPromptReady);
  if (!file_util::PathExists(log_file)) {
    g_browser_process->file_thread()->message_loop()->PostDelayedTask(
        FROM_HERE,
        NewRunnableMethod(this, &Backend::GetBootTimes, request),
        500);
    return;
  }

  BootTimes boot_times;
  std::string tsc_value = ExecuteInShell(kInitialTSCCommand, kInitialTSCPrefix);
  std::string speed_value =
      ExecuteInShell(kClockSpeedCommand, kClockSpeedPrefix);
  boot_times.firmware = 0;
  if (!tsc_value.empty() && !speed_value.empty()) {
    int64 tsc = 0;
    double speed = 0;
    if (StringToInt64(tsc_value, &tsc) &&
        StringToDouble(speed_value, &speed) &&
        speed > 0) {
      boot_times.firmware = static_cast<double>(tsc) / (speed * 1000000);
    }
  }
  GetUptime(kPreStartup, &boot_times.pre_startup);
  GetUptime(kXStarted, &boot_times.x_started);
  GetUptime(kChromeExec, &boot_times.chrome_exec);
  GetUptime(kChromeMain, &boot_times.chrome_main);
  GetUptime(kLoginPromptReady, &boot_times.login_prompt_ready);

  request->ForwardResult(
      GetBootTimesCallback::TupleType(request->handle(), boot_times));
}

}  // namespace chromeos
<commit_msg>Fix crash on login for debug version of Chrome.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/boot_times_loader.h"

#include <vector>

#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/message_loop.h"
#include "base/process_util.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/common/chrome_switches.h"

namespace chromeos {

// File uptime logs are located in.
static const char kLogPath[] = "/tmp";

// Delay in milliseconds between file read attempts.
static const int64 kReadAttemptDelayMs = 500;

BootTimesLoader::BootTimesLoader() : backend_(new Backend()) {
}

BootTimesLoader::Handle BootTimesLoader::GetBootTimes(
    CancelableRequestConsumerBase* consumer,
    BootTimesLoader::GetBootTimesCallback* callback) {
  if (!g_browser_process->file_thread()) {
    // This should only happen if Chrome is shutting down, so we don't do
    // anything.
    return 0;
  }

  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  if (command_line.HasSwitch(switches::kTestType)) {
    // TODO(davemoore) This avoids boottimes for tests. This needs to be
    // replaced with a mock of BootTimesLoader.
    return 0;
  }

  scoped_refptr<CancelableRequest<GetBootTimesCallback> > request(
      new CancelableRequest<GetBootTimesCallback>(callback));
  AddRequest(request, consumer);

  ChromeThread::PostTask(
      ChromeThread::FILE,
      FROM_HERE,
      NewRunnableMethod(backend_.get(), &Backend::GetBootTimes, request));
  return request->handle();
}

// Executes command within a shell, allowing IO redirection. Searches
// for a whitespace delimited string prefixed by prefix in the output and
// returns it.
static std::string ExecuteInShell(
    const std::string& command, const std::string& prefix) {
  std::vector<std::string> args;
  args.push_back("/bin/sh");
  args.push_back("-c");
  args.push_back(command);
  CommandLine cmd(args);
  std::string out;

  if (base::GetAppOutput(cmd, &out)) {
    size_t index = out.find(prefix);
    if (index != std::string::npos) {
      size_t value_index = index + prefix.size();
      size_t whitespace_index = out.find(' ', value_index);
      size_t chars_left = std::string::npos;
      if (whitespace_index == std::string::npos)
        whitespace_index = out.find('\n', value_index);
      if (whitespace_index != std::string::npos)
        chars_left = whitespace_index - value_index;
      return out.substr(value_index, chars_left);
    }
  }
  return std::string();
}

// Extracts the uptime value from files located in /tmp, returning the
// value as a double in value.
static bool GetUptime(const std::string& log, double* value) {
  FilePath log_dir(kLogPath);
  FilePath log_file = log_dir.Append(log);
  std::string contents;
  *value = 0.0;
  if (file_util::ReadFileToString(log_file, &contents)) {
    size_t space_index = contents.find(' ');
    size_t chars_left =
        space_index != std::string::npos ? space_index : std::string::npos;
    std::string value_string = contents.substr(0, chars_left);
    return StringToDouble(value_string, value);
  }
  return false;
}

void BootTimesLoader::Backend::GetBootTimes(
    scoped_refptr<GetBootTimesRequest> request) {
  const char* kInitialTSCCommand = "dmesg | grep 'Initial TSC value:'";
  const char* kInitialTSCPrefix = "TSC value: ";
  const char* kClockSpeedCommand = "dmesg | grep -e 'Detected.*processor'";
  const char* kClockSpeedPrefix = "Detected ";
  const char* kPreStartup = "uptime-pre-startup";
  const char* kChromeExec = "uptime-chrome-exec";
  const char* kChromeMain = "uptime-chrome-main";
  const char* kXStarted = "uptime-x-started";
  const char* kLoginPromptReady = "uptime-login-prompt-ready";

  if (request->canceled())
    return;

  // Wait until login_prompt_ready is output by reposting.
  FilePath log_dir(kLogPath);
  FilePath log_file = log_dir.Append(kLoginPromptReady);
  if (!file_util::PathExists(log_file)) {
    ChromeThread::PostDelayedTask(
        ChromeThread::FILE,
        FROM_HERE,
        NewRunnableMethod(this, &Backend::GetBootTimes, request),
        kReadAttemptDelayMs);
    return;
  }

  BootTimes boot_times;
  std::string tsc_value = ExecuteInShell(kInitialTSCCommand, kInitialTSCPrefix);
  std::string speed_value =
      ExecuteInShell(kClockSpeedCommand, kClockSpeedPrefix);
  boot_times.firmware = 0;
  if (!tsc_value.empty() && !speed_value.empty()) {
    int64 tsc = 0;
    double speed = 0;
    if (StringToInt64(tsc_value, &tsc) &&
        StringToDouble(speed_value, &speed) &&
        speed > 0) {
      boot_times.firmware = static_cast<double>(tsc) / (speed * 1000000);
    }
  }
  GetUptime(kPreStartup, &boot_times.pre_startup);
  GetUptime(kXStarted, &boot_times.x_started);
  GetUptime(kChromeExec, &boot_times.chrome_exec);
  GetUptime(kChromeMain, &boot_times.chrome_main);
  GetUptime(kLoginPromptReady, &boot_times.login_prompt_ready);

  request->ForwardResult(
      GetBootTimesCallback::TupleType(request->handle(), boot_times));
}

}  // namespace chromeos
<|endoftext|>


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

#include "chrome/browser/history/in_memory_database.h"

#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "build/build_config.h"

namespace history {

InMemoryDatabase::InMemoryDatabase() : URLDatabase() {
}

InMemoryDatabase::~InMemoryDatabase() {
}

bool InMemoryDatabase::InitDB() {
  // Set the database page size to 4K for better performance.
  db_.set_page_size(4096);

  if (!db_.OpenInMemory()) {
    NOTREACHED() << "Cannot open databse " << GetDB().GetErrorMessage();
    return false;
  }

  // No reason to leave data behind in memory when rows are removed.
  ignore_result(db_.Execute("PRAGMA auto_vacuum=1"));

  // Ensure this is really an in-memory-only cache.
  ignore_result(db_.Execute("PRAGMA temp_store=MEMORY"));

  // Create the URL table, but leave it empty for now.
  if (!CreateURLTable(false)) {
    NOTREACHED() << "Unable to create table";
    db_.Close();
    return false;
  }

  // Create the keyword search terms table.
  if (!InitKeywordSearchTermsTable()) {
    NOTREACHED() << "Unable to create keyword search terms";
    db_.Close();
    return false;
  }

  return true;
}

bool InMemoryDatabase::InitFromScratch() {
  if (!InitDB())
    return false;

  // InitDB doesn't create the index so in the disk-loading case, it can be
  // added afterwards.
  CreateMainURLIndex();
  CreateKeywordSearchTermsIndices();
  return true;
}

bool InMemoryDatabase::InitFromDisk(const base::FilePath& history_name) {
  if (!InitDB())
    return false;

  // Attach to the history database on disk.  (We can't ATTACH in the middle of
  // a transaction.)
  sql::Statement attach(GetDB().GetUniqueStatement("ATTACH ? AS history"));
#if defined(OS_POSIX)
  attach.BindString(0, history_name.value());
#else
  attach.BindString(0, WideToUTF8(history_name.value()));
#endif
  if (!attach.Run())
    return false;

  // Copy URL data to memory.
  base::TimeTicks begin_load = base::TimeTicks::Now();
  if (!db_.Execute(
      "INSERT INTO urls SELECT * FROM history.urls WHERE typed_count > 0")) {
    // Unable to get data from the history database. This is OK, the file may
    // just not exist yet.
  }
  base::TimeTicks end_load = base::TimeTicks::Now();
  UMA_HISTOGRAM_MEDIUM_TIMES("History.InMemoryDBPopulate",
                             end_load - begin_load);
  UMA_HISTOGRAM_COUNTS("History.InMemoryDBItemCount", db_.GetLastChangeCount());

  {
    // This calculation should be fast (since it's on an in-memory DB with
    // an average of only 35 rows).
    sql::Statement visit_count(db_.GetUniqueStatement(
        "SELECT sum(visit_count) FROM urls"));
    if (visit_count.Step()) {
      UMA_HISTOGRAM_COUNTS("History.InMemoryTypedUrlVisitCount",
                           visit_count.ColumnInt(0));
    }
  }

  // Insert keyword search related URLs.
  begin_load = base::TimeTicks::Now();
  if (!db_.Execute(
      "INSERT INTO urls SELECT u.id, u.url, u.title, u.visit_count, "
      "u.typed_count, u.last_visit_time, u.hidden, u.favicon_id "
      "FROM history.urls u JOIN history.keyword_search_terms kst "
      "WHERE u.typed_count = 0 AND u.id = kst.url_id")) {
    // Unable to get data from the history database. This is OK, the file may
    // just not exist yet.
  }
  end_load = base::TimeTicks::Now();
  UMA_HISTOGRAM_MEDIUM_TIMES("History.InMemoryDBKeywordURLPopulate",
                             end_load - begin_load);
  UMA_HISTOGRAM_COUNTS("History.InMemoryDBKeywordURLItemCount",
                       db_.GetLastChangeCount());

  // Copy search terms to memory.
  begin_load = base::TimeTicks::Now();
  if (!db_.Execute(
      "INSERT INTO keyword_search_terms SELECT * FROM "
      "history.keyword_search_terms")) {
    // Unable to get data from the history database. This is OK, the file may
    // just not exist yet.
  }
  end_load = base::TimeTicks::Now();
  UMA_HISTOGRAM_MEDIUM_TIMES("History.InMemoryDBKeywordTermsPopulate",
                             end_load - begin_load);
  UMA_HISTOGRAM_COUNTS("History.InMemoryDBKeywordTermsCount",
                       db_.GetLastChangeCount());

  // Detach from the history database on disk.
  if (!db_.Execute("DETACH history")) {
    NOTREACHED() << "Unable to detach from history database.";
    return false;
  }

  // Index the table, this is faster than creating the index first and then
  // inserting into it.
  CreateMainURLIndex();
  CreateKeywordSearchTermsIndices();

  return true;
}

sql::Connection& InMemoryDatabase::GetDB() {
  return db_;
}

}  // namespace history
<commit_msg>Fix non-unique copy into history in-memory urls table.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/history/in_memory_database.h"

#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "build/build_config.h"

namespace history {

InMemoryDatabase::InMemoryDatabase() : URLDatabase() {
}

InMemoryDatabase::~InMemoryDatabase() {
}

bool InMemoryDatabase::InitDB() {
  // Set the database page size to 4K for better performance.
  db_.set_page_size(4096);

  if (!db_.OpenInMemory()) {
    NOTREACHED() << "Cannot open databse " << GetDB().GetErrorMessage();
    return false;
  }

  // No reason to leave data behind in memory when rows are removed.
  ignore_result(db_.Execute("PRAGMA auto_vacuum=1"));

  // Ensure this is really an in-memory-only cache.
  ignore_result(db_.Execute("PRAGMA temp_store=MEMORY"));

  // Create the URL table, but leave it empty for now.
  if (!CreateURLTable(false)) {
    NOTREACHED() << "Unable to create table";
    db_.Close();
    return false;
  }

  // Create the keyword search terms table.
  if (!InitKeywordSearchTermsTable()) {
    NOTREACHED() << "Unable to create keyword search terms";
    db_.Close();
    return false;
  }

  return true;
}

bool InMemoryDatabase::InitFromScratch() {
  if (!InitDB())
    return false;

  // InitDB doesn't create the index so in the disk-loading case, it can be
  // added afterwards.
  CreateMainURLIndex();
  CreateKeywordSearchTermsIndices();
  return true;
}

bool InMemoryDatabase::InitFromDisk(const base::FilePath& history_name) {
  if (!InitDB())
    return false;

  // Attach to the history database on disk.  (We can't ATTACH in the middle of
  // a transaction.)
  sql::Statement attach(GetDB().GetUniqueStatement("ATTACH ? AS history"));
#if defined(OS_POSIX)
  attach.BindString(0, history_name.value());
#else
  attach.BindString(0, WideToUTF8(history_name.value()));
#endif
  if (!attach.Run())
    return false;

  // Copy URL data to memory.
  base::TimeTicks begin_load = base::TimeTicks::Now();
  if (!db_.Execute(
      "INSERT INTO urls SELECT * FROM history.urls WHERE typed_count > 0")) {
    // Unable to get data from the history database. This is OK, the file may
    // just not exist yet.
  }
  base::TimeTicks end_load = base::TimeTicks::Now();
  UMA_HISTOGRAM_MEDIUM_TIMES("History.InMemoryDBPopulate",
                             end_load - begin_load);
  UMA_HISTOGRAM_COUNTS("History.InMemoryDBItemCount", db_.GetLastChangeCount());

  {
    // This calculation should be fast (since it's on an in-memory DB with
    // an average of only 35 rows).
    sql::Statement visit_count(db_.GetUniqueStatement(
        "SELECT sum(visit_count) FROM urls"));
    if (visit_count.Step()) {
      UMA_HISTOGRAM_COUNTS("History.InMemoryTypedUrlVisitCount",
                           visit_count.ColumnInt(0));
    }
  }

  // Insert keyword search related URLs.
  begin_load = base::TimeTicks::Now();
  if (!db_.Execute(
      "INSERT OR IGNORE INTO urls SELECT u.id, u.url, u.title, u.visit_count, "
      "u.typed_count, u.last_visit_time, u.hidden, u.favicon_id "
      "FROM history.urls u JOIN history.keyword_search_terms kst "
      "WHERE u.typed_count = 0 AND u.id = kst.url_id")) {
    // Unable to get data from the history database. This is OK, the file may
    // just not exist yet.
  }
  end_load = base::TimeTicks::Now();
  UMA_HISTOGRAM_MEDIUM_TIMES("History.InMemoryDBKeywordURLPopulate",
                             end_load - begin_load);
  UMA_HISTOGRAM_COUNTS("History.InMemoryDBKeywordURLItemCount",
                       db_.GetLastChangeCount());

  // Copy search terms to memory.
  begin_load = base::TimeTicks::Now();
  if (!db_.Execute(
      "INSERT INTO keyword_search_terms SELECT * FROM "
      "history.keyword_search_terms")) {
    // Unable to get data from the history database. This is OK, the file may
    // just not exist yet.
  }
  end_load = base::TimeTicks::Now();
  UMA_HISTOGRAM_MEDIUM_TIMES("History.InMemoryDBKeywordTermsPopulate",
                             end_load - begin_load);
  UMA_HISTOGRAM_COUNTS("History.InMemoryDBKeywordTermsCount",
                       db_.GetLastChangeCount());

  // Detach from the history database on disk.
  if (!db_.Execute("DETACH history")) {
    NOTREACHED() << "Unable to detach from history database.";
    return false;
  }

  // Index the table, this is faster than creating the index first and then
  // inserting into it.
  CreateMainURLIndex();
  CreateKeywordSearchTermsIndices();

  return true;
}

sql::Connection& InMemoryDatabase::GetDB() {
  return db_;
}

}  // namespace history
<|endoftext|>


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

#include "chrome/common/chrome_version_info.h"

#include "base/android/build_info.h"
#include "base/logging.h"
#include "base/string_util.h"

namespace chrome {

// static
std::string VersionInfo::GetVersionStringModifier() {
  switch (GetChannel()) {
    case CHANNEL_UNKNOWN: return "unknown";
    case CHANNEL_CANARY: return "canary";
    case CHANNEL_DEV: return "dev";
    case CHANNEL_BETA: return "beta";
    case CHANNEL_STABLE: return std::string();
  }
  NOTREACHED() << "Unknown channel " << GetChannel();
  return std::string();
}

// static
VersionInfo::Channel VersionInfo::GetChannel() {
  const base::android::BuildInfo* bi = base::android::BuildInfo::GetInstance();
  DCHECK(bi && bi->package_name());

  if (!strcmp(bi->package_name(), "com.android.chrome"))
    return CHANNEL_STABLE;
  if (!strcmp(bi->package_name(), "com.google.android.apps.chrome_beta"))
    return CHANNEL_BETA;
  if (!strcmp(bi->package_name(), "com.google.android.apps.chrome_dev"))
    return CHANNEL_DEV;

  return CHANNEL_UNKNOWN;
}

}  // namespace chrome
<commit_msg>Uses com.chrome.beta for package name.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/common/chrome_version_info.h"

#include "base/android/build_info.h"
#include "base/logging.h"
#include "base/string_util.h"

namespace chrome {

// static
std::string VersionInfo::GetVersionStringModifier() {
  switch (GetChannel()) {
    case CHANNEL_UNKNOWN: return "unknown";
    case CHANNEL_CANARY: return "canary";
    case CHANNEL_DEV: return "dev";
    case CHANNEL_BETA: return "beta";
    case CHANNEL_STABLE: return std::string();
  }
  NOTREACHED() << "Unknown channel " << GetChannel();
  return std::string();
}

// static
VersionInfo::Channel VersionInfo::GetChannel() {
  const base::android::BuildInfo* bi = base::android::BuildInfo::GetInstance();
  DCHECK(bi && bi->package_name());

  if (!strcmp(bi->package_name(), "com.android.chrome"))
    return CHANNEL_STABLE;
  if (!strcmp(bi->package_name(), "com.chrome.beta"))
    return CHANNEL_BETA;
  if (!strcmp(bi->package_name(), "com.google.android.apps.chrome_dev"))
    return CHANNEL_DEV;

  return CHANNEL_UNKNOWN;
}

}  // namespace chrome
<|endoftext|>