text:
/**********************************************************************
  (C) 2008-2010 by Jens Thomas

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation version 2 of the License.

  This program 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 General Public License for more details.
***********************************************************************/
#include <openbabel/babelconfig.h>
#include <openbabel/obmolecformat.h>

#include <algorithm>
#include <cmath>

#ifdef _MSC_VER
#include <regex>
#else
#include <regex.h>
#endif

using namespace std;

namespace OpenBabel
{
#define BOHR_TO_ANGSTROM 0.529177249
#define ANGSTROM_TO_BOHR 1.889725989

  class GAMESSUKFormat
  {
    /* Base class for GAMESS-UK readers with various utility functions that are used by
     * both input and output readers.
     *
     * The most important is ReadGeometry, which takes a list of strings defining the
     * geometry (in the style of a GAMESS-UK input deck) and creates the OBMol from it.
     * This routine supports both Zmatrix and Cartesian formats, although currently not
     * mixed decks.
     */

  public:
    bool ReadGeometry(OBMol &mol, vector<string> &geomList);
    bool ReadVariables(istream &ifs, double factor, string stopstr);
    bool ReadLineCartesian(OBAtom *atom, vector<string> &tokens, double factor);
    bool ReadLineZmatrix(OBMol &mol, OBAtom *atom, vector<string> &tokens, double factor, int *zmatLineCount);
    double Rescale(string text);
    bool IsUnits(string text);
    /**
     * Converts a string to a numerical type
     * This purloined from: http://www.codeguru.com/forum/showthread.php?t=231054
     */
    template <class T>
    bool from_string(T& t, const std::string& s,
                     std::ios_base& (*f)(std::ios_base&))
    {
      std::istringstream iss(s);
      return !(iss >> f >> t).fail();
    }

    // Variables
    enum ReadMode_t {CARTESIAN, ZMATRIX, VARIABLES, CONSTANTS, SKIP};
    ReadMode_t ReadMode;
    char buffer[BUFF_SIZE];
    stringstream errorMsg;

  private:
    map<string, double> variables; // map from variable name to value
    vector<OBInternalCoord*> vic; // Holds lists of internal coordinates
    int LabelToAtomicNumber(string label);
  };

  bool GAMESSUKFormat::ReadGeometry(OBMol &mol, vector<string> &geomList)
  {

    /* Read a geometry from a list. Any variables that appear in the geometry need
     * to be in the variables map that should have been populated before this is called.
     */

    if (geomList.size()==0){
      obErrorLog.ThrowError(__FUNCTION__,
                            "Problems reading a GAMESS-UK Input file: ReadGeometry got empty list",
                            obWarning);
      return false;
    }

    vector<string> tokens; // list of lines and list of tokens on a line
    string line; // For convenience so we can refer to lines from the iterator as 'line'
    double factor=BOHR_TO_ANGSTROM; // The coordinate conversion factor for handling bohr/angstrom issues

    mol.BeginModify();
    // Clear out any existing information
    mol.Clear();
    vic.clear();

    ReadMode=SKIP;
    bool ContainsZmatrix=false;
    int zmatLineCount=0;

    /*
      cerr << "ReadGeometry got geometry list: \n";
      for (vector<string>::iterator i=geomList.begin(); i !=geomList.end(); i++) {

      // Alias the line
      line = *i;
      cerr << "line: " << line << endl;
      }
    */

    for (vector<string>::iterator i=geomList.begin(); i !=geomList.end(); ++i) {

      // Alias the line
      line = *i;

      //cerr << "ReadGeometry line is: " << line << endl;

      // Check for commas & split with that as the separator if necessary
      if (line.find(',')!=string::npos) {
        tokenize(tokens, line, ",");
      } else {
        tokenize(tokens, line, " \t\n");
      }

      // Set the mode
      if (line.compare(0, 4, "zmat")==0 || line.compare(0, 4, "inte")==0) {
        ReadMode=ZMATRIX;
        //cout << "ZMATRIX mode " << ReadMode << endl;
        //cout << "tokens.size()" << tokens.size() << endl;
        if (tokens.size()>1) if (IsUnits(tokens[1])) factor=Rescale(tokens[1]);
        ContainsZmatrix=true;
        vic.push_back((OBInternalCoord*)NULL); // OBMol indexed from 1 -- potential atom index problem
      } else if (line.compare(0, 4, "coor")==0 || line.compare(0, 4, "cart")==0 ||line.compare(0, 4, "geom")==0) {
        ReadMode=CARTESIAN;
        //cout << "CARTESIAN mode " << ReadMode << endl;
        if (tokens.size()>1) if (IsUnits(tokens[1])) factor=Rescale(tokens[1]);

        /*
          We need to have read the variables first
          } else if (line.compare(0, 4, "vari")==0) {
          ReadMode=VARIABLES;
          //cout << "VARIABLES mode "<< ReadMode << endl;
          if (tokens.size() == 2) factor=Rescale(tokens[1]);
          //cout << "Factor now " << factor << endl;
          } else if (line.compare(0, 4, "cons")==0) {
          ReadMode=CONSTANTS;
          //cout << "CONSTANTS mode\n";
          if (tokens.size() == 2)
          factor=Rescale(tokens[1]);
          //cout << "Factor now " << factor << endl;
          */

      } else if (line.compare(0, 3, "end")==0) {
        ReadMode=SKIP;
        //cout << "SKIP mode " << ReadMode << endl;
      } else {
        if (ReadMode==SKIP) continue;
        if (ReadMode==ZMATRIX) {
          // Create an atom
          OBAtom *atom = mol.NewAtom();
          // Read the ZMatrix definition line
          if (! ReadLineZmatrix(mol,atom,tokens,factor,&zmatLineCount) )
            {
              errorMsg << "Problems reading a GAMESS-UK Input file: "
                       << "Could not read zmat line: " << line;
              obErrorLog.ThrowError(__FUNCTION__, errorMsg.str() ,
                                    obWarning);
              return (false);
            }

        } // End ReadMode ZMATRIX

        if (ReadMode==CARTESIAN) {
          OBAtom *atom = mol.NewAtom();
          if (! ReadLineCartesian(atom,tokens,factor) )
            {
              errorMsg << "Problems reading a GAMESS-UK Input file: "
                       << "Could not read xyz line: " << line;
              obErrorLog.ThrowError(__FUNCTION__, errorMsg.str() ,
                                    obWarning);
              return (false);
            }

        } // End ReadMode CARTESIAN

      } // End Test for first chars on line
    } // End loop over lines

    if (ContainsZmatrix)InternalToCartesian(vic,mol);
    mol.EndModify();

    return true;
  } // End Read Geometry

  bool GAMESSUKFormat::IsUnits(string text)
  {
    /* See if the supplied string specifies a unit */

    if ( text.compare(0, 4, "angs")==0 ||
         text.compare(0, 4, "bohr")==0 ||
         text.compare(0, 4, "a.u.")==0 ||
         text.compare(0, 2, "au")==0) {
      return true;
    } else {
      return false;
    }
  }

  double GAMESSUKFormat::Rescale(string text)
  {
    /* Return the correct scale factor given a string identifying the units */

    if (! IsUnits(text) ){
      errorMsg << "Problems reading GUK input - bad scale factor: " << text;
      obErrorLog.ThrowError(__FUNCTION__, errorMsg.str(), obWarning);
      return -1.0;
    }

    if (text.compare(0, 4, "angs")==0) {
      return 1.0;
    } else if (text.compare(0, 4, "bohr")==0||text.compare(0, 4, "a.u.")==0
               ||text.compare(0, 2, "au")==0) {
      return BOHR_TO_ANGSTROM;
    } else {
      return -1.0;
    }
  }

  int GAMESSUKFormat::LabelToAtomicNumber(string label)
  {
    /*
     * Given a string with the label for an atom return the atomic number
     * As we are using the GetAtomicNum function case is not important
     */

    // See if the first 2 characters give us a valid atomic #
    int Z=etab.GetAtomicNum(label.substr(0,2).c_str());

    // If not try the first one
    if (Z==0) Z=etab.GetAtomicNum(label.substr(0,1).c_str());

    if (Z==0){
      // Check if it's an x (dummy) atom
      if(  label.substr(0,1) != "x" && label.substr(0,1) != "X" )
        {
          // Houston...
          errorMsg << "LabelToAtomicNumber got bad Label: " << label << std::endl;
          obErrorLog.ThrowError(__FUNCTION__, errorMsg.str(), obWarning);
        }
    }
    return Z;
  }

  bool GAMESSUKFormat::ReadLineCartesian(OBAtom *atom, vector<string> &tokens, double factor)
  {

    /*  Read a line defining the Cartesian coordinates for an atom
     * This assumes the line is formatted in GAMESS-UK input style as:
     * x y z AtomicNumber Label
     */

    bool ok=false;
    int Z;
    double x,y,z;

    // 4th field is the atomic number
    ok = from_string<int>(Z, tokens.at(3), std::dec);
    atom->SetAtomicNum(Z);

    // Read the atom coordinates
    ok = from_string<double>(x, tokens.at(0), std::dec);
    if ( ! ok)
      {
        // Can't convert to double so see if it's in the variables
        if (variables.find(tokens[0])==variables.end()) return false;
        x = variables[tokens[0]];
      }

    ok = from_string<double>(y, tokens.at(1), std::dec);
    if ( ! ok)
      {
        // Can't convert to double so see if it's in the variables
        if (variables.find(tokens[1])==variables.end()) return false;
        y = variables[tokens[1]];
      }

    ok = from_string<double>(z, tokens.at(2), std::dec);
    if ( ! ok)
      {
        // Can't convert to double so see if it's in the variables
        if (variables.find(tokens[2])==variables.end()) return false;
        z = variables[tokens[2]];
      }

    // Convert to Angstroms
    x=x*factor;
    y=y*factor;
    z=z*factor;
    atom->SetVector(x, y, z); //set coordinates
    return true;
  }

