string f(string s) {
    int k = 0;
    for (int i=0; i<s.length(); i++) if (s[i]==':') k++;
        for (int i=0; i<s.length()-1; i++) {
            if (s[i]==':' && s[i+1]==':') {
                string tmp;
                for (int j=0; j<7-k; j++) {
                    tmp = tmp + t + ":";
                }
                if (k<7) {
                    tmp = tmp + t;
                    s = s.substr(0,i+1) + tmp + s.substr(i+1,s.length()-i-1);
                }
                if (k==7) {
                    s = s.substr(0,i+1) + t + s.substr(i+1,s.length()-i-1);
                }
                if (k==8) {
                    if (s[0]==':') s = s.substr(1,i) + t + s.substr(i+1,s.length()-i-1);
                    else s = s.substr(0,i+1) + t + s.substr(i+1,s.length()-i-2);
                }
                break;
            }
        }
    if (s[0]==':') s = t + s;
    if (s[s.length()-1]==':') s = s + t;
    int last = 0;
    for (int i=0; i<s.length(); i++) if (s[i]==':') {
        if (i-last<4) {
            string tmp = "";
            for (int j=0; j<4-(i-last); j++) tmp += "0";
            s = s.substr(0, last) + tmp + s.substr(last, s.length()-last);
        }
        i = last+4;
        last = i+1;
    }
    int i = s.length();
    if (i-last<4) {
        string tmp = "";
        for (int j=0; j<4-(i-last); j++) tmp += "0";
        s = s.substr(0, last) + tmp + s.substr(last, s.length()-last);
    }
    return s;
}
Example #2
0
string OutfitterPanel::LicenseName(const string &name) const
{
	static const string &LICENSE = " License";
	return "license: " + name.substr(0, name.length() - LICENSE.length());
}
Example #3
0
int GoogleVoice::Login(string email, string passwd)
{
	if(email.length()<1 || email.length()<1) return -1;
	this->email=email; this->passwd=passwd;
	return Login();
}
Example #4
0
void RTFGenParser::tag_start(const QString &tagName, const list<QString> &attrs)
{
    if (m_res_size)
        return;
    CharStyle parentStyle, style;
    {
        Tag* pParentTag = m_tags.getTopTagWithCharStyle();
        if (pParentTag != NULL)
        {
            parentStyle = *(pParentTag->pCharStyle);
        }
    }
    style = parentStyle;
    if ((tagName == "b") || (tagName == "i") || (tagName == "u") ||
            (tagName == "font") || (tagName == "p") || (tagName == "span")){
        QString tag = tagName;
        QString option;
        for (list<QString>::const_iterator it = attrs.begin(); it != attrs.end(); ++it){
            QString key = *it;
            ++it;
            QString value = *it;
            option += " ";
            option += key;
            if (!value.isEmpty()){
                option += "=\"";
                option += value;
                option += "\"";
            }
        }
        tags.push(tag);
        options.push(option);
    }

    if (tagName == "b"){
        style.bold = true;
    }
    else if (tagName == "i"){
        style.italic = true;
    }
    else if (tagName == "u"){
        style.underline = true;
    }
    else if (tagName == "font"){
        for (list<QString>::const_iterator it = attrs.begin(); it != attrs.end(); it++){
            QString name = (*it);
            ++it;
            QString value = (*it);
            if (name == "color")
            {
                style.colorIdx = getColorIdx(value);
            }
            else if (name == "face")
            {
                style.faceIdx = getFontFaceIdx(value);
            }
            else if (name == "size")
            {
                int logicalSize = value.toInt();
                if (value[0] == '+' || value[0] == '-')
                    logicalSize += 3;
                if (logicalSize < 1)
                    logicalSize = 1;
                else if (logicalSize > 7)
                    logicalSize = 7;
                style.sizePt = htmlFontSizeToPt(logicalSize);
            }
        }
    }
    else if (tagName == "p"){
        m_paragraphDir = DirUnknown;
        m_lastParagraphPos = res.length();
        m_bSpace = true;
        for (list<QString>::const_iterator it = attrs.begin(); it != attrs.end(); ++it){
            QString name = (*it).lower();
            ++it;
            QString value = (*it);
            if (name == "dir")
            {
                QString dir = value.lower();
                if (dir == "ltr")
                {
                    res += "\\ltrpar";
                    m_paragraphDir = DirLTR;
                }
                if (dir == "rtl")
                {
                    res += "\\rtlpar";
                    m_paragraphDir = DirRTL;
                }
            }
        }

    }
    else if (tagName == "br"){
        res += "\\line";
        m_bSpace = true;
    }
    else if (tagName == "img"){
        QString src;
        QString alt;
        for (list<QString>::const_iterator it = attrs.begin(); it != attrs.end(); ++it){
            QString name = (*it);
            ++it;
            QString value = (*it);
            if (name == "src"){
                src = value;
                break;
            }
            if (name == "alt"){
                alt = value;
                break;
            }
        }
        if (src.left(5) == "icon:"){
            list<string> smiles = getIcons()->getSmile(src.mid(5).latin1());
            for (list<string>::iterator its = smiles.begin(); its != smiles.end(); ++its){
                string s = *its;
                for (unsigned nSmile = 0; nSmile < 26; nSmile++){
                    if (s != def_smiles[nSmile])
                        continue;
                    res += "<##icqimage00";
                    char buf[4];
                    sprintf(buf, "%02X", nSmile);
                    res += buf;
                    res += ">";
                    return;
                }
            }
            if (!smiles.empty()){
                text(QString::fromUtf8(smiles.front().c_str()));
                return;
            }
        }
        text(alt);
        return;
    }

    // Process attributes which all tags share.

    for (list<QString>::const_iterator it = attrs.begin(); it != attrs.end(); ++it){
        QString name = (*it).lower();
        ++it;
        QString value = (*it);

        // Any tag might have a STYLE.
        if (name == "style"){
            // A really crude CSS parser goes here:
            QRegExp cssReNum("[0-9]+");
            list<QString> cssProp = parseStyle(value);
            for (list<QString>::iterator it = cssProp.begin(); it != cssProp.end(); ++it){
                QString cssPropName = *it;
                ++it;
                if (it == cssProp.end())
                    break;
                QString cssPropValue = *it;
                if (cssPropName == "font-family")
                {
                    style.faceIdx = getFontFaceIdx(cssPropValue);
                }
                else if (cssPropName == "font-size")
                {
                    cssPropValue = cssPropValue.lower();
                    int length;
                    if (cssReNum.match(cssPropValue, 0, &length) == 0){
                        float number = cssPropValue.left(length).toFloat();
                        QString type = cssPropValue.mid(length);
                        if (type == "pt")
                        {
                            style.sizePt = static_cast<int>(number);
                        }
                        else if (type == "px")
                        {
                            // for now, handle like 'pt', though it's wrong
                            style.sizePt = static_cast<int>(number);
                        }
                        else if (type == "%")
                        {
                            style.sizePt = static_cast<int>(parentStyle.sizePt * (number/100));
                        }
                        // We don't handle 'cm', 'em' etc.
                    }
                    else if (cssPropValue == "smaller")
                    {
                        // FONT SIZE=3 is 'normal', 2 is 'smaller'
                        style.sizePt = htmlFontSizeToPt(2, parentStyle.sizePt);
                    }
                    else if (cssPropValue == "larger")
                    {
                        // FONT SIZE=3 is 'normal', 4 is 'larger'
                        style.sizePt = htmlFontSizeToPt(4, parentStyle.sizePt);
                    }

                    // We don't handle 'small', 'medium' etc. It goes too far
                    // beyond our basic implementation.
                    // Also, empty 'type' would be invalid CSS, thus ignored.
                }
                else if (cssPropName == "font-style")
                {
                    style.italic = (cssPropValue.lower() == "italic");
                }
                else if (cssPropName == "font-weight")
                {
                    style.bold = (cssPropValue.toInt() >= 600);
                }
                else if (cssPropName == "text-decoration")
                {
                    style.underline = (cssPropValue.lower() == "underline");
                }
                else if (cssPropName == "color")
                {
                    style.colorIdx = getColorIdx(cssPropValue);
                }
                else if (cssPropName == "background-color")
                {
                    style.bgColorIdx = getColorIdx(cssPropValue);
                }
            }
        }
    }

    Tag& tag = *(m_tags.pushNew());
    tag.name = tagName;
    // Check if anything changed in the style.
    // Only then the tag deserves getting a charStyle.
    if (parentStyle != style)
    {
        QString rtf = style.getDiffRTF(parentStyle);
        if (!rtf.isEmpty())
        {
            res += rtf.utf8();
            m_bSpace = true;
        }
        tag.setCharStyle(style);
    }
}
int main() {
    ios::sync_with_stdio(false);
    cin >> n;
    cin >> s1;
    for (int i = 0; i < 26; i++) {
        memset(graph[i], 0, sizeof(int) * 26);
    }
    memset(inDegree, 0, sizeof(int) * 26);
    bool orderLogical = true;
    n--;
    while (n--) {
        cin >> s2;
        bool isLogic = false;
        for (int i = 0, j = 0; i < s1.length() && j < s2.length(); i++, j++) {
            if (s1[i] != s2[j]) {
                graph[s1[i] - 'a'][s2[j] - 'a'] = 1;
                isLogic = true;
                break;
            }
        }
        if (!isLogic) {
            orderLogical &= s1.length() <= s2.length();
        }
        s1 = s2;
    }
    for (int i = 0; i < 26; i++) {
        for (int j = 0; j < 26; j++) {
            if (graph[i][j] == 1) {
                inDegree[j]++;
            }
        }
    }
    queue<int> q;
    for (int i = 0; i < 26; i++) {
        if (inDegree[i] == 0) {
            q.push(i);
        }
    }
    char res[27];
    int count = 0;
    while (!q.empty()) {
        int cur = q.front();
        q.pop();
        res[count] = (char)(cur + 'a');
        count++;
        for (int i = 0; i < 26; i++) {
            if (graph[cur][i] == 1) {
                graph[cur][i] = 0;
                inDegree[i]--;
                if (inDegree[i] == 0) {
                    q.push(i);
                }
            }
        }
    }
    res[26] = '\0';

    if (count == 26 && orderLogical) {
        cout << res << endl;
    } else {
        cout << "Impossible" << endl;
    }
    return 0;
}
Example #6
0
void LinkedList::ToLower(string &str){
  for(unsigned int i = 0; i<str.length(); i++){
    str[i] = tolower(str[i]);
  }
}
Example #7
0
void interpret() 
{
    double x = 400; //canvas.width / 2
    double y = 300; //canvas.height / 2
    double ang = 0;
    ip = 0;

    unsigned int color = 0xffffff;
    unsigned int startTime = GetTickCount();
    unsigned int allocTime = 1000;

    map<string, Func> funcs;
    globals.reset(new map<string, double>);
    vars = globals;
    outText.clear();

    vector<LoopEntry> loopStack; // elements are from 'do'
    vector<Frame> callStack; // elements are from function call, things that are below the current call which is in vars

    try {
        while (ip < text.length()) {
            if (GetTickCount() - startTime > allocTime)
                error("too much time");
            string c = readChars();
            if (c[0] == '#') { // comment
                ip = text.find('\n', ip);
                continue;
            }
            if (c.empty()) 
                continue;
            if (c == "F" || c == "Fs" || c == "B" || c == "Bs") {
                double n = readNum();
                if (c[0] == 'B')
                    n = -n;
                double px = x, py = y;
                x += n * cos(ang * PI / 180.0);
                y += n * sin(ang * PI / 180.0);
                // 's' is silent, do nothing
                if (c.length() == 1 || c[1] != 's') {
                    drawLine((int)px, (int)py, (int)x, (int)y, color);
                }
            }
            else if (c == "T" || c == "turn") {
                ang += readNum();
            }
            else if (c == "time") {
                allocTime = (int)readNum();
            }
            else if (c == "=") {
                string name = readChars();
                double num = readNum();
                (*vars)[name] = num;
            }
            else if (c == "neg") {
                string name = readChars();
                (*vars)[name] = -getVarCheck(name);
            }
            else if (c.find_first_of("+-/*") != string::npos) {
                string name = readChars();
                double num = readNum();
                double v = getVarCheck(name);
                if (c == "+")
                    (*vars)[name] = v + num;
                if (c == "-")
                    (*vars)[name] = v - num;
                else if (c == "/")
                    (*vars)[name] = v / num;
                else if (c == "*")
                    (*vars)[name] = v * num;
            }
            else if (c == "sqrt") {
                string name = readChars();
                (*vars)[name] = sqrt(getVarCheck(name));
            }
            else if (c == "do") {
                int times = (int)readNum();
                LoopEntry l = {times, ip};
                loopStack.push_back(l);
            }
            else if (c == "next") {
                if (loopStack.size() == 0)
                    error("next without do");
                auto d = loopStack.back();
                loopStack.pop_back();
                --d.timesLeft;
                if (d.timesLeft > 0) {
                    loopStack.push_back(d);
                    ip = d.toip;
                }
            }
            else if (c == "color") {
                int r = (int)readNum();
                int g = (int)readNum();
                int b = (int)readNum();
                color = RGB(r, g, b);
            }
            else if (c == "func") {
                string fname = readChars();
                vector<string> args;
                while(true) {
                    string aname = readChars();
                    if (aname.empty())
                        error("func without startf");
                    if (aname == "startf")
                        break;
                    args.push_back(aname);
                }
                auto endip = text.find("endf", ip);
                if (endip == string::npos) 
                    error("no endf for function " + fname);
                Func fe = { args, ip };
                funcs[fname] = fe;
                ip = endip + 4; // skip after endf
            }
            else if (funcs.find(c) != funcs.end()) { // function call
                auto func = funcs[c];
                Frame fr = { vars, 0 };
                auto newvars = new map<string, double>; // don't change vars before arg evaluation
                for(auto aname : func.args) {
                    double v = readNum();
                    (*newvars)[aname] = v;
                }
                vars.reset(newvars);
                fr.returnIp = ip;
                callStack.push_back(fr);
                ip = func.startip;
            }
            else if (c == "endf" || c == "return") {
                if (callStack.empty())
                    error("no call to return from");
                Frame fr = callStack.back();
                callStack.pop_back();
                vars = fr.returnVars;
                // current vars automatically deleted by shared_ptr
                ip = fr.returnIp;
            }
            else if (c == "if") {
                double n1 = readNum();
                string op = readChars();
                double n2 = readNum();
                bool result;

                if (op == "==") result = (abs(n1 - n2) < EPSILON);
                else if (op == ">=") result = (n1 >= n2);
                else if (op == "<=") result = (n1 <= n2);
                else if (op == ">") result = (n1 > n2);
                else if (op == "<") result = (n1 < n2);
                else if (op == "!=") result = (abs(n1 - n2) > EPSILON);
                else error("Unknown operator " + op);

                // now decide where to go
                if (!result) { // need to find my else or endif
                    int nestlvl = 0;
                    while (true) {
                        string r = readChars();
                        if (r.empty())
                            error("if without endif");
                        if (r == "if")
                            ++nestlvl;
                        else if (r == "else") {
                            if (nestlvl == 0) 
                                break; // found where to go
                        }
                        else if (r == "endif") {
                            if (nestlvl > 0)
                                --nestlvl;
                            else 
                                break; // found where to go
                        }
                    }
                }
            }
            else if (c == "endif") { // do nothing
            }
            else if (c == "else") {
                int nestlvl = 0;
                while (true) { // skip to the end of the endif in my nesting level
                    string r = readChars();
                    if (r.empty())
                        error("else without endif");
                    if (r == "if")
                        ++nestlvl;
                    else if (r == "endif") {
                        if (nestlvl > 0)
                            --nestlvl;
                        else 
                            break;
                    }
                }
            }
            else if (c == "print") {
                double n = readNum();
                stringstream ss;
                ss << n;
                out(ss.str());;
            }
            else {
                error("Unknown command `" + c + "`");
            }
        }
    }
    catch(const exception&)
    {}

    static string prevout;
    if (outText != prevout) {
        SetWindowTextA(g_outwnd, outText.c_str());
        prevout = outText;
    }

}
Example #8
0
Game::Game(string line)
{
		//round
		string token = line.substr(0, 1);
		_round = atoi(token.c_str());
		//game
		token = line.substr(2,1);
		_game = atoi(token.c_str());
		//date
		token = line.substr(5,13);
		_date = new Date(token);
		
		//team names and score
		token = line.substr(19, line.length());
		string splited;
		int locationInLine=19;
		for (int i=0 ; i < token.length(); i++)
		{
			string temp = token.substr(i,1);	
			if (token.length()>(i+4) && token.at(i)==' ' && token.at(i+1)=='-' && token.at(i+2)==' ')
			{
				_home=splited;
				locationInLine+=i+3;
				token=line.substr(locationInLine,line.length());
				splited.clear();
				break;
			}
			splited.append(temp);
		}
		for (int i=0 ; i < token.length(); i++)
		{
			string temp = token.substr(i,1);	
			regex integer("(\\+|-)?[[:digit:]]+");
			if (token.length()>(i+4) && regex_match(temp,integer))
			{
				_guest=splited;
				locationInLine+=i;
				token=line.substr(locationInLine,line.length());
				splited.clear();
				break;
			}
			splited.append(temp);
		}
		int tempFound= token.find('-');
		locationInLine+=tempFound+1;
		string temp = token.substr(0, tempFound);
		_finalScoreHOME=atoi(temp.c_str());
		token=line.substr(locationInLine,line.length());

		tempFound= token.find(' ');
		locationInLine+=tempFound+1;
		temp = token.substr(0, tempFound);
		_finalScoreGUEST=atoi(temp.c_str());
		token=line.substr(locationInLine,line.length());

		tempFound= token.find('(');
		locationInLine+=tempFound+1;
		token=line.substr(locationInLine,line.length());

		tempFound= token.find('-');
		locationInLine+=tempFound+1;
		temp = token.substr(0, tempFound);
		_halftimeScoreHOME=atoi(temp.c_str());
		token=line.substr(locationInLine,line.length());
		
		tempFound= token.find(')');
		locationInLine+=tempFound+1;
		temp = token.substr(0, tempFound);
		_halftimeScoreGUEST=atoi(temp.c_str());
		
}
void Meme::generateMeme(string t, string inPath, string outPath){


        gdImagePtr im;
    int black;
    int white;
    int x, y, x1, y1, fileExt;
    char *err;
    char *err1;
    char *err2;
    FILE* out;
    FILE* in;
    double sz = 20.;
    int brect[8];


    string v = "/home/users/igarrett/Meme-Machine/textInject/impact.ttf";  /* User supplied font PLEASE WORK*/

    string fileName;

    fileName = getFileName(inPath);

    if (fileName.length()==0){
        fileName = inPath;
    }

    fileExt = getexten(fileName);


    char* s = const_cast <char*>(t.c_str());
    char* f = const_cast <char*>(v.c_str());

    const char* strFinalInPath = inPath.c_str();
    const char* strFinalOutPath = outPath.c_str();

    in = fopen(strFinalInPath, "rb");
    
    //Check extension
    if (fileExt==0){
        im = gdImageCreateFromJpeg(in);
    }

    else if (fileExt==1){
        im = gdImageCreateFromPng(in);
    }

    /* Background color (first allocated) */
    white = gdImageColorResolve(im, 255, 255, 255);
    black = gdImageColorResolve(im, 0, 0, 0);



    in = fopen(strFinalInPath, "rb");
    
    //Check extension
    if (fileExt==0){
        im = gdImageCreateFromJpeg(in);
    }

    else if (fileExt==1){
        im = gdImageCreateFromPng(in);
    }

    out = fopen(strFinalOutPath, "wb");


       //Split string if need be
    int memeLength = t.length();
    if (memeLength*12 > gdImageSX(im)){
        int brect1[8];
        int brect2[8];

        int i;
        int whiteSpace;
        for (i=0; i < memeLength/2; i++){
            if (t[i]==' '){
                whiteSpace = i;
            }
        }

        string SubStr1 = t.substr(0,whiteSpace);
        string SubStr2 = t.substr(whiteSpace,memeLength-1);
        char *subIn1 = const_cast <char*>(SubStr1.c_str());
        char *subIn2 = const_cast <char*>(SubStr2.c_str());

        /* obtain brect1 so that we can size the image */
        err1 = gdImageStringFT(NULL,&brect1[0],0,f,sz,0.,0,0,subIn1);
        if (err1) {fprintf(stderr,"%s",err1); return;}

        /* obtain brect1 so that we can size the image */
        err2 = gdImageStringFT(NULL,&brect2[0],0,f,sz,0.,0,0,subIn2);
        if (err2) {fprintf(stderr,"%s",err2); return;}

        //top text
        x = (gdImageSX(im)-(brect1[2]-brect1[0]))/2;
        y = 5 - brect1[7];

        //bottom text
        x1 = (gdImageSX(im)-(brect2[2]-brect2[0]))/2;
        y1 = gdImageSY(im)-(brect2[1]-brect2[6])-5;

        err1 = gdImageStringFT(im,&brect1[0],black,f,sz,0.0,x,y,subIn1);
        err2 = gdImageStringFT(im,&brect1[0],black,f,sz,0.0,x1,y1,subIn2);

        if (err1) {fprintf(stderr,"%s",err1); return;}
        if (err2) {fprintf(stderr,"%s",err2); return;}

    }

    else {
        err = gdImageStringFT(NULL,&brect[0],0,f,sz,0.,0,0,s);
        if (err) {fprintf(stderr,"%s",err); return;}


        x = (gdImageSX(im)-(brect[2]-brect[0]))/2;
        y = 5 - brect[7];

        err = gdImageStringFT(im,&brect[0],black,f,sz,0.0,x,y,s);
        if (err) {fprintf(stderr,"%s",err); return;}
    }


    /* Write img to stdout */
    if (fileExt==0){
        gdImageJpeg(im, out, -1);
    }

    else if (fileExt==1){
        gdImagePng(im, out);
    }

    /* Destroy it */
    gdImageDestroy(im);
}
 static bool compare(string a, string b){
     return a.length() > b.length();
 }
