void FruitSortingApp::loadProfile(string & prof_file_path, FILE *& prof_file)
{
	//char *prof_file_path;
	cout << "enter profile name which must be present in profiles folder...\n";
	cin >> prof_file_path;
	prof_file_path.insert(0, "profiles/");
	//prof_file_path=strcat("profiles/",prof_file_path);
	prof_file = fopen(prof_file_path.data(), "r");
	if(prof_file!=NULL)
	{
		fscanf(prof_file,"%d",&num_of_groups);
		int i;//,hue[num_of_groups],area[num_of_groups];
		for(i=0;i<num_of_groups;i++)
		{
			fscanf(prof_file,"%d %d\n",&hue[i],&area[i]);
			//cout<<hue[i]<<" "<<area[i];
		}

		fscanf(prof_file,"%lf\n",&alpha);
	}
	else
	{
		cout<<"Cannot open profile..exiting\n";
		exit(1);
	}
	cout << "Value has been read successfully from profile\n";
}
Example #2
0
/* The function calculates the Italian tax code related to the personal data
 * It returns a string of 5 characters 
 */
string CalcDate(string day, unsigned short int month, string year, char gender)
{
    // The characters correspond to the number of the month
    const char mounthcode[12] = { 'A', 'B', 'C', 'D', 'E', 'H', 'L', 'M', 'P', 'R', 'S', 'T' };
    const short int MAXLONG = day.size();
    
    short int support;
    string result;

    // It's refers to the year
    result = year.substr(2,3);

    // It's refers to the month
    month--;
    result += mounthcode[month];

    // It's refers to the date of birth and the gender
    if(gender == 'M' || gender == 'm') {
        if(MAXLONG <= 1) {
            day.insert(0, 1, '0'); // example: "3" -> "03"
        }
        result += day;
    }
    else {
        support = stoi(day); // "stoi()" converts the string to an integer
        support += 40;
        result += to_string(support);
    }
    
    return result;
}
	void _FixAttributeIndexingType( string& str, size_t begin )//修复索引Attribute的问题
	{
		set<uint> handled;
		size_t start_pos = begin;
		do 
		{
			start_pos = str.find("[", start_pos);
			if ( start_pos != eastl::string::npos )
			{
				string vbname = _GetVariableName( str, start_pos, -1 );
				if ( handled.end() == handled.find(  Utility::HashCode( vbname ) ) )
				{
					handled.insert( Utility::HashCode( vbname ) );
					string type;
					if ( _VariableModifier_Type(str, vbname, "attribute", type ) )
					{
						string fixtoname = vbname + "_fixed_bohge";
						handled.insert( Utility::HashCode( fixtoname ) );
						string eqution = type + fixtoname + " = " + vbname + ";\r\n";
						Utility::ReplaceAllParamterName( str, vbname, fixtoname, start_pos-vbname.size() );
						str.insert( begin, eqution );
					}
				}
				start_pos += 1;
			}
		} while ( start_pos != eastl::string::npos );
	}
