Example #1
0
File: main.cpp Project: jokoon/eio
// all configurations - > linker -> subsystem = windows
//int WinMain()
int main(int argc, char*argv[])
{
    //OutputDebugStringA("f*****g test in main2");
    //cout << "f*****g test in main" << endl;
    //main();
    configfile cfg;
    cfg.init("bedlab.cfg");
	Vec2i windowsize;
	Vec2i screen_resolution = {int(VideoMode::getDesktopMode().width), int(VideoMode::getDesktopMode().height)} ;
	if (cfg.getvar<int>("auto_winsize"))
	{
		auto window_scale = cfg.getvar<Vec2>("window_scale");
		windowsize = Vec2i(scal(Vec2(screen_resolution), window_scale));
	}
	else
	{
		windowsize = cfg.getvar<Vec2i>("windowsize");
	}
	winsize = Vec2(windowsize);
	UI.init_console(); // ALWAYS AFTER SO IT CAN GET WINDOW SIZE

	wincenter = 0.5f*Vec2(windowsize);
	//msg(windowsize);
    Vec2i windowpos;
	//msg(screen_resolution);
	VideoMode::getDesktopMode().height;
    //SET(screen_resolution);
    if (cfg.getvar<int>("stick_left"))
    {
        windowpos = Vec2i(screen_resolution.x - windowsize.x - 10, 25);
        //msg(screen_resolution);
        //msg(windowpos);
    }
    else
        windowpos = (Vec2i(5, 25));
    
    sf::RenderWindow window(sf::VideoMode(windowsize.x, windowsize.y),
        "bedlab!", 7, sf::ContextSettings(0, 0, 1));
    window.setFramerateLimit(cfg.getvar<int>("fps_max"));
    frame_duration = 1.0f/cfg.getvar<int>("fps_max");

    window.setPosition(windowpos);
    // add all the app
	{
		ADDAPP(smoothmouse);
		ADDAPP(mokio);
		ADDAPP(osm);
		ADDAPP(mousetest);
		ADDAPP(guns_axes);
		ADDAPP(nestedgrid);
		ADDAPP(recoil_test);
		ADDAPP(splosions);
		ADDAPP(industrio);
		ADDAPP(mason);
		ADDAPP(geomtest);
		ADDAPP(astar);
		ADDAPP(quadtree_test2);
		ADDAPP(springrecoil_test);
		ADDAPP(mine_solver);
		ADDAPP(sound_test);
		ADDAPP(clock_system_test);
		ADDAPP(populio);
		ADDAPP(simpleplot);
		ADDAPP(citynet);
		ADDAPP(bag);
		ADDAPP(delaun_distr);
		ADDAPP(spellmech);
		ADDAPP(short_tests);
		ADDAPP(geomtests);
		ADDAPP(tests_path);
		ADDAPP(test_perlin);
		ADDAPP(checkers_box);
		ADDAPP(swarming);
		ADDAPP(citynet2);
		ADDAPP(testbed);
		ADDAPP(geomtest_orient);
		ADDAPP(holosight);
	
		ADDAPP(recoil_simul);
        ADDAPP(recoil_spring);
        ADDAPP(bar_bump);
		ADDAPP(masonette);
		ADDAPP(mild_tests);
		ADDAPP(perlin_plain);

		/*
		ADDAPP(phone_pattern);
		ADDAPP(guns_test);
		ADDAPP(triangul); // just re add triangul.cpp to the project!
		ADDAPP(quadtree_test);
		ADDAPP(balldemo);
		apps["smoothmouse"] = smoothmouse(window,UI);
		ADDAPP(guns_test);
		ADDAPP(kdtree);
		*/

	}
	//{
	//	configfile descr_file;
	//	descr_file.init("demo_descr.txt");
	//	set<string> avail;
	//	for (auto&a : descr_file.dict) avail.insert(a.first);
	//	for(auto&app :apps)
	//	{
	//		if (descr_file.dict.count(app.first))
	//		{
	//			avail.erase(app.first);
	//		}			
	//	}
	//	for (auto&a : avail)
	//	{
	//		msgs("not loaded " + a);
	//	}
	//}
	auto dont_load = cfg.getlist("dont_load");
	for (auto&a : dont_load)
	{
		apps.erase(a);
	}
	//for (auto&a : dont_load) dont_load_these.insert(a);
	//auto dont_load_these = split2(dont_load," ");



    // read the 

    string s = cfg.getstr("app");
	if (cfg.getvar<int>("use_menu") == 1)
	{
		while (1)
		{
			string choice = appchooser(window, UI)();
			//int i = 432;
			msgs("chosen " + choice);
			if (choice != "none")
				apps[choice]();
			else
			{
				break;
			}
		}
	}
	else
	{
		if (s == "")
		{
			msgs("######## error in config, app was not found! ########");
			return -2;
		}
		if (!apps.count(s))
		{
			msgs("######## app " + s + " not found! ######## ");
			throw runtime_error(string("app " + s + " not found!"));
			return -2;
		}
		vector<string> keys;
		auto choice = cfg.getstr("app");
		show_keys(cfg.getstr("app"), keys);
		msgs(choice);
		for (auto&a : keys)
			msgs(a);
		apps[cfg.getstr("app")]();
	}
    return 0;
}
	void AIUpdate()
	{
		uint32 plrcounts[2] = { 0, 0 };

		// details:
		//   loop through inrange players, for new ones, send the enable CP worldstate.
		//   the value of the map is a timestamp of the last update, to avoid cpu time wasted
		//   doing lookups of objects that have already been updated

		unordered_set<PlayerPointer>::iterator itr = _gameobject->GetInRangePlayerSetBegin();		
		unordered_set<PlayerPointer>::iterator itrend = _gameobject->GetInRangePlayerSetEnd();
		map<uint32,uint32>::iterator it2, it3;
		uint32 timeptr = (uint32)UNIXTIME;
		bool in_range;
		bool is_valid;
		PlayerPointer plr = NULLPLR;
		
		for(; itr != itrend; ++itr)
		{
			if( !(*itr)->IsPvPFlagged() || (*itr)->InStealth() )
				is_valid = false;
			else
				is_valid = true;

			in_range = (_gameobject->GetDistanceSq((*itr)) <= BANNER_RANGE) ? true : false;

			it2 = StoredPlayers.find((*itr)->GetLowGUID());
			if( it2 == StoredPlayers.end() )
			{
				// new player :)
				if( in_range )
				{
					(*itr)->SendWorldStateUpdate(WORLDSTATE_HELLFIRE_PVP_CAPTURE_BAR_DISPLAY, 1);
					(*itr)->SendWorldStateUpdate(WORLDSTATE_HELLFIRE_PVP_CAPTURE_BAR_VALUE, Status);
					StoredPlayers.insert(make_pair((*itr)->GetLowGUID(), timeptr));

					if( is_valid )
						plrcounts[(*itr)->GetTeam()]++;
				}
			}
			else
			{
				// oldie
				if( !in_range )
				{
					(*itr)->SendWorldStateUpdate(WORLDSTATE_HELLFIRE_PVP_CAPTURE_BAR_DISPLAY, 0);
					StoredPlayers.erase(it2);
				}
				else
				{
					(*itr)->SendWorldStateUpdate(WORLDSTATE_HELLFIRE_PVP_CAPTURE_BAR_VALUE, Status);
					it2->second = timeptr;
					if( is_valid )
						plrcounts[(*itr)->GetTeam()]++;
				}
			}
		}

		// handle stuff for the last tick
		if( Status == 100 && m_bannerStatus != BANNER_STATUS_ALLIANCE )
		{
			m_bannerStatus = BANNER_STATUS_ALLIANCE;
			SetArtKit();

			// send message to everyone in the zone, has been captured by the Alliance
			_gameobject->GetMapMgr()->SendPvPCaptureMessage(ZONE_HELLFIRE_PENINSULA, ZONE_HELLFIRE_PENINSULA, "|cffffff00%s has been taken by the Alliance!|r", ControlPointName);

			// tower update
			g_allianceTowers++;
			UpdateTowerCount(_gameobject->GetMapMgr());

			// state update
			_gameobject->GetMapMgr()->GetStateManager().UpdateWorldState(g_neutralStateFields[towerid], 0);
			_gameobject->GetMapMgr()->GetStateManager().UpdateWorldState(g_allianceStateFields[towerid], 1);

			// woot
			g_towerOwners[towerid] = 1;
			UpdateInDB();
		}
		else if( Status == 0 && m_bannerStatus != BANNER_STATUS_HORDE )
		{
			m_bannerStatus = BANNER_STATUS_HORDE;
			SetArtKit();

			// send message to everyone in the zone, has been captured by the Horde
			_gameobject->GetMapMgr()->SendPvPCaptureMessage(ZONE_HELLFIRE_PENINSULA, ZONE_HELLFIRE_PENINSULA, "|cffffff00%s has been taken by the Horde!|r", ControlPointName);
			
			// tower update
			g_hordeTowers++;
			UpdateTowerCount(_gameobject->GetMapMgr());

			// state update
			_gameobject->GetMapMgr()->GetStateManager().UpdateWorldState(g_neutralStateFields[towerid], 0);
			_gameobject->GetMapMgr()->GetStateManager().UpdateWorldState(g_hordeStateFields[towerid], 1);

			// woot
			g_towerOwners[towerid] = 0;
			UpdateInDB();
		}
		else if( m_bannerStatus != BANNER_STATUS_NEUTRAL )
		{
			// if the difference for the faction is >50, change to neutral
			if( m_bannerStatus == BANNER_STATUS_ALLIANCE && Status <= 50 )
			{
				// send message: The Alliance has lost control of point xxx
				m_bannerStatus = BANNER_STATUS_NEUTRAL;
				SetArtKit();
				
				g_allianceTowers--;
				UpdateTowerCount(_gameobject->GetMapMgr());

				_gameobject->GetMapMgr()->SendPvPCaptureMessage(ZONE_HELLFIRE_PENINSULA, ZONE_HELLFIRE_PENINSULA, "|cffffff00The Alliance have lost control of %s!|r", ControlPointName);

				// state update
				_gameobject->GetMapMgr()->GetStateManager().UpdateWorldState(g_allianceStateFields[towerid], 0);
				_gameobject->GetMapMgr()->GetStateManager().UpdateWorldState(g_neutralStateFields[towerid], 1);

				// woot
				g_towerOwners[towerid] = -1;
				UpdateInDB();
			}
			else if( m_bannerStatus == BANNER_STATUS_HORDE && Status >= 50 )
			{
				// send message: The Alliance has lost control of point xxx
				m_bannerStatus = BANNER_STATUS_NEUTRAL;
				SetArtKit();

				g_hordeTowers--;
				UpdateTowerCount(_gameobject->GetMapMgr());

				_gameobject->GetMapMgr()->SendPvPCaptureMessage(ZONE_HELLFIRE_PENINSULA, ZONE_HELLFIRE_PENINSULA, "|cffffff00The Horde have lost control of %s!|r", ControlPointName);

				// state update
				_gameobject->GetMapMgr()->GetStateManager().UpdateWorldState(g_hordeStateFields[towerid], 0);
				_gameobject->GetMapMgr()->GetStateManager().UpdateWorldState(g_neutralStateFields[towerid], 1);

				// woot
				g_towerOwners[towerid] = -1;
				UpdateInDB();
			}
		}

		// send any out of range players the disable flag
		for(it2 = StoredPlayers.begin(); it2 != StoredPlayers.end(); )
		{
			it3 = it2;
			++it2;

			if( it3->second != timeptr )
			{
				plr = _gameobject->GetMapMgr()->GetPlayer(it3->first);
				
				// they WILL be out of range at this point. this is guaranteed. means they left the set rly quickly.
				if( plr != NULL )
					plr->SendWorldStateUpdate(WORLDSTATE_HELLFIRE_PVP_CAPTURE_BAR_DISPLAY, 0);

				StoredPlayers.erase(it3);
			}
		}

		// work out current status for next tick
		uint32 delta;
		if( plrcounts[0] > plrcounts[1] )
		{
			delta = plrcounts[0] - plrcounts[1];
			delta *= CAPTURE_RATE;

			// cap it at 25 so the banner always gets removed.
			if( delta > 25 )
				delta = 25;

			Status += delta;
			if( Status >= 100 )
				Status = 100;
		}
		else if( plrcounts[1] > plrcounts[0] )
		{
			delta = plrcounts[1] - plrcounts[0];
			delta *= CAPTURE_RATE;
			
			// cap it at 25 so the banner always gets removed.
			if( delta > 25 )
				delta = 25;

			if( delta > Status )
				Status = 0;
			else
				Status -= delta;
		}
	}
