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

  Program:   Visualization Toolkit
  Module:    vtkXMLTreeReader.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
/*-------------------------------------------------------------------------
  Copyright 2008 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
  the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/

#include "vtkXMLTreeReader.h"

#include "vtkBitArray.h"
#include "vtkInformation.h"
#include "vtkIdTypeArray.h"
#include "vtkMutableDirectedGraph.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkSmartPointer.h"
#include "vtkStringArray.h"
#include "vtkTree.h"

#include "vtk_libxml2.h"
#include VTKLIBXML2_HEADER(parser.h)
#include VTKLIBXML2_HEADER(tree.h)

vtkStandardNewMacro(vtkXMLTreeReader);

const char * vtkXMLTreeReader::TagNameField = ".tagname";
const char * vtkXMLTreeReader::CharDataField = ".chardata";

vtkXMLTreeReader::vtkXMLTreeReader()
{
  this->FileName = 0;
  this->XMLString = 0;
  this->SetNumberOfInputPorts(0);
  this->SetNumberOfOutputPorts(1);
  this->ReadCharData = 0;
  this->ReadTagName = 1;
  this->MaskArrays = 0;
  this->EdgePedigreeIdArrayName = 0;
  this->SetEdgePedigreeIdArrayName("edge id");
  this->VertexPedigreeIdArrayName = 0;
  this->SetVertexPedigreeIdArrayName("vertex id");
  this->GenerateEdgePedigreeIds = true;
  this->GenerateVertexPedigreeIds = true;
}

vtkXMLTreeReader::~vtkXMLTreeReader()
{
  this->SetFileName(0);
  this->SetXMLString(0);
  this->SetEdgePedigreeIdArrayName(0);
  this->SetVertexPedigreeIdArrayName(0);
}

void vtkXMLTreeReader::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << "FileName: "
     << (this->FileName ? this->FileName : "(none)") << endl;
  os << indent << "ReadCharData: "
     << (this->ReadCharData ? "on" : "off") << endl;
  os << indent << "ReadTagName: "
     << (this->ReadTagName ? "on" : "off") << endl;
  os << indent << "MaskArrays: "
     << (this->MaskArrays ? "on" : "off") << endl;
  os << indent << "XMLString: "
     << (this->XMLString ? this->XMLString : "(none)") << endl;
  os << indent << "EdgePedigreeIdArrayName: "
     << (this->EdgePedigreeIdArrayName ? this->EdgePedigreeIdArrayName : "(null)") << endl;
  os << indent << "VertexPedigreeIdArrayName: "
     << (this->VertexPedigreeIdArrayName ? this->VertexPedigreeIdArrayName : "(null)") << endl;
  os << indent << "GenerateEdgePedigreeIds: "
     << (this->GenerateEdgePedigreeIds ? "on" : "off") << endl;
  os << indent << "GenerateVertexPedigreeIds: "
     << (this->GenerateVertexPedigreeIds ? "on" : "off") << endl;
}

void vtkXMLTreeReaderProcessElement(vtkMutableDirectedGraph *tree,
   vtkIdType parent, xmlNode *node, int readCharData, int maskArrays)
{
  vtkDataSetAttributes *data = tree->GetVertexData();
  vtkStringArray *nameArr = vtkStringArray::SafeDownCast(data->GetAbstractArray(vtkXMLTreeReader::TagNameField));
  vtkStdString content;
  for (xmlNode *curNode = node; curNode; curNode = curNode->next)
    {
    //cerr << "type=" << curNode->type << ",name=" << curNode->name << endl;
    if (curNode->content)
      {
      const char *curContent = reinterpret_cast<const char*>(curNode->content);
      content += curContent;
      //cerr << "content=" << curNode->content << endl;
      }

    if (curNode->type != XML_ELEMENT_NODE)
      {
      continue;
      }

    vtkIdType vertex = -1;
    vertex = tree->AddVertex();
    if (parent != -1)
      {
      tree->AddEdge(parent, vertex);
      }

    // Append the node tag and character data to the vtkPointData
    if (nameArr) // If the reader has ReadTagName = ON then populate this array
      {
      nameArr->InsertValue(vertex, reinterpret_cast<const char*>(curNode->name));
      }

    // Append the element attributes to the vtkPointData
    for (xmlAttr *curAttr = curNode->properties; curAttr; curAttr = curAttr->next)
      {
      const char *name = reinterpret_cast<const char*>(curAttr->name);
      int len = static_cast<int>(strlen(name));
      char *validName = new char[len+8];
      strcpy(validName, ".valid.");
      strcat(validName, name);
      vtkStringArray *stringArr = vtkStringArray::SafeDownCast(data->GetAbstractArray(name));
      vtkBitArray *bitArr = 0;
      if (maskArrays)
        {
        bitArr = vtkBitArray::SafeDownCast(data->GetAbstractArray(validName));
        }
      if (!stringArr)
        {
        stringArr = vtkStringArray::New();
        stringArr->SetName(name);
        data->AddArray(stringArr);
        stringArr->Delete();
        if (maskArrays)
          {
          bitArr = vtkBitArray::New();
          bitArr->SetName(validName);
          data->AddArray(bitArr);
          bitArr->Delete();
          }
        }
      const char *value = reinterpret_cast<const char*>(curAttr->children->content);
      stringArr->InsertValue(vertex, value);
      if (maskArrays)
        {
        for (vtkIdType i = bitArr->GetNumberOfTuples(); i < vertex; i++)
          {
          bitArr->InsertNextValue(false);
          }
        bitArr->InsertNextValue(true);
        }
      //cerr << "attname=" << name << ",value=" << value << endl;
      delete [] validName;
      }

    // Process this node's children
    vtkXMLTreeReaderProcessElement(tree, vertex, curNode->children, readCharData, maskArrays);
    }

  if (readCharData && parent >= 0)
    {
    vtkStringArray *charArr = vtkStringArray::SafeDownCast(data->GetAbstractArray(vtkXMLTreeReader::CharDataField));
    charArr->InsertValue(parent, content);
    }
}

int vtkXMLTreeReader::RequestData(
  vtkInformation*,
  vtkInformationVector**,
  vtkInformationVector *outputVector)
{
  if (!this->FileName && !this->XMLString)
    {
    vtkErrorMacro("A FileName or XMLString must be specified");
    return 0;
    }

  xmlDoc *doc = NULL;
  if (this->FileName)
    {
    // Parse the file and get the DOM
    doc = xmlReadFile(this->FileName, NULL, 0);
    }
  else if (this->XMLString)
    {
    // Parse from memory and get the DOM
    doc = xmlReadMemory(this->XMLString, static_cast<int>(strlen(this->XMLString)), "noname.xml", NULL, 0);
    }

  // Store the XML hierarchy into a vtkMutableDirectedGraph,
  // later to be placed in a vtkTree.
  vtkSmartPointer<vtkMutableDirectedGraph> builder =
    vtkSmartPointer<vtkMutableDirectedGraph>::New();

  vtkDataSetAttributes *data = builder->GetVertexData();

  if (this->ReadTagName)
    {
    vtkStringArray *nameArr = vtkStringArray::New();
    nameArr->SetName(vtkXMLTreeReader::TagNameField);
    data->AddArray(nameArr);
    nameArr->Delete();
    }

  if (this->ReadCharData)
    {
    vtkStringArray *charArr = vtkStringArray::New();
    charArr->SetName(vtkXMLTreeReader::CharDataField);
    data->AddArray(charArr);
    charArr->Delete();
    }

  // Get the root element node
  xmlNode *rootElement = xmlDocGetRootElement(doc);
  vtkXMLTreeReaderProcessElement(builder, -1, rootElement, this->ReadCharData, this->MaskArrays);

  // Make all the arrays the same size
  for (int i = 0; i < data->GetNumberOfArrays(); i++)
    {
    vtkStringArray *stringArr = vtkStringArray::SafeDownCast(data->GetAbstractArray(i));
    if (stringArr && (stringArr->GetNumberOfTuples() < builder->GetNumberOfVertices()))
      {
      stringArr->InsertValue(builder->GetNumberOfVertices() - 1, vtkStdString(""));
      }
    }

  // Move the XML hierarchy into a vtkTree
  vtkTree *output = vtkTree::GetData(outputVector);
  if (!output->CheckedShallowCopy(builder))
    {
    vtkErrorMacro(<<"Structure is not a valid tree!");
    return 0;
    }

  // Look for or generate vertex pedigree id array.
  if (this->GenerateVertexPedigreeIds)
    {
    // Create vertex pedigree ids
    vtkSmartPointer<vtkIdTypeArray> ids = vtkSmartPointer<vtkIdTypeArray>::New();
    ids->SetName(this->VertexPedigreeIdArrayName);
    vtkIdType numVerts = output->GetNumberOfVertices();
    ids->SetNumberOfTuples(numVerts);
    for (vtkIdType i = 0; i < numVerts; ++i)
      {
      ids->SetValue(i, i);
      }
    output->GetVertexData()->SetPedigreeIds(ids);
    }
  else
    {
    vtkAbstractArray* pedIds = output->GetVertexData()->GetAbstractArray(this->VertexPedigreeIdArrayName);
    if (pedIds)
      {
      output->GetVertexData()->SetPedigreeIds(pedIds);
      }
    else
      {
      vtkErrorMacro(<< "Vertex pedigree ID array not found.");
      return 0;
      }
    }

  // Look for or generate edge pedigree id array.
  if (this->GenerateEdgePedigreeIds)
    {
    // Create vertex pedigree ids
    vtkSmartPointer<vtkIdTypeArray> ids = vtkSmartPointer<vtkIdTypeArray>::New();
    ids->SetName(this->EdgePedigreeIdArrayName);
    vtkIdType numEdges = output->GetNumberOfEdges();
    ids->SetNumberOfTuples(numEdges);
    for (vtkIdType i = 0; i < numEdges; ++i)
      {
      ids->SetValue(i, i);
      }
    output->GetEdgeData()->SetPedigreeIds(ids);
    }
  else
    {
    vtkAbstractArray* pedIds = output->GetEdgeData()->GetAbstractArray(this->EdgePedigreeIdArrayName);
    if (pedIds)
      {
      output->GetEdgeData()->SetPedigreeIds(pedIds);
      }
    else
      {
      vtkErrorMacro(<< "Edge pedigree ID array not found.");
      return 0;
      }
    }

  return 1;
}

<commit_msg>BUG:  Fix memory leak by calling xmlFreeDoc().<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkXMLTreeReader.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
/*-------------------------------------------------------------------------
  Copyright 2008 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
  the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/

#include "vtkXMLTreeReader.h"

#include "vtkBitArray.h"
#include "vtkInformation.h"
#include "vtkIdTypeArray.h"
#include "vtkMutableDirectedGraph.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkSmartPointer.h"
#include "vtkStringArray.h"
#include "vtkTree.h"

#include "vtk_libxml2.h"
#include VTKLIBXML2_HEADER(parser.h)
#include VTKLIBXML2_HEADER(tree.h)

vtkStandardNewMacro(vtkXMLTreeReader);

const char * vtkXMLTreeReader::TagNameField = ".tagname";
const char * vtkXMLTreeReader::CharDataField = ".chardata";

vtkXMLTreeReader::vtkXMLTreeReader()
{
  this->FileName = 0;
  this->XMLString = 0;
  this->SetNumberOfInputPorts(0);
  this->SetNumberOfOutputPorts(1);
  this->ReadCharData = 0;
  this->ReadTagName = 1;
  this->MaskArrays = 0;
  this->EdgePedigreeIdArrayName = 0;
  this->SetEdgePedigreeIdArrayName("edge id");
  this->VertexPedigreeIdArrayName = 0;
  this->SetVertexPedigreeIdArrayName("vertex id");
  this->GenerateEdgePedigreeIds = true;
  this->GenerateVertexPedigreeIds = true;
}

vtkXMLTreeReader::~vtkXMLTreeReader()
{
  this->SetFileName(0);
  this->SetXMLString(0);
  this->SetEdgePedigreeIdArrayName(0);
  this->SetVertexPedigreeIdArrayName(0);
}

void vtkXMLTreeReader::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << "FileName: "
     << (this->FileName ? this->FileName : "(none)") << endl;
  os << indent << "ReadCharData: "
     << (this->ReadCharData ? "on" : "off") << endl;
  os << indent << "ReadTagName: "
     << (this->ReadTagName ? "on" : "off") << endl;
  os << indent << "MaskArrays: "
     << (this->MaskArrays ? "on" : "off") << endl;
  os << indent << "XMLString: "
     << (this->XMLString ? this->XMLString : "(none)") << endl;
  os << indent << "EdgePedigreeIdArrayName: "
     << (this->EdgePedigreeIdArrayName ? this->EdgePedigreeIdArrayName : "(null)") << endl;
  os << indent << "VertexPedigreeIdArrayName: "
     << (this->VertexPedigreeIdArrayName ? this->VertexPedigreeIdArrayName : "(null)") << endl;
  os << indent << "GenerateEdgePedigreeIds: "
     << (this->GenerateEdgePedigreeIds ? "on" : "off") << endl;
  os << indent << "GenerateVertexPedigreeIds: "
     << (this->GenerateVertexPedigreeIds ? "on" : "off") << endl;
}

void vtkXMLTreeReaderProcessElement(vtkMutableDirectedGraph *tree,
   vtkIdType parent, xmlNode *node, int readCharData, int maskArrays)
{
  vtkDataSetAttributes *data = tree->GetVertexData();
  vtkStringArray *nameArr = vtkStringArray::SafeDownCast(data->GetAbstractArray(vtkXMLTreeReader::TagNameField));
  vtkStdString content;
  for (xmlNode *curNode = node; curNode; curNode = curNode->next)
    {
    //cerr << "type=" << curNode->type << ",name=" << curNode->name << endl;
    if (curNode->content)
      {
      const char *curContent = reinterpret_cast<const char*>(curNode->content);
      content += curContent;
      //cerr << "content=" << curNode->content << endl;
      }

    if (curNode->type != XML_ELEMENT_NODE)
      {
      continue;
      }

    vtkIdType vertex = -1;
    vertex = tree->AddVertex();
    if (parent != -1)
      {
      tree->AddEdge(parent, vertex);
      }

    // Append the node tag and character data to the vtkPointData
    if (nameArr) // If the reader has ReadTagName = ON then populate this array
      {
      nameArr->InsertValue(vertex, reinterpret_cast<const char*>(curNode->name));
      }

    // Append the element attributes to the vtkPointData
    for (xmlAttr *curAttr = curNode->properties; curAttr; curAttr = curAttr->next)
      {
      const char *name = reinterpret_cast<const char*>(curAttr->name);
      int len = static_cast<int>(strlen(name));
      char *validName = new char[len+8];
      strcpy(validName, ".valid.");
      strcat(validName, name);
      vtkStringArray *stringArr = vtkStringArray::SafeDownCast(data->GetAbstractArray(name));
      vtkBitArray *bitArr = 0;
      if (maskArrays)
        {
        bitArr = vtkBitArray::SafeDownCast(data->GetAbstractArray(validName));
        }
      if (!stringArr)
        {
        stringArr = vtkStringArray::New();
        stringArr->SetName(name);
        data->AddArray(stringArr);
        stringArr->Delete();
        if (maskArrays)
          {
          bitArr = vtkBitArray::New();
          bitArr->SetName(validName);
          data->AddArray(bitArr);
          bitArr->Delete();
          }
        }
      const char *value = reinterpret_cast<const char*>(curAttr->children->content);
      stringArr->InsertValue(vertex, value);
      if (maskArrays)
        {
        for (vtkIdType i = bitArr->GetNumberOfTuples(); i < vertex; i++)
          {
          bitArr->InsertNextValue(false);
          }
        bitArr->InsertNextValue(true);
        }
      //cerr << "attname=" << name << ",value=" << value << endl;
      delete [] validName;
      }

    // Process this node's children
    vtkXMLTreeReaderProcessElement(tree, vertex, curNode->children, readCharData, maskArrays);
    }

  if (readCharData && parent >= 0)
    {
    vtkStringArray *charArr = vtkStringArray::SafeDownCast(data->GetAbstractArray(vtkXMLTreeReader::CharDataField));
    charArr->InsertValue(parent, content);
    }
}

int vtkXMLTreeReader::RequestData(
  vtkInformation*,
  vtkInformationVector**,
  vtkInformationVector *outputVector)
{
  if (!this->FileName && !this->XMLString)
    {
    vtkErrorMacro("A FileName or XMLString must be specified");
    return 0;
    }

  xmlDoc *doc = NULL;
  if (this->FileName)
    {
    // Parse the file and get the DOM
    doc = xmlReadFile(this->FileName, NULL, 0);
    }
  else if (this->XMLString)
    {
    // Parse from memory and get the DOM
    doc = xmlReadMemory(this->XMLString, static_cast<int>(strlen(this->XMLString)), "noname.xml", NULL, 0);
    }

  // Store the XML hierarchy into a vtkMutableDirectedGraph,
  // later to be placed in a vtkTree.
  vtkSmartPointer<vtkMutableDirectedGraph> builder =
    vtkSmartPointer<vtkMutableDirectedGraph>::New();

  vtkDataSetAttributes *data = builder->GetVertexData();

  if (this->ReadTagName)
    {
    vtkStringArray *nameArr = vtkStringArray::New();
    nameArr->SetName(vtkXMLTreeReader::TagNameField);
    data->AddArray(nameArr);
    nameArr->Delete();
    }

  if (this->ReadCharData)
    {
    vtkStringArray *charArr = vtkStringArray::New();
    charArr->SetName(vtkXMLTreeReader::CharDataField);
    data->AddArray(charArr);
    charArr->Delete();
    }

  // Get the root element node
  xmlNode *rootElement = xmlDocGetRootElement(doc);
  vtkXMLTreeReaderProcessElement(builder, -1, rootElement, this->ReadCharData, this->MaskArrays);

  xmlFreeDoc(doc);

  // Make all the arrays the same size
  for (int i = 0; i < data->GetNumberOfArrays(); i++)
    {
    vtkStringArray *stringArr = vtkStringArray::SafeDownCast(data->GetAbstractArray(i));
    if (stringArr && (stringArr->GetNumberOfTuples() < builder->GetNumberOfVertices()))
      {
      stringArr->InsertValue(builder->GetNumberOfVertices() - 1, vtkStdString(""));
      }
    }

  // Move the XML hierarchy into a vtkTree
  vtkTree *output = vtkTree::GetData(outputVector);
  if (!output->CheckedShallowCopy(builder))
    {
    vtkErrorMacro(<<"Structure is not a valid tree!");
    return 0;
    }

  // Look for or generate vertex pedigree id array.
  if (this->GenerateVertexPedigreeIds)
    {
    // Create vertex pedigree ids
    vtkSmartPointer<vtkIdTypeArray> ids = vtkSmartPointer<vtkIdTypeArray>::New();
    ids->SetName(this->VertexPedigreeIdArrayName);
    vtkIdType numVerts = output->GetNumberOfVertices();
    ids->SetNumberOfTuples(numVerts);
    for (vtkIdType i = 0; i < numVerts; ++i)
      {
      ids->SetValue(i, i);
      }
    output->GetVertexData()->SetPedigreeIds(ids);
    }
  else
    {
    vtkAbstractArray* pedIds = output->GetVertexData()->GetAbstractArray(this->VertexPedigreeIdArrayName);
    if (pedIds)
      {
      output->GetVertexData()->SetPedigreeIds(pedIds);
      }
    else
      {
      vtkErrorMacro(<< "Vertex pedigree ID array not found.");
      return 0;
      }
    }

  // Look for or generate edge pedigree id array.
  if (this->GenerateEdgePedigreeIds)
    {
    // Create vertex pedigree ids
    vtkSmartPointer<vtkIdTypeArray> ids = vtkSmartPointer<vtkIdTypeArray>::New();
    ids->SetName(this->EdgePedigreeIdArrayName);
    vtkIdType numEdges = output->GetNumberOfEdges();
    ids->SetNumberOfTuples(numEdges);
    for (vtkIdType i = 0; i < numEdges; ++i)
      {
      ids->SetValue(i, i);
      }
    output->GetEdgeData()->SetPedigreeIds(ids);
    }
  else
    {
    vtkAbstractArray* pedIds = output->GetEdgeData()->GetAbstractArray(this->EdgePedigreeIdArrayName);
    if (pedIds)
      {
      output->GetEdgeData()->SetPedigreeIds(pedIds);
      }
    else
      {
      vtkErrorMacro(<< "Edge pedigree ID array not found.");
      return 0;
      }
    }

  return 1;
}

<|endoftext|>


<commit_before>/*
   Programmer: Kristoffer Larson
   Date: February 26, 2014

   Description: Write to a file and read it out.

*/

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

