Example #1
0
void setupShaders(){

multimap<string,string> shaderPrograms;
vector<string> files;
scanDirectory(files,"Shaders");

for(int x=0;x<files.size();x++){
//cout<<files.at(x)<<endl;

int temp=files.at(x).find(".");
string id=files.at(x).substr(0,temp);

shaderPrograms.insert(pair<string,string>(id,files.at(x)));
}

GLuint prog=0, shad=0;
string last="";
for (multimap<string,string>::iterator it=shaderPrograms.begin(); it!=shaderPrograms.end(); ++it){
    //std::cout << (*it).first << " => " << (*it).second << '\n';
    if(it->second[0]=='.')
    continue;
    if(it->first!=last){
    if(last!=""){

        glBindAttribLocation(prog,0,"in_Position");
        glBindAttribLocation(prog,1,"in_Color");
        glBindAttribLocation(prog,2,"in_Tex");
        glBindAttribLocation(prog,3,"in_Norm");

    glLinkProgram(prog);
	printLog(prog);

	//printf("%s",gluErrorString(glGetError()));
    }
    prog=glCreateProgram();
    shaders[it->first]=prog;
    last=it->first;
    }

    if(it->second.find("vert")!=string::npos)
    shad=loadShader("Shaders/"+it->second,GL_VERTEX_SHADER);
    else if(it->second.find("frag")!=string::npos)
    shad=loadShader("Shaders/"+it->second,GL_FRAGMENT_SHADER);
    else if(it->second.find("geom")!=string::npos)
    shad=loadShader("Shaders/"+it->second,GL_GEOMETRY_SHADER);
    //
    //else if(it->second.find("comp")!=string::npos)
    //shad=loadShader("Shaders/"+it->second,GL_COMPUTE_SHADER);
    else if(it->second.find("tess")!=string::npos)
    shad=loadShader("Shaders/"+it->second,GL_TESS_CONTROL_SHADER);
    else if(it->second.find("eval")!=string::npos)
    shad=loadShader("Shaders/"+it->second,GL_TESS_EVALUATION_SHADER);


    glAttachShader(prog,shad);
    //printf("%s\n",gluErrorString(glGetError()));
    subShaders.push_back(shad);
}

//link last program
if(last!=""){

        glBindAttribLocation(prog,0,"in_Position");
        glBindAttribLocation(prog,1,"in_Color");
        glBindAttribLocation(prog,2,"in_Tex");
        glBindAttribLocation(prog,3,"in_Norm");
        glLinkProgram(prog);
        printLog(prog);

    }

//printf("%s\n",gluErrorString(glGetError()));
for(map<string,GLuint>::iterator it=shaders.begin();it!=shaders.end();it++){
cout<<"loaded program "<<it->first<<" : "<<it->second<<endl;
printLog(prog);
}


}
Example #2
0
void make_graph(){
	//	1...line_num(49)
	//	0		1		2		...	48
	//  1*49+0	1*49+1	1*49+2	...	1*49+48
	//	2*49+0	2*49+1	2*49+2	...	2*49+48

	ifstream fin("input_1_2.txt");

	int line_pos = 0;

	int temp_yuan;
	double temp_time;

	while(fin >> temp_time >> temp_yuan){
		line_wait_time[line_pos] = temp_time;
		line_yuan[line_pos] = temp_yuan;

		string temp_line;
		fin >> temp_line;

		vector<string> split_line;
		while(temp_line.size() > 5){
			string temp = temp_line.substr(0, 5);
			split_line.push_back(temp);
			temp_line = temp_line.substr(6);
		}
		split_line.push_back(temp_line);

		for(int i = 0; i < split_line.size(); i ++){
			if(S_to_int.find(split_line[i]) == S_to_int.end()){
				S_to_int.insert(pair<string, int>(split_line[i], S_to_int_size));
				int_to_S.insert(pair<int, string>(S_to_int_size, split_line[i]));
				S_to_int_size ++;
			}

			//add row edge
			int current_s = S_to_int[split_line[i]];
			for(int p = 0; p < line_num; p ++){
				if(p != line_pos){
					addEdge(current_s * line_num + p, current_s * line_num + line_pos, temp_time / 2, temp_yuan);
				}
			}

			//add column edge
			if(i){
				int a, b;
				a = S_to_int[split_line[i - 1]];
				b = S_to_int[split_line[i]];
				
				if(temp_yuan == 3){
					addEdge(a * line_num + line_pos, b * line_num + line_pos, 5, 0);
					addEdge(b * line_num + line_pos, a * line_num + line_pos, 5, 0);
				}
				else{
					addEdge(a * line_num + line_pos, b * line_num + line_pos, 3, 0);
					addEdge(b * line_num + line_pos, a * line_num + line_pos, 3, 0);
				}
			}
		}

		line_pos ++;
	}

	start_node = line_num * S_to_int_size;
}
Example #3
0
bool CAlert::ProcessAlert(bool fThread)
{
    if (!CheckSignature())
        return false;
    if (!IsInEffect())
        return false;

    // alert.nID=max is reserved for if the alert key is
    // compromised. It must have a pre-defined message,
    // must never expire, must apply to all versions,
    // and must cancel all previous
    // alerts or it will be ignored (so an attacker can't
    // send an "everything is OK, don't panic" version that
    // cannot be overridden):
    int maxInt = std::numeric_limits<int>::max();
    if (nID == maxInt)
    {
        if (!(
                nExpiration == maxInt &&
                nCancel == (maxInt-1) &&
                nMinVer == 0 &&
                nMaxVer == maxInt &&
                setSubVer.empty() &&
                nPriority == maxInt &&
                strStatusBar == "URGENT: Alert key compromised, upgrade required"
                ))
            return false;
    }

    {
        LOCK(cs_mapAlerts);
        // Cancel previous alerts
        for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
        {
            const CAlert& alert = (*mi).second;
            if (Cancels(alert))
            {
                printf("cancelling alert %d\n", alert.nID);
                uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);
                mapAlerts.erase(mi++);
            }
            else if (!alert.IsInEffect())
            {
                printf("expiring alert %d\n", alert.nID);
                uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);
                mapAlerts.erase(mi++);
            }
            else
                mi++;
        }

        // Check if this alert has been cancelled
        BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
        {
            const CAlert& alert = item.second;
            if (alert.Cancels(*this))
            {
                printf("alert already cancelled by %d\n", alert.nID);
                return false;
            }
        }

        // Add to mapAlerts
        mapAlerts.insert(make_pair(GetHash(), *this));
        // Notify UI and -alertnotify if it applies to me
        if(AppliesToMe())
        {
            uiInterface.NotifyAlertChanged(GetHash(), CT_NEW);
            std::string strCmd = GetArg("-alertnotify", "");
            if (!strCmd.empty())
            {
                // Alert text should be plain ascii coming from a trusted source, but to
                // be safe we first strip anything not in safeChars, then add single quotes around
                // the whole string before passing it to the shell:
                std::string singleQuote("'");
                // safeChars chosen to allow simple messages/URLs/email addresses, but avoid anything
                // even possibly remotely dangerous like & or >
                std::string safeChars("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890 .,;_/:?@");
                std::string safeStatus;
                for (std::string::size_type i = 0; i < strStatusBar.size(); i++)
                {
                    if (safeChars.find(strStatusBar[i]) != std::string::npos)
                        safeStatus.push_back(strStatusBar[i]);
                }
                safeStatus = singleQuote+safeStatus+singleQuote;
                boost::replace_all(strCmd, "%s", safeStatus);

                if (fThread)
                    boost::thread t(runCommand, strCmd); // thread runs free
                else
                    runCommand(strCmd);
            }
        }
    }

    printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
    return true;
}
void
setupNextSubsession(RTSPClient* rtspClient) {
	UsageEnvironment& env = rtspClient->envir(); // alias
	StreamClientState& scs = ((ourRTSPClient*)rtspClient)->scs; // alias
	bool rtpOverTCP = false;

	if(rtspconf->proto == IPPROTO_TCP) {
		rtpOverTCP = true;
	}

	scs.subsession = scs.iter->next();
	do if (scs.subsession != NULL) {
		if (!scs.subsession->initiate()) {
			env << *rtspClient << "Failed to initiate the \"" << *scs.subsession << "\" subsession: " << env.getResultMsg() << "\n";
			setupNextSubsession(rtspClient); // give up on this subsession; go to the next one
		} else {
			if(strcmp("video", scs.subsession->mediumName()) == 0) {
				video_sess_fmt = scs.subsession->rtpPayloadFormat();
				video_codec_name = strdup(scs.subsession->codecName());
				if(port2channel.find(scs.subsession->clientPortNum()) == port2channel.end()) {
					int cid = port2channel.size();
					port2channel[scs.subsession->clientPortNum()] = cid;
#ifdef ANDROID
					if(rtspconf->builtin_video_decoder != 0) {
						video_codec_id = ga_lookup_codec_id(video_codec_name);
					} else {
					////// Work with ffmpeg
#endif
					/*if(init_vdecoder(cid, scs.subsession->fmtp_spropparametersets()) < 0) {
						rtsperror("cannot initialize video decoder(%d)\n", cid);
						rtspParam->quitLive555 = 1;
						return;
					}*/
					rtsperror("video decoder(%d) initialized (client port %d)\n",
						cid, scs.subsession->clientPortNum());
#ifdef ANDROID
					////////////////////////
					}
#endif
				}
			} else if(strcmp("audio", scs.subsession->mediumName()) == 0) {
				const char *mime = NULL;
				audio_sess_fmt = scs.subsession->rtpPayloadFormat();
				audio_codec_name = strdup(scs.subsession->codecName());
#ifdef ANDROID
				if((mime = ga_lookup_mime(audio_codec_name)) == NULL) {
					showToast(rtspParam->jnienv, "codec %s not supported", audio_codec_name);
					rtsperror("rtspclient: unsupported audio codec: %s\n", audio_codec_name);
					usleep(300000);
					rtspParam->quitLive555 = 1;
					return;
				}
				audio_codec_id = ga_lookup_codec_id(audio_codec_name);
				if(android_prepare_audio(rtspParam, mime, rtspconf->builtin_audio_decoder != 0) < 0)
					return;
				if(rtspconf->builtin_audio_decoder == 0) {
				//////////////////////////////////////
				rtsperror("init software audio decoder.\n");
#endif
				if(adecoder == NULL) {
					if(init_adecoder() < 0) {
						rtsperror("cannot initialize audio decoder.\n");
						rtspParam->quitLive555 = 1;
						return;
					}
				}
#ifdef ANDROID
				//////////////////////////////////////
				}
#endif
				rtsperror("audio decoder initialized.\n");
			}
			env << *rtspClient << "Initiated the \"" << *scs.subsession
				<< "\" subsession (client ports " << scs.subsession->clientPortNum() << "-" << scs.subsession->clientPortNum()+1 << ")\n";

			// Continue setting up this subsession, by sending a RTSP "SETUP" command:
			rtspClient->sendSetupCommand(*scs.subsession, continueAfterSETUP, False, rtpOverTCP ? True : False/*TCP?*/, False, NULL);
		}
		return;
	} while(0);
	//

	// We've finished setting up all of the subsessions.  Now, send a RTSP "PLAY" command to start the streaming:
	scs.duration = scs.session->playEndTime() - scs.session->playStartTime();
	rtspClient->sendPlayCommand(*scs.session, continueAfterPLAY);
}
int main() {
    
    int     T = 0; 
    
    while( scanf( "%s", s1 ) != EOF ) {

        scanf( "%d", &N );
        
        if( T++ )   puts( "" ); 
    
        printf( "Project %d\n", T ); 

        M.clear();

        for( int i = 0; i < N; ++i )
            G[i].clear();
        
        memset( R, -1, sizeof( R ) );
        memset( visited, 0, sizeof( visited ) );

        int X = 0; 
        for( int i = 0; i < N; ++i ) {
            
            scanf( "%s%s", s1, s2 );
            
            iter = M.find( s2 );
            if( iter == M.end() )
                y = M[s2] = X++;
            else    y = iter -> second;
            
            iter = M.find( s1 );
            if( iter == M.end() )
                x = M[s1] = X++;
            else    x = iter -> second;
            
            G[y].push_back( x );
            R[x] = y;
            
        }
        
        tt = 0;
        for( int i = 0; i < N; ++i ) {
            if( !visited[i] ) {
                v = i;
                while( R[v] != -1 )
                    v = R[v];
                top = 0;
                p1[top] = v;
                p2[top] = 0;
                visited[v] = true;
                in[v] = tt++;
                while( top >= 0 ) {
                    if( p2[top] < G[p1[top]].size() ) {
                        y = G[p1[top]][p2[top]]; 
                        if( !visited[y] ) {
                            in[y] = tt++;
                            visited[y] = true;
                            ++top;
                            p1[top] = y;
                            p2[top] = 0;
                        }
                        else    ++p2[top];
                    }
                    else    out[p1[top--]] = tt++;
                }
                
            }
        }
        
        for( scanf( "%d", &N ); N--; ) {
            scanf( "%s%s", s1, s2 );
            x = M[s1];
            y = M[s2];
            if( in[x] >= in[y] &&
                out[x] <= out[y] )
                puts( "Yes" );
            else
                puts( "No" );
        }
        

    } 

} 
Example #6
0
void xData::getMissing3 (map<int,pair<double,double> >& rcvd_gift, map<int,double>& bank, int depth, int maxdepth) {
   if(depth == maxdepth) return;
   map<int,pair<double,double> > my_gift;
   double amt_gift=0;
   for(map<int,pair<double,double> >::iterator it_rcvd = rcvd_gift.begin(); it_rcvd != rcvd_gift.end(); it_rcvd++) {
      int id = it_rcvd->first;
      double leader_gift = (it_rcvd->second).first;
      double follower_gift = (it_rcvd->second).second;
      if(depth != 0) {
         amt_gift = (follower_gift + leader_gift * GIFT_RATE ) / (double)(graph_[id].leaders.size() + graph_[id].followers.size());
         bank[id] += leader_gift * (1-GIFT_RATE);
      } else {
         amt_gift = ((follower_gift * GIFT_RATE) + (leader_gift * GIFT_RATE)) / (double)(graph_[id].leaders.size() + graph_[id].followers.size());
         bank[id] += ((follower_gift * (1-GIFT_RATE)) + (leader_gift * (1-GIFT_RATE)));
      }

      for(set<int>::iterator it_l = graph_[id].leaders.begin(); it_l != graph_[id].leaders.end(); it_l++) {
         my_gift[*it_l].first += amt_gift;
      }
      for(set<int>::iterator it_f = graph_[id].followers.begin(); it_f != graph_[id].followers.end(); it_f++) {
         my_gift[*it_f].second += amt_gift;
      }
   }
   getMissing3(my_gift, bank, depth+1, maxdepth);
}
Example #7
0
BBObj *_bbObjFromHandle( int handle,BBObjType *type ){
	map<int,BBObj*>::const_iterator it=handle_map.find( handle );
	if( it==handle_map.end() ) return 0;
	BBObj *obj=it->second;
	return obj->type==type ? obj : 0;
}
Example #8
0
    void run(std::istream& in)
    	    {
    	    vector<string> tokens;
    	    string line;
    	    int chromCol=0;
    	    int posCol=1;
    	    int idCol=2;
    	    int refCol=3;
    	    int altCol=4;
    	    int sampleCol=-1;

    	    while(getline(in,line,'\n'))
    		    {
    		    if(AbstractApplication::stopping()) break;
    		    if(line.empty() || line[0]=='#') continue;
    		    tokenizer.split(line,tokens);

    		    string chrom=tokens[chromCol];
    		    chat *p2;
    		    int pos=(int)strtol(tokens[posCol].c_str(),&p2,10);
    		    string id=tokens[idCol];
    		    string ref=tokens[refCol];
    		    string alt=tokens[altCol];
    		    string sampleName=tokens[sampleCol];
    		    Row* therow=NULL;
    		    if(!rows.empty() &&
    			rows.back()->pos->chrom.compare(chrom)==0 &&
    			rows.back()->pos->pos==pos &&
    			rows.back()->ref.compare(ref)==0 &&
    			rows.back()->alt.compare(alt)==0
    			)
    			{
    			therow=rows.back();
    			}
    		    else
    			{
    			therow=new Row;
    			therow->pos=new ChromPosition(chrom,pos);
    			therow->id.assign(id);
    			therow->ref.assign(ref);
    			therow->alt.assign(alt);
    			rows.push_back(therow);
    			}
    		    int index_sample=0;
    		    if(sampleCol==-1)
    			{
    			if(sample2col.empty())
    			    {
    			    Sample* sample=new Sample;
    			    sample->name.assign("Sample");
    			    sample->column_index=0;
    			    samples.push_back(sample);
    			    }
    			index_sample=0;
    			}
    		    else
    			{
			map<string,Sample*>::iterator r= sample2col.find(sampleName);
			if(r==sample2col.end())
			    {
			    Sample* sample=new Sample;
			    sample->name.assign(sampleName);
			    sample->column_index=sample2col.size();
			    index_sample=sample->column_index;
			    samples.push_back(sample);
			    sample2col.put(sample->name,sample);
			    }
			else
			    {
			    index_sample=r->second->column_index;
			    }
    			}

    		    if(index_sample>=therow->data.size())
    			{
    			therow->data.resize(index_sample+1);
    			}
    		    Data* data=new Data;
    		    therow->data.assign(index_sample,data);
    		    }
    	    }