Example #3
0
 void remove() {
     pot_.erase(top());
 }
Example #4
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 #5
0
void* conn_to_Task(void* args)
{
    const int MAX_TASK_NUM = 256;
    int listenfd, connfd, tmpfd, epfd, nfds, i;
    char buf_in[1024], buf_out[1024];
    map<int, Split>::iterator Split_Map_iter;
    vector<Split>::iterator Split_Vector_iter;
    list<Split>::iterator Split_List_iter;
    map<int, Task_Info>::iterator Task_iter;
    socklen_t Task_Len;

    struct epoll_event ev, events[MAX_TASK_NUM];
    epfd = epoll_create(MAX_TASK_NUM);
    struct sockaddr_in TM_Addr, Task_Addr;
    listenfd = socket(AF_INET, SOCK_STREAM, 0);

    ev.data.fd = listenfd;
    ev.events = EPOLLIN;

    epoll_ctl(epfd, EPOLL_CTL_ADD, listenfd, &ev);
    bzero(&TM_Addr, sizeof(TM_Addr));
    TM_Addr.sin_family = AF_INET;
    TM_Addr.sin_addr.s_addr = htonl(INADDR_ANY);
    TM_Addr.sin_port = htons(TM_Task_Port);

    bind(listenfd, (sockaddr*)&TM_Addr, sizeof(TM_Addr));
    listen(listenfd, MAX_TASK_NUM);

    while(1)
    {
        nfds = epoll_wait(epfd, events, 256, 500);

        for(i = 0; i < nfds; i++)
        {
            if(events[i].data.fd == listenfd)//A new Task connecting to TM
            {
                connfd = accept(listenfd, (sockaddr*)&Task_Addr, &Task_Len);
                if(connfd < 0)
                {
                    perror("Error occurs when Task wants to connect to T<.\n");
                    exit(1);
                }

                ev.data.fd = connfd;
                ev.events = EPOLLIN;

                epoll_ctl(epfd, EPOLL_CTL_ADD, connfd, &ev);
            } else if(events[i].events & EPOLLIN)// Task wants to send something
            {
                tmpfd = events[i].data.fd;
                if(tmpfd < 0)
                {
                    epoll_ctl(epfd, EPOLL_CTL_DEL, tmpfd, &ev);
                    continue;
                }
                if(recv(tmpfd, buf_in, 1024, 0) < 0)
                {
                    printf("Error occurs when fetching from Task with ID: %d\n", events[i].data.fd);
                    continue;
                }

                if(buf_in[0] == '8')
                {
                    // Deal with Task initial
                    char Task_Kind[10] = "";
                    sscanf(buf_in + sizeof(char) * 2, "%s", Task_Kind);
                    if(strcmp(Task_Kind, "CPU") == 0)
                    {
                        Task_Info new_Task;
                        CPU_Task_Info.insert(pair<int, Task_Info>(events[i].data.fd, new_Task));
                        printf("A new CPU task connected with ID: %d.\n", events[i].data.fd);
                    } else if(strcmp(Task_Kind, "GPU") == 0)
                    {
                        Task_Info new_Task;
                        GPU_Task_Info.insert(pair<int, Task_Info>(events[i].data.fd, new_Task));
                        printf("A new GPU task connected with ID: %d.\n", events[i].data.fd);
                    } else
                    {
                        printf("Invalid MSG from Task with ID: %d.\n", events[i].data.fd);
                        continue;
                    }
                    if(CPU_Task_Info.size() == CPU_Task_num && GPU_Task_Info.size() == GPU_Task_num)
                    {
                        printf("All tasks are connected!\n");
                        Task_All_Connected = true;
                    }
                }
                else if(buf_in[0] == '9')
                {
                    int id = 0;
                    long t = 0;
                    sscanf(buf_in + sizeof(char) * 2, "%d %ld", &id, &t);

                    //printf("This id: %d\n", id);
                    //for(Split_Map_iter = Ongoing_Split.begin(); Split_Map_iter != Ongoing_Split.end(); Split_Map_iter++)
                    //{
                    //	printf("%d %d\n", Split_Map_iter->first, Split_Map_iter->second.Split_Id);
                    //}
                    //printf("%d\n", Unassigned_Split.size());

                    // Search the Split in Ongoing Map
                    Split_Map_iter = Ongoing_Split.find(id);
                    if(Split_Map_iter == Ongoing_Split.end())
                    {
                        //printf("Error: no such Split ongoing!\n");

                        epoll_ctl(epfd, EPOLL_CTL_DEL, tmpfd, &ev);
                        continue;
                    }

                    // Put it into Finished vector
                    Split tmp_Split(Split_Map_iter->second);
                    tmp_Split.Finished_Time = t;
                    Finished_Split.push_back(tmp_Split);

                    // Erase it from Ongoing Map
                    Ongoing_Split.erase(Split_Map_iter);

                    // judge if it is a CPU Task
                    Task_iter = CPU_Task_Info.find(events[i].data.fd);
                    Task_Info *tmp_Task;
                    if(Task_iter == CPU_Task_Info.end())
                    {
                        Task_iter = GPU_Task_Info.find(events[i].data.fd);
                        if(Task_iter == GPU_Task_Info.end())
                        {
                            printf("Error: no such Task can be found with ID: %d.\n", events[i].data.fd);
                            continue;
                        }
                    }
                    tmp_Task = &(Task_iter->second);

                    // revise information in that Task_Info
                    Split *new_Split = new Split(tmp_Task->Task_Queue.front());
                    new_Split->Finished_Time = t;
                    tmp_Task->Splits_Finish_Time.push_back(*new_Split);
                    tmp_Task->Task_Queue.pop();
                    printf("Split %d is done at %ld by Task %d.\n", new_Split->Split_Id, new_Split->Finished_Time, events[i].data.fd);

                    // To see if Job is complete
                    printf("Uassigned_Split: %d\nOngoing_Split: %d\n", Unassigned_Split.size(), Ongoing_Split.size());
                    if(Unassigned_Split.empty()  && Ongoing_Split.empty())
                    {
                        pthread_mutex_lock(&RM_Mutex);
                        pthread_cond_signal(&Job_Complete_RM);
                        pthread_mutex_unlock(&RM_Mutex);
                        pthread_mutex_lock(&IF_Mutex);
                        pthread_cond_signal(&Job_Complete_IF);
                        pthread_mutex_unlock(&IF_Mutex);
                    }
                } else if(buf_in[0] == 'd')
                {
                } else
                {
                    printf("%s\nInvalid MSG from Task with ID: %d.\n",buf_in,  events[i].data.fd);
                    continue;
                }

                ev.data.fd = tmpfd;
                ev.events = EPOLLOUT;
                epoll_ctl(epfd, EPOLL_CTL_MOD, tmpfd, &ev);
            } else if(events[i].events & EPOLLOUT)// Task wants to fetch something
            {
                tmpfd = events[i].data.fd;
                // To see if there is no unassigned splits
                if(Unassigned_Split.empty())
                {
                    sprintf(buf_out, "a Finished");
                    send(tmpfd, buf_out, 1024, 0);
                    strcpy(buf_out, "");
                } else
                {
                    // To see if Tasks are all connected and Splits are all set
                    if(Splits_Set == false || Task_All_Connected == false)
                    {
                        continue;
                    }

                    // Pop Split from unassigned vector and put it into Ongoing map
                    Split tmp_Split = Unassigned_Split.back();
                    Unassigned_Split.pop_back();
                    Ongoing_Split.insert(pair<int, Split>(tmp_Split.Split_Id, tmp_Split));

                    // Judge if it is a CPU task
                    Task_iter = CPU_Task_Info.find(events[i].data.fd);
                    Task_Info *tmp_Task;
                    if(Task_iter == CPU_Task_Info.end())
                    {
                        Task_iter = GPU_Task_Info.find(events[i].data.fd);
                        if(Task_iter == GPU_Task_Info.end())
                        {
                            printf("Error: no such Task can be found with ID: %d.\n", events[i].data.fd);
                            continue;
                        }
                    }
                    tmp_Task = &(Task_iter->second);

                    // Update Task_Info
                    tmp_Task->Task_Queue.push(tmp_Split);

                    // Send to Task
                    sprintf(buf_out, "c %d %ld %ld", tmp_Split.Split_Id, tmp_Split.begin, tmp_Split.offset);

                    printf("Send a new Split to Task %d, Split_Id: %d, begin: %ld, offset: %ld.\n", events[i].data.fd, tmp_Split.Split_Id, tmp_Split.begin, tmp_Split.offset);
                    send(tmpfd, buf_out, 1024, 0);
                    strcpy(buf_out, "");
                }

                ev.data.fd = tmpfd;
                ev.events = EPOLLIN;
                epoll_ctl(epfd, EPOLL_CTL_MOD, tmpfd, &ev);
            } else
            {
                continue;
                // do nothing
            }
        }
    }
    return NULL;
}
Example #6
0
void BannerCache::CacheBannerInternal( CString BannerPath )
{
	CString error;
	RageSurface *img = RageSurfaceUtils::LoadFile( BannerPath, error );
	if( img == NULL )
	{
		LOG->Warn( "BannerCache::CacheBanner: Couldn't load %s: %s", BannerPath.c_str(), error.c_str() );
		return;
	}

	bool WasRotatedBanner = false;

	if( Sprite::IsDiagonalBanner(img->w , img->h) )
	{
		/* Ack.  It's a diagonal banner.  Problem: if we resize a diagonal banner, we
		 * get ugly checker patterns.  We need to un-rotate it.
		 *
		 * If we spin the banner by hand, we need to do a linear filter, or the
		 * fade to the full resolution banner is misaligned, which looks strange.
		 *
		 * To do a linear filter, we need to lose the palette.  Oh well.
		 *
		 * This also makes the banner take less memory, though that could also be
		 * done by RLEing the surface.
		 */
		RageSurfaceUtils::ApplyHotPinkColorKey( img );

		RageSurfaceUtils::ConvertSurface(img, img->w, img->h, 32, 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000);
		
		RageSurface *dst = CreateSurface(
            256, 64, img->format->BitsPerPixel, 
			img->format->Rmask, img->format->Gmask, img->format->Bmask, img->format->Amask );

		if( img->format->BitsPerPixel == 8 ) 
		{
			ASSERT( img->format->palette );
			dst->fmt.palette = img->fmt.palette;
		}

		const float fCustomImageCoords[8] = {
			0.02f,	0.78f,	// top left
			0.22f,	0.98f,	// bottom left
			0.98f,	0.22f,	// bottom right
			0.78f,	0.02f,	// top right
		};

		RageSurfaceUtils::BlitTransform( img, dst, fCustomImageCoords );

//		SDL_SaveBMP( dst, BannerPath + "-test.bmp" );
		delete img;
		img = dst;

		WasRotatedBanner = true;
	}



	const int src_width = img->w, src_height = img->h;

	int width = img->w / 2, height = img->h / 2;
//	int width = img->w, height = img->h;

	/* Round to the nearest power of two.  This simplifies the actual texture load. */
	width = closest(width, power_of_two(width), power_of_two(width) / 2);
	height = closest(height, power_of_two(height), power_of_two(height) / 2);

	/* Don't resize the image to less than 32 pixels in either dimension or the next
	 * power of two of the source (whichever is smaller); it's already very low res. */
	width = max( width, min(32, power_of_two(src_width)) );
	height = max( height, min(32, power_of_two(src_height)) );

	RageSurfaceUtils::ApplyHotPinkColorKey( img );

	RageSurfaceUtils::Zoom( img, width, height );

	/*
	 * When paletted banner cache is enabled, cached banners are paletted.  Cached
	 * 32-bit banners take 1/16 as much memory, 16-bit banners take 1/8, and paletted
	 * banners take 1/4.
	 *
	 * When paletted banner cache is disabled, cached banners are stored in 16-bit
	 * RGBA.  Cached 32-bit banners take 1/8 as much memory, cached 16-bit banners
	 * take 1/4, and cached paletted banners take 1/2.
	 *
	 * Paletted cache is disabled by default because palettization takes time, causing
	 * the initial cache run to take longer.  Also, newer ATI hardware doesn't supported
	 * paletted textures, which would slow down runtime, because we have to depalettize
	 * on use.  They'd still have the same memory benefits, though, since we only load
	 * one cached banner into a texture at once, and the speed hit may not matter on
	 * newer ATI cards.  RGBA is safer, though.
	 */
	if( PREFSMAN->m_bPalettedBannerCache )
	{
		if( img->fmt.BytesPerPixel != 1 )
			RageSurfaceUtils::Palettize( img );
	} else {
		/* Dither to the final format.  We use A1RGB5, since that's usually supported
		 * natively by both OpenGL and D3D. */
		RageSurface *dst = CreateSurface( img->w, img->h, 16,
			0x7C00, 0x03E0, 0x001F, 0x8000 );

		/* OrderedDither is still faster than ErrorDiffusionDither, and
		 * these images are very small and only displayed briefly. */
		RageSurfaceUtils::OrderedDither( img, dst );
		delete img;
		img = dst;
	}

	const CString CachePath = GetBannerCachePath(BannerPath);
	RageSurfaceUtils::SaveSurface( img, CachePath );

	if( PREFSMAN->m_BannerCache == PrefsManager::BNCACHE_LOW_RES )
	{
		/* If an old image is loaded, free it. */
		if( g_BannerPathToImage.find(BannerPath) != g_BannerPathToImage.end() )
		{
			RageSurface *oldimg = g_BannerPathToImage[BannerPath];
			delete oldimg;
			g_BannerPathToImage.erase(BannerPath);
		}

		/* Keep it; we're just going to load it anyway. */
		g_BannerPathToImage[BannerPath] = img;
	}
	else
		delete img;

	/* Remember the original size. */
	BannerData.SetValue( BannerPath, "Path", CachePath );
	BannerData.SetValue( BannerPath, "Width", src_width );
	BannerData.SetValue( BannerPath, "Height", src_height );
	BannerData.SetValue( BannerPath, "FullHash", GetHashForFile( BannerPath ) );
	/* Remember this, so we can hint Sprite. */
	BannerData.SetValue( BannerPath, "Rotated", WasRotatedBanner );
	BannerData.WriteFile( BANNER_CACHE_INDEX );
}
Example #7
0
void
dequeue_answer(int fd)
{
    delete pending_writes[fd].second;
    pending_writes.erase(fd);
}
Example #8
0
bool CAlert::ProcessAlert(const std::vector<unsigned char>& alertKey)
{
    if (!CheckSignature(alertKey))
        return error("CAlert::ProcessAlert: verify signature failed");
    if (!IsInEffect())
        return error("CAlert::ProcessAlert: Expired");

    // 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))
            {
                uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);
                mapAlerts.erase(mi++);
            }
            else if (!alert.IsInEffect())
            {
                uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);
                mapAlerts.erase(mi++);
            }
            else
                mi++;
        }

        // Check if this alert has been cancelled
        for (auto& item : mapAlerts)
        {
            const CAlert& alert = item.second;
            if (alert.Cancels(*this))
                return error("CAlert::ProcessAlert: Cancelled");
        }

        // Add to mapAlerts
        mapAlerts.insert(make_pair(GetHash(), *this));

        if(AppliesToMe())
        {
            uiInterface.NotifyAlertChanged(GetHash(), CT_NEW);
            Notify(strStatusBar);
        }
    }

    return true;
}
Example #9
0
 void erase(int key) {
   int old_time = key_to_time[key];
   time_to_key.erase(old_time);
   key_to_time.erase(key);
   key_to_value.erase(key);
 }
