Beispiel #1
0
	MenuUtils& addPair(pair<string,string> pair_value){
		cnt_list.push_back(pair_value);

		return *this;
	}
Beispiel #2
0
/* Loads the conn.hist file into memory */
void load_connhistory( void )
{
   ifstream stream;
   conn_data *conn;
   size_t conncount = 0;

   connlist.clear(  );

   stream.open( CH_FILE );
   if( !stream.is_open(  ) )
      return;

   do
   {
      string key, value;
      char buf[MIL];

      stream >> key;
      stream.getline( buf, MIL );
      value = buf;

      strip_lspace( key );
      strip_lspace( value );
      strip_tilde( value );

      if( key.empty(  ) )
         continue;

      if( key == "#CONN" )
         conn = new conn_data;
      else if( key == "User" )
         conn->user = value;
      else if( key == "When" )
         conn->when = value;
      else if( key == "Host" )
         conn->host = value;
      else if( key == "Level" )
         conn->level = atoi( value.c_str(  ) );
      else if( key == "Type" )
         conn->type = atoi( value.c_str(  ) );
      else if( key == "Invis" )
         conn->type = atoi( value.c_str(  ) );
      else if( key == "End" )
      {
         if( conncount < MAX_CONNHISTORY )
         {
            ++conncount;
            connlist.push_back( conn );
         }
         else
         {
            bug( "%s: more connection histories than MAX_CONNHISTORY %zd", __FUNCTION__, MAX_CONNHISTORY );
            stream.close(  );
            return;
         }
      }
      else
         bug( "%s: Bad line in connection history file: %s %s", __FUNCTION__, key.c_str(  ), value.c_str(  ) );
   }
   while( !stream.eof(  ) );
   stream.close(  );
}
Beispiel #3
0
/*
* write triangulation to OFF-file
*/
void writeOFFFile()
{
	int i;
	string offFilenameStr = "boundaryComplex.off";
	const char *offFilename = offFilenameStr.c_str();
	ofstream fileOut(offFilename);

	if (fileOut.is_open())
	{
		// count triangles
		int triangleCount = 0;

		for (list<Triangle>::iterator iter = dtTriangles.begin(); iter != dtTriangles.end(); iter++)
		{
			Triangle *currTri = &*iter;

			if (currTri->exists())
				triangleCount++;
		}

		// write OFF header
		fileOut << "OFF" << endl;
		fileOut << (int)dt->number_of_vertices() << " " << triangleCount << " 0" << endl;

		// TODO: some vertex indices are higher than vertexCount: (up to 200 in ts-dragon): why? and if there are holes, need to compact them for triangle writing!

		// write vertex list
		for (Dt::Finite_vertices_iterator vhIter = dt->finite_vertices_begin(); vhIter != dt->finite_vertices_end(); vhIter++)
		{
			DVertex currVH = vhIter;
			int vIndex = currVH->info().index();

			if (vIndex != -1)
			{
				Vector3D vec = v[vIndex].vec;

				for (i = 0; i < 3; i++)
					fileOut << vec[i] << " ";

				fileOut << endl;

				// DEBUG
				if (vIndex >= (int)dt->number_of_vertices())
				{
					cout << "v #" << vIndex << ">= " << (int)dt->number_of_vertices() << "(vertexcount)!" << endl;
					assert(false);
				}
			}
		}

		// write triangle list
		for (list<Triangle>::iterator iter = dtTriangles.begin(); iter != dtTriangles.end(); iter++)
		{
			Triangle *currTri = &*iter;

			if (currTri->exists())
			{
				fileOut << "3 ";

				for (i = 0; i < 3; i++)
					fileOut << currTri->vertex(i)->info().index() << " ";

				fileOut << endl;
			}
		}

		fileOut.close();
	}
	else
		cout << "ERROR: could not write OFF file " << offFilenameStr << endl;
}
Beispiel #4
0
Datei: ui.cpp Projekt: arke/Epiar
// list of events is passed from main input handler. we remove the events we handle and leave the rest to be handled
// by the next input handler. the order of input handlers is in input.cpp
void UI::HandleInput( list<InputEvent> & events ) {
	// Go through all input events to see if they apply to any top-level widget. top-level widgets
	// (like windows) will then take the input and pass it to any children (like the ok button in the window)
	// where appropriate
	list<InputEvent>::iterator i = events.begin();
	while( i != events.end() )
	{
		bool eventWasHandled = false;
	
		switch( i->type ) {
		case KEY:
		
			switch(i->kstate) {
				case KEYTYPED:
					if( keyboardFocus ) { 
						bool handled = keyboardFocus->KeyPress( i->key );
						
						// if the input was handled, we need to remove it from the queue so no other
						// subsystem sees it and acts on it
						if( handled ) {
							events.erase(i);
							i = events.begin();
						}
					}
					break;
				
				default:
					break;
			}

			break;
		case MOUSE:
			int x, y;
			
			// mouse coordinates associated with the mouse event
			x = i->mx;
			y = i->my;

			switch(i->mstate) {
			case MOUSEMOTION:
				// if a widget has mouse focus, we are dragging
				if( mouseFocus ) {
					int dx, dy; // original point of click for the drag
					
					dx = mouseFocus->GetDragX();
					dy = mouseFocus->GetDragY();

					mouseFocus->SetX( x - dx );
					mouseFocus->SetY( y - dy );
					
					eventWasHandled = true;
				}
				break;
			case MOUSEUP:
				// release focus if needed
				if( mouseFocus ) {
					// let the focused widget know it's no longer focused
					mouseFocus->UnfocusMouse();
					mouseFocus = NULL;

					eventWasHandled = true;
				}
				break;
			case MOUSEDOWN:
				Widget *focusedWidget = DetermineMouseFocus( x, y );
				
				// did they click a different widget than the one already in focus?
				if( mouseFocus != focusedWidget ) {
					// A new widget now has focus
					if( mouseFocus )
						mouseFocus->UnfocusMouse();
					
					mouseFocus = focusedWidget;
					
					if( mouseFocus ) {
						mouseFocus->FocusMouse( x - mouseFocus->GetX(), y - mouseFocus->GetY() );
					}
				}
				// mouse down also changes keyboard focus (e.g. clicked on a new text field)
				if( keyboardFocus != focusedWidget ) {
					if( keyboardFocus ) keyboardFocus->UnfocusKeyboard();
					
					keyboardFocus = focusedWidget;
					
					if( keyboardFocus ) {
						keyboardFocus->FocusKeyboard();
					}
				}
				
				// pass the event to the widget
				if( mouseFocus ) {
					mouseFocus->MouseDown( x - mouseFocus->GetX(), y - mouseFocus->GetY() );
					
					eventWasHandled = true;				
				}
				break;
			}
			break;
		}

		if( eventWasHandled ) {
			i = events.erase( i );
		} else {
			i++;
		}
	}
}
Beispiel #5
0
 foreachvalue (const Owned<Store>& store, stores) {
   recovers.push_back(store->recover());
 }