Example #4
0
void replace_multiple_string(string& str, string to_find, string to_replace) {
	size_t pos;
	while ((pos = str.find(to_find)) != string::npos) {
		str.erase(pos, to_find.length());
		str.insert(pos, to_replace);
	}
}
void trimto(const string& source,string& result)
{
    istringstream sin(source);
    string temp;
    while(sin>>temp)
        result.insert(result.end(),temp.begin(),temp.end());
}
Example #6
0
void putInLine(unsigned long int val, string& str){
  str.clear();
  while (val > 0){
    str.insert(0,1,(char)((val%10) + 48));
    val /= 10;
  }
}
Example #7
0
int HMM::divide_sentence(string &sentence,std::string seperator)
{
	int count=0;
	int obs[MAX_LEN];//缓存区,总是new会降低速度
	int *p_obs;
	int *res;
	int states[NUM_STATE]={B,M,E,S};
	int len_obs=sentence.length()/2;
	
	if(len_obs > MAX_LEN *2 )
		p_obs=new int[len_obs];
	else p_obs=obs;
	
	for(int i=0;i<len_obs;i++)
		p_obs[i]=word2num(sentence[i<<1],sentence[(i<<1)+1]);
	res=Viterbi(NUM_OBS,NUM_STATE,len_obs,
				p_obs,states,start_p,
				(double **)trans_p,(double **)emit_p);
	
	for(int i=len_obs-1;i>=0;i--)//模型没问题,就最后分段这出问题了,注意下标。。。在纸上多画画,不要总是空想
	{
		if(res[i]==E || res[i]==S)
		{
			sentence.insert((i+1)<<1,seperator);
			count++;
		}
	}
	if(res[len_obs-1]!=E && res[len_obs-1]!=S)
		sentence+=seperator;//若最后不是结束符,强制加结束符
	if(len_obs > MAX_LEN )
		delete[] p_obs;
	delete[] res;
	return count;
}
Example #8
0
void 
filter_text( vector<string,allocator> *words, string filter )
{
	vector<string,allocator>::iterator iter = words->begin();
	vector<string,allocator>::iterator iter_end = words->end();

        if ( ! filter.size() )
             filter.insert( 0, "\".," );

        cout << "filter elements: " << filter << endl;

	while ( iter != iter_end )
	{
		cout << "filter_text: " << *iter << endl; 

                string::size_type pos = 0;
                while (( pos = (*iter).find_first_of( filter, pos )) != string::npos )
                {
                        cout << "found! : pos: " 
			     << pos << "\t" 
			     << (*iter)[pos] << endl;

			// this is wrong: erases from pos to npos
                        // (*iter).erase(pos);
                        (*iter).erase(pos,1);

			cout << "after: " << *iter << endl;
                }

		cout << "finished with word: " << *iter << endl;

		iter++;
	}
}
Example #9
0
 string addBinary(string a, string b) {
     //swap a and b if a is shorter than b
     //we will store the answer in a
     if(a.length() < b.length())
         a.swap(b);
     //@l1 the index of a[]
     //@l2 the index of b[]
     int l1 = a.length()-1;
     int l2 = b.length()-1;
     int add = 0;
     //process the common bits
     for(; l1>=0 && l2>=0; --l1,--l2)
         {
             int c = a[l1]-'0';
             int d = b[l2]-'0';
             int e = c+d+add;
             a[l1] = e%2+'0';
             add = e/2;
         }
     //process the last bits in a
     for(; l1>=0; --l1)
         {
             int c = a[l1]-'0';
             int e = c+add;
             a[l1] = e%2+'0';
             add = e/2;
         }
     //insert an 1 at the first position
     if(1==add)
         a.insert(0,1,'1');
     return a;
 }