  bool GAMESSUKFormat::ReadLineZmatrix(OBMol &mol, OBAtom *atom, vector<string> &tokens, double factor, int *zmatLineCount)
  {
    /*
     * Read a line from a GAMESS-UK input defining an atom in Inernal Coordinates.
     * We create a list of OBInternalCoords that match the list of atoms in the molecule
     * that are defined using internal coordinates
     */

    double var;
    bool ok=false;
    int n;

    vic.push_back(new OBInternalCoord);
    atom->SetAtomicNum(LabelToAtomicNumber(tokens[0]));

    switch (*zmatLineCount) {
    case 0:
      break;

    case 1:
      if (tokens.size() < 3) {return false;}

      // Specify the atom that defines the distance to this one
      ok = from_string<int>(n, tokens.at(1), std::dec);
      vic[*zmatLineCount]->_a = mol.GetAtom(n);

      // Get the distance
      ok = from_string<double>(var, tokens.at(2), std::dec);
      if ( !ok )
        {
          // Can't convert to double so see if it's in the variables
          if (variables.find(tokens[2])==variables.end()) return false;
          var = variables[tokens[2]];
        }
      vic[*zmatLineCount]->_dst = var;
      break;

    case 2:
      if (tokens.size() < 5) {return false;}

      // Specify the atom that defines the distance to this one
      ok = from_string<int>(n, tokens.at(1), std::dec);
      vic[*zmatLineCount]->_a = mol.GetAtom(n);

      // Get the distance
      ok = from_string<double>(var, tokens.at(2), std::dec);
      if ( !ok )
        {
          // Can't convert to double so see if it's in the variables
          if (variables.find(tokens[2])==variables.end()) return false;
          var = variables[tokens[2]];
        }
      vic[*zmatLineCount]->_dst = var;

      // Specify atom defining angle
      ok = from_string<int>(n, tokens.at(3), std::dec);
      vic[*zmatLineCount]->_b = mol.GetAtom(n);
      // Get the angle
      ok = from_string<double>(var, tokens.at(4), std::dec);
      if ( !ok )
        {
          // Can't convert to double so see if it's in the variables
          if (variables.find(tokens[4])==variables.end()) return false;
          var = variables[tokens[4]];
        }
      vic[*zmatLineCount]->_ang = var;
      break;

    default:
      if (tokens.size() < 7) {return false;}

      ok = from_string<int>(n, tokens.at(1), std::dec);
      vic[*zmatLineCount]->_a = mol.GetAtom(n);
      // Get the distance
      ok = from_string<double>(var, tokens.at(2), std::dec);
      if ( !ok )
        {
          // Can't convert to double so see if it's in the variables
          if (variables.find(tokens[2])==variables.end()) return false;
          var = variables[tokens[2]];
        }
      vic[*zmatLineCount]->_dst = var;

      ok = from_string<int>(n, tokens.at(3), std::dec);
      vic[*zmatLineCount]->_b = mol.GetAtom(n);
      // Get the angle
      ok = from_string<double>(var, tokens.at(4), std::dec);
      if ( !ok )
        {
          // Can't convert to double so see if it's in the variables
          if (variables.find(tokens[4])==variables.end()) return false;
          var = variables[tokens[4]];
        }
      vic[*zmatLineCount]->_ang = var;

      ok = from_string<int>(n, tokens.at(5), std::dec);
      vic[*zmatLineCount]->_c = mol.GetAtom(n);
      // Get the torsion angle
      ok = from_string<double>(var, tokens.at(6), std::dec);
      if ( !ok )
        {
          // Can't convert to double so see if it's in the variables
          if (variables.find(tokens[6])==variables.end()) return false;
          var = variables[tokens[6]];
        }
      vic[*zmatLineCount]->_tor = var;
    }

    (*zmatLineCount)++;
    return true;
  }

  bool GAMESSUKFormat::ReadVariables(istream &ifs, double factor, string stopstr)
  {
    /*
     * This takes an input stream that is positioned where the list of variables
     * starts and the reads the variables into the supplied map
     *
     * This is different to ReadGeometry (which takes a vector of strings as input) because
     * currently the variables always need to be read after the geometry, so we need to save the
     * geometry and then read the variables. However this means that we can parse the variables
     * directly into a map and don't need to keep a copy of the specifcation as strings.
     *
     * stopstr is a string that defines when we stop reading
     */

    string line;
    vector<string> tokens;
    bool ok=false;
    double var;

    // Now read in all the varibles
    while (ifs.good() && ifs.getline(buffer, BUFF_SIZE)) {

      // Skip commnents
      if (EQn(buffer, "#", 1) || EQn(buffer, "?", 1))
        continue;

      // Copy line to a C++ string and convert to lower case
      // & remove leading and trailing spaces
      line = buffer;
      // transform(method.begin(), method.end(), method.begin(), ::tolower);
      ToLower(line);
      Trim(line);

      // Check for end of variables
      if (line.length()==0 && stopstr.length()==0) break;
      if (stopstr.length()>0 && line.compare(0, stopstr.length(), stopstr)==0) break;

      // Check for commas & split with that as the separator if necessary
      if (line.find(',')!=string::npos) {
        tokenize(tokens, line, ",");
      } else {
        tokenize(tokens, line, " \t\n");
      }

      ok = from_string<double>(var, tokens.at(3), std::dec);
      if ( !ok )
        {
          errorMsg << "Problems reading a GAMESS-UK  file: "
                   << "Could not read variable line: " << line;
          obErrorLog.ThrowError(__FUNCTION__, errorMsg.str() , obWarning);
          return false;
        }
      // Add to list of variables
      variables[tokens[0]]=var*factor;
    }

    /*
      cerr << "Got list of variables: " << endl;
      for (map<string,double>::iterator i=variables.begin(); i
      != variables.end(); i++) {
      cerr << "Name: " << i->first << " Value: " << i->second << endl;
      }
    */

    return true;

  } // end Read Variables

  class GAMESSUKInputFormat : public OBMoleculeFormat, public GAMESSUKFormat
  {
  public:
    //Register this format type ID
    GAMESSUKInputFormat()
    {
      OBConversion::RegisterFormat("gukin",this, "chemical/x-gamess-input");
      // Command-line keywords
      //OBConversion::RegisterOptionParam("k", NULL, 1, OBConversion::OUTOPTIONS);
      // Command-line keyword file
      //OBConversion::RegisterOptionParam("f", NULL, 1, OBConversion::OUTOPTIONS);
    }

    virtual const char* Description() //required
    {
      return
        "GAMESS-UK Input\n";
    };

    virtual const char* SpecificationURL()
    {return "http://www.cfs.dl.ac.uk";}; //optional

    virtual const char* GetMIMEType()
    { return "chemical/x-gamessuk-input"; };

    //Flags() can return be any the following combined by | or be omitted if none apply
    // NOTREADABLE  READONEONLY  NOTWRITABLE  WRITEONEONLY
    virtual unsigned int Flags()
    {
      return READONEONLY; // | NOTREADABLE;
    };

    ////////////////////////////////////////////////////
    /// The "API" interface functions
    virtual bool WriteMolecule(OBBase* pOb, OBConversion* pConv);
    virtual bool ReadMolecule(OBBase* pOb, OBConversion* pConv);
  };

  //Make an instance of the format class
  GAMESSUKInputFormat theGAMESSUKInputFormat;

  bool GAMESSUKInputFormat::ReadMolecule(OBBase* pOb, OBConversion* pConv)

  {
    /*
     * Stuff to think about:
     * - At outset check whether we are in zmatrix, cartesian or nw-chem format
     *   (we currently only suppot homogeneous formats - not mixed).
     *
     * For each line need to check:
     * - Is this a comment (?,#)
     * - Are the tokens separated by commas, if so use tokenize to split at commas
     * - Is there an 'end' token on the line
     *
     * For each line we want to check that we haven't hit a change from c to zm or vv
     *
     */

    OBMol* pmol = dynamic_cast<OBMol*>(pOb);
    if (pmol==NULL)
      return false;

    //Define some references so we can use the old parameter names
    istream& ifs = *pConv->GetInStream();
    OBMol &mol = *pmol;

    // Get a default title as the filename
    const char* title = pConv->GetTitle();
    mol.BeginModify();
    mol.SetTitle(title);
    mol.EndModify();

    vector<string> geomList, tokens; // list of lines and list of tokens on a line
    string line; // For convenience so we can refer to lines from the iterator as 'line'
    ReadMode_t ReadMode=SKIP;
    double factor=BOHR_TO_ANGSTROM;

    // Read File and copy geometry specification into geomList
    while (ifs.good() && ifs.getline(buffer, BUFF_SIZE)) {

      // Skip commnents
      if (EQn(buffer, "#", 1) || EQn(buffer, "?", 1)) continue;

      // Copy line to a C++ string and convert to lower case
      // & remove leading and trailing spaces
      line = buffer;
      // transform(method.begin(), method.end(), method.begin(), ::tolower);
      ToLower(line);
      Trim(line);

      // Start of coordinate specifiation
      if (line.compare(0, 4, "zmat")==0)
	{
	  ReadMode=ZMATRIX;
	  geomList.push_back(line);
	  continue;
	}
      else if (line.compare(0, 4, "geom")==0)
	{
	  ReadMode=CARTESIAN;
	  geomList.push_back(line);
	  continue;
	}

      // Reading the coordinate specification into the list
      if (ReadMode==ZMATRIX || ReadMode==CARTESIAN)
	{

	  // Variables specification - process directly from filestream
	  // and then remove from the geometry specification
	  if (line.compare(0, 4, "vari")==0 || line.compare(0, 4, "const")==0)
	    {

	      // Check for commas & split with that as the separator if necessary
	      if (line.find(',')!=string::npos)
		tokenize(tokens, line, ",");
	      else
		tokenize(tokens, line, " \t\n");

	      // See if we need to rescale
	      if (IsUnits(tokens[1])) factor=Rescale(tokens[1]);

	      if (! ReadVariables(ifs, factor, "end")) return false;

	      ReadMode=SKIP;
	      geomList.push_back("end\n");
	      continue;
	    }

	  if (line.compare(0, 3, "end")==0) ReadMode=SKIP;

	  geomList.push_back(line);
	}

    }// End while reading loop

    // Now go and process the coordinate specification if we got any
    bool ok = ReadGeometry(mol, geomList);

    if (mol.NumAtoms() == 0) { // e.g., if we're at the end of a file PR#1737209
      mol.EndModify();
      return false;
    } else {
      if (!pConv->IsOption("b",OBConversion::INOPTIONS))
        mol.ConnectTheDots();
      if (!pConv->IsOption("s",OBConversion::INOPTIONS) && !pConv->IsOption("b",OBConversion::INOPTIONS))
        mol.PerceiveBondOrders();
      return ok;
    }

  } // End ReadMolecule

  ////////////////////////////////////////////////////////////////