Example #11
0
/* All ppc64 events (except CYCLES) have a _GRP<n> suffix.  This is
 * because the legacy opcontrol profiler can only profile events in
 * the same group (i.e., having the same _GRP<n> suffix).  But operf
 * can multiplex events, so we should allow the user to pass event
 * names without the _GRP<n> suffix.
 *
 * If event name is not CYCLES or does not have a _GRP<n> suffix,
 * we'll call ophelp and scan the list of events, searching for one
 * that matches up to the _GRP<n> suffix.  If we don't find a match,
 * then we'll exit with the expected error message for invalid event name.
 */
static string _handle_powerpc_event_spec(string event_spec)
{
	FILE * fp;
	char line[MAX_INPUT];
	size_t grp_pos;
	string evt, err_msg;
	size_t evt_name_len;
	bool first_non_cyc_evt_found = false;
	bool event_found = false;
	char event_name[OP_MAX_EVT_NAME_LEN], * remaining_evt_spec, * colon_start;
	string cmd = OP_BINDIR;
	cmd += "/ophelp";

	colon_start = (char *)index(event_spec.c_str(), ':');
	if (colon_start)
		evt_name_len = colon_start - event_spec.c_str();
	else
		evt_name_len = event_spec.length();
	strncpy(event_name, event_spec.c_str(), evt_name_len);
	event_name[evt_name_len] = '\0';
	remaining_evt_spec = colon_start ?
	                                  ((char *)event_spec.c_str() + strlen(event_name) + 1)
	                                  : NULL;
	if (!strcmp("CYCLES", event_name)) {
		event_found = true;
		goto out;
	}

	evt = event_name;
	// Need to make sure the event name truly has a _GRP<n> suffix.
	grp_pos = evt.rfind("_GRP");
	if ((grp_pos != string::npos) && ((evt = evt.substr(grp_pos, string::npos))).length() > 4) {
		char * end;
		strtoul(evt.substr(4, string::npos).c_str(), &end, 0);
		if (end && (*end == '\0')) {
		// Valid group number found after _GRP, so we can skip to the end.
			event_found = true;
			goto out;
		}
	}

	// If we get here, it implies the user passed a non-CYCLES event without a GRP suffix.
	// Lets try to find a valid suffix for it.
	fp = popen(cmd.c_str(), "r");
	if (fp == NULL) {
		cerr << "Unable to execute ophelp to get info for event "
		     << event_spec << endl;
		exit(EXIT_FAILURE);
	}

	err_msg = "Cannot find event ";
	while (fgets(line, MAX_INPUT, fp)) {
		if (!first_non_cyc_evt_found) {
			if (!strncmp(line, "PM_", 3))
				first_non_cyc_evt_found = true;
			else
				continue;
		}
		if (line[0] == ' ' || line[0] == '\t')
			continue;
		if (!strncmp(line, event_name, evt_name_len)) {
			// Found a potential match.  Check if it's a perfect match.
			string save_event_name = event_name;
			size_t full_evt_len = index(line, ':') - line;
			memset(event_name, '\0', OP_MAX_EVT_NAME_LEN);
			strncpy(event_name, line, full_evt_len);
			string candidate = event_name;
			if (candidate.rfind("_GRP") == evt_name_len) {
				event_found = true;
				break;
			} else {
				memset(event_name, '\0', OP_MAX_EVT_NAME_LEN);
				strncpy(event_name, save_event_name.c_str(), evt_name_len);
			}
		}
	}
	pclose(fp);

out:
	if (!event_found) {
		cerr << err_msg << event_name << endl;
		cerr << "Error retrieving info for event "
				<< event_spec << endl;
		exit(EXIT_FAILURE);
	}
	ostringstream ret_strm;
	if (remaining_evt_spec)
		ret_strm << event_name << ":" << remaining_evt_spec;
	else
		ret_strm << event_name;
	return ret_strm.str();
}
    vector<string> wordBreak(
        string s,
        unordered_set<string> &dict)
    {
        vector<string> res;
        int len = s.length();
        if (len == 0)
        {
            return res;
        }

        // Construct a directed graph where each node i represents s.substr(0, i).
        // There is a link from node i to node j (i < j) if and only if both s.substr(0, i)
        // s.substr(0, j) can be broken into dictionary words. The solution is
        // essentially all the paths from node 0 to node len. This map will keep
        // the previous nodes on those paths for each node.
        unordered_map<int, vector<int>> prevMap;

        // Use breadth-first search to find all the paths from node 0 to node len.
        queue<int> currSearch;
        currSearch.push(0); // 0 represents s.substr(0, 0), i.e., an empty string.
        int currSearchSize = 1;
        while (currSearchSize > 0)
        {
            for (int i = 0; i < currSearchSize; i++)
            {
                int j = currSearch.front();
                currSearch.pop();

                for (int k = j + 1; k <= len; k++)
                {
                    auto it = dict.find(s.substr(j, k - j));
                    if (it != dict.end())
                    {
                        // j is a previous node of k.
                        auto itMap = prevMap.find(k);
                        if (itMap == prevMap.end())
                        {
                            prevMap.insert(make_pair(k, vector<int>({ j })));

                            // This is the first time that we see k and k is not
                            // the end of the string, so we need to add k to the
                            // search queue.
                            if (k != len)
                            {
                                currSearch.push(k);
                            }
                        }
                        else
                        {
                            itMap->second.push_back(j);
                        }
                    }
                }
            }

            currSearchSize = currSearch.size();
        }

        // Backtrack from node len to node 0 to get all the paths.
        vector<int> pathIndexes({ len });
        BuildPathFromPrevMap(s, prevMap, pathIndexes, res);

        return res;
    }
