Пример #1
0
uint16_t Topics::getTopicId(MQString* topic){
    Topic *p = getTopic(topic);
    if ( p != NULL) {
        return p->getTopicId();
    }
    return 0;
}
Пример #2
0
/*=====================================
        Class Topics
 ======================================*/
Topics::Topics(){
	Topic* tp = new Topic(string(MQTTSN_TOPIC_PREDEFINED_TIME));
	tp->setTopicId(MQTTSN_TOPICID_PREDEFINED_TIME);
	_topics.push_back(tp);
	_cnt = 1;
	_nextTopicId = MQTTSN_TOPICID_NORMAL;
}
Пример #3
0
int Topics::execCallback(uint16_t topicId, MqttsPublish* msg){
    Topic* p = getTopic(topicId);
    if ( p != NULL) {
        return p->execCallback(msg);
    }
    return 0;
}
Пример #4
0
int Topics::execCallback(MQString* topic, MqttsnPublish* msg) {
    Topic* p = getTopic(topic);
    if ( p != 0) {
        return p->execCallback(msg);
    }
    return 0;
}
Пример #5
0
bool Topics::setCallback(uint16_t topicId, TopicCallback callback){
    Topic* p = getTopic(topicId);
    if ( p != NULL) {
        p->setCallback(callback);
        return true;
    }else{
        return false;
    }
}
Пример #6
0
bool Topics::setCallback(MQString* topic, TopicCallback callback){
    Topic* p = getTopic(topic);
    if ( p != NULL) {
        p->setCallback(callback);
        return true;
    }else{
        return false;
    }
}
Пример #7
0
bool Topics::setTopicId(MQString* topic, uint16_t id){
    Topic* p = getTopic(topic);
    if ( p != NULL) {
        p->setTopicId(id);
        return true;
    }else{
        return false;
    }
}
Пример #8
0
String WIFI::get(Topic &topic) {
  if (topic.itemIs(3, "macAddress")) {
    return macAddress();
  } else if (topic.itemIs(3, "scanResult")){
    return scanResult();
  } else {
    return TOPIC_NO;
  }
}
Пример #9
0
String WIFI::set(Topic &topic) {

  if (topic.itemIs(3, "scan")) {
    return scanWifi();
  } else {
    return TOPIC_NO;
  }
}
Пример #10
0
String customDevice::get(Topic &topic) {
  /*
  ~/get
  └─device             (level 2)
    └─sensor1          (level 3)
  */

  logging.debug("device get topic " + topic.topic_asString());

  if (topic.getItemCount() != 4) // ~/get/device/sensor1
    return TOPIC_NO;
  if (topic.itemIs(3, "sensor1")) {
    return String(measure());
  } else {
    return TOPIC_NO;
  }
}
Пример #11
0
String customDevice::set(Topic &topic) {
  /*
  ~/set
  └─device             (level 2)
    └─yourItem         (level 3)
  */

  logging.debug("device set topic " + topic.topic_asString() + " to " +
                topic.arg_asString());

  if (topic.getItemCount() != 4) // ~/set/device/yourItem
    return TOPIC_NO;
  if (topic.itemIs(3, "yourItem")) {
    return TOPIC_OK;
  } else {
    return TOPIC_NO;
  }
}
Пример #12
0
void TXTWriter::renderSectionStart(ostream& out, const string& id)
{
	const string& sectTopicID = m_data->getElementProperty(id, "topic");
	const string& sectDesc = m_data->getElementProperty(id, "desc");

	if ( m_printDetailed )
		out << "/section id=" << id << "/ ";
	out << endl << endl << section_beg() << m_data->getElementProperty(id, "type")	;
	if (sectDesc != "")
		out << " - " << sectDesc;

	if (sectTopicID != "")
	{
		Topic* topic =  Topics::getTopicFromAll(sectTopicID, m_data->conventions().getTopics());
		out << " {" << topic->getLabel() << "} ";
	}

	out << section_end() << endl;
}
Пример #13
0
void IsPolitics::GetEveryWordInOneTopicByWordProperty(Topic &onetopic) {
  this->topic_word_size=0;
  this->keyword_map.clear();
//  std::cout<<"mapsize: "<<this->keyword_map.size()<<std::endl;
  std::vector<WeiboWord>::iterator or_it;
  std::list<Weibo>::iterator t_w_it;
  t_w_it = onetopic.GetTopicWeibo()->begin();
  for(;t_w_it != onetopic.GetTopicWeibo()->end();++t_w_it){
    std::vector<WeiboWord> resultword;
    this->SplitWeiboSplit(t_w_it->spilt,resultword);

    or_it = resultword.begin();
    for (; or_it != resultword.end(); ++or_it) {
      onetopic.allweibowordnum++;
      this-> topic_word_size++;
      this->AddKeyToMapWithProperty(*or_it);
    }
  }

}
Пример #14
0
  void run() {
	  uint32_t cnt=0;

	  wf121.init("YETENet","yeteyete");
	  wf121.enableUDPConnection(0xFF01A8C0,12345);

	  while(true) {
		  cnt++;
		  topicCounter1.publish(cnt);
		  AT(NOW() + 100*MILLISECONDS);
	  }
  }