  bool GAMESSUKInputFormat::WriteMolecule(OBBase* pOb, OBConversion* pConv)
  {
    OBMol* pmol = dynamic_cast<OBMol*>(pOb);
    if(pmol==NULL)
      return false;

    //Define some references so we can use the old parameter names
    ostream &ofs = *pConv->GetOutStream();
    OBMol &mol = *pmol;

    char buffer[BUFF_SIZE];

    ofs << "title" << endl;
    ofs << mol.GetTitle() << endl << endl;

    ofs << "#" << endl;
    ofs << "# NB: Class I directives (e.g. memory, multiplicity, charge etc) go here" << endl;
    ofs << "#" << endl;
    ofs << "# For more information see: http://www.cfs.dl.ac.uk/docs/index.shtml" << endl;
    ofs << "#" << endl;
    ofs << endl;

    ofs << "geometry angstrom" << endl;
    FOR_ATOMS_OF_MOL(atom, mol)
      {
        snprintf(buffer, BUFF_SIZE, "%15.8f %15.8f %15.8f %3d %3s\n",
		 atom->GetX(),
		 atom->GetY(),
		 atom->GetZ(),
		 atom->GetAtomicNum(),
		 etab.GetSymbol(atom->GetAtomicNum())
		 );
	ofs << buffer;
      }
    ofs << "end" << endl << endl;

    ofs << endl;
    ofs << "basis 6-31G" << endl;
    ofs << endl;

    ofs << "#" << endl;
    ofs << "# NB: Class II directives go here" << endl;
    ofs << "#" << endl;
    ofs << "# To perform a dft calculation with b3lyp and medium quadrature uncomment the below" << endl;
    ofs << "# dft b3lyp" << endl;
    ofs << "# dft quadrature medium" << endl;
    ofs << "#" << endl;
    ofs << endl;

    ofs << "runtype scf" << endl;
    ofs << endl;
    ofs << "enter" << endl;

    return(true);
  } //End WriteMolecule

  class GAMESSUKOutputFormat : public OBMoleculeFormat, public GAMESSUKFormat
  {
  public:
    //Register this format type ID
    GAMESSUKOutputFormat()
    { OBConversion::RegisterFormat("gukout",this, "chemical/x-gamess-output"); }

    virtual const char* Description() //required
    { return "GAMESS-UK Output\n"; };

    virtual const char* SpecificationURL()
    {return "http://www.cfs.dl.ac.uk";}; //optional

    virtual const char* GetMIMEType()
    { return "chemical/x-gamessuk-output"; };

    ////////////////////////////////////////////////////
    /// The "API" interface functions
    virtual bool ReadMolecule(OBBase* pOb, OBConversion* pConv);

  private:
    enum RunType_t { UNKNOWN, SINGLEPOINT, OPTXYZ, OPTZMAT, SADDLE, FREQUENCIES };
    vector<string> tokens, geomList; // list of lines and list of tokens on a line
    string line; // For convenience so we can refer to lines from the iterator as 'line'
    bool ReadInputZmatrix( OBMol &mol, std::istream &ifs );
    bool ReadInitialCartesian( OBMol &mol, std::istream &ifs );
    bool ReadOptGeomXyz1( OBMol &mol, std::istream &ifs );
    bool ReadOptGeomXyz2( OBMol &mol, std::istream &ifs );
    bool ReadNormalModesHessian( OBMol &mol, std::istream &ifs);
    bool ReadNormalModesForce( OBMol &mol, std::istream &ifs);
  };

  //Make an instance of the format class
  GAMESSUKOutputFormat theGAMESSUKOutputFormat;

  bool GAMESSUKOutputFormat::ReadInputZmatrix( OBMol &mol, std::istream &ifs )
  {
    /* The zmatrix entered by the user
     * REM:  need to add stuff for "automatic z-matrix generation" as we currently
     * ignore the zmatrix & just read the cartesian coordinates
     */
    geomList.clear();

    // skip 2 lines
    ifs.getline(buffer, BUFF_SIZE) && ifs.getline(buffer, BUFF_SIZE);

    // Stick a header line first
    geomList.push_back("zmatrix bohr");

    // Read zmatrix into list until blank line
    while (ifs.good() && ifs.getline(buffer, BUFF_SIZE) && strlen(buffer) != 0)
      {
        line = buffer;
        // transform(method.begin(), method.end(), method.begin(), ::tolower);
        ToLower(line);
        Trim(line);
        geomList.push_back(line);
      }

    // Skip 2 lines
    ifs.getline(buffer, BUFF_SIZE);
    ifs.getline(buffer, BUFF_SIZE);

    // Check if line is variables line
    if (strstr(buffer,"name            input  type     hessian         minima") != NULL)
      {
        // Skip additional line to be where variables are printed
        ifs.getline(buffer, BUFF_SIZE);
        // Read in the variables till we hit blank line
        if (! ReadVariables(ifs, 1.0, "")) return false;
      }

    // Now go and process the geometry
    return ReadGeometry(mol, geomList);
  } // ReadInputZmatrix