Example #10
0
int main(int argc,char *argv[])
{
    //Seed RNG
    srand(time(NULL));
    //get socket
    listenfd = socket(AF_INET, SOCK_STREAM, 0);
    if (listenfd == -1)
        err(1, "socket");
    int g = 1;

    signal(SIGPIPE, SIG_IGN);
    //ignore sigpipes
    setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,&g,sizeof(int));
    //force drop other applications on the same port
    //fcntl(listenfd, F_SETFL, O_NONBLOCK);

    memset(&serv_addr, '0', sizeof(serv_addr));

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_addr.sin_port = htons(6667);

    if (bind(listenfd, (struct sockaddr*)&serv_addr,sizeof(serv_addr)) == -1)
        err(1, "bind to port %d", ntohs(serv_addr.sin_port));

    if(listen(listenfd, 10) == -1){
        printf("Failed to listen\n");
        return -1;
    }
    thread z(ControlServer);
    z.detach();
    //again  because we spawned a thread
    signal(SIGPIPE, SIG_IGN);

    while(true)
    {
        {
            mutex_guard lock(connections_mutex);

            auto dead_connections = std::remove_if(connections.begin(), connections.end(),
                        [&](User const *u){ return u->dead; });
            for (auto it = dead_connections; it != connections.end(); it++)
                delete *it;
            connections.erase(dead_connections, connections.end());

            for (User *puser : connections)
            {
                User &user = *puser;
                string command_str = user.try_read();
                if (user.dead) continue;

                chop_newline_off(command_str);
                vector<string> command = parse_irc_command(command_str);
                if (!command.empty())
                {
                    cout << "\033[91m← " << user.username << "\t" << command_str << "\033[m" << endl;
                    if(command[0] == "USER")
                    {
                        //stub incase anyone wants to implement authentication
                    }
                    else if(command[0] == "PING")
                    {
                        user.write(":tinyirc PONG :" + command[1] + "\r\n");
                    }
                    else if(command[0] == "PONG" && user.status != User::ConnectStatus::NICKSET)
                    {
                        //reset anti-drop
                        user.dontkick = true;
                        user.rticks = 0;
                    }
                    else if(command[0] == "PONG" && user.status == User::ConnectStatus::NICKSET)
                    {
                        //oh nice, you accepted our PING, welcome to the party
                        user.write(":tinyirc 001 " + user.username + " :Hello!" + "\r\n");
                        user.write(":tinyirc 002 " + user.username + " :This server is running TinyIRC pre-alpha!" + "\r\n");
                        user.write(":tinyirc 003 " + user.username + " :This server doesn't have date tracking." + "\r\n");
                        user.write(":tinyirc 004 " + user.username + " tinyirc " + " tinyirc(0.0.1) " + "CDGNRSUWagilopqrswxyz" + " BCIMNORSabcehiklmnopqstvz" + " Iabehkloqv" + "\r\n");
                        user.write(":tinyirc 005 " + user.username + " CALLERID CASEMAPPING=rfc1459 DEAF=D KICKLEN=180 MODES=4 PREFIX=(qaohv)~&@%+ STATUSMSG=~&@%+ EXCEPTS=e INVEX=I NICKLEN=30 NETWORK=tinyirc MAXLIST=beI:250 MAXTARGETS=4 :are supported by this server\r\n");
                        user.write(":tinyirc 005 " + user.username + " CHANTYPES=# CHANLIMIT=#:500 CHANNELLEN=50 TOPICLEN=390 CHANMODES=beI,k,l,BCMNORScimnpstz AWAYLEN=180 WATCH=60 NAMESX UHNAMES KNOCK ELIST=CMNTU SAFELIST :are supported by this server\r\n");
                        user.write(":tinyirc 251 " + user.username + " :LUSERS is unimplemented." + "\r\n");
                        user.status = User::ConnectStatus::READY;

                        user.dontkick = true;
                    }
                    else if(command[0] == "NICK")
                    {
                        string new_nick = remove_erase_if(command[1], ".,#\r");
                        if(new_nick.size() > 225 || new_nick.size() == 0)
                            new_nick = "F****T" + to_string(rand() % 9000);

                        bool inuse = false;
                        if (usersbyname.find(new_nick) != usersbyname.end())
                            inuse = true;

                        //if not authed, set username and PING, else set username
                        if(user.status == User::ConnectStatus::CONNECTED)
                        {
                            user.username = new_nick;
                            if(inuse)
                            {
                                user.kill("Nick already in use");
                                continue;
                            }
                            user.write("PING :" + user.username + "\r\n");
                            user.status = User::ConnectStatus::NICKSET;
                            usersbyname[new_nick] = &user;
                        }
                        else
                        {
                            if(inuse)
                                user.write(":tinyirc " "NOTICE :*** Name already in use..." "\r\n");
                            else
                            {
                                // Update nick in all channels
                                for (string const &channelname : user.channel)
                                {
                                    Channel &channel = channels.at(channelname);
                                    channel.users.erase(user.username);
                                    channel.users.insert(new_nick);
                                }
                                usersbyname[new_nick] = &user;
                                usersbyname.erase(user.username);
                                user.broadcast(":" + user.username + " NICK " + new_nick + "\r\n");
                                user.username = new_nick;
                            }
                        }
                    }
                    else if(command[0] == "JOIN")
                    {
                        string channame = command[1];
                        // TODO handle comma separated chan joins?
                        channame = remove_erase_if(channame,":,. \r");
                        if(channame [0] != '#')
                            channame.insert(0,"#");

                        Channel &channel = channels.emplace(piecewise_construct, forward_as_tuple(channame), forward_as_tuple(channame)).first->second;
                        user.channel.insert(channame);
                        channel.users.insert(user.username);
                        channel.broadcast(":" + user.username + " JOIN " + channame + "\r\n");
                        user.write(":tinyirc MODE :" + channame + " +n" + "\r\n");
                        user.write(":tinyirc 332 " + user.username + " " + channame +  " :" + channel.topic + "\r\n");
                        string msgf(":tinyirc 353 " + user.username + " = " + channame + " :");
                        for(string const &chanuser : channel.users)
                        {
                            msgf += chanuser;
                            msgf += " ";
                        }
                        msgf.erase(msgf.end() - 1);
                        msgf += "\r\n";
                        user.write(msgf);
                        user.write(":tinyirc 366 " + user.username + " " + channame + " :Sucessfully joined channel." +"\r\n");
                    }
                    else if(command[0] == "TOPIC")
                    {
                        auto channel_iter = channels.find(command[1]);
                        if (channel_iter == channels.end())
                        {
                            user.write(":tinyirc 403 " + user.username + " " + command[1] + " :No such channel\r\n");
                        }
                        else
                        {
                            Channel &channel = channel_iter->second;
                            if (command.size() > 2)
                            {
                                channel.topic = command[2];
                                channel.broadcast(":" + user.username + " TOPIC " + command[1] + " :" + command[2] + "\r\n");
                            }
                            else
                            {
                                user.write(":tinyirc 332 " + user.username + " " + command[1] + " :" + channel.topic + "\r\n");
                            }
                        }
                    }
                    else if(command[0] == "PRIVMSG")
                    {
                        //send privmsg to all other users in channel
                        // TODO: warning if channel/user doesn't exist
                        string recip = command[1];
                        string msg = command[2];
                        if (recip.size() == 0) break;

                        string buf(":" + user.username + " PRIVMSG " + recip + " :" + msg + "\r\n");
                        try
                        {
                            if (recip[0] == '#')
                                for (string username : channels.at(recip).users)
                                {
                                    User *chanuser = usersbyname.at(username);
                                    if (&user != chanuser)
                                        usersbyname.at(username)->write(buf);
                                }
                            else
                                usersbyname.at(recip)->write(buf);
                        }
                        catch (out_of_range e)
                        {
                           user.write(":tinyirc 401 " + user.username + " " + recip + " :No such nick/channel\r\n");
                        }
                    }
                    else if(command[0] == "MODE")
                    {
                        //set user mode, required for some irc clients to think you're fully connected(im looking at you xchat)
                        //+i means no messages from people outside the channel and that mode reflects how the server works
                        string const& channel = command[1];
                        if(user.channel.size() != 0)
                        {
                            user.write(":tinyirc 324 " + user.username + " " + channel + " +n" + "\r\n");
                            user.write(":tinyirc 329 " + user.username + " " + channel + " 0 0" + "\r\n");
                        }
                        else
                        {
                            user.detectautisticclient = true;
                            user.write(":" + user.username + " MODE " + user.username + " :+i" + "\r\n");
                        }
                    }
                    else if(command[0] == "WHO")
                    {
                        auto const channel_iter = channels.find(command[1]);
                        if (channel_iter != channels.end())
                            for(string const &chanuser : channel_iter->second.users)
                                user.write(":tinyirc 352 " + user.username + " " + command[1] + " tinyirc " + chanuser + "\r\n");
                        user.write(":tinyirc 315 " + user.username + " " + command[1] + " :End of /WHO list.\r\n");
                    }
                    else if(command[0] == "QUIT")
                    {
                        user.kill("Quit");
                    }
                    else if(command[0] == "PART")
                    {
                        vector<string> ctol;
                        split_string(string(command[1]),",",ctol);
                        string reason = command.size() > 2 ? command[2] : "Leaving";

                        for (string &chantopart : ctol)
                        {
                            auto channeliter = channels.find(chantopart);
                            if (channeliter == channels.end())
                                continue; // Don't part a channel that doesn't exist

                            Channel &channel = channeliter->second;
                            channel.notify_part(user, reason);
                            channel.remove_user(user);
                        }
                    }
                    else if(command[0] == "PROTOCTL")
                    {
                        //gives capabilities of the server, some irc clients dont send one for some reason (im looking at you two irssi and weechat)
                        user.write(":tinyirc 252 " + user.username + " 0 :IRC Operators online" + "\r\n");
                        user.write(":tinyirc 253 " + user.username + " 0 :unknown connections" + "\r\n");
                        user.write(":tinyirc 254 " + user.username + " 0 :LUSERS is unimplmented" + "\r\n");
                        user.write(":tinyirc 255 " + user.username + " :LUSERS is unimplmented" + "\r\n");
                        user.write(":tinyirc 265 " + user.username + " 1 1 :LUSERS is unimplmented" + "\r\n");
                        user.write(":tinyirc 266 " + user.username + " 1 1 :LUSERS is unimplmented" + "\r\n");
                        user.write(":tinyirc 375 " + user.username + " 1 1 :Welcome to tinyirc pre-alpha!" + "\r\n");
                        user.write(":tinyirc 372 " + user.username + " :Padding call" + "\r\n");
                        user.write(":tinyirc 376 " + user.username + " :Ended" + "\r\n");
                        if(!user.detectautisticclient)
                            user.write(":" + user.username + " MODE " + user.username + " :+i" + "\r\n");
                    }
                    else
                    {
                        user.write(":tinyirc 421 " + user.username + " " + command[0] + " :Unknown command\r\n");
                    }
                }

                if(!user.dontkick)
                    user.rticks++;
                if(!user.dontkick && user.rticks == 192)
                {
                    user.kill("Ping timed out");
                    continue;
                }
                if(rand() % 480 == 42 && user.status == User::ConnectStatus::READY)
                {
                    string buf = "PING :" + user.username + "\r\n";
                    send(user.connfd,buf.c_str(),buf.size(),MSG_NOSIGNAL);
                    user.dontkick = false;
                }
            }
        }
        connections_mutex.lock();
        pollfd *pollfds = new pollfd[connections.size() + 1];
        pollfds[0].fd = listenfd;
        pollfds[0].events = POLLIN;
        int i = 1;
        for (User *user : connections)
        {
            pollfds[i].fd = user->connfd;
            pollfds[i].events = POLLIN;
            i++;
        }
        connections_mutex.unlock();

        poll(pollfds, i, 30000);

        if (pollfds[0].revents & POLLIN)
        {
            int connfd = accept(listenfd, nullptr, nullptr);
            if(connfd != -1)
            {
                mutex_guard lock(connections_mutex);
                connections.push_back(new User(connfd)); // accept awaiting request
            }
        }
        delete[] pollfds;
    }
    return 0;
}
 void del_local(const string& key)
 { local_frame_.erase(key); }