Пример #15
0
/*@input
 * 		Topic:话题
 * 		TopicWord:特征词
 * 计算簇与特征词之间的距离
 */
double Cluster::Cal_Words_Topic_Distance(Topic &topic, TopicWord &topic_word) {
    double topic_word_dis = 0.0;
    std::string keyword = topic_word.GetTopicWord();
    std::map<std::string, double>* map_map;
    std::map<string, CooccurrenceWord>::iterator co_it = co_ccur_matrix.find(keyword);
    if (co_it != co_ccur_matrix.end()) {
        map_map = co_it->second.GetWordCooccurrence();
    } else {
        return 0.0;
    }
    list<TopicWord>::iterator clu_it = topic.GetsTopic()->begin();//这里一定要指针??为什么?
    std::string one_topic_word;
    std::map<std::string, double>::iterator second_it;
    for (; clu_it != topic.GetsTopic()->end(); ++clu_it) {
        one_topic_word = clu_it->GetTopicWord();
        second_it = map_map->find(one_topic_word);
        if (second_it != map_map->end()) {
            topic_word_dis += second_it->second;

        }
    }
    return topic_word_dis / topic.GetsTopic()->size();
}
Пример #16
0
void Tag::insert(Topic& topic) {
  /*
    find the given topic_id with the given last_post_time
    if it exists, remove it
    insert the given topic.
  */
  TopicList::iterator search_iter = _topic_list.find_topic(topic);

  if (search_iter != _topic_list.end() && (*search_iter).time() != topic.time()) {
    _topic_list.erase(search_iter);
    _topic_list.insert(topic);
  } else {
    _topic_list.insert(topic);
  }
}
Пример #17
0
String customDevice::set(Topic &topic) {
  /*
  ~/set
  └─device             (level 2)
    └─deviceCFG        (level 3)
    └─index            (level 4) individual setting
    └─value            (level 4) individual setting
    └─scanBus          (level 4) scan 1W-Bus for new devices
*/


  logging.debug("device set topic " + topic.topic_asString() + " to " +
                topic.arg_asString());
  String ret = TOPIC_NO;

  if (topic.itemIs(3, "deviceCFG")) {
    //modify dashboard-------------------
    if (topic.itemIs(4, "addItem")) {
      modifyDashboard();
      return TOPIC_OK;
    }
  }
  return ret;
}
Пример #18
0
void Cluster::ListEveryTopicWeiboId(Topic &one_topic) {
    list<TopicWord>::iterator topic_it = one_topic.GetsTopic()->begin();
    std::map<std::string, double> *topic_weibo_id_map =one_topic.GetTopicWeiboId();
    std::map<std::string, double>::iterator topic_weibo_id_map_it;
    one_topic.topic_message_num = 0;


    for (; topic_it != one_topic.GetsTopic()->end(); ++topic_it) {
        std::set<std::string>::iterator topicword_weibolist_it =
            topic_it->GetWordToWeiboidList()->begin();
        for (; topicword_weibolist_it
                != topic_it->GetWordToWeiboidList()->end(); ++topicword_weibolist_it) {
            std::string weiboid = *topicword_weibolist_it;
            topic_weibo_id_map_it = topic_weibo_id_map->find(weiboid);
            if (topic_weibo_id_map_it != topic_weibo_id_map->end()) {
                topic_weibo_id_map_it->second = topic_weibo_id_map_it->second + 1;
            } else {
                topic_weibo_id_map->insert(make_pair(weiboid, 1.0));
            }
        }
    }



    topic_weibo_id_map_it = topic_weibo_id_map->begin();

    for (; topic_weibo_id_map_it != topic_weibo_id_map->end(); ++topic_weibo_id_map_it) {
        if (topic_weibo_id_map_it->second >= this->BELONG_TOPIC_THROD) {
            subword sw(topic_weibo_id_map_it->first,topic_weibo_id_map_it->second);

            one_topic.GetWeiboIdList()->push_back(sw);
            one_topic.topic_message_num += 1;
        }
    }

    one_topic.GetTopicWeiboId()->clear();
    std::sort(one_topic.GetWeiboIdList()->begin(),
              one_topic.GetWeiboIdList()->end(), weibosort);

    //及时清除内存
    if(one_topic.topic_message_num<=this->MIN_TOPIC_MESSAGE_NUM) {
        one_topic.weibo_id_list.clear();
        std::vector<subword>(one_topic.weibo_id_list).swap(one_topic.weibo_id_list);
    }
    //将得出的结果存进数据库
}
Пример #19
0
uint16_t Topics::createTopic(string* topic){
    if (!getTopic(topic)){
        if ( _cnt < MAX_TOPIC_COUNT){
        	Topic* tp = new Topic();
        	tp->setTopicName(*topic);
        	if(tp->getTopicLength() == 2){
        		uint16_t id = getUint16((uint8_t*)tp->getTopicName());
        		tp->setTopicId(id);
        	}else{
        		tp->setTopicId(getNextTopicId());
        	}
        	_topics.push_back(tp);
        	_cnt++;
        	return _nextTopicId;
        }else{
        	return 0;
        }
    }else{
    	return getTopicId(topic);
    }
}
Пример #20
0
bool MyEventHandler::processEvent(const Event& event, ProviderSession* session)
{
    if (event.eventType() == Event::SESSION_STATUS) {
        printMessages(event);
        MessageIterator iter(event);
        while (iter.next()) {
            Message msg = iter.message();
            if (msg.messageType() == SESSION_TERMINATED) {
                g_running = false;
            }
        }
    }
    else if (event.eventType() == Event::TOPIC_STATUS) {
        TopicList topicList;
        MessageIterator iter(event);
        while (iter.next()) {
            Message msg = iter.message();
            std::cout << msg << std::endl;
            if (msg.messageType() == TOPIC_SUBSCRIBED) {
                std::string topicStr = msg.getElementAsString("topic");
                MutexGuard guard(&g_mutex);
                MyStreams::iterator it = g_streams.find(topicStr);
                if (it == g_streams.end()) {
                    // TopicList knows how to add an entry based on a
                    // TOPIC_SUBSCRIBED message.
                    topicList.add(msg);
                    it = (g_streams.insert(MyStreams::value_type(
                                     topicStr,
                                     new MyStream(topicStr)))).first;
                }
                it->second->setSubscribedState(true);
                if (it->second->isAvailable()) {
                    ++g_availableTopicCount;
                }
            }
            else if (msg.messageType() == TOPIC_UNSUBSCRIBED) {
                std::string topicStr = msg.getElementAsString("topic");
                MutexGuard guard(&g_mutex);
                MyStreams::iterator it = g_streams.find(topicStr);
                if (it == g_streams.end()) {
                    // we should never be coming here. TOPIC_UNSUBSCRIBED can
                    // not come before a TOPIC_SUBSCRIBED or TOPIC_CREATED
                    continue;
                }
                if (it->second->isAvailable()) {
                    --g_availableTopicCount;
                }
                it->second->setSubscribedState(false);
            }
            else if (msg.messageType() == TOPIC_CREATED) {
                std::string topicStr = msg.getElementAsString("topic");
                MutexGuard guard(&g_mutex);
                MyStreams::iterator it = g_streams.find(topicStr);
                if (it == g_streams.end()) {
                    it = (g_streams.insert(MyStreams::value_type(
                                     topicStr,
                                     new MyStream(topicStr)))).first;
                }
                try {
                    Topic topic = session->getTopic(msg);
                    it->second->setTopic(topic);
                } catch (blpapi::Exception &e) {
                    std::cerr
                        << "Exception in Session::getTopic(): "
                        << e.description()
                        << std::endl;
                    continue;
                }
                if (it->second->isAvailable()) {
                    ++g_availableTopicCount;
                }
            }
            else if (msg.messageType() == TOPIC_RECAP) {
                // Here we send a recap in response to a Recap request.
                try {
                    std::string topicStr = msg.getElementAsString("topic");
                    MyStreams::iterator it = g_streams.find(topicStr);
                    MutexGuard guard(&g_mutex);
                    if (it == g_streams.end() || !it->second->isAvailable()) {
                        continue;
                    }
                    Topic topic = session->getTopic(msg);
                    Service service = topic.service();
                    CorrelationId recapCid = msg.correlationId();

                    Event recapEvent = service.createPublishEvent();
                    EventFormatter eventFormatter(recapEvent);
                    eventFormatter.appendRecapMessage(topic, &recapCid);
                    eventFormatter.setElement("numRows", 25);
                    eventFormatter.setElement("numCols", 80);
                    eventFormatter.pushElement("rowUpdate");
                    for (int i = 1; i < 6; ++i) {
                        eventFormatter.appendElement();
                        eventFormatter.setElement("rowNum", i);
                        eventFormatter.pushElement("spanUpdate");
                        eventFormatter.appendElement();
                        eventFormatter.setElement("startCol", 1);
                        eventFormatter.setElement("length", 10);
                        eventFormatter.setElement("text", "RECAP");
                        eventFormatter.popElement();
                        eventFormatter.popElement();
                        eventFormatter.popElement();
                    }
                    eventFormatter.popElement();
                    guard.release()->unlock();
                    session->publish(recapEvent);
                } catch (blpapi::Exception &e) {
                    std::cerr
                        << "Exception in Session::getTopic(): "
                        << e.description()
                        << std::endl;
                    continue;
                }
            }
        }
        if (topicList.size()) {
            // createTopicsAsync will result in RESOLUTION_STATUS,
            // TOPIC_CREATED events.
            session->createTopicsAsync(topicList);
        }
    }
    else if (event.eventType() == Event::RESOLUTION_STATUS) {
        printMessages(event);
    }
    else if (event.eventType() == Event::REQUEST) {
        Service service = session->getService(d_serviceName.c_str());
        MessageIterator iter(event);
        while (iter.next()) {
            Message msg = iter.message();
            msg.print(std::cout);
            if (msg.messageType() == PERMISSION_REQUEST) {
                // This example always sends a 'PERMISSIONED' response.
                // See 'MktdataPublisherExample' on how to parse a Permission
                // request and send an appropriate 'PermissionResponse'.
                Event response = service.createResponseEvent(
                                                          msg.correlationId());
                int permission = 0; // ALLOWED: 0, DENIED: 1
                EventFormatter ef(response);
                ef.appendResponse("PermissionResponse");
                ef.pushElement("topicPermissions");
                // For each of the topics in the request, add an entry
                // to the response
                Element topicsElement = msg.getElement(TOPICS);
                for (size_t i = 0; i < topicsElement.numValues(); ++i) {
                    ef.appendElement();
                    ef.setElement("topic", topicsElement.getValueAsString(i));
                    ef.setElement("result", permission); //PERMISSIONED
                    ef.popElement();
                }
                ef.popElement();
                session->sendResponse(response);
            }
        }
    }
    else {
        MessageIterator iter(event);
        while (iter.next()) {
            Message msg = iter.message();
            MutexGuard guard(&g_lock);
            if (g_authorizationStatus.find(msg.correlationId()) !=
                    g_authorizationStatus.end()) {
                if (msg.messageType() == AUTHORIZATION_SUCCESS) {
                    g_authorizationStatus[msg.correlationId()] = AUTHORIZED;
                }
                else {
                    g_authorizationStatus[msg.correlationId()] = FAILED;
                }
            }
            msg.print(std::cout);
        }
    }

    return true;
}
Пример #21
0
/*-------------------------------------------------------
                Upstream MQTTSnSubscribe
 -------------------------------------------------------*/