Example #10
0
int main(int argc, const char * argv[]) {
    int t;
    string st;
    cin >> t;
    while (t--) {
        cin >> st;
        int sl = st.size();
        int mx = 0;
        for (int i = 0; i <= sl; i++) {
            for (char ch = 0; ch < 3; ch++) {
                tmp = st;
                tmp.insert(i, r[ch]);
                int tot = 0;
                while (true) {
                    int tm = func(tmp);
                    tot += tm;
                    if (tm == 0) {
                        break;
                    }
                }
                if (tot > mx) {
                    mx = tot;
                }
            }
        }
        cout << mx << endl;
    }
}
Example #11
0
int main()
{
	
	int T, count, ret;
	int MAX;
	cin >> T;
	while(T--)
	{
		cin >> temp;
		MAX = 0;
		for(int k = 0; k < temp.length(); k++)
		{
			for(int l = 0; l < 3; l++) 
			{
				count = 0;
				
				str = temp;
				str.insert(k, 1, 'A' + l);
				while(ret = remove()) count += ret;
				
				MAX = max(MAX, count);
			}	
		}
		cout << MAX << endl;
	}
	return 0;
} 
Example #12
0
string incrementPassword(string input, int pos) {
	char lastChar = input.at(pos);

	if (lastChar != 'z') {
		lastChar++;
		input.erase(pos, 1);
		input.insert(pos, 1, lastChar);
	}
	else {
		lastChar = 'a';
		input.erase(pos, 1);
		input.insert(pos, 1, lastChar);
		return incrementPassword(input, pos - 1);
	}
	return input;
}
Example #13
0
void regular(string &file_contents, const char * pattern, string replace)
{
	int cflags = REG_EXTENDED | REG_ICASE ;;
	int status, index, length;
	const size_t nmatch = 1;
	regmatch_t pmatch[nmatch];
	regex_t reg;

	regcomp(&reg, pattern, cflags);
	index = 0;

	while ((file_contents.c_str() + index))
	{
		status = regexec(&reg, file_contents.c_str() + index, nmatch, pmatch, 0);

//		cout<<file_contents.c_str() + index<<endl;
		if (status == REG_NOMATCH){
			cout<<"No Match"<<endl;
			break;
		}
		else if (status == 0)
		{
			length = pmatch[0].rm_eo - pmatch[0].rm_so;

			file_contents.replace(index + pmatch[0].rm_so, length, "");
			file_contents.insert(index + pmatch[0].rm_so, replace);
			index += pmatch[0].rm_eo + replace.length() - length;
		}

	}

}
Example #14
0
// C++ equivalent for PHP's escapeshellarg function.
string filter_url_escape_shell_argument (string argument)
{
  argument = filter_string_str_replace ("'", "\\'", argument);
  argument.insert (0, "'");
  argument.append ("'");
  return argument;
}
Example #15
0
    string addBinary(string a, string b) {
        if (a.length() == 0 || b.length() == 0) {
			return "";
		}

		if (a.length() > b.length()) {
			swap(a, b);
		}

		// a is shorter
		int la = a.length();
		int lb = b.length();

		for (int i = la; i < lb; i ++) {
			a = '0' + a;
		}

		int ca = 0;
		for (int i = lb - 1; i >= 0; i --) {
			b[i] += a[i] - '0' + ca;
			if (b[i] - '0' >= 2) {
				ca = 1;
			} else {
				ca = 0;
			}
			b[i] = (b[i] - '0') % 2 + '0';
		}

		if (ca) {
			b.insert(b.begin(), '1');
		}

		return b;
    }
void addOptionTag(string& hdrs, const string& hdr_name, const string& tag) {
  // see if option tag already exists
  string options = getHeader(hdrs, hdr_name);
  if (options.size()) {
    std::vector<string> option_entries = explode(options, ",");
    for (std::vector<string>::iterator it=option_entries.begin();
	 it != option_entries.end(); it++) {
      if (trim(*it," ") == tag)
	// found - no need to add again
	return;
    }
    // tag not found - add our tag to the (first) hdr_name header
    size_t pos1; size_t pos2; size_t hdr_start;
    if (!findHeader(hdrs, hdr_name, 0, pos1, pos2, hdr_start)) {
      ERROR("internal error: header '%s' disappeared in-between (hdrs = '%s'!\n",
	    hdr_name.c_str(), hdrs.c_str());
      hdrs += hdr_name + COLSP + tag + CRLF;
      return;
    }

    hdrs.insert(pos1, tag+", ");

  } else {
    // hdr does not exist - add it
    hdrs += hdr_name + COLSP + tag + CRLF;
  }
}
Example #17
0
// This filter removes the username and password components from the $url.
string filter_url_remove_username_password (string url)
{
  string slashes = "//";
  size_t pos = url.find (slashes);

  // Consider the following URL for github:
  // https://username:[email protected]/username/repository.git
  if (filter_string_replace_between (url, slashes, ":", "")) {
    if (pos != string::npos) url.insert (pos, slashes);
  }
  if (filter_string_replace_between (url, slashes, "@", "")) {
    if (pos != string::npos) url.insert (pos, slashes);
  }
  
  return url;
}
	void StringConverter::ToSingle (const wstring &wstr, string &str, bool noThrow)
	{
		try
		{
			mbstate_t mbState;
			Memory::Zero (&mbState, sizeof (mbState));
			const wchar_t *src = wstr.c_str();

			size_t size = wcsrtombs (nullptr, &src, 0, &mbState);
			if (size == (size_t) -1)
				throw StringConversionFailed (SRC_POS, wstr);

			vector <char> buf (size + 1);
			Memory::Zero (&mbState, sizeof (mbState));

			if ((size = wcsrtombs (&buf[0], &src, buf.size(), &mbState)) == (size_t) -1)
				throw StringConversionFailed (SRC_POS, wstr);

			str.clear();
			str.insert (0, &buf.front(), size);
			Memory::Erase (&buf.front(), buf.size());
		}
		catch (...)
		{
			if (!noThrow)
				throw;
		}
	}