void read_file(string sLine) {
   ifstream infile;
   infile.open("afile3.dat");

   cout << "The word is: " << endl;
   infile >> sLine;
   cout << sLine << endl;

   cout << "The definition is: ";
   while (!infile.eof()) {
      getline(infile, sLine);
      cout << sLine << endl;
   }

   infile.close();
}//End read_file

void write_file(string sLine) {
   ofstream outfile;
   outfile.open("afile3.dat");
   string data;

   cout << "Enter a word: " << endl;
   getline (cin, sLine);
   //cin >> sLine;
   outfile << sLine << endl;

   cout << "Enter a definition: " << endl;
   getline (cin, sLine);
   outfile << sLine << endl;

   outfile.close();
}//End write_file

int main () {
   string sLine;

   //write_file(sLine);
   read_file(sLine);

   return 0;
}//End main
<commit_msg>Removed a comment<commit_after>/*
   Programmer: Kristoffer Larson
   Date: February 26, 2014

   Description: Write to a file and read it out.

*/

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

void read_file(string sLine) {
   ifstream infile;
   infile.open("afile3.dat");

   cout << "The word is: " << endl;
   infile >> sLine;
   cout << sLine << endl;

   cout << "The definition is: ";
   while (!infile.eof()) {
      getline(infile, sLine);
      cout << sLine << endl;
   }

   infile.close();
}//End read_file

void write_file(string sLine) {
   ofstream outfile;
   outfile.open("afile3.dat");
   string data;

   cout << "Enter a word: " << endl;
   getline (cin, sLine);
   //cin >> sLine;
   outfile << sLine << endl;

   cout << "Enter a definition: " << endl;
   getline (cin, sLine);
   outfile << sLine << endl;

   outfile.close();
}//End write_file

int main () {
   string sLine;

   write_file(sLine);
   read_file(sLine);

   return 0;
}//End main
<|endoftext|>


<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
 *
 * This application is open source and may be redistributed and/or modified
 * freely and without restriction, both in commercial and non commercial applications,
 * as long as this copyright notice is maintained.
 *
 * This application 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.
*/

#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osgUtil/ShaderGen>

#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>

#include <osgGA/TrackballManipulator>
#include <osgGA/FlightManipulator>
#include <osgGA/DriveManipulator>
#include <osgGA/KeySwitchMatrixManipulator>
#include <osgGA/StateSetManipulator>
#include <osgGA/AnimationPathManipulator>
#include <osgGA/TerrainManipulator>