void GatewayControlTask::handleSnSubscribe(Event* ev, ClientNode* clnode, MQTTSnMessage* msg){
	printf(FORMAT2, currentDateTime(), "SUBSCRIBE", LEFTARROW, clnode->getNodeId()->c_str(), msgPrint(msg));

	MQTTSnSubscribe* sSubscribe = new MQTTSnSubscribe();
	MQTTSubscribe* subscribe = new MQTTSubscribe();
	sSubscribe->absorb(msg);

	uint8_t topicIdType = sSubscribe->getFlags() & 0x03;

	subscribe->setMessageId(sSubscribe->getMsgId());

	if(sSubscribe->getFlags() & MQTTSN_FLAG_DUP ){
		subscribe->setDup();
	}
	if(sSubscribe->getFlags() & MQTTSN_FLAG_RETAIN){
		subscribe->setRetain();
	}
	subscribe->setQos(sSubscribe->getQos());

	if(topicIdType != MQTTSN_FLAG_TOPICID_TYPE_RESV){
		if(topicIdType == MQTTSN_FLAG_TOPICID_TYPE_PREDEFINED){
			/*----- Predefined TopicId ------*/
			MQTTSnSubAck* sSuback = new MQTTSnSubAck();

			if(sSubscribe->getMsgId()){       // MessageID
				sSuback->setQos(sSubscribe->getQos());
				sSuback->setTopicId(sSubscribe->getTopicId());
				sSuback->setMsgId(sSubscribe->getMsgId());

				if(sSubscribe->getTopicId() == MQTTSN_TOPICID_PREDEFINED_TIME){
					sSuback->setReturnCode(MQTT_RC_ACCEPTED);
				}else{
					sSuback->setReturnCode(MQTT_RC_REFUSED_IDENTIFIER_REJECTED);
				}

				clnode->setClientSendMessage(sSuback);

				Event* evsuback = new Event();
				evsuback->setClientSendEvent(clnode);
				printf(FORMAT1, currentDateTime(), "SUBACK", RIGHTARROW, clnode->getNodeId()->c_str(), msgPrint(sSuback));

				_res->getClientSendQue()->post(evsuback);
			}

			if(sSubscribe->getTopicId() == MQTTSN_TOPICID_PREDEFINED_TIME){

				MQTTSnPublish* pub = new MQTTSnPublish();
				pub->setTopicIdType(1);  // pre-defined
				pub->setTopicId(MQTTSN_TOPICID_PREDEFINED_TIME);
				pub->setMsgId(clnode->getNextSnMsgId());

				uint8_t buf[4];
				uint32_t tm = time(0);
				setUint32(buf,tm);

				pub->setData(buf, 4);
				printf(GREEN_FORMAT1, currentDateTime(), "PUBLISH", RIGHTARROW, clnode->getNodeId()->c_str(), msgPrint(pub));

				clnode->setClientSendMessage(pub);

				Event *evpub = new Event();
				evpub->setClientSendEvent(clnode);
				_res->getClientSendQue()->post(evpub);
			}
			delete subscribe;
		}else{
			uint16_t tpId;

			Topic* tp = clnode->getTopics()->getTopic(sSubscribe->getTopicName());
			if (tp){
				tpId = tp->getTopicId();
			}else{
				tpId = clnode->getTopics()->createTopic(sSubscribe->getTopicName());
			}

			subscribe->setTopic(sSubscribe->getTopicName(), sSubscribe->getQos());
			if(sSubscribe->getMsgId()){
				MQTTSnSubAck* sSuback = new MQTTSnSubAck();
				sSuback->setMsgId(sSubscribe->getMsgId());
				sSuback->setTopicId(tpId);
				clnode->setWaitedSubAck(sSuback);
			}

			clnode->setBrokerSendMessage(subscribe);
			Event* ev1 = new Event();
			ev1->setBrokerSendEvent(clnode);
			_res->getBrokerSendQue()->post(ev1);
			delete sSubscribe;
			return;
		}

	}else{
		/*-- Irregular TopicIdType --*/
		if(sSubscribe->getMsgId()){
			MQTTSnSubAck* sSuback = new MQTTSnSubAck();
			sSuback->setMsgId(sSubscribe->getMsgId());
			sSuback->setTopicId(sSubscribe->getTopicId());
			sSuback->setReturnCode(MQTT_RC_REFUSED_IDENTIFIER_REJECTED);

			clnode->setClientSendMessage(sSuback);

			Event* evun = new Event();
			evun->setClientSendEvent(clnode);
			printf(FORMAT1, currentDateTime(), "SUBACK", RIGHTARROW, clnode->getNodeId()->c_str(), msgPrint(sSuback));

			_res->getClientSendQue()->post(evun);  // Send SUBACK to Client
		}
		delete subscribe;
	}
	delete sSubscribe;
}
Пример #22
0
/*-------------------------------------------------------
 *               Upstream MQTTSnPublish
 -------------------------------------------------------*/
