Example #1
0
	private : void ruleDeleteFirst(string & word) {
		word.erase(0,1);
	}
Example #2
0
        /**
        * Determine linux distro and version
        */
        static void getLinuxDistro( string& name, string& version ) {
            char buf[4096] = { 0 };

            // try lsb file first
            if ( boost::filesystem::exists( "/etc/lsb-release" ) ) {
                File f;
                f.open( "/etc/lsb-release", true );
                if ( ! f.is_open() || f.bad() )
                    return;
                f.read( 0, buf, f.len() > 4095 ? 4095 : f.len() );

                // find the distribution name and version in the contents.
                // format:  KEY=VAL\n
                string contents = buf;
                unsigned lineCnt = 0;
                try {
                    while ( lineCnt < contents.length() - 1 && contents.substr( lineCnt ).find( '\n' ) != string::npos ) {
                        // until we hit the last newline or eof
                        string line = contents.substr( lineCnt, contents.substr( lineCnt ).find( '\n' ) );
                        lineCnt += contents.substr( lineCnt ).find( '\n' ) + 1;
                        size_t delim = line.find( '=' );
                        string key = line.substr( 0, delim );
                        string val = line.substr( delim + 1 );  // 0-based offset of delim
                        if ( key.compare( "DISTRIB_ID" ) == 0 )
                            name = val;
                        if ( string(key).compare( "DISTRIB_RELEASE" ) == 0 )
                            version = val;
                    }
                }
                catch (const std::out_of_range &e) {
                    // attempted to get invalid substr
                }
                // return with lsb-release data if we found both the name and version
                if ( !name.empty() && !version.empty() ) {
                    return;
                }
            }

            // try known flat-text file locations
            // format: Slackware-x86_64 13.0, Red Hat Enterprise Linux Server release 5.6 (Tikanga), etc.
            typedef vector <string> pathvec;
            pathvec paths;
            pathvec::const_iterator i;
            bool found = false;
            paths.push_back( "/etc/system-release" );
            paths.push_back( "/etc/redhat-release" );
            paths.push_back( "/etc/gentoo-release" );
            paths.push_back( "/etc/novell-release" );
            paths.push_back( "/etc/gentoo-release" );
            paths.push_back( "/etc/SuSE-release" );
            paths.push_back( "/etc/SUSE-release" );
            paths.push_back( "/etc/sles-release" );
            paths.push_back( "/etc/debian_release" );
            paths.push_back( "/etc/slackware-version" );
            paths.push_back( "/etc/centos-release" );
        
            for ( i = paths.begin(); i != paths.end(); ++i ) {
                // for each path
                if ( boost::filesystem::exists( *i ) ) {
                    // if the file exists, break
                    found = true;
                    break;
                }
            }

            if ( found ) {
                // found a file
                File f;
                f.open( i->c_str(), true );
                if ( ! f.is_open() || f.bad() )
                    // file exists but can't be opened
                    return;

                // read up to 512 bytes
                int len = f.len() > 512 ? 512 : f.len();
                f.read( 0, buf, len );
                buf[ len ] = '\0';
                name = buf;
                size_t nl = 0;
                if ( ( nl = name.find( '\n', nl ) ) != string::npos )
                    // stop at first newline
                    name.erase( nl );
                // no standard format for name and version.  use kernel version
                version = "Kernel ";
                version += LinuxSysHelper::readLineFromFile("/proc/sys/kernel/osrelease");
            }
        }
Example #3
0
  bool handleInput() 
  {
    if (VLOG_IS_ON(10) || paused) 
      key = waitKey(0);
    else 
      key = waitKey(30);

    if (key < 0) return true;

    valid_key = true;
    if( key == 'q' ) {
      return false;
    }
    // TBD look for /, then make next letters type search for nodes with names container the following string
    else if (key == 'x' ) {
      paused = !paused;
    }
    else if( key == 'e' ) {
      // TBD follow with file name
      // TBD load the graph in a temp object, then copy it over only if successful
      LOG(INFO) << "reloading graph file";
      clearNodes();
      loadGraph(FLAGS_graph_file);
    }
    else if( key == 'w' ) {
      // TBD increment a count so old saves aren't overwritten?
      saveGraph("temp_graph.yml");
    }
    else if (key == 'a') {
      gridGraph();
    }
    else if (key == 'z') {
      draw_nodes = !draw_nodes;
    }
    else if (key == 's') {
      if (selected_node)
        // TBD make node function to do this without exposing setSignal 
        selected_node->setSignal("enable",  !((bool)selected_node->getSignal("enable")));
    }
    
    // Connection manipulation
    else if (key == 'h') {
      if (source_node) {
        selected_node = source_node;
        selected_ind = source_ind;
        // TBD saw with selected_node?
      }
    }
    else if (key == 'j') {
      selectNextNode();
    }
    else if (key == 'k') {
      selectPrevNode();
    }
    else if (key == 'u') {
      // TBD the node should catch this itself
      selectPort();
      
      stringstream str;
      if (selected_node) {
        str << selected_node->name << " : ";
        str << "matching " << source_type << " \"" << source_port << "\" with ";
      } else {
        str <<"selecting";
      }
      
      str 
          << selected_type << " \"" << selected_port << "\" "
          << CLTXT 
          << selected_ind << " " << selected_port_ind << " " 
          << CLNRM;
      VLOG(1) << str.str();
    } 
    else if (key == 'r') {
      selectSourceNode();
    } 
    else if (key == 't') {
      selectTargetNode();
    } // set source_node to target input
    else if (key == 'd') {
      removePortConnection();
    }
    //////////////////////////////////////////////////
    // following may not be portable
    else if (key == 65362) {  // UP
      selectNodeDirection(-2); 
    } else if (key == 65364) {  // DOWN
      selectNodeDirection(2); 
    } else if (key == 65361) {  // LEFT
      selectNodeDirection(-1); 
    } else if (key == 65363) {  // RIGHT
      selectNodeDirection(1); 
      
    
    //else if (key == 'c') {
      // swap selected node input with source node input- TBD this doesn't work since  
      // outputs can be one-to-many
    //}
    } else {
      valid_key = false;
      // see if node can work with the key
      if (selected_node) 
        valid_key = selected_node->handleKey(key);
    }

    if (valid_key) {
      stringstream tmp;
      tmp << (char) key;
      //tmp.resize(1);
      //tmp[0] = key;
      command_text.append(tmp.str());
      VLOG(4) << tmp.str() << " " << command_text;
    } else if (key >= 0) {
      LOG(INFO) << "unused keypress:" << (char)key << " " << key;
    }

    int max_count = 24;
    if (command_text.size() > 40) max_count /= 2;
    if (command_text.size() > 80) max_count /= 2;
    if (command_text.size() > 160) max_count = 1;
    if (count % max_count == 0) {
      if (command_text.size() > 0);
      command_text = command_text.erase(0,1);
    } else {
      //command_text = "";
    }

    return true;
  }