Example #12
0
ll cal(int num)
{
  map<int,int> map1,mapbd;
  mapp.clear();
  memset(s,0,sizeof(s));
  memset(val,0,sizeof(val));
  qoi=0;
  for(int i=n-1;i>=0;--i)
    {
      int tmp=p[i].second;
      mapp[tmp]=tmp;
      ++qoi,q[qoi][0]=i,q[qoi][1]=s[tmp],s[tmp]=qoi;
    }
  ll r(0);
  for(int i=0;i<n;)
    {
      // cout<<"* "<<i<<' '<<val[i]<<endl;
      // cout<<"--------"<<endl;
      // for(ite=map1.begin();ite!=map1.end();++ite)
      // 	cout<<ite->first<<' '<<ite->second<<endl;
      // cout<<endl<<endl;
      int j=i;
      for(;p[j].first==p[i].first;++j)
	{
	  int tmp=p[j].second;
	  int v=val[q[s[tmp]][0]];
	  if(v)
	    {
	      for(;v>0;)
		{
		  ite=map1.lower_bound(tmp);
		  int tz=min(ite->second,v);
		  ite->second-=tz;
		  v-=tz;
		  //cout<<'!'<<j<<' '<<tz<<endl;
		  r+=tz;
		  if(ite->second<=0)
		    map1.erase(ite);
		}
	      mapbd.erase(tmp);
	    }
	  s[tmp]=q[s[tmp]][1];
	  if(s[tmp]==0)
	    mapp.erase(tmp);
	}
      // cout<<"--------------------"<<endl;
      // for(ite=map1.begin();ite!=map1.end();++ite)
      // 	cout<<ite->first<<' '<<ite->second<<endl;
      // cout<<endl<<endl;
      int k=i;
      for(;i<j;++i)
	{
	  int tmp=p[i].second;
	  ite=mapbd.upper_bound(tmp);
	  int c=(ite==mapbd.end()?num+1:ite->first);
	  ite=map1.upper_bound(tmp);
	  //cout<<"**"<<ite->first<<' '<<ite->second<<endl;
	  for(;ite!=map1.end() && ite->first<=c;)
	    {
	      map1[tmp]+=ite->second;
	      //cout<<"!!"<<i<<' '<<ite->first<<' '<<ite->second<<endl;
	      r+=ite->second;
	      ii=ite;
	      ++ite;
	      map1.erase(ii);
	    }
	}
      i=k;
      for(;i<j;++i)
	{
	  ite=mapp.lower_bound(p[i].second);
	  int c=(i==j-1?num:p[i+1].second);
	  if(ite!=mapp.end() && ite->first<c)
	    {
	      //cout<<"add "<<i<<' '<<ite->first<<' '<<c<<endl;
	      mapbd[ite->first]=1;
	      ++val[q[s[ite->first]][0]];
	      ++map1[c];
	      if(ite->first==p[i].second)
		--r;
	    }
	}
    }
  return r;
}
// The execution function for the retransmission thread
void FMTPSender::RunRetransThread(int sock, map<uint, int>& retrans_fd_map, set<uint>& timeout_set) {
	int sock_fd = sock;

	map<uint, int>::iterator it;

	char recv_buf[FMTP_PACKET_LEN];
	FmtpHeader* recv_header = (FmtpHeader*)recv_buf;
	char* recv_packet_data = recv_buf + FMTP_HLEN;
	FmtpRetransRequest* retx_request = (FmtpRetransRequest*)recv_packet_data;

	char send_buf[FMTP_PACKET_LEN];
	FmtpHeader* send_header = (FmtpHeader*)send_buf;
	char* send_packet_data = send_buf + FMTP_HLEN;

	while (true) {
		if (retrans_tcp_server->Receive(sock_fd, recv_header, FMTP_HLEN) <= 0) {
			SysError("FMTPSender::RunRetransThread()::receive header error");
		}

		// Handle a retransmission request
		if (recv_header->flags & FMTP_RETRANS_REQ) {
			if (retrans_tcp_server->Receive(sock_fd, retx_request, recv_header->data_len) < 0) {
				SysError("FMTPSender::RunRetransThread()::receive retx request data error");
			}

			MessageMetadata* meta = metadata.GetMetadata(retx_request->msg_id);
			if (meta == NULL) {
				//cout << "Error: could not find metadata for file " << retx_request->msg_id << endl;
				continue;
			} else if (timeout_set.find(retx_request->msg_id) != timeout_set.end()) {
				continue;
			}

			// check whether the retransmission for the file has already time out
			if (GetElapsedSeconds(meta->multicast_start_cpu_time) > meta->retx_timeout_seconds) {
				//cout << "Retx timeout for file " << retx_request->msg_id << ".  Elapsed Time: "
				//		<< GetElapsedSeconds(meta->multicast_start_cpu_time) << "    Timeout: " << meta->retx_timeout_seconds << endl;
				send_header->session_id = retx_request->msg_id;
				send_header->flags = FMTP_RETRANS_TIMEOUT;
				send_header->data_len = 0;
				retrans_tcp_server->SelectSend(sock_fd, send_buf, FMTP_HLEN);

				timeout_set.insert(retx_request->msg_id);
			}
			else if (meta->is_disk_file) {	// is disk file transfer
				FileMessageMetadata* file_meta = (FileMessageMetadata*)meta;

				// get the file descriptor to read data from the file
				int fd;
				if ( (it = retrans_fd_map.find(recv_header->session_id)) != retrans_fd_map.end()) {
					fd = it->second;
				}
				else {
					if ( (fd = open(file_meta->file_name.c_str(), O_RDONLY)) < 0)
						SysError("FMTPSender::RunRetransThread() file open error");
					else
						retrans_fd_map[recv_header->session_id] = fd;
				}


				// send the missing blocks to the receiver
				lseek(fd, retx_request->seq_num, SEEK_SET);
				size_t remained_size = retx_request->data_len;
				size_t curr_pos = retx_request->seq_num;
				send_header->session_id = recv_header->session_id;
				send_header->flags = FMTP_RETRANS_DATA;
				while (remained_size > 0) {
					size_t data_length =
							remained_size > FMTP_DATA_LEN ? FMTP_DATA_LEN
									: remained_size;
					send_header->seq_number = curr_pos;
					send_header->data_len = data_length;

					read(fd, send_packet_data, send_header->data_len);
					retrans_tcp_server->SelectSend(sock_fd, send_buf, FMTP_HLEN + send_header->data_len);

					curr_pos += data_length;
					remained_size -= data_length;

					// Update statistics
					send_stats.total_retrans_packets++;
					send_stats.total_retrans_bytes += send_header->data_len;
					//file_meta->stats.session_retrans_packets++;
					//file_meta->stats.session_retrans_bytes += header->data_len;
				}
			}
			else {	// is memory data transfer

			}
		}
		else if (recv_header->flags & FMTP_RETRANS_END) {
			if (retrans_tcp_server->Receive(sock_fd, retx_request, recv_header->data_len) < 0) {
				SysError("FMTPSender::RunRetransThread()::receive retx end msg error");
			}

			// send back the retransmission end message to the receiver
			send_header->session_id = recv_header->session_id;
			send_header->seq_number = 0;
			send_header->data_len = 0;
			send_header->flags = FMTP_RETRANS_END;
			retrans_tcp_server->SelectSend(sock_fd, send_header, FMTP_HLEN);

			map<uint, int>::iterator it = retrans_fd_map.find(recv_header->session_id);
			if ( it != retrans_fd_map.end() ) {
				close(it->second);
				retrans_fd_map.erase(it);
			}

			if ( timeout_set.find(recv_header->session_id) != timeout_set.end() )
				timeout_set.erase(recv_header->session_id);

			// mark the completion of retransmission to one receiver
			metadata.RemoveFinishedReceiver(recv_header->session_id, sock_fd);
		}
		else if (recv_header->flags & FMTP_HISTORY_STATISTICS) {
			char* buf = new char[recv_header->data_len + 1];
			if (retrans_tcp_server->Receive(sock_fd, buf, recv_header->data_len) < 0) {
				break;
			}

			buf[recv_header->data_len] = '\0';
			status_proxy->SendMessageLocal(EXP_RESULT_REPORT, buf);
			delete[] buf;
			cout << "Received a history statistics from socket " << sock_fd << endl;
		}
	}

	cout << "Retransmission thread exited for socket " << sock_fd  << endl;
}
double getdis(int stx, int sty, int enx, int eny) {
    pid ex;
    pq.push(make_pair(0, make_pair(stx, sty)));

    int i;
    int j;

    if (board[stx][sty] == 1) {
        return 0;
    }

    int test;

    while (!pq.empty()) {
        ex = pq.top();
        pq.pop();
        mp1.insert(make_pair(ex.second, 1));
        mp.erase(ex.second);
        i = ex.second.first;
        j = ex.second.second;

        if ((ex.second.first == enx) && (ex.second.second == eny)) {
            return ex.first;
        }

        if ((j + 1 < m) && (board[i][j + 1] == 0) && (mp1.count(make_pair(i, j+1)) == 0)) {
            if (mp.count(make_pair(i, j + 1)) == 0) {
                pq.push(make_pair(ex.first + 1, make_pair(i, j+1)));
                mp.insert(make_pair(make_pair(i,j + 1),ex.first + 1));
            }
            else {
                test = mp[make_pair(i, j + 1)];
                if (test > ex.first + 1) {
                    pq.push(make_pair(ex.first + 1, make_pair(i, j+1)));
                    mp[make_pair(i,j+1)] = ex.first + 1;
                }
            }
        }

        if (((j + 1 < m) && (i + 1 < n)) && (board[i + 1][j + 1] == 0) && (mp1.count(make_pair(i + 1, j+1)) == 0)) {
            if (mp.count(make_pair(i + 1, j + 1)) == 0) {
                pq.push(make_pair(ex.first + rt2, make_pair(i + 1, j+1)));
                mp.insert(make_pair(make_pair(i + 1,j + 1),ex.first + rt2));
            }
            else {
                test = mp[make_pair(i + 1, j + 1)];
                if (test > ex.first + rt2) {
                    pq.push(make_pair(ex.first + rt2, make_pair(i+1, j+1)));
                    mp[make_pair(i+1,j+1)] = ex.first + rt2;
                }
            }
        }

        if ((i + 1 < n) && (board[i+1][j] == 0) && (mp1.count(make_pair(i + 1, j)) == 0)) {
            if (mp.count(make_pair(i + 1, j)) == 0) {
                pq.push(make_pair(ex.first + 1, make_pair(i + 1, j)));
                mp.insert(make_pair(make_pair(i + 1,j),ex.first + 1));
            }
            else {
                test = mp[make_pair(i + 1, j)];
                if (test > ex.first + 1) {
                    pq.push(make_pair(ex.first + 1, make_pair(i + 1, j)));
                    mp[make_pair(i+1,j)] = ex.first + 1;
                }
            }
        }

        if (((j - 1 >= 0) && (i + 1 < n)) && (board[i + 1][j - 1] == 0) && (mp1.count(make_pair(i + 1, j-1)) == 0)) {
            if (mp.count(make_pair(i + 1, j - 1)) == 0) {
                pq.push(make_pair(ex.first + rt2, make_pair(i + 1, j-1)));
                mp.insert(make_pair(make_pair(i + 1,j - 1),ex.first + rt2));
            }
            else {
                test = mp[make_pair(i + 1, j - 1)];
                if (test > ex.first + rt2) {
                    pq.push(make_pair(ex.first + rt2, make_pair(i+1, j-1)));
                    mp[make_pair(i+1,j-1)] = ex.first + rt2;
                }
            }
        }

        if ((j - 1 >= 0) && (board[i][j - 1] == 0) && (mp1.count(make_pair(i, j-1)) == 0)) {
            if (mp.count(make_pair(i, j - 1)) == 0) {
                pq.push(make_pair(ex.first + 1, make_pair(i, j - 1)));
                mp.insert(make_pair(make_pair(i,j - 1),ex.first + 1));
            }
            else {
                test = mp[make_pair(i, j - 1)];
                if (test > ex.first + 1) {
                    pq.push(make_pair(ex.first + 1, make_pair(i, j - 1)));
                    mp[make_pair(i,j-1)] = ex.first + 1;
                }
            }
        }

        if (((j - 1 >= 0) && (i - 1 >= 0)) && (board[i - 1][j - 1] == 0) && (mp1.count(make_pair(i-1, j-1)) == 0)) {
            if (mp.count(make_pair(i - 1, j - 1)) == 0) {
                pq.push(make_pair(ex.first + rt2, make_pair(i - 1, j-1)));
                mp.insert(make_pair(make_pair(i - 1,j - 1),ex.first + rt2));
            }
            else {
                test = mp[make_pair(i - 1, j - 1)];
                if (test > ex.first + rt2) {
                    pq.push(make_pair(ex.first + rt2, make_pair(i-1, j-1)));
                    mp[make_pair(i-1,j-1)] = ex.first + rt2;
                }
            }
        }

        if ((i - 1 >= 0) && (board[i - 1][j] == 0) && (mp1.count(make_pair(i-1, j)) == 0)) {
            if (mp.count(make_pair(i - 1, j)) == 0) {
                pq.push(make_pair(ex.first + 1, make_pair(i - 1, j)));
                mp.insert(make_pair(make_pair(i - 1,j),ex.first + 1));
            }
            else {
                test = mp[make_pair(i - 1, j)];
                if (test > ex.first + 1) {
                    pq.push(make_pair(ex.first + 1, make_pair(i - 1, j)));
                    mp[make_pair(i-1,j)] = ex.first + 1;
                }
            }
        }

        if (((j + 1 < m) && (i - 1 >= 0)) && (board[i - 1][j + 1] == 0) && (mp1.count(make_pair(i - 1, j+1)) == 0)) {
            if (mp.count(make_pair(i - 1, j + 1)) == 0) {
                pq.push(make_pair(ex.first + rt2, make_pair(i - 1, j+1)));
                mp.insert(make_pair(make_pair(i - 1,j + 1),ex.first + rt2));
            }
            else {
                test = mp[make_pair(i - 1, j + 1)];
                if (test > ex.first + rt2) {
                    pq.push(make_pair(ex.first + rt2, make_pair(i-1, j+1)));
                    mp[make_pair(i-1,j+1)] = ex.first + rt2;
                }
            }
        }


    }
}
void check_overlapping_nodes(::std::vector<table_entry*> & links, map<unsigned long long, string> & chains, int len,
                             ::std::map<unsigned long long, unsigned long long>& mapping, unsigned int min_overlap,
                             int ov_perc){
    ::std::map<unsigned long long, string>::iterator chain_it;
    ::std::map<unsigned long long, string>::iterator chain_it_2;
    ::std::vector<small_frag> short_blocks;
    stack<unsigned int> s;
    queue<unsigned long long> q;
    for(chain_it = chains.begin(); chain_it != chains.end(); ++chain_it){
        for(chain_it_2 = chains.begin(); chain_it_2 != chains.end(); ++chain_it_2){
            unsigned int ov = overlappedStringLength(chain_it->second,chain_it_2->second);
            if(chain_it != chain_it_2 && ov < (ov_perc*chain_it->second.length())/100 &&
               (ov_perc*ov < chain_it_2->second.length())/100 && ov > min_overlap){
                bool new_node = false;
                CharString pat_text=prefix(chain_it_2->second,ov);
                //::std::cout << chain_it->second << ::std::endl;
                //::std::cout << chain_it_2->second << ::std::endl;
                //::std::cout << ov << ::std::endl;
                Pattern<CharString, ShiftAnd> pattern(pat_text);
                for(unsigned int i=0; i<links.size();++i){
                    CharString link_read = links[i]->get_short_read()->get_RNA_seq_sequence();
                    Finder<CharString> finder(link_read);
                    if(find(finder,pattern) && (
                       prefix(link_read,beginPosition(finder)) == infix(chain_it->second,chain_it->second.length()-ov-beginPosition(finder),chain_it->second.length()-ov) ||
                       suffix(link_read,length(link_read) - endPosition(finder)) == infix(chain_it_2->second,ov,ov+endPosition(finder)))){
                        //::std::cout << link_read << ::std::endl;
                        //::std::cout << prefix(link_read,beginPosition(finder)) << ::std::endl;
                        //::std::cout << infix(chain_it->second,chain_it->second.length()-ov-beginPosition(finder),chain_it->second.length()-ov) << ::std::endl;
                        //::std::cout << suffix(link_read,length(link_read) - endPosition(finder)) << ::std::endl;
                        //::std::cout << infix(chain_it_2->second,ov,ov+endPosition(finder)) << ::std::endl;
                      
                        new_node = true;
                    }
                }
                if(new_node){
                    small_frag f;
                    f.frag_links.D_chain = chain_it->first;
                    f.frag_links.A_chain = chain_it_2->first;
                    f.frag = prefix(chain_it_2->second,ov);
                    short_blocks.push_back(f);
                }
            }else{
                if(chain_it != chain_it_2 && ov>=(ov_perc*chain_it->second.length())/100){
                    //::std::cout << "Chain_it sub-node of Chain_it_2" << ::std::endl;
                    //::std::cout << "Chain_it " << chain_it->second << ::std::endl;
                    //::std::cout << "Chain_it_2 " << chain_it_2->second << ::std::endl;
                    //::std::cout << ov << ::std::endl;
                    q.push(chain_it->first);
                }else{
                    if(chain_it != chain_it_2 && ov>=(ov_perc*chain_it_2->second.length())/100){
                        //::std::cout << "Chain_it_2 sub-node of Chain_it" << ::std::endl;
                        //::std::cout << "Chain_it " << chain_it->second << ::std::endl;
                        //::std::cout << "Chain_it_2 " <<chain_it_2->second << ::std::endl;
                        //::std::cout << ov << ::std::endl;
                        q.push(chain_it_2->first);
                    }
                }
            }
        }
    }

    for(unsigned int i=0; i<short_blocks.size(); ++i){
        bool sub_seq = false;
        for(unsigned int k=0; k<short_blocks.size(); ++k){
            if(short_blocks[i].frag == short_blocks[k].frag && i<k){
                links_pair erased_links;
                erased_links.D_chain = short_blocks[i].frag_links.D_chain;
                erased_links.A_chain = short_blocks[i].frag_links.A_chain;
                short_blocks[k].other_links.push_back(erased_links);
                sub_seq = true;
            }
            if(i!=k && (::seqan::length(short_blocks[i].frag)) < (::seqan::length(short_blocks[k].frag))){
                Finder<CharString> finder(short_blocks[k].frag);
                Pattern<CharString, ShiftAnd> pattern(short_blocks[i].frag);
                if(find(finder,pattern)){
                    links_pair erased_links;
                    erased_links.D_chain = short_blocks[i].frag_links.D_chain;
                    erased_links.A_chain = short_blocks[i].frag_links.A_chain;
                    //::std::cout << i << k << " - " << beginPosition(finder) << " " << endPosition(finder) << ::std::endl;
                    short_blocks[k].other_links.push_back(erased_links);
                    sub_seq = true;
                }
            }
        }
        if(sub_seq){
            s.push(i);
        }
    }

    while(!s.empty()){
        short_blocks.erase(short_blocks.begin()+s.top());
        s.pop();
    }
    while(!q.empty()){
        chains.erase(q.front());
        q.pop();
    }

    for(unsigned int i=0; i<short_blocks.size(); ++i){
        //::std::cout << short_blocks[i].frag << " " << length(short_blocks[i].frag) << ::std::endl; 
        string ch = "";
        for(unsigned int z = 0; z<len-length(short_blocks[i].frag); ++z){
            ch.append("A");
        }
        ch.append(toCString(short_blocks[i].frag));
        //if(chains.find(fingerprint(ch)) == chains.end()){//Start_If_5
            //chains[fingerprint(ch)] = ::seqan::toCString(short_blocks[i].frag);
            //::std::cout << ::seqan::toCString(short_blocks[i].frag) <<" "<< length(short_blocks[i].frag)<<::std::endl;
            //mapping[fingerprint(ch)] = fingerprint(ch);
            //Add the first link
            string first_half;
            assign(first_half,prefix(chains[short_blocks[i].frag_links.D_chain],len));
            string new_link_1 = first_half;
            new_link_1.append(ch);
            table_entry* link_1 = new table_entry(new_link_1,fingerprint(first_half),fingerprint(ch));
            link_1->push_D_link(short_blocks[i].frag_links.D_chain);
            link_1->push_A_link(short_blocks[i].frag_links.A_chain);
            links.push_back(link_1);
            /*
            //Add the second link
            string second_half;
            assign(second_half,prefix(chains[short_blocks[i].frag_links.A_chain],len));
            string new_link_2 = ch;
            new_link_2.append(second_half);
            table_entry* link_2 = new table_entry(new_link_2,fingerprint(ch),fingerprint(second_half));
            link_2->push_D_link(short_blocks[i].frag_links.D_chain);
            link_2->push_A_link(short_blocks[i].frag_links.A_chain);
            links.push_back(link_2);
            */
            //::std::cout<<links[short_blocks[i].frag_links.D_chain]->get_short_read()->get_RNA_seq_sequence()<<::std::endl;
            //::std::cout<<links[short_blocks[i].frag_links.A_chain]->get_short_read()->get_RNA_seq_sequence()<<::std::endl;

            for(unsigned int j=0; j<short_blocks[i].other_links.size(); ++j){//Start_For_6
                string second_half;
                assign(first_half,prefix(chains[short_blocks[i].other_links[j].D_chain],len));
                string new_link_2 = second_half;
                new_link_2.append(ch);
                table_entry* link_2 = new table_entry(new_link_2,fingerprint(second_half),fingerprint(ch));
                link_2->push_D_link(short_blocks[i].other_links[j].D_chain);
                link_2->push_A_link(short_blocks[i].other_links[j].A_chain);
                links.push_back(link_1);
            }//End_For_6
            //}//End_If_5
    }
}
Example #16
0
void RageLog::UnmapLog(const CString &key)
{
	LogMaps.erase(key);
	UpdateMappedLog();
}
Example #17
0
bool CommandAttacker( Virus &v, AI *ai, Map& m ) {
    // Check for "attacker" status.
    if (v.level() >= attackerMin) {
      if (baseAttackers.size() <= maxAttackers) {
        baseAttackers[v.id()] = -1;
        cout << "Unassigned Attacker: " << v << endl;
      }
      Point vloc = Point(v.x(),v.y());

      if (baseAttackers.count(v.id())) {
        cout << "  Searching for target..." << endl;
        Path *closestPath = NULL;
        Base closest_base;
        EdgeCost closest = EdgeFar;

        // known attacker
        if (baseAttackers[v.id()] == -1) {
          for (vector<Base>::iterator base = ai->bases.begin();
               base != ai->bases.end();
               base++) {
            if ((*base).owner() == ai->playerID()) continue;
            cout << "  Enemy Base: " << (*base) << endl;

            Path p;
            p.start = vloc;
            p.end = Point((*base).x(),(*base).y());
            cout << asText(m,p);

            Path *toBase =
              path_astar(m,vloc,Point((*base).x(),(*base).y()),
                         (AStarBehavior_t)(AS_IgnoreViruses | AS_AllowImpassableEnd));

            if (!toBase) {
              cout << " * No path from " << vloc << " to base " 
                   << (*base) << endl;
              continue; // no path
            }
            cout << asText(m,*toBase);

            EdgeCost d = toBase->nodes.size()-1;
            if (d < closest) {
              closest = d;
              closest_base = *base;
              closestPath = toBase;
            }
          }
          if (closest != EdgeFar) {
            cout << "  Base acquired: " << closest_base << endl;
            baseAttackers[v.id()] = closest_base.id();
          }
        }
        if (closestPath == NULL) {
          baseAttackers.erase(v.id());
          return false; // this guy can't do it.
        }

        // Now, what to do.
        if (closestPath->nodes.size() <= 3) {
          // Look for a kill, or go to a corner.
          Point target;
          if (victimNearby(v,ai,m,target)) {
            cout << " Attacker [" << v.id() << "]" << vloc << " -> Victim " << target << "]" << endl;
            stringstream s(stringstream::out);
            s << " Attacker [" << v.id() << "]" << vloc << " -> Victim " << target << "]";
            string st = s.str();
            ai->players[ai->playerID()].talk((char*)(s.str().c_str()));
            v.move(target.x,target.y);
            return true;
          }
        } else {
          // Direct him toward the base.
          Point vMove = closestPath->nodes[1];
          cout << " Attacker [" << v.id() << "]" << vloc << " -> Base[" << closest_base << "]" << endl;
            stringstream s(stringstream::out);
            s << " Attacker [" << v.id() << "]" << vloc << " -> Base " << closest_base << "]";
            ai->players[ai->playerID()].talk((char*)(s.str().c_str()));
            v.move(vMove.x,vMove.y);
          return true;
        }
      }
    }

    return false;
}
Example #18
0
 void unboard(int s) {
     if (dest.empty() || dest.begin()->first > s) return;
     space += dest.begin()->second;
     dest.erase(dest.begin());
 }