#include <iostream>

int main(int argc, char** argv)
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+
            " is an example of conversion of fixed function pipeline to GLSL");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");

    osgViewer::Viewer viewer(arguments);

    unsigned int helpType = 0;
    if ((helpType = arguments.readHelpType()))
    {
        arguments.getApplicationUsage()->write(std::cout, helpType);
        return 1;
    }

    // report any errors if they have occurred when parsing the program arguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    if (arguments.argc()<=1)
    {
        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
        return 1;
    }

    // set up the camera manipulators.
    {
        osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;

        keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
        keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() );
        keyswitchManipulator->addMatrixManipulator( '3', "Drive", new osgGA::DriveManipulator() );
        keyswitchManipulator->addMatrixManipulator( '4', "Terrain", new osgGA::TerrainManipulator() );

        std::string pathfile;
        char keyForAnimationPath = '5';
        while (arguments.read("-p",pathfile))
        {
            osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile);
            if (apm || !apm->valid())
            {
                unsigned int num = keyswitchManipulator->getNumMatrixManipulators();
                keyswitchManipulator->addMatrixManipulator( keyForAnimationPath, "Path", apm );
                keyswitchManipulator->selectMatrixManipulator(num);
                ++keyForAnimationPath;
            }
        }

        viewer.setCameraManipulator( keyswitchManipulator.get() );
    }

    // add the state manipulator
    viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) );

    // add the thread model handler
    viewer.addEventHandler(new osgViewer::ThreadingHandler);

    // add the window size toggle handler
    viewer.addEventHandler(new osgViewer::WindowSizeHandler);

    // add the stats handler
    viewer.addEventHandler(new osgViewer::StatsHandler);

    // add the help handler
    viewer.addEventHandler(new osgViewer::HelpHandler(arguments.getApplicationUsage()));

    // add the record camera path handler
    viewer.addEventHandler(new osgViewer::RecordCameraPathHandler);

    // add the LOD Scale handler
    viewer.addEventHandler(new osgViewer::LODScaleHandler);

    // add the screen capture handler
    viewer.addEventHandler(new osgViewer::ScreenCaptureHandler);

    osg::ref_ptr<osg::Program> uberProgram = new osg::Program;
    std::string shaderFilename;
    while(arguments.read("--shader", shaderFilename))
    {
        osg::ref_ptr<osg::Shader> shader = osgDB::readShaderFile(shaderFilename);
        if (shader.valid()) uberProgram->addShader(shader.get());
    }

    std::string outputFilename;
    if (arguments.read("-o", outputFilename)) {}

    // load the data
    osg::ref_ptr<osg::Node> loadedModel = osgDB::readRefNodeFiles(arguments);
    if (!loadedModel)
    {
        std::cout << arguments.getApplicationName() <<": No data loaded" << std::endl;
        return 1;
    }

    osg::ref_ptr<osg::StateSet> rootStateSet = viewer.getCamera()->getStateSet();

    // run the shadergen on the loaded scene graph, and assign the uber shader
    osgUtil::ShaderGenVisitor shadergen;

    if (uberProgram->getNumShaders()>0)
    {
        rootStateSet->setAttribute(uberProgram.get());
        rootStateSet->addUniform(new osg::Uniform("diffuseMap", 0));

        shadergen.remapStateSet(rootStateSet.get());
    }
    else
    {
        shadergen.assignUberProgram(rootStateSet.get());
    }

    loadedModel->accept(shadergen);

    if (!outputFilename.empty())
    {
        osgDB::writeNodeFile(*loadedModel, outputFilename);
        osgDB::writeObjectFile(*(viewer.getCamera()->getStateSet()),"rootStateSet.osgt");
        return 0;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occurred when parsing the program arguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    viewer.setSceneData( loadedModel.get() );

    viewer.realize();

    return viewer.run();

}
<commit_msg>Fixed read shader to safer ref version<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
 *
 * This application is open source and may be redistributed and/or modified
 * freely and without restriction, both in commercial and non commercial applications,
 * as long as this copyright notice is maintained.
 *
 * This application 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.
*/

#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osgUtil/ShaderGen>

#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>

#include <osgGA/TrackballManipulator>
#include <osgGA/FlightManipulator>
#include <osgGA/DriveManipulator>
#include <osgGA/KeySwitchMatrixManipulator>
#include <osgGA/StateSetManipulator>
#include <osgGA/AnimationPathManipulator>
#include <osgGA/TerrainManipulator>

#include <iostream>

int main(int argc, char** argv)
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+
            " is an example of conversion of fixed function pipeline to GLSL");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");

    osgViewer::Viewer viewer(arguments);

    unsigned int helpType = 0;
    if ((helpType = arguments.readHelpType()))
    {
        arguments.getApplicationUsage()->write(std::cout, helpType);
        return 1;
    }

    // report any errors if they have occurred when parsing the program arguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    if (arguments.argc()<=1)
    {
        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
        return 1;
    }

    // set up the camera manipulators.
    {
        osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;

        keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
        keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() );
        keyswitchManipulator->addMatrixManipulator( '3', "Drive", new osgGA::DriveManipulator() );
        keyswitchManipulator->addMatrixManipulator( '4', "Terrain", new osgGA::TerrainManipulator() );

        std::string pathfile;
        char keyForAnimationPath = '5';
        while (arguments.read("-p",pathfile))
        {
            osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile);
            if (apm || !apm->valid())
            {
                unsigned int num = keyswitchManipulator->getNumMatrixManipulators();
                keyswitchManipulator->addMatrixManipulator( keyForAnimationPath, "Path", apm );
                keyswitchManipulator->selectMatrixManipulator(num);
                ++keyForAnimationPath;
            }
        }

        viewer.setCameraManipulator( keyswitchManipulator.get() );
    }

    // add the state manipulator
    viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) );

    // add the thread model handler
    viewer.addEventHandler(new osgViewer::ThreadingHandler);

    // add the window size toggle handler
    viewer.addEventHandler(new osgViewer::WindowSizeHandler);

    // add the stats handler
    viewer.addEventHandler(new osgViewer::StatsHandler);

    // add the help handler
    viewer.addEventHandler(new osgViewer::HelpHandler(arguments.getApplicationUsage()));

    // add the record camera path handler
    viewer.addEventHandler(new osgViewer::RecordCameraPathHandler);

    // add the LOD Scale handler
    viewer.addEventHandler(new osgViewer::LODScaleHandler);

    // add the screen capture handler
    viewer.addEventHandler(new osgViewer::ScreenCaptureHandler);

    osg::ref_ptr<osg::Program> uberProgram = new osg::Program;
    std::string shaderFilename;
    while(arguments.read("--shader", shaderFilename))
    {
        osg::ref_ptr<osg::Shader> shader = osgDB::readRefShaderFile(shaderFilename);
        if (shader.valid()) uberProgram->addShader(shader.get());
    }

    std::string outputFilename;
    if (arguments.read("-o", outputFilename)) {}

    // load the data
    osg::ref_ptr<osg::Node> loadedModel = osgDB::readRefNodeFiles(arguments);
    if (!loadedModel)
    {
        std::cout << arguments.getApplicationName() <<": No data loaded" << std::endl;
        return 1;
    }

    osg::ref_ptr<osg::StateSet> rootStateSet = viewer.getCamera()->getStateSet();

    // run the shadergen on the loaded scene graph, and assign the uber shader
    osgUtil::ShaderGenVisitor shadergen;

    if (uberProgram->getNumShaders()>0)
    {
        rootStateSet->setAttribute(uberProgram.get());
        rootStateSet->addUniform(new osg::Uniform("diffuseMap", 0));

        shadergen.remapStateSet(rootStateSet.get());
    }
    else
    {
        shadergen.assignUberProgram(rootStateSet.get());
    }

    loadedModel->accept(shadergen);

    if (!outputFilename.empty())
    {
        osgDB::writeNodeFile(*loadedModel, outputFilename);
        osgDB::writeObjectFile(*(viewer.getCamera()->getStateSet()),"rootStateSet.osgt");
        return 0;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occurred when parsing the program arguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    viewer.setSceneData( loadedModel.get() );

    viewer.realize();

    return viewer.run();

}
<|endoftext|>


<commit_before>#include "Agent.h"

using namespace std;

Agent::Agent(Environment* _world){
	srand( unsigned int( time(NULL) ) );
	running = false;

	steps = 0;
	posX = 0;
	posY = 0;
	world = _world;
	startPos = world->GetMapNode(0,0);
	endPos = world->GetMapNode(9,14);
	pathFinding = new PathFinding(world);
	pathFinding->FindPath(&movingPath, startPos, endPos);
	positionNode = startPos;
}

Agent::~Agent(){

	delete pathFinding;
	pathFinding = nullptr;
}

int Agent::Run(){
	running = true;
	int numOfSteps = movingPath.size();
	//running until environment is clean
	while (running) {
		world->draw(posX, posY);
		std::cout<< movingPath.size();
		std::cin.get();
		Move();

		//will end if taking more than 1k steps.
		steps++;
		if(steps > numOfSteps) {
			running = false;
			return 1;
		}
	}
	return 0;
};

void Agent::Move() {

	unsigned int index = 1;
	Node* holder = positionNode;
	positionNode = movingPath[movingPath.size() - index];

	if(index < movingPath.size()) {

		movingPath.erase(movingPath.end() - index);
	}
	holder->setValue(0);
	positionNode->setValue(3);
}

<commit_msg>Testing of the A*<commit_after>#include "Agent.h"

using namespace std;

Agent::Agent(Environment* _world){
	srand( unsigned int( time(NULL) ) );
	running = false;

	steps = 0;
	posX = 0;
	posY = 0;
	world = _world;
	startPos = world->GetMapNode(9,4);
	endPos = world->GetMapNode(3, 9);
	pathFinding = new PathFinding(world);
	pathFinding->FindPath(&movingPath, startPos, endPos);
	positionNode = startPos;

}

Agent::~Agent(){

	delete pathFinding;
	pathFinding = nullptr;
}

int Agent::Run(){
	running = true;
	int numOfSteps = movingPath.size();
	//running until environment is clean
	while (running) {
		world->draw(posX, posY);

		Move();
		Sleep( 500 );

		//will end if taking more than 1k steps.
		steps++;
		if(steps > numOfSteps) {
			running = false;
			return 1;
		}
	}
	return 0;
};

void Agent::Move() {

	unsigned int index = 1;
	Node* holder = positionNode;
	positionNode = movingPath[movingPath.size() - index];

	if(index < movingPath.size()) {

		movingPath.erase(movingPath.end() - index);
	}
	holder->setValue(0);
	positionNode->setValue(3);
}

<|endoftext|>


<commit_before>#ifndef CELL_AUTOMATA_ISING_SYSTEM
#define CELL_AUTOMATA_ISING_SYSTEM

#include "../utilpack/array_matrix.hpp"
#include "spin.hpp"
#include "spin_params.hpp"
#include "system_initializer_func.hpp"

template<template<typename> typename spin_T,
	 std::size_t row_Num, std::size_t column_Num, typename simulator_T>
class Ising_system
{
    using random_engine_type		= simulator_T::random_engine_type;
    using random_engine_pointer_type	= random_engine_type*;
    using numerical_type		= simulator_T::numerical_type;
    using spin_type			= spin_T<simulator_T>;
    using array_matrix			=
	Utilpack::array_matrix<spin_type, row_Num, column_Num>;