  bool GAMESSUKOutputFormat::ReadInitialCartesian( OBMol &mol, std::istream &ifs )
  {
    bool ok=false;
    double x,y,z;
    int n;

    // Skip 3 lines
    ifs.getline(buffer, BUFF_SIZE) &&
      ifs.getline(buffer, BUFF_SIZE) &&
      ifs.getline(buffer, BUFF_SIZE);

    // Create regex for the coords
    //                     ------label--------   -------charge-------- < seems enough for a match
    string pattern(" *\\* *[a-zA-Z]{1,2}[0-9]* *[0-9]{1,3}\\.[0-9]{1}");
    bool iok;
#ifdef _MSC_VER
    std::tr1::regex myregex;
    try {
      myregex.assign(pattern,
                     std::tr1::regex_constants::extended |
                     std::tr1::regex_constants::nosubs);
      iok = true;
    } catch (std::tr1::regex_error ex) {
      iok = false;
    }
#else
    regex_t *myregex = new regex_t;
    iok = regcomp(myregex, pattern.c_str(), REG_EXTENDED | REG_NOSUB)==0;
#endif
    if (!iok) cerr << "Error compiling regex in GUK OUTPUT!\n";

    // Read in the coordinates - we process them directly rather
    // then use ReadGeometry as we probably should do...
    mol.BeginModify();
    while (ifs.good() && ifs.getline(buffer, BUFF_SIZE)){

      // End of geometry block
      if (strstr(buffer,"*************************")!=NULL)break;
#ifdef _MSC_VER
      if (std::tr1::regex_search(buffer, myregex)) {
#else
        if (regexec(myregex, buffer, 0, 0, 0)==0) {
#endif
          //cerr << "Got Coord line: " << buffer << endl;
          OBAtom *atom = mol.NewAtom();
          tokenize(tokens,buffer," ");

          ok = from_string<int>(n, tokens.at(2), std::dec);
          atom->SetAtomicNum(n);
          ok = from_string<double>(x, tokens.at(3), std::dec);
          x=x*BOHR_TO_ANGSTROM;
          ok = from_string<double>(y, tokens.at(4), std::dec);
          y=y*BOHR_TO_ANGSTROM;
          ok = from_string<double>(z, tokens.at(5), std::dec);
          z=z*BOHR_TO_ANGSTROM;
          atom->SetVector(x, y, z);
        }
      }
      mol.EndModify();
#ifndef _MSC_VER
      regfree(myregex);
#endif
      return true;
    } // End ReadInitalCartesian

    bool GAMESSUKOutputFormat::ReadOptGeomXyz1( OBMol &mol, std::istream &ifs )
    {
      bool ok=false;
      double x,y,z;
      int n;

      // Clear the Molecule as we're going to start from scratch again.
      mol.BeginModify();
      mol.Clear();

      // FF to start of coordinate specification
      while (ifs.good() && ifs.getline(buffer, BUFF_SIZE)) {
        if (strstr(buffer,
                   "atom     znuc       x             y             z") != NULL) break;
      }

      // Skip 2 lines - should then be at the coordinates
      ifs.getline(buffer, BUFF_SIZE) &&
        ifs.getline(buffer, BUFF_SIZE);

      // Read in the coordinates - we process them directly rather
      // then use ReadGeometry as we probably should do...
      while (ifs.good() && ifs.getline(buffer, BUFF_SIZE)){

        // End of geometry block
        if (strstr(buffer,"*************************")!=NULL)break;

        //cerr << "Got Coord line: " << buffer << endl;
        OBAtom *atom = mol.NewAtom();
        tokenize(tokens,buffer," ");

        ok = from_string<int>(n, tokens.at(2), std::dec);
        atom->SetAtomicNum(n);
        ok = from_string<double>(x, tokens.at(3), std::dec);
        x=x*BOHR_TO_ANGSTROM;
        ok = from_string<double>(y, tokens.at(4), std::dec);
        y=y*BOHR_TO_ANGSTROM;
        ok = from_string<double>(z, tokens.at(5), std::dec);
        z=z*BOHR_TO_ANGSTROM;
        atom->SetVector(x, y, z);

      }

      mol.EndModify();
      return true;
    } // End ReadOptGeomXyz

    bool GAMESSUKOutputFormat::ReadOptGeomXyz2( OBMol &mol, std::istream &ifs )
    {
      bool ok=false;
      double x,y,z;
      int n;

      // Clear the Molecule as we're going to start from scratch again.
      mol.BeginModify();
      mol.Clear();

      while (ifs.good() && ifs.getline(buffer, BUFF_SIZE)) {
        if (strstr(buffer,
                   "       x              y              z            chg  tag") != NULL) break;
      }

      // Skip 1 line - should then be at the coordinates
      ifs.getline(buffer, BUFF_SIZE);

      // Read in the coordinates - we process them directly rather
      // then use ReadGeometry as we probably should do...
      while (ifs.good() && ifs.getline(buffer, BUFF_SIZE)){

        // End of geometry block
        if (strstr(buffer,"============================================================")!=NULL)break;

        //cerr << "Got Coord line: " << buffer << endl;
        OBAtom *atom = mol.NewAtom();
        tokenize(tokens,buffer," ");

        ok = from_string<int>(n, tokens.at(3), std::dec);
        atom->SetAtomicNum(n);
        ok = from_string<double>(x, tokens.at(0), std::dec);
        x=x*BOHR_TO_ANGSTROM;
        ok = from_string<double>(y, tokens.at(1), std::dec);
        y=y*BOHR_TO_ANGSTROM;
        ok = from_string<double>(z, tokens.at(2), std::dec);
        z=z*BOHR_TO_ANGSTROM;
        atom->SetVector(x, y, z);
      }

      mol.EndModify();
      return true;

    } // End ReadOptGeomZmat

    bool GAMESSUKOutputFormat::ReadNormalModesHessian( OBMol &mol, std::istream &ifs)
    {

      bool ok=false;
      double dtmp,dtmp2;

      int ncols = 8; // Think this is always the case
      int natoms = mol.NumAtoms();
      int maxroot = natoms*3;

      // Create data structures
      std::vector< double > frequencies, intensities;
      std::vector< std::vector< vector3 > > Lx;

      // Set up data structures with null data
      for( int i=0; i<maxroot; i++ )
        {
          std::vector< vector3 > atoml;
          for( int j=0; j < natoms; j++ )
            {
              atoml.push_back( vector3(0.0,0.0,0.0) );
            }
          Lx.push_back( atoml );
        }

      ifs.getline(buffer, BUFF_SIZE); // skip "===============" line

      int root7;
      for ( int root1=0; root1 < maxroot; root1+=ncols )
        {
          root7 = root1 + ncols;
          root7 = min(maxroot,root7);

          //Skip 6 lines to col header with frequencies
          for( int j=0; j < 6; j++ )
            ifs.getline(buffer, BUFF_SIZE);

          tokenize(tokens,buffer," \t\n");
          for( std::size_t si=0; si < tokens.size(); si++ )
            {
              ok = from_string<double>(dtmp, tokens.at(si), std::dec);
              frequencies.push_back(dtmp);
              intensities.push_back( 0.0 ); // Add placeholder data
            }

          // Skip 2 lines to where data matrix starts
          ifs.getline(buffer, BUFF_SIZE);
          ifs.getline(buffer, BUFF_SIZE);

          int mycols=root7-root1;
          // Loop over atoms & the x,y,z
          int atomcount=0;
          for ( int i=0; i<maxroot; i+=3 )
            {
              for ( int j=0; j<3; j++ )
                {
                  ifs.getline(buffer, BUFF_SIZE);
                  //std::cout << "GOT LINE:" << buffer <<std::endl;
                  tokenize(tokens,buffer," \t\n");
                  int start=1;
                  if ( j == 0 )
                    start=3;
                  for ( int k=0; k<mycols; k++ )
                    {
                      //std::cout << "Lx[ " << root1+k << " ]" <<
                      //  "][ " << atomcount << " ] [ " << j << " ] = " << tokens.at(start+k) << std::endl;
                      ok = from_string<double>(dtmp, tokens.at(start+k), std::dec);
                      if ( j==0)
                        Lx[ root1+k ][ atomcount ].SetX( dtmp );
                      else if ( j==1 )
                        Lx[ root1+k ][ atomcount ].SetY( dtmp );
                      else if ( j==2 )
                        Lx[ root1+k ][ atomcount ].SetZ( dtmp );
                    }
                } // End j loop
              atomcount+=1;
            } // End loop over atoms
        } // loop over root1

      // Now skip down to read in intensities
      for( int i=0; i<7; i++ )
        {
          ifs.getline(buffer, BUFF_SIZE);
        }

      // loop until we've read them all in
      for( std::size_t si=0; si<frequencies.size(); si++ )
        {
          ifs.getline(buffer, BUFF_SIZE);
          // End of info
          if (strstr(buffer,"============")!=NULL)break;
          tokenize(tokens,buffer," \t\n");

          ok = from_string<double>(dtmp, tokens.at(1), std::dec);
          ok = from_string<double>(dtmp2, tokens.at(6), std::dec);
          // Now match them up
          for( std::size_t sj=0; sj<frequencies.size(); sj++ )
            {
              if ( std::abs( frequencies.at(sj) - dtmp ) < 0.01 )
                {
                  intensities[sj]= dtmp2;
                  continue;
                }
            }
        }

      //for (int i=0; i< frequencies.size(); i++ )
      //  std::cout << "Frequency: " << frequencies.at(i) << " : " << intensities.at(i) << std::endl;

      if(frequencies.size()>0)
        {
          OBVibrationData* vd = new OBVibrationData;
          vd->SetData(Lx, frequencies, intensities);
          vd->SetOrigin(fileformatInput);
          mol.SetData(vd);
        }
      return ok;
    } // End ReadNormalModesHessian

    bool GAMESSUKOutputFormat::ReadNormalModesForce( OBMol &mol, std::istream &ifs)
    {

      bool ok=false;
      double dtmp;

      int ncols = 9; // Think this is always the case
      int natoms = mol.NumAtoms();
      int maxroot = natoms*3;
      int start,mycols;

      // Create data structures
      std::vector< double > frequencies, intensities;
      std::vector< std::vector< vector3 > > Lx;

      // Set up data structures with null data
      for( int i=0; i<maxroot; i++ )
        {
          std::vector< vector3 > atoml;
          for( int j=0; j < natoms; j++ )
            {
              atoml.push_back( vector3(0.0,0.0,0.0) );
            }
          Lx.push_back( atoml );
        }

      ifs.getline(buffer, BUFF_SIZE); // skip "===============" line

      int root7;
      for ( int root1=0; root1 < maxroot; root1+=ncols )
        {
          root7 = root1 + ncols;
          root7 = min(maxroot,root7);
          mycols=root7-root1;

          //Skip 6 lines to col header with frequencies
          for( int j=0; j < 6; j++ )
            ifs.getline(buffer, BUFF_SIZE);

          line=buffer;
          // Need  to manually chop up line
          start=20; // Numbers start at col 20 & are 11 characters long
          for( int i=0; i<mycols; i++)
            {
              ok = from_string<double>(dtmp, line.substr(start,12), std::dec);
              frequencies.push_back(dtmp);
              intensities.push_back( 10.0 ); // Intensities aren't printed so just use 10
              start+=12;
            }

          // Skip 2 lines to where data matrix starts
          ifs.getline(buffer, BUFF_SIZE);
          ifs.getline(buffer, BUFF_SIZE);

          // Loop over atoms & the x,y,z
          int atomcount=0;
          for ( int i=0; i<maxroot; i+=3 )
            {
              //for j in range(3):
              for ( int j=0; j<3; j++ )
                {
                  ifs.getline(buffer, BUFF_SIZE);
                  //std::cout << "GOT LINE:" << buffer <<std::endl;
                  tokenize(tokens,buffer," \t\n");
                  start=1;
                  if ( j == 0 )
                    start=3;
                  for ( int k=0; k<mycols; k++ )
                    {
                      // std::cout << "Lx[ " << root1+k << " ]" <<
                      //  "][ " << atomcount << " ] [ " << j << " ] = " << tokens.at(start+k) << std::endl;
                      ok = from_string<double>(dtmp, tokens.at(start+k), std::dec);
                      if ( j==0)
                        Lx[ root1+k ][ atomcount ].SetX( dtmp );
                      else if ( j==1 )
                        Lx[ root1+k ][ atomcount ].SetY( dtmp );
                      else if ( j==2 )
                        Lx[ root1+k ][ atomcount ].SetZ( dtmp );
                    }
                } // End j loop
              atomcount+=1;
            } // End loop over atoms
        } // loop over root1

      //for (int i=0; i< frequencies.size(); i++ )
      //  std::cout << "Frequency: " << frequencies.at(i) << " : " << intensities.at(i) << std::endl;

      if(frequencies.size()>0)
        {
          OBVibrationData* vd = new OBVibrationData;
          vd->SetData(Lx, frequencies, intensities);
          vd->SetOrigin(fileformatInput);
          mol.SetData(vd);
        }
      return ok;
    } // End ReadNormalModesForce

    /*
      bool GAMESSUKOutputFormat::ReadOptGeomZmat( OBMol &mol, std::istream &ifs )
      {

      //Below was for reading in zmatricies - ignore for the time being

      // Original geometry specification should still be in geomList
      // So just update the variables
      //cerr << "Got converged for OPTZMAT\n";

      // FF to variable specification
      while (ifs.good() && ifs.getline(buffer, BUFF_SIZE)) {
      if (strstr(buffer,
      " variable           value                hessian") != NULL) break;
      }
      // Skip a line - should then be at variable specification
      ifs.getline(buffer, BUFF_SIZE);

      // Process them
      if (! ReadVariables(ifs, BOHR_TO_ANGSTROM,
      "===============================================")) return false;

      // Now go and process with the geometry we read before
      return ReadGeometry(mol, geomList);

      } //ReadOptGeomZmat
    */

    bool GAMESSUKOutputFormat::ReadMolecule(OBBase* pOb, OBConversion* pConv) {

      /*
        Read a GAMESS-UK output file. The reader is currently set up to only return one molecule, i.e
        if the run is some sort of optimisation run, then only the optimised geometry is returned.

        Previously we parsed in the z-matrix - and the code to do that is still here and should work.
        However, the zmatrix is not actually used anywhere in OpenBabel currently - it's just converted
        to Cartesians, and this code appears to be buggy, so for the time being we just stick to reading
        Cartesians.
      */

      OBMol *pmol = dynamic_cast<OBMol*>(pOb);
      if (pmol==NULL)
        return false;

      //Define some references so we can use the old parameter names
      istream& ifs = *pConv->GetInStream();
      OBMol &mol = *pmol;

      // Get a default title as the filename
      const char* title = pConv->GetTitle();
      mol.BeginModify();
      mol.SetTitle(title);
      mol.EndModify();

      RunType_t RunType=UNKNOWN;
      bool ok;
      std::string runt;

      while (ifs.good() && ifs.getline(buffer, BUFF_SIZE))
        {

          if (strstr(buffer,"                              input z-matrix") != NULL)
            {
              /* OpenBabel's handling of zmatricies is currently too buggy and the zmatrix
               * read in isn't currently used - it's just converted to cartesians, so we
               * can skip this for the time being
               */
              continue;
              /*
                ok = ReadInputZmatrix( mol, ifs );
                // Set Runtype to SINGLEPOINT so we don't read in the cartesians
                RunType=SINGLEPOINT;
              */
            } // End Reading user z-matrix

          // Read the cartesian coordinates if we've not read in the ZMATRIX
          if (strstr(buffer,"*            charge       x             y              z       shells") != NULL &&
              RunType==UNKNOWN)
            ok = ReadInitialCartesian( mol, ifs );

          // Determine the RunType - affects how we move on from here.
          if (strstr(buffer," * RUN TYPE") != NULL)
            {
              tokenize(tokens,buffer," \t\n");
              runt=tokens[3].substr(0,5);
              if(runt=="optxy") RunType=OPTXYZ;
              else if (runt=="optim") RunType=OPTZMAT;
              else if (runt=="saddl") RunType=SADDLE;
              continue;
            } // End RUNTYPE

          // Read the optimised geometry
          if (strstr(buffer,"optimization converged") != NULL)
            {
              if (RunType==OPTXYZ)
                ok = ReadOptGeomXyz1( mol, ifs );
              else if (RunType==OPTZMAT || RunType==SADDLE)
                ok = ReadOptGeomXyz2( mol, ifs );
            } // End read optimised geometry

          // Frequencies for runtype hessian
          if (strstr(buffer,"cartesians to normal") != NULL)
            ok = ReadNormalModesHessian( mol, ifs);

          // Frequencies for runtype force
          if (strstr(buffer,"eigenvectors of cartesian") != NULL)
            ok = ReadNormalModesForce( mol, ifs);

        } // End Reading loop

      if (mol.NumAtoms() == 0) { // Something went wrong
        mol.EndModify();
        return false;
      } else {
        mol.BeginModify();
        if (!pConv->IsOption("b",OBConversion::INOPTIONS))
          mol.ConnectTheDots();
        if (!pConv->IsOption("s",OBConversion::INOPTIONS) && !pConv->IsOption("b",OBConversion::INOPTIONS))
          mol.PerceiveBondOrders();
        mol.EndModify();
        return true;
      }

    } // End GAMESSUKOutputFormat::ReadMolecule

  } //namespace OpenBabel


text:
(function(root){
    // Get app
    var app = root.app;

    // Page
    var Page = app.Page = React.createClass({
        displayName: "Page",

        getInitialState: function() {
            return {
                active: this.props.active
            };
        },

        componentWillMount: function(){
            this.dispatchToken = app.dispatcher.register(function(payload){
                switch(payload.actionType) {
                    case "change:url":
                        this.state.active = payload.currentPage == this.props.page.name && payload.currentTopic == this.props.topic.name;
                        this.setState(payload);
                        break;
                }
            }.bind(this));
        },

        componentWillUnmount: function(){
            app.dispatcher.unregister(this.dispatchToken);
        },

        componentDidMount: function(){
            if (this.state.active) {
                app.dispatcher.dispatch({
                    actionType: "change:page",
                    pageId: this.props.page.id,
                });
            }
        },

        changeMarkdown: function(e){
            e.preventDefault();

            app.router.setRoute($(e.target).attr("href"));
            app.dispatcher.dispatch({
                actionType: "change:page",
                pageId: this.props.page.id,
            });
        },

        render: function() {
            var page = this.props.page;
            var source = this.props.source;

            var cn = ["page", this.state.active ? "active" : ""].join(' ');
            return

                            {page.title}

        }
    });
})(this);

redpajama_set_name: RedPajamaGithub


text:
<?php

require_once('../includes/base.php');
require_once('../database/Funcionarios.php');

// check privileges
// if ($s_type != "admin") {
//   $_SESSION["s_errors"]["generic"][] = 'Não tem permissões';
//   header("Location: ../index.php");
//   die;
// }

// check parameters
if (!isset($_GET["uid"])) {
  $_SESSION["s_errors"]["generic"][] = 'O login é obrigatório!';
  header("Location: list.php");
  die;
}

if ($s_values)
  $employee = $s_values;
else
  $employee = Funcionarios::getEmployeesData($_GET["uid"]);

if ($employee == null) {
  $_SESSION["s_errors"]["generic"][] = 'O funcionário '.$_GET["uid"].' não existe!';
  header("Location: list.php");
}

// celar the password
$employee["pass"] = "";

$smarty->assign("employee", $employee);

$smarty->display('definicoes_conta/edit.tpl');

?>


text:
#ifndef MEDIA_CDM_PPAPI_EXTERNAL_OPEN_CDM_MEDIAENGINE_OPEN_CDM_MEDIAENGINE_FACTORY_H_
#define MEDIA_CDM_PPAPI_EXTERNAL_OPEN_CDM_MEDIAENGINE_OPEN_CDM_MEDIAENGINE_FACTORY_H_

#include <string>

#include "media/cdm/ppapi/external_open_cdm/src/mediaengine/open_cdm_mediaengine.h"
#include "media/cdm/ppapi/external_open_cdm/src/mediaengine/open_cdm_mediaengine_impl.h"

#include "media/cdm/ppapi/cdm_logging.h"

namespace media {

#ifdef OCDM_USE_PLAYREADY
const std::string open_cdm_key_system = "com.microsoft.playready";
#else
const std::string open_cdm_key_system = "org.chromium.externalclearkey";
#endif

// TODO(ska): outsource the mapping of key system string
// to mediaengine and platform implementations

class OpenCdmMediaengineFactory {
 public:
  static OpenCdmMediaengine *Create(std::string key_system,
                                    OpenCdmPlatformSessionId session_id);
};

/*
 * returns raw pointer to be platform and type independent, can be converted
 * to smart pointer on successful creation.
 */
OpenCdmMediaengine *OpenCdmMediaengineFactory::Create(
    std::string key_system, OpenCdmPlatformSessionId session_id) {
  if (key_system == open_cdm_key_system) {
    CDM_DLOG() << "Instantiate OpenCdmMediaengineImpl!";
    return new OpenCdmMediaengineImpl(session_id.session_id,
                                      session_id.session_id_len);
  } else {
    CDM_DLOG() << "Failed to create MediaEngine";
    return NULL;
  }
}
}  // namespace media

#endif  // MEDIA_CDM_PPAPI_EXTERNAL_OPEN_CDM_MEDIAENGINE_OPEN_CDM_MEDIAENGINE_FACTORY_H_


text:
package proj.mgmt.rest.utils;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;

public abstract class MySqlUtil<T> implements DBHelperUtil<T> {