Example #19
0
void AP::ClearClientInfo(uint iClientID)
	{
		mapDeferredJumps.erase(iClientID);
	}
Example #20
0
File: f.cpp Project: kzoacn/OI
inline void solve() {
	n = getnum();
	q = getnum();

	cnt.clear();

	for (int i = 1; i <= n; i++) {
		hus[i].clear();
		wife[i].clear();

		hus[i].push_back(i);
		wife[i].push_back(i);

		hus_idx[i] = i;
		wife_idx[i] = i;
		
		cnt[make_pair(i, i)] = 1;
	}

	int ans = 0, cur_ans = 0;

	for (int t = 1; t <= q; t++) {
		int type = getnum();
		int x = getnum();
		int y = getnum();

		if (type == 1) {
			int fx = hus_idx[x];
			int fy = hus_idx[y];
			if (fx != fy) {
				if (hus[fx].size() > hus[fy].size())
					swap(fx, fy), swap(x, y);
				vector<int> &_ = hus[fx];
				vector<int> &__ = hus[fy];
				for (int i = 0; i < (int)_.size(); i++) {
					int now = _[i];
					info cur = make_pair(fx, wife_idx[now]);	
					info nxt = make_pair(fy, wife_idx[now]);
					if (cnt.count(cur)) {
						int cur_value = cnt[cur];
						if (cnt.count(nxt)) {
							int nxt_value = cnt[nxt];
							update(cur_ans, (ll)cur_value * nxt_value % mod); 
							cnt[nxt] += cur_value;	
						} else {
							cnt[nxt] = cur_value;
						}
						cnt.erase(cur);
					}
					__.push_back(now);	
					hus_idx[now] = fy;
				}
				_.clear();
			}
		} else {
			int fx = wife_idx[x];
			int fy = wife_idx[y];
			if (fx != fy) {
				if (wife[fx].size() > wife[fy].size())
					swap(fx, fy), swap(x, y);
				vector<int> &_ = wife[fx];
				vector<int> &__ = wife[fy];
				for (int i = 0; i < (int)_.size(); i++) {
					int now = _[i];
					info cur = make_pair(hus_idx[now], fx);	
					info nxt = make_pair(hus_idx[now], fy);
					if (cnt.count(cur)) {
						int cur_value = cnt[cur];
						if (cnt.count(nxt)) {
							int nxt_value = cnt[nxt];
							update(cur_ans, (ll)cur_value * nxt_value % mod); 
							cnt[nxt] += cur_value;	
						} else {
							cnt[nxt] = cur_value;
						}
						cnt.erase(cur);
					}
					wife_idx[now] = fy;
					__.push_back(now);	
				}
				_.clear();
			}
		}

		update(ans, (ll)t * cur_ans % mod);
	}

	printf("%d\n", ans);
}
Example #21
0
	int unite(int a,int b){
		int x=root(a),y=root(b);if(x==y)return 0;
		parent[y]=x;
		size[x]+=size[y],size.erase(y);
		return 1;
	}