Example #4
0
void SDeleteN (string &s, unsigned int pos, int count) {
	if (pos > s.size()) pos = s.size();
	s.erase (pos, count);
}
 void strip(string& s) {
     int size_n=s.size();
     for (int i=0;i<size_n;i++) 
         if (s[size_n-i-1]==' ') s.erase(size_n-i-1,1);
     }
int parser::parseUserToken(string& str) {
    regex_t re;
    size_t     nmatch = 3;
    regmatch_t pmatch[3];

    char *pattern = "^[ \t]*([^ \t]+)[ \t]*=[ \t]*([^ \t]+)[ \t]*;[ \t]*";
    if(regcomp(&re, pattern, REG_EXTENDED) != 0) {
       cerr << "Error: Can't Parse Token at \n" << str << endl;
       exit(1);
    }
    int status = regexec(&re, str.c_str(), nmatch, pmatch, 0);
    regfree(&re);

    if(status!=0) {
        cerr << "Error: Can't Parse Token at \n" << str << endl;
        exit(1);
    }
    string token = str.substr(pmatch[1].rm_so, pmatch[1].rm_eo - pmatch[1].rm_so);
    string value = str.substr(pmatch[2].rm_so, pmatch[2].rm_eo - pmatch[2].rm_so);
    int ivalue = atoi(value.c_str());
    float fvalue = atof(value.c_str());
    if(token == "technology") {
        input_handle.setTech(value);
    } else if (token == "memSize") {
        input_handle.setMemSize(ivalue);
    } else if (token ==  "rows") {
        input_handle.setNRows(ivalue);
    } else if (token ==  "banks" ) {
        input_handle.setNBanks(ivalue);
    } else if (token ==  "colMux") {
        input_handle.setNColMux(ivalue);
    } else if (token ==  "wordSize") {
        input_handle.setWordSize(ivalue);
    } else if (token ==  "SAoffset") {
        input_handle.setSAOffset(fvalue);
    } else if (token ==  "height") {
        input_handle.setBCHeight(fvalue);
    } else if (token ==  "width") {
        input_handle.setBCWidth(fvalue);
    } else if (token ==  "energyConstraint" ) {
        input_handle.setENConstraint(fvalue);
    } else if (token ==  "delayConstraint") {
        input_handle.setDLConstraint(fvalue);
    } else if (token ==  "wnio") {
        input_handle.setWDWidth(ivalue);
    } else if (token ==  "tasePath" ) {
        input_handle.setTASEPath(value);
    } else if (token ==  "temp" ) {
        input_handle.setTemp(fvalue);
    } else if (token ==  "vdd" ) {
        input_handle.setVdd(fvalue);
    } else if (token ==  "WLBoost" ) {
        input_handle.setWLBoost(fvalue);
    } else if (token ==  "WLoffset" ) {
        input_handle.setWLOffset(fvalue);
    } else {
        cerr << "Error: Can't Parse Token at \n" << str << endl;
        exit(1);
    }
    str.erase(pmatch[0].rm_so, pmatch[0].rm_eo - pmatch[0].rm_so);
}
Example #7
0
void Config::ParseParamValues(const string& name, string& value)
{
  // erase equal sign if present
  int eqIdx = value.find_first_not_of(" \t=");
  if (eqIdx != string::npos) {
    value.erase(0, eqIdx);
  }

  if (name == "frequency") {
    Freq(StrToDouble(value));
  }
  else if (name == "mcFrequency") {
    McFreq(StrToDouble(value));
  }
  else if (name == "gMeshDimX") {
    ValueParser::GetVectorOfIValues(value, gMeshDimX_);
  }
  else if (name == "gMeshDimY") {
    ValueParser::GetVectorOfIValues(value, gMeshDimY_);
  }
  else if (name == "clusterIcType") {
    ValueParser::GetVectorOfValues(value, clusterIcType_);
  }
  else if (name == "maxArea") {
    MaxArea(StrToDouble(value));
  }
  else if (name == "processor") {
    string pName;
    double area, freq, epi, pleak;
    int ooo;
    ValueParser::ExtractValue(value, pName);
    ValueParser::ExtractValue(value, area);
    ValueParser::ExtractValue(value, ooo);
    ValueParser::ExtractValue(value, freq);
    ValueParser::ExtractValue(value, epi);
    ValueParser::ExtractValue(value, pleak);

    // read L1 and L2 sizes
    vector<double> l1Size, l2Size;
    LStrip(value);
    value.erase(0, value.find('=')+1);
    string l1val = value.substr(0, value.find('l'));
    ValueParser::GetVectorOfValues(l1val, l1Size);
    value.erase(0, value.find('=')+1);
    ValueParser::GetVectorOfValues(value, l2Size);

    AddProc(pName, area, ooo, freq, epi, pleak, l1Size, l2Size);
  }
  else if (name == "maxProcAreaPerCluster") {
    double val = StrToDouble(value);
    if (val > 1.0) {
      cout << "-W- maxProcAreaPerCluster adjusted to 1.0" << endl;
      val = 1.0;
    }
    else if (val < 0.1) {
      cout << "-W- maxProcAreaPerCluster adjusted to 0.1" << endl;
      val = 0.1;
    }
    MaxProcAreaPerCluster(val);
  }
  else if (name == "numL3PerCluster") {
    numL3PerCluster_.clear();
    ValueParser::GetVectorOfIValues(value, numL3PerCluster_);
  }
  else if (name == "memDensity") {
    MemDensity(StrToDouble(value));
  }
  else if (name == "wlFile") {
    WlFile(value);
  }
  else if (name == "l3LatencyOfSize") {
    l3LatencyOfSize_ = Function::ParseFunction(value);
  }
  else if (name == "l3ShareDegreeOfPNum") {
    l3ShareDegreeOfPNum_ = Function::ParseFunction(value);
  }
  else if (name == "busTimeOfClusterArea") {
    busTimeOfClusterArea_ = Function::ParseFunction(value);
  }
  else if (name == "meshLinkDelayOfClusterArea") {
    meshLinkDelayOfClusterArea_ = Function::ParseFunction(value);
  }
  else if (name == "xbarDelayOfClusterArea") {
    xbarDelayOfClusterArea_ = Function::ParseFunction(value);
  }
  else if (name == "missRatioOfMemSize") {
    missRatioOfMemSize_ = Function::ParseFunction(value);
  }
  else if (name == "l3AccessEnergyOfSize") {
    l3AccessEnergyOfSize_ = Function::ParseFunction(value);
  }
  else if (name == "l3LeakagePowerOfSize") {
    l3LeakagePowerOfSize_ = Function::ParseFunction(value);
  }
  else if (name == "memCtrlAccessEnergy") {
    MemCtrlAccessEnergy(StrToDouble(value));
  }
  else if (name == "memCtrlLeakagePower") {
    MemCtrlLeakagePower(StrToDouble(value));
  }
  else if (name == "linkWidth") {
    linkWidth_ = StrToInt(value);
  }
  else {
    cerr << "-W- Unknown parameter: " << name << endl;
  }
}
Example #8
0
	string GetTrim(string strText)//去字符串两侧空格
	{
		strText.erase(0,strText.find_first_not_of(""));//删除左空格
		strText.erase(0,strText.find_last_not_of("")+1);//删除右空格
		return strText;
	}