	private static String CLAZZ_NAME = MySqlUtil.class.getName();
	private static Logger _logger = Logger.getLogger(CLAZZ_NAME);

	private String getSelectStatement() {
		return getSelectStatement(0, Integer.MAX_VALUE);
	}

	private String getSelectStatement(int pStart, int pLength) {
		String selectStatement = "SELECT * FROM " + getTableName() + " LIMIT "
				+ pStart + ", " + pLength;
		return selectStatement;
	}

	@Override
	public List<HashMap<String, T>> queryData(int pStartIdx, int pLength) {
		String methodName = "queryData";
		_logger.entering(CLAZZ_NAME, methodName);
		List<HashMap<String, T>> returnList = new LinkedList<HashMap<String, T>>();
		String selectStatement = getSelectStatement(pStartIdx, pLength);
		_logger.exiting(CLAZZ_NAME, methodName, returnList);
		return returnList;
	}

	@Override
	public void deleteData(int pId) {
		// TODO Auto-generated method stub

	}

	@Override
	public void deleteData(HashMap<String, T> pObject) {
		// TODO Auto-generated method stub

	}

	@Override
	public void updateData(int pId, HashMap<String, T> pObject) {
		// TODO Auto-generated method stub

	}

	@Override
	public void updateData(HashMap<String, T> pObject) {
		// TODO Auto-generated method stub

	}

	@Override
	public void updateData(int pId) {
		// TODO Auto-generated method stub

	}

}


text:
require 'spec_helper'

describe WikiPost do
  before(:each) do
    @wiki_post = WikiPost.new
  end

  it "should require name" do
    @wiki_post.name = nil
    @wiki_post.should_not be_valid
#    @wiki_post.errors.on(:name).should_not be_nil
  end

  it "should pass correct names" do
    @wiki_post.title = "correct title"
    @wiki_post.raw_text = "corrent raw text"
    combinations(["abcdefghijklmnopqrstuvwxzy", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "0123456789", "абвгдеёжзийклмнопрстуфхцчшщЪьэюя", "АБВГДЕЁЖЗИКЛМНОПРСТУФХЦЧШЩЪЬЭЮЯ", "_"]).each do |combination|
      @wiki_post.name = combination.join("")
      @wiki_post.should be_valid
    end
  end

  it "should faild incorrect names" do
    @wiki_post.title = "correct title"
    @wiki_post.raw_text = "corrent raw text"
    for inc in '!@#$%^&*().,'.split("")
      @wiki_post.name = "hello" + inc
      @wiki_post.should_not be_valid
    end
  end

  it "should process text" do
    @wiki_post.name = "name"

    @wiki_post.raw_text = "correct raw **text**"
    @wiki_post.save
    @wiki_post.processed_text.should == SimpleWiki::MarkupProcessor.process(@wiki_post.raw_text)
  end