Beispiel #6
0
void GenPermutation(vector<string> &prefix_set, int start, list<string> &result, int freq, int suffix_len)
{
    if(start==prefix_set.size()-1)
    {
	result.push_back(prefix_set[start]);
	if(result.size()<=suffix_len)
	    return;
	
	list<string>::iterator it;
	printf("{");
	for(it=result.begin(); it!=result.end(); it++)
	    printf("%s ",it->c_str());
	printf("}#%d \n",freq);

	result.pop_back();
	if(result.size()>suffix_len)
	{
	    printf("{");
	    int i;
	    for(i=0, it=result.begin(); it!=result.end(); i++,it++)
	    {
		printf("%s",it->c_str());
		if(i!=result.size()-1)
		    printf(",");
	    }
	    printf("}#%d\n",freq);
	}
        return;
    }

    result.push_back(prefix_set[start]);
    GenPermutation(prefix_set, start+1, result, freq, suffix_len);
    result.pop_back();
    GenPermutation(prefix_set, start+1, result, freq, suffix_len);
}
void waves(int numwave)
{
    if(numwave == 1)
    {
        wave_apuntador = &wave1_complete;
        show_dialogs();
    }
    else if(numwave == 2)
        wave_apuntador = &wave2_complete;

    while((*wave_apuntador) != true)
    {
        segundos++;
        //cout << "Segundos: " << segundos << endl;
        frame++;
        if(frame%50==0)
        {
            if(numwave == 1)
                personajes.push_back(new Hollow (rand()%880,rand() % 570,renderer,&personajes));

            else if(numwave == 2)
            {
                personajes.push_back(new Hollow2 (rand()%880,rand() % 570,renderer,&personajes));
                personajes.push_back(new Hollow3 (rand()%880,rand() % 570,renderer,&personajes));
            }
        }
        while(SDL_PollEvent(&Event))
        {
            if(Event.type == SDL_KEYDOWN)
            {
                if(Event.key.keysym.sym == SDLK_ESCAPE)
                {
                    esc = true;
                    return;
                }
            }
            if(Event.type == SDL_QUIT)
            {
                exit(0);
            }
        }

        for(list<Personaje*>::iterator i = personajes.begin(); i!=personajes.end(); i++)
        {
            (*i)->logic((Uint8*)SDL_GetKeyboardState( NULL ));
            if((*i)->id == "Personaje")
            {
                pos_x = (*i)->rectangulo.x;
                pos_y = (*i)->rectangulo.y;
                if((*i)->HP == 0)
                {
                    (*i)->reset();
                    return;
                }

                else if((*i)->contador_puntos == 400)//100
                {
                    *wave_apuntador = true;
                    (*i)->reset();
                }
            }
        }

        SDL_RenderCopy(renderer, game_background, NULL, &rect_background);
        //SDL_RenderCopy(renderer, *dialogo_actual, NULL, &rect_text);

        for(list<Personaje*>::iterator i = personajes.begin(); i!=personajes.end(); i++)
            (*i)->render(renderer);

        SDL_RenderPresent(renderer);

        SDL_Delay(16.66);

        if(segundos == 2300 && (*wave_apuntador) != true)//800
        {
            esc = true;
            return;
        }
    }
}
void VrmlNodeMultiTouchSensor::removeMultiTouchNode(VrmlNodeMultiTouchSensor *node)
{
    multiTouchSensors.remove(node);
}
Beispiel #9
0
 AnswerSet operator()(const list<AspFluent>& plan) {
   return AnswerSet(plan.begin(), plan.end());
 }
Beispiel #10
0
 void trim_cache(list<VPtr> *to_release) {
   while (size > max_size) {
     to_release->push_back(lru.back().second);
     lru_remove(lru.back().first);
   }
 }
