Example #1
0
void LasSplitor::splitFiles(string resFolder)
{
	double density = this->_ptNum/this->_area;
	double factor = density/4.0;
	double RegionH = 1000.0/factor + 1.0;
	double RegionW = 1000.0/factor + 1.0;

	if(resFolder.at(resFolder.length()-1) != '/')
	{
		resFolder = resFolder + string("/");
	}

	int partN = 0;
	char intTag [4];
	for(double gY=this->_region.minY; gY<=this->_region.maxY; gY+=RegionH)
	{
		for(double gX=this->_region.minX; gX<=this->_region.maxX; gX+=RegionW)
		{
			partN++;
			memset(intTag, 0, sizeof(char)*4);
			sprintf(intTag, "%d", partN);
			string path = resFolder + string(intTag) + ".las";

			Block block;
			block.mbr.minX = gX;
			block.mbr.maxX = gX + RegionW;
			block.mbr.minY = gY;
			block.mbr.maxY = gY + RegionH;
			memset(block.neigh, 0, sizeof(int)*4);
			block.lasIO = NULL;
			block.lasIO = new LasIO(path);
			block.lasIO->open(true);
			this->_blocks.push_back(block);
		}
	}

	//split the las files
	for(vector<LasIO*>::iterator it1=this->_lasIOs.begin(); it1!=this->_lasIOs.end(); ++it1)
	{
		LasIO *lasIO = *it1;
		LASPoint* pts = lasIO->readAllPts();
		LASPoint* pt = NULL;
		int ptNum = lasIO->lasHeader()->records_number;		
		for(int ii=0; ii<ptNum; ++ii)
		{
			pt = &pts[ii];
			for(vector<Block>::iterator it2=this->_blocks.begin(); it2!=this->_blocks.end(); ++it2)
			{
				Block block = *it2;
				if(pt->x>=block.mbr.minX && pt->x<=block.mbr.maxX && pt->y>=block.mbr.minY && pt->y<=block.mbr.maxY)
				{
					block.lasIO->writePt(*pt);
					break;
				}
			}
		}

		if(pts != NULL)
		{
			delete []pts;
			pts = NULL;
		}
	}

	//free memory
	for(vector<LasIO*>::iterator it=this->_lasIOs.begin(); it!=this->_lasIOs.end(); ++it)
	{
		LasIO *lasIO = *it;
		if(lasIO != NULL)
		{
			delete lasIO;
			lasIO = NULL;
		}
	}
	this->_lasIOs.clear();

	//close the file
	for(vector<Block>::iterator it=this->_blocks.begin(); it!=this->_blocks.end(); ++it)
	{
		Block block = *it;
		block.lasIO->close();
		//remove(block.lasIO->lasPath().c_str());
	}

	//if nuber of points less than 1,000,000, it will be merged	
	printf("density : %lf\n", density);
}
Example #2
0
bool EulerUtils::Strings::isPalindrome( string s ) {
    unsigned int len = s.size();
    for ( unsigned int lh_idx=0, rh_idx=(len-1) ; lh_idx<(len/2+1) ; ++lh_idx, --rh_idx )
        if ( s.at(lh_idx) != s.at(rh_idx) ) return false;
    return true;
}
Example #3
0
string toyTetragraphHash(string message) {
    // First, tth divides the message into blocks of 16 letters, ignoring spaces, punctuation, and capitalization
    int characterIndex = 0;
    vector<string> blocksOfCharacters;
    string blockOfCharacters = "";
    blocksOfCharacters.push_back(blockOfCharacters);
    while (true) {
        if (characterIndex >= message.size()) {
            break;
        }
        char character = message.at(characterIndex);
        if ((character >= 'A' && character <= 'Z') || (character >= 'a' && character <= 'z')) {
            if (blocksOfCharacters.at(blocksOfCharacters.size() - 1).size() >= 16) {
                blocksOfCharacters.push_back(blockOfCharacters);
            }
            if (character >= 'A' && character <= 'Z') {
                character += 32;
            }
            blocksOfCharacters.at(blocksOfCharacters.size() - 1) += character;
        }
        characterIndex++;
    }
    
    // If the message length is not divisible by 16, it is padded out with nulls
    while (true) {
        if (blocksOfCharacters.at(blocksOfCharacters.size() - 1).size() < 16) {
            blocksOfCharacters.at(blocksOfCharacters.size() - 1) += 'a';
        } else {
            break;
        }
    }
    
    // blocksOfCharacters
    int blockIndex = 0;
    while (true) {
        // cout << blocksOfCharacters.at(blockIndex) << '\n';
        blockIndex++;
        if (blockIndex >= blocksOfCharacters.size()) {
            break;
        }
    }
    
    // A four-number running total is maintained that starts out with the value (0, 0, 0, 0)
    vector<int> totals(4);
    
    // totals
    int totalIndex = 0;
    while (true) {
        // cout << totals.at(totalIndex) << ' ';
        totalIndex++;
        if (totalIndex >= 4) {
            // cout << '\n';
            break;
        }
    }
    
    // Get the next block of text and arrange it as a row-wise 4 x 4 block of text and covert it to numbers (A = 0, B = 1, ...)
    vector<vector<int>> blocksOfNumbers;
    vector<int> blockOfNumbers;
    blocksOfNumbers.push_back(blockOfNumbers);
    while (true) {
        blockOfCharacters = blocksOfCharacters.at(blocksOfNumbers.size() - 1);
        char character = blockOfCharacters.at(blocksOfNumbers.at(blocksOfNumbers.size() - 1).size());
        blocksOfNumbers.at(blocksOfNumbers.size() - 1).push_back(character - 97);
        if (blocksOfNumbers.at(blocksOfNumbers.size() - 1).size() >= 16) {
            if (blocksOfNumbers.size() < blocksOfCharacters.size()) {
                blocksOfNumbers.push_back(blockOfNumbers);
            } else {
                break;
            }
        }
    }
    
    // blocksOfNumbers
    blockIndex = 0;
    int numberIndex = 0;
    while (true) {
        // cout << blocksOfNumbers.at(blockIndex).at(numberIndex) << ' ';
        numberIndex++;
        if (numberIndex >= 16) {
            // cout << '\n';
            blockIndex++;
            numberIndex = 0;
            if (blockIndex >= blocksOfNumbers.size()) {
                break;
            }
        }
    }
    
    // Then add each column mod 26 and add the result to the running total mod 26
    blockIndex = 0;
    int columnIndex = 0;
    while (true) {
        blockOfNumbers = blocksOfNumbers.at(blockIndex);
        totals.at(columnIndex) += blockOfNumbers.at(columnIndex) + blockOfNumbers.at(columnIndex + 4) + blockOfNumbers.at(columnIndex + 8) + blockOfNumbers.at(columnIndex + 12);
        totals.at(columnIndex) = totals.at(columnIndex) % 26;
        columnIndex++;
        if (columnIndex >= 4) {
            blockIndex++;
            columnIndex = 0;
            if (blockIndex >= blocksOfNumbers.size()) {
                break;
            }
        }
    }
    
    // totals
    totalIndex = 0;
    while (true) {
        // cout << totals.at(totalIndex) << ' ';
        totalIndex++;
        if (totalIndex >= 4) {
            // cout << '\n';
            break;
        }
    }
    
    // Using the matrix from round 1, rotate the first row left by 1, second row left by 2, third row left by 3, and reverse the order of the fourth row
    vector<vector<int>> rotatedBlocks;
    vector<int> rotatedBlock;
    rotatedBlocks.push_back(rotatedBlock);
    while (true) {
        blockOfNumbers = blocksOfNumbers.at(rotatedBlocks.size() - 1);
        vector<int> rotations {1, 2, 3, 0, 6, 7, 4, 5, 11, 8, 9, 10, 15, 14, 13, 12};
        int rotation = rotations.at(rotatedBlocks.at(rotatedBlocks.size() - 1).size());
        rotatedBlocks.at(rotatedBlocks.size() - 1).push_back(blockOfNumbers.at(rotation));
        if (rotatedBlocks.at(rotatedBlocks.size() - 1).size() >= blockOfNumbers.size()) {
            if (rotatedBlocks.size() < blocksOfNumbers.size()) {
                rotatedBlocks.push_back(rotatedBlock);
            } else {
                break;
            }
        }
    }
    
    // rotatedBlocks
    blockIndex = 0;
    numberIndex = 0;
    while (true) {
        // cout << rotatedBlocks.at(blockIndex).at(numberIndex) << ' ';
        numberIndex++;
        if (numberIndex >= 16) {
            // cout << '\n';
            blockIndex++;
            numberIndex = 0;
            if (blockIndex >= rotatedBlocks.size()) {
                break;
            }
        }
    }
    
    // Now add each column mod 26 and add the result to the running total
    blockIndex = 0;
    columnIndex = 0;
    while (true) {
        rotatedBlock = rotatedBlocks.at(blockIndex);
        totals.at(columnIndex) += rotatedBlock.at(columnIndex) + rotatedBlock.at(columnIndex + 4) + rotatedBlock.at(columnIndex + 8) + rotatedBlock.at(columnIndex + 12);
        totals.at(columnIndex) = totals.at(columnIndex) % 26;
        columnIndex++;
        if (columnIndex >= 4) {
            blockIndex++;
            columnIndex = 0;
            if (blockIndex >= rotatedBlocks.size()) {
                break;
            }
        }
    }
    
    // totals
    totalIndex = 0;
    while (true) {
        // cout << totals.at(totalIndex) << ' ';
        totalIndex++;
        if (totalIndex >= 4) {
            // cout << '\n';
            break;
        }
    }
    
    // After the final block is processed, convert the final running total to letters.
    string hash = "";
    totalIndex = 0;
    while (true) {
        hash += totals.at(totalIndex) + 97;
        totalIndex++;
        if (totalIndex >= 4) {
            break;
        }
    }
    
    return hash;
}
Example #4
0
void Codeinepad::to_lower(string &s)
{
	for (size_t i = 0; i < s.size(); i++)
		s.at(i) = tolower(s.at(i));
}
Example #5
0
 void Scope::validateObjectIdString(const string& str) {
     uassert(10448, "invalid object id: length", str.size() == 24);
     for (size_t i = 0; i < str.size(); i++)
         uassert(10430,  "invalid object id: not hex", std::isxdigit(str.at(i)));
 }
Example #6
0
		//	Checks if there is a '#' at the front of the string
		bool checkComment(string str){
			if (str.at(0) == '#'){
				return true;
			}
			return false;
		}