  def combinations(array)
    m = array.length
    (1...2**m).map do | n |
      (0...m).select { | i | n[i] == 1 }.map { | i | array[i] }
    end
  end
end


text:
var xhrHeaders = hammerhead.get('../request-pipeline/xhr/headers');

if (window.fetch) {
    asyncTest('global fetch - redirect request to proxy', function () {
        fetch('/xhr-test/100')
            .then(function (response) {
                return response.text();
            }).then(function (url) {
                strictEqual(url, '/sessionId/https://example.com/xhr-test/100');
                start();
            });
    });

    asyncTest('Request - redirect request to proxy', function () {
        var request = new Request('/xhr-test/100');

        fetch(request)
            .then(function (response) {
                return response.text();
            }).then(function (url) {
                strictEqual(url, '/sessionId/https://example.com/xhr-test/100');
                start();
            });
    });

    asyncTest('nested Request - redirect request to proxy', function () {
        var request = new Request('/xhr-test/100');

        fetch(new Request(request))
            .then(function (response) {
                return response.text();
            }).then(function (url) {
                strictEqual(url, '/sessionId/https://example.com/xhr-test/100');
                start();
            });
    });

    asyncTest('pass arguments', function () {
        var data = {
            param1: 'value1',
            param2: 'value2'
        };

        fetch('/echo-request-body', {
            method:  'post',
            headers: {
                'Content-Type': 'application/json; charset=UTF-8'
            },
            body: JSON.stringify(data)
        })
            .then(function (response) {
                return response.json();
            })
            .then(function (json) {
                strictEqual(JSON.stringify(json), JSON.stringify(data));
                start();
            });
    });

    asyncTest('the internal 222 status code should be replaced with 0 on the client side', function () {
        fetch('/xhr-222/')
            .then(function (response) {
                strictEqual(response.status, 0);

                start();
            });
    });

    module('Response.type', function () {
        asyncTest('basic', function () {
            fetch('/xhr-test/100')
                .then(function (response) {
                    strictEqual(response.type, 'basic');
                    start();
                });
        });
        asyncTest('cors', function () {
            fetch(window.QUnitGlobals.crossDomainHostname + '/xhr-test/100')
                .then(function (response) {
                    strictEqual(response.type, 'cors');
                    start();
                });
        });
        asyncTest('opaque', function () {
            fetch(window.QUnitGlobals.crossDomainHostname + '/xhr-222/')
                .then(function (response) {
                    strictEqual(response.type, 'opaque');
                    start();
                });
        });
    });

    module('request modes', function () {
        module('no-cors');

        // NOTE: not supported scenario
        // It is impossible to add custom headers to the fetch request
        // with the 'no-cors' mode
        // see https://fetch.spec.whatwg.org/#concept-headers-guard
        // https://fetch.spec.whatwg.org/#cors-safelisted-request-header
        QUnit.skip('same-domain', function () {
            fetch('/xhr-test/100', { mode: 'no-cors' })
                .then(function (response) {
                    strictEqual(response.status, 0);
                    strictEqual(response.type, 'opaque');

                    start();
                });
        });

        module('same-origin');

        asyncTest('same-domain', function () {
            fetch('/xhr-test/100', { mode: 'same-origin' })
                .then(function (response) {
                    strictEqual(response.status, 200);
                    strictEqual(response.type, 'basic');

                    start();
                });
        });

        asyncTest('same-domain (sub-domain)', function () {
            fetch('https://sub-domain.example.com', { mode: 'same-origin' })
                .then(function () {
                    ok(false, 'request should not be performed');
                })
                .catch(function (err) {
                    ok(err instanceof TypeError);
                    start();
                });
        });

        asyncTest('cross-domain (global fetch)', function () {
            fetch('http://cross.domain.com', { mode: 'same-origin' })
                .then(function () {
                    ok(false, 'request should not be performed');
                })
                .catch(function (err) {
                    ok(err instanceof TypeError);
                    start();
                });
        });

        asyncTest('cross-domain (Request)', function () {
            var request = new Request('http://cross.domain.com', { mode: 'same-origin' });

            fetch(request)
                .then(function () {
                    ok(false, 'request should not be performed');
                })
                .catch(function (err) {
                    ok(err instanceof TypeError);
                    start();
                });
        });
    });

    module('special headers', function () {
        module('Fetch request credentials', function () {
            module('default values');

            asyncTest('headers is object', function () {
                fetch('/echo-request-headers', {
                    method:  'post',
                    headers: {
                        'Content-Type': 'application/json; charset=UTF-8'
                    }
                })
                    .then(function (response) {
                        return response.json();
                    })
                    .then(function (headers) {
                        strictEqual('omit', headers[xhrHeaders.fetchRequestCredentials]);
                        start();
                    });
            });

            asyncTest('headers is window.Headers', function () {
                var testHeaders = new Headers();

                testHeaders.append('Content-Type', 'application/json; charset=UTF-8');

                fetch('/echo-request-headers', {
                    method:  'post',
                    headers: testHeaders
                })
                    .then(function (response) {
                        return response.json();
                    })
                    .then(function (headers) {
                        strictEqual('omit', headers[xhrHeaders.fetchRequestCredentials]);
                        start();
                    });
            });

            module('non-default values');

            asyncTest('headers is object', function () {
                fetch('/echo-request-headers', {
                    method:      'post',
                    headers:     { 'Content-Type': 'application/json; charset=UTF-8' },
                    credentials: 'same-origin'
                })
                    .then(function (response) {
                        return response.json();
                    })
                    .then(function (headers) {
                        strictEqual('same-origin', headers[xhrHeaders.fetchRequestCredentials]);
                        start();
                    });
            });

            asyncTest('headers is window.Headers', function () {
                var testHeaders = new Headers();

                testHeaders.append('Content-Type', 'application/json; charset=UTF-8');

                fetch('/echo-request-headers', {
                    method:      'post',
                    headers:     testHeaders,
                    credentials: 'same-origin'
                })
                    .then(function (response) {
                        return response.json();
                    })
                    .then(function (headers) {
                        strictEqual('same-origin', headers[xhrHeaders.fetchRequestCredentials]);
                        start();
                    });
            });
        });

        module('Origin', function () {
            module('global fetch');

            asyncTest('headers is object', function () {
                fetch('/echo-request-headers', {
                    method:  'post',
                    headers: {
                        'Content-Type': 'application/json; charset=UTF-8'
                    }
                })
                    .then(function (response) {
                        return response.json();
                    })
                    .then(function (headers) {
                        strictEqual('https://example.com', headers[xhrHeaders.origin]);
                        start();
                    });
            });

            asyncTest('headers is window.Headers', function () {
                var testHeaders = new Headers();

                testHeaders.append('Content-Type', 'application/json; charset=UTF-8');

                fetch('/echo-request-headers', {
                    method:  'post',
                    headers: testHeaders
                })
                    .then(function (response) {
                        return response.json();
                    })
                    .then(function (headers) {
                        strictEqual('https://example.com', headers[xhrHeaders.origin]);
                        start();
                    });
            });

            module('Request');

            asyncTest('headers is object', function () {
                var request = new Request('/echo-request-headers', {
                    method:  'post',
                    headers: {
                        'Content-Type': 'application/json; charset=UTF-8'
                    }
                });

                fetch(request)
                    .then(function (response) {
                        return response.json();
                    })
                    .then(function (headers) {
                        strictEqual('https://example.com', headers[xhrHeaders.origin]);
                        start();
                    });
            });

            asyncTest('headers is window.Headers', function () {
                var testHeaders = new Headers();

                testHeaders.append('Content-Type', 'application/json; charset=UTF-8');

                var request = new Request('/echo-request-headers', {
                    method:  'post',
                    headers: testHeaders
                });

                fetch(request)
                    .then(function (response) {
                        return response.json();
                    })
                    .then(function (headers) {
                        strictEqual('https://example.com', headers[xhrHeaders.origin]);
                        start();
                    });
            });
        });
    });

    module('regression', function () {
        asyncTest('request promise should be rejected for the 500 http status code (GH-602)', function () {
            expect(1);

            fetch('/respond-500')
                .then(function (response) {
                    return response.text();
                })
                .then(function () {
                    ok(false, 'request promise should be rejected');
                    start();
                })
                .catch(function (err) {
                    ok(err instanceof TypeError);
                    start();
                });
        });

        test('request promise should be rejected on invalid calling (GH-939)', function () {
            var testCases = [
                [],
                [123],
                [function () { }],
                [null]
            ];

            var createTestCasePromise = function (args) {
                return fetch.apply(window, args)
                    .then(function () {
                        ok(false, 'wrong state of the request promise');
                    })
                    .catch(function () {
                        ok(true);
                    });
            };

            return Promise.all(testCases.map(createTestCasePromise));
        });
    });
}


text:
import os
from wsgiref import simple_server

from oslo_config import cfg
import paste.deploy
from stevedore import named

from kiloeyes.common import namespace
from kiloeyes.common import resource_api
from kiloeyes.openstack.common import log

OPTS = [
    cfg.MultiStrOpt('dispatcher',
                    default=[],
                    help='Dispatchers to process data.'),
]
cfg.CONF.register_opts(OPTS)

LOG = log.getLogger(__name__)

def api_app(conf):
    cfg.CONF(args=[], project='kiloeyes')
    log_levels = (cfg.CONF.default_log_levels)
    cfg.set_defaults(log.log_opts, default_log_levels=log_levels)
    log.setup('kiloeyes')

    dispatcher_manager = named.NamedExtensionManager(
        namespace=namespace.DISPATCHER_NS,
        names=cfg.CONF.dispatcher,
        invoke_on_load=True,
        invoke_args=[cfg.CONF])

    if not list(dispatcher_manager):
        LOG.error('Failed to load any dispatchers for %s' %
                  namespace.DISPATCHER_NS)
        return None

    # Create the application
    app = resource_api.ResourceAPI()

    # add each dispatcher to the application to serve requests offered by
    # each dispatcher
    for driver in dispatcher_manager:
        app.add_route(None, driver.obj)

    LOG.debug('Dispatcher drivers have been added to the routes!')
    return app

if __name__ == '__main__':
    wsgi_app = (
        paste.deploy.loadapp('config:etc/kiloeyes.ini',
                             relative_to=os.getcwd()))
    httpd = simple_server.make_server('127.0.0.1', 9000, wsgi_app)
    httpd.serve_forever()


text:
namespace sevent
{
    namespace event
    {
#ifdef SEVENT_USE_INT_ID
        typedef NumericEventId eventid_t;
#else
        typedef StringEventId eventid_t;
#endif
        typedef boost::shared_ptr<eventid_t> eventid_t_ptr;
    } // namespace socket
} // namespace sevent


text:
import Ember from 'ember';
import layout from '../templates/components/mdl-layout-header';
import LayoutComponent from './mdl-layout-inner';

export default Ember.Component.extend({
  layout: layout,
  classNames: ['mdl-layout__header'],
  classNameBindings: [
      'animating:is-animating',
      'isCompact:is-compact',
      'castingShadow:is-casting-shadow',
      '_layoutComponent.isSeamedMode:mdl-layout__header--seamed',
      '_layoutComponent.isWaterfallMode:mdl-layout__header--waterfall',
      '_layoutComponent.isScrollMode:mdl-layout__header--scroll',
      'transparent:mdl-layout__header--transparent'

  ],
  _layoutComponent: Ember.computed(function () {
    return this.nearestOfType(LayoutComponent);
  }),
  init() {
    this._super(...arguments);
    Ember.run.scheduleOnce('afterRender', this, function () {
      this.get('_layoutComponent').registerComponent(this);
    });
  },
  castingShadow: Ember.computed('_layoutComponent.mode', function () {
    return this.get('_layoutComponent.mode') === 'standard';
  }),
  showDrawerButton: Ember.computed.alias('_layoutComponent.hasDrawer'),
  actions: {
    toggleMenu() {
      this.get('_layoutComponent').toggleProperty('drawerOpen');
    }
  },
  headerTransitionEndHandler_() {
    this.set('animating', false);
  },
  didInsertElement() {
    var lC = this.get('_layoutComponent');

    if (lC.get('isSeamedMode')) {
      this.get('element').addEventListener('transitionend',
          this.headerTransitionEndHandler_.bind(this));
    }

  },

});


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#fafafa</color>
    <color name="colorPrimaryDark">#9e9e9e</color>
    <color name="colorAccent">#9e9e9e</color>
</resources>


text:
package gov.nara.nwts.ftapp.gui;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JTextField;

/**
 * Displays a directory selection dialog; results will be saved to a specified text field.
 * @author TBrady
 *
 */
class DirSelect extends FileSelect {
	private static final long serialVersionUID = 1L;

	public void configureChooser() {
		jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
	}
	DirSelect(JFrame parent, JTextField result, String title) {
		super(parent, result, title);
	}
}


text:
require 'test_helper'
require 'hanami/application_name'

describe Hanami::ApplicationName do
  describe 'formats' do
    describe '#to_s' do
      it 'renders downcased' do
        application_name = Hanami::ApplicationName.new('MY-APP')
        application_name.to_s.must_equal 'my_app'
      end

      it 'renders trimmed' do
        application_name = Hanami::ApplicationName.new(' my-app ')
        application_name.to_s.must_equal 'my_app'
      end

      it 'renders internal spaces as underscores' do
        application_name = Hanami::ApplicationName.new('my app')
        application_name.to_s.must_equal 'my_app'
      end
    end

    describe '#to_env_s' do
      it 'renders uppercased with non-alphanumeric characters as underscores' do
        application_name = Hanami::ApplicationName.new('my-app')
        application_name.to_env_s.must_equal 'MY_APP'
      end
    end
  end

  describe 'reserved words' do
    it 'prohibits "hanami"' do
      exception = -> { Hanami::ApplicationName.new('hanami') }.must_raise RuntimeError
      exception.message.must_equal "application name must not be any one of the following: hanami"
    end

    describe '.invalid?' do
      describe 'when name is "hanami"' do
        it 'returns true' do
          Hanami::ApplicationName.invalid?('hanami').must_equal true
        end
      end
    end
  end
end


text:
package fr.cph.stock.external.web.company;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.ToString;

@Getter
@ToString
public class Quote {
	private String symbol;
	@JsonProperty("StockExchange")
	private String stockExchange;
	@JsonProperty("Name")
	private String name;
	@JsonProperty("Currency")
	private String currency;
	@JsonProperty("DividendYield")
	private Double dividendYield;
	@JsonProperty("LastTradePriceOnly")
	private Double lastTradePriceOnly;
	@JsonProperty("MarketCapitalization")
	private String marketCapitalization;
	@JsonProperty("PreviousClose")
	private Double previousClose;
	@JsonProperty("ChangeinPercent")
	private String changeinPercent;
	@JsonProperty("YearLow")
	private Double yearLow;
	@JsonProperty("YearHigh")
	private Double yearHigh;
}


text:
package com.sleepycat.je.latch;

import java.io.Serializable;

/**
 * A class that provides interesting stats about a particular latch.
 */
public class LatchStats implements Cloneable, Serializable {