  public:
    Ising_system(spin_params<spin_type, simulator_T> s_params,
		 random_engine_type& ran_e):
	spin_params(s_params), random_engine(ran_e)
    {
	typename
	uniform_real_distribution<std::size_t>::param_type
	    param(0, array_matrix.size() - 1);
	dist_size.param(param);

	initialize();
    }

    void initialize()
    {
	system_initialize<spin_type, row_Num, column_Num>
	    (system, spin_params, random_engine_pointer);
	return;
    }

    void reset_states()
    {
	for(spin_type spin : system)
	    spin.reset_state();
	return;
    }

    void step()
    {
	array_matrix.at(dist_size(random_engine)).step();
	return;
    }

  private:
    array_matrix system;
    spin_params<spin_type> spin_params;
    random_engine_pointer_type random_engine_pointer;
    std::uniform_int_distribution<std::size_t> dist_size;
};

#endif /* CELL_AUTOMATA_ISING_SYSTEM */
<commit_msg>fix bug and correspond to Spin_params ver having default template parameter.<commit_after>#ifndef CELL_AUTOMATA_ISING_SYSTEM
#define CELL_AUTOMATA_ISING_SYSTEM

#include "../utilpack/array_matrix.hpp"
#include "spin.hpp"
#include "spin_params.hpp"
#include "system_initializer_func.hpp"

template<template<typename> class spin_T,
	 std::size_t row_Num, std::size_t column_Num, typename simulator_T>
class Ising_system
{
    using random_engine_type		= typename simulator_T::random_engine_type;
    using random_engine_pointer_type	= random_engine_type*;
    using numerical_type		= typename simulator_T::numerical_type;
    using spin_type			= spin_T<simulator_T>;
    using array_matrix			=
	Utilpack::array_matrix<spin_type, row_Num, column_Num>;

  public:
    Ising_system(Spin_params<spin_type>& s_params,
		 random_engine_type& ran_e):
	spin_params(s_params), random_engine_pointer(&ran_e)
    {
	typename
	    std::uniform_int_distribution<std::size_t>::param_type
	    param(0, system.size() - 1);
	dist_size.param(param);

	initialize();
    }

    void initialize()
    {
	system_initialize<spin_type, row_Num, column_Num>
	    (system, spin_params, random_engine_pointer);
	return;
    }

    void reset_states()
    {
	for(spin_type spin : system)
	    spin.reset_state();
	return;
    }

    void step()
    {
	system.at(dist_size(*random_engine_pointer)).step();
	return;
    }

  private:
    array_matrix system;
    Spin_params<spin_type> spin_params;
    random_engine_pointer_type random_engine_pointer;
    std::uniform_int_distribution<std::size_t> dist_size;
};

#endif /* CELL_AUTOMATA_ISING_SYSTEM */
<|endoftext|>


<commit_before>//===- llvm/unittest/IR/VerifierTest.cpp - Verifier unit tests ------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/Analysis/Verifier.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalAlias.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "gtest/gtest.h"

namespace llvm {
namespace {

TEST(VerifierTest, Branch_i1) {
  LLVMContext &C = getGlobalContext();
  FunctionType *FTy = FunctionType::get(Type::getVoidTy(C), /*isVarArg=*/false);
  OwningPtr<Function> F(Function::Create(FTy, GlobalValue::ExternalLinkage));
  BasicBlock *Entry = BasicBlock::Create(C, "entry", F.get());
  BasicBlock *Exit = BasicBlock::Create(C, "exit", F.get());
  ReturnInst::Create(C, Exit);

  // To avoid triggering an assertion in BranchInst::Create, we first create
  // a branch with an 'i1' condition ...

  Constant *False = ConstantInt::getFalse(C);
  BranchInst *BI = BranchInst::Create(Exit, Exit, False, Entry);

  // ... then use setOperand to redirect it to a value of different type.

  Constant *Zero32 = ConstantInt::get(IntegerType::get(C, 32), 0);
  BI->setOperand(0, Zero32);

  EXPECT_TRUE(verifyFunction(*F, ReturnStatusAction));
}

TEST(VerifierTest, AliasUnnamedAddr) {
  LLVMContext &C = getGlobalContext();
  Module M("M", C);
  Type *Ty = Type::getInt8Ty(C);
  Constant *Init = Constant::getNullValue(Ty);
  GlobalVariable *Aliasee = new GlobalVariable(M, Ty, true,
                                               GlobalValue::ExternalLinkage,
                                               Init, "foo");
  GlobalAlias *GA = new GlobalAlias(Type::getInt8PtrTy(C),
                                    GlobalValue::ExternalLinkage,
                                    "bar", Aliasee, &M);
  GA->setUnnamedAddr(true);
  std::string Error;
  EXPECT_TRUE(verifyModule(M, ReturnStatusAction, &Error));
  EXPECT_TRUE(StringRef(Error).startswith("Alias cannot have unnamed_addr"));
}
}
}
<commit_msg>Add unit test to test a trivial verifier check.<commit_after>//===- llvm/unittest/IR/VerifierTest.cpp - Verifier unit tests ------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/Analysis/Verifier.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalAlias.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "gtest/gtest.h"

namespace llvm {
namespace {

TEST(VerifierTest, Branch_i1) {
  LLVMContext &C = getGlobalContext();
  FunctionType *FTy = FunctionType::get(Type::getVoidTy(C), /*isVarArg=*/false);
  OwningPtr<Function> F(Function::Create(FTy, GlobalValue::ExternalLinkage));
  BasicBlock *Entry = BasicBlock::Create(C, "entry", F.get());
  BasicBlock *Exit = BasicBlock::Create(C, "exit", F.get());
  ReturnInst::Create(C, Exit);

  // To avoid triggering an assertion in BranchInst::Create, we first create
  // a branch with an 'i1' condition ...

  Constant *False = ConstantInt::getFalse(C);
  BranchInst *BI = BranchInst::Create(Exit, Exit, False, Entry);

  // ... then use setOperand to redirect it to a value of different type.

  Constant *Zero32 = ConstantInt::get(IntegerType::get(C, 32), 0);
  BI->setOperand(0, Zero32);

  EXPECT_TRUE(verifyFunction(*F, ReturnStatusAction));
}

TEST(VerifierTest, AliasUnnamedAddr) {
  LLVMContext &C = getGlobalContext();
  Module M("M", C);
  Type *Ty = Type::getInt8Ty(C);
  Constant *Init = Constant::getNullValue(Ty);
  GlobalVariable *Aliasee = new GlobalVariable(M, Ty, true,
                                               GlobalValue::ExternalLinkage,
                                               Init, "foo");
  GlobalAlias *GA = new GlobalAlias(Type::getInt8PtrTy(C),
                                    GlobalValue::ExternalLinkage,
                                    "bar", Aliasee, &M);
  GA->setUnnamedAddr(true);
  std::string Error;
  EXPECT_TRUE(verifyModule(M, ReturnStatusAction, &Error));
  EXPECT_TRUE(StringRef(Error).startswith("Alias cannot have unnamed_addr"));
}

TEST(VerifierTest, InvalidRetAttribute) {
  LLVMContext &C = getGlobalContext();
  Module M("M", C);
  FunctionType *FTy = FunctionType::get(Type::getInt32Ty(C), /*isVarArg=*/false);
  Function *F = cast<Function>(M.getOrInsertFunction("foo", FTy));
  AttributeSet AS = F->getAttributes();
  F->setAttributes(AS.addAttribute(C, AttributeSet::ReturnIndex,
                                   Attribute::UWTable));

  std::string Error;
  EXPECT_TRUE(verifyModule(M, ReturnStatusAction, &Error));
  EXPECT_TRUE(StringRef(Error).
              startswith("Attribute 'uwtable' only applies to functions!"));
}

}
}
<|endoftext|>


<commit_before>#include "Device.h"
#include "../../Drivers/SPIDisplay/SPIDisplay.h"
#include "../../Drivers/DevicesInterop/GHIElectronics_TinyCLR_Devices.h"
#include "../../Drivers/DevicesInterop/GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Interop.h"

void STM32F4_Startup_OnSoftResetDevice(const TinyCLR_Api_Provider* apiProvider, const TinyCLR_Interop_Provider* interopProvider) {
    apiProvider->Add(apiProvider, SPIDisplay_GetApi());

    auto interopProvider = reinterpret_cast<const TinyCLR_Interop_Provider*>(apiProvider->FindDefault(apiProvider, TinyCLR_Api_Type::InteropProvider));

    if (interopProvider != nullptr)
        interopProvider->Add(interopProvider, &Interop_GHIElectronics_TinyCLR_Devices);
}<commit_msg>Fixed Cerb style to match the rest<commit_after>#include "Device.h"
#include "../../Drivers/SPIDisplay/SPIDisplay.h"
#include "../../Drivers/DevicesInterop/GHIElectronics_TinyCLR_Devices.h"
#include "../../Drivers/DevicesInterop/GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Interop.h"

void STM32F4_Startup_OnSoftResetDevice(const TinyCLR_Api_Provider* apiProvider, const TinyCLR_Interop_Provider* interopProvider) {
    apiProvider->Add(apiProvider, SPIDisplay_GetApi());
    interopProvider->Add(interopProvider, &Interop_GHIElectronics_TinyCLR_Devices);
}
<|endoftext|>


<commit_before>//===- unittests/Ninja/Lexer.cpp ------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "llbuild/Ninja/Lexer.h"

#include "gtest/gtest.h"

using namespace llbuild;

namespace {

TEST(LexerTest, Basic) {
  char Input[] = "| : || # Comment";
  ninja::Lexer Lexer(Input, strlen(Input));

  // Check that we get the appropriate tokens.
  ninja::Token Tok;
  Lexer.lex(Tok);

  Tok.dump();
  EXPECT_TRUE(false);
}

}
<commit_msg>[Ninja] Finish basic ninja::Lexer unites.<commit_after>//===- unittests/Ninja/Lexer.cpp ------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "llbuild/Ninja/Lexer.h"

#include "gtest/gtest.h"

using namespace llbuild;

namespace {

TEST(LexerTest, Basic) {
  char Input[] = "| : || # Comment";
  size_t InputSize = strlen(Input);
  ninja::Lexer Lexer(Input, InputSize);

  // Check that we get the appropriate tokens.
  ninja::Token Tok;
  ninja::Token &Result = Lexer.lex(Tok);

  // Check .lex() result.
  EXPECT_EQ(&Result, &Tok);

  // Check first token.
  EXPECT_EQ(ninja::Token::Kind::Pipe, Tok.TokenKind);
  EXPECT_EQ(&Input[0], Tok.Start);
  EXPECT_EQ(1U, Tok.Length);
  EXPECT_EQ(1U, Tok.Line);
  EXPECT_EQ(0U, Tok.Column);

  // Check second token.
  Lexer.lex(Tok);
  EXPECT_EQ(ninja::Token::Kind::Colon, Tok.TokenKind);
  EXPECT_EQ(&Input[2], Tok.Start);
  EXPECT_EQ(1U, Tok.Length);
  EXPECT_EQ(1U, Tok.Line);
  EXPECT_EQ(2U, Tok.Column);

  // Check third token.
  Lexer.lex(Tok);
  EXPECT_EQ(ninja::Token::Kind::PipePipe, Tok.TokenKind);
  EXPECT_EQ(&Input[4], Tok.Start);
  EXPECT_EQ(2U, Tok.Length);
  EXPECT_EQ(1U, Tok.Line);
  EXPECT_EQ(4U, Tok.Column);

  // Check fourth token.
  Lexer.lex(Tok);
  EXPECT_EQ(ninja::Token::Kind::Comment, Tok.TokenKind);
  EXPECT_EQ(&Input[7], Tok.Start);
  EXPECT_EQ(9U, Tok.Length);
  EXPECT_EQ(1U, Tok.Line);
  EXPECT_EQ(7U, Tok.Column);

  // Check final token.
  Lexer.lex(Tok);
  EXPECT_EQ(ninja::Token::Kind::EndOfFile, Tok.TokenKind);
  EXPECT_EQ(&Input[strlen(Input)], Tok.Start);
  EXPECT_EQ(0U, Tok.Length);
  EXPECT_EQ(1U, Tok.Line);
  EXPECT_EQ(InputSize, Tok.Column);

  // Check we continue to get EOF.
  Lexer.lex(Tok);
  EXPECT_EQ(ninja::Token::Kind::EndOfFile, Tok.TokenKind);
}

}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2003-2006 Tommi Maekitalo
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * As a special exception, you may use this file as part of a free
 * software library without restriction. Specifically, if other files
 * instantiate templates or use macros or inline functions from this
 * file, or you compile this file and link it with other files to
 * produce an executable, this file does not by itself cause the
 * resulting executable to be covered by the GNU General Public
 * License. This exception does not however invalidate any other
 * reasons why the executable file might be covered by the GNU Library
 * General Public License.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "tnt/scopemanager.h"