Example #22
0
int main()
{
	int n,maxPop,users;

	while(1)
	{
		scanf("%d", &n);

		if(!n)
			break;

		m.erase(m.begin(), m.end());
		maxPop = 0;
		users = 0;

		for(int i=0; i < n; i++)
		{
			vector<unsigned long long> v(5);
			unsigned long long s = 0;
			unsigned long long mulf = 1000000000000LL;

			for(int j=0; j < 5; j++)
				scanf("%llu", &v[j]);

			sort(v.begin(), v.end());

			for(int j=0; j < 4; j++)
			{
				//printf("%llu - ", v[j]);
				s += v[j] * mulf;
				mulf /= 1000;
				//printf("%llu\n", v[j]);
			}
			s += v[4];

			//printf("%llu\n", s);

			if (m.find(s) == m.end())
				m[s] = 1;
			else
				m[s] += 1;
		}

		for(auto it = m.begin(); it != m.end(); it++)
		{
			if ((*it).second > maxPop)
			{
				maxPop = (*it).second;
				users = maxPop;
			}
			else if ((*it).second == maxPop)
			{
				users += (*it).second;
			}

			//printf("%d\n", (*it).second);
		}
		
		printf("%d\n", users);
	}

	return EXIT_SUCCESS;
}
Example #23
0
DWORD WINAPI WorkerThread(LPVOID lpParam) {   
	int             i;   
	fd_set         fdread;   
	int             ret;   
	struct timeval tv = {1, 0};   
	char           uchoose;     
	while (1){     
		FD_ZERO(&fdread);     
		for (i = 0; i < svr.total; i++){ 
			FD_SET(svr.socks[i], &fdread); 
		}                      
		ret = select(0, &fdread, NULL, NULL, &tv); 
		if (ret == 0) {        
			continue; 
		} 
		for (i = 0; i < svr.total; i++){ 
			if (FD_ISSET(svr.socks[i], &fdread)) {         // A read event happened on g_CliSocketArr 
				ret = recv(svr.socks[i], &uchoose, 1, 0); 
				if (ret == 0 || (ret == SOCKET_ERROR && WSAGetLastError() == WSAECONNRESET)){ 
					// Client socket closed           
					cout<<"套接字 "<<svr.socks[i]<<"关闭"<<endl;
					cout<<"当前连接总数:  "<<svr.total-1<<endl;
					sit=sockmap.find(svr.socks[i]);
					if(sit!=sockmap.end()){
						int sid=sit->second;
						sockmap.erase(sit);
						it=idmap.find(sid);
						if(it!=idmap.end()){
							idmap.erase(it);
						}
					}
					closesocket(svr.socks[i]); 
					if (i < svr.total - 1){ 
						svr.socks[i--] = svr.socks[--svr.total]; 
					} 
					else{
						svr.total--;
					}
				} 
				else{ 
					switch(uchoose){
					case 'p' : //发送消息
						svr.mesgs[0]->setsock(svr.socks[i]);
						svr.mesgs[0]->process();
						break;
					case 'l': //账号登陆
						svr.mesgs[1]->setsock(svr.socks[i]);
						svr.mesgs[1]->process();
						break;
					case 'f': //查看好友
						svr.mesgs[2]->setsock(svr.socks[i]);
						svr.mesgs[2]->process();
						break;
					case 's': //查看资料
						svr.mesgs[3]->setsock(svr.socks[i]);
						svr.mesgs[3]->process();
						break;
					case 'r': //加入聊天室
						svr.mesgs[4]->setsock(svr.socks[i]);
						svr.mesgs[4]->process();
						break;
					case 'b': //发送聊天室消息
						svr.mesgs[5]->setsock(svr.socks[i]);
						svr.mesgs[5]->process();
						break;
					case 'a': //添加好友
						svr.mesgs[6]->setsock(svr.socks[i]);
						svr.mesgs[6]->process();
						break;
					case 'c': //修改密码
						svr.mesgs[7]->setsock(svr.socks[i]);
						svr.mesgs[7]->process();
					default:
						break;
					}
				} 
			}  
		} 
	}     
	return 0; 
} 
    T get(string key, ComputeFn computeFn)
    {
      // only allow one thread
      unique_lock<mutex> exclusion(this->monitor);
      
      // three possibilities
      if(cache.find(key) != cache.end())
      {
	// we have the value cached, just return it
      }
      else if(started_computation.find(key) != started_computation.end())
      {
	// another thread is computing the value, so we 
	// must wait...
	while(cache.find(key) == cache.end())
	  result_ready.wait(exclusion);
	//result_ready.at(key)->notify_one();
      }
      else
      {
	// tell other threads to wait for our computation
	started_computation.insert(key);
	
	// release the lock...
	exclusion.unlock();
	
	// compute the value
	T value = computeFn();
	
	// now we must re-lock the exclusion, update the map, and notify waiting threads
	exclusion.lock();
	cache.insert(std::pair<string,T>(key,value));
      }  

      // update the use times
      long time = virtual_time++;
      if(id_2_last_used.find(key) != id_2_last_used.end())
      {
	long prev_time = id_2_last_used.at(key);
	auto erase_at = last_used_2_id.find(prev_time);
	if(erase_at != last_used_2_id.end())	  
	  last_used_2_id.erase(erase_at);
      }
      id_2_last_used[key] = time;
      last_used_2_id[time] = key;

      // 
      string remove_key;
      if(cache.size() > capacity)
      {
	// free the least recently used item.
	remove_key = last_used_2_id.begin()->second;
	cache.erase(remove_key);
	started_computation.erase(remove_key);
      }
      
      // release the lock
      T result = cache.at(key);
      exclusion.unlock();
      result_ready.notify_all();
      return result;
    }