    public int nAcquiresNoWaiters = 0;

    /**
     * Number of times acquire() was called when the latch was already owned by
     * the caller.
     */
    public int nAcquiresSelfOwned = 0;

    /**
     * Number of times acquire() was called with allowNesting=true when the
     * latch was already owned by the caller for shared access.
     */
    public int nAcquiresUpgrade = 0;

    /**
     * Number of times acquire() was called when the latch was already owned by
     * the some other thread.
     */
    public int nAcquiresWithContention = 0;

    /**
     * Number of times acquireNoWait() was called when the latch was
     * successfully acquired.
     */
    public int nAcquireNoWaitSuccessful = 0;

    /**
     * Number of unsuccessful acquireNoWait() calls.
     */
    public int nAcquireNoWaitUnsuccessful = 0;

    /**
     * Number of times acquireShared() was called when the latch was
     * successfully acquired.
     */
    public int nAcquireSharedSuccessful = 0;

    /**
     * Numbed of calls to release();
     */
    public int nReleases = 0;

    public String toString() {
        StringBuffer sb = new StringBuffer();
        sb.append("nAcquiresNoWaiters=").
	    append(nAcquiresNoWaiters).append('\n');
        sb.append("nAcquiresSelfOwned=").
	    append(nAcquiresSelfOwned).append('\n');
        sb.append("nAcquiresUpgrade=").
	    append(nAcquiresUpgrade).append('\n');
        sb.append("nAcquiresWithContention=").
	    append(nAcquiresWithContention).append('\n');
        sb.append("nAcquiresNoWaitSuccessful=").
	    append(nAcquireNoWaitSuccessful).append('\n');
        sb.append("nAcquiresNoWaitUnSuccessful=").
	    append(nAcquireNoWaitUnsuccessful).append('\n');
        sb.append("nAcquiresSharedSuccessful=").
	    append(nAcquireSharedSuccessful).append('\n');
        return sb.toString();
    }

    public Object clone()
        throws CloneNotSupportedException {

        return super.clone();
    }
}


text:
	<meta charset="utf-8" />
	<meta name="generator" content="R package animation 2.6">
	<title>Animations Using the R Language</title>
	<link rel="stylesheet" href="css/reset.css" />
	<link rel="stylesheet" href="css/styles.css" />
	<link rel="stylesheet" href="css/scianimator.css" />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.3/styles/github.min.css">


text:
import sys
import os
from gmail import Gmail

def main():
	# Bob is sender, Alide is destination.
	from_address = "bob@domain.com"
	to_address = "alice@domain.com"
	file_info = {"type":"pdf", "subtype":"pdf"}
	a_title = u"Research: slide of today"
	a_body = u'''Dear Alice.

Good afternoon, I'm Bob.
I attach today's slide(2015-04-01.pdf) to this mail.

-----------
Bob Marley.
Kyoto Sangyo University in Japan.
bob@domain.com.
'''
	files = []
	for a_file in os.listdir('.'):
		if ".pdf" in a_file:
			files.append(a_file)

	if len(files) >= 2:
		print "PDF is only one."
		for a_file in files:
			print a_file.decode('utf-8')
	elif len(files) == 0:
		print "PDF is not found."
	elif len(files) == 1:
		a_file = files[0]
		file_info["name"] = a_file
		file_info["path"] = "./" + a_file
		comment = raw_input("comment > ").decode('utf-8')
		if len(comment) == 0:
			a_body = a_body % (a_file.decode('utf-8'), comment)
		else:
			a_body = a_body % (a_file.decode('utf-8'), "\n"+comment)
		print "\n"
		print a_title
		print "*" * 50
		print a_body
		print "*" * 50

		if raw_input("Is This OK? ") == 'y':
			a_gmail = Gmail()
			a_message = a_gmail.create_message(from_address, to_address, a_title, file_info, a_body)
			a_gmail.send(from_address, to_address, a_message)
			print u"Sent!"
		else:
			print u"Sending miss."

if __name__ == '__main__':
	sys.exit(main())


text:
package oncecenter.wizard.newsr;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import oncecenter.Activator;
import oncecenter.util.ImageRegistry;
import oncecenter.util.Ssh;
import oncecenter.util.TypeUtil;
import oncecenter.views.xenconnectiontreeview.elements.VMTreeObject;
import oncecenter.views.xenconnectiontreeview.elements.VMTreeObjectHost;
import oncecenter.views.xenconnectiontreeview.elements.VMTreeObjectRoot;
import oncecenter.wizard.newvmfromtemp.NewVMPage;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.plugin.AbstractUIPlugin;

public class SRLocationWizardPage extends NewVMPage {

	boolean useNFS = true;

	private Text ipText;
	private Text pathText;
	private Text userNameText;
	private Text passwordText;
	private Button check;
	private boolean flag;

	private ProgressMonitorDialog proBarDialog;

	private String infoMsg = "";
	private String errorMsg = "";
	private String ipStr = "";
	private String pathStr = "";
	private String userStr = "";
	private String passStr = "";
	public String getIpStr() {
		return ipStr;
	}

	public String getPathStr() {
		return pathStr;
	}

	private CLabel image;

	VMTreeObjectRoot selection;

	public Text getText() {
		return ipText;
	}

	/**
	 * Create the wizard.
	 */
	public SRLocationWizardPage(VMTreeObjectRoot selection) {
		super("н¨´æ´¢");
		setTitle("н¨´æ´¢");
		setDescription("ÇëÊäÈëÒªÁ¬½ÓµÄ´æ´¢µÄλÖ㬰üÀ¨Ö÷»úµÄipºÍ´æ´¢Â·¾¶");
		this.selection=selection;
	}

	/**
	 * Create contents of the wizard.
	 * @param parent
	 */
	public void createControl(Composite parent) {
		final Composite container = new Composite(parent, SWT.NULL);
		setControl(container);

		Label lblNewLabel = new Label(container, SWT.NONE);
		lblNewLabel.setBounds(45, 47, 80, 20);
		lblNewLabel.setText("Ö÷»úµØÖ·");

		ipText = new Text(container, SWT.BORDER);
		ipText.setBounds(152, 44, 266, 23);

		Label pathLabel = new Label(container,SWT.NONE);
		pathLabel.setBounds(45, 77, 80, 20);
		pathLabel.setText("¹ÒÔØ·¾¶");
		pathText = new Text(container,SWT.BORDER);
		pathText.setBounds(152, 74, 266, 23);

		Label userNameLabel = new Label(container,SWT.NONE);
		userNameLabel.setText("̞   ");
		userNameLabel.setBounds(45, 107, 80, 20);
		userNameText = new Text(container,SWT.BORDER);
		userNameText.setBounds(152, 104, 266, 23);

		Label passwordLabel = new Label(container,SWT.NONE);
		passwordLabel.setText("ÃÜÂë  ");
		passwordLabel.setBounds(45, 137, 80, 20);
		passwordText = new Text(container,SWT.PASSWORD|SWT.BORDER);
		passwordText.setBounds(152, 134, 266, 23);

		refresh();

		check = new Button(container, SWT.PUSH);
		check.setBounds(430, 184, 50, 25);
		check.setText("¼ì²â");

		image = new CLabel(container,SWT.NONE);
		image.setImage(ImageRegistry.getImage(ImageRegistry.SUCCESS));
		image.setBounds(220, 180, 100, 50);
		image.setVisible(false);

		check.addSelectionListener(new SelectionListener(){

			@Override
			public void widgetDefaultSelected(SelectionEvent arg0) {

				widgetSelected(arg0);
			}

			@Override
			public void widgetSelected(SelectionEvent arg0)
			{
				flag = true;
				ipStr = ipText.getText();
				pathStr = pathText.getText();
				userStr = userNameText.getText();
				passStr = passwordText.getText();
				proBarDialog = new ProgressMonitorDialog(Display.getCurrent().getActiveShell());
				try {
					proBarDialog.run(true, true, new IRunnableWithProgress(){

						@Override
						public void run(IProgressMonitor monitor)throws InvocationTargetException,InterruptedException
						{

							monitor.beginTask("ÕýÔÚ¼ì²â........",  IProgressMonitor.UNKNOWN);
							Display display=PlatformUI.getWorkbench().getDisplay();

							if(useNFS){
								if(ipStr==null||ipStr.length()==0
										||pathStr==null||pathStr.length()==0
										||userStr==null||userStr.length()==0
										||passStr==null||passStr.length()==0)
								{
									flag = false;
									infoMsg = "ÇëÕýÈ·Ìîд¸÷Ïî";
						        	errorMsg = "ipµØÖ·£¬Â·¾¶£¬Óû§Ãû£¬ÃÜÂ룬¾ù²»ÄÜΪ¿Õ¡£";
								}else{
									Ssh ssh = new Ssh(ipStr, userStr, passStr);
									boolean isSuccess = ssh.Connect();
									if(!isSuccess){
										flag = false;
										infoMsg = "ÎÞ·¨Á¬½ÓÄ¿±ê»úÆ÷";
							        	errorMsg = "Çë¼ì²éipµØÖ·ºÍÓû§ÃûÃÜÂë¡£";
									}else{
										Ssh ssh1 = new Ssh(selection.getIpAddress(), selection.getUsername(), selection.getPassword());
										ssh1.Connect();
										String ret = "";
										String cmd = "showmount -e " + ipStr;
										try {
											ret = ssh1.Command(cmd);
										} catch (Exception e) {
											e.printStackTrace();
										}
										if(ret == null || ret.length() == 0)
										{
											flag = false;
								        	infoMsg = "Ä¿±ê" + ipStr + "먦ÆôNFS·þÎñ";
								        	errorMsg = "ÎÞ·¨¼ì²âµ½Ä¿±ê»úÆ÷ÉϵÄNFS·þÎñ£¬Çë¼ì²éÉèÖÃÊÇ·ñÕýÈ·²¢ÖØÊÔ¡£";
										}else{
											boolean checkPath = false;
											String[] paths = ret.split("\n");
											for(int i = 1; i < paths.length; ++i)
											{
												String position = paths[i].split(" ")[0];
												if(position.equals(pathStr))
												{
													checkPath = true;
													break;
												}
											}
											if(!checkPath)
											{
												flag = false;
												infoMsg = "Ä¿±ê·¾¶ "+ pathStr + "먦ÆôNFS·þÎñ";
												errorMsg = "¸ø¶¨µÄ·¾¶Î´¿ªÆôNFS·þÎñ£¬Çë¼ì²éÆäËûµÄ¿ÉÓ÷¾¶";
											}else{
												flag = true;
												((NewSRWizard)getWizard()).ip = ipStr;
												((NewSRWizard)getWizard()).path = pathStr;
												((NewSRWizard)getWizard()).username = userStr;
												((NewSRWizard)getWizard()).password = passStr;
											}
										}
									}
								}

							}else{
								if(pathStr==null||pathStr.length()==0)
								{
									flag = false;
									infoMsg = "ÇëÕýÈ·Ìîд¸÷Ïî";
						        	errorMsg = "·¾¶²»ÄÜΪ¿Õ¡£";
								}else{
									boolean checkPath = true;
									String hostName = "";
									//¼ì²é·¾¶ÊÇ·ñ´æÔÚ
									if(selection instanceof VMTreeObjectHost){
										Ssh ssh = new Ssh(selection.getIpAddress(), selection.getUsername(), selection.getPassword());
										ssh.Connect();
										String cmd = "test -e " + pathStr;
										try {
											ssh.Command(cmd);
										} catch (Exception e) {
											e.printStackTrace();
											checkPath = false;
											hostName+=(selection.getName()+" ");
										}
									}else{
										for(VMTreeObject o : selection.getChildren()){
											if(o instanceof VMTreeObjectHost){
												Ssh ssh = new Ssh(((VMTreeObjectHost)o).getIpAddress(), selection.getUsername(), selection.getPassword());
												ssh.Connect();
												String cmd = "test -e " + pathStr;
												try {
													ssh.Command(cmd);
												} catch (Exception e) {
													e.printStackTrace();
													checkPath = false;
													hostName+=(o.getName()+" ");
												}
											}
										}
									}
									if(!checkPath){
										flag = false;
										infoMsg = "·¾¶³ö´í";
							        	errorMsg = "Ö÷»ú£º"+hostName+"Éϲ»´æÔÚ·¾¶"+pathStr+" £¬Çë¼ì²é·¾¶ÊÇ·ñÌîд´íÎó";
									}else{
										flag = true;
										((NewSRWizard)getWizard()).path = pathStr;
									}
								}
							}
							if(flag){
								if (!display.isDisposed()){
								    Runnable runnable = new Runnable(){
								        public void run( ){
								        	image.setVisible(true);
											setPageComplete(true);
								        }
									};
								    display.syncExec(runnable);
								}
							}else{
								if (!display.isDisposed()){
								    Runnable runnable = new Runnable(){
								        public void run( ){
								        	ServiceNotOpenDialog dialog = new ServiceNotOpenDialog(Display.getCurrent().getActiveShell(),infoMsg, errorMsg);
											dialog.open();
											image.setVisible(false);
											canFlipToNextPage();
								        }
									};
								    display.syncExec(runnable);
								}
//								monitor.done();
//								return;
							}
//							if (!display.isDisposed()){
//							    Runnable runnable = new Runnable(){
//							        public void run( ){
//							        	getWizard().getContainer().updateButtons();
//							        }
//								};
//							    display.syncExec(runnable);
//							}

							monitor.done();
						}
					});
				} catch (InvocationTargetException e1) {

					e1.printStackTrace();
				} catch (InterruptedException e1) {

					e1.printStackTrace();
				}
			}
		} );

	}