Example #9
0
File: main.cpp Project: HuiD/ece590
void gameLoopCleanUp() {
    delete background;
    while(!colList.empty()) {
        CollisionPair * tmp = colList.back();
        colList.pop_back();
        delete tmp;
    }
    cout<<"collist"<<colList.size()<<endl;
    for(map<int, Hero* >::iterator it=heroGroup.begin(); it!=heroGroup.end(); ++it) {
        delete it->second;
        heroGroup.erase(it);
    }
    //                        while (!heroGroup.empty()){
    //                            Hero * tmp = heroGroup[0];
    //                            heroGroup.erase(0);
    //                            delete tmp;
    //                        }
    cout<<"hero"<<heroGroup.size()<<endl;

    while(!blocks.empty()) {
        Block * tmp = blocks.back();
        blocks.pop_back();
        delete tmp;
    }
    cout<<"block"<<blocks.size()<<endl;

    while(!explosionGroup.empty()) {
        Explosion * tmp = explosionGroup.back();
        explosionGroup.pop_back();
        delete tmp;
    }
    cout<<"exp"<<explosionGroup.size()<<endl;

    //                        while(!enemyGroup.empty()){
    //                            Enemy * tmp = enemyGroup.back();
    //                            enemyGroup.pop_back();
    //                            delete tmp;
    //                        }
    //                        cout<<"enemy"<<enemyGroup.size()<<endl;

    while(!bombGroup.empty()) {
        Bomb * tmp = bombGroup.back();
        bombGroup.pop_back();
        delete tmp;
    }
    cout<<"bomb"<<bombGroup.size()<<endl;

    while(!upgradeGroup.empty()) {
        Upgrade * tmp = upgradeGroup.back();
        upgradeGroup.pop_back();
        delete tmp;
    }
    cout<<"up"<<upgradeGroup.size()<<endl;

    TTF_CloseFont(text_font);
    delete tcpclient;
    delete udpclient;
    delete remoteip;
    Mix_HaltMusic();
    Mix_FreeMusic(mainMusic);
    delete winScreen;
    delete loseScreen;
}
void MultiTouchApp::draw()
{
	dx::enableAlphaBlending();
	dx::setMatricesWindow( getWindowSize() );
	dx::clear( Color( 0.1f, 0.1f, 0.1f ) );

	for( map<uint32_t,TouchPoint>::const_iterator activeIt = mActivePoints.begin(); activeIt != mActivePoints.end(); ++activeIt ) {
		activeIt->second.draw();
	}

	for( list<TouchPoint>::iterator dyingIt = mDyingPoints.begin(); dyingIt != mDyingPoints.end(); ) {
		dyingIt->draw();
		if( dyingIt->isDead() )
			dyingIt = mDyingPoints.erase( dyingIt );
		else
			++dyingIt;
	}
	
	// draw yellow circles at the active touch points
	dx::color( Color( 1, 1, 0 ) );
	for( vector<TouchEvent::Touch>::const_iterator touchIt = getActiveTouches().begin(); touchIt != getActiveTouches().end(); ++touchIt )
		dx::drawStrokedCircle( touchIt->getPos(), 20.0f );
}
Example #11
0
void callback(event *ev) {
    map<string, bool>::iterator iter;
    string hex_id;
    string actual_identifier;
    int ntohl_number_of_fragments;
    int distance;
    hex_id = chararray_to_hex(ev->id);
    switch (ev->type) {
        case SCOPE_PUBLISHED:
            cout << "SCOPE_PUBLISHED: " << hex_id << endl;
            delete ev;
            break;
        case SCOPE_UNPUBLISHED:
            cout << "SCOPE_UNPUBLISHED: " << hex_id << endl;
            delete ev;
            break;
        case START_PUBLISH:
            cout << "START_PUBLISH: " << hex_id << endl;
            /*I don't need to do anything here..The publisher will receive the backpath "hello" message implicitly when the first request for retransmission will be sent*/
            delete ev;
            break;
        case STOP_PUBLISH:
            cout << "STOP_PUBLISH: " << hex_id << endl;
            delete ev;
            break;
        case PUBLISHED_DATA:
            //cout << "PUBLISHED_DATA: " << hex_id << endl;
            pthread_mutex_lock(&global_mutex);
            iter = expectedInfo.find(ev->id.substr(0, ev->id.length() - PURSUIT_ID_LEN));
            if (iter != expectedInfo.end()) {
                /*this is not a retransmitted fragment*/
                if ((*iter).second == false) {
                    (*iter).second = true;
                    /*this is the the first fragment I receive*/
                    /*start measuring*/
                    gettimeofday(&start_tv, &tz);
                    printf("START TIME: %ld,%ld \n", start_tv.tv_sec, start_tv.tv_usec);
                    create_random_ID(backchannel_id);
                    ba->publish_info(backchannel_id, ev->id.substr(0, ev->id.length() - 2 * PURSUIT_ID_LEN) + algid1, DOMAIN_LOCAL, NULL, 0);
                    ba->subscribe_info(backchannel_id, ev->id.substr(0, ev->id.length() - 2 * PURSUIT_ID_LEN) + algid2, DOMAIN_LOCAL, NULL, 0);
                    efs = new ExpectedFragmentSequence();
                    efs->firstID = ev->id.substr(0, ev->id.length() - PURSUIT_ID_LEN) + string((const char *) ev->id.substr(ev->id.length() - PURSUIT_ID_LEN, sizeof (int)).c_str(), sizeof (int)) + hex_to_chararray("00000000");
                    memcpy(&ntohl_number_of_fragments, ev->id.substr(ev->id.length() - PURSUIT_ID_LEN, sizeof (int)).c_str(), sizeof (int));
                    efs->number_of_fragments = ntohl(ntohl_number_of_fragments);
                    efs->fragments_so_far = 1;
                    efs->fragments_map = bitvector(efs->number_of_fragments);
                    distance = calculate_number_of_fragments(efs->firstID, ev->id) - 1; //e.g. from 0 to 1 distance = 1
                    efs->fragments_map[distance] = true;
                    efs->time_beat = 3;
                    efs->p_to_s_channel = ev->id.substr(0, ev->id.length() - 2 * PURSUIT_ID_LEN) + algid2 + backchannel_id;
                    efs->s_to_p_channel = ev->id.substr(0, ev->id.length() - 2 * PURSUIT_ID_LEN) + algid1 + backchannel_id;
                    retransmission_channel_map.insert(pair<string, string > (efs->p_to_s_channel, bin_item_identifier));
                    efs->printEFS();
                    //cout << efs->fragments_map.to_string().c_str() << endl;
                    pthread_create(&timeout_thread, NULL, timeout_handler, NULL);
                } else {
                    distance = calculate_number_of_fragments(efs->firstID, ev->id) - 1; //e.g. from 0 to 1 distance = 1
                    if (bitvector::bit::unspecified_bool_type(efs->fragments_map[distance]) == false) {
                        efs->fragments_so_far++;
                        efs->fragments_map[distance] = true;
                        efs->time_beat = 3;
                        //cout << efs->fragments_map.to_string().c_str() << endl;
                        if (efs->fragments_so_far == efs->number_of_fragments) {
                            pthread_cancel(timeout_thread);
                            efs->printResult();
                            delete efs;
                            efs = NULL;
                            delete ev;
                            delete ba;
                            break;
                        }
                    } else {
                        cout << "Received a duplicate fragment: " << hex_id << endl;
                    }
                }
            } else {
                /*A retransmission*/
                actual_identifier = (*retransmission_channel_map.find(ev->id.substr(0, ev->id.length() - PURSUIT_ID_LEN))).second + ev->id.substr(ev->id.length() - PURSUIT_ID_LEN, PURSUIT_ID_LEN);
                distance = calculate_number_of_fragments(efs->firstID, actual_identifier) - 1; //e.g. from 0 to 1 distance = 1
                if (bitvector::bit::unspecified_bool_type(efs->fragments_map[distance]) == false) {
                    efs->fragments_so_far++;
                    efs->fragments_map[distance] = true;
                    efs->time_beat = 3;
                    //cout << efs->fragments_map.to_string().c_str() << endl;
                    if (efs->fragments_so_far == efs->number_of_fragments) {
                        pthread_cancel(timeout_thread);
                        efs->printResult();
                        delete efs;
                        efs = NULL;
                        delete ev;
                        delete ba;
                        break;
                    }
                } else {
                    cout << "Received a duplicate fragment: " << hex_id << endl;
                }
            }
            pthread_mutex_unlock(&global_mutex);
            delete ev;
            break;
    }
}
  void testInsanity(map<UserId, map<Numberz::type,Insanity> > &insane, const Insanity &argument) {
    printf("testInsanity()\n");

    Xtruct hello;
    hello.string_thing = "Hello2";
    hello.byte_thing = 2;
    hello.i32_thing = 2;
    hello.i64_thing = 2;

    Xtruct goodbye;
    goodbye.string_thing = "Goodbye4";
    goodbye.byte_thing = 4;
    goodbye.i32_thing = 4;
    goodbye.i64_thing = 4;

    Insanity crazy;
    crazy.userMap.insert(make_pair(Numberz::EIGHT, 8));
    crazy.xtructs.push_back(goodbye);

    Insanity looney;
    crazy.userMap.insert(make_pair(Numberz::FIVE, 5));
    crazy.xtructs.push_back(hello);

    map<Numberz::type, Insanity> first_map;
    map<Numberz::type, Insanity> second_map;

    first_map.insert(make_pair(Numberz::TWO, crazy));
    first_map.insert(make_pair(Numberz::THREE, crazy));

    second_map.insert(make_pair(Numberz::SIX, looney));

    insane.insert(make_pair(1, first_map));
    insane.insert(make_pair(2, second_map));

    printf("return");
    printf(" = {");
    map<UserId, map<Numberz::type,Insanity> >::const_iterator i_iter;
    for (i_iter = insane.begin(); i_iter != insane.end(); ++i_iter) {
      printf("%"PRId64" => {", i_iter->first);
      map<Numberz::type,Insanity>::const_iterator i2_iter;
      for (i2_iter = i_iter->second.begin();
           i2_iter != i_iter->second.end();
           ++i2_iter) {
        printf("%d => {", i2_iter->first);
        map<Numberz::type, UserId> userMap = i2_iter->second.userMap;
        map<Numberz::type, UserId>::const_iterator um;
        printf("{");
        for (um = userMap.begin(); um != userMap.end(); ++um) {
          printf("%d => %"PRId64", ", um->first, um->second);
        }
        printf("}, ");

        vector<Xtruct> xtructs = i2_iter->second.xtructs;
        vector<Xtruct>::const_iterator x;
        printf("{");
        for (x = xtructs.begin(); x != xtructs.end(); ++x) {
          printf("{\"%s\", %d, %d, %"PRId64"}, ", x->string_thing.c_str(), (int)x->byte_thing, x->i32_thing, x->i64_thing);
        }
        printf("}");

        printf("}, ");
      }
      printf("}, ");
    }
    printf("}\n");


  }