Example #13
0
vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
	vector<vector<string> > ret(0);
    int i = 0 , se = 0, len = start.length(), runlen = 0;
	unordered_map<string, int> m[2] ;
	unordered_map<string, string> parent ;
	//unordered_set<char> alpha({'a','b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'});
	queue<string> q[2] ;
	string str[2] ;

	str[0] = end ;
	str[1] = start ;

	m[1][start] = 1 ;
	m[0][end] = 1 ;

	q[1].push(start) ;
	q[0].push(end) ;
	while(1){
		string ref ;
		se = ! se ;
		if(q[se].empty()){
			break;
		}
		ref = q[se].front() ;
			
		for(i = 0; i < len; i++){
			char c ;
			//unordered_set<char> a (alpha) ;
			//a.erase(ref[i]) ;
			for( c = 'a'; c <= 'z'; c++){
				if(c == ref[i]){continue;}
				string temp (ref) ;
				temp[i] = c ;
				if(m[!se][temp] > 0){
					int newrunlen = m[se][q[se].front()] + m[!se][temp] ;
					if(newrunlen == runlen || runlen == 0  ){
						vector<string> transformation ;
						stack<string> start ;
						queue<string> end ;
						runlen = newrunlen ;
						string str (q[se].front()) ;
						while(str.length() == len ){
							if(se == 1){
								start.push(str) ;
							}else{
								end.push(str);
							}
							str = parent[str] ;
						}
						str = temp ;
						while(str.length() == len){
							if(se == 1){
								end.push(str) ;
							}else{
								start.push(str) ;
							}
							str = parent[str] ;
						}
						while(!start.empty()){
							transformation.push_back(start.top()) ;
							start.pop() ;
						}
						while(!end.empty()){
							transformation.push_back(end.front()) ;
							end.pop() ;
						}
						ret.push_back(transformation);
					}else{
						return ret ;
					}
				}
				if(dict.find(temp) != dict.end()){
					dict.erase(temp);
					q[se].push(temp) ;
					m[se][temp] = m[se][q[se].front()] + 1;					
					parent[temp] = q[se].front() ;
				}
			}
		}
		m[se][q[se].front()] = 0 ;
		q[se].pop(); 
	}
	return ret ;
}
Example #14
0
	bool command::IsMark(string s){
		if (s.length()!=1) return false;
		if(s[0]!='#' ) return false;
		
		return true;
	}