void GatewayControlTask::handleSnPublish(Event* ev, ClientNode* clnode, MQTTSnMessage* msg){

	printf(BLUE_FORMAT2, currentDateTime(), "PUBLISH", LEFTARROW, clnode->getNodeId()->c_str(), msgPrint(msg));

	MQTTSnPublish* sPublish = new MQTTSnPublish();
	MQTTPublish* mqMsg = new MQTTPublish();
	sPublish->absorb(msg);

	Topic* tp = clnode->getTopics()->getTopic(sPublish->getTopicId());

	if(tp || ((sPublish->getFlags() && MQTTSN_TOPIC_TYPE) == MQTTSN_TOPIC_TYPE_SHORT)){
		if(tp){
			mqMsg->setTopic(tp->getTopicName());
		}else{
			string str;
			mqMsg->setTopic(sPublish->getTopic(&str));
		}
		if(sPublish->getMsgId()){
			MQTTSnPubAck* sPuback = new MQTTSnPubAck();
			sPuback->setMsgId(sPublish->getMsgId());
			sPuback->setTopicId(sPublish->getTopicId());
			if(clnode->getWaitedPubAck()){
				delete clnode->getWaitedPubAck();
			}
			clnode->setWaitedPubAck(sPuback);

			mqMsg->setMessageId(sPublish->getMsgId());
		}

		mqMsg->setQos(sPublish->getQos());

		if(sPublish->getFlags() && MQTTSN_FLAG_DUP){
			mqMsg->setDup();
		}
		if(sPublish->getFlags() && MQTTSN_FLAG_RETAIN){
			mqMsg->setRetain();
		}

		mqMsg->setPayload(sPublish->getData() , sPublish->getDataLength());

		clnode->setBrokerSendMessage(mqMsg);
		Event* ev1 = new Event();
		ev1->setBrokerSendEvent(clnode);
		_res->getBrokerSendQue()->post(ev1);

	}else{
		if(sPublish->getMsgId()){
			MQTTSnPubAck* sPuback = new MQTTSnPubAck();
			sPuback->setMsgId(sPublish->getMsgId());
			sPuback->setTopicId(sPublish->getTopicId());
			sPuback->setReturnCode(MQTTSN_RC_REJECTED_INVALID_TOPIC_ID);

			clnode->setClientSendMessage(sPuback);

			Event* ev1 = new Event();
			ev1->setClientSendEvent(clnode);
			printf(BLUE_FORMAT1, currentDateTime(), "PUBACK", RIGHTARROW, clnode->getNodeId()->c_str(), msgPrint(sPuback));

			_res->getClientSendQue()->post(ev1);  // Send PubAck INVALID_TOPIC_ID
		}
	}
	delete sPublish;
}
Пример #23
0
//--------------------------------------------------------------
void ofApp::setup(){

    ofSetWindowShape(800, 1000);
    ofPoint chartPos = ofPoint(ofGetWidth() * 0.1, ofGetHeight() * 0.1);
    ofPoint chartSize = ofPoint(ofGetWidth() * 0.8, ofGetHeight() * 0.8);
    drawLabels = true;
    chartType = 0;
    
    // 0: Load tsv file
    ofBuffer file = ofBufferFromFile("pomodoro.tsv");
    
    // 1: Get all possible dates
    vector<string> allDates;
    string prevDate = "";
    while (!file.isLastLine()){
        string line = file.getNextLine();
        vector <string> split = ofSplitString(line, "\t");
        string thisDate = split[0];
        
        if(thisDate != prevDate){
            allDates.push_back(thisDate);
        }
        prevDate = thisDate;
    }
    
    // 2: Create topics with names and pass all possible dates
    file.resetLineReader();
    while (!file.isLastLine()){
        string line = file.getNextLine();
        vector <string> split = ofSplitString(line, "\t");
        string thisName = split[1];
        
        bool nameIsStored = false;
        
        for (int i = 0; i < allTopics.size(); i++) {
            
            if(allTopics[i].name == thisName){
                
                nameIsStored = true;
            }
        }
        
        if(!nameIsStored){
            Topic thisTopic;
            thisTopic.setup(thisName, allDates);
            allTopics.push_back(thisTopic);
        }
    }

    // 3: Fill out hours
    file.resetLineReader();
    while (!file.isLastLine()){
        string line = file.getNextLine();
        vector <string> split = ofSplitString(line, "\t");
        string thisName = split[1];
        string thisDate = split[0];
        float theseHours = split[5].size() * 0.5;

        for (int i = 0; i < allTopics.size(); i++) {

            if(allTopics[i].name == thisName){

                for (int j = 0; j < allTopics[i].dates.size(); j++){

                    if (allTopics[i].dates[j] == thisDate) {

                        allTopics[i].hours[j] += theseHours;
                    }
                }
            }
        }
    }
    
    // 4: Calculate the total hours for each topic
    for (int i = 0; i < allTopics.size(); i++) {
        allTopics[i].calculateHours();
    }

    // 5: Sort by total hours
    sort(allTopics.begin(), allTopics.end(), sortByCount);
    
    // 6: Before setting the vertices, we need to know
    // what is the highest value of hours for one day
    vector<float> allHours;
    for (int i = 0; i < allTopics[0].hours.size(); i++) {
        float sumOfHours = 0.0;
        for (int j = 0; j < allTopics.size(); j++) {
//            cout << allTopics[j].hours[i] << endl;
            sumOfHours += allTopics[j].hours[i];
        }
//        cout << "****************************" << endl;
//        cout << sumOfHours << endl;
//        cout << "****************************" << endl;
        allHours.push_back(sumOfHours);
    }
    float maxHoursPerDay = 0.0;
    for (int i = 0; i < allHours.size(); i++) {
//        cout << allHours[i] << endl;
        if (allHours[i] > maxHoursPerDay) {
            maxHoursPerDay = allHours[i];
        }
    }
    cout << maxHoursPerDay << endl;
    
    // 7: Set bars (and area vertices)
    for (int i = 0; i < allTopics.size(); i++) {
        allTopics[i].setBars(i, allTopics, chartPos, chartSize, maxHoursPerDay);
    }
    
    // 7: Set polar coordinates
    float innerRadius = ofGetWidth() * 0.05;
    float outerRadius = ofGetWidth() * 0.45;
    for (int i = 0; i < allTopics.size(); i++) {
        allTopics[i].setPolar(i, allTopics, innerRadius, outerRadius, maxHoursPerDay);
    }
    
    // 8: Set colors
    for (int i = 0; i < allTopics.size(); i++) {
        allTopics[i].setColor(i, allTopics.size());
    }
}
Пример #24
0
void Camera::DetectSatellite() {
	int horizontalLine[WIDTH];
	int verticalLine[HEIGHT];

	// Init Arrays
	for (int x = 0; x < WIDTH; x++) {
		horizontalLine[x] = 0;
	}
	for (int y = 0; y < HEIGHT; y++) {
		verticalLine[y] = 0;
	}

	int pixel = 0;
	// Sum up Picture to Lines
	for (int y = 0; y < HEIGHT; y++) {
		for (int x = 0; x < WIDTH; x++) {
			if ((int) DCMI_Buffer[2 * x + 2 * y * WIDTH] > THRESHOLD) {
				horizontalLine[x] += (int) DCMI_Buffer[2 * x + 2 * WIDTH * y];
				verticalLine[y] += (int) DCMI_Buffer[2 * x + 2 * WIDTH * y];
				pixel++;
			}
		}
	}

	if(pixel<MINPIXELTHRESHOLD) { //Cancel if object is too small
		target.x=0;
		target.y=0;
		return;
	}

    // Find the position in the arrays where the sumed up values
	// are Q1, HALF and Q3 of the overall sum. HALF is exactly
	// the center of gravity of the picture, the span between
	// Q1 and Q3 is a good indicatior for the angle of the obj.
    int counter = 0;
    int sum1 = 0;
    int sum2 = 0;
    for(int x = 0; x < WIDTH; x++) {
        sum1 += horizontalLine[x];
    }
    int first_quarter = 0;
    int third_quarter = 0;
    int targetX = 0;
    int spanX = 0;
    while(sum2<Q3*sum1) {
        sum2 += horizontalLine[counter];
        counter++;
        if((Q1*sum1<sum2)&&(first_quarter==0)){
            first_quarter = counter;
        }
        if((HALF*sum1<sum2)&&(targetX==0)) {
            targetX = counter;
        }
        if((Q3*sum1<sum2)&&(third_quarter==0)) {
            third_quarter = counter;
        }
    }
    spanX = third_quarter - first_quarter;

    counter = 0;
    sum1 = 0;
    sum2 = 0;
    for(int y = 0; y < HEIGHT; y++) {
        sum1 += verticalLine[y];
    }
    first_quarter = 0;
    third_quarter = 0;
    int targetY = 0;
    int spanY = 0;
    while(sum2<Q3*sum1) {
        sum2 += verticalLine[counter];
        counter++;
        if((Q1*sum1<sum2)&&(first_quarter==0)){
            first_quarter = counter;
        }
        if((HALF*sum1<sum2)&&(targetY==0)) {
            targetY = counter;
        }
        if((Q3*sum1<sum2)&&(third_quarter==0)) {
            third_quarter = counter;
        }
    }
    spanY = third_quarter - first_quarter;
    // ----------------------------------

    bool fireAngle = spanX>2*spanY;
	target.y = targetX;
	target.x = targetY;
	cameraTargetTopic.publish(target);
	cameraFireTopic.publish(fireAngle);
	xprintf("Target: x:%d, y:%d\n", target.x, target.y);
	xprintf("Fire: %d\n", fireAngle);
	// ---------------------------------
}
Пример #25
0
int main(int argc, char *argv[]) {
  try {
    BaseTestCase::startTest(argv);
    // create Admin and connect
    XoramAdmin* admin = new XoramAdmin();
    admin->connect("root", "root", 60);

    // create destination
    Queue* queue = admin->createQueue("queue");
    printf("queue->getUID() = %s, queue->getName() = %s\n",queue->getUID(), queue->getName());
    Topic* topic = admin->createTopic("topic");
    printf("topic->getUID() = %s, topic->getName() = %s\n",topic->getUID(), topic->getName());

    // set right
    admin->setFreeReading(queue);
    admin->setFreeWriting(queue);
    admin->setFreeReading(topic);
    admin->setFreeWriting(topic);

    // create "anonymous" user
    admin->createUser("anonymous", "anonymous");

    ConnectionFactory* cf = new TCPConnectionFactory("localhost", 16010);
    Connection* cnx = cf->createConnection("anonymous", "anonymous");
    cnx->start();
    Session* sess = cnx->createSession();
    MessageProducer* prod1 = sess->createProducer(queue);
    MessageProducer* prod2 = sess->createProducer(topic);
    MessageConsumer* cons1 = sess->createConsumer(queue);
    MessageConsumer* cons2 = sess->createConsumer(topic);

    Message* msg1 = sess->createMessage();
    prod1->send(msg1);
    printf("##### Message sent on queue: %s\n", msg1->getMessageID());

    Message* msg2 = sess->createMessage();
    prod2->send(msg2);
    printf("##### Message sent on topic: %s\n", msg2->getMessageID());
    
    Message* msg = cons1->receive();
    printf("##### Message received from queue: %s\n", msg->getMessageID());

    msg = cons2->receive();
    printf("##### Message received from tpoic: %s\n", msg->getMessageID());
    
    // delete User
    CreateUserReply* userReply = admin->createUser("removeUser", "removeUser");
    admin->deleteUser("removeUser",userReply->getProxId());

    // delete Queue and Topic
    printf("delete Queue %s\n", queue->getUID());
    admin->deleteDestination(queue->getUID());
    printf("delete Topic %s\n", topic->getUID());
    admin->deleteDestination(topic->getUID());

    admin->disconnect();

    cnx->close();

} catch (Exception exc) {
    printf("##### exception - %s", exc.getMessage());
    BaseTestCase::error(&exc);
  } catch (...) {
    printf("##### exception\n");
    BaseTestCase::error(new Exception(" catch ..., unknown exception "));
  }
  printf("##### bye\n");
  BaseTestCase::endTest();
}
Пример #26
0
String Controller::call(Topic &topic) {

  // MQTT state information via API-call
  if (topic.modifyTopic(0) == "event/mqtt/connected") {
    if (topic.argIs(0, "1")) {
      on_mqtt_connected();
    } else {
      on_mqtt_disconnected();
    }
  }

  // D("Controller: begin call");
  // set
  if (topic.itemIs(1, "set")) {
    if (topic.itemIs(2, "ffs")) {
      return ffs.set(topic);
    } else if (topic.itemIs(2, "clock")) {
      return clock.set(topic);
    } else if (topic.itemIs(2, "esp")) {
      return espTools.set(topic);
    } else if (topic.itemIs(2, "wifi")) {
      return wifi.set(topic);
    } else if (topic.itemIs(2, "device")) {
      if (topic.itemIs(3, "fillDashboard")) {
        return device.fillDashboard();
      } else {
        return device.set(topic);
      }
    } else if (topic.itemIs(2, "controller")) {
      if (topic.itemIs(3, "reconnectDelay")) {
        D("set reconnectDelay");
        Di("arg=", topic.getArgAsLong(0));
        reconnectDelay = topic.getArgAsLong(0);
        if (reconnectDelay < 1)
          reconnectDelay = 1;
        if (reconnectDelay > RECONNECT_DELAY_MAX)
          reconnectDelay = RECONNECT_DELAY_MAX;
        reconnectDelayed = 0;
        return TOPIC_OK;
      } else {
        return TOPIC_NO;
      }
    } else {
      return TOPIC_NO;
    }
    // get
  } else if (topic.itemIs(1, "get")) {
    if (topic.itemIs(2, "ffs")) {
      return ffs.get(topic);
    } else if (topic.itemIs(2, "clock")) {
      return clock.get(topic);
    } else if (topic.itemIs(2, "esp")) {
      return espTools.get(topic);
    } else if (topic.itemIs(2, "wifi")) {
      return wifi.get(topic);
    } else if (topic.itemIs(2, "device")) {
      if(topic.itemIs(3, "flags")) {
        return fwConfig();
      } else if(topic.itemIs(3, "version")) {
        return device.getVersion();
      } else if (topic.itemIs(3, "type")) {
        return device.getType();
      } else if (topic.itemIs(3, "dashboard")) {
        return device.getDashboard();
      } else {
        return device.get(topic);
      }
    } else {
      return TOPIC_NO;
    }
  } else {
    return TOPIC_NO;
  }
  // D("Controller: end call");
}
Пример #27
0
/*
 * @description:
 *  一趟聚类的思想
 */