void VrmlNodeMultiTouchSensor::addMultiTouchNode(VrmlNodeMultiTouchSensor *node)
{
    multiTouchSensors.push_front(node);
}
Beispiel #12
0
void show(list<Stack>& list, string msg) {
	cout << msg << ", function show" << endl;
	for (auto iter = list.begin(); iter != list.end(); ++iter) {
		cout << "element: " << *iter << endl;
	}
}
Beispiel #13
0
//-----------------------------------------------------------------------------
// <OnNotification>
// Callback that is triggered when a value, group or node changes
//-----------------------------------------------------------------------------
void OnNotification
(
	Notification const* _notification,
	void* _context
)
{
	qpid::types::Variant::Map eventmap;
	// Must do this inside a critical section to avoid conflicts with the main thread
	pthread_mutex_lock( &g_criticalSection );

	switch( _notification->GetType() )
	{
		case Notification::Type_ValueAdded:
		{
			if( NodeInfo* nodeInfo = GetNodeInfo( _notification ) )
			{
				// Add the new value to our list
				nodeInfo->m_values.push_back( _notification->GetValueID() );
				uint8 basic = Manager::Get()->GetNodeBasic(_notification->GetHomeId(),_notification->GetNodeId());
				uint8 generic = Manager::Get()->GetNodeGeneric(_notification->GetHomeId(),_notification->GetNodeId());
				uint8 specific = Manager::Get()->GetNodeSpecific(_notification->GetHomeId(),_notification->GetNodeId());
				ValueID id = _notification->GetValueID();
				string label = Manager::Get()->GetValueLabel(id);
				stringstream tempstream;
				tempstream << (int) _notification->GetNodeId();
				tempstream << "/";
				tempstream << (int) id.GetInstance();
				string nodeinstance = tempstream.str();
				tempstream << "-";
				tempstream << label;
				string tempstring = tempstream.str();
				ZWaveNode *device;
				if (basic == BASIC_TYPE_CONTROLLER) {
					if ((device = devices.findId(nodeinstance)) != NULL) {
						device->addValue(label, id);
						device->setDevicetype("remote");
					} else {
						device = new ZWaveNode(nodeinstance, "remote");	
						device->addValue(label, id);
						devices.add(device);
						agoConnection->addDevice(device->getId().c_str(), device->getDevicetype().c_str());
					}
				} else
				switch(id.GetCommandClassId()) {
					case COMMAND_CLASS_SWITCH_MULTILEVEL:
						if (label == "Level") {
							if ((device = devices.findId(nodeinstance)) != NULL) {
								device->addValue(label, id);
								device->setDevicetype("dimmer");
							} else {
								device = new ZWaveNode(nodeinstance, "dimmer");	
								device->addValue(label, id);
								devices.add(device);
								agoConnection->addDevice(device->getId().c_str(), device->getDevicetype().c_str());
							}
							// Manager::Get()->EnablePoll(id);
						}
					break;
					case COMMAND_CLASS_SWITCH_BINARY:
						if (label == "Switch") {
							if ((device = devices.findId(nodeinstance)) != NULL) {
								device->addValue(label, id);
							} else {
								device = new ZWaveNode(nodeinstance, "switch");	
								device->addValue(label, id);
								devices.add(device);
								agoConnection->addDevice(device->getId().c_str(), device->getDevicetype().c_str());
							}
							// Manager::Get()->EnablePoll(id);
						}
					break;
					case COMMAND_CLASS_SENSOR_BINARY:
						if (label == "Sensor") {
							if ((device = devices.findId(tempstring)) != NULL) {
								device->addValue(label, id);
							} else {
								device = new ZWaveNode(tempstring, "binarysensor");	
								device->addValue(label, id);
								devices.add(device);
								agoConnection->addDevice(device->getId().c_str(), device->getDevicetype().c_str());
							}
							// Manager::Get()->EnablePoll(id);
						}
					break;
					case COMMAND_CLASS_SENSOR_MULTILEVEL:
						if (label == "Luminance") {
							device = new ZWaveNode(tempstring, "brightnesssensor");	
							device->addValue(label, id);
							devices.add(device);
							agoConnection->addDevice(device->getId().c_str(), device->getDevicetype().c_str());
						} else if (label == "Temperature") {
							if (generic == GENERIC_TYPE_THERMOSTAT) {
								if ((device = devices.findId(nodeinstance)) != NULL) {
									device->addValue(label, id);
								} else {
									device = new ZWaveNode(nodeinstance, "thermostat");	
									device->addValue(label, id);
									devices.add(device);
									agoConnection->addDevice(device->getId().c_str(), device->getDevicetype().c_str());
								}
							} else {
								device = new ZWaveNode(tempstring, "temperaturesensor");	
								device->addValue(label, id);
								devices.add(device);
								agoConnection->addDevice(device->getId().c_str(), device->getDevicetype().c_str());
							}
						} else {
							printf("WARNING: unhandled label for SENSOR_MULTILEVEL: %s - adding generic multilevelsensor\n",label.c_str());
							if ((device = devices.findId(nodeinstance)) != NULL) {
								device->addValue(label, id);
							} else {
								device = new ZWaveNode(nodeinstance, "multilevelsensor");	
								device->addValue(label, id);
								devices.add(device);
								agoConnection->addDevice(device->getId().c_str(), device->getDevicetype().c_str());
							}
						}
						// Manager::Get()->EnablePoll(id);
					break;
					case COMMAND_CLASS_METER:
						if (label == "Power") {
							device = new ZWaveNode(tempstring, "powermeter");	
							device->addValue(label, id);
							devices.add(device);
							agoConnection->addDevice(device->getId().c_str(), device->getDevicetype().c_str());
						} else if (label == "Energy") {
							device = new ZWaveNode(tempstring, "energymeter");	
							device->addValue(label, id);
							devices.add(device);
							agoConnection->addDevice(device->getId().c_str(), device->getDevicetype().c_str());
						} else {
							printf("WARNING: unhandled label for CLASS_METER: %s - adding generic multilevelsensor\n",label.c_str());
							if ((device = devices.findId(nodeinstance)) != NULL) {
								device->addValue(label, id);
							} else {
								device = new ZWaveNode(nodeinstance, "multilevelsensor");	
								device->addValue(label, id);
								devices.add(device);
								agoConnection->addDevice(device->getId().c_str(), device->getDevicetype().c_str());
							}
						}
						// Manager::Get()->EnablePoll(id);
					break;
					case COMMAND_CLASS_BASIC_WINDOW_COVERING:
						// if (label == "Open") {
							if ((device = devices.findId(nodeinstance)) != NULL) {
								device->addValue(label, id);
								device->setDevicetype("drapes");
							} else {
								device = new ZWaveNode(nodeinstance, "drapes");	
								device->addValue(label, id);
								devices.add(device);
								agoConnection->addDevice(device->getId().c_str(), device->getDevicetype().c_str());
							}
							// Manager::Get()->EnablePoll(id);
					//	}
					break;
					case COMMAND_CLASS_THERMOSTAT_SETPOINT:
						if (polling) Manager::Get()->EnablePoll(id);
					case COMMAND_CLASS_THERMOSTAT_MODE:
					case COMMAND_CLASS_THERMOSTAT_FAN_MODE:
					case COMMAND_CLASS_THERMOSTAT_FAN_STATE:
					case COMMAND_CLASS_THERMOSTAT_OPERATING_STATE:
						cout << "adding thermostat label: " << label << endl;
						if ((device = devices.findId(nodeinstance)) != NULL) {
							device->addValue(label, id);
							device->setDevicetype("thermostat");
						} else {
							device = new ZWaveNode(nodeinstance, "thermostat");	
							device->addValue(label, id);
							devices.add(device);
							agoConnection->addDevice(device->getId().c_str(), device->getDevicetype().c_str());
						}
					break;
					default:
						printf("Notification: Unassigned Value Added Home 0x%08x Node %d Genre %d Class %x Instance %d Index %d Type %d - Label: %s\n", _notification->GetHomeId(), _notification->GetNodeId(), id.GetGenre(), id.GetCommandClassId(), id.GetInstance(), id.GetIndex(), id.GetType(),label.c_str());
						// printf("Notification: Unassigned Value Added Home 0x%08x Node %d Genre %d Class %x Instance %d Index %d Type %d - ID: %" PRIu64 "\n", _notification->GetHomeId(), _notification->GetNodeId(), id.GetGenre(), id.GetCommandClassId(), id.GetInstance(), id.GetIndex(), id.GetType(),id.GetId());

				}
			}
			break;
		}
		case Notification::Type_ValueRemoved:
		{
			if( NodeInfo* nodeInfo = GetNodeInfo( _notification ) )
			{
				// Remove the value from out list
				for( list<ValueID>::iterator it = nodeInfo->m_values.begin(); it != nodeInfo->m_values.end(); ++it )
				{
					if( (*it) == _notification->GetValueID() )
					{
						nodeInfo->m_values.erase( it );
						break;
					}
				}
			}
			break;
		}

		case Notification::Type_ValueChanged:
		{
			if( NodeInfo* nodeInfo = GetNodeInfo( _notification ) )
			{
				// One of the node values has changed
				// TBD...
				// nodeInfo = nodeInfo;
				ValueID id = _notification->GetValueID();
				string str;
				printf("Notification: Value Changed Home 0x%08x Node %d Genre %d Class %d Instance %d Index %d Type %d\n", _notification->GetHomeId(), _notification->GetNodeId(), id.GetGenre(), id.GetCommandClassId(), id.GetInstance(), id.GetIndex(), id.GetType());
			      if (Manager::Get()->GetValueAsString(id, &str)) {
					qpid::types::Variant cachedValue;
					cachedValue.parse(str);
					valueCache[id] = cachedValue;
					string label = Manager::Get()->GetValueLabel(id);
					string units = Manager::Get()->GetValueUnits(id);

					// TODO: send proper types and don't convert everything to string
					string level = str;
					string eventtype = "";
					if (str == "True") level="255";
					if (str == "False") level="0";
					printf("Value: %s Label: %s Unit: %s\n",str.c_str(),label.c_str(),units.c_str());
					if ((label == "Basic") || (label == "Switch") || (label == "Level")) {
						eventtype="event.device.statechanged";
					}
					if (label == "Luminance") {
						eventtype="event.environment.brightnesschanged";
					}
					if (label == "Temperature") {
						eventtype="event.environment.temperaturechanged";
						if (units=="F" && unitsystem==0) {
							units="C";
							str = float2str((atof(str.c_str())-32)*5/9);
							level = str;
						} else if (units =="C" && unitsystem==1) {
							units="F";
							str = float2str(atof(str.c_str())*9/5 + 32);
							level = str;
						}
					}
					if (label == "Relative Humidity") {
						eventtype="event.environment.humiditychanged";
					}
					if (label == "Battery Level") {
						eventtype="event.device.batterylevelchanged";
					}
					if (label == "Alarm Level") {
						eventtype="event.security.alarmlevelchanged";
					}
					if (label == "Alarm Type") {
						eventtype="event.security.alarmtypechanged";
					}
					if (label == "Sensor") {
						eventtype="event.security.sensortriggered";
					}
					if (label == "Energy") {
						eventtype="event.environment.energychanged";
					}
					if (label == "Power") {
						eventtype="event.environment.powerchanged";
					}
					if (label == "Mode") {
						eventtype="event.environment.modechanged";
					}
					if (label == "Fan Mode") {
						eventtype="event.environment.fanmodechanged";
					}
					if (label == "Fan State") {
						eventtype="event.environment.fanstatechanged";
					}
					if (label == "Operating State") {
						eventtype="event.environment.operatingstatechanged";
					}
					if (label == "Cooling 1") {
						eventtype="event.environment.coolsetpointchanged";
					}
					if (label == "Heating 1") {
						eventtype="event.environment.heatsetpointchanged";
					}
					if (label == "Fan State") {
						eventtype="event.environment.fanstatechanged";
					}
					if (eventtype != "") {	
						ZWaveNode *device = devices.findValue(id);
						if (device != NULL) {
							if (debug) printf("Sending %s event from child %s\n",eventtype.c_str(), device->getId().c_str());
							agoConnection->emitEvent(device->getId().c_str(), eventtype.c_str(), level.c_str(), units.c_str());	
						}
					}
				}
			}
			break;
		}
		case Notification::Type_Group:
		{
			if( NodeInfo* nodeInfo = GetNodeInfo( _notification ) )
			{
				// One of the node's association groups has changed
				// TBD...
				nodeInfo = nodeInfo;
				eventmap["description"]="Node association added";
				eventmap["state"]="associationchanged";
				eventmap["nodeid"] = _notification->GetNodeId();
				eventmap["homeid"] = _notification->GetHomeId();
				agoConnection->emitEvent("zwavecontroller", "event.zwave.associationchanged", eventmap);
			}
			break;
		}

		case Notification::Type_NodeAdded:
		{
			// Add the new node to our list
			NodeInfo* nodeInfo = new NodeInfo();
			nodeInfo->m_homeId = _notification->GetHomeId();
			nodeInfo->m_nodeId = _notification->GetNodeId();
			nodeInfo->m_polled = false;		
			g_nodes.push_back( nodeInfo );

			// todo: announce node
			eventmap["description"]="Node added";
			eventmap["state"]="nodeadded";
			eventmap["nodeid"] = _notification->GetNodeId();
			eventmap["homeid"] = _notification->GetHomeId();
			agoConnection->emitEvent("zwavecontroller", "event.zwave.networkchanged", eventmap);
			break;
		}

		case Notification::Type_NodeRemoved:
		{
			// Remove the node from our list
			uint32 const homeId = _notification->GetHomeId();
			uint8 const nodeId = _notification->GetNodeId();
			eventmap["description"]="Node removed";
			eventmap["state"]="noderemoved";
			eventmap["nodeid"] = _notification->GetNodeId();
			eventmap["homeid"] = _notification->GetHomeId();
			agoConnection->emitEvent("zwavecontroller", "event.zwave.networkchanged", eventmap);
			for( list<NodeInfo*>::iterator it = g_nodes.begin(); it != g_nodes.end(); ++it )
			{
				NodeInfo* nodeInfo = *it;
				if( ( nodeInfo->m_homeId == homeId ) && ( nodeInfo->m_nodeId == nodeId ) )
				{
					g_nodes.erase( it );
					break;
				}
			}
			break;
		}

		case Notification::Type_NodeEvent:
		{
			if( NodeInfo* nodeInfo = GetNodeInfo( _notification ) )
			{
				// We have received an event from the node, caused by a
				// basic_set or hail message.
				ValueID id = _notification->GetValueID();
				string label = Manager::Get()->GetValueLabel(id);
				stringstream level;
				level << (int) _notification->GetByte();
				string eventtype = "event.device.statechanged";
				ZWaveNode *device = devices.findValue(id);
				if (device != NULL) {
					if (debug) printf("Sending %s event from child %s\n",eventtype.c_str(), device->getId().c_str());
					agoConnection->emitEvent(device->getId().c_str(), eventtype.c_str(), level.str().c_str(), "");	
				} else {
					cout << "no agocontrol device found for node event - Label: " << label << " Level: " << level << endl;
				}

			}
			break;
		}
		case Notification::Type_SceneEvent:
		{
			if( NodeInfo* nodeInfo = GetNodeInfo( _notification ) )
			{
				int scene = _notification->GetSceneId();
				ValueID id = _notification->GetValueID();
                                string label = Manager::Get()->GetValueLabel(id);
                                stringstream tempstream;
                                tempstream << (int) _notification->GetNodeId();
                                tempstream << "/1";
                                string nodeinstance = tempstream.str();
				string eventtype = "event.device.statechanged";
				ZWaveNode *device;
				if ((device = devices.findId(nodeinstance)) != NULL) {
					if (debug) printf("Sending %s for scene %d event from child %s\n",
						  eventtype.c_str(), scene, device->getId().c_str());
					agoConnection->emitEvent(device->getId().c_str(), eventtype.c_str(), scene, "");	
				} else {
					cout << "WARNING: no agocontrol device found for scene event" << endl;
					cout << "Node: " << nodeinstance << " Scene: " << scene << endl;
				}

			}
			break;
		}
		case Notification::Type_PollingDisabled:
		{
			if( NodeInfo* nodeInfo = GetNodeInfo( _notification ) )
			{
				nodeInfo->m_polled = false;
			}
			break;
		}

		case Notification::Type_PollingEnabled:
		{
			if( NodeInfo* nodeInfo = GetNodeInfo( _notification ) )
			{
				nodeInfo->m_polled = true;
			}
			break;
		}

		case Notification::Type_DriverReady:
		{
			g_homeId = _notification->GetHomeId();
			break;
		}


		case Notification::Type_DriverFailed:
		{
			g_initFailed = true;
			pthread_cond_broadcast(&initCond);
			break;
		}

		case Notification::Type_AwakeNodesQueried:
		case Notification::Type_AllNodesQueried:
		case Notification::Type_AllNodesQueriedSomeDead:
		{
			pthread_cond_broadcast(&initCond);
			break;
		}
		case Notification::Type_DriverReset:
		case Notification::Type_Notification:
		case Notification::Type_NodeNaming:
		case Notification::Type_NodeProtocolInfo:
		case Notification::Type_NodeQueriesComplete:
		case Notification::Type_EssentialNodeQueriesComplete:
		{
			break;
		}
		default:
		{
			cout << "WARNING: Unhandled OpenZWave Event: " << _notification->GetType() << endl;
		}
	}

	pthread_mutex_unlock( &g_criticalSection );
}
Beispiel #14
0
	void clear(){
		cnt_list.clear();
	}