Example #15
0
bool wordQuery::isContainedWord(string l,string s)
{
	//build counting Matrix
    l=string(" ")+l;
	s=string(" ")+s;
	int column=l.length();
	int row=s.length();
	int **pMatrix=new int *[row];
	for(int i=0;i<row;i++)
	   pMatrix[i]=new int[column];
	//signal Matrix to retrive common subsequence
	int **sMatrix=new int *[row];
	for(int i=0;i<row;i++)
	   sMatrix[i]=new int[column];
    //initialization
	for(int i=0;i<row;i++)
		for(int j=0;j<column;j++)
		{
			pMatrix[i][j]=0;
			sMatrix[i][j]=0;
		}
    //dynamic programming find longest common subsequence
    for(int i=0;i<row;i++)
	{
		for(int j=0;j<column;j++)
		{
			if(i==0||j==0)
			{
				pMatrix[i][j]=0;
			}
			if(i>0&&j>0&&l.at(j)==s.at(i))
			{
				pMatrix[i][j]=pMatrix[i-1][j-1]+1;
				sMatrix[i][j]=1;
			}
			if(i>0&&j>0&&l.at(j)!=s.at(i))
			{
				pMatrix[i][j]=(pMatrix[i][j-1]>pMatrix[i-1][j]?pMatrix[i][j-1]:pMatrix[i-1][j]); //selection expression 
				sMatrix[i][j]=(pMatrix[i][j-1]>pMatrix[i-1][j]?2:3);
			}
		}
	}
	//print result
	string retrivedword="";
	int prow=s.length()-1;
	int pcolumn=l.length()-1;
	while(prow>0&&pcolumn>0)
	{
		if(sMatrix[prow][pcolumn]==1)
		{
			retrivedword+=s.at(prow);
			prow--;
			pcolumn--;
		}
		if(sMatrix[prow][pcolumn]==2)
		{
			pcolumn--;
		}
		if(sMatrix[prow][pcolumn]==3)
		{
			prow--;
		}
	}
	//cout<<pMatrix[row-1][column-1]<<endl;
	reverse(retrivedword.begin(), retrivedword.end()); 
	//cout<<retrivedword<<endl;
	//judgement
	if(s.length()-1==pMatrix[row-1][column-1])
	{
		//delete counting Matrix
	    for(int i=0;i<row;i++)
	    {
		    delete pMatrix[i];
		    delete sMatrix[i];
	    }
	    delete pMatrix;
	    delete sMatrix;
		return true;
	}
	else
	{
		//delete counting Matrix
	    for(int i=0;i<row;i++)
	    {
		    delete pMatrix[i];
		    delete sMatrix[i];
	    }
	    delete pMatrix;
	    delete sMatrix;
		return false;
	}
}
void Base32DecodeBase16Encode(const string & input, string & output)
{
	// Here's the base32 decoding:

		// The "Base 32 Encoding" section of http://tools.ietf.org/html/rfc4648#page-8
		// shows that every 8 bytes of base32 encoded data must be translated back into 5 bytes
		// of original data during a decoding process. The following code does this.

	int input_len = input.length();
	assert( input_len == 32 );
	const char * input_str = input.c_str();
	int output_len = (input_len*5)/8;
	assert( output_len == 20 );
		// Because input strings are assumed to be SHA1 hash values in base32, it is also assumed
		// that they will be 32 characters (and bytes in this case) in length, and so the output
		// string should be 20 bytes in length.
	unsigned char *output_str = new unsigned char[output_len];
	
	char curr_char, temp_char;
	long long temp_buffer = 0; //formerly: __int64 temp_buffer = 0;
	for( int i=0; i<input_len; i++ )
	{
		curr_char = input_str[i];
		if( curr_char >= 'A' && curr_char <= 'Z' )
			temp_char = curr_char - 'A';
		if( curr_char >= '2' && curr_char <= '7' )
			temp_char = curr_char - '2' + 26;

		if( temp_buffer )
			temp_buffer <<= 5; //temp_buffer = (temp_buffer << 5);
		temp_buffer |= temp_char;

		// if 8 encoded characters have been decoded into the temp location,
			// then copy them to the appropriate section of the final decoded location
		if( (i>0) && !((i+1) % 8) )
		{
			unsigned char * source = reinterpret_cast<unsigned char*>(&temp_buffer);
			//strncpy(output_str+(5*(((i+1)/8)-1)), source, 5);
			int start_index = 5*(((i+1)/8)-1);
			int copy_index = 4;
			for( int x=start_index; x<(start_index+5); x++, copy_index-- )
				output_str[x] = source[copy_index];
			temp_buffer = 0;

			// I could be mistaken, but I'm guessing that the necessity of copying
			// in "reverse" order results from temp_buffer's little endian byte order.
		}
	}

	// Here's the base16 encoding (for human-readable output and the chosen validation tests):

		// The "Base 16 Encoding" section of http://tools.ietf.org/html/rfc4648#page-10
		// shows that every byte original data must be encoded as two characters from the
		// base16 alphabet - one charactor for the original byte's high nibble, and one for
		// its low nibble.

	unsigned char out_temp, chr_temp;
	for( int y=0; y<output_len; y++ )
	{
		out_temp = Base16EncodeNibble( output_str[y] >> 4 ); //encode the high nibble
		output.append( 1, static_cast<char>(out_temp) );
		out_temp = Base16EncodeNibble( output_str[y] & 0xF ); //encode the low nibble
		output.append( 1, static_cast<char>(out_temp) );
	}

	delete [] output_str;
}
Example #17
0
void SpeakPlugin::replace_chars(string& input) // german chars replacement
{
  size_t pos;

  while( (pos = input.find("Ä")) != string::npos)
  {
    input.replace(pos, 2, "Ae");
  }
  while( (pos = input.find("ä")) != string::npos)
  {
    input.replace(pos, 2, "ae");
  }
  while( (pos = input.find("Ü")) != string::npos)
  {
    input.replace(pos, 2, "Ue");
  }
  while( (pos = input.find("ü")) != string::npos)
  {
    input.replace(pos, 2, "ue");
  }
  while( (pos = input.find("Ö")) != string::npos)
  {
    input.replace(pos, 2, "Oe");
  }
  while( (pos = input.find("ö")) != string::npos)
  {
    input.replace(pos, 2, "oe");
  }
  while( (pos = input.find("ß")) != string::npos)
  {
    input.replace(pos, 2, "ss");
  }
  while( (pos = input.find("°")) != string::npos)
  {
    input.erase(pos, 1);
  }

  while( (pos = input.find("€")) != string::npos)
  {
    input.erase( pos, 3);
    if( pos >= input.length())
      pos = input.length() -1;

    size_t tpos = pos;

    if( isdigit(input.at(tpos)))
    {
      while( isdigit(input.at(++tpos)));
      input.insert( tpos, " EUR");
      continue;
    }

    if( isspace(input.at(tpos)))
    {
      tpos--;
      if( isdigit(input.at(tpos)))
      {
        input.insert(pos, " EUR");
        continue;
      }
      if( isspace(input.at(tpos)))
      {
        tpos--;
        if( isdigit(input.at(tpos)))
        {
          input.insert(pos, "EUR");
          continue;
        }
        tpos++;
      }
      tpos++;

      tpos++;
      if( isdigit(input.at(tpos)))
      {
        while( isdigit(input.at(++tpos)));
        input.insert( tpos, " EUR");
        continue;
      }
    }

    input.insert(pos, "EUR");
  }

  while( (pos = input.find("EUR EUR")) != string::npos)
    input.erase(pos, 4);
}
Example #18
0
string compatible(string a, string b){
	string ret;
    if(a == b){
		ret = "00" + a;
		return ret;
	}
    if(a == "INT" && b == "FLOAT"){
		ret ="20INT";
		// cout<<"here2"<<" "<<ret<<endl;
		return ret;
	}
    if(b == "INT" && a == "FLOAT"){
		ret = "20FLOAT";
		return ret;

	}
	string s1 = a.substr(0,5);
	string s2 = b.substr(0,5);
	if(s1 == "array" && s2=="array"){
		s1 = a.substr(0,a.length() - 1);
		std::size_t pos = s1.find(",");
		s1 = s1.substr(pos);
		s1 = s1.substr(1,s1.length() - 1);

		s2 = b.substr(0,b.length() - 1);
		pos = s2.find(",");
		s2 = s2.substr(pos);
		s2 = s2.substr(1,s2.length() - 1);
		if(s1 == s2){
			ret = "00" + a;
			return ret;
		}
		else{
			ret = "NOPE";
			return ret;
		}
	}

	s1 = a.substr(0,6);
	s2 = b.substr(0,6);
	if(s1 == "STRUCT" && s2 == "STRUCT"){
		string s1 = a.substr(7,a.length() - 7);
		for(int i=0; i<s1.length();i++){
			if(s1[i] == ' '){
				s1 = s1.substr(0,i);
				break;
			}
		}

		string s2 = b.substr(7,b.length() - 7);
		for(int i=0; i<s2.length();i++){
			if(s2[i] == ' '){
				s2 = s2.substr(0,i);
				break;
			}
		}

		if(s1 == s2){
			ret = "00"+a;
			return ret;
		}
		else{
			ret = "NOPE";
			return ret;
		}
	}

	s1 = a.substr(0,7);
	s2 = b.substr(0,7);

	if(s1 == "pointer" && s2 == "pointer"){
		s1 = a.substr(8,a.length() - 9);
		s2 = b.substr(8,b.length() - 9);

		if(s1=="VOID"){
			ret = "20" + a;
			return ret;
		}
		else if(s2 == "VOID"){
			ret = "10" + b;
			return ret;
		}

		if(compatible(s1,s2) != "NOPE"){
			string s3 = s1.substr(0,7);
			string s4 = s2.substr(0,7);
			if(s3 == "pointer" || s2 == "pointer"){
				return "NOPE";
			}
			s3 = compatible(s1,s2);
			if(s3[0] == '0'){
				return "00" + a;
			}
			else if(s3[0] == '1'){
				s3 = s3.substr(2,s3.length() - 2);
				ret = + "10pointer(" + s3 + ")";
				return ret;
			}
			else{
				s3 = s3.substr(2,s3.length() - 2);
				ret = + "20pointer(" + s3 + ")";
				return ret;
			}
		}
	}

	s1 = a.substr(0,5);
	s2 = b.substr(0,5);

	if(s1=="point" && s2=="array"){
		// cout<<"here\n";
		s1 = a.substr(8,a.length() - 9);

		s2 = b.substr(0,b.length() - 1);

		std::size_t pos = s2.find(",");
		s2 = s2.substr(pos);
		s2 = s2.substr(1,s2.length() - 1);
		// cout<<s1<<" "<<s2<<endl;
		if(compatible(s1,s2) != "NOPE"){
			string s3 = compatible(s1,s2);
			if(s3[0] == '0'){
				return "00" + a;
			}
			else if(s3[0] == '1'){
				s3 = s3.substr(2,s3.length() - 2);
				ret = + "10pointer(" + s3 + ")";
				return ret;
			}
			else{
				s3 = s3.substr(2,s3.length() - 2);
				ret = + "20pointer(" + s3 + ")";
				return ret;
			}
		}

	}

	// s1 = a.substr(0,5);
	// s2 = b.substr(0,5);
	//
	// if(s1=="array" && s2=="pointer"){
	// 	// cout<<"here\n";
	// 	s2 = b.substr(8,b.length() - 9);
	//
	// 	s1 = a.substr(0,a.length() - 1);
	//
	// 	std::size_t pos = s1.find(",");
	// 	s1 = s1.substr(pos);
	// 	s1 = s1.substr(1,s1.length() - 1);
	// 	// cout<<s1<<" "<<s2<<endl;
	// 	string s3 = compatible(s1,s2);
	// 	if(s3.substr(0,2) == ){
	// 		ret = "00" + a;
	// 		return ret;
	// 	}
	// }

	return "NOPE";

}
/*!
* Extracts and stores logical lines of code.
* Determines and extract logical SLOC to place in the result variable
* using addSLOC function. Each time the addSLOC function is called,
* a new logical SLOC is added. This function assumes that the directive
* is handled before it is called.
*
* \param result counter results
* \param line processed physical line of code
* \param lineBak original physical line of code
* \param strLSLOC processed logical string
* \param strLSLOCBak original logical string
* \param data_continue continuation of a data declaration line
*/
void CSqlCounter::LSLOC(results* result, string line, size_t lineNumber, string lineBak, string &strLSLOC, string &strLSLOCBak, bool &data_continue)
{
	size_t i, ind, nextInd, startInd, endInd, strSize;
	ptrdiff_t j;
	bool trunc_flag	= false, found;
	string exec_keyword, data_keyword;
	list<size_t> slocIndices, eslocIndices, dslocIndices, gslocIndices;

	// find locations of executable keywords
	for (i = 0; i < exec_name_list.size(); i++)
	{
		ind = 0;
		nextInd = 0;
		exec_keyword = exec_name_list.at(i);
		while (ind != string::npos)
		{
			ind = CUtil::FindKeyword(line, exec_keyword, nextInd, TO_END_OF_STRING, false);
			if (ind != string::npos)
			{
				// check for grant, revoke, deny
				if (exec_keyword == "grant" || exec_keyword == "revoke" || exec_keyword == "deny")
				{
					// ignore GRANT OPTION
					if (line.length() <= ind + 12 || CUtil::ToLower(line.substr(ind, 12)) != "grant option")
						gslocIndices.push_back(ind);
				}
				nextInd = ind + 1;
				slocIndices.push_back(ind);
				eslocIndices.push_back(ind);
			}
		}
	}
	eslocIndices.sort();
	eslocIndices.unique();

	// process grant, revoke, deny
	if (gslocIndices.size() > 0)
	{
		slocIndices.sort();
		slocIndices.unique();
	}
	while (gslocIndices.size() > 0)
	{
		ind = gslocIndices.front() + 1;
		gslocIndices.pop_front();
		
		// search for ON, TO, FROM until first non-exec keyword found and clear slocIndices in between
		// (ideally this check would span multiple lines, but we avoid this for now)
		if (ind < line.length())
		{
			nextInd = CUtil::FindKeyword(line, "on", ind, TO_END_OF_STRING, false);
			if (nextInd == string::npos)
			{
				nextInd = CUtil::FindKeyword(line, "to", ind, TO_END_OF_STRING, false);
				if (nextInd == string::npos)
				{
					nextInd = CUtil::FindKeyword(line, "from", ind, TO_END_OF_STRING, false);
					if (nextInd == string::npos)
						nextInd = line.length();
				}
			}
			// clear any slocIndices between these values
			list<size_t>::iterator it, it2;
			for (it = eslocIndices.begin(), it2 = slocIndices.begin(); it != eslocIndices.end(); ++it, ++it2)
			{
				if (*it >= ind && *it < nextInd)
				{
					*it = INVALID_POSITION;
					*it2 = INVALID_POSITION;
				}
			}
			eslocIndices.remove(INVALID_POSITION);
			slocIndices.remove(INVALID_POSITION);
		}
	}

	// find locations of data keywords
	for (i = 0; i < data_name_list.size(); i++)
	{
		ind = 0;
		nextInd = 0;
		data_keyword = data_name_list.at(i);
		while (ind != string::npos)
		{
			ind = CUtil::FindKeyword(line, data_keyword, nextInd, TO_END_OF_STRING, false);
			if (ind != string::npos)
			{
				// try to get variable name (var name is listed before type in SQL)
				nextInd = ind + 1;
				found = false;
				for (j = ind - 1; j >= 0; j--)
				{
					if (line[j] != ' ' && line[j] != '\t')
						found = true;
					else if (found && (line[j] == ' ' || line[j] == '\t' || line[j] == ','))
					{
						ind = j + 1;
						break;
					}
				}
				if (found && j <= 0)
					ind = 1;
				slocIndices.push_back(ind);
				dslocIndices.push_back(ind);
			}
		}
	}
	dslocIndices.sort();
	dslocIndices.unique();

	// process total set of keywords
	slocIndices.sort();
	slocIndices.unique();
	startInd = 0;
	while (slocIndices.size() > 0)
	{
		// get current keyword index
		startInd = slocIndices.front();
		slocIndices.pop_front();
		if (slocIndices.size() > 0)
			endInd = slocIndices.front();
		else
			endInd = string::npos;

		// process continuation
		if (strLSLOCBak.length() > 0)
		{
			strSize = CUtil::TruncateLine(startInd, strLSLOC.length(), this->lsloc_truncate, trunc_flag);
			if (strSize > 0)
			{
				strLSLOC += line.substr(0, strSize);
				strLSLOCBak += lineBak.substr(0, strSize);
			}
			if (result->addSLOC(strLSLOCBak, lineNumber, trunc_flag))
			{
				if (data_continue)
					result->data_lines[LOG]++;
				else
					result->exec_lines[LOG]++;
			}
			strLSLOC = strLSLOCBak = "";
		}
		data_continue = false;

		// determine keyword type
		if (eslocIndices.size() > 0 && eslocIndices.front() == startInd)
			eslocIndices.pop_front();
		else
		{
			dslocIndices.pop_front();
			data_continue = true;
		}

		// process LSLOC
		if (endInd != string::npos)
		{
			strSize = CUtil::TruncateLine(endInd - startInd, 0, this->lsloc_truncate, trunc_flag);
			if (strSize > 0)
			{
				strLSLOC = line.substr(startInd, strSize);
				strLSLOCBak = lineBak.substr(startInd, strSize);
			}
			if (result->addSLOC(strLSLOCBak, lineNumber, trunc_flag))
			{
				if (data_continue)
					result->data_lines[LOG]++;
				else
					result->exec_lines[LOG]++;
			}
			strLSLOC = strLSLOCBak = "";
			startInd = endInd;
		}
	}

	// capture continuing LSLOC
	if (startInd < line.length())
	{
		strSize = CUtil::TruncateLine(line.length() - startInd, strLSLOC.length(), this->lsloc_truncate, trunc_flag);
		if (strSize > 0)
		{
			strLSLOC += line.substr(startInd, strSize);
			strLSLOCBak += lineBak.substr(startInd, strSize);
		}
	}
}
Example #20
0
// Does string begin with substring?
bool CVCUtility::beginsWith(string myString, string mySubstring)
{
	if(myString.length() < mySubstring.length()) return false;
	return (myString.substr(0, mySubstring.length()) == mySubstring);
}
Example #21
0
void RTFGenParser::text(const QString &text)
{
    if (m_res_size)
        return;
    unsigned size = res.length();
    if (size > m_max_size){
        textPos = start_pos;
        m_res_size = size;
        return;
    }
    for (int i = 0; i < (int)(text.length()); i++){
        QChar c = text[i];
        if (c.isSpace()){
            unsigned size = res.length();
            if (size > m_max_size){
                textPos = start_pos + i;
                m_res_size = size;
                return;
            }
        }
        // In Qt, unless you force the paragraph direction with (Left/Right)
        // Ctrl-Shift (also known as Key_Direction_L and Key_Direction_R),
        // the P tag won't have a DIR attribute at all. In such cases, unlike
        // HTML, Qt will render the paragraph LTR or RTL according to the
        // first strong character (as Unicode TR#9 defines). Thus, if the
        // direction isn't known yet, we check each character till we find
        // a strong one.
        if ((m_lastParagraphPos != 0) && (m_paragraphDir == DirUnknown))
        {
            switch(c.direction())
            {
            case QChar::DirL:
                res.insert(m_lastParagraphPos, "\\ltrpar");
                m_paragraphDir = DirLTR;
                break;
            case QChar::DirR:
                res.insert(m_lastParagraphPos, "\\rtlpar");
                m_paragraphDir = DirRTL;
                break;
            default: // to avoid warnings
                break;
            }
        }

        unsigned short u = c.unicode();
        if (c == '\r' || c == '\n')
            continue;
        if ((c == '{') || (c == '}') || (c == '\\')){
            char b[5];
            snprintf(b, sizeof(b), "\\\'%02x", u & 0xFF);
            res += b;
            m_bSpace = false;
            continue;
        }
        if (u < 0x80){
            if (m_bSpace)
                res += ' ';
            res += (char)u;
            m_bSpace = false;
            continue;
        }
        QString s;
        s += c;
        if (m_codec){
            string plain;
            plain = m_codec->fromUnicode(s);
            if ((plain.length() == 1) && (m_codec->toUnicode(plain.c_str()) == s)){
                char b[5];
                snprintf(b, sizeof(b), "\\\'%02x", plain[0] & 0xFF);
                res += b;
                m_bSpace = false;
                continue;
            }
        }
        res += "\\u";
        res += number(s[0].unicode());
        res += "?";
        m_bSpace = false;
    }
}
Example #22
0
// Does string end with substring?
bool CVCUtility::endsWith(string myString, string mySubstring)
{
	if(myString.length() < mySubstring.length()) return false;
	return (myString.substr(myString.length()-mySubstring.length(), mySubstring.length()) == mySubstring);
}
Example #23
0
bool isOneOff(const string &a, const string &b) {
    int cnt = 0, len = a.length();
    for (int i = 0; cnt < 2 && i < len; i++) if (a[i] != b[i]) cnt++;
    return (cnt == 1);
}
Example #24
0
// Is this a substring?
bool CVCUtility::substring(string myString, string mySubstring)
{
	if(myString.length() < mySubstring.length()) return false;
	return (myString.find(mySubstring)>0);
}
// Insert (another) line of text into the interpreter.
LuaInterpreter::State LuaInterpreter::insertLine( string& line, bool fInsertInOutput )
{
    if( fInsertInOutput == true )
    {
        mOutput += line;
        mOutput += '\n';
    }
 
    if( mFirstLine && line.substr(0,1) == "=" )
    {
        line = "return " + line.substr(1, line.length()-1 );
    }
 
    mCurrentStatement += " ";
    mCurrentStatement += line;
    mFirstLine = false;
 
    mState = LI_READY;
 
    if( luaL_loadstring( mL, mCurrentStatement.c_str() ) )
    {
        string error( lua_tostring( mL, -1 ) );
        lua_pop( mL, 1 );
 
        // If the error is not a syntax error cuased by not enough of the
        // statement been yet entered...
        if( error.substr( error.length()-6, 5 ) != "<eof>" )
        {
            mOutput += error;
            mOutput += "\n";
            mOutput += LI_PROMPT;
            mCurrentStatement.clear();
            mState = LI_ERROR;
        }
        // Otherwise...
        else
        {
            // Secondary prompt
            mPrompt = LI_PROMPT2;
 
            mState = LI_NEED_MORE_INPUT;
        }
        return mState;
    }
    else
    {
        // The statment compiled correctly, now run it.
 
        if( lua_pcall( mL, 0, LUA_MULTRET, 0 ) )
        {
            // The error message (if any) will be added to the output as part
            // of the stack reporting.
            lua_gc( mL, LUA_GCCOLLECT, 0 );     // Do a full garbage collection on errors.
            mState = LI_ERROR;
        }
    }
 
    mCurrentStatement.clear();
    mFirstLine = true;
 
    // Report stack contents
    if ( lua_gettop(mL) > 0)
    {
      lua_getglobal(mL, "print");
      lua_insert(mL, 1);
      lua_pcall(mL, lua_gettop(mL)-1, 0, 0);
    }
 
 
    mPrompt = LI_PROMPT;
 
    // Clear stack
    lua_settop( mL, 0 );
 
    return mState;
}
bool findHeader(const string& hdrs,const string& hdr_name, 
		size_t& pos1, size_t& pos2, size_t& hdr_start)
{
  unsigned int p;
  char* hdr = strdup(hdr_name.c_str());
  const char* hdrs_c = hdrs.c_str();
  char* hdr_c = hdr;
  const char* hdrs_end = hdrs_c + hdrs.length();
  const char* hdr_end = hdr_c + hdr_name.length(); 

  while(hdr_c != hdr_end){
    if('A' <= *hdr_c && *hdr_c <= 'Z')
      *hdr_c -= 'A' - 'a';
    hdr_c++;
  }

  while(hdrs_c != hdrs_end){

    hdr_c = hdr;

    while((hdrs_c != hdrs_end) && (hdr_c != hdr_end)){

      char c = *hdrs_c;
      if('A' <= *hdrs_c && *hdrs_c <= 'Z')
	c -= 'A' - 'a';

      if(c != *hdr_c)
	break;

      hdr_c++;
      hdrs_c++;
    }

    if(hdr_c == hdr_end)
      break;

    while((hdrs_c != hdrs_end) && (*hdrs_c != '\n'))
      hdrs_c++;

    if(hdrs_c != hdrs_end)
      hdrs_c++;
  }
    
  if(hdr_c == hdr_end){
    hdr_start = hdrs_c - hdrs.c_str();;

    while((hdrs_c != hdrs_end) && (*hdrs_c == ' '))
      hdrs_c++;

    if((hdrs_c != hdrs_end) && (*hdrs_c == ':')){

      hdrs_c++;
      while((hdrs_c != hdrs_end) && (*hdrs_c == ' '))
	hdrs_c++;
	    
      p = hdrs_c - hdrs.c_str();
	    
      string::size_type p_end;
      if((p_end = hdrs.find('\n',p)) != string::npos){
		
	free(hdr);
	// return hdrs.substr(p,p_end-p);
	pos1 = p;
	pos2 = p_end;
	return true;
      }
    }
  }

  free(hdr);
  //    return "";
  return false;
}