//comment it out from actual implementation when testing is done...
void print_alignment(vector<pair<char, char> >& alignment, string& ref, string& read, int ref_position, 
			int read_position, int step, fragment_alignment &fragment_alignment_info, bool print, ofstream& fp_detail)
{
	int i, k, index = 0;
	int updated_index;
	int fragment_count = 0;
	int start = 0, end = -1;
	int  score = 0;
	bool flag_ref = false;
	bool flag_read = false;
	bool flag_break = false;
	int ref_start, ref_end;
	int read_start, read_end;

	ref_start = ref_position;//04-01-15
	read_start = read_position;

	while(index < alignment.size())
	{
		flag_break = false;
		if(DEBUG == 99)
			fp_detail << ref_position << "\t    ";
		for(i = index, k = 0; i < alignment.size() && k < BREAKAT; i++, k++)
		{
			if(alignment[i].second == '.')//03-26-15
			{
				updated_index = i;
				flag_break = true;
				break;
			}

			if(DEBUG == 99)	
				fp_detail << alignment[i].first;
			
			if(alignment[i].first != '-')
			{
				/*
				if(flag_ref == false)
				{
					if(alignment[i].first != '-')//03-26-15
					//if(alignment[i].first == alignment[i].second && alignment[i].first != '-')
					{
						start = i;
						flag_ref = true;
						ref_start = ref_position;
						ref_end = ref_position;
					}
				}
				else
				{
					if(alignment[i].first != '-')//03-26-15
					//if(alignment[i].first == alignment[i].second && alignment[i].first != '-')
                                        {
						end = i;
                                                ref_end = ref_position;
                                        }

				}
				*/
				assert(alignment[i].first == ref.at(ref_position));//03-25-15
				ref_position += step;
			}
			
		}
		//cout << "\t" << ref_position;
		
		if(DEBUG == 99)
		{
			fp_detail << std::right << std::setw(12) << (ref_position - step); 
			//printf("%12d", ref_position - step);
			fp_detail << endl;
			fp_detail << "\t    ";
		}

		for(i = index, k = 0; i < alignment.size() && k < BREAKAT; i++, k++)
		{
			if(alignment[i].second == '.')
				break;
			if(alignment[i].first == alignment[i].second && alignment[i].first != '-')
			{
				if(DEBUG == 99)
					fp_detail << "|";
				score += 1;
			}
			else
				if(DEBUG == 99)
					fp_detail << " ";
		}

		if(DEBUG == 99)
		{
			fp_detail << endl;
			fp_detail << read_position << "\t    ";
		}
		for(i = index, k = 0; i < alignment.size() && k < BREAKAT; i++, k++)
		{
			if(alignment[i].second == '.')//03-26-15
				break;
			if(alignment[i].second == 'o')
			{
				if(DEBUG == 99)
					fp_detail << '-';
			}
			else
			{
				if(DEBUG == 99)
					fp_detail << alignment[i].second;
			}
			if(alignment[i].second != '-')
			{
				/*
				if(flag_read == false)
                                {
					if(alignment[i].first != '-')//03-26-15
                                        //if(alignment[i].first == alignment[i].second && alignment[i].first != '-')
                                        {
                                                flag_read = true;
                                                read_start = read_position;
                                                read_end = read_position;
                                        }
                                }
                                else
                                {
					if(alignment[i].first != '-')//03-26-15
                                        //if(alignment[i].first == alignment[i].second && alignment[i].first != '-')
                                        {
                                                read_end = read_position;
                                        }

                                }
				*/
				//cout << endl << alignment[i].second << " VS " << read.at(read_position) << endl;
				assert(alignment[i].second == read.at(read_position));
				read_position += step;
			}
			
		}

		if(DEBUG == 99)
		{	
			fp_detail << std::right << std::setw(12) << (read_position - step);
			//printf("%12d", read_position - step);
			fp_detail << endl;
			fp_detail << endl;
		}
		if(flag_break == true)
		{
			break;
			index = updated_index;
			while(alignment[index].second == '.')
				index += 1;
			//while(ref_position < fragment_alignment_info.fragment_ind[fragment_count].first &&
			//	read_position < fragment_alignment_info.fragment_ind[fragment_count].second)
			fragment_count += 1;
			ref_position = fragment_alignment_info.fragment_ind[fragment_count].first;
			read_position = fragment_alignment_info.fragment_ind[fragment_count].second;
			cout << "Next ref_position = " << ref_position << ", And read_position = " << read_position << endl;
			cout << "BREAK##########################################################################DANCE" << endl << endl;
		}
		else
			index += BREAKAT;
	}

	ref_end = ref_position;//04-01-15
	read_end = read_position;
	start = 0;
	end = alignment.size() - 1;

	if(print == true)
		return;

	fragment_alignment_info.ref_start = ref_start;
        fragment_alignment_info.ref_end = ref_end - 1;//<= end

	fragment_alignment_info.read_start = read_start;
	fragment_alignment_info.read_end = read_end - 1;//<= end

	for(i = start; i <= end; i++)
	{
		fragment_alignment_info.alignment.push_back(alignment[i]);
	}
	fragment_alignment_info.end_to_end = alignment;
	fragment_alignment_info.identity_match = score;
	fragment_alignment_info.total_len = fragment_alignment_info.alignment.size();
}
Example #8
0
void DFAState(string str){
    char c;
    int s = 1;
    //cout << "Current State: " << s << endl;
    bool wwwCheck = true;
    for(int i = 0; i < str.length(); i++){
        c = str.at(i);
        cout << "Character read: " << c << endl;
        cout << "Current State: q" << s << endl;
        
        /*
        if(s < 4){
            if(c == 'w'){
                s++;
                continue;
            }
            else{
                cout << "trap state1" << endl;
                continue;
            }
        }
        else if(s == 4){
            if(c == '.'){
                s++;
                continue;
            }
            else{
                cout << "trap state2" << endl;
                continue;
            }
        }
        else if(s == 5){
            if(isalpha(c)){
                s++;
                continue;
            }
            else{
                cout << "trap state3" << endl;
                continue;
            }
        }
        else if(s == 6){
            if(isalpha(c)){
                continue;
            }
            else if(c == '.'){
                s++;
                continue;
            }
            else{
                cout << "trap state4" << endl;
            }
        }
        else if(s == 7){
            if(c == 'c'){
                s++;
                continue;
            }
            else{
                cout << "trap state5" << endl;
                continue;
            }
        }
        else if(s == 8){
            if(c == 'o'){
                s++;
                continue;
            }
            else if(c == 'n'){
                s = 11;
                continue;
            }
            else{
                cout << "trap state6" << endl;
                continue;
            }
        }
        else if(s == 9){
            if(c == 'm'){
                s++;
                continue;
            }
            else if(c == '.'){
                s = 12;
                continue;
            }
            else{
                cout << "trap state5" << endl;
                continue;
            }
        }
         */
        
        //checking for only valid characters
        if(islower(c)){
            if(s < 4 && wwwCheck){
                if(c == 'w'){
                    s++;
                    continue;
                }
                else{
                    s = 6;
                    wwwCheck = false;
                    continue;
                }
            
            }
            else if(s == 5){
                s++;
                continue;
            }
            else if(s == 6 || s == 7){
                continue;
            }
            else if(s == 8){
                if(c == 'c'){
                    s++;
                    continue;
                }
            }
            else if(s == 9){
                if(c == 'n'){
                    s = 10;
                    continue;
                }
                else if(c == 'o'){
                    s = 11;
                    continue;
                }
            }
            else if(s == 11){
                if(c == 'm'){
                    s++;
                    continue;
                }
            }
            else if(s == 13){
                if(c == 'c'){
                    s++;
                    continue;
                }
            }
            else if(s == 14){
                if(c == 'n'){
                    s++;
                    continue;
                }
            }
            break;
        }
        else if(c == '.'){
            switch (s) {
                case 4:
                    s++;
                    continue;
                case 6:
                    s = 8;
                    continue;
                case 7:
                    s++;
                    continue;
                case 11:
                    s = 13;
                    continue;
                default:
                    cout << "error on . switch" << endl;
            }
            break;
        }
        else{
            cout << "Invalid character read" << endl;
            break;
        }
       
        
    }
    if(s == 10 || s == 12 || s == 15){
        cout << "Finish State: q" << s << endl;
    }
    else{
        cout << "Trap State: q" << s << endl;
    }
    
}
Example #9
0
int analysisOpt(string &str, string &alphabet)
{
	int Opt = 0;
	int pos = 0;

	if(!str.length())
		return 21;

	if(str.rfind("--help") != -1)
	{
		pos = str.rfind("--help");
		str.erase(pos, pos+6);
		if(str.length())
			return 0;
		return 1;
	} else
	if(str.rfind("--h") != -1)
	{
		pos = str.rfind("-h");
		str.erase(pos, pos+2);
		if(str.length())
			return 0;
		return 1;
	}

	if( (str.rfind("-t encode") != -1) || (str.rfind("--type=encode") != -1) )
	{
		Opt = 21;
		pos = str.rfind("-t encode");
		if(pos>=0)
			str.erase(pos, pos+9);
		else
		{
			pos = str.rfind("--type=encode");
			str.erase(pos, pos+13);
		}
	} else
	if( (str.rfind("-t decode") != -1) || (str.rfind("--type=decode") != -1) )
	{
		Opt = 22;
		pos = str.rfind("-t decode");
		if(pos>=0)
			str.erase(pos, pos+9);
		else
		{
			pos = str.rfind("--type=decode");
			str.erase(pos, pos+13);
		}
	} 
	else
		Opt = 21;

	if(!str.length())
		return Opt;

	if(str.at(str.length()-1) == ' ')
		str.erase(str.length()-1);
	if(str.at(0) == ' ')
		str.erase(0, 1);

	pos = str.find(" ");
	if(pos < 0)
		pos = str.length()-1;
	string opt = str.substr(0, pos+1);
	str.erase(0, pos+1);

	if( ((opt.at(0)) == '-') && ((opt.at(1)) == '-') && ((opt.at(2)) == 'a'))
	{
		pos = opt.find("\"", 12);
		if(pos == -1)
			return 0;
		alphabet = opt.substr(12, pos-1);
		alphabet.erase(alphabet.length()-1);
		if(Opt)
			Opt = Opt + 1100;
		else
			Opt = 11;
	} else
	if( ((opt.at(0)) == '-') && ((opt.at(1)) == 'a') )
	{
		pos = str.find("\"", 1);
		if(pos == -1)
			return 0;
		alphabet = str.substr(1, pos-1);
		str.erase(0, pos+2);
		if(Opt)
			Opt = Opt + 1100;
		else
			Opt = 11;
	}

	if(str.length())
		return 0;

	return Opt;
}
Example #10
0
//建立储存查询条件的结构
//where sage > 20 and sgender = ‘F’;
list<Condition> CreateConditionlist(string condinfo)
{
	list<Condition> condlist;
	int opos, npos;

	condlist.clear();
	//判断是否有where语句
	opos = condinfo.find_first_not_of(" ", 0);
	if (condinfo.at(opos) == ';'){ 
		//没有where语句,查询条件为空
		return condlist;
	}
	else{
		//有where语句
		npos = condinfo.find_first_of(" ", opos);
		string where = condinfo.substr(opos, npos - opos);
		if (where == "where"){
			//符合语法要求
			opos = npos;  //从where后面的语句开始处理
			while (1){
				condinfo = condinfo.substr(opos, condinfo.length() - opos);
				opos = condinfo.find_first_not_of(" \n", 0);
				npos = condinfo.find("and", opos);
				if (opos == -1 || condinfo.at(opos) == ';') break;   //语句结束
				if (npos == string::npos){
					//最后一个查询条件
					//分号结束语句(分号前可能有空格)
					npos = condinfo.find_first_of(";", opos);
					npos++;
				}
				else npos = condinfo.find_first_of(" \n", npos);
				string condstr = condinfo.substr(opos, npos - opos);  
				//id >= '10010' (and/;)

				//所要查询的属性名
				opos = condstr.find_first_not_of(" \n", 0);
				npos = condstr.find_first_of(" \n", opos);
				if (opos == -1 || npos == -1){
					//语法错误
					throw Grammer_error(condstr);
				}
				string attr = condstr.substr(opos, npos - opos);

				//查询的比较条件(== / >= / <...)
				opos = condstr.find_first_not_of(" \n", npos);
				npos = condstr.find_first_of(" \n", opos);
				if (opos == -1 || npos == -1){
					//语法错误
					throw Grammer_error(condstr);
				}
				string type = condstr.substr(opos, npos - opos);
				if (type != "=" && type != ">" && type != ">="
					&& type != "<" && type != "<=" && type != "<>"){
					//比较符号错误
					throw Grammer_error(type);
				}

				//比较值
				opos = condstr.find_first_not_of(" ';\n", npos);
				npos = condstr.find_first_of(" ';\n", opos);  //可能以分号结尾
				if (opos == -1 || npos == -1){
					//语法错误
					throw Grammer_error(condstr);
				}
				string value = condstr.substr(opos, npos - opos);

				struct Condition oneCondition;
				oneCondition.compare_attr = attr;
				oneCondition.compare_type = type;
				oneCondition.compare_value = value;
				
				condlist.push_back(oneCondition);  //向链表中插入一条记录
				
				while (opos++ < condstr.length());

			} //while
		}
		else throw Grammer_error(where); //抛出异常
	}
	return condlist;
}
vector<string> SyntaxHelper::breakStringIntoWords(string str) {
	vector<string> list;
	string word;

	//separate elements
	for (size_t i=0; i<str.length(); i++) {
		char curChar = str.at(i);
		if (curChar=='(') {
			str = str.replace(i, 1, " ( ");
			i+=2;
		}
		if (curChar=='+') {
			str = str.replace(i, 1, " + ");
			i+=2;
		}
		if (curChar=='-') {
			str = str.replace(i, 1, " - ");
			i+=2;
		}
		if (curChar==')') {
			str = str.replace(i, 1, " ) ");
			i+=2;
		}
		if (curChar==';') {
			str = str.replace(i, 1, " ; ");
			i+=2;
		}
		if (curChar==',') {
				str = str.replace(i, 1, " , ");
				i+=2;
		}
		if (curChar=='_') {
			if ((int) i>3 && str.substr(i-4, 9) == "prog_line") {
			} else { 
				str = str.replace(i, 1, " _ ");
				i+=2;
			}
		}
		if (curChar==34) {
			str = str.replace(i, 1, " \" ");
			i+=2;
		}
		if (curChar=='.') {
			str = str.replace(i, 1, " . ");
			i+=2;
		}
		if (curChar=='<') {
			str = str.replace(i, 1, " < ");
			i+=2;
		}
		if (curChar=='>') {
			str = str.replace(i, 1, " > ");
			i+=2;
		}
		if (curChar=='=') {
			str = str.replace(i, 1, " = ");
			i+=2;
		}
		if (curChar=='*') {	// recognize * in relation and * in pattern
			// only add space if * is in pattern
			// make a subtring up to this char
			string sub_str = str.substr(0, i);
			if (sub_str.find_last_of("such that")==string::npos ||
				sub_str.find_last_of("such that")<sub_str.find_last_of("pattern")) {
				str = str.replace(i, 1, " * ");
				i+=2;
			}
		}
	}

	istringstream ss;
	ss.str(str);
	while (ss >> word) {
		list.push_back(word);
	}
	return list;
}
Example #12
0
void handleWithCommand(string command)
{
	int i, j, opos, npos;

	i = 0; j = 0;
	opos = command.find_first_not_of(" \n", 0);
	npos = command.find_first_of(" ", opos);
	string comtype = command.substr(opos, npos - opos);
	//判断命令类型
	if (comtype == "execfile"){
		//打开存储待插入记录的文件
		opos = command.find_first_not_of(" ", npos);
		npos = command.find_first_of(";", opos);
		string filename = command.substr(opos, npos - opos);
		
		ifstream infile;
		char buf[1024];
		infile.open("./student/" + filename, ios::in);
		while (!infile.eof()){
			memset(buf, 0, 1024);
			infile.getline(buf, 1024);
			if (infile.eof()) break;
			string cmd(buf);
			handleWithCommand(cmd);
		}
		cout << "Query OK." << endl;
	}
	else if (comtype == "create"){
		opos = npos + 1;
		npos = command.find_first_of(" ", opos); 
		string object = command.substr(opos, npos - opos);
		if (object == "table"){
			//建表命令
			opos = npos + 1;
			npos = command.find_first_of(" (", opos);
			string tbname = command.substr(opos, npos - opos);
			//创建建表的语法树
			FieldTree* T;
			T = createCreateTableTree(tbname, command.substr(npos, command.length() - npos));
			
			//处理语法树,传参给API
			API_Create_Table(tbname, T);
			/*Table Table(tbname);
			Table.initializeTable(T);
			Table.createTable(); //此处为调用API中create table命令*/

			cout << "Query OK, 0 rows affected." << endl;
			return;
		}
		else if (object == "index"){
			//建索引命令
			opos = npos + 1;
			opos = command.find_first_not_of(" ", opos);  //索引名开始的位置
			npos = command.find_first_of(" ", opos);  //索引名结束后的第一个空格位置
			string indexname = command.substr(opos, npos - opos);
			//创建索引结构
			IndexStruct* I;
			I = createCreateIndexStruct(indexname, command.substr(npos, command.length() - npos));
			
			//传参给API
			API_Create_Index(*I);
			/*Index Idx(indexname);
			Idx.initializeIndex(I);
			Idx.createIndex();  //调用建索引的API*/

		}
		else{
			//非法命令
			throw Grammer_error(object);
		}
	}
	else if (comtype == "drop"){
		opos = command.find_first_not_of(" ", npos);
		npos = command.find_first_of(" ", opos);
		string dropOrient = command.substr(opos, npos - opos);
		if (dropOrient == "table"){
			//删除表命令
			opos = command.find_first_not_of(" ", npos);
			npos = command.find_first_of(" ;", opos);
			string tbname = command.substr(opos, npos - opos);
			//下一部分非空格符应只有分号
			opos = command.find_first_not_of(" ", npos);
			if (command.at(opos) != ';'){
				//语法错误
				throw Grammer_error(tbname);
			}

			//传参给API
			Table T(tbname);
			T.getTableInfo();
			API_Drop_Table(T);
			/*
			T.dropTable();  //调用API的删除表命令*/
		}
		else if (dropOrient == "index"){
			//删除索引命令
			opos = command.find_first_not_of(" ", npos);
			npos = command.find_first_of(" ;", opos);
			string idxname = command.substr(opos, npos - opos);
			//下一部分非空格符应只有分号
			opos = command.find_first_not_of(" ", npos);
			if (command.at(opos) != ';'){
				//语法错误
				throw Grammer_error(idxname);
			}

			//传参给API
			API_Drop_Index(idxname);
			/*Index Idx(idxname);
			Idx.dropIndex(); //调用API中删除索引的命令*/
		}
		else{
			//非法命令
			throw Grammer_error(dropOrient);
		}
	}
	else if (comtype == "insert"){
		//插入记录指令
		opos = command.find_first_not_of(" ", npos);
		npos = command.find_first_of(" ", opos);
		string into = command.substr(opos, npos - opos);
		if (into == "into"){
			//符合语法要求
			//表名
			opos = command.find_first_not_of(" ", npos);
			npos = command.find_first_of(" ", opos);
			string tbname = command.substr(opos, npos - opos);

			//"values"
			opos = command.find_first_not_of(" ", npos);
			npos = command.find_first_of(" (", opos);
			string values = command.substr(opos, npos - opos);
			if (values == "values"){
				//符合语法要求
				TupleStruct* tup;
				tup = CreateTupleStruct(command.substr(npos, command.length() - npos));

				//传tuple给API
				Table tbl(tbname);
				tbl.getTableInfo();
				Tuple tuple(tbname);
				tuple.initializeTuple(tup);

				API_Insert(tbl, tuple);
				/*
				tuple.Insert();   //调用API中的insert命令*/
			}
			else{
				//不符合语法要求
				throw Grammer_error(into);
			}
		}
		else{
			//不符合语法要求
			throw Grammer_error(into);
		}
		cout << "Query OK, 1 rows affected." << endl;
	}
	else if (comtype == "select"){
		//select * from student;
		//select * from student where...
		opos = command.find_first_not_of(" ", npos);
		npos = command.find_first_of(" ", opos);
		string selectall = command.substr(opos, npos - opos);
		if (selectall == "*"){
			//符合语法要求
			opos = command.find_first_not_of(" ", npos);
			npos = command.find_first_of(" ", opos);
			string from = command.substr(opos, npos - opos);
			if (from == "from"){
				//符合语法要求
				opos = command.find_first_not_of(" ", npos);
				npos = command.find_first_of(" ;", opos);
				string tbname = command.substr(opos, npos - opos);
				list<Condition> conditionlist;   //储存查询条件
				conditionlist = CreateConditionlist(command.substr(npos, command.length() - npos));

				//传参给API
				Table tbl(tbname);
				tbl.getTableInfo();
				API_Select(tbl,conditionlist);
				/*vector<int> offsetlist;
				//API从索引里查找,返回offserlist
				Tuple tuple(tbname);
				tuple.Select(offsetlist, conditionlist); //API调用select命令*/
			}
			else{
				//不符合语法要求
				throw Grammer_error(from);
			}
		}
		else{
			//不符合语法要求
			throw Grammer_error(selectall);
		}
	}
	else if (comtype == "delete"){
		//delete from student;
		//delete from student where sno = ‘88888888’;
		opos = command.find_first_not_of(" ", npos);
		npos = command.find_first_of(" ", opos);
		string from = command.substr(opos, npos - opos);
		if (from == "from"){
			//符合语法要求
			opos = command.find_first_not_of(" ", npos);
			npos = command.find_first_of(" ;", opos);
			string tbname = command.substr(opos, npos - opos);
			list<Condition> conditionlist;   //储存查询条件
			conditionlist = CreateConditionlist(command.substr(npos, command.length() - npos));

			//传参给API
			Table tbl(tbname);
			tbl.getTableInfo();
			API_Delete(tbl, conditionlist);
			/*vector<int> offsetlist;
			//API从索引里查找,返回offserlist
			Tuple tuple(tbname);
			tuple.Delete(offsetlist, conditionlist); //API调用delete命令*/
		}
		else{
			//不符合语法要求
			throw Grammer_error(from);
		}
	}
	else{
		//非法命令
		throw Grammer_error(comtype);
	}
}
Example #13
0
int find_kband_similarity(string& str1, string& str2, vector<pair<char, char> >& alignment, int &str1_end, int &str2_end)
{
        int row, column;
        int kband, match, preoff = -1, shift;
        int i, j, h, k, offset;
        float len_ratio;
        string swap;

	/*
        if(str1.length() < str2.length())
        {
                swap = str1;
                str1 = str2;
                str2 = swap;
        }
	*/

	//cout << "str1 = " << str1 << endl;
	//cout << "str2 = " << str2 << endl;

	kband = 5;
	kband = min(FRAGMENTSIZE / 4, str2.length() / 2);//03-26-15//70

        row = str1.length() + 1;
        column = 2 * kband + 2;
        len_ratio = 1.0 * str2.length() / str1.length();
	
        for(i = 0; i < row; i ++)
        {
                matrix[i][0].cost = i * -GAP * LOCAL;// * 0;
                matrix[i][0].dir = UP;
		matrix[i][0].matrix_col = 0;
		matrix[i][0].str2_index = 0;
		matrix[i][0].match = 0;
		matrix[i][0].length = i;
        }

        for(j = 1; j < column; j++)
        {
                matrix[0][j].cost = j * -GAP * LOCAL;
                matrix[0][j].dir = BACK;
		matrix[0][j].matrix_col = j - 1;
		matrix[0][j].str2_index = j;
		matrix[0][j].match = 0;
		matrix[0][j].length = j;
        }

        int max_score = 0.0;
        int max_row, max_col;
	int max_length, max_match;
        max_row = max_col = 0;
	int gap_cost = 0;
	str1_end = str2_end = 0;
	max_length = max_match = 0;
	int start_col, end_col;

        for(i = 1; i < row; i++)
        {
                offset = (int) (len_ratio * i);
		start_col = max(1 - offset, -kband);
		end_col = min(str2.length() - offset, kband);

                for(h = start_col; h <= end_col; h++)
                {
                        k = offset + h;

                        if(k >= 1 && k <= str2.length())
                        {
				if(str1.at(i - 1) == str2.at(k - 1))
				{	
					match = WEIGHT;
						
					if(i > 1 && k > 1)//03-26-15
					{
						if(str1.at(i - 2) == str2.at(k - 2))
						{
							match = WEIGHT + MAT_NEXT;
						}
					}
					
				}
				else
				{
					match = MISMATCH;
											
					if(i > 1 && k > 1)
					{
						if(str1.at(i - 2) == str2.at(k - 2))
							match = MISMATCH - MAT_NEXT;
					}
					
				} 
				
                                if(offset > kband + 1)
                                        j = k - (offset - kband) + 1;
                                else
                                        j = k;

                                if(preoff == offset || offset <= kband + 1)
                                        shift = -1;
                                else
                                        shift = offset - preoff -1;

                                //assert(i >= 1 && i < row);
                                //assert(j >= 1 && j < 2 * kband + 2);

                                matrix[i][j].dir = DIAG;
				matrix[i][j].matrix_col = (j + shift);
				matrix[i][j].str2_index = k;
				matrix[i][j].length = matrix[i - 1][j + shift].length + 1;
					
				if(match >= WEIGHT)
					matrix[i][j].match = matrix[i - 1][j + shift].match + match;//1;
				else
					matrix[i][j].match = matrix[i - 1][j + shift].match;
				/*
				if(match >= WEIGHT)
					matrix[i][j].match = matrix[i - 1][j + shift].match + match;
				*/
                                if(LOCAL == 0)
                                        matrix[i][j].cost = max(0, matrix[i - 1][j + shift].cost + match);
                                else
                                        matrix[i][j].cost = matrix[i - 1][j + shift].cost + match;

                                if(j + shift + 1 <= 2 * kband + 1)
                                {
					if(matrix[i - 1][j + shift + 1].dir == DIAG)
                                   		gap_cost = GAP + GAP_OPEN;
                                	else
                                        	gap_cost = GAP;

                                        if(matrix[i][j].cost < matrix[i - 1][j + shift + 1].cost - gap_cost) 
					{ // <= changed to <
				                matrix[i][j].dir = UP;
						matrix[i][j].matrix_col = (j + shift + 1);
						matrix[i][j].str2_index = k;
                                        	matrix[i][j].cost = matrix[i - 1][j + shift + 1].cost - gap_cost;
						matrix[i][j].length = matrix[i - 1][j + shift + 1].length + 1;
						matrix[i][j].match = matrix[i - 1][j + shift + 1].match;
					}
                                }

                                if(j - 1 >= 1)// && str2.at(k - 1) != 'N')
                                {
					if(matrix[i][j - 1].dir == DIAG)
                                        	gap_cost = GAP + GAP_OPEN;
                                	else
                                        	gap_cost = GAP;

                                        if(matrix[i][j].cost < matrix[i][j - 1].cost - gap_cost)
					{ // <= changed to <
                                                matrix[i][j].dir = BACK;
						matrix[i][j].matrix_col = (j - 1);
						matrix[i][j].str2_index = k;
                                        	matrix[i][j].cost = matrix[i][j - 1].cost - gap_cost;
						matrix[i][j].length = matrix[i][j - 1].length + 1;
						matrix[i][j].match = matrix[i][j - 1].match;
					}
                                }
				/*
                                if(DEBUG == 99)
                                {
					//cout << "@(" << i << "," << j << "," << k << "): " << matrix[i][j] << "\t";
                                        //cout << "@(" << str1.at(i - 1) << ", " << str2.at(k - 1) << "): " << matrix[i][j] << "\t";
                                        cout << "(" << str1.at(i - 1) << "," << str2.at(k - 1) << "):"
                                                << "(" << i << "," << j << "):" << matrix[i][j].cost << "\t";
                                }
				*/
								
                                if(k >= 0.75 * i && k <= 1.25 * i)//03-26-15
					if(max_score <= matrix[i][j].cost ||
						(max_row < i && max_col < j && 
						matrix[i][j].cost > 0.525 *  matrix[i][j].length))
                              	{		
                                       	max_score = matrix[i][j].cost;
                                       	max_row = i;
                                       	max_col = j;
                                       	str1_end = i;
                                       	str2_end = k;
					max_length = matrix[i][j].length;
					max_match = matrix[i][j].match;
					/*
					cout << "Row = " << str1.at(i - 1) << ", and Col = " << 
					str2.at(k - 1) << ", Len " << matrix[i][j].length <<
					", Score = " << matrix[i][j].match << ": " <<
					(1.0 * matrix[i][j].match / matrix[i][j].length)  << endl;
					*/
					//cout << "(" << i << ", " << j << ")    ";
					//cout << "" << i << "," << k << "," << j << "    ";
					//cout << "" << i << "|" << k << "|" << j << "|" << matrix[i][j].dir << "|  ";
					
				}

                        }

                }

                preoff = offset; //to prevent updating same row values
		if(j + 1 < column)
                        matrix[i][j + 1].cost = -(i + j + 1) * GAP * LOCAL;
		/*		
                if(DEBUG == 99) 
		{
                        cout << "\n";
                        cout << "-------------------------------------------------------------------------------";
			cout << "-------------------------------------------------------------------------------" << endl;

                }
		*/
		
        }


	//cout << "Total score = " << matrix[max_row][max_col] << ", with kband_score = " << max_score << endl;
	cout << "Max score found at the row = " << str1_end << ", and at the col = " << str2_end << endl;
	trace_path_cell_back(matrix, max_row, max_col, str1, str2, alignment);
	cout << "" << alignment.size() << " VS " << max_length << endl;
	assert(alignment.size() == max_length);	
	return max_match;
}
Example #14
0
bool Calendar::isTaskDone(const string& task)
{
	if(task.at(0) == 'x') return true;
	return false;
}
Example #15
0
void io_pipe(string input)
{	
	
	char *inputchar = new char [input.length()+1];//makes a char* from string
	char *fakechar	= new char [input.length()+1];
	strcpy(inputchar,input.c_str());
	
	
	char **argvIN		= new char*[strlen(inputchar)];
	char **argvSPACE	= new char*[strlen(inputchar)];
	char **argvOPEN		= new char*[strlen(inputchar)];
	
	char *spa = new char[5];
	char *open1 = new char[5];
	strcpy(spa," \n");
	strcpy(open1,"<> ");
	
	int sz;

	bool out,dout,in,cerrr = false;
	bool sign = false;	



	//take OPEN [1] tokenize the space out of it and then execute it and the OPEN [2] should be passed into open
	
	unsigned int first =1;
	char *holder;
	int x=0;
	while (first!=0)
	{
		if(x==3)
			sign = true;
		first =0;
		if(input.find(">")!=string::npos)
		{
			unsigned int temp = input.find(">");
			first = temp;
			if(temp-1>0)
			{
				if(input.at(temp-1)=='2')
					cerrr=true;
			}
			temp = temp +1;
			if(temp<input.size())
			{
				if(input.at(temp)!='>')
					out=true;
				else if(input.at(temp)=='>')
				{
					out =false;
					dout = true;
				}
			}
		}
		if(input.find("<")!=string::npos)
		{
			if(first>input.find("<")||first ==0)
			{
				first=input.find("<");
				out = false;
				cerrr=false;
				dout = false;
				in = true;
			}
		}
		string fake = input;
		if(cerrr)
			fake.resize(first-1);

		else
			fake.resize(first);

		if(first+1<input.size()&&!dout&&first!=0)
			input =input.substr(first+1);

		else if(first+2<input.size()&&dout&&first!=0)
			input =input.substr(first+2);

		if(number_of_io_redirections==0)
		{
			strcpy(inputchar,fake.c_str());

			initial(inputchar,argvIN); //this puts the whole input into a char** for further breakdown

			checker(argvIN,argvSPACE,spa,sz);
		}

		number_of_io_redirections++;
		fake =input;
		strcpy(fakechar,fake.c_str());
		initial(fakechar,argvIN);
		checker(argvIN,argvOPEN,open1,sz);
		holder = argvOPEN[0]; // holds the file name to output or input
		if(out)
		{
			if(-1==open(holder,O_WRONLY|O_CREAT|O_TRUNC,0644))
				perror("open");
				x=1;
		}
		else if(dout)
		{
			if(-1==open(holder,O_WRONLY|O_CREAT|O_APPEND,0644))
				perror("open");
				x=2;
		}
		else if(in)
		{
			if(-1==open(holder,O_RDONLY))
				perror("open");
				x=3;
		}
		if(sign && x!=3)
		{
			cout << "Error: case not handled (cannot combine < and >)" << endl;
		
	delete[] inputchar;
	delete[] fakechar;
	delete[] argvIN;
	delete[] argvSPACE;
	delete[] argvOPEN;	
	delete[] spa;
	delete[] open1;
			return;
		}
		sign = false;
	}

	int status =0;
	int pid=fork();
	if (pid == -1)//there was an error with the forking
	{
		perror("fork");//if error does the proper error output
		exit(1);
	}
	else if (pid ==0)//if the child process is running
	{
		int cl =1;
		if(out)
		{
			if (cerrr)
				cl=2;
			if(-1==close(cl))
				perror("close");
			if(-1==open(holder,O_WRONLY|O_CREAT|O_TRUNC,0644))
				perror("open");
		}
		else if(dout)
		{
			if(cerrr)
				cl =2;
			if(-1==close(cl))
				perror("close");
			if(-1==open(holder,O_WRONLY|O_CREAT|O_APPEND,0644))
				perror("open");
		}
		else if(in)
		{
			if(-1==close(0))
				perror("close");
			if(-1==open(holder,O_RDONLY))
				perror("open");
		}
		if(-1==execvp(argvSPACE[0],argvSPACE))
		{
			status = -1;
			perror("execvp");
		}
			
		exit (1);
	}
	else if (pid >0)//parent process is running
	{
		if (-1 == wait(&status))// if the wait fails it displays error and exits
		{
			perror("wait");
			exit(1);
		}
	}

	out=false;
	dout=false;
	in=false;
		
	delete[] inputchar;
	delete[] fakechar;
	delete[] argvIN;
	delete[] argvSPACE;
	delete[] argvOPEN;
	delete[] spa;
	delete[] open1;
	
}
Example #16
0
string get_nearest_connector(const string &s, const size_t &pos) {
    if (pos==string::npos) return "";
    else if (s.at(pos)=='|') return "||";
    else if (s.at(pos)=='&') return "&&";
    else return ";";
}
// Function analyzes the given ion string to determine if it can undergo a
// neutral loss of any kind. If it can, that potential neutral loss is recorded.
void MSProductClass::generate_NL_ionsMZ(string ion, char ion_type) {
	double mass, mz_value;
	int N = (signed) ion.length();
	string Nstr = int2string(N);
	string new_ion;
	string phosphoChars = "sty";
	size_t f;

	bool hasPhospho = false;
	bool loseNH3 = false;
	bool loseH2O = false;


	// In CID data there is sufficient noise in the spectra to allow for matches
	// to decoy fragment ions. This is not the case for HCD data.
	// Therefore we need to allow neutral losses in HCD data to be generated
	// using all of the decoy residues
	if( g_IS_HCD ) phosphoChars = "sty234567890@#$%&;?~";


	// compute mass of ion
	mass = 0.0;
	for(int i = 0; i < N; i++) { mass += AAmass[ ion.at(i) ]; }


	// determine if the ion contains an STY letter, if it does, then the loss
	// of a phospho-group is possible.
	int H3PO4ctr = 0;
	for(int i = 0; i < N; i++) {
		f = phosphoChars.find( ion.at(i) );
		if(f != string::npos) H3PO4ctr++;
	}
	if( H3PO4ctr > 0 ) hasPhospho = true; // has at least 1 phosphorylated AA


/*****************************************************************************
	// determine if the ion can lose ammonia or water
	int NH3ctr = 0, H2Octr = 0;
	for(int i = 0; i < N; i++) {
		if(ion.at(i) == 'R') NH3ctr++;
		if(ion.at(i) == 'K') NH3ctr++;
		if(ion.at(i) == 'Q') NH3ctr++;
		if(ion.at(i) == 'N') NH3ctr++;

		if(ion.at(i) == 'S') H2Octr++;
		if(ion.at(i) == 'T') H2Octr++;
		if(ion.at(i) == 'E') H2Octr++;
		if(ion.at(i) == 'D') H2Octr++;
	}

	if( NH3ctr > 0 ) loseNH3 = true;
	if( H2Octr > 0 ) loseH2O = true;


	// For HCD data, neutral loss peaks help, but they don't help much
	// for CID data. Therefore, don't generate the H2O and NH3 neutral loss
	// peaks for CID data
	if( !g_IS_HCD ) {
		loseNH3 = false;
		loseH2O = false;
	}
*******************************************************************************/


	double extraProton = 0; // Computes: ( H * (z-1) ) <- you need this for dealing with multiple charge states;
	for(int z = 1; z < charge; z++) {

		extraProton = ( H * (z-1) );

		if(ion_type == 'b') {

			// this ion contains a phospho group that can undergo neutral loss
			if(hasPhospho) {
				new_ion.clear();
				new_ion = "b^" + Nstr + ":" + ion + "-H3PO4";
				if(z > 1) new_ion += "/+" + int2string(z);

				mz_value = mass + H - e + extraProton;
				mz_value += -H3PO4;
				mz_value /= z;

				if( (mz_value > MIN_MZ) && (N > 1) ) {
					b_ions[ new_ion ] = mz_value;
					b_ion_set.insert(new_ion);
				}
			} // end if(hasPhospho)


			if(loseNH3) {
				new_ion.clear();
				new_ion = "b^" + Nstr + ":" + ion + "-NH3";
				if(z > 1) new_ion += "/+" + int2string(z);

				mz_value = mass + H -e + extraProton;
				mz_value += -NH3;
				mz_value /= z;

				if( (mz_value > MIN_MZ) && (N > 1) ) {
					b_ions[ new_ion ] = mz_value;
					b_ion_set.insert(new_ion);
				}
			} // end if(loseNH3)


			if(loseH2O) {
				new_ion.clear();
				new_ion = "b^" + Nstr + ":" + ion + "-H2O";
				if(z > 1) new_ion += "/+" + int2string(z);

				mz_value = mass + H -e + extraProton;
				mz_value += -H2O;
				mz_value /= z;

				if( (mz_value > MIN_MZ) && (N > 1) ) {
					b_ions[ new_ion ] = mz_value;
					b_ion_set.insert(new_ion);
				}
			} // end if(loseH2O)

		} // end b-ion
		else if(ion_type == 'y') {

			// this ion contains a phospho group that can undergo neutral loss
			if(hasPhospho) {
				new_ion.clear();
				new_ion = "y^" + Nstr + ":" + ion + "-H3PO4";
				if(z > 1) new_ion += "/+" + int2string(z);

				mz_value = mass + H2O + H + extraProton;
				mz_value += -H3PO4;
				mz_value /= z;

				if( (mz_value > MIN_MZ) && (N > 1) ) {
					y_ions[ new_ion ] = mz_value;
					y_ion_set.insert(new_ion);
				}
			} // end if(hasPhospho)


			if(loseNH3) {
				new_ion.clear();
				new_ion = "y^" + Nstr + ":" + ion + "-NH3";
				if(z > 1) new_ion += "/+" + int2string(z);

				mz_value = mass + H2O + H + extraProton;
				mz_value += -NH3;
				mz_value /= z;

				if( (mz_value > MIN_MZ) && (N > 1) ) {
					y_ions[ new_ion ] = mz_value;
					y_ion_set.insert(new_ion);
				}
			} // end if(loseNH3)


			if(loseH2O) {
				new_ion.clear();
				new_ion = "y^" + Nstr + ":" + ion + "-H2O";
				if(z > 1) new_ion += "/+" + int2string(z);

				mz_value = mass + H2O + H + extraProton;
				mz_value += -H2O;
				mz_value /= z;

				if( (mz_value > MIN_MZ) && (N > 1) ) {
					y_ions[ new_ion ] = mz_value;
					y_ion_set.insert(new_ion);
				}
			} // end if(loseH2O)

		} // end y-ion
	}
}
Example #18
0
bool is_blank(const string &s) {
    for (size_t i=0;i<s.length();i++)
        if (s.at(i)!=' ')
            return false;
    return true;
}
void prepare_fasta_output_distribution(ifstream& fp_input, ofstream& fp_fasta, ofstream& fp_detail, 
					string& reference, meta_data& meta_details)
{
  	ofstream condense_log;
  	condense_log.open("condense_log.tsv", ofstream::out);

        vector<map<char,int>> mutationStats;
	//baslragsh;

        string read_name, cigar, alignment, quality, len;
	string alignment_string, quality_score, detail;
	int total_score, average_score, opt, reflength;
	int i, k, count, refindex, readindex;
	int fprimer_length, except_primer;
        unordered_map<string, int> umap;
	vector< pair<string, string>> sequences; 
	double exponent;

	int raw_sequence_count = 0;//debug purposes only

	fp_detail << "###############################################Sequence Anaysis Starts##############################################" << endl;
	
	distribution error_correction[reference.length()];
	for(i = 0; i < reference.length(); i++)
	{
	  	mutationStats.push_back(map<char,int>());
		mutationStats[i]['A'] = 0;
		mutationStats[i]['C'] = 0;
		mutationStats[i]['G'] = 0;
		mutationStats[i]['T'] = 0;
		mutationStats[i]['N'] = 0;
		for(k = 0; k < ILLUMINA_SCORE; k++)
			error_correction[i].qscore[k] = 0;

		error_correction[i].matching_base = 0;
		error_correction[i].mismatch = 0;
		error_correction[i].expected_mismatch = 0.0;
		error_correction[i].standard_deviation = 0.0;
	}
	

	condense_log << "Observed,Expected,zscore,correct,raw pval,A,C,G,T,N,%mutated" << endl;
	fprimer_length = meta_details.fprimer.length();
	except_primer = reference.length() - meta_details.fprimer.length();

	while(getline(fp_input, read_name))
        {
	  	raw_sequence_count++;
                getline(fp_input, cigar);
                getline(fp_input, alignment_string);
		getline(fp_input, quality_score);
		
		total_score = 0;
		for(i = 0; i < quality_score.length(); i++)
		{
			total_score += quality_score.at(i) - '!';
		}

		average_score = total_score / quality_score.length();
		fp_detail << endl << "Global Average Score = " << average_score << endl;

		if(average_score < GLOBAL_QSCORE)
			continue;
		
		refindex = fprimer_length;
		i = readindex = 0;
		alignment = "";
		quality = "";
		len = "";

		fp_detail << "CIGAR = " << cigar << endl;
		while(i < cigar.length())
		{
			if(cigar.at(i) >= '0' && cigar.at(i) <= '9')
				len += cigar.at(i);
			else
			{
				opt = cigar.at(i);
				count = atoi(len.c_str());
				fp_detail << "Count = " << count << ", and Option = " << opt << endl;
				len = "";			

				//fp_detail << "Reference = " << reference << endl;
				//fp_detail << "Alignment = " << alignment_string << endl;

				if(opt == 'M' || opt == 'X')
				{
					for(k = 0; k < count; k++)
					{
						if(alignment_string.at(readindex) == reference.at(refindex))
						{
							error_correction[refindex].matching_base += 1;
						}
						else 
						{
							error_correction[refindex].mismatch += 1;
							mutationStats[refindex][alignment_string.at(readindex)] += 1;
							char blah = alignment_string.at(readindex);
							//if(!(alignment_string.at(readindex) == 'A') && (alignment_string.at(readindex) != 'C') && (alignment_string.at(readindex) != 'G') && (alignment_string.at(readindex) != 'T')){
							//if((blah != 'A') && (blah != 'C') && (blah != 'G') && (blah != 'T')){
							fp_detail << "BASE Mismatch is Found at = " << refindex << endl;
						}

						error_correction[refindex].qscore[quality_score.at(readindex) - '!'] += 1;

						//fp_detail << k << "= (" << refindex << ", " << readindex << ") = " 
						//	"(" << reference.at(refindex) << ", " << alignment_string.at(readindex) << ")" << endl;

						refindex += 1;
						readindex += 1;
					}	
				}
				else if(opt == 'I')
				{
					readindex += count;
				}
				else if(opt == 'D')
				{
					refindex += count;
				}
				else
				{
					assert(false);
				}
			} 
			
			i += 1;
		}

	}

	fp_detail << endl;
	for(i = 0; i < reference.length(); i++)
	{
		fp_detail << "Showing Analysis for Index = " << i << endl;
		if(error_correction[i].mismatch + error_correction[i].matching_base == 0)
			continue;

		for(k = 0; k < ILLUMINA_SCORE; k++)
		{
			if(error_correction[i].qscore[k] == 0)
				continue;

			exponent = pow(10, -1 * k *  0.1);
			fp_detail << "QSCORE = " << k << ", and COUNT = " << error_correction[i].qscore[k] << ", and Exponent = " << exponent << endl;
			error_correction[i].expected_mismatch += (error_correction[i].qscore[k] * exponent);
			error_correction[i].standard_deviation += (error_correction[i].qscore[k] * exponent * (1 - exponent));
			
			fp_detail << "Expected Number of Mismatch = " << error_correction[i].expected_mismatch;
	                fp_detail << ", and Standard Deviation = " << error_correction[i].standard_deviation << endl;

		}

		error_correction[i].standard_deviation = sqrt(error_correction[i].standard_deviation);
		error_correction[i].zscore = (error_correction[i].mismatch + 0.5 - 
						error_correction[i].expected_mismatch) / 
						error_correction[i].standard_deviation;
		
		error_correction[i].pvalue = 1-c_norm(error_correction[i].zscore);
		cout << "A pvalue is: " << error_correction[i].pvalue << endl;

		fp_detail << "Error Correction At Position = " << i - fprimer_length << endl;
		fp_detail << "Mismatch = " << error_correction[i].mismatch << ", and Matching BASE = " 
				<< error_correction[i].matching_base << endl;

		fp_detail << "Expected Number of Mismatch = " << error_correction[i].expected_mismatch;
		fp_detail << ", and Standard Deviation = " << error_correction[i].standard_deviation << endl;
		fp_detail << "Finally calculated ZSCORE = " << error_correction[i].zscore << endl;
		fp_detail << "Finally p-value is = " << error_correction[i].pvalue << endl;
		fp_detail << "Fail to reject null hypothesis is = " << (error_correction[i].reject_by_bh_threshold ? "0" : "1")<< endl;
		
		fp_detail << endl;

		//if(error_correction[i].mismatch > 0)
		//	assert(false);
	}
	set_reject_flags(error_correction, reference.length());

	for(i = 0; i < reference.length(); i++){
		if(error_correction[i].mismatch + error_correction[i].matching_base == 0)
		  continue;
		condense_log << error_correction[i].mismatch << "," << error_correction[i].expected_mismatch << "," << error_correction[i].zscore;
		condense_log << "," << (error_correction[i].reject_by_bh_threshold ? "0" : "1");
		condense_log << "," << (error_correction[i].pvalue) << ",";

		condense_log << mutationStats[i]['A'] << ",";
		condense_log << mutationStats[i]['C'] << ",";
		condense_log << mutationStats[i]['G'] << ",";
		condense_log << mutationStats[i]['T'] << ",";
		condense_log << mutationStats[i]['N'] << ",";
		condense_log << "," << double((double)error_correction[i].mismatch / (double)raw_sequence_count) << endl;
		
          if(error_correction[i].reject_by_bh_threshold){
	    fp_detail << "No Correcting at position " << i << endl;
	  } else {
	    fp_detail << "Correcting at position " << i << endl;

	  }
	}
	//condense_log.close();
	fp_input.clear();
	fp_input.seekg(0, fp_input.beg);

	while(getline(fp_input, read_name))
        {
                getline(fp_input, cigar);
                getline(fp_input, alignment_string);
		getline(fp_input, quality_score);
		
		total_score = 0;
		for(i = 0; i < quality_score.length(); i++)
		{
			total_score += quality_score.at(i) - '!';
		}

		average_score = total_score / quality_score.length();
		fp_detail << endl << "Global Average Score = " << average_score << endl;

		if(average_score < GLOBAL_QSCORE)
			continue;
		
		refindex = meta_details.fprimer.length();
		i = readindex = 0;
		alignment = "";
		quality = "";
		len = "";

		fp_detail << "CIGAR = " << cigar << endl;
		while(i < cigar.length())
		{
			if(cigar.at(i) >= '0' && cigar.at(i) <= '9')
				len += cigar.at(i);
			else
			{
				opt = cigar.at(i);
				count = atoi(len.c_str());
				fp_detail << "Count = " << count << ", and Option = " << opt << endl;
				len = "";			

				fp_detail << "Reference = " << reference << endl;
				fp_detail << "Alignment = " << alignment_string << endl;

				if(opt == 'M' || opt == 'X')
				{
					for(k = 0; k < count; k++)
					{
					  	/*if(error_correction[refindex].reject_by_bh_threshold){
						  cout << "Rejectin null hypothesis whooo at " << refindex << endl;
						} else {
						  cout << "Acceptin null hypothesis =( " << refindex << endl;
						}*/
						if(alignment_string.at(readindex) != reference.at(refindex) &&
							//error_correction[refindex].zscore < ZSCORE &&
							!error_correction[refindex].reject_by_bh_threshold)
						{
							fp_detail << endl << "Error CORRECTION Point at " << readindex << endl;
							fp_detail << "ZSCORE at this point = " << error_correction[refindex].zscore << endl;
							fp_detail << "Changin " << alignment_string.at(readindex) << " To " <<
									reference.at(readindex) << endl;
						
							alignment += reference.at(refindex);
							quality += quality_score.at(readindex);

						}
						else
						{
						        fp_detail << endl << "No correction at " << refindex;
							alignment += alignment_string.at(readindex);
							quality += quality_score.at(readindex);
						}

						//fp_detail << k << "= (" << refindex << ", " << readindex << ")" << endl;

						refindex += 1;
						readindex += 1;
					}	
				}
				else if(opt == 'I')
				{
					for(k = 0; k < count; k++)
					{
						alignment += alignment_string.at(readindex);
						quality += quality_score.at(readindex);

						readindex += 1;
					}
				}
				else if(opt == 'D')
				{
					refindex += count;
				}
				else
				{
					assert(false);
				}
			} 
			
			i += 1;
		}

		detail = cigar + "\n" + alignment;
		if(umap.find(detail) == umap.end())
                {
                        //umap[alignment] = 1;
                	sequences.push_back(make_pair(read_name, detail));
			umap[detail] = 1;
                }
                else
                {
                        umap[detail] += 1;
                }

		/*
                fp_fasta << ">" << read_name;

                fp_fasta << "|DUPCOUNT=1";
                fp_fasta << "|CIGAR=" << cigar << endl;
                fp_fasta << alignment << endl;
		*/
        }



	for(i = 0; i < sequences.size(); i++)
	{
	        fp_fasta << ">" << sequences[i].first;

                fp_fasta << "|DUPCOUNT=" << umap[sequences[i].second];
                fp_fasta << "|CIGAR=" << sequences[i].second << endl;
                //fp_fasta << alignment << endl;

	}

        fp_input.close();
        fp_fasta.close();
	condense_log.close();

	return;
}
Example #20
0
bool StmtParser::parseForLoop(string text, string &out) {
  // for arrName[exp1] := exp2 to exp3 do stmt

  string arrName, exp_1, exp_2, exp_3, stmt;
  int arrNameEnd = -1, bracketDepth = 0, idxExpEnd = -1, assignOpIdx, toIdx, doIdx;

  for (int i = 4; i < text.size(); i++) {
    if (text.at(i) == '[') {
      arrNameEnd = i;
      break;
    }
  }

  if (arrNameEnd < 0) {
    cout << "Error: no array in first part of for loop!" << endl;
    return false;
  }

  for (int i = arrNameEnd; i < text.size(); i++) {
    if (text.at(i) == '[') {
      bracketDepth++;
    } else if (text.at(i) == ']') {
      bracketDepth--;
      if (bracketDepth == 0) {
        idxExpEnd = i;
        break;
      } else if (bracketDepth < 0) {
        cout << "Error: too many ']' without a matching '['." << endl;
        return false;
      }
    } else if (text.at(i) == ':' && i < text.size()-1 && text.at(i+1) == '=') {
      cout << "Error: cannot have assignment statement as array index." << endl;
      return false;
    }
  }

  if (idxExpEnd < 0) {
    cout << "Error: no matching ']'." << endl;
    return false;
  }

  assignOpIdx = text.find(":=");
  toIdx = text.find(" to ");
  doIdx = text.find(" do ");

  if (assignOpIdx == string::npos) {
    cout << "Error: no assignment statement." << endl;
    return false;
  } else if (toIdx == string::npos) {
    cout << "Error: missing \"to\" keyword." << endl;
    return false;
  } else if (doIdx == string::npos) {
    cout << "Error: missing \"do\" keyword." << endl;
    return false;
  }

  if (toIdx != text.find(" to ", assignOpIdx)) {
    cout << "Error: missing assignment before \"to\" operator." << endl;
    return false;
  } else if (doIdx != text.find(" do ", toIdx)) {
    cout << "Error: \"do\" keyword appears before \"to\" keyword." << endl;
    return false;
  }

  int forStart = text.find("for");

  arrName = text.substr(forStart + 4, arrNameEnd - forStart - 4);
  exp_1 = text.substr(arrNameEnd + 1, idxExpEnd - arrNameEnd - 1);
  exp_2 = text.substr(assignOpIdx + 3, toIdx - assignOpIdx - 3);
  exp_3 = text.substr(toIdx + 4, doIdx - toIdx - 4);
  stmt = text.substr(doIdx + 4);
  arrName = parseUtil.trim(arrName);
  int array_id = 0;
  if (arrNames->find(arrName) != arrNames->end()) {
    array_id = (*arrNames)[arrName];
  } else {
    array_id = arrNames->size();
    (*arrNames)[arrName] = array_id;
  }

  if (debug) {
    //cout << "arrayName " << (forStart + 4) << " length " << (arrNameEnd - forStart - 4) << endl;
    //cout << "exp1 " << (arrNameEnd+1) << " length " << (idxExpEnd - arrNameEnd - 1) << endl;
    //cout << "exp2 " << (assignOpIdx + 3) << " length " << (toIdx - assignOpIdx - 3) << endl;
    //cout << "exp3 " << (toIdx + 4) << " length " << (doIdx - toIdx - 4) << endl;
    //cout << text << " " << text.substr(3, 1) << endl;
    cout << "FOR: " << arrName << " (id: " << array_id << ") at " << exp_1 << endl;
    cout << "FROM: " << exp_2 << " to " << exp_3 << endl;
    cout << "DO: " << stmt << endl;
  }

  bool compiled = true;

  stringstream ss, arrStream;
  ss << loopCount++;
  arrStream << array_id;
  string loopName = ss.str();
  if (treasure) {
    out += "; Here lay the start of the faaaaar loop\n";
  } else {
    out += "; Beginning of for loop\n";
  }
  string evalResult = "";
  out += "push ecx\nmov ecx, 0\n";
  if (treasure) {
    out += "fore_" + loopName + ": nop\n";
  } else {
    out += "top_" + loopName + ": nop\n";
  }
  compiled = compiled && expParser.parseExp(exp_3, evalResult);
  out += evalResult;
  out += "push ebx\n";
  out += "mov ebx, eax\n";
  compiled = compiled && expParser.parseExp(exp_2, evalResult);
  out += evalResult;
  out += "add eax, ecx\ninc ecx\n";
  out += "cmp eax, ebx\npop ebx\n";
  if (treasure) {
    out += "jg aft_" + loopName + "\n";
  } else {
    out += "jg done_" + loopName + "\n";
  }
  out += "push ebx\n";
  out += "mov ebx, eax\n";
  compiled = compiled && expParser.parseExp(exp_1, evalResult);
  out += evalResult;
  out += "push ecx\n";
  out += "push " + arrStream.str() + "\npush eax \npush ebx\n";
  out += "call setValue\nadd esp, 12\n";
  out += "pop ecx\npop ebx\n";
  evalResult = "";
  compiled = compiled && parseStmt(stmt, evalResult);
  out += evalResult;
  if (treasure) {
    out += "jmp fore_" + loopName + "\n";
    out += "aft_" + loopName + ": pop ecx\n";
  } else {
    out += "jmp top_" + loopName + "\n";
    out += "done_" + loopName + ": pop ecx\n";
  }
  return compiled;
}
void prepare_fasta_output_heuristic(ifstream& fp_input, ofstream& fp_fasta, ofstream& fp_detail, 
					string& reference, meta_data& meta_details)
{
        string read_name, cigar, alignment, quality, len;
	string alignment_string, quality_score, detail;
	int total_score, average_score, opt;
	int i, k, count, refindex, readindex;
        unordered_map<string, int> umap;
	vector< pair<string, string>> sequences; 
	fp_detail << "###############################################Sequence Anaysis Starts##############################################" << endl;
	
	while(getline(fp_input, read_name))
        {
                getline(fp_input, cigar);
                getline(fp_input, alignment_string);
		getline(fp_input, quality_score);
		
		total_score = 0;
		for(i = 0; i < quality_score.length(); i++)
		{
			total_score += quality_score.at(i) - '!';
		}

		average_score = total_score / quality_score.length();
		fp_detail << endl << "Global Average Score = " << average_score << endl;

		if(average_score < GLOBAL_QSCORE)
			continue;
		
		refindex = meta_details.fprimer.length();
		i = readindex = 0;
		alignment = "";
		quality = "";
		len = "";

		fp_detail << "CIGAR = " << cigar << endl;
		while(i < cigar.length())
		{
			if(cigar.at(i) >= '0' && cigar.at(i) <= '9')
				len += cigar.at(i);
			else
			{
				opt = cigar.at(i);
				count = atoi(len.c_str());
				fp_detail << "Count = " << count << ", and Option = " << opt << endl;
				len = "";			

				fp_detail << "Reference = " << reference << endl;
				fp_detail << "Alignment = " << alignment_string << endl;

				if(opt == 'M' || opt == 'X')
				{
					for(k = 0; k < count; k++)
					{
						if(alignment_string.at(readindex) == 'N')
						{
							alignment += reference.at(refindex);
							quality += quality_score.at(readindex);

						}
						else if(quality_score.at(readindex) - '!' < PERBASE_QSCORE)
						{
							alignment += reference.at(refindex);
							quality += quality_score.at(readindex);
						}
						else
						{
							alignment += alignment_string.at(readindex);
							quality += quality_score.at(readindex);
						}

						//fp_detail << k << "= (" << refindex << ", " << readindex << ")" << endl;

						refindex += 1;
						readindex += 1;
					}	
				}
				else if(opt == 'I')
				{
					for(k = 0; k < count; k++)
					{
						alignment += alignment_string.at(readindex);
						quality += quality_score.at(readindex);

						readindex += 1;
					}
				}
				else if(opt == 'D')
				{
					refindex += count;
				}
				else
				{
					assert(false);
				}
			} 
			
			i += 1;
		}

		detail = cigar + "\n" + alignment;
		if(umap.find(detail) == umap.end())
                {
                        //umap[alignment] = 1;
                	sequences.push_back(make_pair(read_name, detail));
			umap[detail] = 1;
                }
                else
                {
                        umap[detail] += 1;
                }

		/*
                fp_fasta << ">" << read_name;

                fp_fasta << "|DUPCOUNT=1";
                fp_fasta << "|CIGAR=" << cigar << endl;
                fp_fasta << alignment << endl;
		*/
        }

	//sort(sequences.begin(), sequences.end(), compare_string);

	for(i = 0; i < sequences.size(); i++)
	{
	        fp_fasta << ">" << sequences[i].first;

                fp_fasta << "|DUPCOUNT=" << umap[sequences[i].second];
                fp_fasta << "|CIGAR=" << sequences[i].second << endl;
                //fp_fasta << alignment << endl;

	}

        //fp_input.close();
        //fp_fasta.close();

	return;
}
Example #22
0
bool StmtParser::parseAssignment(string text, string &out) {
  int parenDepth = 0, bracketDepth = 0, assignOpIdx = -1, b1Idx = -1, b2Idx = -1;

  for (int i = 0; i < text.size()-1; i++) {
    char c = text.at(i);
    if (c == '[') {
      if (parenDepth == 0 && b1Idx < 0 && bracketDepth == 0) {
        b1Idx = i;
      }
      bracketDepth++;
    } else if (c == ']') {
      bracketDepth--;
      if (bracketDepth < 0) {
        cout << "Error: too many ']' without a matching '['" << endl;
        return false;
      }
      if (parenDepth == 0 && b2Idx < 0 && bracketDepth == 0) {
        b2Idx = i;
      }
    } else if (c == '(') {
      parenDepth++;
    } else if (c == ')') {
      parenDepth--;
      if (parenDepth < 0) {
        cout << "Error: too many ')' without a matching '('" << endl;
        return false;
      }
    } else if (c == ':' && text.at(i+1) == '=' && parenDepth == 0
              && bracketDepth == 0) {
      assignOpIdx = i;
      break;
    }
  }

  if (assignOpIdx < 0) {
    cout << "Error: no \":=\" operator found in assignment statement." << endl;
    return false;
  }

  if (b1Idx < 0 || b2Idx < 0 || b1Idx > assignOpIdx || b2Idx > assignOpIdx) {
    cout << "Error: no valid variable to right of \":=\"" << endl;
    return false;
  }

  for (int i = b2Idx + 1; i < assignOpIdx; i++) {
    char c = text.at(i);
    if (c != ' ' && c != '\r' && c != '\n') {
      cout << "Error: invalid character between variable and assignment."
           << endl;
      return false;
    }
  }

    //string lhs = text.substr(0, assignOpIdx);
  string arrName = text.substr(0, b1Idx);
  if (!parseUtil.isValidVarName(arrName)) {
    cout << "Error: cannot name array: " << arrName << endl;
    return false;
  }
  arrName = parseUtil.trim(arrName);

  int array_id = 0;
  if (arrNames->find(arrName) != arrNames->end()) {
    array_id = (*arrNames)[arrName];
  } else {
    array_id = arrNames->size();
    (*arrNames)[arrName] = array_id;
  }

  stringstream ss;
  ss << array_id;
  string idxExp = text.substr(b1Idx + 1, b2Idx - b1Idx - 1);
  string rhs = text.substr(assignOpIdx+2);
  string evalResult = "";
  bool compiled = true;
  out += "push ecx\n";
  if (treasure) {
    out += "; Stowin' " + text + " away\n";
    out += "; Puttin' tha arrrrrrrrray on tha stack\n";
  } else {
    out += "; assignment statement for: " + text + "\n";
    out += "; pushing array name\n";
  }
  out += "push " + ss.str() + "\n";
  if (treasure) {
    out += "; Markin' this spot on tha treasure map: " + idxExp + "\n";
  } else {
    out += "; pushing index expression: " + idxExp + "\n";
  }
  compiled = compiled && expParser.parseExp(idxExp, evalResult);
  out += evalResult;
  out += "push eax\n";
  if (treasure) {
    out += "; Buryin' the treasure: " + rhs + "\n";
  } else {
    out += "; pushing rhs expression: " + rhs + "\n";
  }
  compiled = compiled && expParser.parseExp(rhs, evalResult);
  out += evalResult;
  out += "push eax\n";
  out += "call setValue\n";
  out += "add esp, 12\n";
  out += "pop ecx \n";
  return compiled;

}
Example #23
0
Move Move::getMove(const string &input) {
    Move move;
    move.length = 0;
    int length = input.length();

    /* move d2 */
    if (length == 7) {
        int x = input.at(5) - 'a';
        int y = 7 - input.at(6) + '0';
        int i = getIdx(x, y);
        if (i == -1) return move;
        move.length = 1;
        move.capture = false;
        move.x = i;
        return move;
    }

    /* move d2d3 */
    if (length == 9) {
        int x1 = input.at(5) - 'a';
        int y1 = 7 - input.at(6) + '0';
        int i1 = getIdx(x1, y1);
        if (i1 == -1) return move;
        int x2 = input.at(7) - 'a';
        int y2 = 7 - input.at(8) + '0';
        int i2 = getIdx(x2, y2);
        if (i2 == -1) return move;
        move.length = 2;
        move.capture = false;
        move.x = i1;
        move.y = i2;
        return move;
    }

    /* move d2,d3 */
    if (length == 10) {
        int x1 = input.at(5) - 'a';
        int y1 = 7 - input.at(6) + '0';
        int i1 = getIdx(x1, y1);
        if (i1 == -1) return move;
        int x2 = input.at(8) - 'a';
        int y2 = 7 - input.at(9) + '0';
        int i2 = getIdx(x2, y2);
        if (i2 == -1) return move;
        move.length = 2;
        move.capture = true;
        move.x = i1;
        move.y = i2;
        return move;
    }

    /* move a1d1,f4 */
    if (length == 12) {
        int x1 = input.at(5) - 'a';
        int y1 = 7 - input.at(6) + '0';
        int i1 = getIdx(x1, y1);
        if (i1 == -1) return move;
        int x2 = input.at(7) - 'a';
        int y2 = 7 - input.at(8) + '0';
        int i2 = getIdx(x2, y2);
        if (i2 == -1) return move;
        int comma = input.at(9);
        if (comma != ',') return move;
        int x3 = input.at(10) - 'a';
        int y3 = 7 - input.at(11) + '0';
        int i3 = getIdx(x3, y3);
        if (i3 == -1) return move;
        move.length = 3;
        move.capture = true;
        move.x = i1;
        move.y = i2;
        move.z = i3;
        return move;
    }
    return move;
}
Example #24
0
void RenderingConfig::SetUpOpenCLDevices(const bool useCPUs, const bool useGPUs,
	const unsigned int forceGPUWorkSize, const unsigned int oclDeviceThreads, const string &oclDeviceConfig) {

	std::vector<DeviceDescription *> descs = ctx->GetAvailableDeviceDescriptions();
	DeviceDescription::Filter(DEVICE_TYPE_OPENCL, descs);

	// Device info
	bool haveSelectionString = (oclDeviceConfig.length() > 0);
	if (haveSelectionString && (oclDeviceConfig.length() != descs.size())) {
		stringstream ss;
		ss << "OpenCL device selection string has the wrong length, must be " <<
				descs.size() << " instead of " << oclDeviceConfig.length();
		throw runtime_error(ss.str().c_str());
	}

	std::vector<DeviceDescription *> selectedDescs;
#if !defined(LUXRAYS_DISABLE_OPENCL)
	for (size_t i = 0; i < descs.size(); ++i) {
		OpenCLDeviceDescription *desc = (OpenCLDeviceDescription *)descs[i];

		if (haveSelectionString) {
			if (oclDeviceConfig.at(i) == '1') {
				if (desc->GetOpenCLType() == OCL_DEVICE_TYPE_GPU)
					desc->SetForceWorkGroupSize(forceGPUWorkSize);
				selectedDescs.push_back(desc);
			}
		} else {
			if ((useCPUs && desc->GetOpenCLType() == OCL_DEVICE_TYPE_CPU) ||
					(useGPUs && desc->GetOpenCLType() == OCL_DEVICE_TYPE_GPU)) {
				if (desc->GetOpenCLType() == OCL_DEVICE_TYPE_GPU)
					desc->SetForceWorkGroupSize(forceGPUWorkSize);
				selectedDescs.push_back(descs[i]);
			}
		}
	}
#endif

	if (selectedDescs.size() == 0)
		cerr << "No OpenCL device selected" << endl;
	else {
#if !defined(LUXRAYS_DISABLE_OPENCL)
		if (cfg.GetInt("opencl.latency.mode", 1) && (cfg.GetInt("renderengine.type", 0) == 3) &&
				(cfg.GetInt("pathgpu.openglinterop.enable", 0) != 0)) {
			// Ask for OpenGL interoperability on the first device
			((OpenCLDeviceDescription *)selectedDescs[0])->EnableOGLInterop();
		}
#endif

		// Allocate devices
		const size_t gpuRenderThreadCount = (oclDeviceThreads < 1) ?
				(2 * selectedDescs.size()) : oclDeviceThreads;
		if ((gpuRenderThreadCount == 1) && (selectedDescs.size() == 1)) {
			// Optimize the special case of one render thread and one GPU
			intersectionGPUDevices =  ctx->AddIntersectionDevices(selectedDescs);
		} else if ((gpuRenderThreadCount > 1) && (selectedDescs.size() == 1)) {
			// Optimize the special case of many render thread and one GPU
			intersectionGPUDevices =  ctx->AddVirtualM2OIntersectionDevices(gpuRenderThreadCount, selectedDescs);
		} else {
			// Create and start the virtual devices (only if there is more than one GPUs)
			intersectionGPUDevices =  ctx->AddVirtualM2MIntersectionDevices(gpuRenderThreadCount, selectedDescs);
		}

		cerr << "OpenCL Devices used: ";
		for (size_t i = 0; i < intersectionGPUDevices.size(); ++i)
			cerr << "[" << intersectionGPUDevices[i]->GetName() << "]";
		cerr << endl;
	}
}
Example #25
0
int zpracujAdresu(int argc, char *argv[])
{
	celaAdresa.clear();
	celaAdresa.append(argv[argc-1]);
	userName.clear();
	userPassword.clear();
	adresaServeru.clear();
	int nam = 1;
	int pas = 1;
	int i = 0;
	int zac = 0;

	if (celaAdresa.compare(0,6, "ftp://") == 0) //pokial adresa zacina na ftp://
	{
		i = 6;
		zac = 1;
		if (celaAdresa.compare(6,4, "ftp.") == 0) //pokiald je ftp
		{
			nam = 0;		 //ak je priamo zadana hodnota ftp a nieje zadane meno a heslo hosta je potrebne pouzit 							anonymne prihlasenie
			pas = 0;
			i = 10;
			adresaServeru.append("ftp.");
			}
	}
	else if (celaAdresa.compare(0,4, "ftp.") == 0)       //ak je adresa bez ftp:// a hned nasleduje ftp.
	{
		i = 4;
		adresaServeru.append("ftp.");
		nam = 0;		//ak je priamo zadana hodnota ftp a nieje zadane meno a heslo hosta je potrebne pouzit anonymne prihlasenie
		pas = 0;
	}

	if (nam == 0 && pas == 0)
	{
		userName.append("anonymous");
		userPassword.append("secret");
	}
	int p = i;
	while(i < celaAdresa.length()) //nacitaj hosta
	{
		string tmpStr;
		tmpStr.clear();
		tmpStr += celaAdresa.at(i);
		if (celaAdresa.compare(i,1, "@") == 0)
		{
			if(zac == 0)
			{
				fprintf(stderr, " Musis pridat ftp:// na zaciatok !\n");
				return -1;
			}
			if(nam != 0 && pas!=0)
			{
			int wrname = 1;
			int wrpass = 0;
				while(p<i) // rozdelenie a ulezenie username a pass
				{
					if (celaAdresa.compare(p,1, ":") == 0)
					{
						wrname = 0;
						wrpass = 1;
					}
					else if(wrname == 1)
					{
						userName += celaAdresa.at(p);					
					}
					else if(wrpass == 1)
					{
						userPassword +=	celaAdresa.at(p);
					}
					p++;
				}
				if(userName.length() == 0 ){
					fprintf(stderr, " Chyba meno uzivatele !\n");
					return -1;
				}
				else if(userPassword.length() == 0 ){
					fprintf(stderr, "Chyba heslo uzivatele !\n");
					return -1;
				}
			break;
			}
		}

		if(nam == 0 && pas == 0)
		{
			if (celaAdresa.compare(i,1, ":") == 0) //pokial bolo zadane cislo portu
				break;
		}		
		
		if (celaAdresa.compare(i,1, "/") == 0)
			break;

		if (isspace(celaAdresa.at(i)))
		{
			fprintf(stderr, "Medzera v adrese!\n");
			return -1;
		}
		adresaServeru += tmpStr;
		i++;
	}
//////////////////Nacitanie adresy
	if(celaAdresa.compare(i,1, "@") == 0)
	{
		i++;
		if(celaAdresa.compare(i,4, "ftp.") == 0)
		{
			adresaServeru.clear();
			while(i < celaAdresa.length())
			{
				string tmpStr;
				tmpStr.clear();
				if (celaAdresa.compare(i,1, "/") == 0) //zadany path
					break;
				if (celaAdresa.compare(i,1, ":") == 0) //pokial bolo zadane cislo portu
					break;
				if (isspace(celaAdresa.at(i)))
				{
					fprintf(stderr, "Medzera v adrese!\n");
					return -1;
				}
				tmpStr += celaAdresa.at(i);
				adresaServeru += tmpStr;
				i++;
			}
		}
		else
		{
			fprintf(stderr, " Chyba meno ftp serveru !\n");
			return -1;
		}
	}
////////////////////////////////////////////PORTTTTTTPORTTTT
	if (celaAdresa.compare(i,1, ":") == 0) //nacitam cislo portu
	{
		i++;
		if(celaAdresa.compare(i,2, "21") == 0)
			port = 21;
		else 
		{
			fprintf(stderr, "Zly port pouzite port 21\n");
			return -1;
		}
		i+=2;
		if(i < celaAdresa.length() )
		{
			if (celaAdresa.compare(i,1, "/") != 0)
			{
				fprintf(stderr, "Zle zadane parametre!\n");
				return -1;
			}
		}
	}
//////////////////////////////////////////////////////////////PATH
	if (celaAdresa.compare(i,1, "/") == 0)
	{
		path.clear();
			while (i < celaAdresa.length()) //nacita zostatok adresy PATH
			{
				string tmpStr;
				tmpStr.clear();
				tmpStr += celaAdresa.at(i);
				path += tmpStr;
				i++;
			}
	}
return 0;
}
void read_vs_reference(string& read, string& read_name_first, int dir, vector<reference_index>& refindex, 
				vector<pair<int, vector<pair<int, int> > > >& primary_chain)
{
	time_t start, end;

	unordered_map<long, int> kmer_list;
	//vector<pair<int, vector<pair<int, int> > > > primary_chain;
	cout << "\t readseq_first: " << read_name_first << " with length = " << read.length() 
			<< " comparing to " << refindex.size() << " references" << endl;
	
	time(&start);

	bool flag = true;
	long hash_key = 0;
	int map_val; 

	for(int k = 0; k < read.length(); k++)
	{
		if(flag == true && k + KMER > read.length())
			break;
		for(int l = k, end = k, i = KMER - 2; l < end + KMER - 1 && flag == true; l++, k++, i--)
		{
			map_val = map_value(read.at(l));
			if(map_val == -1)
				break;

			hash_key += base_power_kmer[i][map_val];
			
			//cout << "For character " << read.at(k) << ", at position = " << k <<
			//	", the hash_key = " << hash_key << endl;
		}

		map_val = map_value(read.at(k));
		if(map_val == -1)
		{
			//cout << "Encountered invalid character N ########################" << endl;
			flag = true;
			hash_key = 0;
			continue;
		}
		else
			flag = false;

		hash_key = hash_key * BASE + map_val;

		if(kmer_list.find(hash_key) == kmer_list.end())
		{
			kmer_list[hash_key] = k - KMER + 1;
		}
		else
			kmer_list[hash_key] = -1;//need work here
		//cout << "For character " << read.at(k) << ", at position = " << k <<
		//		", the hash_key = " << hash_key << endl;
	
		map_val = map_value(read.at(k - KMER + 1));
		hash_key -= base_power_kmer[KMER - 1][map_val];
	}



	for(int index = 0; index < refindex.size(); index++)
	{
		vector<pair<int, int> > kmer_index;
	
		for(auto it = kmer_list.cbegin(); it != kmer_list.cend(); ++it)
		{
			//std::cout << " " << it->first << ":" << it->second;  // cannot modify *it
  			//std::cout << std::endl;
			
			if(it->second != -1 && refindex.at(index).index[it->first] != -1)
			{
				vector<int> pos = refindex.at(index).position.at(refindex.at(index).index[it->first]);
				//cout << "Size of the Vector == " << pos.size() << endl;
				//if(pos.size() > 3)//experiment 04-21-2015 failed
				//	continue;			

				for(int i = 0; i < pos.size(); i++)
				{
					kmer_index.push_back(make_pair(pos.at(i), it->second));
				}
			}
			
		}
		
		if(kmer_index.size() == 0) 
			continue;

		sort(kmer_index.begin(), kmer_index.end(), compare_function);
		/*		
		for(int k = 0; k < kmer_index.size(); k++)
		{
			cout << "For the ref_index = " << index << ": " << kmer_index.at(k).first << ": " << 
				kmer_index.at(k).second << endl;
		}
		
		cout << endl << "After the refinement: " << endl << endl;
		*/
		refine_kmer_index(kmer_index, primary_chain, read, dir, refindex, index);
		/*
		for(int k = 0; k < kmer_index.size(); k++)
		{
			cout << "For the ref_index = " << index << ": " << kmer_index.at(k).first << ": " << 
				kmer_index.at(k).second << endl;
		}
		
		cout << endl;
		*/
		/*
		int first_index, last_index;
		int max_count = 0, count = 0;
		int i = 0, j = 0;
		bool flag = true;

		for(int k = 0; k < kmer_index.size(); k++)
                {
                        if(kmer_index[k].first == -1)
                                continue;

                        first_index = kmer_index[k].first + 1 - kmer_index[k].second;///1.3
                        last_index = kmer_index[k].first + 1 - kmer_index[k].second + read.length() / 1.35;
                        if((first_index >= 1) && (last_index <= refindex[index].ref.length()))
                        {
                                //kmer_ref.push_back(make_pair(index * MAXLEN + dir, make_pair(first_index, last_index)));
                                kmer_ref.push_back(make_pair(index * MAXLEN + dir, kmer_index[k]));
                                //cout << "Pushing: first = " << kmer_index[i].first << " And second = " << kmer_index[i].second << endl;
                        }

		}
		*/

		kmer_index.clear();

	}

	time(&end);

	cout << "Total time taken inside read_vs_reference = " << difftime(end, start) << endl;
	cout << "size of the candidate idices = " << primary_chain.size() << endl << endl;
	
	kmer_list.clear();
	/*
	sort(primary_chain.begin(), primary_chain.end(), compare_chain);

	for(int i = 0; i < primary_chain.size(); i++)
        {
                cout << "\t" << i << ") " << primary_chain[i].first << " == " << primary_chain[i].second.size() << endl;
                for(int k = 0; k < primary_chain[i].second.size(); k++)
                        cout << "\t\tref = " << primary_chain[i].second[k].first << " : read = " <<
                                primary_chain[i].second[k].second << " : diff = "  <<
                                (primary_chain[i].second[k].first - primary_chain[i].second[k].second) << endl;
        }
	
        primary_chain.clear();
	*/

	return;
}
Example #27
0
bool isWin()
{
    for (int i = 0; i < word.length(); i++)
        if (word.at(i) != '*') return false;
    return true;
}
bool find_alignment_direction(string& read, reference_index& reference, ofstream& fp_detail)
{
	time_t start, end;

	time(&start);

	bool flag = true;
	long hash_key = 0;
	int map_val;
	int forward_map_count = 0;
	int reverse_map_count = 0; 

	for(int k = 0; k < read.length() && k < SEED; k++)
	{
		if(flag == true && k + KMER > read.length())
			break;
		for(int l = k, end = k, i = KMER - 2; l < end + KMER - 1 && flag == true; l++, k++, i--)
		{
			map_val = map_value(read.at(l));
			if(map_val == -1)
				break;

			hash_key += base_power_kmer[i][map_val];
			
			//cout << "For character " << read.at(k) << ", at position = " << k <<
			//	", the hash_key = " << hash_key << endl;
		}

		map_val = map_value(read.at(k));
		if(map_val == -1)
		{
			//cout << "Encountered invalid character N ########################" << endl;
			flag = true;
			hash_key = 0;
			continue;
		}
		else
			flag = false;

		hash_key = hash_key * BASE + map_val;

		if(reference.index[hash_key] != -1)
		{
			forward_map_count += 1;
		}
		if(reference.revind[hash_key] != -1)
		{
			reverse_map_count += 1;
		}
		
		//cout << "For character " << read.at(k) << ", at position = " << k <<
		//		", the hash_key = " << hash_key << endl;
	
		map_val = map_value(read.at(k - KMER + 1));
		hash_key -= base_power_kmer[KMER - 1][map_val];
	}

	if(forward_map_count >= reverse_map_count)
		return true;
	else 
		return false;

}
Example #29
0
void printl(struct stat s, string fdName, unsigned &width) {

	// if link
	// print 'l'
	if(S_ISLNK(s.st_mode)) {
		cout << 'l';
	}
	// else if directory
	// print 'd'
	else if(S_ISDIR(s.st_mode)) {
		cout << 'd';
	}
	// else, neither link nor directory
	// print '-'
	else {
		cout << '-';
	}

	// if user has read permission, print 'r'
	// else print '-' indicating no read permission
	//cout << (s.st_mode & S_IRUSR)?"r":"-"
	if(s.st_mode & S_IRUSR) {
		cout << 'r';
	}
	else {
		cout << '-';
	}
	// if user has write permission, print 'w'
	// else print '-' indicating no write permission
	if(s.st_mode & S_IWUSR) {
		cout << 'w';
	}
	else {
		cout << '-';
	}
	// if user has execute permission, print 'x'
	// else print '-' indicating no execute permission
	if(s.st_mode & S_IXUSR) {
		cout << 'x';
	}
	else {
		cout << '-';
	}

	//----------------------------------------
	// if group has read permission, print 'r'
	// else print '-' indicating no read permission
	if(s.st_mode & S_IRGRP) {
		cout << 'r';
	}
	else {
		cout << '-';
	}
	// if group has write permission, print 'w'
	// else print '-' indicating no write permission
	if(s.st_mode & S_IWGRP) {
		cout << 'w';
	}
	else {
		cout << '-';
	}
	// if group has execute permission, print 'x'
	// else print '-' indicating no execute permission
	if(s.st_mode & S_IXGRP) {
		cout << 'x';
	}
	else {
		cout << '-';
	}

	//----------------------------
	// if others has read permission, print 'r'
	// else print '-' indicating no read permission
	if(s.st_mode & S_IROTH) {
		cout << 'r';
	}
	else {
		cout << '-';
	}
	// if others has write permission, print 'w'
	// else print '-' indicating no write permission
	if(s.st_mode & S_IWOTH) {
		cout << 'w';
	}
	else {
		cout << '-';
	}
	// if others has execute permission, print 'x'
	// else print '-' indicating no execute permission
	if(s.st_mode & S_IXOTH) {
		cout << 'x';
	}
	else {
		cout << '-';
	}
	
	cout << ' ';

	// print number of hard links
	cout << setw(5) << right << s.st_nlink;

	cout << ' ';

	// print username
	struct passwd *userid = getpwuid(s.st_uid);
	if(userid == NULL) {
		perror("getpwuid");
		exit(1);
	}
	else {
		cout << userid->pw_name;
	}
	
	cout << ' ';
	
	// print groupname
	struct group *groupid = getgrgid(s.st_gid);
	if(groupid == NULL) {
		perror("getgrgid");
		exit(1);
	}
	else {
		cout << groupid->gr_name;
	}
	
	cout << ' ';
	cout << setw(8) << right << s.st_size;

	cout << ' ';

	// print time
	// if created in a different year, print year
	// else print time
	time_t time = s.st_mtime;
	struct tm *thisTime = localtime(&time);
	char printMD[100];
	char printYorT[100];
	char temp[100];
	string tempString;
	string year = "2015";
	strftime(temp, 100, "%G", thisTime);
	int tempWidth = 4;
	for(unsigned i = 0; temp[i] != '\0'; i++) {
		tempString += temp[i];
	}
	strftime(printMD, 100, "%b %e ", thisTime);
	cout << printMD;
	if(tempString == year) {
		strftime(printYorT, 100, "%H:%M", thisTime);
	}
	else {
		strftime(printYorT, 100, "%G", thisTime);
		tempWidth = 5;
	}

	cout << setw(tempWidth) << right << printYorT << setw(0);

	cout << ' ';

	// print file name
	// color code accordingly
	// blue(directories), green(executables), grayBack(hidden)
	if((fdName.at(0) == '.') && (s.st_mode & S_IFDIR)) {
		cout << blueOnGray;
	}
	else if((fdName.at(0) == '.') && (s.st_mode & S_IXUSR)) {
		cout << greenOnGray;
	}
	else if(fdName.at(0) == '.') {
		cout << whiteOnGray;
	}
	else if(s.st_mode & S_IFDIR) {
		cout << blue;
	}
	else if(s.st_mode & S_IXUSR) {
		cout << green;
	}
	
	cout << fdName << normal << endl;

}
Example #30
0
	string ranks[RANK_COUNT] = {"A", "2", "3", "4", "5", "6",
		"7", "8", "9", "10", "J", "Q", "K"};
		
	out << ranks[c.getRank()] << suits[c.getSuit()];
	
	return out;
}

istream &operator>>(istream &in, Card &c){
	string suits = "CDHS", ranks = "A234567891JQK";
	
	string str;
	in >> str;
	assert ( !in.fail() );
	
	//Read in the rank, make sure it's valid
	c.rank_ = (Rank)ranks.find( str.at(0) );
	assert ( c.rank_ != string::npos );
	
	//If it's a 10, make sure the 2nd character is a 0
	if ( c.rank_ == TEN ){
		assert(str.at(1) == '0');
		str.at(1) = str.at(2);
	}
	
	//Read in the suit, make sure it's valid
	c.suit_ = (Suit)suits.find( str.at(1) );
	assert ( c.suit_ != string::npos );
	
	return in;
}