Beispiel #15
0
 void push_point(m2::PointD const & pt)
 {
   /// @todo Filter for equal points.
   m_points.back().push_back(this->convert_point(pt));
 }
Beispiel #16
0
void 
Shape::addPoints(list<vec3> p)
{
	list<vec3>::iterator i;
	for (i = p.begin(); i != p.end(); i++) { points.push_back(*i); }
}
Beispiel #17
0
bool ZBrain::EscapeFromStuckIn(list<rvector>& wayPointList)
{
	// 길찾기 코드의 허점이 드러나는 맵 지점들이 있다.. 그런 곳에서는 몹이 이동하지를 못한다
	// 그런곳을 탈출하기 위해 땜빵을 한다. true 리턴하면 웨이포인트를 여기서 지정했다는 의미.
	DWORD currTime = timeGetTime();
	// 오랜시간 같은 곳에 멈춰있다면 아예 워프해버린다
	if (currTime - m_dwExPositionTimeForWarp > 2000)
	{
		rvector diff = m_exPositionForWarp - m_pBody->GetPosition();

		ResetStuckInStateForWarp();

		if (MagnitudeSq(diff) < 100)
		{
			OutputDebugString("NPC NEED WARP....\n");
			RNavigationMesh* pNavMesh = ZGetGame()->GetWorld()->GetBsp()->GetNavigationMesh();
			if (pNavMesh) {
				// 근방의 랜덤지점을 정한다

				// 랜덤 방향 얻기
				float angle = (rand() % (314*2)) * 0.01f;
				D3DXMATRIX matRot;
				D3DXMatrixRotationZ(&matRot, angle);

				rvector dir(200, 0, 0);	// 이동할 거리
				dir = dir * matRot;
				rvector newpos = m_pBody->GetPosition() + dir;

				// 가장 가까운 네비게이션노드의 센터로 옮긴다 (네비게이션노드가 크게 잡혀 있는 맵에선 워프가 심하게 눈에 띌수 있음..)
				RNavigationNode* pNavNode = pNavMesh->FindClosestNode(newpos);
				if (pNavNode) {
					m_pBody->SetPosition( pNavNode->CenterVertex());
					OutputDebugString("NPC WARP DONE!\n");
					return false;
				}
			}
		}
	}

	// 짧은시간 같은 곳에 멈춰있다면 앞으로 한발짝 정도 움직여서 탈출시도
	if (currTime - m_dwExPositionTime > 1000)
	{
		rvector diff = m_exPosition - m_pBody->GetPosition();

		ResetStuckInState();

		if (MagnitudeSq(diff) < 100)
		{
			wayPointList.clear();

			// 기본적으로 앞쪽으로 방향을 잡되 좌우로 랜덤하게 방향을 준다
			rvector dir = m_pBody->GetDirection();
			rmatrix matRot;
			D3DXMatrixRotationZ(&matRot, (rand()%314 - 157) * 0.01f);	// 3.14 즉 반바퀴 범위 내에서 방향을 틀게 함
			Normalize(dir);

			dir *= m_pBody->GetCollRadius() * 0.8f;
			wayPointList.push_back(m_pBody->GetPosition() + dir);

			PushWayPointsToTask();

			return true;
		}
	}

	return false;
}
Beispiel #18
0
void CMessageModel::getMsgByMsgId(uint32_t nUserId, uint32_t nPeerId, const list<uint32_t> &lsMsgId, list<IM::BaseDefine::MsgInfo> &lsMsg)
{
    if(lsMsgId.empty())

    {
        return ;
    }
    uint32_t nRelateId = CRelationModel::getInstance()->getRelationId(nUserId, nPeerId, false);

    if(nRelateId == INVALID_VALUE)
    {
        log("invalid relation id between %u and %u", nUserId, nPeerId);
        return;
    }

    CDBManager* pDBManager = CDBManager::getInstance();
    CDBConn* pDBConn = pDBManager->GetDBConn("teamtalk_slave");
    if (pDBConn)
    {
        string strTableName = "IMMessage_" + int2string(nRelateId % 8);
        string strClause ;
        bool bFirst = true;
        for(auto it= lsMsgId.begin(); it!=lsMsgId.end();++it)
        {
            if (bFirst) {
                bFirst = false;
                strClause = int2string(*it);
            }
            else
            {
                strClause += ("," + int2string(*it));
            }
        }

        string strSql = "select * from " + strTableName + " where relateId=" + int2string(nRelateId) + "  and status=0 and msgId in (" + strClause + ") order by created desc, id desc limit 100";
        CResultSet* pResultSet = pDBConn->ExecuteQuery(strSql.c_str());
        if (pResultSet)
        {
            while (pResultSet->Next())
            {
                IM::BaseDefine::MsgInfo msg;
                msg.set_msg_id(pResultSet->GetInt("msgId"));
                msg.set_from_session_id(pResultSet->GetInt("fromId"));
                msg.set_create_time(pResultSet->GetInt("created"));
                IM::BaseDefine::MsgType nMsgType = IM::BaseDefine::MsgType(pResultSet->GetInt("type"));
                if(IM::BaseDefine::MsgType_IsValid(nMsgType))
                {
                    msg.set_msg_type(nMsgType);
                    msg.set_msg_data(pResultSet->GetString("content"));
                    lsMsg.push_back(msg);
                }
                else
                {
                    log("invalid msgType. userId=%u, peerId=%u, msgType=%u, msgId=%u", nUserId, nPeerId, nMsgType, msg.msg_id());
                }
            }
            delete pResultSet;
        }
        else
        {
            log("no result set for sql:%s", strSql.c_str());
        }
        pDBManager->RelDBConn(pDBConn);
        if(!lsMsg.empty())
        {
            CAudioModel::getInstance()->readAudios(lsMsg);
        }
    }
    else
    {
        log("no db connection for teamtalk_slave");
    }
}
Double TEncRCPic::estimatePicLambda( list<TEncRCPic*>& listPreviousPictures, SliceType eSliceType)
{
  Double alpha         = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha;
  Double beta          = m_encRCSeq->getPicPara( m_frameLevel ).m_beta;
  Double bpp       = (Double)m_targetBits/(Double)m_numberOfPixel;
  Double estLambda;
  if (eSliceType == I_SLICE)
  {
    estLambda = calculateLambdaIntra(alpha, beta, pow(m_totalCostIntra/(Double)m_numberOfPixel, BETA1), bpp);
  }
  else
  {
    estLambda = alpha * pow( bpp, beta );
  }

  Double lastLevelLambda = -1.0;
  Double lastPicLambda   = -1.0;
  Double lastValidLambda = -1.0;
  list<TEncRCPic*>::iterator it;
  for ( it = listPreviousPictures.begin(); it != listPreviousPictures.end(); it++ )
  {
    if ( (*it)->getFrameLevel() == m_frameLevel )
    {
      lastLevelLambda = (*it)->getPicActualLambda();
    }
    lastPicLambda     = (*it)->getPicActualLambda();

    if ( lastPicLambda > 0.0 )
    {
      lastValidLambda = lastPicLambda;
    }
  }

  if ( lastLevelLambda > 0.0 )
  {
    lastLevelLambda = Clip3( 0.1, 10000.0, lastLevelLambda );
    estLambda = Clip3( lastLevelLambda * pow( 2.0, -3.0/3.0 ), lastLevelLambda * pow( 2.0, 3.0/3.0 ), estLambda );
  }

  if ( lastPicLambda > 0.0 )
  {
    lastPicLambda = Clip3( 0.1, 2000.0, lastPicLambda );
    estLambda = Clip3( lastPicLambda * pow( 2.0, -10.0/3.0 ), lastPicLambda * pow( 2.0, 10.0/3.0 ), estLambda );
  }
  else if ( lastValidLambda > 0.0 )
  {
    lastValidLambda = Clip3( 0.1, 2000.0, lastValidLambda );
    estLambda = Clip3( lastValidLambda * pow(2.0, -10.0/3.0), lastValidLambda * pow(2.0, 10.0/3.0), estLambda );
  }
  else
  {
    estLambda = Clip3( 0.1, 10000.0, estLambda );
  }

  if ( estLambda < 0.1 )
  {
    estLambda = 0.1;
  }

  m_estPicLambda = estLambda;

  Double totalWeight = 0.0;
  // initial BU bit allocation weight
  for ( Int i=0; i<m_numberOfLCU; i++ )
  {
    Double alphaLCU, betaLCU;
    if ( m_encRCSeq->getUseLCUSeparateModel() )
    {
      alphaLCU = m_encRCSeq->getLCUPara( m_frameLevel, i ).m_alpha;
      betaLCU  = m_encRCSeq->getLCUPara( m_frameLevel, i ).m_beta;
    }
    else
    {
      alphaLCU = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha;
      betaLCU  = m_encRCSeq->getPicPara( m_frameLevel ).m_beta;
    }

    m_LCUs[i].m_bitWeight =  m_LCUs[i].m_numberOfPixel * pow( estLambda/alphaLCU, 1.0/betaLCU );

    if ( m_LCUs[i].m_bitWeight < 0.01 )
    {
      m_LCUs[i].m_bitWeight = 0.01;
    }
    totalWeight += m_LCUs[i].m_bitWeight;
  }
  for ( Int i=0; i<m_numberOfLCU; i++ )
  {
    Double BUTargetBits = m_targetBits * m_LCUs[i].m_bitWeight / totalWeight;
    m_LCUs[i].m_bitWeight = BUTargetBits;
  }

  return estLambda;
}
Beispiel #20
0
void CMessageModel::getMessageDuringTime(uint32_t nUserId, uint32_t nPeerId, uint32_t nStartTime,
                               uint32_t nEndTime, uint32_t nOffset, uint32_t nCount, 
                               list<IM::BaseDefine::MsgInfo>& lsMsg)
{
    uint32_t nRelateId = CRelationModel::getInstance()->getRelationId(nUserId, nPeerId, false);
	if (nRelateId != INVALID_VALUE)
    {
        CDBManager* pDBManager = CDBManager::getInstance();
        CDBConn* pDBConn = pDBManager->GetDBConn("teamtalk_slave");
        if (pDBConn)
        {
            string strTableName = "IMMessage_" + int2string(nRelateId % 8);
            string strSql;
            if (nCount == 0)
            {
                strSql = "select * from " + strTableName + " force index (idx_relateId_status_created) where relateId= " + int2string(nRelateId) + " and status = 0 and created >= " + int2string(nStartTime) + " and created <= " + int2string(nEndTime) + " order by created desc";
            }
            else
            {
                strSql = "select * from " + strTableName + " force index (idx_relateId_status_created) where relateId= " + int2string(nRelateId) + " and status = 0 and created >= " + int2string(nStartTime) + " and created <= " + int2string(nEndTime) + " order by created desc limit " + int2string(nOffset) + "," + int2string(nCount);
            }
            CResultSet* pResultSet = pDBConn->ExecuteQuery(strSql.c_str());
            if (pResultSet)
            {
                while (pResultSet->Next())
                {
                    IM::BaseDefine::MsgInfo cMsg;
                    cMsg.set_msg_id(pResultSet->GetInt("msgId"));
                    cMsg.set_from_session_id(pResultSet->GetInt("fromId"));
                    cMsg.set_create_time(pResultSet->GetInt("created"));
                    IM::BaseDefine::MsgType nMsgType = IM::BaseDefine::MsgType(pResultSet->GetInt("type"));
                    if(IM::BaseDefine::MsgType_IsValid(nMsgType))
                    {
                        cMsg.set_msg_type(nMsgType);
                        cMsg.set_msg_data(pResultSet->GetString("content"));
                        lsMsg.push_back(cMsg);
                    }
                    else
                    {
                        log("invalid msgType. userId=%u, peerId=%u, startTime=%u, endTime=%u, offset=%u, size=%u, msgType=%u, msgId=%u", nUserId, nPeerId, nStartTime, nEndTime, nOffset, nCount, nMsgType, pResultSet->GetInt("msgId"));
                    }
                }
                delete pResultSet;
            }
            else
            {
                log("no result set: %s", strSql.c_str());
            }
            pDBManager->RelDBConn(pDBConn);
            if (!lsMsg.empty())
            {
                CAudioModel::getInstance()->readAudios(lsMsg);
            }
        }
        else
        {
            log("no db connection for teamtalk_slave");
        }
	}
    else
    {
        log("no relation between %lu and %lu", nUserId, nPeerId);
    }
}
Beispiel #21
0
	/** returns RESULT_xxx after applying that result to our totals, and logging timing information */
	int run(const string& description, const memory<unsigned char>& v) {
		//printf("START: %p\nEND: %p\n", v.begin(), v.end());

		int we_accept = 0, other_accept = 0, we_reject = 0, other_reject = 0;

		// if debug output is coming, print header
		bool headerPrinted = (verbosity >= 3);
		if(headerPrinted)
			printf("\n\n###\n%s\n", description.c_str());

		// run everything and accumulate results
		vector<bool> results;
		for(Validator* p : validators) {
			vector<double> timings(repeatCount);

			bool r; // result
			for(int i = 0; i < repeatCount; ++i) {
				p->prepare(v.size());
				ticks t0 = getticks();
				bool thisResult = p->validate(v);
				ticks t1 = getticks();

				timings[i] = elapsed(t1, t0);

				// safety - bomb out if we get different results from different runs
				if(i == 0) {
					results.push_back(thisResult);
					r = thisResult;
				} else if(r != thisResult) {
					printf("ERROR: inconsistent results from runs by same validator against same data\n");
					exit(1);
				}
			}

			timingResults.push_back(TimingResult(p, description, v.size(), timings));

			if(r) {
				if(p->ours())
					we_accept++;
				else
					other_accept++;
			} else {
				if(p->ours())
					we_reject++;
				else
					other_reject++;
			}
		}

		// what's the overall result? apply to total.
		int result;

		if(we_accept + other_accept == 0) {
			result = RESULT_GOOD;
			goodReject++;
		} else if(we_reject + other_reject == 0) {
			result = RESULT_GOOD;
			goodAccept++;
		} else if(other_accept != 0 && other_reject != 0) {
			result = RESULT_CONFUSION;
		} else {
			result = RESULT_FAILURE;
		}

		totals[result]++;


		// print if necessary (due to error and/or verbosity level)
		if(verbosity >= 2 || result != RESULT_GOOD) {
			if(!headerPrinted)
				printf("%s -- ", description.c_str());

			vector<bool>::const_iterator resultp = results.begin();
			for(const Validator* p : validators) {
				printf("%s %s", p->name().c_str(), *resultp ? "accept, " : "reject, ");
				++resultp;
			}

			switch(result) {
				case RESULT_GOOD: printf("good.\n"); break;
				case RESULT_CONFUSION: printf("CONFUSION!\n"); break;
				case RESULT_FAILURE: printf("FAILURE!\n"); break;
			}
		}

		return result;
	}