void *processRequest (void *socketid)
{
    int n;
    int *sock = (int*)socketid;
    int acceptSock = *sock; 
	string videoName;

    bool clientSignaledToClose = false;

    while(!clientSignaledToClose){
        char SIDReq[1024];
        memset(SIDReq, 0, sizeof(SIDReq));

        //Receive packet
        say("Receiving packet...\n");
        if ((n = Xrecv(acceptSock, SIDReq, sizeof(SIDReq), 0)) <= 0) {
            cerr << "Xrecv failed!" << endl;
            Xclose(acceptSock);
            delete sock;
            return NULL;
        }

        string SIDReqStr(SIDReq);
        say("Got request: " + SIDReqStr);
        // if the request is about number of chunks return number of chunks
        // since this is first time, you would return along with header

        // If Request contains "numchunks", return number of CID's.
        if(isNumChunksRequest(SIDReqStr)){
			// Get Video Name out of the request
			string prefix = "get numchunks ";
			videoName = SIDReqStr.substr(prefix.length());
			
			say("Request asks for number of chunks: " + videoName);

			//Figure out what video they would like
            			
			// Check to see if this video is the one that the user is looking for
			if(CIDlist.find(videoName) != CIDlist.end()){
				// Add the number of chunks to the string
	            stringstream yy;
	            yy << CIDlist[videoName]->size();
	            string response = yy.str();
	
	            // Add a character of whitespace to the response
				response += " ";
	
				// Append on the list of Server AD-HIDs to the response
				for(vector<string>::iterator it = ContentServerXidList[videoName]->begin();
					it != ContentServerXidList["BigBuckBunny"]->end();
					++it){
						response += *it + " ";
				}
	
		        // Send back the number of CIDs followed by list of AD-HIDs
	            say("Sending back " + response, LVL_DEBUG);
	            Xsend(acceptSock,(void *) response.c_str(), response.length(), 0);
			}
			else{
	            cerr << "Invalid Video Name: " << videoName << endl;
	            Xclose(acceptSock);
	            delete sock;
	            return NULL;
			}
        } 
        else if(isTerminationRequest(SIDReqStr)){
            clientSignaledToClose = true;
        }
		else if(isVideoSelectionRequest(SIDReqStr)){
			ostringstream oss;
			for(vector<string>::iterator it = videoList.begin(); it != videoList.end(); ++it){
				oss << *it << " ";
			}
			Xsend(acceptSock,(void *) oss.str().c_str(), oss.str().length(), 0);
		}
        else {
            // Otherwise, if the request was not about the number of chunks,
            // it must be a request for a certain chunk

            // Format of the request:   start-offset:end-offset
            // Each offset position corresponds to a CID (chunk)
            say("Request is for a certain chunk span");

            // Parse the Request, extract start and end offsets

            int findpos = SIDReqStr.find(":");
            // split around this position
            string prefix = "block ";
            string str = SIDReqStr.substr(prefix.length(), findpos);
            int start_offset = atoi(str.c_str()); 
            str = SIDReqStr.substr(findpos + 1);
            int end_offset = atoi(str.c_str());

            // construct the string from CIDlist
            // return the list of CIDs, NOT including end_offset
            string requestedCIDlist = "";
            for(int i = start_offset; i < end_offset; i++){
                requestedCIDlist += CIDlist[videoName]->at(i) + " ";
            }       
            Xsend(acceptSock, (void *)requestedCIDlist.c_str(), requestedCIDlist.length(), 0);
            say("sending requested CID list: ", LVL_DEBUG);
        }
    }

    Xclose(acceptSock);
    delete sock;
	return NULL;
}
Example #14
0
bool                              // returns true if success
processTreeSection(FILE *fp,
		   string& theline,
		   bool& new_section)
{
  string *tid  = NULL;
  TChain  *t1   = NULL;
  vector<string> v_tokens;

  string treename;

  if (gl_verbose)
    cout << "Processing Tree section" << endl;

  new_section=false;

  while (getLine(fp,theline,"Tree")) {
    if (!theline.size()) continue;
    if (theline[0] == '#') continue; // comments are welcome

    if (theline[0] == '[') {
      new_section=true;
      break;
    }

    string key, value;
    if (!getKeyValue(theline,key,value)) continue;

    //--------------------
    if (key == "id") {
    //--------------------
      if (tid != NULL) {
	cerr << "no more than one id per F1 section allowed " << value << endl;
	break;
      }
      tid = new string(value);
      
      map<string, TChain *>::const_iterator tit = glmap_id2chain.find(*tid);
      if (tit != glmap_id2chain.end()) {
	cerr << "Tree id " << *tid << " already defined" << endl;
	break;
      }
    //------------------------------
    } else if( key == "treename" ) {
    //------------------------------
      if( !tid ) {
	cerr << "id key must be defined first in the section" << endl; continue;
      }
      if( t1 ) {
	cerr << "Tree already defined" << endl; continue;
      }
      treename = value;

    //------------------------------
    } else if( key == "globslist" ) {
    //------------------------------
      t1 = getChainFromGlobslist(*tid,treename,value);
      if( !t1 )
	exit(-1);

    //------------------------------
    } else if( key == "copytree" ) {
    //------------------------------
      if( !tid ) {
	cerr << "id key must be defined first in the section" << endl; continue;      }
    
      Tokenize(value,v_tokens,",");
      
      if (v_tokens.size() != 2) {
	cerr << "copytree syntax expected: copytree=treeid,cutstring: " << value << endl; continue; }

      TChain *t2 = findChain(v_tokens[0]);
      if (!t2) {
	cerr << "tree " << v_tokens[0] << " must be defined previously" << endl; continue;    }
      if (gl_verbose)
	cout<<"Begin CopyTree of "<<v_tokens[0]<<" with selection "<<v_tokens[1]<<flush;
      
      t1 = (TChain *)(t2->CopyTree(v_tokens[1].c_str()));

      if( !t1 ) {
	cerr << "CopyTree failed" << endl; exit(-1); }

      if (gl_verbose)
	cout<<"...Done."<<endl;

    //------------------------------
    } else if( key == "save2file" ) {
    //------------------------------
      if( !t1 ) {
	cerr << "save2file: must define tree first" << endl; continue; }

      TFile *rootfile = openRootFile(value,"RECREATE");
      
      t1->SetDirectory(rootfile);
      t1->Write();
      rootfile->Flush();

      if (gl_verbose)
	cout << "Tree written to file " << value << endl;

      rootfile->Close();

    //------------------------------
    } else if( key == "unbinnedfit" ) {
    //------------------------------
      if( !tid ) {
	cerr << "id key must be defined first in the section" << endl; continue;      }
      if( !t1 ) {
	cerr << "Tree must already be defined using 'globslist'" << endl; continue;   }

      int fitresult=-99;

      Tokenize(value,v_tokens,",");
      switch(v_tokens.size()) {
      case 2: fitresult = t1->UnbinnedFit(v_tokens[0].c_str(),
					  v_tokens[1].c_str());
	break;
      case 3: fitresult = t1->UnbinnedFit(v_tokens[0].c_str(),
					  v_tokens[1].c_str(),
					  v_tokens[2].c_str()); 
	break;
      case 4: fitresult = t1->UnbinnedFit(v_tokens[0].c_str(),  // funcname
					  v_tokens[1].c_str(),  // varexp
					  v_tokens[2].c_str(),  // selection
					  v_tokens[3].c_str()); // option
	break;
      default:
	cerr << "unbinnedfit: expect 2-4 arguments separated by commas: " << value <<endl;
	exit(-1);
      }
      cout << "fit result returned = " << fitresult << endl;
      cout << "Number of selected entries in the fit = " << t1->GetSelectedRows() << endl;
    }
    else {
      cerr << "unknown key " << key << endl;
    }
  }

  if (tid) delete tid;
  return (t1 != NULL);
}                                                  // processTreesection
Example #15
0
bool CAlert::ProcessAlert()
{
    if (!CheckSignature())
        return false;
    if (!IsInEffect())
        return false;

    // alert.nID=max is reserved for if the alert key is
    // compromised. It must have a pre-defined message,
    // must never expire, must apply to all versions,
    // and must cancel all previous
    // alerts or it will be ignored (so an attacker can't
    // send an "everything is OK, don't panic" version that
    // cannot be overridden):
    int maxInt = std::numeric_limits<int>::max();
    if (nID == maxInt)
    {
        if (!(
                nExpiration == maxInt &&
                nCancel == (maxInt-1) &&
                nMinVer == 0 &&
                nMaxVer == maxInt &&
                setSubVer.empty() &&
                nPriority == maxInt &&
                strStatusBar == "URGENT: Alert key compromised, upgrade required"
                ))
            return false;
    }

    {
        LOCK(cs_mapAlerts);
        // Cancel previous alerts
        for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
        {
            const CAlert& alert = (*mi).second;
            if (Cancels(alert))
            {
                printf("cancelling alert %d\n", alert.nID);
                uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);
                mapAlerts.erase(mi++);
            }
            else if (!alert.IsInEffect())
            {
                printf("expiring alert %d\n", alert.nID);
                uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);
                mapAlerts.erase(mi++);
            }
            else
                mi++;
        }

        // Check if this alert has been cancelled
        BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
        {
            const CAlert& alert = item.second;
            if (alert.Cancels(*this))
            {
                printf("alert already cancelled by %d\n", alert.nID);
                return false;
            }
        }

        // Add to mapAlerts
        mapAlerts.insert(make_pair(GetHash(), *this));
        // Notify UI if it applies to me
        if(AppliesToMe())
            uiInterface.NotifyAlertChanged(GetHash(), CT_NEW);
    }

    printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
    return true;
}
Example #16
0
File: main.cpp Project: HuiD/ece590
int eventLoop(SDL_Surface * screen) {
    SDL_Event event;
    int animationCounter = 0;
    while(1) {
        while (SDL_PollEvent(&event)) {
            switch (event.type) {
            case SDL_KEYUP:
                if(handle_keyup(event.key.keysym.sym)==MENU) {
                    gameLoopCleanUp();
                    return MENU;
                }
                break;
            case SDL_KEYDOWN:
                handle_key(event.key.keysym.sym);
                break;
            }


        }

        handleNetwork();

        std::map<int, Hero*>::iterator it;
        for(it=heroGroup.begin(); it!=heroGroup.end(); ++it)
        {
            if (it->second->getVisible())
                it->second->update(blocks, colList, heroGroup, bombGroup, explosionGroup);
        }
        if(moved) {
            hero_pos newPos=heroGroup[myId]->getPos();
            heromessage msg;
            msg.LoadByte(newPos.x, newPos.y, newPos.id);
            udpclient->Send(msg,tcpclient->getIpAddress() ,-1);
            moved=false;
        }
        if(bombed)
        {
            int bombx, bomby, level;
            bombx=heroGroup[myId]->getBombx();
            bomby=heroGroup[myId]->getBomby();
            level=heroGroup[myId]->getBombLevel();
            bombmessage bmsg;
            bmsg.LoadByte(bombx, bomby, level);
            udpclient->Send(bmsg, tcpclient->getIpAddress(), -1);
            bombed=false;
        }
        for (int i = 0; i < blocks.size(); i++) {
            blocks[i]->update(colList, heroGroup, explosionGroup, upgradeGroup);
        }

        for (int i = 0; i < bombGroup.size(); i++) {
            bombGroup.at(i)->update(blocks, colList, heroGroup, bombGroup, explosionGroup);
        }
        for (int i = 0; i < explosionGroup.size(); i++) {
            explosionGroup.at(i)->update();
        }
        for (int i = 0; i < upgradeGroup.size(); i++) {
            upgradeGroup.at(i)->update();
        }

        for (int i = 0; i < colList.size(); i++) {
            CollisionPair * tmp = colList.at(i);
            if (tmp->isCollided()) {
                tmp->onCollision();
            }
        }

        background->blit(screen);

        if (Mix_PlayingMusic() == 0) {
            if (Mix_PlayMusic(mainMusic, -1) == -1)
                fprintf(stderr, "Unable to play WAV file: %s\n", Mix_GetError());
        }

        for (int j = 0; j < bombGroup.size(); j++) {
            bombGroup.at(j)->blit(screen);
        }
        for (int j = 0; j < explosionGroup.size(); j++) {
            SDL_Rect tmp = explosionGroup.at(j)->getShowPart();
            explosionGroup.at(j)->blit(screen, &tmp);
        }
        for (int i = 0; i < blocks.size(); i++) {
            blocks.at(i)->blit(screen);
        }

        for (int i = 0; i < upgradeGroup.size(); i++) {
            upgradeGroup.at(i)->blit(screen);
        }
        for(map<int, Hero* >::iterator it=heroGroup.begin(); it!=heroGroup.end(); ++it) {
            it->second->blit(screen);
        }

        for(map<int, Hero* >::iterator it=heroGroup.begin(); it!=heroGroup.end(); ++it) {
            sprintf(textbuf[it->first], "Player %d = %d", it->first+1, it->second->getLife());
            text_image[it->first] =  TTF_RenderText_Solid(text_font, textbuf[it->first], font_color);
            int offsetX = it->first<2 ? 0:1;
            int offsetY = it->first%2==0 ? 0:1;
            textDest[it->first].x = 50+750*offsetX;
            textDest[it->first].y = 10+50*offsetY;
            textDest[it->first].w = text_image[it->first]->w;
            textDest[it->first].h = text_image[it->first]->h;
            SDL_BlitSurface(text_image[it->first], NULL, screen, &(textDest[it->first]));
            SDL_FreeSurface(text_image[it->first]);
        }


        // game over
        bool iWin = false;
        if (heroGroup[myId]->getLife()!=0) {
            iWin = true;
            for(map<int, Hero* >::iterator it=heroGroup.begin(); it!=heroGroup.end(); ++it) {
                if (it->first != myId) {
                    if (it->second->getLife() != 0) {
                        iWin = false;
                        break;
                    }
                }
            }
        }
        bool iLose=false;
        if (heroGroup[myId]->getLife()==0) {
            iLose = true;
            int counter = 0;
            for(map<int, Hero* >::iterator it=heroGroup.begin(); it!=heroGroup.end(); ++it) {
                if (it->first != myId) {
                    if (it->second->getLife() != 0) {
                        counter++;
                        if (counter>1) {
                            iLose = false;
                            break;
                        }
                    }
                }
            }
        }

        if (iWin) {
            animationCounter++;
            if (animationCounter>20) {
                winScreen->blit(screen);
                SDL_Flip(screen);
                SDL_Delay(3000);
                gameLoopCleanUp();
                return MENU;
            }
        }
        else if (iLose) {
            animationCounter++;
            if (animationCounter>20) {
                loseScreen->blit(screen);
                SDL_Flip(screen);
                SDL_Delay(3000);
                gameLoopCleanUp();
                return MENU;
            }
        }

        /* since its double buffered, make
         the changes show up*/
        SDL_Flip(screen);

        SDL_Delay(50);
    }
    return 0;
}
Example #17
0
void xData::writeFiles (int A, map<int,map<string,pair<double,int> > >& prAfBrecSum, map<int,double>& bank, ofstream& attrFile, ofstream& edgeFile, bool isTrain) {
   if(1) {
      //cout << "--" << A << "--" << endl;
      vector<pair<int,double> > tmp;

      double max_bank = 0;
      if(0) {
         for(map<int,map<string,pair<double,int> > >::iterator it_rec = prAfBrecSum.begin(); it_rec != prAfBrecSum.end(); it_rec++) {
            if(it_rec->first == -1) continue;
            double prAvgSum = 0;
            int rec = it_rec->first;
            for(map<string,pair<double,int> >::iterator it_type = (it_rec->second).begin(); it_type != (it_rec->second).end(); it_type++) {
               string type = it_type->first;
               prAvgSum += (it_type->second).first / ((double)prAfBrecSum[-1][type].second * pow(2,(double)type.size()));
            }
            tmp.push_back(pair<int,double>(rec,prAvgSum));
         }
      } else {
         for(map<int,double>::iterator it_b = bank.begin(); it_b != bank.end(); it_b++) {
            if(graph_[A].leaders.find(it_b->first) != graph_[A].leaders.end() || it_b->first == A ) continue; // skip anyone I am already following or who is me
            tmp.push_back(pair<int,double>(it_b->first,it_b->second));
            if (it_b->second > max_bank) max_bank = it_b->second;
         }
      }
      sort(tmp.begin(),tmp.end(),sort_v_p_i_d_d);

      int counter=0;
      int rlast = int_min(tmp.size(),50);
      //int rlast = 50;
      for(vector<pair<int,double> >::iterator it_tmp = tmp.begin(); it_tmp != tmp.end() && counter < rlast; it_tmp++) {
         counter++;
         int id = (*it_tmp).first;
         if(isTrain) {
            if(validate_[A].find(id) != validate_[A].end()) attrFile << "1,";
            else attrFile << "0,";
         }
         double rank = (rlast<=1) ? 1.0 : (double)(rlast-counter)/(double)(rlast-1);
         attrFile << rank << ",";
         if(max_bank > 0) attrFile << it_tmp->second / max_bank << ",";
         else attrFile << "0,";
         attrFile << graph_[id].pLO << ",";
         attrFile << graph_[id].pFO << ",";
         attrFile << graph_[id].pFR << ",";
         attrFile << graph_[id].UC << ",";
         attrFile << graph_[A].pLO << ",";
         attrFile << graph_[A].pFO << ",";
         attrFile << graph_[A].pFR << ",";
         attrFile << graph_[A].UC << ",";
         //attrFile << graph_[id].leaders.size() << ",";
         //attrFile << graph_[id].followers.size() << ",";
         //int BsizeBinary = (graph_[id].leaders.size() + graph_[id].followers.size() > 30 ) ? 1 : 0;
         //attrFile << graph_[id].leaders.size() + graph_[id].followers.size() << ",";
         //attrFile << graph_[A].pLO * graph_[id].pFO << ","; 
         //attrFile << graph_[A].pFO * graph_[id].pLO << ",";
         //attrFile << graph_[A].pFR * graph_[id].pFR << ",";
         //int AsizeBinary = (graph_[A].leaders.size() + graph_[A].followers.size() > 30 ) ? 1 : 0;
         //attrFile << graph_[A].leaders.size() + graph_[A].followers.size() << ",";
         int types_count = 0;
         for(set<string>::iterator it_type = types_.begin(); it_type != types_.end(); it_type++) {
            types_count++;
            if(prAfBrecSum[id].find(*it_type) == prAfBrecSum[id].end()) {
               if(*it_type == "F") attrFile << "0,";
               else if(*it_type == "FF") attrFile << "0,";
               else if(*it_type == "LF") attrFile << "0,";
               else if(*it_type == "FL") attrFile << "0,";
               else if(*it_type == "LL") attrFile << "0,";
               attrFile << "0";
            } else {
               if(*it_type == "F") attrFile << graph_[id].myLsConnectBack_rate << ","; // << prAfBrecSum[id][*it_type].first;
               else if(*it_type == "FF") attrFile << graph_[id].myLsLsConnectBack_rate << ","; // << prAfBrecSum[id][*it_type].first;
               else if(*it_type == "LF") attrFile << graph_[id].myLsFsConnectBack_rate << ","; // << prAfBrecSum[id][*it_type].first;
               else if(*it_type == "FL") attrFile << graph_[id].myFsLsConnectBack_rate << ","; // << prAfBrecSum[id][*it_type].first;
               else if(*it_type == "LL") attrFile << graph_[id].myFsFsConnectBack_rate << ","; // << prAfBrecSum[id][*it_type].first;
               attrFile << prAfBrecSum[id][*it_type].first / (double)prAfBrecSum[-1][*it_type].second;
            }
            if(types_count < types_.size()) attrFile << ",";
         }
         attrFile << endl;
         edgeFile << A << "," << id << endl;
      }
      attrFile << flush;
      edgeFile << flush;
   }
}
Example #18
0
/**
 * This populates darkCorrections with the result of the equation:
 *   dark = a + x * b
 * for each line,band. a, b are from the "vis_*_dark_model.tab" files
 * and x is the ExposureDuration.
 *
 * @param icube
 */