Example #9
0
string RemoveTrailingNewlines(string str) {
    while(!str.empty() && str.at(str.length()-1) == '\n') {
        str.erase(str.length()-1);
    }
    return str;
}
Example #10
0
double Parser::parse(string &wyrazenie)
{
//-------------------------------------------------------------------------

    int pos;
    bool ifA3 = false;
    bool ifB3 = false;
    bool ifC3 = false;
    bool ifD3 = false;
    bool ifE3 = false;



   if(wyrazenie[0]=='-')
            wyrazenie.insert(0,"0");
    else if(wyrazenie[0] == '.')
        wyrazenie.insert(0,"0");



    for (unsigned int i = 0; i < wyrazenie.length() - 1; ++i)
    {

       if(ifSpacja(wyrazenie[i]))
       {
            wyrazenie.erase(i,1);
            parse(wyrazenie);
       }
       if (ifCyfra(wyrazenie[i]) && ifLewyNaw(wyrazenie[i+1]))
            wyrazenie.insert(i+1, "*");

        else if (ifPrawyNaw(wyrazenie[i]) && (wyrazenie[i+1]=='.' || ifLewyNaw(wyrazenie[i+1])))
            wyrazenie.insert(i+1, "*");




	    else if(ifLewyNaw(wyrazenie[i]) && wyrazenie[i+1] == '-' )
            wyrazenie.insert(i+1,"0");
        else if(!ifCyfra(wyrazenie[i]) && wyrazenie[i+1] == '.' )
            wyrazenie.insert(i+1,"0");
    }


     while((pos=wyrazenie.find("pi")) != -1)
     {
         wyrazenie.replace(pos, 2,PI);
     }
     while((pos=wyrazenie.find("e")) != -1)
     {
         wyrazenie.replace(pos, 2,e);
     }

     if((pos=wyrazenie.find("=")) == 1)
     {

         if((pos=wyrazenie.find("a")) == 0)
         {
            ifA3=true;
            wyrazenie.erase(0,2);
         }
         else if((pos=wyrazenie.find("b")) == 0)
         {
             ifB3=true;
             wyrazenie.erase(0,2);
         }
         else if((pos=wyrazenie.find("c")) == 0)
         {
             ifC3=true;
             wyrazenie.erase(0,2);
         }
         else if((pos=wyrazenie.find("d")) == 0)
         {
             ifD3=true;
             wyrazenie.erase(0,2);
         }
         else if((pos=wyrazenie.find("f")) == 0)
         {
             ifE3=true;
             wyrazenie.erase(0,2);
         }

     }

    else
    {


        while ((pos=wyrazenie.find("a")) != -1)
        {

            wyrazenie.replace(pos, 1,a1);

        }

        while ((pos=wyrazenie.find("b")) != -1)
        {

            wyrazenie.replace(pos, 1,b1);

        }

        while ((pos=wyrazenie.find("c")) != -1)
        {

            wyrazenie.replace(pos, 1,c1);
        }

        while ((pos=wyrazenie.find("d")) != -1)
        {

            wyrazenie.replace(pos, 1,d1);
        }

        while ((pos=wyrazenie.find("f")) != -1)
        {

            wyrazenie.replace(pos, 1,e1);
        }
    }



    Stack<char> S;
    string wynik;
    unsigned int i2 = 0;


    while (i2 < wyrazenie.length())
    {
        char c = wyrazenie[i2++];

//wczytywanie cyfry

	   if (ifCyfra(c))
        {

            string n(1, c);
            while (ifCyfra(c = wyrazenie[i2]) || (c=='.'))
            {
                n += c;
                ++i2;
            }

            wynik += n;
            wynik += ' ';
        }




	    else if (ifOper(c))
        {

            if (ifPrior1(c))
            {
                while (!S.empty() && (ifPrior1(S.top()) || ifPrior2(S.top()) || ifPrior3(S.top())))
                {
                    wynik += S.top();
                    wynik += ' ';
                    S.pop();
                }
            }
            if (ifPrior2(c))
            {
                while (!S.empty() && (ifPrior2(S.top()) || ifPrior3(S.top())))
                {
                    wynik += S.top();
                    wynik += ' ';
                    S.pop();
                }
            }
            if (ifPrior3(c))
            {
                while (!S.empty() && ( ifPrior3(S.top())))
                {
                    wynik += S.top();
                    wynik += ' ';
                    S.pop();
                }
            }

            S.push_back(c);
        }



	    else if (ifSpacja(c))
        {

        }




	    else if (ifLewyNaw(c))
        {

            S.push_back(c);
        }
        else if (ifPrawyNaw(c))
        {

            while (!S.empty() && !ifLewyNaw(S.top()))
            {
                wynik += S.top();
                wynik += ' ';
                S.pop();
            }

            S.pop();

        }




	    else
        {

            cout<<"Niepoprawny znak\n"<<endl;

        }
    }



    while (!S.empty())
    {
        wynik += S.top();
        wynik += ' ';
        S.pop();
    }

//-------------------------------------------------------------------------

    string ONP=wynik;



    Stack <double> S1;
    unsigned i3 = 0;
    char c;
    while (i3 < ONP.length())
    {
        c = ONP[i3++];



        if (ifCyfra(c) || c=='.')
        {
            double v = c - '0';
            while (ifCyfra(c = ONP[i3]))
            {
                v *= 10;
                v += c - '0';
                i3++;
            }



		    if((c=ONP[i3++]) == '.')
            {
                double j=10;
                while (ifCyfra(c = ONP[i3]))
                {
                    v+=(c-'0')/(j);
                    j*=10;
                    i3++;
                }
            }

            S1.push_back(v);
        }



        else if (ifOper(c))
        {
            double a = S1.top(); S1.pop();
            double b = S1.top(); S1.pop();

            switch (c)
            {
            case '+':
                S1.push_back(b + a);
                break;
            case '-':
                S1.push_back(b - a);
                break;
            case '*':
                S1.push_back(b * a);
                break;
            case '/':
                S1.push_back(b / a);
                break;
            case '^':
                S1.push_back(pow(b, a));
                break;
            }
        }




	    else if (ifSpacja(c))
        {

        }




		else
        {
            //throw string("Niepoprawny znak!\n");
            cout<<"Niepoprawny znak\n"<<endl;
            break;
        }
    }

   if(ifA3)
   {

      stringstream ss;

      ss << S1.top();
      a1 = ss.str();

   }
   else if(ifB3)
   {
       stringstream ss;
      ss << S1.top();
      b1 = ss.str();
   }
   else if(ifC3)
   {
      stringstream ss;
      ss << S1.top();
      c1 = ss.str();
   }
   else if(ifD3)
   {
       stringstream ss;
      ss << S1.top();
      d1 = ss.str();
   }
   else if(ifE3)
   {
       stringstream ss;
      ss << S1.top();
      e1 = ss.str();
   }


   return S1.top();

//-------------------------------------------------------------------------
}
Example #11
0
void set(string date){
	for(int i = 0;i<date.size();i++){ // ตัดช่องว่างออก
		if(date[i] == ' ') date.erase(i,1);
	}
	setcache = date; // เอาวันที่ไปเก็บไว้
}
Example #12
0
	private : void ruleDeleteRange(string & word, char startpos, char length) {
		if (atoi( &startpos )+atoi( &length ) > word.size()) return;
		word.erase(atoi( &startpos ), atoi( &length ));
	}