#include "tnt/sessionscope.h"
#include "tnt/httprequest.h"
#include "tnt/httpreply.h"
#include <cxxtools/log.h>
#include <cxxtools/md5stream.h>
#include <pthread.h>
#include <stdlib.h>

log_define("tntnet.scopemanager")

namespace tnt
{
  static const char sessionCookiePrefix[] = "tntnet.";

  Scope* ScopeManager::getApplicationScope(const std::string& appname)
  {
    cxxtools::MutexLock lock(applicationScopesMutex);

    scopes_type::iterator it = applicationScopes.find(appname);
    if (it == applicationScopes.end())
    {
      log_debug("applicationscope not found - create new");
      Scope* s = new Scope();
      it = applicationScopes.insert(scopes_type::value_type(appname, s)).first;
      return s;
    }
    else
      log_debug("applicationscope found");

    return it->second;
  }

  Sessionscope* ScopeManager::getSessionScope(const std::string& sessioncookie)
  {
    log_debug("getSessionScope(\"" << sessioncookie << "\")");

    cxxtools::MutexLock lock(sessionScopesMutex);
    sessionscopes_type::iterator it = sessionScopes.find(sessioncookie);
    if (it == sessionScopes.end())
    {
      log_debug("session " << sessioncookie << " not found");
      return 0;
    }
    else
    {
      log_debug("session " << sessioncookie << " found");
      it->second->touch();
      return it->second;
    }
  }

  bool ScopeManager::hasSessionScope(const std::string& sessioncookie)
  {
    cxxtools::MutexLock lock(sessionScopesMutex);
    sessionscopes_type::iterator it = sessionScopes.find(sessioncookie);
    return it != sessionScopes.end();
  }

  void ScopeManager::putSessionScope(const std::string& sessioncookie, Sessionscope* s)
  {
    s->addRef();

    cxxtools::MutexLock lock(sessionScopesMutex);
    sessionscopes_type::iterator it = sessionScopes.find(sessioncookie);
    if (it != sessionScopes.end())
    {
      it->second->release();
      it->second = s;
    }
    else
      sessionScopes[sessioncookie] = s;
  }

  void ScopeManager::removeApplicationScope(const std::string& appname)
  {
    cxxtools::MutexLock lock(applicationScopesMutex);
    scopes_type::iterator it = applicationScopes.find(appname);
    if (it != applicationScopes.end())
    {
      it->second->release();
      applicationScopes.erase(it);
    }
  }

  void ScopeManager::removeSessionScope(const std::string& sessioncookie)
  {
    cxxtools::MutexLock lock(sessionScopesMutex);
    sessionscopes_type::iterator it = sessionScopes.find(sessioncookie);
    if (it != sessionScopes.end())
    {
      it->second->release();
      sessionScopes.erase(it);
    }
  }

  void ScopeManager::preCall(HttpRequest& request, const std::string& app)
  {
    // check session-cookie
    std::string currentSessionCookieName = sessionCookiePrefix + app;
    Cookie c = request.getCookie(currentSessionCookieName);
    if (c.getValue().empty())
    {
      /*
      cxxtools::MutexLock lock(sessionScopesMutex);
      log_debug(sessionScopes.size() << " sessions available");
      for (sessionscopes_type::iterator it = sessionScopes.begin(); it != sessionScopes.end(); ++it)
        log_debug("available session " << it->first << " value " << it->second);
        */

      log_debug("session-cookie " << currentSessionCookieName << " not found");
      request.setSessionScope(0);
    }
    else
    {
      log_debug("session-cookie " << currentSessionCookieName << " found: " << c.getValue());
      Sessionscope* sessionScope = getSessionScope(c.getValue());
      if (sessionScope != 0)
      {
        log_debug("session found");
        request.setSessionScope(sessionScope);
      }
    }

    // set application-scope
    request.setApplicationScope(getApplicationScope(app));
  }

  void ScopeManager::postCall(HttpRequest& request, HttpReply& reply, const std::string& app)
  {
    std::string currentSessionCookieName = sessionCookiePrefix + app;

    if (request.hasSessionScope())
    {
      // request has session-scope
      std::string cookie = request.getCookie(currentSessionCookieName);
      if (cookie.empty() || !hasSessionScope(cookie))
      {
        // client has no or unknown cookie

        cxxtools::Md5stream c;
        c << request.getSerial() << '-' << ::pthread_self() << '-' << rand();
        cookie = c.getHexDigest();
        log_info("create new session " << cookie);
        reply.setCookie(currentSessionCookieName, cookie);
        putSessionScope(cookie, &request.getSessionScope());
      }
    }
    else
    {
      std::string cookie = request.getCookie(currentSessionCookieName);
      if (!cookie.empty())
      {
        // client has cookie
        log_debug("clear Cookie " << currentSessionCookieName);
        reply.clearCookie(currentSessionCookieName);
        removeSessionScope(cookie);
      }
    }
  }

  void ScopeManager::checkSessionTimeout()
  {
    time_t currentTime;
    time(&currentTime);
    cxxtools::MutexLock lock(sessionScopesMutex);
    sessionscopes_type::iterator it = sessionScopes.begin();
    unsigned count = 0;
    while (it != sessionScopes.end())
    {
      Sessionscope* s = it->second;
      if (static_cast <unsigned> (currentTime - s->getAtime()) > s->getTimeout())
      {
        log_info("sessiontimeout for session " << it->first << " reached");
        sessionscopes_type::iterator it2 = it;
        ++it;
        s->release();
        sessionScopes.erase(it2);
        ++count;
      }
      else
        ++it;
    }

  }
}
<commit_msg>do not add a dot at the end of session cookie name if no library is set<commit_after>/*
 * Copyright (C) 2003-2006 Tommi Maekitalo
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * As a special exception, you may use this file as part of a free
 * software library without restriction. Specifically, if other files
 * instantiate templates or use macros or inline functions from this
 * file, or you compile this file and link it with other files to
 * produce an executable, this file does not by itself cause the
 * resulting executable to be covered by the GNU General Public
 * License. This exception does not however invalidate any other
 * reasons why the executable file might be covered by the GNU Library
 * General Public License.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "tnt/scopemanager.h"
#include "tnt/sessionscope.h"
#include "tnt/httprequest.h"
#include "tnt/httpreply.h"
#include <cxxtools/log.h>
#include <cxxtools/md5stream.h>
#include <pthread.h>
#include <stdlib.h>

log_define("tntnet.scopemanager")

namespace tnt
{
  Scope* ScopeManager::getApplicationScope(const std::string& appname)
  {
    cxxtools::MutexLock lock(applicationScopesMutex);

    scopes_type::iterator it = applicationScopes.find(appname);
    if (it == applicationScopes.end())
    {
      log_debug("applicationscope not found - create new");
      Scope* s = new Scope();
      it = applicationScopes.insert(scopes_type::value_type(appname, s)).first;
      return s;
    }
    else
      log_debug("applicationscope found");

    return it->second;
  }

  Sessionscope* ScopeManager::getSessionScope(const std::string& sessioncookie)
  {
    log_debug("getSessionScope(\"" << sessioncookie << "\")");

    cxxtools::MutexLock lock(sessionScopesMutex);
    sessionscopes_type::iterator it = sessionScopes.find(sessioncookie);
    if (it == sessionScopes.end())
    {
      log_debug("session " << sessioncookie << " not found");
      return 0;
    }
    else
    {
      log_debug("session " << sessioncookie << " found");
      it->second->touch();
      return it->second;
    }
  }

  bool ScopeManager::hasSessionScope(const std::string& sessioncookie)
  {
    cxxtools::MutexLock lock(sessionScopesMutex);
    sessionscopes_type::iterator it = sessionScopes.find(sessioncookie);
    return it != sessionScopes.end();
  }

  void ScopeManager::putSessionScope(const std::string& sessioncookie, Sessionscope* s)
  {
    s->addRef();

    cxxtools::MutexLock lock(sessionScopesMutex);
    sessionscopes_type::iterator it = sessionScopes.find(sessioncookie);
    if (it != sessionScopes.end())
    {
      it->second->release();
      it->second = s;
    }
    else
      sessionScopes[sessioncookie] = s;
  }

  void ScopeManager::removeApplicationScope(const std::string& appname)
  {
    cxxtools::MutexLock lock(applicationScopesMutex);
    scopes_type::iterator it = applicationScopes.find(appname);
    if (it != applicationScopes.end())
    {
      it->second->release();
      applicationScopes.erase(it);
    }
  }

  void ScopeManager::removeSessionScope(const std::string& sessioncookie)
  {
    cxxtools::MutexLock lock(sessionScopesMutex);
    sessionscopes_type::iterator it = sessionScopes.find(sessioncookie);
    if (it != sessionScopes.end())
    {
      it->second->release();
      sessionScopes.erase(it);
    }
  }

  void ScopeManager::preCall(HttpRequest& request, const std::string& app)
  {
    // check session-cookie
    std::string currentSessionCookieName = app.empty() ? std::string("tntnet") : "tntnet." + app;
    Cookie c = request.getCookie(currentSessionCookieName);
    if (c.getValue().empty())
    {
      /*
      cxxtools::MutexLock lock(sessionScopesMutex);
      log_debug(sessionScopes.size() << " sessions available");
      for (sessionscopes_type::iterator it = sessionScopes.begin(); it != sessionScopes.end(); ++it)
        log_debug("available session " << it->first << " value " << it->second);
        */

      log_debug("session-cookie " << currentSessionCookieName << " not found");
      request.setSessionScope(0);
    }
    else
    {
      log_debug("session-cookie " << currentSessionCookieName << " found: " << c.getValue());
      Sessionscope* sessionScope = getSessionScope(c.getValue());
      if (sessionScope != 0)
      {
        log_debug("session found");
        request.setSessionScope(sessionScope);
      }
    }

    // set application-scope
    request.setApplicationScope(getApplicationScope(app));
  }

  void ScopeManager::postCall(HttpRequest& request, HttpReply& reply, const std::string& app)
  {
    std::string currentSessionCookieName = app.empty() ? std::string("tntnet") : "tntnet." + app;

    if (request.hasSessionScope())
    {
      // request has session-scope
      std::string cookie = request.getCookie(currentSessionCookieName);
      if (cookie.empty() || !hasSessionScope(cookie))
      {
        // client has no or unknown cookie

        cxxtools::Md5stream c;
        c << request.getSerial() << '-' << ::pthread_self() << '-' << rand();
        cookie = c.getHexDigest();
        log_info("create new session " << cookie);
        reply.setCookie(currentSessionCookieName, cookie);
        putSessionScope(cookie, &request.getSessionScope());
      }
    }
    else
    {
      std::string cookie = request.getCookie(currentSessionCookieName);
      if (!cookie.empty())
      {
        // client has cookie
        log_debug("clear Cookie " << currentSessionCookieName);
        reply.clearCookie(currentSessionCookieName);
        removeSessionScope(cookie);
      }
    }
  }

  void ScopeManager::checkSessionTimeout()
  {
    time_t currentTime;
    time(&currentTime);
    cxxtools::MutexLock lock(sessionScopesMutex);
    sessionscopes_type::iterator it = sessionScopes.begin();
    unsigned count = 0;
    while (it != sessionScopes.end())
    {
      Sessionscope* s = it->second;
      if (static_cast <unsigned> (currentTime - s->getAtime()) > s->getTimeout())
      {
        log_info("sessiontimeout for session " << it->first << " reached");
        sessionscopes_type::iterator it2 = it;
        ++it;
        s->release();
        sessionScopes.erase(it2);
        ++count;
      }
      else
        ++it;
    }

  }
}
<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 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 <Windowsx.h>