void Cluster::Singlepass() {
#ifdef TIME
    time_t start3;
    start3 = time(NULL);
#endif


    this->SetClusterThrod(this->GenClusterThrod() + THROD_ADD);
    std::cout << "CLUSTER_THROD: " << this->CLSTER_THROD << std::endl;

#ifdef DEBUG_CLUSTER1
    printMatrix(this->co_ccur_matrix);
#endif

    MAP::iterator topic_w_it = this->topicword->begin();
    TopicWord firstword = topic_w_it->second;
    //这里初始化一个词作为一个簇(topic)
    Topic topic;
    topic.TopicInit(firstword);
    this->clusterList.push_back(topic);

    //对于每一个词,计算词在话题列表Topic的距离
    topic_w_it++;
    std::cout<<"聚类前特征词的个数"<<this->topicword->size()<<std::endl;
    for (; topic_w_it != this->topicword->end(); ++topic_w_it) {

        vector<Topic>::iterator vec_clu_it = this->clusterList.begin();
        double maxDistance = MINVALUE;
        vector<Topic>::iterator belong_clus_it = vec_clu_it;//这里应该是赋值还是指针????
        for (; vec_clu_it != this->clusterList.end(); ++vec_clu_it) {
            double words_distance = Cal_Words_Topic_Distance(*vec_clu_it,topic_w_it->second);
            //查看是否有比之前保留的最近的簇更近的簇
            if (maxDistance < words_distance) {
                maxDistance = words_distance;
                belong_clus_it = vec_clu_it;
            }
        }
        //如果该词与该簇距离最近,那么将该词加入该簇
        if (maxDistance < this->CLSTER_THROD) {
            Topic newTopic;
            newTopic.TopicInit(topic_w_it->second);
            this->clusterList.push_back(newTopic);
        } else {
            belong_clus_it->addTopicWord(topic_w_it->second);
        }
    }


#ifdef TIME
    time_t ends4;
    ends4 = time(NULL);
    std::cout << "一趟聚类用时:" << difftime(ends4, start3) << std::endl;
#endif

#ifdef TIME
    time_t start5;
    start5 = time(NULL);
#endif
    //及时将共现矩阵清空
//	this->co_ccur_matrix.clear();
    //match weibo id to topic
    this->MatchWeiboIDToTopic();
    //select the weibo which have more than two words in topic
    this->ListAllTopicWeiboId();

#ifdef TIME
    time_t ends5;
    ends5 = time(NULL);
    std::cout << "微博对应话题用时:" << difftime(ends5, start5) << std::endl;
#endif


    this->SortTopic();
//	this->InsterAllTopicToDatabase();


#ifdef PRINTTOPICA
    printTopic(&this->clusterList);
#endif
}