void calculateVisDarkCurrent(Cube *icube) {
  PvlGroup &inst = icube->label()->findGroup("Instrument", Pvl::Traverse);

  // This is the dark current corrections for VIS
  bool hires = ((inst["SamplingMode"][0] == "HIGH") || (inst["SamplingMode"][0] == "HI-RES"));
  QString calFile = "$cassini/calibration/vims/vis_";

  if(hires) {
    calFile += "hires";
  }
  else {
    calFile += "lowres";
  }

  calFile += "_dark_model_v????.tab";

  FileName calFileName(calFile);
  calFileName = calFileName.highestVersion();

  calibInfo += PvlKeyword("DarkCurrentFile", calFileName.originalPath() + "/" + calFileName.name());

  calFile = calFileName.expanded();

  EndianSwapper swapper("LSB");

  FILE *calFilePtr = fopen(calFile.toAscii().data(), "r");

  double visExposure = toDouble(inst["ExposureDuration"][1]);

  int sampleOffset, lineOffset;
  GetOffsets(*icube->label(), sampleOffset, lineOffset);

  /**
   * Reading in one parameter at a time:
   *   parameter 1 = constant coefficient
   *   parameter 2 = exposure coefficient
   *   param1 + param2*exposure = dark correction
   *
   * Do byte swapping where necessary.
   */
  for(int parameter = 1; parameter <= 2; parameter ++) {
    for(int band = 1; band <= 96; band++) {
      for(int sample = 1; sample <= 64; sample++) {
        float calData;

        if(fread(&calData, sizeof(calData), 1, calFilePtr) != 1) {
          // error!
          QString msg = "Error reading file [" + calFile + "]";
          throw IException(IException::Io, msg, _FILEINFO_);
        }

        int associatedSample = sample - sampleOffset + 1;

        calData = swapper.Float(&calData);
        pair<int, int> index = pair<int, int>(associatedSample, band);

        map< pair<int, int>, double>::iterator pos = sampleBasedDarkCorrections.find(index);
        if(pos == sampleBasedDarkCorrections.end()) {
          sampleBasedDarkCorrections.insert(pair< pair<int, int>, double>(index, calData));
        }
        else {
          (*pos).second = (*pos).second + visExposure * calData;
        }
      }
    }
  }

  fclose(calFilePtr);

  // If spectral summing is on, go in sets of 8 and set darks to the average
  /*
  PvlGroup &archive = icube->Label()->findGroup("Archive", Pvl::Traverse);
  if(archive["SpectralSummingFlag"][0] == "ON") {
    for(int band = 1; band <= 96; band += 8) {
      for(int sample = 1; sample <= 64; sample++) {
        Statistics stats;

        // we're calculating an average of 8 of these values through the bands
        for(int avgIndex = 0; avgIndex < 8; avgIndex ++) {
          // this wont go out of bounds as long as we have 8 as the increment
          pair<int,int> index = pair<int,int>(sample, band+avgIndex);
          stats.AddData(sampleBasedDarkCorrections.find(index)->second);
        }

        // now set the values to the average
        for(int setIndex = 0; setIndex < 8; setIndex ++) {
          pair<int,int> index = pair<int,int>(sample, band+setIndex);
          if(!setIndex) printf("Changing %.4f to %.4f\n", sampleBasedDarkCorrections.find(index)->second, stats.Average());
          sampleBasedDarkCorrections.find(index)->second = stats.Average();
        }
      }
    }
  }*/
}
Example #19
0
void xData::getMissing (int id, map<int,EdgeRec>& myMissing, ofstream& attrFile, ofstream& edgeFile, bool isTrain) {
   int voter_limit = 10;
   int topN=9;
   double ls1_=0, ls2_=0;
   int ao_cnt=0, bo_cnt=0, ab_cnt=0;
   set<int> followers_only;
   venn(graph_[id].leaders, graph_[id].followers, ao_cnt, bo_cnt, ab_cnt, NULL, &(followers_only), NULL);
   if(recommend_Fs_) {
      for(set<int>::iterator it_fo = followers_only.begin(); it_fo != followers_only.end(); it_fo++) {
         myMissing[*it_fo].Fs=graph_[*it_fo].myLsConnectBack_rate;
      }
   }
   if(recommend_FsLs_) {
      map<int,double> myFsLs;
      int recommenders = 0;
      for(set<int>::iterator it_followers = graph_[id].followers.begin(); it_followers != graph_[id].followers.end(); it_followers++) {
         int follower = *it_followers;
         int ao_cnt=0, bo_cnt=0, ab_cnt=0;
         set<int> recommendations;
         venn(graph_[id].leaders,graph_[follower].leaders,ao_cnt,bo_cnt,ab_cnt,NULL,&recommendations,NULL);
         recommendations.erase(id);  // need to remove myself from recommendations
         if( bo_cnt > 0) {
            for(set<int>::iterator it_FsL = recommendations.begin(); it_FsL != recommendations.end(); it_FsL++) {
               int Fs_leader = *it_FsL;
               //myFsLs[Fs_leader] += 1.0 / (double)(recommendations.size());
               myFsLs[Fs_leader] += 1.0;
            }
            recommenders++;
         }
      }
      if(recommenders > 0) {
         vector<pair<int,double> > tmp;
         for(map<int,double>::iterator it_tmp=myFsLs.begin(); it_tmp!=myFsLs.end(); it_tmp++) {
            tmp.push_back(pair<int,double>(it_tmp->first,it_tmp->second));
         }
         sort(tmp.begin(),tmp.end(),sort_v_p_i_d_d);
         for(int i=0; i < tmp.size() && i < topN; i++) {
            myMissing[tmp[i].first].FsLs = (tmp[i].second+ls1_)/((double)recommenders+ls2_);
         }
      }
   }
   if(recommend_FsFs_) {
      map<int,double> myFsFs;
      int recommenders = 0;
      for(set<int>::iterator it_followers = graph_[id].followers.begin(); it_followers != graph_[id].followers.end(); it_followers++) {
         int follower = *it_followers;
         int ao_cnt=0, bo_cnt=0, ab_cnt=0;
         set<int> recommendations;
         venn(graph_[id].leaders,graph_[follower].followers,ao_cnt,bo_cnt,ab_cnt,NULL,&recommendations,NULL);
         recommendations.erase(id);  // need to remove myself from recommendations
         if( bo_cnt > 0) {
            for(set<int>::iterator it_FsF = recommendations.begin(); it_FsF != recommendations.end(); it_FsF++) {
               int Fs_follower = *it_FsF;
               //myFsFs[Fs_follower] += 1.0 / (double)(recommendations.size());
               myFsFs[Fs_follower] += 1.0;
            }
            recommenders++;
         }
      }
      if(recommenders > 0) {
         vector<pair<int,double> > tmp;
         for(map<int,double>::iterator it_tmp=myFsFs.begin(); it_tmp!=myFsFs.end(); it_tmp++) {
            tmp.push_back(pair<int,double>(it_tmp->first,it_tmp->second));
         }
         sort(tmp.begin(),tmp.end(),sort_v_p_i_d_d);
         for(int i=0; i < tmp.size() && i < topN; i++) {
            myMissing[tmp[i].first].FsFs = (tmp[i].second+ls1_)/((double)recommenders+ls2_);
         }
      }
   }
   if(recommend_LsLs_) {
      map<int,double> myLsLs;
      int recommenders = 0;
      for(set<int>::iterator it_leaders = graph_[id].leaders.begin(); it_leaders != graph_[id].leaders.end(); it_leaders++) {
         int leader = *it_leaders;
         int ao_cnt=0, bo_cnt=0, ab_cnt=0;
         set<int> recommendations;
         venn(graph_[id].leaders,graph_[leader].leaders,ao_cnt,bo_cnt,ab_cnt,NULL,&recommendations,NULL);
         recommendations.erase(id);  // need to remove myself from recommendations
         if( bo_cnt > 0) {
            for(set<int>::iterator it_LsL = recommendations.begin(); it_LsL != recommendations.end(); it_LsL++) {
               int Ls_leader = *it_LsL;
               //myLsLs[Ls_leader] += 1.0 / (double)(recommendations.size());
               myLsLs[Ls_leader] += 1.0;
            }
            recommenders++;
         }
      }
      if(recommenders > 0) {
         vector<pair<int,double> > tmp;
         for(map<int,double>::iterator it_tmp=myLsLs.begin(); it_tmp!=myLsLs.end(); it_tmp++) {
            tmp.push_back(pair<int,double>(it_tmp->first,it_tmp->second));
         }
         sort(tmp.begin(),tmp.end(),sort_v_p_i_d_d);
         for(int i=0; i < tmp.size() && i < topN; i++) {
            myMissing[tmp[i].first].LsLs = (tmp[i].second+ls1_)/((double)recommenders+ls2_);
         }
      }
   }
   if(recommend_LsFs_) {
      map<int,double> myLsFs;
      int recommenders = 0;
      for(set<int>::iterator it_leaders = graph_[id].leaders.begin(); it_leaders != graph_[id].leaders.end(); it_leaders++) {
         int leader = *it_leaders;
         int ao_cnt=0, bo_cnt=0, ab_cnt=0;
         set<int> recommendations;
         venn(graph_[id].leaders,graph_[leader].followers,ao_cnt,bo_cnt,ab_cnt,NULL,&recommendations,NULL);
         recommendations.erase(id);  // need to remove myself from recommendations
         if( bo_cnt > 0) {
            for(set<int>::iterator it_LsF = recommendations.begin(); it_LsF != recommendations.end(); it_LsF++) {
               int Ls_follower = *it_LsF;
               //myLsFs[Ls_follower] += 1.0 / (double)(recommendations.size());
               myLsFs[Ls_follower] += 1.0;
            }
            recommenders++;
         }
      }
      if(recommenders > 0) {
         vector<pair<int,double> > tmp;
         for(map<int,double>::iterator it_tmp=myLsFs.begin(); it_tmp!=myLsFs.end(); it_tmp++) {
            tmp.push_back(pair<int,double>(it_tmp->first,it_tmp->second));
         }
         sort(tmp.begin(),tmp.end(),sort_v_p_i_d_d);
         for(int i=0; i < tmp.size() && i < topN; i++) {
            myMissing[tmp[i].first].LsFs = (tmp[i].second+ls1_)/((double)recommenders+ls2_);
         }
      }
   }
   if(recommend_LsFsLs_) {
      set<int> myLsFs; // my leaders followers
      //cout << "find my leaders followers" << endl;
      for(set<int>::iterator it_leaders = graph_[id].leaders.begin(); it_leaders != graph_[id].leaders.end(); it_leaders++) {
         int leader = *it_leaders;
         myLsFs.insert(graph_[leader].followers.begin(),graph_[leader].followers.end());
      }
      myLsFs.erase(id); // need to remove myself from my leaders followers
      vector<Voter> voters;
      //cout << "calculate distance and find recs" << endl;
      for(set<int>::iterator it_myLsFs = myLsFs.begin(); it_myLsFs != myLsFs.end(); it_myLsFs++) {
         Voter v;
         int ao_cnt=0, bo_cnt=0, ab_cnt=0;
         venn(graph_[id].leaders, graph_[*it_myLsFs].leaders, ao_cnt, bo_cnt, ab_cnt, NULL, &(v.recommendations) /*b*/, NULL);
         v.recommendations.erase(id);  // need to remove myself
         bo_cnt--;
         v.id=*it_myLsFs;
         v.overlap=(double)ab_cnt/(double)(ao_cnt+bo_cnt+ab_cnt);
         voters.push_back(v);
      }
      sort(voters.begin(),voters.end(),sort_v_v_d);
      int v_count=0;
      int vR_count=0;
      for(vector<Voter>::iterator it_voter=voters.begin(); it_voter != voters.end(); it_voter++) {
         if(v_count < voter_limit) {
            if(graph_[id].leaders.find(it_voter->id) == graph_[id].leaders.end()) { // check to see if I am already following this person
               //myMissing[it_voter->id].LsFs+=it_voter->overlap;
               v_count++;
            }
         }
         if(vR_count < voter_limit) {
            if(it_voter->recommendations.size() == 0) continue; // need to allow voters with no recommendations for LsFs
            for(set<int>::iterator it_r=it_voter->recommendations.begin(); it_r!=it_voter->recommendations.end(); it_r++) {
               myMissing[*it_r].LsFsLs += it_voter->overlap / ((double)int_min(voter_limit,voters.size())*(double)it_voter->recommendations.size());
               //myMissing[*it_r].LsFsLs += it_voter->overlap / ((double)int_min(voter_limit,voters.size()));
               //myMissing[*it_r].LsFsLs += 1.0 / ((double)int_min(voter_limit,voters.size()));
            }
            vR_count++;
         }
         if(v_count == voter_limit && vR_count == voter_limit) break;
      }
   }
   for(map<int,EdgeRec>::iterator it_missing = myMissing.begin(); it_missing != myMissing.end(); it_missing++) {
      if(isTrain) {
         if(validate_[id].find(it_missing->first) != validate_[id].end()) attrFile << "1,";
         else attrFile << "0,";
      }
      // !!! DON'T FORGET TO CHANGE THE HEADER STRING header1 if you modify the attributes !!!
      attrFile << it_missing->second.Fs << "," \
               << it_missing->second.FsLs << "," \
               << it_missing->second.FsFs << "," \
               << it_missing->second.LsLs << "," \
               << it_missing->second.LsFs << "," \
               << it_missing->second.LsFsLs << endl << flush;
      edgeFile << id << "," << it_missing->first << endl << flush;
   }

}
Example #20
0
/**
 * This calculates the dark current corrections for IR. If
 * IRDARKAVG is false, then it translates the sideplane data
 * into the lineBasedDarkCorrections map directly and does nothing further
 * with the data. Otherwise, this will apply a least squares linear
 * fit (the original script did chi-squared, but this is okay) for
 * each band and uses the points on the line instead of the sideplane
 * data directly.
 *
 * @param icube
 */