Example #13
0
	private : void ruleDeleteN(string & word, char pos) {
		if (atoi( &pos ) > word.size()) return;
		word.erase(atoi( &pos ), 1);
	}
Example #14
0
	private : void ruleDeleteLast(string & word) {
		word.erase(word.size()-1,1);
	}
Example #15
0
// This function does not use cURL.
// It is a very simple function that sends a HTTP GET or POST request and reads the response.
// It runs on devices without libcurl.
// $url: The URL including host / port / path.
// $error: To store any error messages.
// $post: Value pairs for a POST request.
// $filename: The filename to store the data to.
// $verbose: Print headers and data to standard out.
string filter_url_simple_http_request (string url, string& error, const map <string, string>& post, const string& filename, bool verbose)
{
  // The "http" scheme is used to locate network resources via the HTTP protocol.
  // http_URL = "http:" "//" host [ ":" port ] [ abs_path [ "?" query ]]
  // If the port is empty or not given, port 80 is assumed.
  
  // Remove the scheme.
  size_t pos = url.find ("://");
  if (pos == string::npos) {
    error = "Unknown protocol";
    return "";
  }
  url.erase (0, pos + 3);

  // Extract the host.
  pos = url.find (":");
  if (pos == string::npos) pos = url.find ("/");
  if (pos == string::npos) pos = url.length () + 1;
  string hostname = url.substr (0, pos);
  url.erase (0, hostname.length ());

  // Extract the port number.
  int port = 80;
  pos = url.find (":");
  if (pos != string::npos) {
    url.erase (0, 1);
    size_t pos2 = url.find ("/");
    if (pos2 == string::npos) pos2 = url.length () + 1;
    string p = url.substr (0, pos2);
    port = convert_to_int (p);
    url.erase (0, p.length ());
  }
  
  // The absolute path plus optional query remain after extracting the preceding stuff.

  // Resolve the host.
  struct hostent * host = gethostbyname (hostname.c_str());
  if ( (host == NULL) || (host->h_addr == NULL) ) {
    error = hostname + ": ";
    error.append (hstrerror (h_errno));
    return "";
  }
  
  // Socket setup.
  struct sockaddr_in client;
  bzero (&client, sizeof (client));
  client.sin_family = AF_INET;
  client.sin_port = htons (port);
  memcpy (&client.sin_addr, host->h_addr, host->h_length);
  int sock = socket (AF_INET, SOCK_STREAM, 0);
  if (sock < 0) {
    error = "Creating socket: ";
    error.append (strerror (errno));
    return "";
  }

  // Because a Bibledit client should work even over very bad networks, set a timeout on the socket.
  struct timeval tv;
  tv.tv_sec = 30;  // Timeout in seconds.
  setsockopt (sock, SOL_SOCKET, SO_RCVTIMEO, (struct timeval *)&tv, sizeof(struct timeval));
  setsockopt (sock, SOL_SOCKET, SO_SNDTIMEO, (struct timeval *)&tv, sizeof(struct timeval));
  
  // Connect to the host.
  if (connect (sock, (struct sockaddr *)&client, sizeof (client)) < 0 ) {
    error = "Connecting to " + hostname + ": ";
    error.append (strerror (errno));
    close (sock);
    return "";
  }

  // Assemble the data to POST, if any.
  string postdata;
  for (auto & element : post) {
    if (!postdata.empty ()) postdata.append ("&");
    postdata.append (element.first);
    postdata.append ("=");
    postdata.append (filter_url_urlencode (element.second));
  }

  // Send the request.
  string request = "GET";
  if (!post.empty ()) request = "POST";
  request.append (" ");
  request.append (url);
  request.append (" ");
  request.append ("HTTP/1.1");
  request.append ("\r\n");
  request.append ("Host: ");
  request.append (hostname);
  request.append ("\r\n");
  //request.append ("Connection: close");
  //request.append ("\r\n");
  if (!post.empty ()) {
    request.append ("Content-Type: application/x-www-form-urlencoded");
    request.append ("\r\n");
    request.append ("Content-Length: " + convert_to_string (postdata.length()));
    request.append ("\r\n");
  }
  request.append ("\r\n");
  request.append (postdata);
  if (verbose) cout << request << endl;
  if (send (sock, request.c_str(), request.length(), 0) != (int) request.length ()) {
    error = "Sending request: ";
    error.append (strerror (errno));
    close (sock);
    return "";
  }

  // Read the response headers and body.
  string headers;
  string response;
  bool reading_body = false;
  char prev = 0;
  char cur;
  FILE * file = NULL;
  if (!filename.empty ()) file = fopen (filename.c_str(), "w");
  while (int result = read (sock, &cur, 1) > 0 ) {
    if (reading_body) {
      if (file) fwrite (&cur, 1, 1, file);
      else response += cur;
    } else {
      if (cur == '\r') continue;
      headers += cur;
      if ((cur == '\n') && (prev == '\n')) reading_body = true;
      prev = cur;
    }
    if (result < 0) {
      error = "Receiving: ";
      error.append (strerror (errno));
      close (sock);
      if (file) fclose (file);
      return "";
    }
  }
  close (sock);
  if (file) fclose (file);
  if (verbose) {
    cout << headers << endl;
    cout << response << endl;
  }

  // Check the response headers.
  vector <string> lines = filter_string_explode (headers, '\n');
  for (auto & line : lines) {
    if (line.empty ()) continue;
    if (line.find ("HTTP") != string::npos) {
      size_t pos = line.find (" ");
      if (pos != string::npos) {
        line.erase (0, pos + 1);
        int response_code = convert_to_int (line);
        if (response_code != 200) {
          error = "Response code: " + line;
          return "";
        }
      } else {
        error = "Invalid response: " + line;
        return "";
      }
    }
  }
  
  // Done.
  return response;
}
Example #16
0
string UMINIFY::Uminify(string filename)
{
	_filename = filename;
	//reading file into vector one string at a time
	ifstream readfile(filename.c_str());  //change filename here to your file's name
	
	//checking if file exist
	readfile >> temp;
	if(temp.empty()) return "File doesn't exist or is empty...\n";
	
	//file exist
	file.push_back(temp);
	while(readfile >> temp) file.push_back(temp);
	
	//looping through vector file
	
	for(unsigned int i=0;i<file.size();i++)  //start of loop
	{
		if(file[i] == "#include")
		{
			headers.push_back(file[i]);
			headers.push_back(file[i+1]);
			i++;
			continue;
		}
		
		//checking if string file[i] is a quote
		if(file[i][0] == '"' || file[i][file[i].size()-1] == '"') quote = true;
		else quote = false;
		
		//checking if string file[i] is a for loop due to the semicolons involved
		if(file[i][0] == 'f' && file[i][1] == 'o' && file[i][2] == 'r' && file[i][3] == '(') loop = true;  //when loop is true, newline after ; is disabled
		
		if(file[i] == "{")
		{
			write =  write + "\n" + index(tab) + file[i] + "\n";
			index_flag = true; //tab next item going to write
			tab++;  //adds tab
			continue;
		} 
		
		else if(file[i] == "}")
		{
			tab--; //removes tab
			index_flag = true;  //tab next item going to write
			write = write + index(tab) + file[i] + "\n";
			continue;
		}
		
		if((file[i][file[i].size()-1] == ';' && !loop) || (file[i][file[i].size()-1] == ':' && !quote))   //test if ; is for and if : is in a quote 
		{
			//writes with space and continues
			if(index_flag) write = write + index(tab) + file[i] + "\n";
			else 
			{
				write = write + file[i] + "\n";
				index_flag = true; //same as above
			}
			continue;
		}
		else if(loop)  //if a for loop
		{
			if(file[i][file[i].size()-1] == ')') //locates if end of loop
			{
				write = write + file[i];
				loop = false; //no longer a loop
			}
			else if(index_flag) 
			{
				write = write + index(tab) + file[i] + " ";
				index_flag = false; //same as above
			}
			else write = write + file[i] + " ";
			continue;
		}
		
		if(index_flag)  //if tab output
		{
			write = write + index(tab) + file[i] + " ";
			index_flag = false;
		}
		else write = write + file[i] + " ";
	} //loop ends
	
	temp.erase();
	temp += "~~~~~ Uminify ~~~~~~~~\n";
	temp += "~~~~~ (c/c++) ~~~~~~~~\n";
	temp += "~~~~~_________~~~~~~~~\n";
	temp += "By: Sh3rlock W1sd0m\n";
	return temp;
}
int parser::parseKNOBS(string& str) {
    while(!str.empty()) {
        regex_t re;
        size_t nmatch = 6;
        regmatch_t pmatch[6];
        // Modify to check for numbers
        char *pattern = "^[ \t]*([^ \t]+)[ \t]*([0-9]+(\\.[0-9]+)?)?[ \t]*([0-9]+(\\.[0-9]+)?)?[ \t]*";
        regcomp(&re, pattern, REG_EXTENDED);
        int status = regexec(&re, str.c_str(), nmatch, pmatch, 0);
        regfree(&re);
        if(status != 0) {
            cerr << "Error: Can't Parse OPTIMIZE Token" << endl;
            exit(1);
        }
        if(
            (pmatch[2].rm_so == -1 && pmatch[4].rm_so != -1)
        ||  (pmatch[4].rm_so == -1 && pmatch[2].rm_so != -1)
          )
        {
            cerr << "Error: Can't Parse OPTIMIZE Token." << endl;
            cerr << "Format: OPTIMIZE KNOBS KONB1 [MIN MAX] KNOB2 [MIN MAX] .." << endl;
            exit(1);
        }
        // store min max
        int count = input_handle.knobCount++;
        input_handle.knobMin[count] = -1;
        input_handle.knobMax[count] = -1;
        input_handle.knobName[count] = str.substr(pmatch[1].rm_so, pmatch[1].rm_eo - pmatch[1].rm_so);
        if(pmatch[2].rm_so != -1) {
            input_handle.knobMin[count] = atof((str.substr(pmatch[2].rm_so, pmatch[2].rm_eo - pmatch[2].rm_so)).c_str());
            input_handle.knobMax[count] = atof((str.substr(pmatch[4].rm_so, pmatch[4].rm_eo - pmatch[4].rm_so)).c_str());
            #ifdef DEBUG
            cout << "knob = " << input_handle.knobName[count] << " min = " << input_handle.knobMin[count] << " max = " << input_handle.knobMax[count] << endl;
            #endif
        }
        str.erase(pmatch[0].rm_so, pmatch[0].rm_eo - pmatch[0].rm_so);

        // Error if Min > Max
        float min = input_handle.knobMin[count];
        float max = input_handle.knobMax[count];
        if(min > max)
          cerr << "Maximum value of " << input_handle.knobName[count] << " is greater than its minimum value." << endl;

        // Limit the value of bank, rows, col
        if(input_handle.knobName[count] == "NBANKS") {
            if(max > 32 || min < 1) {
              cerr << "Number of banks should be between 1 and 32" << endl;;
              exit(1);
            }
        } else if (input_handle.knobName[count] == "NCOLS") {
            if(max > 32 || min < 1) {
              cerr << "Number of columns should be between 1 and 32" << endl;;
              exit(1);
            }
        } else if (input_handle.knobName[count] == "NROWS") {
            if(max > 512 || min < 32) {
              cerr << "Number of rows should be between 32 and 512" << endl;;
              exit(1);
            }
        }
    }
    return 0;
}
Example #18
0
void XmlParser::attributeFinder(string tempToken, stack<XmlNode *> &nodeStack, int &nodePtr, size_t &posSpace, string delim)
{
	Logger::printDebugLog("Strated looking for attributes");
	string nodeName = tempToken.substr(1, posSpace - 1); //0th element should be <
	size_t posTemp;
	XmlNode *temp = createNode(nodeName, nodePtr);
	if(temp == NULL)
	{
		//TODO: be sure stack is empty!
		Logger::printDebugLog("Added head of tree into nodeStack");
		nodeStack.push(head[nodePtr]); //insert firs element to stack
		temp = nodeStack.top();
	}
	else
	{
		nodeStack.top() -> subNodes.push_back(temp);
		Logger::printDebugLog("Node added as a subnode of the top node in stack");
		nodeStack.push(temp);
		Logger::printDebugLog("Node added to stack");
	}
	if (delim == "/")
	{
		Logger::printDebugLog("This is just a single node, so it is removed from stack ex: <br/> or <br test=1/>");
		nodeStack.pop();//node cloased
	}
	tempToken.erase(0, posSpace + 1);
	string attrName, attrValue;
	bool hasQuote;
	Logger::printDebugLog("Strated scanning for attributes");
	while((posTemp = tempToken.find("=")) != string::npos)
	{
		hasQuote = false;
		attrName = tempToken.substr(0, posTemp); //range between space and = sign like //<a href=
		Logger::printDebugLog("Found attribute name");
		if(tempToken[posTemp + 1] == '\"')
		{
			Logger::printDebugLog("Attribute has quotes so moved posSpace pointer accordingly");
			hasQuote = true;
			++posTemp; //Move to other side of quote
			posSpace = tempToken.substr(posTemp + 1, string::npos).find("\"") + posTemp + 1; // FIXME:So expensive
		}
		else
		{
			Logger::printDebugLog("Attribute doesn't have any quotes so moved posSpace pointer accordingly");
			if((posSpace = tempToken.find(" ")) == string::npos)
			{
				if(delim.empty() == false)
				{
					posSpace = tempToken.find(delim);
				}
				else
				{
					posSpace = tempToken.size();
				}
			}
		}
		attrValue = tempToken.substr(posTemp + 1, posSpace - posTemp - 1);
		Logger::printDebugLog("Found attribute value");
		if(hasQuote)
		{
			tempToken.erase(0, posSpace + 2);
		}
		else
		{
			tempToken.erase(0, posSpace + 1);
		}
		Logger::printDebugLog("Removed attribute from temp memory");
		XmlAttribute *tempAttr = new XmlAttribute();
		tempAttr -> attrName = attrName;
		tempAttr -> attrVal = attrValue;
		temp -> attributes.push_back(tempAttr);
		Logger::printDebugLog("Saved attribute into node memory");
	}
}
Example #19
0
/* Break up the equation string into tokens */
bool Evaluator::tokenize( string eq_str) {
	this->tokenized = false;
	if (eq_str.empty()) return false;

	token.clear();
	token_type.clear();

	//remove any spaces from the input equation 
	eq_str.erase(remove(eq_str.begin(), eq_str.end(), ' '), eq_str.end());

	bool neg = false; //switch if parsing a negative sign (not minus)
	int brac_count = 0;
	TOK_TYPE last_tok = NONE;
	

//	int curr1 = 0;       //index to keep track of last split 
	for (auto i = 0; i < eq_str.size(); i++) {
		char ch = eq_str[i];
		string s(1, ch);
		//cout << i <<" "<<eq_str[i]<< "   is_operator:" << is_operator(eq_str[i]) << endl;
		
		// Check for negative. A negative occurs when '-' is the first character in the equation, 
		// or if the preceeding character is an operator or a '('
		if (ch == '-' && (i == 0 || eq_str[i - 1] == '(' || is_operator(eq_str[i - 1]))) {
			if (neg) return false; //double negative 
			neg = true; 
			token.push_back("NEG");
			token_type.push_back(NEG);
			continue;
		}

		else if (is_open_brace(ch)) {
			// if the previous token is variable, number, or ")", assume multiply
			if (last_tok == VAR || last_tok == NUM || last_tok == BRAC_C) {
				token.push_back("*");
				token_type.push_back(OP);
			}
			token.push_back(s);
			brac_count++;
			last_tok = BRAC_O;
		}
		else if (is_close_brace(ch)) {
			if (neg || last_tok == BRAC_O || last_tok == OP) return false; // "-)", "()", "[op])" aren't valid
			if (brac_count == 0) return false; // close bracket encountered before open bracket
			token.push_back(s);
			brac_count--;
			last_tok = BRAC_C;
		}
		else if (is_operator(ch)) {
			// negative or operator followed by an operator is invalid
			if (neg || last_tok == BRAC_O || last_tok == OP || last_tok == NONE) return false;
			token.push_back(s);
			last_tok = OP;
		}
		else if (is_number(ch)) {
			if (last_tok == VAR || last_tok == BRAC_C) { //previous token is a variable or ')'. assume multiply
				token.push_back("*");
				token_type.push_back(OP);
			}
			bool dot = ch == '.'; //see a dot 
			while (i+1 < eq_str.size()) {
				if (is_number(eq_str[i + 1])) {
					if (eq_str[i + 1] == '.') {
						if (dot) return false; //see 2 dots in this number, which is invalid number
						dot = true;
					}
					s += eq_str[++i];
				}
				else break;
			}
			
			if (s == ".") return false; //make sure the number isn't just a '.'
			
			token.push_back(s);
			last_tok = NUM;
		}
		else if (is_variable(ch)) {
			// if before the variable it's another variable, a number, or a ")", assume multiply
			if (last_tok == VAR || last_tok == NUM || last_tok == BRAC_C) {
				token.push_back("*");
				token_type.push_back(OP);
			}
			token.push_back(s);
			last_tok = VAR;
		}
		else return false; //encountered unknown character

		token_type.push_back(last_tok);
		neg = false;
	} //end of traversing the equation string

	//check the number of bracket is correct
	if (brac_count != 0) return false;

	//tokenize successfully
	this->equation = eq_str;
	this->tokenized = true;
	return true;
}
Example #20
0
void base_string::_Erase(string &src, const char c)
{
	int nPos = string::npos;
	while((nPos = src.find(c)) != string::npos)
		src.erase(nPos, 1);
}
Example #21
0
void swapRight(string &word) {
	char d = word.at(word.length() - 1);
	word.erase(word.length() - 1);
	word = string(1, d).append(word);
}
Example #22
0
inline void filter(string& s)
{
    for (; s.size() && isspace(s[s.size() - 1]); s.erase(s.size() - 1));
}
Example #23
0
void STrimRightN (string &s) {
	if (s.empty()) return;
	int i = s.size() - 1;
	while ((s[i] == ' ' || s[i] == '\t') && i >= 0) i--;
	s.erase (i+1);	
}
Example #24
0
vector <string> parseLine(string line, int line_number, string filename, bool allowError=true)
{
  // Cleanup the input line before using...
  line=removeLeadingWhitespace(line);
  line=removeTrailingWhitespace(line);

  if (show_debug)
  {
    //cout << "ParseLine: Parsing line '" << line << "'" << endl;
  }

  // Break the line into a series of vectors
  vector<string> result;

  string origLine = line;
  size_t space=line.find_first_of(" ");

  // Only one item on line - a single command
  if(space==string::npos)
  {
    result.push_back(line);
    return result;
  }

  // Put the command as the first item
  result.push_back(line.substr(0,space));
  line.erase(0,space);

  while(line.length()>0){
  	// Need to remove any leading spaces
  	while((line.at(0)==' ')||(line.at(0)=='\t')) {
    	line.erase(0,1);
    }
    if(line.length()==0) break;

    if(line.at(0)=='"') {
        // A string
        //cout << "looking for string..." << endl;
        space=1;
        space=line.find_first_of("\"",space);
        while((space!=string::npos)){
            if (verbose_parse_output==true){
                DisplayOnConsole("normal","Line length is: "+IntToString(line.length()));
            }
            if (show_debug){cout << "Char is at " << space << endl;}
            if (space!=1)
            {
                if (line.length()>4)
                {
                    if (line.at(space-2)!='\\'){
                        if (show_debug){ cout << "string is not double escaped (\\)" << endl; }
                        if (line.at(space-1)!='\\'){
                            if (show_debug){ cout << "string is not single escaped\nnot a \"" << endl; }
                            break;
                        }
                        else
                        {
                            if (show_debug){cout << "Single escaped char!" << endl;}
                            space=line.find_first_of("\"",space+1);
                            if (space==string::npos)
                            {
                                break;
                            }
                        }
                    }
                    else
                    {
                        // scan for a new " character
                        unsigned int space_old = space;
                        space=line.find_first_of("\"",space);

                        if (space == space_old)
                        {
                            // there must not be another " on the line, return as it is...
                            break;
                        }
                    }
                }
                else
                {
                    space=line.find_first_of("\"",space);
                    break;
                }
            }
            else
            {
                break;
            }
        }
        //cout << "found at " << space << endl;
        if (space==string::npos){
            // unable to find a closing quote!
            if (allowError){parse_error("Error: Missing closing quote!",line_number,filename);}
        }
        result.push_back(line.substr(0,space+1));
        line.erase(0,space+1);
    } else if (line.at(0)=='(') {
        space=1;

        if (GetCount(line,")") > 1)
        {
            space=line.find_last_of(")");
        }
        else
        {
            space=line.find_first_of(")",space);
        }

        if (space==string::npos){
            // unable to find a closing bracket!
            if(allowError){parse_error("Error: Missing closing bracket!",line_number,filename);}
        }
        result.push_back(line.substr(0,space+1));
        line.erase(0,space+1);
    } else {
    	space=line.find_first_of(" ");
    	if(space==string::npos) {
    		// Last one on the line
    		result.push_back(line);
    		line.clear();
    	} else {
    		result.push_back(line.substr(0,space));
    		line.erase(0,space);
    	}
    }
  }

  for(unsigned int i=1;i!=result.size()-1;i++)
  {
    //if (show_debug){cout << "replacing \\\" in '" << result[i] << "' with \"..." << endl;}
    result[i]=replaceAll(result[i],"\\\"","\"");
  }
  return result;
}
Example #25
0
 string remove_letter( string str, char c )
 {
   str.erase( remove( str.begin(), str.end(), c ), str.end() ) ;
   return str ;
 }