Example #19
0
bool get_full_path(string& name, string& path)
{
	DWORD error, path_size;

	path_size = GetCurrentDirectoryA(0, NULL);
	if (path_size == 0) {
		error = GetLastError();
		cout << "Error, GetCurrentDirectoryA() failed with code: " << error << endl;
		return false;
	}

	path.insert(path.begin(), path_size, '\0');

	path_size = GetCurrentDirectoryA(path_size, const_cast<char*>(path.c_str()));
	if (path_size == 0) {
		error = GetLastError();
		cout << "Error, GetCurrentDirectoryA() failed with code: " << error << endl;
		return false;
	}

	path.pop_back();
	

	path += '\\';
	path += name;

	return true;
}
Example #20
0
string HtoB3 (string x)
{
	string y = "" ;
	while(x.size() != 3 && x.size() != 4)
	{
		x.insert(0 , "0");
	}
	for (int j= 0 ; j< x.size() ; ++j)
	{
		y+= " ";
		if(x[j] == '0') y+= "0000" ;
		else if (x[j] == '1') y+= "0001" ;
		else if (x[j] == '2') y+= "0010" ;
		else if (x[j] == '3') y+= "0011" ;
		else if (x[j] == '4') y+= "0100" ;
		else if (x[j] == '5') y+= "0101" ;
		else if (x[j] == '6') y+= "0110" ;
		else if (x[j] == '7') y+= "0111" ;
		else if (x[j] == '8') y+= "1000" ;
		else if (x[j] == '9') y+= "1001" ;
		else if (x[j] == 'A') y+= "1010" ;
		else if (x[j] == 'B') y+= "1011" ;
		else if (x[j] == 'C') y+= "1100" ;
		else if (x[j] == 'D') y+= "1101" ;
		else if (x[j] == 'E') y+= "1110" ;
		else if (x[j] == 'F') y+= "1111" ;
	}

	return y;
}
Example #21
0
bool AutoImporter::validate(const DataDescriptor* pDescriptor,
                            const vector<const DataDescriptor*>& importedDescriptors,
                            string& errorMessage) const
{
    if (pDescriptor == NULL)
    {
        return NULL;
    }

    bool bValid = false;

    Importer* pImporter = const_cast<AutoImporter*>(this)->findImporter(pDescriptor);
    if (pImporter != NULL)
    {
        bValid = pImporter->validate(pDescriptor, importedDescriptors, errorMessage);
        if (errorMessage.empty() == false)
        {
            VERIFY(mpPlugIn != NULL);
            string importerName = mpPlugIn->getName();
            errorMessage.insert(0, importerName + ":\n");
        }
    }

    return bValid;
}
Example #22
0
bool FindFileInTree(const string & directory, string & filename)
{
  bool found = false;
  string wildcard = directory;
  wildcard += "*.*";

  WIN32_FIND_DATA fileinfo;
  HANDLE hFindFile = FindFirstFile(wildcard.c_str(), &fileinfo);
  if (hFindFile != INVALID_HANDLE_VALUE) {
    do {
      if (stricmp(fileinfo.cFileName, filename.c_str()) == 0) {
        filename.insert(0, directory);
        found = true;
        break;
      }

      string subdir = GetFullPathNameString(directory + fileinfo.cFileName);
      if (IsUsableDirectory(fileinfo) && !DirExcluded(subdir)) {
        subdir += '\\';

        found = FindFileInTree(subdir, filename);
        if (found)
          break;
      }
    } while (FindNextFile(hFindFile, &fileinfo));

    FindClose(hFindFile);
  }

  return found;
}
 string addstr(string num1, string num2){
     int n=abs(int(num1.length())-int(num2.length()));
     string str(n,'0');
     if(num1.length()<num2.length()) num1.insert(0,str);
     else num2.insert(0,str);
     int carry=0;
     n=int(num1.length());
     string res(n,'0');
     for(int i=n-1; i>=0; --i){
         int temp=(num1[i]-'0')+(num2[i]-'0')+carry;
         res[i]=temp%10+'0';
         carry=temp/10;
     }
     if(carry) res.insert(res.begin(),carry+'0');
     return res;
 }