Beispiel #22
0
void increaseSalary(list<Employee*> elist,float n)
{
    for (list<Employee*>::iterator it = elist.begin(); it != elist.end(); it++)
        (*it)->increaseSalary(n);
}
Beispiel #23
0
bool judgementb(string a,list<string> b){
	list<string>::iterator i;
	for(i=b.begin();i!=b.end();++i){
		if(a==*i){return 1;break;}}
	return 0;}
Beispiel #24
0
void printDetails(list<Employee*> elist)
{
    for (list<Employee*>::iterator it = elist.begin(); it != elist.end(); it++)
        (*it)->printDetails();
}
Beispiel #25
0
/* Removes a single conn entry */
conn_data::~conn_data(  )
{
   connlist.remove( this );
}
 int getArraySize(void) const {return stars.size();}
Beispiel #27
0
// creates edge and triangle structures and links them to existing vertex/tetrahedron structure, to permit storing attributes
void createAggregateDataStructure(){
	int i, j;

	// traverse all tetrahedra and create their triangles, edges and references to them
	stack<Cell> tetraStack;
	tetraStack.push(dt->infinite_cell());

	// while stack not empty
	while (tetraStack.size() > 0){
		// pop tetra from stack
		Cell ch = tetraStack.top();
		tetraStack.pop();
		Tetrahedron *currTetra = &ch->info();

		// DEBUG
		//		cout << "tetra " << COUT_CELL(ch) << endl;

		bool triangleCreated[4];
		Edge *edge[6];

		for (i = 0; i < 6; i++)
			edge[i] = NULL;

		// reference its four triangles (create if not yet existing)
		for (i = 0; i < 4; i++)	{
			triangleCreated[i] = false;

			// look up at neighbor tetrahedron
			Cell oppCH = ch->neighbor(i);
			int oppIndex = oppCH->index(ch);
			Tetrahedron *oppTetra = &oppCH->info();

			// test if triangle exists already
			Triangle *triangle = oppTetra->triangle(oppIndex);

			if (triangle == NULL){
				triangleCreated[i] = true;

				// create new triangle

				//int vIndex[3];

				//for (j = 0; j < 3; j++)
				//				//	vIndex[j] = (i + 1 + j) % 4;
				//	vIndex[j] = tetraTriVertexIndices[i][j];

				Triangle newTriangle(ch, i);
				dtTriangles.push_back(newTriangle);
				triangle = &dtTriangles.back();

				// also push tetrahedron on stack as unhandled
				tetraStack.push(oppCH);

				// DEBUG
				//				cout << "triangle " << *triangle << " created" << endl;
			}

			currTetra->setTriangle(i, triangle);	// reference triangle
			oppTetra->setTriangle(oppIndex, triangle);		// also in opposite tetrahedron
		}

		// reference its six edges (create if not yet existing)
		for (i = 0; i < 6; i++){
			int edgeVIndex[2];

			for (j = 0; j < 2; j++)
				edgeVIndex[j] = ch->vertex(tetraEdgeVertexIndices[i][j])->info().index();

			sort(edgeVIndex, edgeVIndex + 2);

			IntPair intPair(edgeVIndex[0], edgeVIndex[1]);
			map<IntPair, Edge>::iterator mapIter = dtEdgeMap.find(intPair);

			if (mapIter != dtEdgeMap.end())
				edge[i] = &mapIter->second;
			else
			{
				Edge newEdge(ch, tetraEdgeVertexIndices[i][0], tetraEdgeVertexIndices[i][1]);
				dtEdgeMap.insert(pair<IntPair, Edge>(intPair, newEdge));
				map<IntPair, Edge>::iterator mapIter = dtEdgeMap.find(intPair);
				edge[i] = &mapIter->second;
			}
		}

		// only set edges into newly created triangles
		for (i = 0; i < 4; i++)
			if (triangleCreated[i])
				for (j = 0; j < 3; j++)
					currTetra->triangle(i)->setEdge(j, edge[tetraTriEdgeIndices[i][j]]);
	}
	// DEBUG
	cout << "aggregate data structure: " << dtEdgeMap.size() << " edges, " << dtTriangles.size() << " triangles" << endl;
}
Beispiel #28
0
 bool IsExist() const
 {
   return !m_points.empty();
 }
Beispiel #29
0
void Renderer::addEntities(const list<StaticEntity*>& entities) {

	this->entities.insert(this->entities.end(), entities.begin(), entities.end());

}
Beispiel #30
0
	MenuUtils& addPair(string idx,string value){
		cnt_list.push_back(pair<string,string>(idx,value));

		return *this;
	}