void calculateIrDarkCurrent(Cube *icube) {
  UserInterface &ui = Application::GetUserInterface();

  bool found = false;

  // verify if IR we have sideplane data
  for(int obj = 0; !found && obj < icube->label()->objects(); obj++) {
    PvlObject &object = icube->label()->object(obj);

    if(object.name() != "Table") continue;

    if(object.hasKeyword("Name") && object["Name"][0] == "SideplaneIr") found = true;
  }

  if(!found) {
    calibInfo += PvlKeyword("SideplaneCorrection", "None");
    return;
  }

  Table sideplane("SideplaneIr", ui.GetFileName("FROM"));

  // If spectal summing is on OR compressor_id isnt N/A then
  //   just return.
  PvlGroup &archive = icube->label()->findGroup("Archive", Pvl::Traverse);

  // If dark subtracted (compressorid is valid) and cant do linear
  //   correction (spectral editing flag on) then do not do dark
  if(archive["CompressorId"][0] != "N/A" &&
      archive["SpectralEditingFlag"][0] == "ON") {
    calibInfo += PvlKeyword("SideplaneCorrection", "None");
    return;
  }

  // If subtracted (compressor id is valid) and dont do linear then return
  if(archive["CompressorId"][0] != "N/A" && ui.GetBoolean("IRORIGDARK") == true) {
    calibInfo += PvlKeyword("SideplaneCorrection", "None");
    return;
  }

  if(archive["SpectralSummingFlag"][0] == "ON") return;

  // Insert the sideplane data into our lineBasedDarkCorrections map (line,band to correction)
  for(int line = 1; line <= icube->lineCount(); line++) {
    for(int band = 1; band <= icube->bandCount(); band++) {
      pair<int, int> index = pair<int, int>(line, band);
      int value = (int)sideplane[(line-1)*icube->bandCount() + (band-1)][2];

      if(value != 57344)
        lineBasedDarkCorrections.insert(pair< pair<int, int>, double>(index, value));
      else
        lineBasedDarkCorrections.insert(pair< pair<int, int>, double>(index, Null));
    }
  }

  if(ui.GetBoolean("IRORIGDARK") == true) {
    calibInfo += PvlKeyword("SideplaneCorrection", "Sideplane");
    return;
  }

  // do linear fits
  for(int band = 1; band <= icube->bandCount(); band++) {
    PolynomialUnivariate basis(1);
    LeastSquares lsq(basis);

    for(int line = 1; line <= icube->lineCount(); line++) {
      pair<int, int> index = pair<int, int>(line, band);
      map< pair<int, int>, double>::iterator val = lineBasedDarkCorrections.find(index);

      if(val != lineBasedDarkCorrections.end()) {
        vector<double> input;
        input.push_back(line);
        double expected = val->second;

        if(!IsSpecial(expected))
          lsq.AddKnown(input, expected);
      }
    }

    if(lsq.Rows() == 0) return;
    lsq.Solve();

    double coefficients[2] = {
      basis.Coefficient(0),
      basis.Coefficient(1)
    };

    for(int line = 1; line <= icube->lineCount(); line++) {
      pair<int, int> index = pair<int, int>(line, band);

      map< pair<int, int>, double>::iterator val = lineBasedDarkCorrections.find(index);
      if(val != lineBasedDarkCorrections.end()) {
        double currentDark = val->second;

        if(!IsSpecial(currentDark)) {
          double newDark = coefficients[0] + line * coefficients[1];

          // initial dark applied by compressor
          if(archive["CompressorId"][0] != "N/A") {
            // input is in (dn-dark) units
            // (dn-dark) - (fit-dark) = dn-fit
            newDark -= currentDark;
          }

          val->second = newDark;
        }
      }
    }
  }

  if(archive["CompressorId"][0] != "N/A") {
    calibInfo += PvlKeyword("SideplaneCorrection", "Fit Delta");
  }
  else {
    calibInfo += PvlKeyword("SideplaneCorrection", "Fit");
  }
}
Example #21
0
  void ApplyHooks(const char *modName, HMODULE module)
  {
    {
      size_t i = 0;
      while(modName[i])
      {
        lowername[i] = (char)tolower(modName[i]);
        i++;
      }
      lowername[i] = 0;
    }

#if ENABLED(VERBOSE_DEBUG_HOOK)
    RDCDEBUG("=== ApplyHooks(%s, %p)", modName, module);
#endif

    // fraps seems to non-safely modify the assembly around the hook function, if
    // we modify its import descriptors it leads to a crash as it hooks OUR functions.
    // instead, skip modifying the import descriptors, it will hook the 'real' d3d functions
    // and we can call them and have fraps + renderdoc playing nicely together.
    // we also exclude some other overlay renderers here, such as steam's
    //
    // Also we exclude ourselves here - just in case the application has already loaded
    // renderdoc.dll, or tries to load it.
    if(strstr(lowername, "fraps") || strstr(lowername, "gameoverlayrenderer") ||
       strstr(lowername, STRINGIZE(RDOC_DLL_FILE) ".dll") == lowername)
      return;

    // set module pointer if we are hooking exports from this module
    for(auto it = DllHooks.begin(); it != DllHooks.end(); ++it)
    {
      if(!_stricmp(it->first.c_str(), modName))
      {
        if(it->second.module == NULL)
        {
          it->second.module = module;
          it->second.FetchOrdinalNames();
        }
        else
        {
          it->second.module = module;
        }
      }
    }

    // for safety (and because we don't need to), ignore these modules
    if(!_stricmp(modName, "kernel32.dll") || !_stricmp(modName, "powrprof.dll") ||
       !_stricmp(modName, "opengl32.dll") || !_stricmp(modName, "gdi32.dll") ||
       strstr(lowername, "msvcr") == lowername || strstr(lowername, "msvcp") == lowername ||
       strstr(lowername, "nv-vk") == lowername || strstr(lowername, "amdvlk") == lowername ||
       strstr(lowername, "igvk") == lowername || strstr(lowername, "nvopencl") == lowername)
      return;

    byte *baseAddress = (byte *)module;

    // the module could have been unloaded after our toolhelp snapshot, especially if we spent a
    // long time
    // dealing with a previous module (like adding our hooks).
    wchar_t modpath[1024] = {0};
    GetModuleFileNameW(module, modpath, 1023);
    if(modpath[0] == 0)
      return;
    // increment the module reference count, so it doesn't disappear while we're processing it
    // there's a very small race condition here between if GetModuleFileName returns, the module is
    // unloaded then we load it again. The only way around that is inserting very scary locks
    // between here
    // and FreeLibrary that I want to avoid. Worst case, we load a dll, hook it, then unload it
    // again.
    HMODULE refcountModHandle = LoadLibraryW(modpath);

    PIMAGE_DOS_HEADER dosheader = (PIMAGE_DOS_HEADER)baseAddress;

    if(dosheader->e_magic != 0x5a4d)
    {
      RDCDEBUG("Ignoring module %s, since magic is 0x%04x not 0x%04x", modName,
               (uint32_t)dosheader->e_magic, 0x5a4dU);
      FreeLibrary(refcountModHandle);
      return;
    }

    char *PE00 = (char *)(baseAddress + dosheader->e_lfanew);
    PIMAGE_FILE_HEADER fileHeader = (PIMAGE_FILE_HEADER)(PE00 + 4);
    PIMAGE_OPTIONAL_HEADER optHeader =
        (PIMAGE_OPTIONAL_HEADER)((BYTE *)fileHeader + sizeof(IMAGE_FILE_HEADER));

    DWORD iatOffset = optHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;

    IMAGE_IMPORT_DESCRIPTOR *importDesc = (IMAGE_IMPORT_DESCRIPTOR *)(baseAddress + iatOffset);

#if ENABLED(VERBOSE_DEBUG_HOOK)
    RDCDEBUG("=== import descriptors:");
#endif

    while(iatOffset && importDesc->FirstThunk)
    {
      const char *dllName = (const char *)(baseAddress + importDesc->Name);

#if ENABLED(VERBOSE_DEBUG_HOOK)
      RDCDEBUG("found IAT for %s", dllName);
#endif

      DllHookset *hookset = NULL;

      for(auto it = DllHooks.begin(); it != DllHooks.end(); ++it)
        if(!_stricmp(it->first.c_str(), dllName))
          hookset = &it->second;

      if(hookset && importDesc->OriginalFirstThunk > 0 && importDesc->FirstThunk > 0)
      {
        IMAGE_THUNK_DATA *origFirst =
            (IMAGE_THUNK_DATA *)(baseAddress + importDesc->OriginalFirstThunk);
        IMAGE_THUNK_DATA *first = (IMAGE_THUNK_DATA *)(baseAddress + importDesc->FirstThunk);

#if ENABLED(VERBOSE_DEBUG_HOOK)
        RDCDEBUG("Hooking imports for %s", dllName);
#endif

        while(origFirst->u1.AddressOfData)
        {
          void **IATentry = (void **)&first->u1.AddressOfData;

          struct hook_find
          {
            bool operator()(const FunctionHook &a, const char *b)
            {
              return strcmp(a.function.c_str(), b) < 0;
            }
          };

#if ENABLED(RDOC_X64)
          if(IMAGE_SNAP_BY_ORDINAL64(origFirst->u1.AddressOfData))
#else
          if(IMAGE_SNAP_BY_ORDINAL32(origFirst->u1.AddressOfData))
#endif
          {
            // low bits of origFirst->u1.AddressOfData contain an ordinal
            WORD ordinal = IMAGE_ORDINAL64(origFirst->u1.AddressOfData);

#if ENABLED(VERBOSE_DEBUG_HOOK)
            RDCDEBUG("Found ordinal import %u", (uint32_t)ordinal);
#endif

            if(!hookset->OrdinalNames.empty())
            {
              if(ordinal >= hookset->OrdinalBase)
              {
                // rebase into OrdinalNames index
                DWORD nameIndex = ordinal - hookset->OrdinalBase;

                // it's perfectly valid to have more functions than names, we only
                // list those with names - so ignore any others
                if(nameIndex < hookset->OrdinalNames.size())
                {
                  const char *importName = (const char *)hookset->OrdinalNames[nameIndex].c_str();

#if ENABLED(VERBOSE_DEBUG_HOOK)
                  RDCDEBUG("Located ordinal %u as %s", (uint32_t)ordinal, importName);
#endif

                  auto found =
                      std::lower_bound(hookset->FunctionHooks.begin(), hookset->FunctionHooks.end(),
                                       importName, hook_find());

                  if(found != hookset->FunctionHooks.end() &&
                     !strcmp(found->function.c_str(), importName) && found->excludeModule != module)
                  {
                    bool already = false;
                    bool applied;
                    {
                      SCOPED_LOCK(lock);
                      applied = found->ApplyHook(IATentry, already);
                    }

                    // if we failed, or if it's already set and we're not doing a missedOrdinals
                    // second pass, then just bail out immediately as we've already hooked this
                    // module and there's no point wasting time re-hooking nothing
                    if(!applied || (already && !missedOrdinals))
                    {
#if ENABLED(VERBOSE_DEBUG_HOOK)
                      RDCDEBUG("Stopping hooking module, %d %d %d", (int)applied, (int)already,
                               (int)missedOrdinals);
#endif
                      FreeLibrary(refcountModHandle);
                      return;
                    }
                  }
                }
              }
              else
              {
                RDCERR("Import ordinal is below ordinal base in %s importing module %s", modName,
                       dllName);
              }
            }
            else
            {
#if ENABLED(VERBOSE_DEBUG_HOOK)
              RDCDEBUG("missed ordinals, will try again");
#endif
              // the very first time we try to apply hooks, we might apply them to a module
              // before we've looked up the ordinal names for the one it's linking against.
              // Subsequent times we're only loading one new module - and since it can't
              // link to itself we will have all ordinal names loaded.
              //
              // Setting this flag causes us to do a second pass right at the start
              missedOrdinals = true;
            }

            // continue
            origFirst++;
            first++;
            continue;
          }

          IMAGE_IMPORT_BY_NAME *import =
              (IMAGE_IMPORT_BY_NAME *)(baseAddress + origFirst->u1.AddressOfData);

          const char *importName = (const char *)import->Name;

#if ENABLED(VERBOSE_DEBUG_HOOK)
          RDCDEBUG("Found normal import %s", importName);
#endif

          auto found = std::lower_bound(hookset->FunctionHooks.begin(),
                                        hookset->FunctionHooks.end(), importName, hook_find());

          if(found != hookset->FunctionHooks.end() &&
             !strcmp(found->function.c_str(), importName) && found->excludeModule != module)
          {
            bool already = false;
            bool applied;
            {
              SCOPED_LOCK(lock);
              applied = found->ApplyHook(IATentry, already);
            }

            // if we failed, or if it's already set and we're not doing a missedOrdinals
            // second pass, then just bail out immediately as we've already hooked this
            // module and there's no point wasting time re-hooking nothing
            if(!applied || (already && !missedOrdinals))
            {
#if ENABLED(VERBOSE_DEBUG_HOOK)
              RDCDEBUG("Stopping hooking module, %d %d %d", (int)applied, (int)already,
                       (int)missedOrdinals);
#endif
              FreeLibrary(refcountModHandle);
              return;
            }
          }

          origFirst++;
          first++;
        }
      }
      else
      {
        if(hookset)
        {
#if ENABLED(VERBOSE_DEBUG_HOOK)
          RDCDEBUG("!! Invalid IAT found for %s! %u %u", dllName, importDesc->OriginalFirstThunk,
                   importDesc->FirstThunk);
#endif
        }
      }

      importDesc++;
    }

    FreeLibrary(refcountModHandle);
  }