Example #24
0
string CsvStreamer::sanitize(string str)
{
	size_t quote_pos = str.find('"');
	bool needs_quotes = quote_pos != string::npos
						|| str.find(this->delimiter) != string::npos
						|| str.find('\r') != string::npos
						|| str.find('\n') != string::npos
						|| str[0] == ' '
						|| str[str.length() - 1] == ' ';
	
	
	if (needs_quotes)
	{
		// First escape quotes by turning any " in the data into "" ...
		
		// (Note: The second condition is a failsafe against a bug that creeps up
		// sometimes in 64-bit; quote_pos may be at or near unsigned int max value,
		// yet apparently still != string::npos... causing of range errors.)
		while (quote_pos != string::npos && quote_pos < str.length())
		{
			str.insert(quote_pos, "\"");
			quote_pos = str.find('"', quote_pos + 2);	// Skip over these quotes and go to the next ones
		}
		
		// ... then wrap the data in quotes
		str = '"' + str + '"';
	}
	
	return str;
}
void replace_string(string &s, const string &oldVal, const string &newVal)
{
    if (oldVal.size() == 0 /*|| newVal.size() == 0*/)
    {
        return;
    }

    auto oldValSize = oldVal.size();
    auto oldIterCur = oldVal.begin();
    auto newIter = newVal.begin();
    auto sIterPrev = s.begin();
    auto sIterCur = sIterPrev;
    while (sIterPrev <= s.end() - oldValSize)
    {
        oldIterCur = oldVal.begin();
        sIterCur = sIterPrev;
        while (oldIterCur != oldVal.end() && *oldIterCur == *sIterCur)
        {
            ++oldIterCur;
            ++sIterCur;
        }
        if (oldIterCur == oldVal.end())
        {
            sIterPrev = s.erase(sIterPrev, sIterCur);
            if (newVal.size())
            {
                sIterPrev = s.insert(sIterPrev, newVal.begin(), newVal.end());
                sIterPrev += newVal.size();
            }
        }
        else
            ++sIterPrev;
    }

}
Example #26
0
// report error
VOID SANDBOX::Error(string msg)
{
    if (msg.length() > 0 && msg[0] != '\n')
    {
        msg = "\n" + msg;
    }

    string::size_type pos = msg.length() > 1 ? msg.length() - 2 : 0;

    // prefix every line
    for (pos = msg.find_last_of('\n', pos);
         pos != string::npos;
         pos = (pos == 0 ? string::npos : msg.find_last_of('\n', pos-1)))
    {
        if (pos == msg.length() - 1)
        {
            msg += "Fence: \n";
        }
        else
        {
            msg.insert(pos + 1, "Fence: ");
        }
    }

    cerr << msg << endl << flush;
    fflush(NULL);

    exit(1);
}
Example #27
0
// 将两个字符串形式表示的非负整数进行相加操作,返回字符串表示的结果。
string add(string number1, string number2)
{
    // 将结果保存在字符串number1中,为了相加方便,调整加数,使得第一个加数的数位
    // 总是大于第二个加数的数位。由于两个正数相加,和的数位最多为两个加数数位较大值
    // 加一,可以预先分配存储空间以方便计算。
    if (number1.length() < number2.length())
        number1.swap(number2);
    number1.insert(number1.begin(), '0');

    // 相加时从低位开始加。初始时进位为0。由于字符串中保存的是数位的ASCII码字符,
    // 需要做相应的转换,使之成为对应的数字值。当前的数位为模基数的值,进位则为除
    // 基数的值。
    int carry = 0, i = number1.length() - 1, j = number2.length() - 1;
    for (; i >= 0; i--, j--)
    {
        int sum = number1[i] - '0' + (j >= 0 ? (number2[j] - '0') : 0) + carry;
        number1[i] = sum % BASE + '0';
        carry = sum / BASE;
    }

    // 移除前导0。
    zeroJustify(number1);

    return number1;
}
Example #28
0
File: main-fz.cpp Project: siala/SM
void write_solution(FlatZinc::FlatZincModel *fm, string filename)
{
  if (fm->finished())
    {
      //cout << fm->verif_constraints.size() << filename <<endl;
      unsigned int __size=filename.size();
      for (__size; __size>0; __size--)
	if (filename[__size-1] == '/')
	  break;
      filename.insert(__size,"sol_" );

      ofstream myfile;
      myfile.open (filename.c_str());

      //cout << filename <<endl;
      for (unsigned int i = 0; i < fm->verif_constraints.size() ; i++)
	{
	  if (fm->verif_constraints[i].first != "int_in")
	    {
	      myfile << "constraint " << fm->verif_constraints[i].first << "(" ;
	      int size = fm->verif_constraints[i].second.size();
	      for (unsigned int j = 0; j <size ; j++)
		{
		  myfile << fm->verif_constraints[i].second[j].get_string() ;
		  if (j< (size -1))
		    myfile << " , ";
		}
	      myfile << ");" << endl;
	    }
	}
      myfile <<"solve satisfy;" << endl;
      myfile.close();
      std::cout <<" c DONE" << endl;
    }
}
Example #29
0
string
urlDecode(string urlencoded)
{
  /* URL Encoding seems to be %<hex> so all we should have
   * to do is replace %<hex> with &#x<hex>; to output these
   * characters in HTML.
   */
  string output;
  string x;
  
  for (int i = 0; i < urlencoded.length(); i++)
	{
	  if (urlencoded[i] == '%')
		{

		  // grab the character from the two-digit HEX in the the string
		  x = hexToChar(urlencoded.substr(i+1, 2));
			
		  // ERASE the %01 characters...
		  urlencoded.erase(i, 3);

		  // INSERT the character literal that we're replacing
		  urlencoded.insert(i, x);
		  
		}
	  else if (urlencoded[i] == '+')
		{
		  urlencoded[i] = ' ';
		}

	}
  return urlencoded;
  
}
Example #30
0
void muzzley::HTTPRepT::stringify(string& _out) {
	_out.insert(_out.length(), "HTTP/1.1 "),
	_out.insert(_out.length(),  muzzley::status_names[this->__status]);
	_out.insert(_out.length(), CRLF);
	for (auto i : this->__headers) {
		_out.insert(_out.length(), i.first);
		_out.insert(_out.length(), ": ");
		_out.insert(_out.length(), i.second);
		_out.insert(_out.length(), CRLF);
	}
	_out.insert(_out.length(), CRLF);
	_out.insert(_out.length(), this->__body);
}