Example #26
0
bool SGFNode::makeNode(string sb)
{
	// separate property string
	string propertyString;
	char c='\0';
	int insideSBracket=0;

	// read properties up to first '(' or ';'
	// allowing '(' ')' inside '[' ']'
	for(int i=0;i<sb.length();i++) {
		c = sb.at(i);
		if(!insideSBracket && c=='[') insideSBracket++;
		else if(c==']' && (!(i>0&&sb.at(i-1)=='\\'))) insideSBracket--;
		if (insideSBracket==0) {
			if (c=='(' || c==';' || c==')') {
				propertyString = sb.substr(0, i);
				sb.erase(0, i);
				break;
			}
		}
	}
	
	// extract properties
	if(!extractProperties(propertyString)) {
		string message = "Bad node: ";
		message+=propertyString;
		message+="\n";
		LogWriter::printerr(message, "SGF");
		return false;
	}

/*	SGFNode* node;
	try {
		node = new SGFNode();
	} catch(exception& e) {
		cerr << e.what();
		return false;
	}*/
	SGFNode node;

	if (c=='(') {
		string pb;
		int bcount, i;
		char b;
		
		while (c=='(') {
			// remove up to matching ')' from sb 
			// and put into pb
			bcount = 0;
			insideSBracket = 0;
			
			for(i=0;i<sb.length();i++) {
				// WARNING: Don't count '(' or ')' inside comments!
				// and check for escaped ']' i.e. "C[This is some comment \](blah blah) ]"
				b = sb.at(i);
				if(!insideSBracket && b=='[') 
					insideSBracket++;
				else if(b==']' && (!(i>0&&sb.at(i-1)=='\\'))) {
					insideSBracket--;
					// error check
					if(insideSBracket<0) {
						// The stupid program that wrote this sgf 
						// has not escaped a ']' inside a comment
						insideSBracket = 0;
						// NOTE: We should really just quit parsing this sgf
						// and say's it's got an invalid node
						string message = "Bad node (mismatched brackets '[', ']'): ";
						message+=sb.substr(0, i);
						message+="\n";
						LogWriter::printerr(message, "SGF");
						return false;
					}
				}
				if(!insideSBracket) {
					if(b=='(')
						bcount++;
					else if(b==')' && bcount<=1)
						break;
					else if(b==')')
						bcount--;
				}
			}
			
			// remove '(;' from start by starting after it
			//pb = *(new string(sb.substr(2, i).trim()));
			pb = string(sb.substr(2, i));
			sb.erase(0, i);
		
			if (pb.length()>0) {
				// run make node
				if(!node.makeNode(pb))
					return false;

				// add as child
				addChild(node);
			}
			
			// see whats next
			c = sb.at(0);
		}
	}
	else if (c==';') {
		// copy all sb from after ';' to end
		string pb = string(sb.substr(1));
		//pb.deleteCharAt(pb.length()-1);
		
		if (pb.length()>0) {
			// make sure this isn't the end of a variation
			// or an empty node e.g. '(;W[pp];B[pl];)'
			if(pb.at(0)!=')') {
				// run make node
				if(!node.makeNode(pb))
					return false;
				// add as child
				addChild(node);
			}
		}			
	}
	return true;
}
Example #27
0
bool ControlPoint::getDescription(Url* url, string& description)
{
   bool rval = false;

   MO_CAT_DEBUG(MO_UPNP_CAT,
      "Getting UPnP description from url '%s'...",
      url->toString().c_str());

   // do http connection
   HttpClient client;
   if((rval = client.connect(url)))
   {
      // create special headers
      DynamicObject headers;
      headers["Connection"] = "close";

      // do get
      Url path(url->getPath());
      HttpResponse* response = client.get(&path, &headers);
      if((rval = (response != NULL)))
      {
         MO_CAT_DEBUG(MO_UPNP_CAT,
            "Get UPnP description response header:\n%s",
            response->getHeader()->toString().c_str());

         // receive response
         ByteBuffer bb(2048);
         ByteArrayOutputStream baos(&bb, true);
         if((rval = client.receiveContent(&baos)))
         {
            MO_CAT_DEBUG(MO_UPNP_CAT,
               "Get UPnP description response body:\n%s",
               string(bb.data(), bb.length()).c_str());
            if(response->getHeader()->getStatusCode() < 400)
            {
               // get description
               description.erase();
               description.append(bb.data(), bb.length());
            }
            else
            {
               // error getting description
               ExceptionRef e = new Exception(
                  "HTTP transmission error.",
                  "monarch.upnp.HttpError");
               e->getDetails()["statusMessage"] =
                  response->getHeader()->getStatusMessage();
               e->getDetails()["statusCode"] =
                  response->getHeader()->getStatusCode();
            }
         }
      }

      // disconnect
      client.disconnect();
   }

   if(!rval)
   {
      MO_CAT_ERROR(MO_UPNP_CAT,
         "Failed to get UPnP description from url '%s': %s",
         url->toString().c_str(),
         JsonWriter::writeToString(
            Exception::getAsDynamicObject()).c_str());
   }

   return rval;
}
Example #28
0
// separate a list of tags and values within a single node, between two ';'
// e.g. AB[10]B[pp]C[this is a comment]
bool SGFNode::extractProperties(string node)
{
	char c;
	vector<string> values;
	string temp;
	string key;
	int i=0;
	while(i<node.length()) {
		// ok must be a tag name then, so read in
		values.clear();
		
		// remove whitespace
		while(i<node.length() && ((c=node.at(i))=='\n' || c==' ' || c=='\t' || c=='\r'))
			node.erase(i, 1);

		// nothing here so return
		if(i>=node.length())
			return true;

		temp = "";

		// read in tag name, upto '['
		while(i<node.length() && (c=node.at(i))!='[') {
			temp.append(1, c);
			i++;
		}

		// if reached end of string
		// something wrong with this node
		// so quit
		if(i>=node.length())
			return false;

		key = temp.substr(0, temp.size());
		
		// continue if we have another value waiting
		// denoted by '[' upto ']'
		while (i<node.length() && (c=node.at(i)=='[')) {
			// step past '['
			i++;
	
			temp = "";

			while(i<node.length() && ((c=node.at(i))!=']' || (i>0 && node.at(i-1)=='\\'))) {
				temp.append(1, c);
				i++;
			}
			// if haven't found matching ']'
			if(i>=node.length())
				return false;
			values.push_back(temp);
			i++;
		}

		// if reached end of string without hitting ']'
		// something wrong with this node
		// so quit
		if(i>=node.length() && c!=']')
			return false;

		setProperty(key, values);
	}
	return true;
}
Example #29
0
void trim(string& in) {
	string::size_type loc = in.find_first_not_of(" \r\t\f\n");
	if(loc != string::npos) in.erase(0,loc);
	loc = in.find_last_not_of(" \r\t\f\n");
	if(loc != string::npos) in.erase(loc+1);
}
Example #30
0
	private : void ruleRotateRight(string & word) {
		word = word[word.size()-1] + word ;
		word.erase(word.size()-1,1);
	}