Example #22
0
bool CharSaver::save(const string &pathAndName,
                     map <string, int> &knownChars)
{
    ofstream outfile;//the file to write to
    map<string, int>::iterator mapIter;//points to an element in knownChars
    string theKey;//a key from knownChars
    int colorIndex = 0;//index of the current color in colorNames
    char oneChar = ' ';//the current known character
    bool result = true;//false on file access error

    if (loadErrors)
        cout << "CharSaver::save(): not saving because there were errors loading." << endl;
    else
    {
        //### Open the file for writing ###
        outfile.open(pathAndName.c_str());
        if (!outfile.is_open())
        {
            cout << "Couldn't open " << pathAndName << " for writing" << endl;
            result = false;
        }//if !is_open()

        //### Save the mappings ###
        mapIter = knownChars.begin();
        while ((result) && (mapIter != knownChars.end()))
        {
            theKey = (*mapIter).first;

            //### Verify that the key is 2 bytes long ###
            if (theKey.size() != 2)
            {
                cout << "CharSaver::save(): got a key that isn't 2 bytes long" << endl;
                result = false;
            }//if size()

            //### Extract the character and color ###
            if (result)
            {
                oneChar = theKey.at(0);

                colorIndex = static_cast<int>(theKey.at(1));
                if ((colorIndex < 0) || (colorIndex >= static_cast<int>(colorNames.size())))
                {
                    cout << "CharSaver::save(): got an invalid color index " << colorIndex << endl;
                    result = false;
                }//if colorIndex || colorIndex
            }//if result

            //### Write them to file ###
            if (result)
            {
                outfile << oneChar << " " << colorNames.at(colorIndex)
                        << " " << (*mapIter).second << endl;
                if (!outfile.good())
                {
                    cout << "Error writing to " << pathAndName << endl;
                    result = false;
                }//if !good()
            }//if result

            mapIter++;
        }//while result && mapIter

        if (outfile.is_open())
        {
            outfile << "END";
            outfile.close();
        }//if is_open()
    }//else loadErrors

    return result;
}//save
inline void update(string &w, int& maxStep){
    if (words.find(w) != words.end()){
        maxStep = max(maxStep, words[w]);
    }
}
Example #24
0
File: vdfls.cpp Project: yyr/vapor
bool VarFileInfo::Test(int j) const {
	map <int,  struct STAT64>::const_iterator iter = _varStatMap.find(j);

	return(iter != _varStatMap.end());
}
int main(int argc, char *argv[]) {

	time(&startTime);	

	/******************************************************************************
	 *                 === PARSE THE COMMAND LINE OPTIONS ===
	 ******************************************************************************/
	Options defaults;
  
  	Options opt = parseOptions(argc, argv, defaults);
  	if (opt.errorFlag) {
  		cerr << endl;
  		cerr << "The program terminated with errors:" << endl;
  		cerr << endl;
  		cerr << opt.errorMessages << endl;
  		cerr << endl;
  		cerr << opt.OPerrors << endl;
  
  		usage();
  		exit(1);
  	}	

	ofstream fout;
	fout.open((opt.proteinId + ".out" ).c_str());

	if(!fout.is_open()) {
		cerr << "Unable to open " << opt.proteinId << endl;
		exit(0);
	}

	System sys;
	if(!sys.readPdb(opt.pdbFile)) {
		cerr << "Unable to read from " << opt.pdbFile << endl;
		exit(0);
	}

	// Read topology file to get Charge for each atom
	CharmmTopologyReader topRead(opt.topFile);
	if(!topRead.read()) {
		cerr << "Unable to read topology file " << opt.topFile << endl;
		exit(0);
	}

	setCharge(sys,topRead);
/*
	CharmmSystemBuilder CSB(sys,opt.topFile,opt.parFile,opt.solvFile);
	CSB.setSolvent("CHEX");
	CSB.setBuildNonBondedInteractions(false);

	if(!CSB.buildSystemFromPDB(opt.pdbFile)) {
		cerr << "Unable to build system from " << opt.pdbFile << endl;
		exit(0);
	}

	sys.buildAllAtoms();
*/
	// Add hydrogen bond term
	HydrogenBondBuilder hb(sys, opt.hBondFile);
	if(!hb.buildInteractions(10)) {
		cerr << "Unable to build hbond interactions for " << opt.pdbFile << endl;
		exit(0);
	}
	// print format for the logfile
	/*
	tmsegment A,1 233 238
	tmsegment B,2 233 238
	tmsegment C,3 233 238

	sequence 1 GKDIAFIVHGYGGLVFMDLLVRR
	sequence 2 GRDIGFIVHGYGGLVFMDLLVRR
	sequence 3 GRDITFIYHGYGGLVFMDLLVRR

	interfacial 1 00000110110010011001001
	interfacial 2 00100110110010011001001
	interfacial 3 01000110110010011001001

	allhbonds B,235,HA2:A,234,O=2.84814;B,238,HA1:A,234,O=3.40832;A,235,HA2:B,234,O=2.84814A,238,HA1:B,234,O=3.40832;B,235,HA2:A,234,O=2.84814;B,238,HA1:A,234,O=3.40832;A,235,HA2:B,234,O=2.84814A,238,HA1:B,234,O=3.40832;B,235,HA2:A,234,O=2.84814;B,238,HA1:A,234,O=3.40832;A,235,HA2:B,234,O=2.84814A,238,HA1:B,234,O=3.40832

	hbonds 1 2 B,235,HA2:A,234,O=2.84814;B,238,HA1:A,234,O=3.40832;A,235,HA2:B,234,O=2.84814A,238,HA1:B,234,O=3.40832
	hbonds 1 3 B,235,HA2:A,234,O=2.84814;B,238,HA1:A,234,O=3.40832;A,235,HA2:B,234,O=2.84814A,238,HA1:B,234,O=3.40832
	hbonds 2 3 B,235,HA2:A,234,O=2.84814;B,238,HA1:A,234,O=3.40832;A,235,HA2:B,234,O=2.84814A,238,HA1:B,234,O=3.40832
	*/

	// create segments;
	for(int i = 0; i < opt.segment.size(); i++) {
		vector<string> toks = MslTools::tokenize(opt.segment[i]);
		segments.push_back(new Segment(sys,toks[0],toks[1],MslTools::toInt(toks[2]),MslTools::toInt(toks[3])));
		fout << "tmsegment " << toks[0] << "," << toks[1] << " " << toks[2] << " " << toks[3] << " " << segments.back()->getSequence() << endl;
		mappedSegments[toks[0] + "," + toks[1]] = segments.back();
	}

	EnergySet* Eset = sys.getEnergySet();
	vector<Hbond*> interhelicalHbonds;
	getInterHelicalHbonds(Eset,interhelicalHbonds);

	//fout << "allhbonds "; 
	//for(int i = 0; i < interhelicalHbonds.size(); i++) {
	//	fout << interhelicalHbonds[i]->getFormattedLine() << ";";
	//}
	//fout << endl;

	// map hbonds based on the helices
	map<string,vector<Hbond*> > hbondsMapped;
	for(int i = 0; i < interhelicalHbonds.size(); i++) {
		string seg1 =  interhelicalHbonds[i]->getDonor()->getChainId() + "," + interhelicalHbonds[i]->getDonorTmId() ;
		string seg2 = interhelicalHbonds[i]->getAcceptor()->getChainId() + "," + interhelicalHbonds[i]->getAcceptorTmId();
		if(hbondsMapped.find(seg1 + " " + seg2) != hbondsMapped.end()) {
			hbondsMapped[seg1 + " " + seg2].push_back(interhelicalHbonds[i]);
		} else if (hbondsMapped.find(seg2 + " " + seg1) != hbondsMapped.end()) {
			hbondsMapped[seg2 + " " + seg1].push_back(interhelicalHbonds[i]);
		} else {
			hbondsMapped[seg1 + " " + seg2].push_back(interhelicalHbonds[i]);
		}
		//cout << "HERE " << seg1 << " " << seg2 << endl;
	}


	stringstream ss;

	ss << "bg_color white" << endl;
	ss << "load " << opt.pdbFile << endl;
	ss << "rotate X,90,all, 0" << endl;
	ss << "show cartoon" << endl;



	int interfaceNum = 0;
	int hbondNum = 0;
	for(map<string,vector<Hbond*> >::iterator it = hbondsMapped.begin(); it != hbondsMapped.end(); it++) {
		//if(it->second.size() < 4) {
		//	continue;
		//}
		ss << getHbondPseLine(hbondNum,it->second );
		interfaceNum++;

		// find interface
		vector<string> toks = MslTools::tokenize(it->first);
		Segment* seg1 = NULL;
		Segment* seg2 = NULL;
		if(mappedSegments.find(toks[0]) != mappedSegments.end()) {
			seg1 = mappedSegments[toks[0]];
		} else {
			cerr << "ERROR cant find segment " << opt.pdbFile << " " << toks[0] << endl;
		}

		if(mappedSegments.find(toks[1]) != mappedSegments.end()) {
			seg2 = mappedSegments[toks[1]];
		} else {
			cerr << "ERROR cant find segment " << opt.pdbFile << " " << toks[1] << endl;
		}

		AtomPointerVector& seg1Atoms = seg1->getAtoms();
		AtomPointerVector& seg2Atoms = seg2->getAtoms();

		map<string,unsigned int> interface = interfaceResidueCheck(seg1Atoms,seg2Atoms); 
		map<string,string> perChainInterface;
		
		for(map<string,unsigned int>::iterator it1 = interface.begin(); it1 != interface.end(); it1++) {
			// split A,23,GLY A,24,GLY and map [A] = 23+24
			vector<string> toks = MslTools::tokenize(it1->first,","); 
			if(perChainInterface.find(toks[0]) == perChainInterface.end()) {
				perChainInterface[toks[0]] = toks[1];
			} else {
				perChainInterface[toks[0]] += "+" + toks[1];
			}
		}

		string interfaceId = "TM_" + seg1->getChain() + "_" + seg1->getTmId() + "_" + seg2->getChain() + "_" + seg2->getTmId() ;
		
		ss << "select " << interfaceId << " , "; 

		for(map<string,string>::iterator it1 = perChainInterface.begin(); it1 != perChainInterface.end(); it1++) {
			if(it1 == perChainInterface.begin()) {
				ss << " chain " << it1->first << " and resi " << it1->second ; 
			} else {
				ss << " or chain " << it1->first << " and resi " << it1->second ; 
			}
		}

		ss << endl;
		ss << "show stick, " << interfaceId << endl;
		
		fout << "hbonds " << it->first << "  ";
		for(vector<Hbond*>::iterator it1 = it->second.begin(); it1 != it->second.end(); it1++) {
			Atom* donor = (*it1)->getDonor();
			Atom* acceptor = (*it1)->getAcceptor();
			double distance = (*it1)->getDistance();
			char tmp[10000];
			sprintf(tmp,"%s:%s=%4.3f;",donor->getAtomOfIdentityId().c_str(),acceptor->getAtomOfIdentityId().c_str(),distance);
			fout << tmp;
		}
		fout << endl;
	}

	ss << "zoom all,3" << endl;
	ss << "set label_color, black" << endl;
	ss << "save " << opt.proteinId << ".pse" << endl;

	if(interfaceNum > 0) {
		ofstream pout;
		pout.open((opt.proteinId + ".inp").c_str());
		if(!pout.is_open()) {
			cerr << "Unable to open " << opt.proteinId << ".inp" << endl;
			exit(0);
		}

		pout << ss.str() ;

		string cmd = "pymol -cqd \"@" + opt.proteinId + ".inp\"";
		system(cmd.c_str());
	}

	time(&endTime);
	diffTime = difftime (endTime, startTime);

	fout << endl << "Total Time: " << setiosflags(ios::fixed) << setprecision(0) << diffTime << " seconds" << endl;
}
Example #26
0
const string &primOpName(PrimOpPtr x) {
    map<int, string>::iterator i = primOpNames.find(x->primOpCode);
    assert(i != primOpNames.end());
    return i->second;
}
int main(){
    FILE * previous = fopen("prev.txt", "r");
    if (previous != NULL) {
        long long t, id;
        int size;
        while (fscanf(previous, "%lld %d", &t, &size) == 2) {
            for (int k = 0; k < size; ++k) {
                fscanf(previous, "%lld", &id);
                m[t].insert(id);
                timestamp[id] = t;
            }
        }
        fclose(previous);
    }
    
    int n; scanf("%d", &n);
    while (n--) {
        scanf("%s", buffer);
        if (buffer[0] == 's') {//set
            long long id, t;
            scanf("%lld %lld", &id, &t);
            
            if (timestamp.count(id) > 0) { // delete old update
                long long old_t = timestamp[id];
                m[old_t].erase(id);
            }
            
            timestamp[id] = t;
            m[t].insert(id);


        } else if (buffer[0] == 'l') { // list
            
            long long bound; scanf("%lld", &bound);

            bool first = true;
            for (m_iterator it = m.begin(); it != m.end(); ++it) {
                if (it->first > bound) break;
                for(set_iterator person = it->second.begin(); person != it->second.end(); ++person) {
                    if (!first) printf(" ");
                    first = false;
                    printf("%lld", *person);
                }
            }
            puts("");
            
        } else if (buffer[0] == 'd') { // del
            long long id; scanf("%lld", &id);
            if (timestamp.count(id) > 0) {
                long long old_t = timestamp[id];
                m[old_t].erase(id);
                timestamp.erase(id);
            }
            
        } else if (buffer[0] == 'c') { // clear
            m.clear();
            timestamp.clear();
            
        } else {
            printf("WTF is this? %s\n", buffer);
            assert(false);
        }
    }
    
    // dump to file
    previous = fopen("prev.txt", "w");
    assert(previous);
    for(m_iterator it = m.begin(); it != m.end(); ++it) {
        int size = it->second.size();
        if (size == 0) continue;
        fprintf(previous, "%lld %d", it->first, size);
        for(set_iterator p = it->second.begin(); p != it->second.end(); ++p) {
            fprintf(previous, " %lld", *p);
        }
        fprintf(previous, "\n");
    }
    fclose(previous);
    
    return 0;
}
Example #28
0
int CCachedAffairMap::Static_CheckBeOverTime(map<unsigned long long, tr1::shared_ptr<CCachedAffair> >& cachedMap, CCachedAffairMapLock &Lock, long nowTime)
{
	//只处理异步的超时
	
	//try
	{
		list<tr1::shared_ptr<CCachedAffair> >				listNeedRemove ;
	    {
			//先将超时的条目移除
			Lock.LockMap();		
#if 0
	        if (cachedMap.size () < 1)
			{
				Lock.UnLockMap();
	            return 1;
			}

	        map<unsigned long long, tr1::shared_ptr<CCachedAffair> >::iterator iter 
				= find_if (cachedMap.begin(), cachedMap.end (), CCachedAffairMap::CBeOverTime<unsigned long long,CCachedAffair*> (nowTime));
	        while (iter != cachedMap.end ())
	        {
	            tr1::shared_ptr<CCachedAffair> pAffairItem = iter->second;
	            listNeedRemove.push_back (pAffairItem);
	            cachedMap.erase(iter);

	            ++iter;
	            if (iter == cachedMap.end ())
	                break;
				
	            iter = find_if (iter ,cachedMap.end (),CCachedAffairMap::CBeOverTime<unsigned long long,CCachedAffair*> (nowTime));
	        }
#else

#endif
			for(map<unsigned long long, tr1::shared_ptr<CCachedAffair> >::iterator iter = cachedMap.begin();iter!=cachedMap.end();++iter)
			{
				if((iter->second ->m_dwPushedTime + iter->second ->m_nOverTime) < nowTime)
				{
					tr1::shared_ptr<CCachedAffair> pAffairItem = iter->second;
					listNeedRemove.push_back (pAffairItem);
					cachedMap.erase(iter);

					++iter;
					if (iter == cachedMap.end ())
						break;
				}
			}

			Lock.UnLockMap();
	    }

		//处理超时的条目
	    list<tr1::shared_ptr<CCachedAffair> >::iterator iterRemove = listNeedRemove.begin () ;
	    while (iterRemove != listNeedRemove.end ())
	    {
	    	(*iterRemove)->DoOverTime();
	    }

	    return 1;
	}
	//catch(...)
	{

	}

    return -1;
}
Example #29
0
int main(int argc, char **argv){
  if (argc <2)
  {
    std::cerr <<"Missing argument.. " << endl;
    return 0;
  }
  int loop = atoi (argv[1] ); 
  struct timeval t1, t2;
  gettimeofday(&t1, NULL);
  init_device_streams(1);
  gettimeofday(&t2, NULL);
  std::cerr<< "Time DEVICE init: " <<DIFF_TIME(t1, t2) <<" s." <<endl;
  int concurentThreadsSupported = (int)std::thread::hardware_concurrency();
  //ExecutionEngine *execEngine = new ExecutionEngine(2, 1, ExecEngineConstants::FCFS_QUEUE);
  // int nextTaskDependency;
  //std::cerr  << "Number of threads: [" << concurentThreadsSupported << "]" <<std::endl;
  // Creates first task, which does not have dependencies
  size_t pos, pos2;
  string input_line;
  string tid ;
  string prev_tid = "";

  std::cerr << "I/O" ;
  while(cin && getline(cin, input_line) && !cin.eof()) {
    pos=input_line.find_first_of(TAB,0);
    if (pos == string::npos){
      cerr << "no TAB in the input! We are toasted." << endl;
      return 1; // failure
    }

    tid= input_line.substr(0,pos); // tile id
    if (0 != tid.compare(prev_tid) && prev_tid.size()>0) 
      std::cerr << "  [" <<prev_tid << "]" ;
    // actual geometry info: did,oid,num_ver,mbb, geom
    int i = input_line[pos+1] - '1'; // array position 
    pos2=input_line.find_first_of(COMMA,pos+3); //oid = input_line.substr(pos+3,pos2-pos-3) 
    pos=input_line.find_first_of(COMMA,pos2+1); //num_ver = input_line.substr(pos2+1,pos)
    vertexes[tid][i] += std::stoi(input_line.substr(pos2+1,pos-pos2-1));
    geoms[tid][i].push_back(input_line.substr(pos2+1)); // mbb, geom
    prev_tid = tid; 
  }
  std::cerr << std::endl;

  JoinTask *jt = NULL;
    map<string,map<int,vector<string> > >::iterator it;
    map<string,map<int,int> >::iterator vertexes_iter;
  while (loop-- > 0) {
    std::cerr << "-------------------------------------------------------------------------" << std::endl;

    ExecutionEngine *execEngine = new ExecutionEngine(concurentThreadsSupported-1, 1, ExecEngineConstants::PRIORITY_QUEUE);

    // for each tile 
    for (it=geoms.begin(); it !=geoms.end(); ++it)
    {
      jt = new JoinTask(JCARDINALITY);

      for (int i = 0 ; i < JCARDINALITY; i++){
      jt->nr_vertices[i] = vertexes[it->first][i];

      jt->geom_arr[i]->assign(
          geoms[it->first][i].begin(),
          geoms[it->first][i].end());
      }
      jt->setSpeedup(ExecEngineConstants::GPU, 
                     gpuSpeedUp(jt->nr_vertices[0],
                                jt->nr_vertices[1],
                                jt->geom_arr[0]->size(), 
                                jt->geom_arr[1]->size()));
      jt->setSpeedup(ExecEngineConstants::CPU, 
                     cpuSpeedUp(jt->nr_vertices[0],
                                jt->nr_vertices[1],
                                jt->geom_arr[0]->size(), 
                                jt->geom_arr[1]->size()));
      // Dispatches current tasks for execution
      //std::cerr << ts->getId() << "-------" << prev_tid<< std::endl;
      execEngine->insertTask(jt);
    }

    // Computing threads startup consuming tasks
    execEngine->startupExecution();

    // No more task will be assigned for execution. Waits
    // until all currently assigned have finished.
    execEngine->endExecution();

    delete execEngine;
  }
  fini_device_streams(1);
  return 0;
}
Example #30
0
void *clientSession(void *arg) {
	unsigned int *connection = (unsigned int *) arg;
	int connfd = connection[0];
	unsigned int ip = connection[1];
	sem_wait(&sem);
	if (repeatedLogins.find(ip) == repeatedLogins.end())
		repeatedLogins.insert(pair<unsigned int, pair<string, int> >(ip, pair<string, int>("", 2)));
	sem_post(&sem);
	delete connection;
	int n = 0;
	char *message = new char[BUFFER_SIZE];
	char *username = new char[BUFFER_SIZE];
	char *password = new char[BUFFER_SIZE];
	bzero(message, BUFFER_SIZE);
	bool loggingIn = true;
	while (loggingIn) {
		if (send(connfd, "> Username: "******"error: ");
			pthread_exit(NULL);
		}
		bzero(username, BUFFER_SIZE);
		if ((n = recv(connfd, username, BUFFER_SIZE, 0)) == -1) {
			perror("error: ");
			pthread_exit(NULL);
		} else if (n == 0) {
			if (close(connfd) == -1) {
				perror("error: ");
				pthread_exit(NULL);
			}
			delete username;
			delete message;
			pthread_exit(NULL);
		}
		if (send(connfd, "> Password: "******"error: ");
			pthread_exit(NULL);
		}
		bzero(password, BUFFER_SIZE);
		if (recv(connfd, password, BUFFER_SIZE, 0) == -1) {
			perror("error: ");
			pthread_exit(NULL);
		} else if (n == 0) {
			if (close(connfd) == -1) {
				perror("error: ");
				pthread_exit(NULL);
			}
			delete username;
			delete password;
			delete message;
			pthread_exit(NULL);
		}
		sem_wait(&sem);
		string user(username);
		string pass(password);
		if (accounts.find(user) != accounts.end()) {
			if (accounts[user].isBlocked(ip)) {
				if (accounts[user].blockExpired(ip, BLOCK_TIME)) {
					accounts[user].removeBlocked(ip);
				} else {
					sem_post(&sem);
					stringstream blockStream;
					blockStream << "IP was blocked for " << BLOCK_TIME << " seconds for 3 consecutively failed logins\n";
					string blockMessage = blockStream.str();
					if (send(connfd, blockMessage.data(), blockMessage.length(), 0) == -1) {
						perror("error: ");
						pthread_exit(NULL);
					}
					bzero(message, BUFFER_SIZE);
					continue;
				}
			}
			if (accounts[user].getPassword() == pass) {
				if (accounts[user].getConnection() == -1) {
					string validLogin("Welcome to simple chat server!\n");
					if (send(connfd, validLogin.data(), validLogin.length(), 0) == -1) {
						perror("error: ");
						pthread_exit(NULL);
					}
					if (send(connfd, "> ", 2, 0) == -1) {
						perror("error: ");
						pthread_exit(NULL);
					}
					loggingIn = false;
					accounts[user].setConnection(connfd);
					bzero(message, BUFFER_SIZE);
				} else {
					string dupeLogin("User already signed in, try again.\n");
					if (send(connfd, dupeLogin.data(), dupeLogin.length(), 0) == -1) {
						perror("error: ");
						pthread_exit(NULL);
					}
				}
			} else {
				string invalidPassword("Invalid password, try again.\n");
				if (repeatedLogins[ip].first == user) {
					repeatedLogins[ip].second--;
					if (repeatedLogins[ip].second <= 0) {
						accounts[user].addBlocked(ip);
						repeatedLogins[ip].first = "";
						repeatedLogins[ip].second = 2;
					}
				} else {
					repeatedLogins[ip].first = user;
					repeatedLogins[ip].second = 2;
				}
				if (send(connfd, invalidPassword.data(), invalidPassword.length(), 0) == -1) {
					perror("error: ");
					pthread_exit(NULL);
				}
			}
		} else {
			string invalidLogin("Invalid username, try again.\n");
			if (send(connfd, invalidLogin.data(), invalidLogin.length(), 0) == -1) {
				perror("error: ");
				pthread_exit(NULL);
			}
		}
		sem_post(&sem);
	}
	delete password;
	string user(username);
	if (recv(connfd, message, BUFFER_SIZE, 0) == -1) {
		perror("error: ");
		pthread_exit(NULL);
	}
	socklen_t port = atoi(message);
	if ((msgfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		perror("error: ");
		pthread_exit(NULL);
	}
	clientAddress.sin_port = port;
	if (connect(msgfd, (struct sockaddr *) &clientAddress, sizeof(clientAddress)) == -1) {
		perror("error: ");
		pthread_exit(NULL);
	}
	time(&currentTime);
	sem_wait(&sem);
	accounts[user].setMessageConnection(msgfd);
	accounts[user].setTimeout(currentTime);
	sem_post(&sem);
	while ((n = recv(connfd, message, BUFFER_SIZE, 0)) > 0) {
		string response;
		stringstream ss;
		ss << message;
		string command;
		ss >> command;
		if (command == "whoelse") {
			stringstream st;
			sem_wait(&sem);
			for (map<string, User>::iterator it = accounts.begin(); it != accounts.end(); ++it) {
				if (it->second.getConnection() != -1 && it->first != user) {
					st << it->first << endl;
				}
			}
			sem_post(&sem);
			st << "> ";
			response = st.str();
		} else if (command == "wholasthr") {
			stringstream st;
			time_t current;
			time(&current);
			sem_wait(&sem);
			for (map<string, User>::iterator it = accounts.begin(); it != accounts.end(); ++it) {
				if (it->second.getConnection() != -1)
					it->second.setLast(current);
				if (difftime(current, it->second.getLast()) < LAST_HOUR && it->first != user) {
					st << it->first << endl;
				}
			}
			sem_post(&sem);
			st << "> ";
			response = st.str();
		} else if (command == "broadcast") {
			string nextMessage = "";
			ss >> nextMessage;
			if (nextMessage == "") {
				response = "error: broadcast expected a message\n> ";
			} else {
				stringstream st;
				st << user << ": ";
				st << nextMessage;
				string endMessage;
				getline(ss, endMessage);
				st << endMessage;
				st << "\n";
				string broadcastMessage = st.str();
				sem_wait(&sem);
				for (map<string, User>::iterator it = accounts.begin(); it != accounts.end(); ++it) {
					if (it->second.getConnection() != -1 && it->first != user) {
						if (send(accounts[it->first].getMessageConnection(), broadcastMessage.data(), broadcastMessage.length(), 0) == -1) {
							perror("error: ");
							pthread_exit(NULL);
						}
					}
				}
				response = "> ";
				sem_post(&sem);
			}
		} else if (command == "message") {