Example #25
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;
}
Example #26
0
void* proxy( void *arg )
{
	pthread_detach( pthread_self() );
	fd_set	writeSet;
	fd_set	readSet;
	int		maxfd = 0;
	unsigned char	buf[MAXBUF];
	char		tempjson[MAXBUF + 1];
	struct timeval	timeout;
	TunnelInfo	*tunnelinfo	= NULL;
	int		maxfdp		= 0;
	int ret=0;
	ssl_info *sslinfo1;
	sockinfo *tempinfo ;
	sockinfo *tempinfo1 ;
	map<int, sockinfo*>::iterator it;
	map<int, sockinfo*>::iterator it1;
	map<int, sockinfo*>::iterator it2;
	int backcode=0;
	while ( proxyrun )
	{

	    if(pingtime+ping<get_curr_unixtime()&&socklist.count(mainsock)!=0&&mainsock!=0)
        {

            #if OPENSSL
            int sendlen = SendPing(mainsock, mainsslinfo->ssl );
            #else
            int sendlen = SendPing(mainsock, &mainsslinfo->ssl );
            #endif
            //发送失败断开连接
            if(sendlen==-1)
            {
                shutdown( mainsock,2);
                mainsock = 0;
                proxyrun=0;
            }
            pingtime = get_curr_unixtime();
	    }

		timeout.tv_sec	= 0;
		timeout.tv_usec = 5000;
		FD_ZERO( &readSet );
		maxfd	= 0;
		maxfdp	= 0;
		FD_ZERO( &writeSet );

		/* 遍历添加 */
		//map<int, sockinfo*>::iterator it;
		for ( it = socklist.begin(); it != socklist.end();  )
		{
			tempinfo = it->second;
			/* 如果未连接才添加,写入监听 */
			if ( tempinfo->isconnect == 0 )
			{
				FD_SET( it->first, &writeSet );
			}
			else{
				FD_SET( it->first, &readSet );
			}
			maxfdp = it->first > maxfdp ? it->first : maxfdp;
			maxfd++;
			//继续遍历
			++it;
		}





		if(maxfd==0)
		{
			sleeps( 500 );
		}

		/*  printf("add ok \r\n"); */
        ret = select( maxfdp + 1, &readSet, &writeSet, NULL, &timeout ); /* 为等待时间传入NULL,则永久等待。传入0立即返回。不要勿用。 */
		if ( ret == -1 && maxfd != 0 )
		{
            echo("select error\r\n");
			continue;
		}

		if ( ret > 0 )
		{
			for ( it1 = socklist.begin(); it1 != socklist.end(); )
			{
			    tempinfo = it1->second;
			    /*等于1才是添加到 readSet的*/
				if (FD_ISSET( it1->first, &readSet )&&tempinfo->isconnect==1 )
				{
                    //先清空
                    memset((char *)buf,0,MAXBUF);
                    sslinfo1 = tempinfo->sslinfo;
                    /* 远程的转发给本地 */
                    if ( tempinfo->istype == 1 )
                    {
                        if ( tempinfo->isconnectlocal == 0 )
                        {
                            backcode=ConnectLocal(sslinfo1,(char *)buf,MAXBUF,&it1,tempinfo,&socklist,tempjson,&tunnellist,tunnelinfo);
                            if(backcode==-1)
                            {
                              continue;
                            }
                        }

                        if( tempinfo->isconnectlocal == 2||tempinfo->isconnectlocal == 1  )
                        {
                            backcode=RemoteToLocal(sslinfo1,MAXBUF,(char *)buf,tempinfo,&it1,&socklist);
                            if(backcode==-1)
                            {
                              continue;
                            }
                        }
                    }
                    /* 本地的转发给远程 */
                    else if(tempinfo->istype == 2){
                        backcode=LocalToRemote(&it1,(char*)buf,MAXBUF,tempinfo,sslinfo1,&socklist);
                        if(backcode==-1)
                        {
                          continue;
                        }
                    }
                    //控制连接
                    else if(tempinfo->istype ==3){
                         backcode=CmdSock(&mainsock,MAXBUF,(char *)buf,tempinfo,&socklist,tempjson,server_addr,&ClientId,&tunneloklist,&tunnellist);
                         if(backcode==-1)
                         {

                            clearsock( it1->first, tempinfo );
							socklist.erase(it1++);
							mainsock=0;
							tunneloklist.clear();
                            continue;
                         }
                    }


				}
				//可写,表示连接上了
				if ( FD_ISSET( it1->first, &writeSet )&&tempinfo->isconnect==0 )
				{

					if ( tempinfo->isconnect == 0 )
					{
					    //检测连接是否可用
						if (check_sock(it1->first)!= 0 )
						{
						    	//关闭远程连接
							if(tempinfo->istype==2){
                                echo("连接本地失败");
							    shutdown( tempinfo->tosock, 2 );
							}
							clearsock(it1->first,tempinfo);
							socklist.erase(it1++);
							continue;
						}

						/* 置为1 */
						tempinfo->isconnect = 1;

						/* 为远程连接 */
						if ( tempinfo->istype == 1 )
						{
						    //初始化远程连接
                            backcode=RemoteSslInit(&it1,tempinfo,ClientId,&socklist);
                            if(backcode==-1)
                            {
                              continue;
                            }
						}

						//本地连接
                        if ( tempinfo->istype == 2 )
						{
                            it2 = socklist.find(tempinfo->tosock);
                            if(it2 != socklist.end())
                            {
                                tempinfo1 = it2->second;
                                tempinfo1->isconnectlocal=2;
                                /* copy到临时缓存区 */
                                if ( tempinfo1->packbuflen > 0 )
                                {
                                    setnonblocking( it1->first, 0 );
                                    #if WIN32
                                    send(it1->first,(char *)tempinfo1->packbuf,tempinfo1->packbuflen, 0 );
                                    #else
                                    send( it1->first, tempinfo1->packbuf, tempinfo1->packbuflen, 0 );
                                    #endif
                                    setnonblocking(it1->first, 1 );
                                    free( tempinfo1->packbuf );
                                    tempinfo1->packbuf	= NULL;
                                    tempinfo1->packbuflen	= 0;
                                }
                            }
						}
					}
				}
				//继续遍历
				++it1;
			}
		}
		//睡1豪秒,避免CPU过高
		sleeps(2);
	}
	/* 退出 */
	proxyrun = 0;
	return(0);
}
/**
 * Main entry called from Matlab
 * @param nlhs number of left-hand-side arguments
 * @param plhs pointers to mxArrays in the left-hand-side
 * @param nrhs number of right-hand-side arguments
 * @param prhs pointers to mxArrays in the right-hand-side
 */