	public void refresh(){
		String type = ((NewSRWizard)this.getWizard()).type;
		if(type!=null&&type.contains(TypeUtil.nfsSign)){
			useNFS = true;
		}else{
			useNFS = false;
		}
		if(!useNFS){
			if(ipText!=null)
				ipText.setEnabled(false);
			if(userNameText!=null)
				userNameText.setEnabled(false);
			if(passwordText!=null)
				passwordText.setEnabled(false);
		}else{
			if(ipText!=null)
				ipText.setEnabled(true);
			if(userNameText!=null)
				userNameText.setEnabled(true);
			if(passwordText!=null)
				passwordText.setEnabled(true);
		}
	}

	public boolean canFlipToNextPage(){
		return flag;
	}

	public Text getUserNameText() {
		return userNameText;
	}

	public void setUserNameText(Text userNameText) {
		this.userNameText = userNameText;
	}

	public Text getPasswordText() {
		return passwordText;
	}

	public void setPasswordText(Text passwordText) {
		this.passwordText = passwordText;
	}

	class ServiceNotOpenDialog extends Dialog
	{
		private Label infoLabel;
		private Label errorLabel;
		private CLabel imageCLabel;

		private String infoMsg = "";
		private String errorMsg = "";

		private static final int CLOSE_ID = 0;
		private static final String CLOSE_LABEL = "Close";
		protected ServiceNotOpenDialog(Shell parentShell,String infoMsg, String errorMsg) {
			super(parentShell);

			this.infoMsg = infoMsg;
			this.errorMsg = errorMsg;

		}

		protected Control createDialogArea(Composite parent)
		{
			Composite composite = (Composite)super.createDialogArea(parent);
			GridLayout layout = new GridLayout(2,true);
			layout.verticalSpacing = 22;
			layout.horizontalSpacing = 15;
			layout.makeColumnsEqualWidth = false;
			composite.setLayout(layout);
			imageCLabel = new CLabel(composite, SWT.NONE);
			imageCLabel.setImage(ImageRegistry.getImage(ImageRegistry.SERVICENOTOPEN));
			GridData imgData = new GridData();
			imgData.verticalSpan = 2;
			imageCLabel.setLayoutData(imgData);

			infoLabel = new Label(composite, SWT.NONE);
			infoLabel.setText(infoMsg);

			errorLabel = new Label(composite, SWT.NONE);
			errorLabel.setText(errorMsg);

			return parent;
		}

		protected void createButtonsForButtonBar(Composite parent)
		{
			createButton(parent,ServiceNotOpenDialog.CLOSE_ID,ServiceNotOpenDialog.CLOSE_LABEL,true);
		}

		protected void buttonPressed(int buttonId)
		{
			if(ServiceNotOpenDialog.CLOSE_ID == buttonId)
				close();
		}
	}
}


text:
layout: post
title: Image operationes
tags:
- Python Study
---
Image operation cases: 1.Add text to image; 2.Resize multiple images.

### Case 1: Add  a number on the picture
Question:
Put a red number on the upper right corner of your profile picture, similar to the effect of numbers of unread messages.

Steps:

* Get the path and name of image.

Here I use sys.argv() to get the path and name of the image.

```python
import sys

if __name__ == '__main__':
    add_number(sys.argv[1])
```
Remember that sys.argv[0] is the name of the script. sys.argv[1] is what I needed

* Get the path of image

I use a regular expression to describe then path, then save it into "path" viable.

```python
pattern = re.compile('(.*\/).*')
    path = re.findall(pattern,path_file)[0]

'''The idea is to capture all the content to the last slash by using (.*\/)
and discard the rest .*. '''

```

* Add a text to image

PIL have a methode as below:

```python
ImageDraw.Draw.text(xy, text, fill=None, font=None, anchor=None)
```
We need to find a font for our text.
It takes me a while to find a useable font file in my Macbook.

```
/System/Library/Fonts/Apple Symbols.ttf

```

#### Here is the complete code:

```python
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
import sys
import re

def add_number(path_file):
    '''
    Get a file with its path as arguments of function "add_number",
     use draw.txt to add a txt on to the image,
     and save the new image to the same location.
     '''
    im = Image.open(path_file)

    pattern = re.compile('(.*\/).*')
    path = re.findall(pattern,path_file)[0]
    # get a jpeg file
    font = ImageFont.truetype('/System/Library/Fonts/Apple Symbols.ttf', 50)
    #get a font type file,and size
    draw = ImageDraw.Draw(im)
    #get a draw object
    w,h = im.size
    draw.text((w-50,0), "8", (255,0,0), font=font)
    # locate "8" at right-up corner
    im.save((path+"add number.jpeg"), "jpeg")

if __name__ == '__main__':
    add_number(sys.argv[1])
```

The result looks like this:

![test](https://github.com/JingQin-JQ/learning-python/blob/master/one-code-per-day/add%20number.jpeg?raw=true)

### Case 2: Resize all pictures in a folder
Question:
There is a folder, have a lot of photos, resize them into no more than the size of iPhone5 resolution.

Steps:

  * What does iPhone5 resolution means?

 640*1136 pixel (or smaller)

  * How to keep the original width/height ratio of pictures when resize them.

    * We don't need to resize it if the picture is smaller than 640*1136.
    * Because we also don't want to change the width/height ratio of pictures. So we need to resize according to the bigger diffrence between height and width.

  ```python
  rate = max(img.size[0]/640.0 if img.size[0] > 640 else 0, img.size[1]/1136.0 if img.size[1] > 1136 else 0)
  ```

 * Get all image files from a folder

 We defined a function called "run" to use os.walk to go through all the path of given folder, and get all image fils for function "process_image" to resize.

 ```python
 def run(directory): #get all pictures from folder
    '''
    Get "directory" as arguments of function "run",
     find all image file which have their type in "img_types" ,
     call function "process_image" to resize them.
     '''
    img_types = ['.png','.jpeg','.bmp','.JPG']
    for root, dirs, files in os.walk(directory):
        for name in files:
            if os.path.splitext(name)[1] in img_types:
                img_file = img.open(directory+"/" + name)
                process_image(img_file,os.path.splitext(name),directory)
 ```

 * Resize all pictures and save them

 Function "process_image" takes image them selves, their names and their pathes as prameters, resize images by using "thumbnail ", then save them.

#### Here is the complete code:

```python
from PIL import Image as img
import os
import os.path
import sys

def run(directory): #get all pictures from folder
    '''
    Get "directory" as arguments of function "run",
     find all image file which have their type in "img_types" ,
     call function "process_image" to resize them.
     '''
    img_types = ['.png','.jpeg','.bmp','.JPG']
    for root, dirs, files in os.walk(directory):
        for name in files:
            if os.path.splitext(name)[1] in img_types:
                img_file = img.open(directory+"/" + name)
                process_image(img_file,os.path.splitext(name),directory)

def process_image(img,name,directory): # resize pics to 640*1136(or smaller)
    '''
    Get "img", "name"and "directory" as arguments of function "process_image",
     resize images to 640*1136 or smaller, and keep their own w/h ratio.
     save new images to the same directory with "_resize" added to their old name.
     '''
    img_w,img_h = img.size
    rate = max(img_w/640.0 if img_w > 640 else 0, img_h/1136.0 if img_h > 1136 else 0)
    # get a rate for resize
    if rate:
        img.thumbnail((img_w/rate, img_h/rate))
    img.save(directory+ name[0]+"_resize"+".jpeg", "jpeg")

if __name__ == '__main__':
    run(sys.argv[1])
```


text:
bucharest-lister
================

Perl 6 bindings for Kyoto Cabinet