#include "base/registry.h"

#include "Resource.h"

// This enum needs to be in sync with the strings below.
enum Branch {
  UNKNOWN_BRANCH = 0,
  DEV_BRANCH,
  BETA_BRANCH,
  STABLE_BRANCH,
};

// This vector of strings needs to be in sync with the Branch enum above.
static const wchar_t* const kBranchStrings[] = {
  L"?",
  L"1.1-dev",
  L"1.1-beta",
  L"",
};

// This vector of strings needs to be in sync with the Branch enum above.
static const wchar_t* const kBranchStringsReadable[] = {
  L"?",
  L"Dev",
  L"Beta",
  L"Stable",
};

// The Registry Hive to write to. Points to the hive where we found the 'ap' key
// unless there is an error, in which case it is 0.
HKEY registry_hive = 0;

// The value of the 'ap' key under the registry hive specified in
// |registry_hive|.
std::wstring update_branch;

// The Google Update key to read to find out which branch you are on.
static const wchar_t* const kGoogleUpdateKey =
    L"Software\\Google\\Update\\ClientState\\"
    L"{8A69D345-D564-463C-AFF1-A69D9E530F96}";

// The Google Update value that defines which branch you are on.
static const wchar_t* const kBranchKey = L"ap";

// The suffix Google Update sometimes adds to the channel name (channel names
// are defined in kBranchStrings), indicating that a full install is needed. We
// strip this out (if present) for the purpose of determining which channel you
// are on.
static const wchar_t* const kChannelSuffix = L"-full";

// Title to show in the MessageBoxes.
static const wchar_t* const kMessageBoxTitle = L"Google Chrome Channel Changer";

// A parameter passed into us when we are trying to elevate. This is used as a
// safeguard to make sure we only try to elevate once (so that if it fails we
// don't create an infinite process spawn loop).
static const wchar_t* const kElevationParam = L"--elevation-attempt";

// The icon to use.
static HICON dlg_icon = NULL;

void DetectBranch() {
  // See if we can find the 'ap' key on the HKCU branch.
  registry_hive = HKEY_CURRENT_USER;
  RegKey google_update_hkcu(registry_hive, kGoogleUpdateKey, KEY_READ);
  if (!google_update_hkcu.Valid() ||
      !google_update_hkcu.ReadValue(kBranchKey, &update_branch)) {
    // HKCU failed us, try the same for the HKLM branch.
    registry_hive = HKEY_LOCAL_MACHINE;
    RegKey google_update_hklm(registry_hive, kGoogleUpdateKey, KEY_READ);
    if (!google_update_hklm.Valid() ||
        !google_update_hklm.ReadValue(kBranchKey, &update_branch)) {
      // HKLM also failed us! "Set condition 1 throughout the ship!"
      registry_hive = 0;  // Failed to find the 'ap' key.
      update_branch = kBranchStrings[UNKNOWN_BRANCH];
    }
  }

  // We look for '1.1-beta' or '1.1-dev', but Google Update might have added
  // '-full' to the channel name, which we need to strip out to determine what
  // channel you are on.
  std::wstring suffix = kChannelSuffix;
  if (update_branch.length() > suffix.length()) {
    size_t index = update_branch.rfind(suffix);
    if (index != std::wstring::npos &&
        index == update_branch.length() - suffix.length()) {
      update_branch = update_branch.substr(0, index);
    }
  }
}

void SetMainLabel(HWND dialog, Branch branch) {
  std::wstring main_label = L"You are currently on ";
  if (branch == DEV_BRANCH || branch == BETA_BRANCH || branch == STABLE_BRANCH)
    main_label += std::wstring(L"the ") + kBranchStringsReadable[branch] +
                  std::wstring(L" channel");
  else
    main_label += L"NO UPDATE CHANNEL";

  main_label += L". Choose a different channel and click Update, "
                L"or click Close to stay on this channel.";

  SetWindowText(GetDlgItem(dialog, IDC_LABEL_MAIN), main_label.c_str());
}

void OnInitDialog(HWND dialog) {
  SendMessage(dialog, WM_SETICON, (WPARAM) false, (LPARAM) dlg_icon);

  Branch branch = UNKNOWN_BRANCH;
  if (update_branch == kBranchStrings[STABLE_BRANCH]) {
    branch = STABLE_BRANCH;
  } else if (update_branch == kBranchStrings[DEV_BRANCH]) {
    branch = DEV_BRANCH;
  } else if (update_branch == kBranchStrings[BETA_BRANCH]) {
    branch = BETA_BRANCH;
  } else {
    // Hide the controls we can't use.
    EnableWindow(GetDlgItem(dialog, IDOK), false);
    EnableWindow(GetDlgItem(dialog, IDC_STABLE), false);
    EnableWindow(GetDlgItem(dialog, IDC_BETA), false);
    EnableWindow(GetDlgItem(dialog, IDC_CUTTING_EDGE), false);

    MessageBox(dialog, L"KEY NOT FOUND\n\nGoogle Chrome is not installed, or "
                       L"is not using GoogleUpdate for updates.",
                       kMessageBoxTitle,
                       MB_ICONEXCLAMATION | MB_OK);
  }

  SetMainLabel(dialog, branch);

  CheckDlgButton(dialog, IDC_STABLE,
                 branch == STABLE_BRANCH ? BST_CHECKED : BST_UNCHECKED);
  CheckDlgButton(dialog, IDC_CUTTING_EDGE,
                 branch == DEV_BRANCH ? BST_CHECKED : BST_UNCHECKED);
  CheckDlgButton(dialog, IDC_BETA,
                 branch == BETA_BRANCH ? BST_CHECKED : BST_UNCHECKED);
}

INT_PTR OnCtlColorStatic(HWND dialog, WPARAM wparam, LPARAM lparam) {
  HDC hdc = reinterpret_cast<HDC>(wparam);
  HWND control_wnd = reinterpret_cast<HWND>(lparam);

  if (GetDlgItem(dialog, IDC_STABLE) == control_wnd ||
      GetDlgItem(dialog, IDC_BETA) == control_wnd ||
      GetDlgItem(dialog, IDC_CUTTING_EDGE) == control_wnd ||
      GetDlgItem(dialog, IDC_LABEL_MAIN) == control_wnd ||
      GetDlgItem(dialog, IDC_SECONDARY_LABEL) == control_wnd) {
    SetBkMode(hdc, TRANSPARENT);
    SetTextColor(hdc, RGB(0, 0, 0));
    return reinterpret_cast<INT_PTR>(GetSysColorBrush(COLOR_WINDOW));
  }

  return static_cast<INT_PTR>(FALSE);
}

void SaveChanges(HWND dialog) {
  Branch branch = UNKNOWN_BRANCH;
  if (IsDlgButtonChecked(dialog, IDC_STABLE))
    branch = STABLE_BRANCH;
  else if (IsDlgButtonChecked(dialog, IDC_BETA))
    branch = BETA_BRANCH;
  else if (IsDlgButtonChecked(dialog, IDC_CUTTING_EDGE))
    branch = DEV_BRANCH;

  if (branch != UNKNOWN_BRANCH) {
    RegKey google_update(registry_hive, kGoogleUpdateKey, KEY_WRITE);
    if (!google_update.WriteValue(kBranchKey, kBranchStrings[branch])) {
      MessageBox(dialog, L"Unable to change value. Please make sure you\n"
                         L"have permission to change registry keys.",
                         L"Unable to update branch info", MB_OK | MB_ICONERROR);
    } else {
      std::wstring save_msg = L"Your changes have been saved.\nYou are now "
                              L"on the " +
                              std::wstring(kBranchStringsReadable[branch]) +
                              L" branch.";
      MessageBox(dialog, save_msg.c_str(), L"Changes were saved",
                 MB_OK | MB_ICONINFORMATION);

      SetMainLabel(dialog, branch);
    }
  }
}

INT_PTR CALLBACK DialogWndProc(HWND dialog,
                               UINT message_id,
                               WPARAM wparam,
                               LPARAM lparam) {
  UNREFERENCED_PARAMETER(lparam);

  switch (message_id) {
    case WM_INITDIALOG:
      OnInitDialog(dialog);
      return static_cast<INT_PTR>(TRUE);
    case WM_CTLCOLORSTATIC:
      return OnCtlColorStatic(dialog, wparam, lparam);
    case WM_COMMAND:
      // If the user presses the OK button.
      if (LOWORD(wparam) == IDOK) {
        SaveChanges(dialog);
        return static_cast<INT_PTR>(TRUE);
      }
      // If the user presses the Cancel button.
      if (LOWORD(wparam) == IDCANCEL) {
        ::EndDialog(dialog, LOWORD(wparam));
        return static_cast<INT_PTR>(TRUE);
      }
      break;
    case WM_ERASEBKGND:
      PAINTSTRUCT paint;
      HDC hdc = BeginPaint(dialog, &paint);
      if (!hdc)
        return static_cast<INT_PTR>(FALSE);  // We didn't handle it.

      // Fill the background with White.
      HBRUSH brush = GetStockBrush(WHITE_BRUSH);
      HGDIOBJ old_brush = SelectObject(hdc, brush);
      RECT rc;
      GetClientRect(dialog, &rc);
      FillRect(hdc, &rc, brush);

      // Clean up.
      SelectObject(hdc, old_brush);
      EndPaint(dialog, &paint);
      return static_cast<INT_PTR>(TRUE);
  }

  return static_cast<INT_PTR>(FALSE);
}

// This function checks to see if we are running elevated. This function will
// return false on error and on success will modify the parameter |elevated|
// to specify whether we are running elevated or not. This function should only
// be called for Vista or later.
bool IsRunningElevated(bool* elevated) {
  HANDLE process_token;
  if (!::OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &process_token))
    return false;

  TOKEN_ELEVATION_TYPE elevation_type = TokenElevationTypeDefault;
  DWORD size_returned = 0;
  if (!::GetTokenInformation(process_token, TokenElevationType,
      &elevation_type, sizeof(elevation_type), &size_returned)) {
    ::CloseHandle(process_token);
    return false;
  }

  ::CloseHandle(process_token);
  *elevated = (elevation_type == TokenElevationTypeFull);
  return true;
}