void mexFunction( int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[] )
{
	if (nlhs>1)
        mexErrMsgIdAndTxt("mexopencv:error","Wrong number of arguments");
    
	// Determine argument format between constructor or (id,method,...)
	vector<MxArray> rhs(prhs,prhs+nrhs);
	int id = 0;
	string method;
	if (nrhs==0) {
		// Constructor is called. Create a new object from argument
		obj_[++last_id] = NormalBayesClassifier();
		plhs[0] = MxArray(last_id);
		return;
	}
	else if (rhs[0].isNumeric() && rhs[0].numel()==1 && nrhs>1) {
		id = rhs[0].toInt();
		method = rhs[1].toString();
	}
	else
        mexErrMsgIdAndTxt("mexopencv:error","Invalid arguments");
	
	// Big operation switch
	NormalBayesClassifier& obj = obj_[id];
    if (method == "delete") {
    	if (nrhs!=2 || nlhs!=0)
    		mexErrMsgIdAndTxt("mexopencv:error","Output not assigned");
    	obj_.erase(id);
    }
    else if (method == "clear") {
    	if (nrhs!=2 || nlhs!=0)
    		mexErrMsgIdAndTxt("mexopencv:error","Wrong number of arguments");
    	obj.clear();
    }
    else if (method == "load") {
    	if (nrhs!=3 || nlhs!=0)
    		mexErrMsgIdAndTxt("mexopencv:error","Wrong number of arguments");
    	obj.load(rhs[2].toString().c_str());
    }
    else if (method == "save") {
    	if (nrhs!=3 || nlhs!=0)
    		mexErrMsgIdAndTxt("mexopencv:error","Wrong number of arguments");
    	obj.save(rhs[2].toString().c_str());
    }
    else if (method == "train") {
    	if (nrhs<4 || nlhs>1)
    		mexErrMsgIdAndTxt("mexopencv:error","Wrong number of arguments");
    	Mat trainData(rhs[2].toMat(CV_32F));
    	Mat responses(rhs[3].toMat(CV_32F));
    	Mat varIdx;
    	Mat sampleIdx;
    	bool update=false;
    	for (int i=4; i<nrhs; i+=2) {
    		string key(rhs[i].toString());
    		if (key=="VarIdx")
    			varIdx = rhs[i+1].toMat(CV_32S);
    		else if (key=="SampleIdx")
    			sampleIdx = rhs[i+1].toMat(CV_32S);
    		else if (key=="Update")
    			update = rhs[i+1].toBool();
    		else
    			mexErrMsgIdAndTxt("mexopencv:error","Unrecognized option");
    	}
    	bool b = obj.train(trainData,responses,varIdx,sampleIdx,update);
    	plhs[0] = MxArray(b);
    }
    else if (method == "predict") {
    	if (nrhs<3 || nlhs>1)
    		mexErrMsgIdAndTxt("mexopencv:error","Wrong number of arguments");
    	Mat samples(rhs[2].toMat(CV_32F)),results;
    	obj.predict(samples,&results);
    	plhs[0] = MxArray(results);
    }
    else
		mexErrMsgIdAndTxt("mexopencv:error","Unrecognized operation");
}
Example #28
0
 BSONObj WaitProgram( const BSONObj& a ){
     int pid = a.firstElement().numberInt();
     BSONObj x = BSON( "" << wait_for_pid( pid ) );
     shells.erase( pid );
     return x;
 }
Example #29
0
int main(int argc, char* argv[]){

	hd44780 lcd(14, 15, 24, 25, 8, 7);
   	lcd.init(20, 4);
	lcd.setAutoscroll(hd44780::HSCROLL_LINE | hd44780::VSCROLL);
	
	rpihw::gpio &io = rpihw::gpio::get();
	io.setup(23, rpihw::OUTPUT);
	io.write(23, rpihw::HIGH); bool *backlight = new bool(true);

	uint8_t blank[8]		= {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
	lcd.defChar(hd44780::CCHAR2, blank);
	
	getDatabaseDetails(&DBHOST, &USER, &PASSWORD, &DATABASE);
	retrieveSQL(entries, lcd);
	entries.erase(0);
	
	int card = 0;
	
	lcd.move(0,2);
	printfl("DeltaPi ver. 0.9.0",lcd);
	
	do{
		moveAndClearLine(0,0,lcd);
		lcd.write("Retrieving database");
		retrieveSQL(entries, lcd);
		scanCard(entries, card, lcd);
		if (!(*backlight))
			changeBacklight(io, backlight, lcd);
		if (card > 10){
			moveAndClearLine(0,1,lcd);
			lcd.write("Retrieving database");
			retrieveSQL(entries, lcd);
			printInfo(entries, card, lcd);
			transaction(entries, card, lcd);
		}
		else if (card == 0){
			printHelp(lcd);
		}else if (card == 1){
			lcd.write("Retrieving database");
			retrieveSQL(entries, lcd);
			printSummary(entries, lcd);
		} else if (card == 3){
			lcd.clear();
			lcd.move(0,1);
			printfl("Retrieving database", lcd);
			retrieveSQL(entries, lcd);	
		} else if (card == 4){
			printTime(lcd);
		} else if (card == 6){
			printLastCoffee(lcd);
		} else if (card == 9){
			changeBacklight(io, backlight, lcd);
		}
	}while (card != -1);
	lcd.clear();
	
	printfl("  Closing DeltaPi", lcd);
	lcd.move(6,2);
	lcd.write("Goodbye!    .",128);
	io.write(23, rpihw::LOW);
	
	delete backlight;
	return 0;
}
Example #30
0
int main() {
  int T; cin >> T;

  for(int t = 1; t <= T; t++) {
    int N, M; cin >> N >> M;

    graph.clear();
    graph.resize(N);
    edges.clear();
    edge_ineff_count.clear();
    edge_ineff_count.resize(M, 0);

    for(int i = 0; i < M; i++) {
      int u, v, c; cin >> u >> v >> c;
      graph[u].push_back({v, c});
      graph[v].push_back({u, c});
      edges.push_back({u, v});
    }

    for(int i = 0; i < N; i++) {
      visited.clear();
      visited.resize(N, false);

      vector<int> D(N, INF);
      vector<int> parent(N, -1);
      set<pair<int, int> > Q;
      D[i] = 0;
      Q.insert({0, i});

      while(!Q.empty()) {
        auto top = *Q.begin();
        Q.erase(Q.begin());
        int v = top.second, cost = top.first;
        for(auto it: graph[v]) {
          int v2 = it.first, cost2 = it.second;
          if(D[v2] > D[v] + cost2) {
            if(D[v2] != INF) {
              Q.erase({D[v2], v2});
            }
            D[v2] = D[v] + cost2;
            parent[v2] = v;
            Q.insert({D[v2], v2});
          }
        }
      }

      for(int i = 0; i < M; i++) edge_map[edges[i]] = i;

      for(int j = 0; j < N; j++) {
        if(j == i) continue;

        edge_map.erase({j, parent[j]});
        edge_map.erase({parent[j], j});
      }

      for(auto it: edge_map) {
        edge_ineff_count[it.second]++;
      }
      edge_map.clear();
    }

    cout << "Case #" << t << ":" << endl;
    for(int i = 0; i < M; i++) {
      if(edge_ineff_count[i] >= N) cout << i << endl;
    }
  }
}