// This function checks to see if we need to elevate. Essentially, we need to
// elevate if ALL of the following conditions are true:
// - The OS is Vista or later.
// - UAC is enabled.
// - We are not already elevated.
// - The registry hive we are working with is HKLM.
// This function will return false on error and on success will modify the
// parameter |elevation_required| to specify whether we need to elevated or not.
bool ElevationIsRequired(bool* elevation_required) {
  *elevation_required = false;

  // First, make sure we are running on Vista or more recent.
  OSVERSIONINFO info = {0};
  info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
  if (!::GetVersionEx(&info))
    return false;  // Failure.

  // Unless we are Vista or newer, we don't need to elevate.
  if (info.dwMajorVersion < 6)
    return true;  // No error, we just don't need to elevate.

  // Make sure UAC is not disabled.
  RegKey key(HKEY_LOCAL_MACHINE,
             L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System");
  DWORD uac_enabled;
  if (!key.ReadValueDW(L"EnableLUA", &uac_enabled))
    uac_enabled = true;  // If the value doesn't exist, then UAC is enabled.

  if (!uac_enabled)
    return true;  // No error, but UAC is disabled, so elevation is futile!

  // This is Vista or more recent, so check if already running elevated.
  bool elevated = false;
  if (!IsRunningElevated(&elevated))
    return false;  // Error checking to see if we already elevated.

  if (elevated)
    return true;  // No error, but we are already elevated.

  // We are not already running elevated, check if we found our key under HKLM
  // because then we need to elevate us so that our writes don't get
  // virtualized.
  *elevation_required = (registry_hive == HKEY_LOCAL_MACHINE);
  return true;  // Success.
}

int RelaunchProcessWithElevation() {
  // Get the path and EXE name of this process so we can relaunch it.
  wchar_t executable[MAX_PATH];
  if (!::GetModuleFileName(0, &executable[0], MAX_PATH))
    return 0;

  SHELLEXECUTEINFO info;
  ZeroMemory(&info, sizeof(info));
  info.hwnd            = GetDesktopWindow();
  info.cbSize          = sizeof(SHELLEXECUTEINFOW);
  info.lpVerb          = L"runas";  // Relaunch with elevation.
  info.lpFile          = executable;
  info.lpParameters    = kElevationParam;  // Our special notification param.
  info.nShow           = SW_SHOWNORMAL;
  return ::ShellExecuteEx(&info);
}

BOOL RestartWithElevationIfRequired(const std::wstring& cmd_line) {
  bool elevation_required = false;
  if (!ElevationIsRequired(&elevation_required)) {
    ::MessageBox(NULL, L"Cannot determine if Elevation is required",
                 kMessageBoxTitle, MB_OK | MB_ICONERROR);
    return TRUE;  // This causes the app to exit.
  }

  if (elevation_required) {
    if (cmd_line.find(kElevationParam) != std::wstring::npos) {
      // If we get here, that means we tried to elevate but it failed.
      // We break here to prevent an infinite spawning loop.
      ::MessageBox(NULL, L"Second elevation attempted", kMessageBoxTitle,
                   MB_OK | MB_ICONERROR);
      return TRUE;  // This causes the app to exit.
    }

    // Restart this application with elevation.
    if (!RelaunchProcessWithElevation()) {
      ::MessageBox(NULL, L"Elevation attempt failed", kMessageBoxTitle,
                   MB_OK | MB_ICONERROR);
    }
    return TRUE;  // This causes the app to exit.
  }

  return FALSE;  // No elevation required, Channel Changer can continue running.
}

int APIENTRY _tWinMain(HINSTANCE instance,
                       HINSTANCE previous_instance,
                       LPTSTR    cmd_line,
                       int       cmd_show) {
  UNREFERENCED_PARAMETER(previous_instance);
  UNREFERENCED_PARAMETER(cmd_show);

  // Detect which update path the user is on. This also sets the registry_hive
  // parameter to the right Registry hive, which we will use later to determine
  // if we need to elevate (Vista and later only).
  DetectBranch();

  // If we detect that we need to elevate then we will restart this process
  // as an elevated process, so all this process needs to do is exit.
  // NOTE: We need to elevate on Vista if we detect that Chrome was installed
  // system-wide (because then we'll be modifying Google Update keys under
  // HKLM). We don't want to set the elevation policy in the manifest because
  // then we block non-admin users (that want to modify user-level Chrome
  // installation) from running the channel changer.
  if (RestartWithElevationIfRequired(cmd_line))
    return TRUE;

  dlg_icon = ::LoadIcon(instance, MAKEINTRESOURCE(IDI_BRANCH_SWITCHER));

  ::DialogBox(instance,
              MAKEINTRESOURCE(IDD_MAIN_DIALOG),
              ::GetDesktopWindow(),
              DialogWndProc);

  return TRUE;
}
<commit_msg>Changing which installation the Channel Changer uses.<commit_after>// Copyright (c) 2006-2008 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 <Windowsx.h>

#include "base/registry.h"

#include "Resource.h"

// This enum needs to be in sync with the strings below.
enum Branch {
  UNKNOWN_BRANCH = 0,
  DEV_BRANCH,
  BETA_BRANCH,
  STABLE_BRANCH,
};

// This vector of strings needs to be in sync with the Branch enum above.
static const wchar_t* const kBranchStrings[] = {
  L"?",
  L"1.1-dev",
  L"1.1-beta",
  L"",
};

// This vector of strings needs to be in sync with the Branch enum above.
static const wchar_t* const kBranchStringsReadable[] = {
  L"?",
  L"Dev",
  L"Beta",
  L"Stable",
};

// The Registry Hive to write to. Points to the hive where we found the 'ap' key
// unless there is an error, in which case it is 0.
HKEY registry_hive = 0;

// The value of the 'ap' key under the registry hive specified in
// |registry_hive|.
std::wstring update_branch;

// The Google Update key to read to find out which branch you are on.
static const wchar_t* const kChromeClientStateKey =
    L"Software\\Google\\Update\\ClientState\\"
    L"{8A69D345-D564-463C-AFF1-A69D9E530F96}";

// The Google Client key to read to find out which branch you are on.
static const wchar_t* const kChromeClientsKey =
    L"Software\\Google\\Update\\Clients\\"
    L"{8A69D345-D564-463C-AFF1-A69D9E530F96}";

// The Google Update value that defines which branch you are on.
static const wchar_t* const kBranchKey = L"ap";

// The suffix Google Update sometimes adds to the channel name (channel names
// are defined in kBranchStrings), indicating that a full install is needed. We
// strip this out (if present) for the purpose of determining which channel you
// are on.
static const wchar_t* const kChannelSuffix = L"-full";

// Title to show in the MessageBoxes.
static const wchar_t* const kMessageBoxTitle = L"Google Chrome Channel Changer";

// A parameter passed into us when we are trying to elevate. This is used as a
// safeguard to make sure we only try to elevate once (so that if it fails we
// don't create an infinite process spawn loop).
static const wchar_t* const kElevationParam = L"--elevation-attempt";

// The icon to use.
static HICON dlg_icon = NULL;

// We need to detect which update branch the user is on. We do this by checking
// under the Google Update 'Clients\<Chrome GUID>' key for HKLM (for
// system-level installs) and then HKCU (for user-level installs). Once we find
// the right registry hive, we read the current value of the 'ap' key under
// Google Update 'ClientState\<Chrome GUID>' key.
void DetectBranch() {
  // See if we can find the Clients key on the HKLM branch.
  registry_hive = HKEY_LOCAL_MACHINE;
  RegKey google_update_hklm(registry_hive, kChromeClientsKey, KEY_READ);
  if (!google_update_hklm.Valid()) {
    // HKLM failed us, try the same for the HKCU branch.
    registry_hive = HKEY_CURRENT_USER;
    RegKey google_update_hkcu(registry_hive, kChromeClientsKey, KEY_READ);
    if (!google_update_hkcu.Valid()) {
      // HKCU also failed us! "Set condition 1 throughout the ship!"
      registry_hive = 0;  // Failed to find Google Update Chrome key.
      update_branch = kBranchStrings[UNKNOWN_BRANCH];
    }
  }

  if (registry_hive != 0) {
    // Now that we know which hive to use, read the 'ap' key from it.
    RegKey client_state(registry_hive, kChromeClientStateKey, KEY_READ);
    client_state.ReadValue(kBranchKey, &update_branch);

    // We look for '1.1-beta' or '1.1-dev', but Google Update might have added
    // '-full' to the channel name, which we need to strip out to determine what
    // channel you are on.
    std::wstring suffix = kChannelSuffix;
    if (update_branch.length() > suffix.length()) {
      size_t index = update_branch.rfind(suffix);
      if (index != std::wstring::npos &&
          index == update_branch.length() - suffix.length()) {
        update_branch = update_branch.substr(0, index);
      }
    }
  }
}

void SetMainLabel(HWND dialog, Branch branch) {
  std::wstring main_label = L"You are currently on ";
  if (branch == DEV_BRANCH || branch == BETA_BRANCH || branch == STABLE_BRANCH)
    main_label += std::wstring(L"the ") + kBranchStringsReadable[branch] +
                  std::wstring(L" channel");
  else
    main_label += L"NO UPDATE CHANNEL";

  main_label += L". Choose a different channel and click Update, "
                L"or click Close to stay on this channel.";

  SetWindowText(GetDlgItem(dialog, IDC_LABEL_MAIN), main_label.c_str());
}

void OnInitDialog(HWND dialog) {
  SendMessage(dialog, WM_SETICON, (WPARAM) false, (LPARAM) dlg_icon);

  Branch branch = UNKNOWN_BRANCH;
  if (update_branch == kBranchStrings[STABLE_BRANCH]) {
    branch = STABLE_BRANCH;
  } else if (update_branch == kBranchStrings[DEV_BRANCH]) {
    branch = DEV_BRANCH;
  } else if (update_branch == kBranchStrings[BETA_BRANCH]) {
    branch = BETA_BRANCH;
  } else {
    // Hide the controls we can't use.
    EnableWindow(GetDlgItem(dialog, IDOK), false);
    EnableWindow(GetDlgItem(dialog, IDC_STABLE), false);
    EnableWindow(GetDlgItem(dialog, IDC_BETA), false);
    EnableWindow(GetDlgItem(dialog, IDC_CUTTING_EDGE), false);

    MessageBox(dialog, L"KEY NOT FOUND\n\nGoogle Chrome is not installed, or "
                       L"is not using GoogleUpdate for updates.",
                       kMessageBoxTitle,
                       MB_ICONEXCLAMATION | MB_OK);
  }

  SetMainLabel(dialog, branch);

  CheckDlgButton(dialog, IDC_STABLE,
                 branch == STABLE_BRANCH ? BST_CHECKED : BST_UNCHECKED);
  CheckDlgButton(dialog, IDC_CUTTING_EDGE,
                 branch == DEV_BRANCH ? BST_CHECKED : BST_UNCHECKED);
  CheckDlgButton(dialog, IDC_BETA,
                 branch == BETA_BRANCH ? BST_CHECKED : BST_UNCHECKED);
}

INT_PTR OnCtlColorStatic(HWND dialog, WPARAM wparam, LPARAM lparam) {
  HDC hdc = reinterpret_cast<HDC>(wparam);
  HWND control_wnd = reinterpret_cast<HWND>(lparam);

  if (GetDlgItem(dialog, IDC_STABLE) == control_wnd ||
      GetDlgItem(dialog, IDC_BETA) == control_wnd ||
      GetDlgItem(dialog, IDC_CUTTING_EDGE) == control_wnd ||
      GetDlgItem(dialog, IDC_LABEL_MAIN) == control_wnd ||
      GetDlgItem(dialog, IDC_SECONDARY_LABEL) == control_wnd) {
    SetBkMode(hdc, TRANSPARENT);
    SetTextColor(hdc, RGB(0, 0, 0));
    return reinterpret_cast<INT_PTR>(GetSysColorBrush(COLOR_WINDOW));
  }

  return static_cast<INT_PTR>(FALSE);
}

void SaveChanges(HWND dialog) {
  Branch branch = UNKNOWN_BRANCH;
  if (IsDlgButtonChecked(dialog, IDC_STABLE))
    branch = STABLE_BRANCH;
  else if (IsDlgButtonChecked(dialog, IDC_BETA))
    branch = BETA_BRANCH;
  else if (IsDlgButtonChecked(dialog, IDC_CUTTING_EDGE))
    branch = DEV_BRANCH;

  if (branch != UNKNOWN_BRANCH) {
    RegKey google_update(registry_hive, kChromeClientStateKey, KEY_WRITE);
    if (!google_update.WriteValue(kBranchKey, kBranchStrings[branch])) {
      MessageBox(dialog, L"Unable to change value. Please make sure you\n"
                         L"have permission to change registry keys.",
                         L"Unable to update branch info", MB_OK | MB_ICONERROR);
    } else {
      std::wstring save_msg = L"Your changes have been saved.\nYou are now "
                              L"on the " +
                              std::wstring(kBranchStringsReadable[branch]) +
                              L" branch.";
      MessageBox(dialog, save_msg.c_str(), L"Changes were saved",
                 MB_OK | MB_ICONINFORMATION);

      SetMainLabel(dialog, branch);
    }
  }
}

INT_PTR CALLBACK DialogWndProc(HWND dialog,
                               UINT message_id,
                               WPARAM wparam,
                               LPARAM lparam) {
  UNREFERENCED_PARAMETER(lparam);

  switch (message_id) {
    case WM_INITDIALOG:
      OnInitDialog(dialog);
      return static_cast<INT_PTR>(TRUE);
    case WM_CTLCOLORSTATIC:
      return OnCtlColorStatic(dialog, wparam, lparam);
    case WM_COMMAND:
      // If the user presses the OK button.
      if (LOWORD(wparam) == IDOK) {
        SaveChanges(dialog);
        return static_cast<INT_PTR>(TRUE);
      }
      // If the user presses the Cancel button.
      if (LOWORD(wparam) == IDCANCEL) {
        ::EndDialog(dialog, LOWORD(wparam));
        return static_cast<INT_PTR>(TRUE);
      }
      break;
    case WM_ERASEBKGND:
      PAINTSTRUCT paint;
      HDC hdc = BeginPaint(dialog, &paint);
      if (!hdc)
        return static_cast<INT_PTR>(FALSE);  // We didn't handle it.

      // Fill the background with White.
      HBRUSH brush = GetStockBrush(WHITE_BRUSH);
      HGDIOBJ old_brush = SelectObject(hdc, brush);
      RECT rc;
      GetClientRect(dialog, &rc);
      FillRect(hdc, &rc, brush);

      // Clean up.
      SelectObject(hdc, old_brush);
      EndPaint(dialog, &paint);
      return static_cast<INT_PTR>(TRUE);
  }

  return static_cast<INT_PTR>(FALSE);
}

// This function checks to see if we are running elevated. This function will
// return false on error and on success will modify the parameter |elevated|
// to specify whether we are running elevated or not. This function should only
// be called for Vista or later.
bool IsRunningElevated(bool* elevated) {
  HANDLE process_token;
  if (!::OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &process_token))
    return false;

  TOKEN_ELEVATION_TYPE elevation_type = TokenElevationTypeDefault;
  DWORD size_returned = 0;
  if (!::GetTokenInformation(process_token, TokenElevationType,
      &elevation_type, sizeof(elevation_type), &size_returned)) {
    ::CloseHandle(process_token);
    return false;
  }

  ::CloseHandle(process_token);
  *elevated = (elevation_type == TokenElevationTypeFull);
  return true;
}

// This function checks to see if we need to elevate. Essentially, we need to
// elevate if ALL of the following conditions are true:
// - The OS is Vista or later.
// - UAC is enabled.
// - We are not already elevated.
// - The registry hive we are working with is HKLM.
// This function will return false on error and on success will modify the
// parameter |elevation_required| to specify whether we need to elevated or not.
bool ElevationIsRequired(bool* elevation_required) {
  *elevation_required = false;

  // First, make sure we are running on Vista or more recent.
  OSVERSIONINFO info = {0};
  info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
  if (!::GetVersionEx(&info))
    return false;  // Failure.

  // Unless we are Vista or newer, we don't need to elevate.
  if (info.dwMajorVersion < 6)
    return true;  // No error, we just don't need to elevate.

  // Make sure UAC is not disabled.
  RegKey key(HKEY_LOCAL_MACHINE,
             L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System");
  DWORD uac_enabled;
  if (!key.ReadValueDW(L"EnableLUA", &uac_enabled))
    uac_enabled = true;  // If the value doesn't exist, then UAC is enabled.

  if (!uac_enabled)
    return true;  // No error, but UAC is disabled, so elevation is futile!

  // This is Vista or more recent, so check if already running elevated.
  bool elevated = false;
  if (!IsRunningElevated(&elevated))
    return false;  // Error checking to see if we already elevated.

  if (elevated)
    return true;  // No error, but we are already elevated.

  // We are not already running elevated, check if we found our key under HKLM
  // because then we need to elevate us so that our writes don't get
  // virtualized.
  *elevation_required = (registry_hive == HKEY_LOCAL_MACHINE);
  return true;  // Success.
}

int RelaunchProcessWithElevation() {
  // Get the path and EXE name of this process so we can relaunch it.
  wchar_t executable[MAX_PATH];
  if (!::GetModuleFileName(0, &executable[0], MAX_PATH))
    return 0;

  SHELLEXECUTEINFO info;
  ZeroMemory(&info, sizeof(info));
  info.hwnd            = GetDesktopWindow();
  info.cbSize          = sizeof(SHELLEXECUTEINFOW);
  info.lpVerb          = L"runas";  // Relaunch with elevation.
  info.lpFile          = executable;
  info.lpParameters    = kElevationParam;  // Our special notification param.
  info.nShow           = SW_SHOWNORMAL;
  return ::ShellExecuteEx(&info);
}

BOOL RestartWithElevationIfRequired(const std::wstring& cmd_line) {
  bool elevation_required = false;
  if (!ElevationIsRequired(&elevation_required)) {
    ::MessageBox(NULL, L"Cannot determine if Elevation is required",
                 kMessageBoxTitle, MB_OK | MB_ICONERROR);
    return TRUE;  // This causes the app to exit.
  }

  if (elevation_required) {
    if (cmd_line.find(kElevationParam) != std::wstring::npos) {
      // If we get here, that means we tried to elevate but it failed.
      // We break here to prevent an infinite spawning loop.
      ::MessageBox(NULL, L"Second elevation attempted", kMessageBoxTitle,
                   MB_OK | MB_ICONERROR);
      return TRUE;  // This causes the app to exit.
    }

    // Restart this application with elevation.
    if (!RelaunchProcessWithElevation()) {
      ::MessageBox(NULL, L"Elevation attempt failed", kMessageBoxTitle,
                   MB_OK | MB_ICONERROR);
    }
    return TRUE;  // This causes the app to exit.
  }

  return FALSE;  // No elevation required, Channel Changer can continue running.
}

int APIENTRY _tWinMain(HINSTANCE instance,
                       HINSTANCE previous_instance,
                       LPTSTR    cmd_line,
                       int       cmd_show) {
  UNREFERENCED_PARAMETER(previous_instance);
  UNREFERENCED_PARAMETER(cmd_show);

  // Detect which update path the user is on. This also sets the registry_hive
  // parameter to the right Registry hive, which we will use later to determine
  // if we need to elevate (Vista and later only).
  DetectBranch();

  // If we detect that we need to elevate then we will restart this process
  // as an elevated process, so all this process needs to do is exit.
  // NOTE: We need to elevate on Vista if we detect that Chrome was installed
  // system-wide (because then we'll be modifying Google Update keys under
  // HKLM). We don't want to set the elevation policy in the manifest because
  // then we block non-admin users (that want to modify user-level Chrome
  // installation) from running the channel changer.
  if (RestartWithElevationIfRequired(cmd_line))
    return TRUE;

  dlg_icon = ::LoadIcon(instance, MAKEINTRESOURCE(IDI_BRANCH_SWITCHER));

  ::DialogBox(instance,
              MAKEINTRESOURCE(IDD_MAIN_DIALOG),
              ::GetDesktopWindow(),
              DialogWndProc);

  return TRUE;
}
<|endoftext|>


<commit_before>/*
        Net.cpp
        ----------------
        begin           : 1999.11.29
        copyright       : (C) 1999 by John Barrett (ZW)
        email           : jbarrett@box100.com
*/

#include "Net.h"

void initAtlasNet()
{
	Py_Initialize();

	initURI();
	initURIList();
	initIntList();
	initLongList();
	initFloatList();
	initStringList();
}
<commit_msg>instead of being Object/Types.c duplicate Net.cpp calls it<commit_after>/*
        Net.cpp
        ----------------
        begin           : 1999.11.29
        copyright       : (C) 1999 by John Barrett (ZW)
        email           : jbarrett@box100.com
*/

#include "Net.h"

void initAtlasNet()
{
	initAtlasTypes();
}
<|endoftext|>


<commit_before>// Time:  O(1), per operation.
// Space: O(k), k is the capacity of cache.

#include <list>

class LRUCache {
public:
    LRUCache(int capacity) : capa_(capacity) {
    }

    int get(int key) {
        auto it = map_.find(key);
        if (it != map_.end()) {
            // It key exists, update it.
            auto l_it = it->second;
            int value = l_it->second;
            update(it, value);
            return value;
        } else {
            return -1;
        }
    }

    void set(int key, int value) {
        auto it = map_.find(key);
        // It key exists, update it.
        if (it != map_.end()) {
            update(it, value);
        } else {
            // If cache is full, remove the last one.
            if (list_.size() == capa_) {
                auto del = list_.back(); list_.pop_back();
                map_.erase(del.first);
            }
            list_.emplace_front(key, value);
            map_[key]=list_.begin();
        }
    }

private:
    list<pair<int, int>> list_; // key, value
    unordered_map<int, list<pair<int, int>>::iterator> map_; // key, list iterator
    int capa_;

    // Update (key, iterator of (key, value)) pair
    void update(unordered_map<int, list<pair<int, int>>::iterator>::iterator it, int value) {
        auto l_it = it->second;
        int key = l_it->first;
        list_.erase(l_it);
        list_.emplace_front(key, value);
        it->second = list_.begin();
    }
};
<commit_msg>Update lru-cache.cpp<commit_after>// Time:  O(1), per operation.
// Space: O(k), k is capacity of cache.

#include <list>

class LRUCache {
public:
    LRUCache(int capacity) : capa_(capacity) {
    }

    int get(int key) {
        if (map_.find(key) != map_.end()) {
            // It key exists, update it.
            const auto value = map_[key]->second;
            update(key, value);
            return value;
        } else {
            return -1;
        }
    }

    void set(int key, int value) {
        // If cache is full while inserting, remove the last one.
        if (map_.find(key) == map_.end() && list_.size() == capa_) {
            auto del = list_.back(); list_.pop_back();
            map_.erase(del.first);
        }
         update(key, value);
    }

private:
    list<pair<int, int>> list_; // key, value
    unordered_map<int, list<pair<int, int>>::iterator> map_; // key, list iterator
    int capa_;

    // Update (key, iterator of (key, value)) pair
    void update(int key, int value) {
        auto it = map_.find(key);
        if (it != map_.end()) {
            list_.erase(it->second);
        }
        list_.emplace_front(key, value);
        map_[key] = list_.begin();
    }
};
<|endoftext|>