Beispiel #1
0
TEST_F(TConfigParserTest, Parse)
{
    TConfigTemplateParser device_parser(GetDataFilePath("../wb-mqtt-serial-templates/"), false);
    TConfigParser parser(GetDataFilePath("../config.json"), false,
                         TSerialDeviceFactory::GetRegisterTypes, device_parser.Parse());
    PHandlerConfig config = parser.Parse();
    Emit() << "Debug: " << config->Debug;
    Emit() << "Ports:";
    for (auto port_config: config->PortConfigs) {
        TTestLogIndent indent(*this);
        ASSERT_EQ(config->Debug, port_config->Debug);
        Emit() << "------";
        Emit() << "ConnSettings: " << port_config->ConnSettings;
        Emit() << "PollInterval: " << port_config->PollInterval.count();
        if (port_config->DeviceConfigs.empty()) {
            Emit() << "No device configs.";
            continue;
        }
        Emit() << "DeviceConfigs:";
        for (auto device_config: port_config->DeviceConfigs) {
            TTestLogIndent indent(*this);
            Emit() << "------";
            Emit() << "Id: " << device_config->Id;
            Emit() << "Name: " << device_config->Name;
            Emit() << "SlaveId: " << device_config->SlaveId;
            if (!device_config->DeviceChannels.empty()) {
                Emit() << "DeviceChannels:";
                for (auto modbus_channel: device_config->DeviceChannels) {
                    TTestLogIndent indent(*this);
                    Emit() << "------";
                    Emit() << "Name: " << modbus_channel->Name;
                    Emit() << "Type: " << modbus_channel->Type;
                    Emit() << "DeviceId: " << modbus_channel->DeviceId;
                    Emit() << "Order: " << modbus_channel->Order;
                    Emit() << "OnValue: " << modbus_channel->OnValue;
                    Emit() << "Max: " << modbus_channel->Max;
                    Emit() << "ReadOnly: " << modbus_channel->ReadOnly;
                    std::stringstream s;
                    bool first = true;
                    for (auto reg: modbus_channel->Registers) {
                        if (first)
                            first = false;
                        else
                            s << ", ";
                        s << reg;
                        if (reg->PollInterval.count())
                            s << " (poll_interval=" << reg->PollInterval.count() << ")";
                    }
                    Emit() << "Registers: " << s.str();
                }

                if (device_config->SetupItems.empty())
                    continue;

                Emit() << "SetupItems:";
                for (auto setup_item: device_config->SetupItems) {
                    TTestLogIndent indent(*this);
                    Emit() << "------";
                    Emit() << "Name: " << setup_item->Name;
                    Emit() << "Address: " << setup_item->Reg->Address;
                    Emit() << "Value: " << setup_item->Value;
                }
            }
        }
    }

}
Beispiel #2
0
void SenMLPack::fromCbor(Stream* source, SenMLStreamMethod format)
{
    SenMLCborParser parser(this, format);
    parser.parse(source);
}
Beispiel #3
0
void
TextDocumentTest::ReadyToRun()
{
	BRect frame(50.0, 50.0, 749.0, 549.0);

	BWindow* window = new BWindow(frame, "Text document test",
		B_TITLED_WINDOW, B_QUIT_ON_WINDOW_CLOSE | B_AUTO_UPDATE_SIZE_LIMITS);

	TextDocumentView* documentView = new TextDocumentView("text document view");

	BLayoutBuilder::Group<>(window, B_VERTICAL)
		.Add(documentView)
	;

	CharacterStyle regularStyle;

	float fontSize = regularStyle.Font().Size();

	ParagraphStyle paragraphStyle;
	paragraphStyle.SetJustify(true);
	paragraphStyle.SetSpacingTop(ceilf(fontSize * 0.6f));
	paragraphStyle.SetLineSpacing(ceilf(fontSize * 0.2f));

//	CharacterStyle boldStyle(regularStyle);
//	boldStyle.SetBold(true);
//
//	CharacterStyle italicStyle(regularStyle);
//	italicStyle.SetItalic(true);
//
//	CharacterStyle italicAndBoldStyle(boldStyle);
//	italicAndBoldStyle.SetItalic(true);
//
//	CharacterStyle bigStyle(regularStyle);
//	bigStyle.SetFontSize(24);
//	bigStyle.SetForegroundColor(255, 50, 50);
//
//	TextDocumentRef document(new TextDocument(), true);
//
//	Paragraph paragraph(paragraphStyle);
//	paragraph.Append(TextSpan("This is a", regularStyle));
//	paragraph.Append(TextSpan(" test ", bigStyle));
//	paragraph.Append(TextSpan("to see if ", regularStyle));
//	paragraph.Append(TextSpan("different", boldStyle));
//	paragraph.Append(TextSpan(" character styles already work.", regularStyle));
//	document->Append(paragraph);
//
//	paragraphStyle.SetSpacingTop(8.0f);
//	paragraphStyle.SetAlignment(ALIGN_CENTER);
//	paragraphStyle.SetJustify(false);
//
//	paragraph = Paragraph(paragraphStyle);
//	paragraph.Append(TextSpan("Different alignment styles ", regularStyle));
//	paragraph.Append(TextSpan("are", boldStyle));
//	paragraph.Append(TextSpan(" supported as of now!", regularStyle));
//	document->Append(paragraph);
//
//	// Test a bullet list
//	paragraphStyle.SetSpacingTop(8.0f);
//	paragraphStyle.SetAlignment(ALIGN_LEFT);
//	paragraphStyle.SetJustify(true);
//	paragraphStyle.SetBullet(Bullet("•", 12.0f));
//	paragraphStyle.SetLineInset(10.0f);
//
//	paragraph = Paragraph(paragraphStyle);
//	paragraph.Append(TextSpan("Even bullet lists are supported.", regularStyle));
//	document->Append(paragraph);
//
//	paragraph = Paragraph(paragraphStyle);
//	paragraph.Append(TextSpan("The wrapping in ", regularStyle));
//	paragraph.Append(TextSpan("this", italicStyle));
//
//	paragraph.Append(TextSpan(" bullet item should look visually "
//		"pleasing. And ", regularStyle));
//	paragraph.Append(TextSpan("why", italicAndBoldStyle));
//	paragraph.Append(TextSpan(" should it not?", regularStyle));
//	document->Append(paragraph);

	MarkupParser parser(regularStyle, paragraphStyle);

	TextDocumentRef document = parser.CreateDocumentFromMarkup(
		"== Text document test ==\n"
		"This is a test to see if '''different''' "
		"character styles already work.\n"
		"Different alignment styles '''are''' supported as of now!\n"
		" * Even bullet lists are supported.\n"
		" * The wrapping in ''this'' bullet item should look visually "
		"pleasing. And ''why'' should it not?\n"
	);

	documentView->SetTextDocument(document);

	window->Show();
}
Beispiel #4
0
void MatroskaWrapper::GetSubtitles(agi::fs::path const& filename, AssFile *target) {
	MkvStdIO input(filename);
	char err[2048];
	agi::scoped_holder<MatroskaFile*, decltype(&mkv_Close)> file(mkv_Open(&input, err, sizeof(err)), mkv_Close);
	if (!file) throw MatroskaException(err);

	// Get info
	unsigned tracks = mkv_GetNumTracks(file);
	std::vector<unsigned> tracksFound;
	std::vector<std::string> tracksNames;

	// Find tracks
	for (auto track : boost::irange(0u, tracks)) {
		auto trackInfo = mkv_GetTrackInfo(file, track);
		if (trackInfo->Type != 0x11) continue;

		// Known subtitle format
		std::string CodecID(trackInfo->CodecID);
		if (CodecID == "S_TEXT/SSA" || CodecID == "S_TEXT/ASS" || CodecID == "S_TEXT/UTF8") {
			tracksFound.push_back(track);
			tracksNames.emplace_back(str(boost::format("%d (%s %s)") % track % CodecID % trackInfo->Language));
			if (trackInfo->Name) {
				tracksNames.back() += ": ";
				tracksNames.back() += trackInfo->Name;
			}
		}
	}

	// No tracks found
	if (tracksFound.empty())
		throw MatroskaException("File has no recognised subtitle tracks.");

	unsigned trackToRead;
	// Only one track found
	if (tracksFound.size() == 1)
		trackToRead = tracksFound[0];
	// Pick a track
	else {
		int choice = wxGetSingleChoiceIndex(_("Choose which track to read:"), _("Multiple subtitle tracks found"), to_wx(tracksNames));
		if (choice == -1)
			throw agi::UserCancelException("canceled");

		trackToRead = tracksFound[choice];
	}

	// Picked track
	mkv_SetTrackMask(file, ~(1 << trackToRead));
	auto trackInfo = mkv_GetTrackInfo(file, trackToRead);
	std::string CodecID(trackInfo->CodecID);
	bool srt = CodecID == "S_TEXT/UTF8";
	bool ssa = CodecID == "S_TEXT/SSA";

	AssParser parser(target, !ssa);

	// Read private data if it's ASS/SSA
	if (!srt) {
		// Read raw data
		std::string priv((const char *)trackInfo->CodecPrivate, trackInfo->CodecPrivateSize);

		// Load into file
		boost::char_separator<char> sep("\r\n");
		for (auto const& cur : boost::tokenizer<boost::char_separator<char>>(priv, sep))
			parser.AddLine(cur);
	}
	// Load default if it's SRT
	else {
		target->LoadDefault(false);
		parser.AddLine("[Events]");
	}

	// Read timecode scale
	auto segInfo = mkv_GetFileInfo(file);
	longlong timecodeScale = mkv_TruncFloat(trackInfo->TimecodeScale) * segInfo->TimecodeScale;

	// Progress bar
	auto totalTime = double(segInfo->Duration) / timecodeScale;
	DialogProgress progress(nullptr, _("Parsing Matroska"), _("Reading subtitles from Matroska file."));
	progress.Run([&](agi::ProgressSink *ps) { read_subtitles(ps, file, &input, srt, totalTime, &parser); });
}
Beispiel #5
0
void loadDataSheet(XMLNode table_node, std::map<string, int> &map, int (*add_func)(TupleParser&)) {
	vector<XMLNode> rows;
	vector<StringRef> col_names;

	XMLNode row_node = table_node.child("table:table-row");
	while(row_node) {
		rows.emplace_back(row_node);
		row_node = row_node.sibling("table:table-row");
	}

	{
		ASSERT(!rows.empty());
		XMLNode first_row = rows.front();
		XMLNode cell_node = first_row.child("table:table-cell");

		while(cell_node) {
			col_names.push_back(getText(cell_node));
			cell_node = cell_node.sibling("table:table-cell");
		}
	}
	
	std::map<StringRef, int> column_map;
	for(int n = 0; n < (int)col_names.size(); n++)
		if(!col_names[n].isEmpty()) {
			if(column_map.find(col_names[n]) != column_map.end())
				THROW("Duplicate argument: %s", col_names[n]);
			column_map.emplace(col_names[n], n);
		}

	vector<const char*> columns;
	columns.reserve(col_names.size());
	bool errors = false;

	int id_column = 0; {
		auto it = column_map.find("id");
		if(it == column_map.end())
			THROW("Id column must be defined");
		id_column = it->second;
	}

	for(int r = 1; r < (int)rows.size(); r++) {
		XMLNode row = rows[r];

		int cell_idx = 0;
		XMLNode cell = row.child("table:table-cell");
		
		columns.clear();
		while(cell && cell_idx < (int)col_names.size()) {
			const char *value = getText(cell);
		
			const char *repeat_attrib = cell.hasAttrib("table:number-columns-repeated");
			int num_repeat = repeat_attrib? toInt(repeat_attrib) : 1;

			for(int i = 0; i < num_repeat; i++)
				columns.push_back(value);
			cell_idx += num_repeat;
			
			cell = cell.sibling("table:table-cell");
		}

		int num_columns = (int)min(col_names.size(), columns.size());
		bool is_empty = true;
		for(int n = 0; n < num_columns; n++)
			if(columns[n][0]) {
				is_empty = false;
				break;
			}

		if(is_empty)
			continue;

		TupleParser parser(columns.data(), num_columns, column_map);
		try {
			string id = columns[id_column];
			if(id.empty())
				THROW("ID undefined");
			if(map.find(id) != map.end())
				THROW("Duplicated ID: %s", id.c_str());

			int index = add_func(parser);
			map.emplace(std::move(id), index);
		}
		catch(const Exception &ex) {
			errors = true;
			printf("Error while parsing row: %d (id: %s):\n%s\n",
					r, columns[id_column], ex.what());
		}
	}

	if(errors)
		THROW("Errors while parsing sheet: %s\n", table_node.attrib("table:name"));
}
QTSS_Error DoSetup(QTSS_StandardRTSP_Params* inParams)
{
    ReflectorSession* theSession = NULL;
	UInt32 len = sizeof(theSession);
	QTSS_GetValue(inParams->inRTSPSession, sRTSPBroadcastSessionAttr, 0, &theSession, &len);

	if(theSession == NULL)
		return QTSS_RequestFailed;

    Bool16 foundSession = false;
    UInt32 theLen = 0;
    RTPSessionOutput** theOutput = NULL;
    QTSS_Error theErr = QTSS_GetValuePtr(inParams->inClientSession, sOutputAttr, 0, (void**)&theOutput, &theLen);
    if (theLen != sizeof(RTPSessionOutput*))
	{
        if (theErr != QTSS_NoErr)
        {            
            RTPSessionOutput* theNewOutput = NEW RTPSessionOutput(inParams->inClientSession, theSession, sServerPrefs, sStreamCookieAttr );
            theSession->AddOutput(theNewOutput,true);
            (void)QTSS_SetValue(inParams->inClientSession, sOutputAttr, 0, &theNewOutput, sizeof(theNewOutput));
        }
    }

    //unless there is a digit at the end of this path (representing trackID), don't
    //even bother with the request
    char* theDigitStr = NULL;
    (void)QTSS_GetValueAsString(inParams->inRTSPRequest, qtssRTSPReqFileDigit, 0, &theDigitStr);
    QTSSCharArrayDeleter theDigitStrDeleter(theDigitStr);
    if (theDigitStr == NULL)
    {
        return QTSSModuleUtils::SendErrorResponse(inParams->inRTSPRequest, qtssClientBadRequest,sExpectedDigitFilenameErr);
    }
    
    UInt32 theTrackID = ::strtol(theDigitStr, NULL, 10);
   
    // Get info about this trackID
    SourceInfo::StreamInfo* theStreamInfo = theSession->GetSourceInfo()->GetStreamInfoByTrackID(theTrackID);
    // If theStreamInfo is NULL, we don't have a legit track, so return an error
    if (theStreamInfo == NULL)
        return QTSSModuleUtils::SendErrorResponse(inParams->inRTSPRequest, qtssClientBadRequest,
                                                    sReflectorBadTrackIDErr);
                                                    
    StrPtrLen* thePayloadName = &theStreamInfo->fPayloadName;
    QTSS_RTPPayloadType thePayloadType = theStreamInfo->fPayloadType;

    StringParser parser(thePayloadName);
    
    parser.GetThru(NULL, '/');
    theStreamInfo->fTimeScale = parser.ConsumeInteger(NULL);
    if (theStreamInfo->fTimeScale == 0)
        theStreamInfo->fTimeScale = 90000;
    
    QTSS_RTPStreamObject newStream = NULL;
    {
        // Ok, this is completely crazy but I can't think of a better way to do this that's
        // safe so we'll do it this way for now. Because the ReflectorStreams use this session's
        // stream queue, we need to make sure that each ReflectorStream is not reflecting to this
        // session while we call QTSS_AddRTPStream. One brutal way to do this is to grab each
        // ReflectorStream's mutex, which will stop every reflector stream from running.
        
        for (UInt32 x = 0; x < theSession->GetNumStreams(); x++)
            theSession->GetStreamByIndex(x)->GetMutex()->Lock();
            
        theErr = QTSS_AddRTPStream(inParams->inClientSession, inParams->inRTSPRequest, &newStream, 0);

        for (UInt32 y = 0; y < theSession->GetNumStreams(); y++)
            theSession->GetStreamByIndex(y)->GetMutex()->Unlock();
            
        if (theErr != QTSS_NoErr)
            return theErr;
    }
    
    // Set up dictionary items for this stream
    theErr = QTSS_SetValue(newStream, qtssRTPStrPayloadName, 0, thePayloadName->Ptr, thePayloadName->Len);
    Assert(theErr == QTSS_NoErr);
    theErr = QTSS_SetValue(newStream, qtssRTPStrPayloadType, 0, &thePayloadType, sizeof(thePayloadType));
    Assert(theErr == QTSS_NoErr);
    theErr = QTSS_SetValue(newStream, qtssRTPStrTrackID, 0, &theTrackID, sizeof(theTrackID));
    Assert(theErr == QTSS_NoErr);
    theErr = QTSS_SetValue(newStream, qtssRTPStrTimescale, 0, &theStreamInfo->fTimeScale, sizeof(theStreamInfo->fTimeScale));
    Assert(theErr == QTSS_NoErr);

    // We only want to allow over buffering to dynamic rate clients   
    SInt32  canDynamicRate = -1;
    theLen = sizeof(canDynamicRate);
    (void) QTSS_GetValue(inParams->inRTSPRequest, qtssRTSPReqDynamicRateState, 0, (void*) &canDynamicRate, &theLen);
    if (canDynamicRate < 1) // -1 no rate field, 0 off
        (void)QTSS_SetValue(inParams->inClientSession, qtssCliSesOverBufferEnabled, 0, &sFalse, sizeof(sFalse));

    // Place the stream cookie in this stream for future reference
    void* theStreamCookie = theSession->GetStreamCookie(theTrackID);
    Assert(theStreamCookie != NULL);
    theErr = QTSS_SetValue(newStream, sStreamCookieAttr, 0, &theStreamCookie, sizeof(theStreamCookie));
    Assert(theErr == QTSS_NoErr);

    // Set the number of quality levels.
    static UInt32 sNumQualityLevels = ReflectorSession::kNumQualityLevels;
    theErr = QTSS_SetValue(newStream, qtssRTPStrNumQualityLevels, 0, &sNumQualityLevels, sizeof(sNumQualityLevels));
    Assert(theErr == QTSS_NoErr);
    
    //send the setup response
    (void)QTSS_AppendRTSPHeader(inParams->inRTSPRequest, qtssCacheControlHeader,
                                kCacheControlHeader.Ptr, kCacheControlHeader.Len);
    (void)QTSS_SendStandardRTSPResponse(inParams->inRTSPRequest, newStream, qtssSetupRespDontWriteSSRC);
    return QTSS_NoErr;
}
Beispiel #7
0
//**********************************************************************************************************************
AlignCommand::AlignCommand(string option)  {
	try {
		abort = false; calledHelp = false;
		
		//allow user to run help
		if(option == "help") { help(); abort = true; calledHelp = true;}
		else if(option == "citation") { citation(); abort = true; calledHelp = true;}
		
		else {
			vector<string> myArray = setParameters();
			
			OptionParser parser(option);
			map<string, string> parameters = parser.getParameters(); 
			
			ValidParameters validParameter("align.seqs");
			map<string, string>::iterator it;
			
			//check to make sure all parameters are valid for command
			for (it = parameters.begin(); it != parameters.end(); it++) { 
				if (!validParameter.isValidParameter(it->first, myArray, it->second)) {  abort = true;  }
			}
			
			//initialize outputTypes
			vector<string> tempOutNames;
			outputTypes["fasta"] = tempOutNames;
			outputTypes["alignreport"] = tempOutNames;
			outputTypes["accnos"] = tempOutNames;
			
			//if the user changes the output directory command factory will send this info to us in the output parameter 
			outputDir = validParameter.valid(parameters, "outputdir");		if (outputDir == "not found"){	outputDir = "";		}

			//if the user changes the input directory command factory will send this info to us in the output parameter 
			string inputDir = validParameter.valid(parameters, "inputdir");
			
			if (inputDir == "not found"){	inputDir = "";		}
			else {
				string path;

				//user has given a template file
                it = parameters.find("reference");
				if(it != parameters.end()){ 
					path = util.hasPath(it->second);
					//if the user has not given a path then, add inputdir. else leave path alone.
					if (path == "") {	parameters["reference"] = inputDir + it->second;		}
				}
                
                it = parameters.find("fasta");
                if(it != parameters.end()){
                    path = util.hasPath(it->second);
                    //if the user has not given a path then, add inputdir. else leave path alone.
                    if (path == "") {	parameters["fasta"] = inputDir + it->second;		}
                }
			}

            templateFileName = validParameter.validFile(parameters, "reference");
            if (templateFileName == "not found") { m->mothurOut("[ERROR]: The reference parameter is a required for the align.seqs command, aborting.\n"); abort = true;
            }else if (templateFileName == "not open") { abort = true; }
            
            fastafile = validParameter.validFile(parameters, "fasta");
            if (fastafile == "not found") {
                fastafile = current->getFastaFile();
                if (fastafile != "") { m->mothurOut("Using " + fastafile + " as input file for the fasta parameter.\n"); }
                else { 	m->mothurOut("[ERROR]: You have no current fasta file and the fasta parameter is required.\n");  abort = true; }
            }
            else if (fastafile == "not open") { abort = true; }
            else { current->setFastaFile(fastafile); }

		
			//check for optional parameter and set defaults
			// ...at some point should added some additional type checking...
			string temp;
			temp = validParameter.valid(parameters, "ksize");		if (temp == "not found"){	temp = "8";				}
			util.mothurConvert(temp, kmerSize); 
			
			temp = validParameter.valid(parameters, "match");		if (temp == "not found"){	temp = "1.0";			}
			util.mothurConvert(temp, match);  
			
			temp = validParameter.valid(parameters, "mismatch");		if (temp == "not found"){	temp = "-1.0";			}
			util.mothurConvert(temp, misMatch);  
			
			temp = validParameter.valid(parameters, "gapopen");		if (temp == "not found"){	temp = "-5.0";			}
			util.mothurConvert(temp, gapOpen);  
			
			temp = validParameter.valid(parameters, "gapextend");	if (temp == "not found"){	temp = "-2.0";			}
			util.mothurConvert(temp, gapExtend); 
			
			temp = validParameter.valid(parameters, "processors");	if (temp == "not found"){	temp = current->getProcessors();	}
			processors = current->setProcessors(temp);
			
			temp = validParameter.valid(parameters, "flip");			if (temp == "not found"){	temp = "t";				}
			flip = util.isTrue(temp);
			
			temp = validParameter.valid(parameters, "threshold");	if (temp == "not found"){	temp = "0.50";			}
			util.mothurConvert(temp, threshold); 
			
			search = validParameter.valid(parameters, "search");		if (search == "not found"){	search = "kmer";		}
			if ((search != "suffix") && (search != "kmer") && (search != "blast")) { m->mothurOut("invalid search option: choices are kmer, suffix or blast."); m->mothurOutEndLine(); abort=true; }
			
			align = validParameter.valid(parameters, "align");		if (align == "not found"){	align = "needleman";	}
			if ((align != "needleman") && (align != "gotoh") && (align != "blast") && (align != "noalign")) { m->mothurOut("invalid align option: choices are needleman, gotoh, blast or noalign."); m->mothurOutEndLine(); abort=true; }

		}
		
	}
	catch(exception& e) {
		m->errorOut(e, "AlignCommand", "AlignCommand");
		exit(1);
	}
}
Beispiel #8
0
//**********************************************************************************************************************
AlignCommand::AlignCommand(string option)  {
	try {
		abort = false; calledHelp = false;
		
		//allow user to run help
		if(option == "help") { help(); abort = true; calledHelp = true;}
		else if(option == "citation") { citation(); abort = true; calledHelp = true;}
		
		else {
			vector<string> myArray = setParameters();
			
			OptionParser parser(option);
			map<string, string> parameters = parser.getParameters(); 
			
			ValidParameters validParameter("align.seqs");
			map<string, string>::iterator it;
			
			//check to make sure all parameters are valid for command
			for (it = parameters.begin(); it != parameters.end(); it++) { 
				if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
			}
			
			//initialize outputTypes
			vector<string> tempOutNames;
			outputTypes["fasta"] = tempOutNames;
			outputTypes["alignreport"] = tempOutNames;
			outputTypes["accnos"] = tempOutNames;
			
			//if the user changes the output directory command factory will send this info to us in the output parameter 
			outputDir = validParameter.validFile(parameters, "outputdir", false);		if (outputDir == "not found"){	outputDir = "";		}
			

			//if the user changes the input directory command factory will send this info to us in the output parameter 
			string inputDir = validParameter.validFile(parameters, "inputdir", false);		
			
			if (inputDir == "not found"){	inputDir = "";		}
			else {
				string path;

				it = parameters.find("reference");

				//user has given a template file
				if(it != parameters.end()){ 
					path = m->hasPath(it->second);
					//if the user has not given a path then, add inputdir. else leave path alone.
					if (path == "") {	parameters["reference"] = inputDir + it->second;		}
				}
			}

			candidateFileName = validParameter.validFile(parameters, "fasta", false);
			if (candidateFileName == "not found") { 
				//if there is a current fasta file, use it
				string filename = m->getFastaFile(); 
				if (filename != "") { candidateFileNames.push_back(filename); m->mothurOut("Using " + filename + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
				else { 	m->mothurOut("You have no current fastafile and the candidate parameter is required."); m->mothurOutEndLine(); abort = true; }
			}else { 
				m->splitAtDash(candidateFileName, candidateFileNames);
				
				//go through files and make sure they are good, if not, then disregard them
				for (int i = 0; i < candidateFileNames.size(); i++) {
					//candidateFileNames[i] = m->getFullPathName(candidateFileNames[i]);
					
					bool ignore = false;
					if (candidateFileNames[i] == "current") { 
						candidateFileNames[i] = m->getFastaFile(); 
						if (candidateFileNames[i] != "") {  m->mothurOut("Using " + candidateFileNames[i] + " as input file for the fasta parameter where you had given current."); m->mothurOutEndLine(); }
						else { 	
							m->mothurOut("You have no current fastafile, ignoring current."); m->mothurOutEndLine(); ignore=true; 
							//erase from file list
							candidateFileNames.erase(candidateFileNames.begin()+i);
							i--;
						}
					}
					
					if (!ignore) {
					
						if (inputDir != "") {
							string path = m->hasPath(candidateFileNames[i]);
							//if the user has not given a path then, add inputdir. else leave path alone.
							if (path == "") {	candidateFileNames[i] = inputDir + candidateFileNames[i];		}
						}
		
						int ableToOpen;
						ifstream in;
						ableToOpen = m->openInputFile(candidateFileNames[i], in, "noerror");
						in.close();	
						
						//if you can't open it, try default location
						if (ableToOpen == 1) {
							if (m->getDefaultPath() != "") { //default path is set
								string tryPath = m->getDefaultPath() + m->getSimpleName(candidateFileNames[i]);
								m->mothurOut("Unable to open " + candidateFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
								ifstream in2;
								ableToOpen = m->openInputFile(tryPath, in2, "noerror");
								in2.close();
								candidateFileNames[i] = tryPath;
							}
						}
						
						//if you can't open it, try output location
						if (ableToOpen == 1) {
							if (m->getOutputDir() != "") { //default path is set
								string tryPath = m->getOutputDir() + m->getSimpleName(candidateFileNames[i]);
								m->mothurOut("Unable to open " + candidateFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
								ifstream in2;
								ableToOpen = m->openInputFile(tryPath, in2, "noerror");
								in2.close();
								candidateFileNames[i] = tryPath;
							}
						}
						
										

						if (ableToOpen == 1) { 
							m->mothurOut("Unable to open " + candidateFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); 
							//erase from file list
							candidateFileNames.erase(candidateFileNames.begin()+i);
							i--;
						}else {
							m->setFastaFile(candidateFileNames[i]);
						}
					}
				}
				
				//make sure there is at least one valid file left
				if (candidateFileNames.size() == 0) { m->mothurOut("no valid files."); m->mothurOutEndLine(); abort = true; }
			}
		
			//check for optional parameter and set defaults
			// ...at some point should added some additional type checking...
			string temp;
			temp = validParameter.validFile(parameters, "ksize", false);		if (temp == "not found"){	temp = "8";				}
			m->mothurConvert(temp, kmerSize); 
			
			temp = validParameter.validFile(parameters, "match", false);		if (temp == "not found"){	temp = "1.0";			}
			m->mothurConvert(temp, match);  
			
			temp = validParameter.validFile(parameters, "mismatch", false);		if (temp == "not found"){	temp = "-1.0";			}
			m->mothurConvert(temp, misMatch);  
			
			temp = validParameter.validFile(parameters, "gapopen", false);		if (temp == "not found"){	temp = "-5.0";			}
			m->mothurConvert(temp, gapOpen);  
			
			temp = validParameter.validFile(parameters, "gapextend", false);	if (temp == "not found"){	temp = "-2.0";			}
			m->mothurConvert(temp, gapExtend); 
			
			temp = validParameter.validFile(parameters, "processors", false);	if (temp == "not found"){	temp = m->getProcessors();	}
			m->setProcessors(temp);
			m->mothurConvert(temp, processors); 
			
			temp = validParameter.validFile(parameters, "flip", false);			if (temp == "not found"){	temp = "f";				}
			flip = m->isTrue(temp);
			
			//this has to go after save so that if the user sets save=t and provides no reference we abort
			templateFileName = validParameter.validFile(parameters, "reference", true);
			if (templateFileName == "not found") { m->mothurOut("[ERROR]: The reference parameter is a required for the align.seqs command, aborting.\n"); abort = true;
			}else if (templateFileName == "not open") { abort = true; }	
			
			temp = validParameter.validFile(parameters, "threshold", false);	if (temp == "not found"){	temp = "0.50";			}
			m->mothurConvert(temp, threshold); 
			
			search = validParameter.validFile(parameters, "search", false);		if (search == "not found"){	search = "kmer";		}
			if ((search != "suffix") && (search != "kmer") && (search != "blast")) { m->mothurOut("invalid search option: choices are kmer, suffix or blast."); m->mothurOutEndLine(); abort=true; }
			
			align = validParameter.validFile(parameters, "align", false);		if (align == "not found"){	align = "needleman";	}
			if ((align != "needleman") && (align != "gotoh") && (align != "blast") && (align != "noalign")) { m->mothurOut("invalid align option: choices are needleman, gotoh, blast or noalign."); m->mothurOutEndLine(); abort=true; }

		}
		
	}
	catch(exception& e) {
		m->errorOut(e, "AlignCommand", "AlignCommand");
		exit(1);
	}
}
Beispiel #9
0
/* static */ already_AddRefed<Image>
ImageFactory::CreateRasterImage(nsIRequest* aRequest,
                                ProgressTracker* aProgressTracker,
                                const nsCString& aMimeType,
                                ImageURL* aURI,
                                uint32_t aImageFlags,
                                uint32_t aInnerWindowId)
{
  MOZ_ASSERT(aProgressTracker);

  nsresult rv;

  RefPtr<RasterImage> newImage = new RasterImage(aURI);
  aProgressTracker->SetImage(newImage);
  newImage->SetProgressTracker(aProgressTracker);

  nsAutoCString ref;
  aURI->GetRef(ref);
  net::nsMediaFragmentURIParser parser(ref);
  if (parser.HasSampleSize()) {
      /* Get our principal */
      nsCOMPtr<nsIChannel> chan(do_QueryInterface(aRequest));
      nsCOMPtr<nsIPrincipal> principal;
      if (chan) {
        nsContentUtils::GetSecurityManager()
          ->GetChannelResultPrincipal(chan, getter_AddRefs(principal));
      }

      if ((principal &&
           principal->GetAppStatus() == nsIPrincipal::APP_STATUS_CERTIFIED) ||
          gfxPrefs::ImageMozSampleSizeEnabled()) {
        newImage->SetRequestedSampleSize(parser.GetSampleSize());
      }
  }

  rv = newImage->Init(aMimeType.get(), aImageFlags);
  if (NS_FAILED(rv)) {
    return BadImage("RasterImage::Init failed", newImage);
  }

  newImage->SetInnerWindowID(aInnerWindowId);

  uint32_t len = GetContentSize(aRequest);

  // Pass anything usable on so that the RasterImage can preallocate
  // its source buffer.
  if (len > 0) {
    // Bound by something reasonable
    uint32_t sizeHint = std::min<uint32_t>(len, 20000000);
    rv = newImage->SetSourceSizeHint(sizeHint);
    if (NS_FAILED(rv)) {
      // Flush memory, try to get some back, and try again.
      rv = nsMemory::HeapMinimize(true);
      nsresult rv2 = newImage->SetSourceSizeHint(sizeHint);
      // If we've still failed at this point, things are going downhill.
      if (NS_FAILED(rv) || NS_FAILED(rv2)) {
        NS_WARNING("About to hit OOM in imagelib!");
      }
    }
  }

  return newImage.forget();
}
TOKEN_DEF_END
//////////////////////////////////////////////////////////////////////////
HRESULT CAdInventoryBox::LoadBuffer(BYTE* Buffer, bool Complete)
{
	TOKEN_TABLE_START(commands)
		TOKEN_TABLE (INVENTORY_BOX)
		TOKEN_TABLE (TEMPLATE)
		TOKEN_TABLE (WINDOW)
		TOKEN_TABLE (EXCLUSIVE)
		TOKEN_TABLE (ALWAYS_VISIBLE)
		TOKEN_TABLE (AREA)
		TOKEN_TABLE (SPACING)
		TOKEN_TABLE (ITEM_WIDTH)
		TOKEN_TABLE (ITEM_HEIGHT)
		TOKEN_TABLE (SCROLL_BY)
		TOKEN_TABLE (NAME)
		TOKEN_TABLE (CAPTION)
		TOKEN_TABLE (HIDE_SELECTED)
		TOKEN_TABLE (EDITOR_PROPERTY)
	TOKEN_TABLE_END
	
	BYTE* params;
	int cmd=2;
	CBParser parser(Game);
	bool always_visible=false;

	m_Exclusive = false;
	if(Complete)
	{
		if(parser.GetCommand ((char**)&Buffer, commands, (char**)&params)!=TOKEN_INVENTORY_BOX)
		{
			Game->LOG(0, "'INVENTORY_BOX' keyword expected.");
			return E_FAIL;
		}
		Buffer = params;
	}

	while (cmd>0 && (cmd = parser.GetCommand ((char**)&Buffer, commands, (char**)&params)) > 0)
	{
		switch (cmd)
		{
			case TOKEN_TEMPLATE:
				if(FAILED(LoadFile((char*)params))) cmd = PARSERR_GENERIC;
			break;

			case TOKEN_NAME:
				SetName((char*)params);
			break;

			case TOKEN_CAPTION:
				SetCaption((char*)params);
			break;

			case TOKEN_WINDOW:
				SAFE_DELETE(m_Window);
				m_Window = new CUIWindow(Game);				
				if(!m_Window || FAILED(m_Window->LoadBuffer(params, false)))
				{
					SAFE_DELETE(m_Window);
					cmd = PARSERR_GENERIC;
				}
				else Game->RegisterObject(m_Window);
			break;

			case TOKEN_AREA:
				parser.ScanStr((char*)params, "%d,%d,%d,%d", &m_ItemsArea.left, &m_ItemsArea.top, &m_ItemsArea.right, &m_ItemsArea.bottom);
			break;

			case TOKEN_EXCLUSIVE:
				parser.ScanStr((char*)params, "%b", &m_Exclusive);
			break;

			case TOKEN_HIDE_SELECTED:
				parser.ScanStr((char*)params, "%b", &m_HideSelected);
			break;

			case TOKEN_ALWAYS_VISIBLE:
				parser.ScanStr((char*)params, "%b", &always_visible);
			break;

			case TOKEN_SPACING:
				parser.ScanStr((char*)params, "%d", &m_Spacing);
			break;

			case TOKEN_ITEM_WIDTH:
				parser.ScanStr((char*)params, "%d", &m_ItemWidth);
			break;

			case TOKEN_ITEM_HEIGHT:
				parser.ScanStr((char*)params, "%d", &m_ItemHeight);
			break;

			case TOKEN_SCROLL_BY:
				parser.ScanStr((char*)params, "%d", &m_ScrollBy);
			break;

			case TOKEN_EDITOR_PROPERTY:
				ParseEditorProperty(params, false);
			break;
		}
	}
	if (cmd == PARSERR_TOKENNOTFOUND)
	{
		Game->LOG(0, "Syntax error in INVENTORY_BOX definition");
		return E_FAIL;
	}
	if (cmd == PARSERR_GENERIC)
	{
		Game->LOG(0, "Error loading INVENTORY_BOX definition");
		return E_FAIL;
	}

	if(m_Exclusive)
	{
		SAFE_DELETE(m_CloseButton);
		m_CloseButton = new CUIButton(Game);
		if(m_CloseButton)
		{
			m_CloseButton->SetName("close");
			m_CloseButton->SetListener(this, m_CloseButton, 0);
			m_CloseButton->m_Parent = m_Window;
		}
	}

	m_Visible = always_visible;

	if(m_Window)
	{
		for(int i=0; i<m_Window->m_Widgets.GetSize(); i++)
		{
			if(!m_Window->m_Widgets[i]->m_ListenerObject)
				m_Window->m_Widgets[i]->SetListener(this, m_Window->m_Widgets[i], 0);
		}
	}

	return S_OK;
}
Beispiel #11
0
//**********************************************************************************************************************
GetRelAbundCommand::GetRelAbundCommand(string option) {
	try {
		abort = false; calledHelp = false;   
		allLines = 1;
				
		//allow user to run help
		if(option == "help") { help(); abort = true; calledHelp = true; }
		else if(option == "citation") { citation(); abort = true; calledHelp = true;}
		
		else {
			vector<string> myArray = setParameters();
			
			OptionParser parser(option);
			map<string,string> parameters = parser.getParameters();
			map<string,string>::iterator it;
			
			ValidParameters validParameter;
			
			//check to make sure all parameters are valid for command
			for (it = parameters.begin(); it != parameters.end(); it++) { 
				if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
			}
			
			//initialize outputTypes
			vector<string> tempOutNames;
			outputTypes["relabund"] = tempOutNames;
			
			//if the user changes the input directory command factory will send this info to us in the output parameter 
			string inputDir = validParameter.validFile(parameters, "inputdir", false);		
			if (inputDir == "not found"){	inputDir = "";		}
			else {
				string path;
				it = parameters.find("shared");
				//user has given a template file
				if(it != parameters.end()){ 
					path = m->hasPath(it->second);
					//if the user has not given a path then, add inputdir. else leave path alone.
					if (path == "") {	parameters["shared"] = inputDir + it->second;		}
				}
			}
		
			//get shared file
			sharedfile = validParameter.validFile(parameters, "shared", true);
			if (sharedfile == "not open") { sharedfile = ""; abort = true; }	
			else if (sharedfile == "not found") { 
				//if there is a current shared file, use it
				sharedfile = m->getSharedFile(); 
				if (sharedfile != "") { m->mothurOut("Using " + sharedfile + " as input file for the shared parameter."); m->mothurOutEndLine(); }
				else { 	m->mothurOut("You have no current sharedfile and the shared parameter is required."); m->mothurOutEndLine(); abort = true; }
			}else { m->setSharedFile(sharedfile); }
			
			
			//if the user changes the output directory command factory will send this info to us in the output parameter 
			outputDir = validParameter.validFile(parameters, "outputdir", false);		if (outputDir == "not found"){	outputDir = m->hasPath(sharedfile);		}

			//check for optional parameter and set defaults
			// ...at some point should added some additional type checking...
			label = validParameter.validFile(parameters, "label", false);			
			if (label == "not found") { label = ""; }
			else { 
				if(label != "all") {  m->splitAtDash(label, labels);  allLines = 0;  }
				else { allLines = 1;  }
			}
			
			groups = validParameter.validFile(parameters, "groups", false);			
			if (groups == "not found") { groups = ""; pickedGroups = false; }
			else { 
				pickedGroups = true;
				m->splitAtDash(groups, Groups);
				m->setGroups(Groups);
			}
			
			scale = validParameter.validFile(parameters, "scale", false);				if (scale == "not found") { scale = "totalgroup"; }
			
			if ((scale != "totalgroup") && (scale != "totalotu") && (scale != "averagegroup") && (scale != "averageotu")) {
				m->mothurOut(scale + " is not a valid scaling option for the get.relabund command. Choices are totalgroup, totalotu, averagegroup, averageotu."); m->mothurOutEndLine(); abort = true; 
			}
		}

	}
	catch(exception& e) {
		m->errorOut(e, "GetRelAbundCommand", "GetRelAbundCommand");
		exit(1);
	}
}
Beispiel #12
0
bool UserPlugin::onVCard(const VCardWrapper& vcardWrapper)
{
	const gloox::JID jid=vcardWrapper.jid();
	gloox::VCard vcard=gloox::VCard(vcardWrapper.vcard());

	qDebug() << "Got vcard: "+vcardWrapper.id();
	QString jidStr=QString::fromStdString(jid.full());
	QString reqId=QString("vcard_%1").arg(vcardWrapper.id());
	AsyncRequest* req=bot()->asyncRequests()->byStanzaId(reqId);
	if (req==0l)
	{
		return false;
	}
	if (vcardWrapper.isEmpty())
	{
		reply(req->stanza(), "No VCard found");
		bot()->asyncRequests()->removeAll(req);
		return true;
	}

	if (req->name()=="VCARD")
	{
		QString replyStr=vcardWrapper.vcardStr();
		if (replyStr.isEmpty())
		{
			reply(req->stanza(), "Empty VCard");
		}
		else
		{
			reply(req->stanza(), QString("VCard: %1").arg(replyStr));
		}
	}
	else if (req->name()=="PHOTO")
	{
		std::string photoContentStd=vcard.photo().binval;
		QByteArray photoContent=QByteArray(photoContentStd.data(),
				photoContentStd.size());
		//QFile file("/tmp/out.png");
		//file.open(QIODevice::WriteOnly);
		//file.write(photoContentStd.data(), photoContentStd.size());
		//file.close();
		QImage image;
		if (!image.loadFromData(photoContent))
		{
			reply(req->stanza(), "Can't load image");
			bot()->asyncRequests()->removeAll(req);
			return true;
		}

		MessageParser parser(req->stanza(), getMyNick(req->stanza()));
		parser.nextToken();
		QString cmd=parser.nextToken().toUpper();
		QString jid=parser.nextToken();
		QString widthStr=parser.nextToken();
		QString white=parser.nextToken();
		QString black=parser.nextToken();

		Image2Ascii img2ascii(image);

		if (!widthStr.isEmpty())
			img2ascii.setWidth(widthStr.toInt());
		if (!white.isEmpty() && white.length()<=5)
			img2ascii.setWhite(white);
		if (!black.isEmpty() && black.length()<=5)
			img2ascii.setBlack(black);

		QString ascii=img2ascii.ascii();
		if (ascii.isEmpty())
			reply(req->stanza(), "Can't convert image to ASCII");
		else
			reply(req->stanza(), QString("Photo:\n%1").arg(ascii));
	}
	bot()->asyncRequests()->removeAll(req);
	return true;
}
Beispiel #13
0
bool UserPlugin::parseMessage(gloox::Stanza* s, const QStringList& flags)
{
	Q_UNUSED(flags)

	MessageParser parser(s, getMyNick(s));
	parser.nextToken();
	QString cmd=parser.nextToken().toUpper();
	QString arg=parser.nextToken();

	if(cmd=="TIME")
	{
		std::string id=bot()->client()->getID();
		QString jid=resolveTargetJid(s, arg);

		gloox::Stanza *st=gloox::Stanza::createIqStanza(
				gloox::JID(jid.toStdString()), id, gloox::StanzaIqGet,
				"jabber:iq:time");

		qDebug() << QString::fromStdString(st->xml());

		gloox::Stanza *sf=new gloox::Stanza(s);
		sf->addAttribute("id", id);

		AsyncRequest *req=new AsyncRequest(-1, this, sf, 3600);
		req->setName(cmd);
		bot()->asyncRequests()->append(req);
		bot()->client()->send(st);
		return true;
	}
	if (cmd=="VERSION" || cmd=="PING")
	{
		std::string id=bot()->client()->getID();
		QString jid=resolveTargetJid(s, arg);

		gloox::Stanza *st=gloox::Stanza::createIqStanza(
				gloox::JID(jid.toStdString()), id, gloox::StanzaIqGet,
				"jabber:iq:version");

		qDebug() << QString::fromStdString(st->xml());

		gloox::Stanza *sf=new gloox::Stanza(s);
		sf->addAttribute("id", id);

		AsyncRequest *req=new AsyncRequest(-1, this, sf, 3600);
		req->setName(cmd);
		bot()->asyncRequests()->append(req);
		bot()->client()->send(st);
		return true;
	}
	if (cmd=="DISCO")
	{
		std::string id=bot()->client()->getID();
		QString jid=resolveTargetJid(s, arg);

		gloox::Stanza *st=gloox::Stanza::createIqStanza(
				gloox::JID(jid.toStdString()), id, gloox::StanzaIqGet,
				"http://jabber.org/protocol/disco#items");
		gloox::Stanza *sf=new gloox::Stanza(s);
		sf->addAttribute("id", id);
		AsyncRequest *req=new AsyncRequest(-1, this, sf, 3600);
		req->setName(jid);
		bot()->asyncRequests()->append(req);
		bot()->client()->send(st);
		return true;
	}
	if (cmd=="BANLIST" || cmd=="VOICELIST" || cmd=="MEMBERLIST" ||
	    cmd=="MODERATORLIST" || cmd=="ADMINLIST" || cmd=="OWNERLIST")
	{
		std::string id = bot()->client()->getID();
		QString jid = QString::fromStdString(s->from().bare());

		gloox::Stanza *st = gloox::Stanza::createIqStanza(
				gloox::JID(jid.toStdString()), id,
				gloox::StanzaIqGet,
				"http://jabber.org/protocol/muc#admin");
		
		gloox::Tag* q = st->findChild("query", "xmlns",
				      "http://jabber.org/protocol/muc#admin");
		if (q)
		{
			gloox::Tag *i = new gloox::Tag(q, "item");
			std::string affil;
			if (cmd=="MODERATORLIST" || cmd=="MODERLIST")
				i->addAttribute("role", "moderator");
			else if(cmd=="BANLIST" || cmd=="OUTCAST")
				affil = "outcast";
			else if(cmd=="VOICELIST" || cmd=="PARTICIPANTLIST")
				i->addAttribute("role", "participant");
			else if(cmd=="MEMBERLIST")
				affil = "member";
			else if(cmd=="ADMINLIST")
				affil = "admin";
			else if(cmd=="OWNERLIST")
				affil = "owner";
		
			i->addAttribute("affiliation", affil);
      		}
		st->finalize();

		gloox::Stanza *sf = new gloox::Stanza(s);
		sf->addAttribute("id", id);
		AsyncRequest *req = new AsyncRequest(-1, this, sf, 3600);
		req->setName(jid);
		bot()->asyncRequests()->append(req);
		bot()->client()->send(st);
		return true;
	}
	if (cmd=="VCARD" || cmd=="PHOTO")
	{
		QString jid=bot()->getJID(s, arg);
		if (jid.isEmpty())
			jid=arg;
		if (jid.isEmpty())
			jid=QString::fromStdString(s->from().bare());
		QString vcardId=bot()->client()->fetchVCard(jid);
		gloox::Stanza *sf=new gloox::Stanza(s);
		qDebug() << "VCard request: " << jid;
		sf->addAttribute("id", QString("vcard_%1").arg(vcardId).toStdString());
		AsyncRequest *req=new AsyncRequest(-1, this, sf, 3600);
		req->setName(cmd);
		bot()->asyncRequests()->append(req);
		return true;
	}
	if (cmd=="STATLIST" || cmd=="STAT")
	{
		std::string id=bot()->client()->getID();
		QString jid=resolveTargetJid(s, arg);

		gloox::Stanza *st=gloox::Stanza::createIqStanza(
			gloox::JID(jid.toStdString()), id, gloox::StanzaIqGet,
			"http://jabber.org/protocol/stats");

		if (cmd=="STAT")
		{
			gloox::Tag* tag=st->findChild("query", "xmlns",
				"http://jabber.org/protocol/stats");
			if (tag)
			{
				for (;;)
				{
					QString item=parser.nextToken();
					if (item.isEmpty())
						break;
					tag->addChild(new gloox::Tag("stat","name",item.toStdString()));
				}
			}
		}
		st->finalize();

		gloox::Stanza *sf=new gloox::Stanza(s);
		sf->addAttribute("id", id);
		AsyncRequest *req=new AsyncRequest(-1, this, sf, 3600);
		req->setName(QString(cmd));
		bot()->asyncRequests()->append(req);
		bot()->client()->send(st);
		return true;
	}

	if (cmd=="UPTIME")
	{
		std::string id=bot()->client()->getID();
		QString jid=resolveTargetJid(s, arg);

		gloox::Stanza *st=gloox::Stanza::createIqStanza(
				gloox::JID(jid.toStdString()), id, gloox::StanzaIqGet,
				"jabber:iq:last");
		gloox::Stanza *sf=new gloox::Stanza(s);
		sf->addAttribute("id", id);
		AsyncRequest *req=new AsyncRequest(-1, this, sf, 3600);
		req->setName(jid);
		bot()->asyncRequests()->append(req);
		bot()->client()->send(st);
		return true;
	}

	return false;
}
Beispiel #14
0
/*
================
idCameraAnim::Load
================
*/
void idCameraAnim::LoadAnim( void ) {
	int			version;
	idLexer		parser( LEXFL_ALLOWPATHNAMES | LEXFL_NOSTRINGESCAPECHARS | LEXFL_NOSTRINGCONCAT );
	idToken		token;
	int			numFrames;
	int			numCuts;
	int			i;
	idStr		filename;
	const char	*key;

	key = spawnArgs.GetString( "anim" );
	if ( !key ) {
		gameLocal.Error( "Missing 'anim' key on '%s'", name.c_str() );
	}

	filename = spawnArgs.GetString( va( "anim %s", key ) );
	if ( !filename.Length() ) {
		gameLocal.Error( "Missing 'anim %s' key on '%s'", key, name.c_str() );
	}

	filename.SetFileExtension( MD5_CAMERA_EXT );
	if ( !parser.LoadFile( filename ) ) {
		gameLocal.Error( "Unable to load '%s' on '%s'", filename.c_str(), name.c_str() );
	}

	cameraCuts.Clear();
	cameraCuts.SetGranularity( 1 );
	camera.Clear();
	camera.SetGranularity( 1 );

	parser.ExpectTokenString( MD5_VERSION_STRING );
	version = parser.ParseInt();
	if ( version != MD5_VERSION ) {
		parser.Error( "Invalid version %d.  Should be version %d\n", version, MD5_VERSION );
	}

	// skip the commandline
	parser.ExpectTokenString( "commandline" );
	parser.ReadToken( &token );

	// parse num frames
	parser.ExpectTokenString( "numFrames" );
	numFrames = parser.ParseInt();
	if ( numFrames <= 0 ) {
		parser.Error( "Invalid number of frames: %d", numFrames );
	}

	// parse framerate
	parser.ExpectTokenString( "frameRate" );
	frameRate = parser.ParseInt();
	if ( frameRate <= 0 ) {
		parser.Error( "Invalid framerate: %d", frameRate );
	}

	// parse num cuts
	parser.ExpectTokenString( "numCuts" );
	numCuts = parser.ParseInt();
	if ( ( numCuts < 0 ) || ( numCuts > numFrames ) ) {
		parser.Error( "Invalid number of camera cuts: %d", numCuts );
	}

	// parse the camera cuts
	parser.ExpectTokenString( "cuts" );
	parser.ExpectTokenString( "{" );
	cameraCuts.SetNum( numCuts );
	for( i = 0; i < numCuts; i++ ) {
		cameraCuts[ i ] = parser.ParseInt();
		if ( ( cameraCuts[ i ] < 1 ) || ( cameraCuts[ i ] >= numFrames ) ) {
			parser.Error( "Invalid camera cut" );
		}
	}
	parser.ExpectTokenString( "}" );

	// parse the camera frames
	parser.ExpectTokenString( "camera" );
	parser.ExpectTokenString( "{" );
	camera.SetNum( numFrames );
	for( i = 0; i < numFrames; i++ ) {
		parser.Parse1DMatrix( 3, camera[ i ].t.ToFloatPtr() );
		parser.Parse1DMatrix( 3, camera[ i ].q.ToFloatPtr() );
		camera[ i ].fov = parser.ParseFloat();
	}
	parser.ExpectTokenString( "}" );

#if 0
	if ( !gameLocal.GetLocalPlayer() ) {
		return;
	}

	idDebugGraph gGraph;
	idDebugGraph tGraph;
	idDebugGraph qGraph;
	idDebugGraph dtGraph;
	idDebugGraph dqGraph;
	gGraph.SetNumSamples( numFrames );
	tGraph.SetNumSamples( numFrames );
	qGraph.SetNumSamples( numFrames );
	dtGraph.SetNumSamples( numFrames );
	dqGraph.SetNumSamples( numFrames );

	gameLocal.Printf( "\n\ndelta vec:\n" );
	float diff_t, last_t, t;
	float diff_q, last_q, q;
	diff_t = last_t = 0.0f;
	diff_q = last_q = 0.0f;
	for( i = 1; i < numFrames; i++ ) {
		t = ( camera[ i ].t - camera[ i - 1 ].t ).Length();
		q = ( camera[ i ].q.ToQuat() - camera[ i - 1 ].q.ToQuat() ).Length();
		diff_t = t - last_t;
		diff_q = q - last_q;
		gGraph.AddValue( ( i % 10 ) == 0 );
		tGraph.AddValue( t );
		qGraph.AddValue( q );
		dtGraph.AddValue( diff_t );
		dqGraph.AddValue( diff_q );

		gameLocal.Printf( "%d: %.8f  :  %.8f,     %.8f  :  %.8f\n", i, t, diff_t, q, diff_q  );
		last_t = t;
		last_q = q;
	}

	gGraph.Draw( colorBlue, 300.0f );
	tGraph.Draw( colorOrange, 60.0f );
	dtGraph.Draw( colorYellow, 6000.0f );
	qGraph.Draw( colorGreen, 60.0f );
	dqGraph.Draw( colorCyan, 6000.0f );
#endif
}
Beispiel #15
0
CarModel::CarModel(b2World* world,unsigned int id)
{
	m_id = id;
	//open the file
	std::ifstream ifs("carsetup.TOML");
	//make TOML parser
	toml::Parser parser(ifs);
	
	toml::Value documentRoot = parser.parse();
	toml::Value* params = documentRoot.find("carparams");
	
	// Populate our physic parameters
	m_maxForwardSpeed	= (float)params->find("max_forward_speed")->as<double>();
	m_maxBackwardSpeed	= (float)params->find("max_backward_speed")->as<double>();
	m_maxDriveForce		= (float)params->find("max_drive_force")->as<double>();
	m_maxLateralImpulse = (float)params->find("max_lateral_impulse")->as<double>();
	m_angularDamping	= (float)params->find("angular_damping")->as<double>();
	m_angularFriction	= (float)params->find("angular_friction")->as<double>();
	m_bodyDensity		= (float)params->find("body_density")->as<double>();
	m_currentTraction	= (float)params->find("traction")->as<double>();
	m_steerTorque		= (float)params->find("steer_torque")->as<double>();
	m_steerTorqueOffset = (float)params->find("steer_torque_offset")->as<double>();
	m_driftFriction		= (float)params->find("drift_friction")->as<double>();
	m_dragModifier		= (float)params->find("drag_modifier")->as<double>();
	m_steerAllowSpeed	= (float)params->find("steer_allow_speed")->as<double>();

	// Read our polygonal car body vertices
	toml::Value* carBodyParams = documentRoot.find("carbody");

	const toml::Array& bodyVertices = carBodyParams->find("body_vertices")->as<toml::Array>();
	
	b2Vec2 *vertices = new b2Vec2[bodyVertices.size()];
	unsigned int k = 0;
	for (const toml::Value& v : bodyVertices)
	{
		const toml::Array& bodyVerticesCoords = v.as<toml::Array>();
		vertices[k++].Set(bodyVerticesCoords.at(0).asNumber(), bodyVerticesCoords.at(1).asNumber());
	}

	// Create the car body definition 
	b2BodyDef bodyDef;
	// Mark it as dynamic (it's a car so it will move :) )
	bodyDef.type = b2_dynamicBody;
	// This creates and adds the body to the world (adds it as the first element of the double linked list) 
	m_body = world->CreateBody(&bodyDef);
	// We set the angular damping
	m_body->SetAngularDamping(m_angularDamping);

	// Create the poly shape from the vertices and link it to a fixture
	b2PolygonShape polygonShape;
	polygonShape.Set(vertices, bodyVertices.size());
	b2Fixture* fixture = m_body->CreateFixture(&polygonShape, m_bodyDensity);

	// Set the collision filter for our car (it should only collide with static, i.e walls)
	b2Filter filter;
	filter.categoryBits = CATEGORY_CAR;
	filter.maskBits		= CATEGORY_STATIC;
	
	fixture->SetFilterData(filter);

	// Set user data so we can identify our car in a possible collision, or sensor trigger
	fixture->SetUserData(new CarFUD(id));
	
	// Cleanup
	delete[] vertices;
}
Beispiel #16
0
void NavigationClient::Main()
{

	std::cout << "Navigation client started" << std::endl;
	int argsNumber;
	argsNumber = 3;
    char *arguments[argsNumber];
    arguments[0]="./arg_test";
    arguments[1]="-host";
    //arguments[2]="10.41.42.1";
    //se puede poner también patrolbot
    arguments[2]="77.7.27.1";

  int robotCase, counter;
	
  ArClientBase client;
  ArPose pose(0, 0, 0);
  ArPose GoToPose(3000.0, 0.0, -90.0);
  ArNetPacket posePacket, directGoToPosePacket;

  ArArgumentParser parser(&argsNumber, arguments);posePacket.empty();
		 
  ArClientSimpleConnector clientConnector(&parser);
  parser.loadDefaultArguments();
  
  headingsForBedroom.push_back(45);
  headingsForBedroom.push_back(25);
  headingsForBedroom.push_back(0);
  
 
  headingsForLiving.push_back(-20);
  headingsForLiving.push_back(-55);
  headingsForLiving.push_back(-80);
  headingsForLiving.push_back(-110);
  headingsForLiving.push_back(-140);
  
  openDoor = false;
  if (!clientConnector.parseArgs() || !parser.checkHelpAndWarnUnparsed()) {
    clientConnector.logOptions();
    exit(0);
  }
  
  printf("Connecting...\n");
  if (!clientConnector.connectClient(&client)) {
    if (client.wasRejected())
      printf("Server rejected connection, exiting\n");
    else
      printf("Could not connect to server, exiting\n");
    
    exit(1);
  } 

  printf("Connected to server.\n");
  client.addHandler("pathPlannerStatus", new ArGlobalFunctor1<ArNetPacket*>(&handlePathPlannerStatus));
  client.addHandler("update", new ArGlobalFunctor1<ArNetPacket*>(&handleRobotUpdate));
  client.addHandler("goalName", new ArGlobalFunctor1<ArNetPacket*>(&handleGoalName));
  client.addHandler("getGoals", new  ArGlobalFunctor1<ArNetPacket*>(&handleGoalList));
  client.addHandler("getSensorCurrent", new ArGlobalFunctor1<ArNetPacket*>(&handleSensorCurrent));
  client.addHandler("getSensorList", new ArGlobalFunctor1<ArNetPacket*>(&handleSensorList));
  client.addHandler("getLocState", new ArGlobalFunctor1<ArNetPacket*>(&handleLocState));

  client.runAsync();

  client.requestOnce("getGoals");
  client.requestOnce("getSensorList");
  client.requestOnceWithString("getSensorCurrent", "lms2xx_1");
  // client.request("pathPlannerStatus", 5000);
  client.request("goalName", 1000);
  client.request("update", 1000);
  client.requestOnce("getLocState");
  
  sleep(2);
  int cont =0;
  while (!openDoor) {
    cont++;
    ArUtil::sleep(2000);
    client.requestOnceWithString("getSensorCurrent", "lms2xx_1");
  }

  printf("*** Door has been OPENED *** \n");
  sleep(2);

  if (client.dataExists("localizeToPose")) {
	  printf(".. Server does have \"localizeToPose\" request.\n");
	  posePacket.byte4ToBuf(sharedMemory->getInstance().getLocalizationRobotPosition().get_X());
	  posePacket.byte4ToBuf(sharedMemory->getInstance().getLocalizationRobotPosition().get_Y());
	  posePacket.byte4ToBuf(sharedMemory->getInstance().getLocalizationRobotPosition().get_Angle());
	  
	  client.requestOnce("localizeToPose", &posePacket);
	  ArUtil::sleep(1500);
  }
  else
	  printf(".. Server doesn't have that request.\n");

  
  for(;;){
		string action = sharedMemory->getInstance().getAction();
			
		if (action=="navigate"){
		    cout<<"Starting: "<< action << "STATE in NavigationClient"<<endl;  
		    navigateTo(sharedMemory->getInstance().getStringDestination(), &client);
                   sharedMemory->getInstance().setAction("turn");
		 
			
		}if (action=="navigateToParty"){
		    cout<<"Starting: "<< action << "STATE in NavigationClient"<<endl;  
		    navigateTo(sharedMemory->getInstance().getStringDestination(), &client);
		    sleep(6);
		    sharedMemory->getInstance().startDownToRotations=false;
		    sharedMemory->getInstance().sintetizer.set_Phrase("If you need something please wave your hand to my bottom kinect");
		    sleep(8);
		    indexHeading=0;
		    sharedMemory->getInstance().setAction("turn");
		   
		}
		else if (action=="navigateBackToEmergency"){
		    
		    cout<<"Starting: "<< action << "STATE in NavigationClient"<<endl;  
		    
		    navigateTo(sharedMemory->getInstance().getStringDestination(), &client);
		     // sharedMemory->sintetizer.set_Phrase("Emergency Situation resolved");
		    sharedMemory->getInstance().setAction("createReport");
			
		}else if (action=="navigateToEntrance"){
		    cout<<"Starting: "<< action << "STATE in NavigationClient"<<endl;  
		    sharedMemory->getInstance().sintetizer.set_Phrase("Do not worry, I have called the ambulance");
			  sleep(2);
		    sharedMemory->getInstance().sintetizer.set_Phrase("Please wait a moment, I willl wait for them");
			  sleep(2);
	  
		    navigateTo(sharedMemory->getInstance().getStringDestination(), &client);
		    sharedMemory->getInstance().setAction("waitForAmbulance");
		}
		else if (action=="navigateCloseTo"){
		    cout<<"Starting: "<< action << "STATE in NavigationClient"<<endl;  
		    navigateTo(sharedMemory->getInstance().getStringDestination(), &client);
	            sharedMemory->getInstance().setAction("requestEmergencyObjects");
			
		}
		else if (action=="navigateToHome"){
		  cout<<"Starting: "<< action << " STATE in NavigationClient"<<endl;  
		  navigateTo(sharedMemory->getInstance().getStringDestination(), &client);
		  sharedMemory->getInstance().setAction("requestCommand");
		}
		else if (action=="navigateToQuestions"){
		  cout<<"Starting: "<< action << " STATE in NavigationClient"<<endl;  
		  navigateTo(sharedMemory->getInstance().getStringDestination(), &client);
		  sharedMemory->getInstance().setAction("requestQuestions");
		}
		else if (action=="navigateToObject"){
		  //solo es utilizado por cocktail Party
		  //Si se quita la indicación de lugar en requestOptions aqui debe mandarse el destino predefinido (kitchen?)
		  cout<<"Starting: "<< action << " STATE in NavigationClient"<<endl;  
		  navigateTo(sharedMemory->getInstance().getStringDestination(), &client);
		  sharedMemory->getInstance().setAction("recognizeObject");
		}
		else if (action=="navigateToObjectCategory"){
		  //considera que la posición de la categoria de un objeto (en pick and place) es la misma posición que la de donde esta el objeto en emergencia.
		  cout<<"Starting: "<< action << " STATE in NavigationClient"<<endl; 
		  //por default ahorita esta dining como el la categoria del objeto
		  navigateTo(sharedMemory->getInstance().getStringDestination(), &client);
		  if (sharedMemory->getInstance().getTestRunning()=="pick and place" || sharedMemory->getInstance().getTestRunning()=="Emergency" )
		    sharedMemory->getInstance().setAction("deliverObject");
		  else
		  sharedMemory->getInstance().setAction("userRecognize");
			
		}else if (action=="navigateToPoint"){
		    
		    cout<<"Starting: "<< action << " STATE in NavigationClient"<<endl;  
		    //TODO verificar que esto limpia el objeto
		    posePacket.empty();
		    posePacket.byte4ToBuf(sharedMemory->getInstance().lastObjective->getObjetivePosition().get_X());
		    posePacket.byte4ToBuf(sharedMemory->getInstance().lastObjective->getObjetivePosition().get_Y());
		    posePacket.byte4ToBuf(sharedMemory->getInstance().lastObjective->getObjetivePosition().get_Angle());
		    cout << "Enviando punto a navegación: "<< sharedMemory->getInstance().lastObjective->getObjetivePosition().get_X() << "," << sharedMemory->getInstance().lastObjective->getObjetivePosition().get_Y() << "," << sharedMemory->getInstance().lastObjective->getObjetivePosition().get_Angle()<<endl;
		    client.requestOnce("gotoPose", &posePacket);
		  
		    sleep(10);
		    printf("Before while Navigation");
		    while (strncmp(textData, "Arrived at", 10) != 0){
			sleep(10);
		    }
		 
		    printf("Navigation ended");
	           if (sharedMemory->getInstance().getTestRunning()=="CocktailParty")
		   sharedMemory->getInstance().setAction("userLearn");
		   else
		   sharedMemory->getInstance().setAction("requestEmergencyObjects");
	
		}else if (action=="navigateForward"){
		  
		  stringstream command;
		  cout<<"Starting: "<< action << " STATE in NavigationClient"<<endl;  
		  command<<"8 " << sharedMemory->getInstance().getGestureDepthPosition();
		  cout<< "******  AVANZA "<<command.str().c_str()<<" mm"<<endl;
		  client.requestOnceWithString("MicroControllerMotionCommand",command.str().c_str());
		  sleep(10);
		  printf("Before while Navigation");
		  while (strncmp(textData, "Stopped", 10) != 0){
			sleep(10);
			
		  }
		  sharedMemory->getInstance().setAction("turn");
		}else if (action=="turn"){
		  
		  int heading=0;
		  stringstream command;
                  cout<<"Starting: "<< action << " STATE in NavigationClient"<<endl;
		  if (sharedMemory->getInstance().startDownToRotations==false){
		    if (sharedMemory->getInstance().getStringDestination()=="bedroom"){
		      cout<<"Entrando BEDROOM 1"<<endl;
		      if (indexHeading < headingsForBedroom.size()){
			heading=headingsForBedroom[indexHeading];
			indexHeading++;
			cout<<"Entrando a If UNO bedroom"<<endl;
		      }else{
			sharedMemory->getInstance().startDownToRotations=true;
			indexHeading=headingsForBedroom.size()-2;
			heading=(-1000);//valor dado para detectar que no se obtuvo un valor válido para el heading, dado que se cambia la forma en como se recorre el arreglo
			cout<<"Entrando a else UNO bedroom"<<endl;
		      }
		    }else {//if (sharedMemory->getInstance().getStringDestination()=="living"){
		      cout<<"Entrando a LIVING 1"<<endl;
		      if (indexHeading < headingsForLiving.size()){
			heading=headingsForLiving[indexHeading];
			indexHeading++;
			cout<<"Entrando a If UNO living"<<endl;
		      }else{
			sharedMemory->getInstance().startDownToRotations=true;
			indexHeading=headingsForLiving.size()-2;//no menos uno porque ya el proceso anterior permition visitar este indice
			heading=(-1000);
			cout<<"Entrando a else UNO Living"<<endl;
		      }
		    }
		    
		  }else{
		    if (sharedMemory->getInstance().getStringDestination()=="bedroom"){
		      cout<<"Entrando BEDROoM 2"<<endl;
		      if (indexHeading >= 0){
			heading=headingsForBedroom[indexHeading];
			indexHeading--;
			cout<<"Entrando a if DOS bedroom"<<endl;
		      }else{
			sharedMemory->getInstance().startDownToRotations=false;
			indexHeading=1;
			heading=(-1000);
			cout<<"Entrando a else DOS bedroom"<<endl;
		      }
		    }else {//if (sharedMemory->getInstance().getStringDestination()=="living"){
		      cout<<"Entrando a LIVING 2"<<endl;
		      if (indexHeading>= 0){
			heading=headingsForLiving[indexHeading];
			indexHeading--;
			cout<<"Entrando a if DOS living"<<endl;
		      }else{
			sharedMemory->getInstance().startDownToRotations=false;
			indexHeading=1;//no 0 porque ya el proceso anterior permitió visitar este indice
			heading=(-1000);
			cout<<"Entrando a else DOS living"<<endl;
		      }
		    }
		  }
		    
		  if (heading>(-1000)){
		    command<<"12 " << heading;
		    cout<< "******  ROTAR "<<command.str().c_str()<<" grades con INDEXHEADING: "<<indexHeading<<"valorArray"<< headingsForLiving[indexHeading]<<endl;
		    client.requestOnceWithString("MicroControllerMotionCommand",command.str().c_str());
		    //sharedMemory->getInstance().sintetizer.set_Phrase("If you need something, please wave your hand to my bottom kinect");
	            sleep(1);
		    cout<<"*INVERSA al hacer el heading: "<< sharedMemory->getInstance().startDownToRotations << endl;
		    sharedMemory->getInstance().setAction("payAttention"); 
		  }
		}else if (action=="navigateToExit"){
		    //éste estado solo llamarlo para terminar la prueba
		    cout<<"Starting: "<< action << "STATE in NavigationClient"<<endl;  
		    navigateTo("Exit", &client);
		   sharedMemory->getInstance().setAction("turnOff");;		
		}
		else if (action=="turnOff"){
                       cout<<"Starting: "<< action << " STATE in NavigationClient"<<endl;  
			//ArUtil::sleep(60000);
			printf("Server disconnected.\n");
			Aria::shutdown();
		}
	
	}
	return ;
  
}
Beispiel #17
0
bool MathPrintout::OnPrintPage(int num)
{
  double screenScaleX, screenScaleY;
  double ppiScale;
  GroupCell* tmp;
  wxDC* dc = GetDC();

  int marginX, marginY;
  GetPageMargins(&marginX, &marginY);

  ppiScale = GetPPIScale();
  GetScreenScale(&screenScaleX, &screenScaleY);

  marginX += SCALE_PX(MC_BASE_INDENT, ppiScale);

  dc->SetUserScale(screenScaleX, screenScaleY);

  // Go to current page
  tmp = (GroupCell *)m_pages[num - 1];

  // Print page
  if (tmp != NULL)
  {
    if (tmp->GetGroupType() == GC_TYPE_PAGEBREAK)
      tmp = (GroupCell *)tmp->m_next;
    if (tmp == NULL)
      return true;

    wxPoint point;
    point.x = marginX;
    point.y = marginY + tmp->GetMaxCenter() + GetHeaderHeight();
    wxConfigBase* config = wxConfig::Get();
    int fontsize = 12;
    int drop = tmp->GetMaxDrop();

    config->Read(wxT("fontsize"), &fontsize);

    PrintHeader(num, dc, ppiScale);
    CellParser parser(*dc, ppiScale);

    parser.SetIndent(marginX);
    // Inform the output routines that we are printing
    parser.SetPrinter(true);
    // Make sure that during print nothing is outside the crop rectangle
    MathCell::ClipToDrawRegion(true);
    
    while (tmp != NULL && tmp->GetGroupType() != GC_TYPE_PAGEBREAK)
    {
      // The following line seems to misteriously fix the "subsequent text
      // cells aren't printed" problem on linux.
      // No Idea why, though.
      dc->SetPen(wxPen(wxT("light grey"), 1, wxPENSTYLE_SOLID));
      tmp->Draw(point, fontsize);
      if (tmp->m_next != NULL) {
        point.x = marginX;
        point.y += drop + tmp->m_next->GetMaxCenter();
        point.y += SCALE_PX(MC_GROUP_SKIP, ppiScale);
        drop = tmp->m_next->GetMaxDrop();
      }

      tmp = (GroupCell *)tmp->m_next;
      if (tmp == NULL || tmp->BreakPageHere())
        break;
    }
    MathCell::ClipToDrawRegion(false);
    return true;
  }
  MathCell::ClipToDrawRegion(false);
  return false;
}
Beispiel #18
0
bool CppCheckExecutor::parseFromArgs(CppCheck *cppcheck, int argc, const char* const argv[])
{
    CmdLineParser parser(&_settings);
    bool success = parser.ParseFromArgs(argc, argv);
    cppcheck->settings(_settings);   // copy the settings

    if (success) {
        if (parser.GetShowVersion() && !parser.GetShowErrorMessages()) {
            const char * extraVersion = cppcheck->extraVersion();
            if (strlen(extraVersion) > 0)
                std::cout << "Cppcheck " << cppcheck->version() << " ("
                          << extraVersion << ")" << std::endl;
            else
                std::cout << "Cppcheck " << cppcheck->version() << std::endl;
        }

        if (parser.GetShowErrorMessages()) {
            errorlist = true;
            std::cout << ErrorLogger::ErrorMessage::getXMLHeader(_settings._xml_version);
            cppcheck->getErrorMessages();
            std::cout << ErrorLogger::ErrorMessage::getXMLFooter(_settings._xml_version) << std::endl;
        }

        if (parser.ExitAfterPrinting())
            std::exit(0);
    }

    // Check that all include paths exist
    {
        std::list<std::string>::iterator iter;
        for (iter = _settings._includePaths.begin();
             iter != _settings._includePaths.end();
            ) {
            const std::string path(Path::toNativeSeparators(*iter));
            if (FileLister::isDirectory(path))
                ++iter;
            else {
                // If the include path is not found, warn user and remove the
                // non-existing path from the list.
                std::cout << "cppcheck: warning: Couldn't find path given by -I '" + path + "'" << std::endl;
                iter = _settings._includePaths.erase(iter);
            }
        }
    }

    std::vector<std::string> pathnames = parser.GetPathNames();
    std::vector<std::string> filenames;
    std::map<std::string, long> filesizes;

    if (!pathnames.empty()) {
        // Execute recursiveAddFiles() to each given file parameter
        std::vector<std::string>::const_iterator iter;
        for (iter = pathnames.begin(); iter != pathnames.end(); ++iter)
            FileLister::recursiveAddFiles(filenames, filesizes, Path::toNativeSeparators(*iter));
    }

    if (!filenames.empty()) {
        // Remove header files from the list of ignored files.
        // Also output a warning for the user.
        // TODO: Remove all unknown files? (use FileLister::acceptFile())
        bool warned = false;
        std::vector<std::string> ignored = parser.GetIgnoredPaths();
        std::vector<std::string>::iterator iterIgnored = ignored.begin();
        for (int i = (int)ignored.size() - 1; i >= 0; i--) {
            const std::string extension = Path::getFilenameExtension(ignored[i]);
            if (extension == ".h" || extension == ".hpp") {
                ignored.erase(iterIgnored + i);
                if (!warned) {
                    std::cout << "cppcheck: filename exclusion does not apply to header (.h and .hpp) files." << std::endl;
                    std::cout << "cppcheck: Please use --suppress for ignoring results from the header files." << std::endl;
                    warned = true; // Warn only once
                }
            }
        }

        PathMatch matcher(parser.GetIgnoredPaths());
        std::vector<std::string>::iterator iterBegin = filenames.begin();
        for (int i = (int)filenames.size() - 1; i >= 0; i--) {
#if defined(_WIN32)
            // For Windows we want case-insensitive path matching
            const bool caseSensitive = false;
#else
            const bool caseSensitive = true;
#endif
            if (matcher.Match(filenames[(unsigned int)i], caseSensitive))
                filenames.erase(iterBegin + i);
        }
    } else {
        std::cout << "cppcheck: error: could not find or open any of the paths given." << std::endl;
        return false;
    }

    if (!filenames.empty()) {
        std::vector<std::string>::iterator iter;
        for (iter = filenames.begin(); iter != filenames.end(); ++iter) {
            _filenames.push_back(*iter);
            _filesizes[*iter] = filesizes[*iter];
        }

        return true;
    } else {
        std::cout << "cppcheck: error: no files to check - all paths ignored." << std::endl;
        return false;
    }
}
Beispiel #19
0
void V800export::export_sessions(QList<QString> sessions, unsigned char mode)
{
    QSettings settings;
    QString default_dir = settings.value(tr("default_dir")).toString();

    for(int sessions_iter = 0; sessions_iter < sessions.length(); sessions_iter++)
    {
        QStringList filters;
        filters << QString(tr("%1_*")).arg(sessions[sessions_iter]);

        QDir filter_dir(default_dir);
        filter_dir.setNameFilters(filters);
        filter_dir.setFilter(QDir::Dirs);

        int multi_sessions_iter;
        QStringList multi_sessions = filter_dir.entryList();
        for(multi_sessions_iter = 0; multi_sessions_iter < multi_sessions.length(); multi_sessions_iter++)
        {
            if(!make_bipolar_names(multi_sessions[multi_sessions_iter]))
            {
                emit export_session_error(sessions[sessions_iter], RENAME_ERROR);
                continue;
            }

            QString session_info(QString(tr("%1/%2/v2-users-0000000-training-sessions-%3")).arg(default_dir).arg(multi_sessions[multi_sessions_iter]).arg(multi_sessions[multi_sessions_iter]));
            polar::v2::TrainingSession parser(session_info);

            qDebug("Parser: %s", session_info.toUtf8().constData());

            parser.setTcxOption(polar::v2::TrainingSession::ForceTcxUTC, true);

            if(!parser.parse())
                emit export_session_error(sessions[sessions_iter], PARSE_ERROR);

            if(mode & TCX_EXPORT)
            {
                QString tcx(QString(tr("%1/%2.tcx")).arg(default_dir).arg(multi_sessions[multi_sessions_iter]));
                if(!parser.writeTCX(tcx))
                    emit export_session_error(sessions[sessions_iter], TCX_ERROR);
            }

            if(mode & HRM_EXPORT)
            {
                QString hrm(QString(tr("%1/%2")).arg(default_dir).arg(multi_sessions[multi_sessions_iter]));
                QStringList hrm_out = parser.writeHRM(hrm);
                if(hrm_out.length() < 1)
                    emit export_session_error(sessions[sessions_iter], HRM_ERROR);
            }

            if(mode & GPX_EXPORT)
            {
                QString gpx(QString(tr("%1/%2.gpx")).arg(default_dir).arg(multi_sessions[multi_sessions_iter]));
                if(!parser.writeGPX(gpx))
                    emit export_session_error(sessions[sessions_iter], GPX_ERROR);
            }

            QDir(QString(tr("%1/%2")).arg(default_dir).arg(multi_sessions[multi_sessions_iter])).removeRecursively();
        }

        emit export_session_done(sessions_iter, sessions.length());
    }

    emit export_sessions_done();
}
void
SVGMotionSMILAnimationFunction::
  RebuildPathAndVerticesFromBasicAttrs(const nsIContent* aContextElem)
{
  MOZ_ASSERT(!HasAttr(nsGkAtoms::path),
             "Should be using |path| attr if we have it");
  MOZ_ASSERT(!mPath, "regenerating when we aleady have path");
  MOZ_ASSERT(mPathVertices.IsEmpty(),
             "regenerating when we already have vertices");

  if (!aContextElem->IsSVGElement()) {
    NS_ERROR("Uh oh, SVG animateMotion element targeting a non-SVG node");
    return;
  }

  SVGMotionSMILPathUtils::PathGenerator
    pathGenerator(static_cast<const nsSVGElement*>(aContextElem));

  bool success = false;
  if (HasAttr(nsGkAtoms::values)) {
    // Generate path based on our values array
    mPathSourceType = ePathSourceType_ValuesAttr;
    const nsAString& valuesStr = GetAttr(nsGkAtoms::values)->GetStringValue();
    SVGMotionSMILPathUtils::MotionValueParser parser(&pathGenerator,
                                                     &mPathVertices);
    success = nsSMILParserUtils::ParseValuesGeneric(valuesStr, parser);
  } else if (HasAttr(nsGkAtoms::to) || HasAttr(nsGkAtoms::by)) {
    // Apply 'from' value (or a dummy 0,0 'from' value)
    if (HasAttr(nsGkAtoms::from)) {
      const nsAString& fromStr = GetAttr(nsGkAtoms::from)->GetStringValue();
      success = pathGenerator.MoveToAbsolute(fromStr);
      mPathVertices.AppendElement(0.0);
    } else {
      // Create dummy 'from' value at 0,0, if we're doing by-animation.
      // (NOTE: We don't add the dummy 0-point to our list for *to-animation*,
      // because the nsSMILAnimationFunction logic for to-animation doesn't
      // expect a dummy value. It only expects one value: the final 'to' value.)
      pathGenerator.MoveToOrigin();
      if (!HasAttr(nsGkAtoms::to)) {
        mPathVertices.AppendElement(0.0);
      }
      success = true;
    }

    // Apply 'to' or 'by' value
    if (success) {
      double dist;
      if (HasAttr(nsGkAtoms::to)) {
        mPathSourceType = ePathSourceType_ToAttr;
        const nsAString& toStr = GetAttr(nsGkAtoms::to)->GetStringValue();
        success = pathGenerator.LineToAbsolute(toStr, dist);
      } else { // HasAttr(nsGkAtoms::by)
        mPathSourceType = ePathSourceType_ByAttr;
        const nsAString& byStr = GetAttr(nsGkAtoms::by)->GetStringValue();
        success = pathGenerator.LineToRelative(byStr, dist);
      }
      if (success) {
        mPathVertices.AppendElement(dist);
      }
    }
  }
  if (success) {
    mPath = pathGenerator.GetResultingPath();
  } else {
    // Parse failure. Leave path as null, and clear path-related member data.
    mPathVertices.Clear();
  }
}
int main(int argc, char** argv)
{
	bool res = ::wxInitialize();
	if (!res) {
		::fprintf(stderr, "analoguerepeaterd: failed to initialise the wxWidgets library, exiting\n");
		return -1;
	}

	wxCmdLineParser parser(argc, argv);
	parser.AddSwitch(NOLOGGING_SWITCH, wxEmptyString, wxEmptyString, wxCMD_LINE_PARAM_OPTIONAL);
	parser.AddSwitch(DAEMON_SWITCH,    wxEmptyString, wxEmptyString, wxCMD_LINE_PARAM_OPTIONAL);
	parser.AddOption(LOGDIR_OPTION,    wxEmptyString, wxEmptyString, wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL);
	parser.AddOption(CONFDIR_OPTION,   wxEmptyString, wxEmptyString, wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL);
	parser.AddParam(NAME_PARAM, wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL);

	int cmd = parser.Parse();
	if (cmd != 0) {
		::wxUninitialize();
		return 0;
	}

	bool  nolog = parser.Found(NOLOGGING_SWITCH);
	bool daemon = parser.Found(DAEMON_SWITCH);

	wxString logDir;
	bool found = parser.Found(LOGDIR_OPTION, &logDir);
	if (!found)
		logDir.Clear();

	wxString confDir;
	found = parser.Found(CONFDIR_OPTION, &confDir);
	if (!found)
		confDir = CONF_DIR;

	wxString name;
	if (parser.GetParamCount() > 0U)
		name = parser.GetParam(0U);

	if (daemon) {
		pid_t pid = ::fork();

		if (pid < 0) {
			::fprintf(stderr, "analoguerepeaterd: error in fork(), exiting\n");
			::wxUninitialize();
			return 1;
		}

		// If this is the parent, exit
		if (pid > 0)
			return 0;

		// We are the child from here onwards
		::setsid();

		::chdir("/");

		::umask(0);
	}

	CAnalogueRepeaterD repeater(nolog, logDir, confDir, name);

	if (!repeater.init()) {
		::wxUninitialize();
		return 1;
	}

	repeater.run();

	::wxUninitialize();
	return 0;
}
Beispiel #22
0
int main(int argc, char **argv)
{
  Aria::init();
  ArArgumentParser parser(&argc, argv);
  parser.loadDefaultArguments();
  ArRobot robot;

  ArRobotConnector robotConnector(&parser, &robot);
  if(!robotConnector.connectRobot())
  {
    ArLog::log(ArLog::Terse, "mtxIOTest: Could not connect to the robot.");
    if(parser.checkHelpAndWarnUnparsed())
    {
        // -help not given
        Aria::logOptions();
        Aria::exit(1);
    }
  }

  if (!Aria::parseArgs() || !parser.checkHelpAndWarnUnparsed())
  {
    Aria::logOptions();
    Aria::exit(1);
  }
  ArLog::log(ArLog::Normal, "mtxIOTest: Connected.");
  robot.comInt(ArCommands::JOYINFO, 0);

  ArMTXIO mtxIO;

  if(!mtxIO.isEnabled())
  {
    ArLog::log(ArLog::Terse, "mtxIOTest: Error opening MTX IO device interface!");
    Aria::exit(4);
  }

  robot.runAsync(true);

  ArMTXIO mtxIO2;
  if(!mtxIO2.isEnabled())
  {
    ArLog::log(ArLog::Terse, "mtxIOTest: Error opening a second MTX IO interface");
    Aria::exit(5);
  }

  unsigned char out = 1;
  while(true)
  {
    mtxIO.lock();
    unsigned char cur;
    // get current state
    if(!mtxIO.getDigitalOutputControl1(&cur))
    {
      ArLog::log(ArLog::Terse, "mtxIOTest: Error getting current state of output control 1");
      mtxIO.unlock();
      Aria::exit(2);
    }

    // set new state
    cur = out;
    if(!mtxIO.setDigitalOutputControl1(&cur))
    {
      ArLog::log(ArLog::Terse, "mtxIOTest: Error setting state of output control 1");
      mtxIO.unlock();
      Aria::exit(3);
    }
  

    mtxIO2.lock();
    if(!mtxIO2.setDigitalOutputControl2(&cur))
    {
      ArLog::log(ArLog::Terse, "mtxIOTest: Error setting state of output control 2 through second interface object");
      mtxIO.unlock();
      Aria::exit(6);
    }
    mtxIO2.unlock();
      
    mtxIO.unlock();
    ArUtil::sleep(500);
 
    // shift 
    out = out << 1;
    if(out == 0) out = 1;
  }
    
    
  Aria::exit(0);

}
Beispiel #23
0
void PHPCodeGenerator::GenConstruction(PObjectBase obj, bool is_widget )
{
	wxString type = obj->GetObjectTypeName();
	PObjectInfo info = obj->GetObjectInfo();

	if ( ObjectDatabase::HasCppProperties( type ) )
	{
		m_source->WriteLn( GetCode( obj, wxT("construction") ) );

		GenSettings( obj->GetObjectInfo(), obj );

		bool isWidget = !info->IsSubclassOf( wxT("sizer") );

		for ( unsigned int i = 0; i < obj->GetChildCount(); i++ )
		{
			PObjectBase child = obj->GetChild( i );
			GenConstruction( child, isWidget );

			if ( type == wxT("toolbar") )
			{
				GenAddToolbar(child->GetObjectInfo(), child);
			}
		}

		if ( !isWidget ) // sizers
		{
			wxString afterAddChild = GetCode( obj, wxT( "after_addchild" ) );
			if ( !afterAddChild.empty() )
			{
				m_source->WriteLn( afterAddChild );
			}
			m_source->WriteLn();

			if (is_widget)
			{
				// the parent object is not a sizer. There is no template for
				// this so we'll make it manually.
				// It's not a good practice to embed templates into the source code,
				// because you will need to recompile...

				wxString _template =	wxT("#wxparent $name->SetSizer( @$$name ); #nl")
										wxT("#wxparent $name->Layout();")
										wxT("#ifnull #parent $size")
										wxT("@{ #nl @$$name->Fit( #wxparent $name ); @}");

				PHPTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath );
				m_source->WriteLn(parser.ParseTemplate());
			}
		}
		else if ( type == wxT("splitter") )
		{
			// Generating the split
			switch ( obj->GetChildCount() )
			{
				case 1:
				{
					PObjectBase sub1 = obj->GetChild(0)->GetChild(0);
					wxString _template = wxT("@$this->$name->Initialize( ");
					_template = _template + wxT("@$this->") + sub1->GetProperty( wxT("name") )->GetValue() + wxT(" );");

					PHPTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath );
					m_source->WriteLn(parser.ParseTemplate());
					break;
				}
				case 2:
				{
					PObjectBase sub1,sub2;
					sub1 = obj->GetChild(0)->GetChild(0);
					sub2 = obj->GetChild(1)->GetChild(0);

					wxString _template;
					if ( obj->GetProperty( wxT("splitmode") )->GetValue() == wxT("wxSPLIT_VERTICAL") )
					{
						_template = wxT("@$this->$name->SplitVertically( ");
					}
					else
					{
						_template = wxT("@$this->$name->SplitHorizontally( ");
					}

					_template = _template + wxT("@$this->") + sub1->GetProperty( wxT("name") )->GetValue() +
						wxT(", @$this->") + sub2->GetProperty( wxT("name") )->GetValue() + wxT(", $sashpos );");

					PHPTemplateParser parser( obj, _template, m_i18n, m_useRelativePath, m_basePath );
					m_source->WriteLn(parser.ParseTemplate());
					break;
				}
				default:
					wxLogError( wxT("Missing subwindows for wxSplitterWindow widget.") );
					break;
			}
		}
		else if (
				type == wxT("menubar")	||
				type == wxT("menu")		||
				type == wxT("submenu")	||
				type == wxT("toolbar")	||
				type == wxT("ribbonbar")	||
				type == wxT("listbook")	||
				type == wxT("simplebook") ||
				type == wxT("notebook")	||
				type == wxT("auinotebook")	||
				type == wxT("treelistctrl")	||
				type == wxT("flatnotebook") ||
				type == wxT("wizard")
			)
		{
			wxString afterAddChild = GetCode( obj, wxT("after_addchild") );
			if ( !afterAddChild.empty() )
			{
				m_source->WriteLn( afterAddChild );
			}
			m_source->WriteLn();
		}
	}
	else if ( info->IsSubclassOf( wxT("sizeritembase") ) )
	{
		// The child must be added to the sizer having in mind the
		// child object type (there are 3 different routines)
		GenConstruction( obj->GetChild(0), false );

		PObjectInfo childInfo = obj->GetChild(0)->GetObjectInfo();
		wxString temp_name;
		if ( childInfo->IsSubclassOf( wxT("wxWindow") ) || wxT("CustomControl") == childInfo->GetClassName() )
		{
			temp_name = wxT("window_add");
		}
		else if ( childInfo->IsSubclassOf( wxT("sizer") ) )
		{
			temp_name = wxT("sizer_add");
		}
		else if ( childInfo->GetClassName() == wxT("spacer") )
		{
			temp_name = wxT("spacer_add");
		}
		else
		{
			LogDebug( wxT("SizerItem child is not a Spacer and is not a subclass of wxWindow or of sizer.") );
			return;
		}

		m_source->WriteLn( GetCode( obj, temp_name ) );
	}
	else if (	type == wxT("notebookpage")		||
				type == wxT("flatnotebookpage")	||
				type == wxT("listbookpage")		||
				type == wxT("simplebookpage")	||
				type == wxT("choicebookpage")	||
				type == wxT("auinotebookpage")
			)
	{
		GenConstruction( obj->GetChild( 0 ), false );
		m_source->WriteLn( GetCode( obj, wxT("page_add") ) );
		GenSettings( obj->GetObjectInfo(), obj );
	}
	else if ( type == wxT("treelistctrlcolumn") )
	{
		m_source->WriteLn( GetCode( obj, wxT("column_add") ) );
		GenSettings( obj->GetObjectInfo(), obj );
	}
	else if ( type == wxT("tool") )
	{
		// If loading bitmap from ICON resource, and size is not set, set size to toolbars bitmapsize
		// So hacky, yet so useful ...
		wxSize toolbarsize = obj->GetParent()->GetPropertyAsSize( _("bitmapsize") );
		if ( wxDefaultSize != toolbarsize )
		{
			PProperty prop = obj->GetProperty( _("bitmap") );
			if ( prop )
			{
				wxString oldVal = prop->GetValueAsString();
				wxString path, source;
				wxSize toolsize;
				TypeConv::ParseBitmapWithResource( oldVal, &path, &source, &toolsize );
				if ( wxT("Load From Icon Resource") == source && wxDefaultSize == toolsize )
				{
					prop->SetValue( wxString::Format( wxT("%s; %s [%i; %i]"), path.c_str(), source.c_str(), toolbarsize.GetWidth(), toolbarsize.GetHeight() ) );
					m_source->WriteLn( GetCode( obj, wxT("construction") ) );
					prop->SetValue( oldVal );
					return;
				}
			}
		}
		m_source->WriteLn( GetCode( obj, wxT("construction") ) );
	}
	else
	{
		// Generate the children
		for ( unsigned int i = 0; i < obj->GetChildCount(); i++ )
		{
			GenConstruction( obj->GetChild( i ), false );
		}
	}
}
Beispiel #24
0
/*!
 Parses a UTF-8 encoded JSON document and creates a QJsonDocument
 from it.

 \a json contains the json document to be parsed.

 The optional \a error variable can be used to pass in a QJsonParseError data
 structure that will contain information about possible errors encountered during
 parsing.

 \sa toJson(), QJsonParseError
 */
QJsonDocument QJsonDocument::fromJson(const QByteArray &json, QJsonParseError *error)
{
    QJsonPrivate::Parser parser(json.constData(), json.length());
    return parser.parse(error);
}
Beispiel #25
0
QString MsgViewBase::parseText(const QString &text, bool bIgnoreColors, bool bUseSmiles)
{
    ViewParser parser(bIgnoreColors, bUseSmiles);
    return parser.parse(text);
}
Beispiel #26
0
//Request-Line = Method SP Request-URI SP RTSP-Version CRLF
int RtspRequest::ParseRequestLine(string& sReqLine)
{
    int ret = 0;
    //StringArray_t saReqLineParam;
    m_Method = qtssIllegalMethod;
#if 0    
    StringUtil::Split(sReqLine, ' ', saReqLineParam);
    if(saReqLineParam.size() == 3) 
    {    
        m_Method = RTSPProtocol::GetMethod(StrPtrLen(saReqLineParam[0].c_str()));
        if(qtssIllegalMethod != m_Method)
        {
            return -1;//qtssClientBadRequest;
        }

        ret = ParseRtspURI(saReqLineParam[1].c_str());
        if(ret < 0)
        {
            return -1;
        }

        StrPtrLen RtspVer = RTSPProtocol::GetVersionString(RTSPProtocol::k10Version);
        if(strcmp(RtspVer.Ptr, saReqLineParam[2].c_str()) != 0)
        {
            return -1;
        }
    }
#endif 
//first get the method
    StrPtrLen ReqLine((char*)sReqLine.c_str());
    StringParser parser(&ReqLine);
    StrPtrLen theParsedData;
    parser.ConsumeWord(&theParsedData);
    //this->SetVal(qtssRTSPReqMethodStr, theParsedData.Ptr, theParsedData.Len);


    //THIS WORKS UNDER THE ASSUMPTION THAT:
    //valid HTTP/1.1 headers are: GET, HEAD, POST, PUT, OPTIONS, DELETE, TRACE
    m_Method = RTSPProtocol::GetMethod(theParsedData);
    if (m_Method == qtssIllegalMethod)
        return -1;//QTSSModuleUtils::SendErrorResponse(this, qtssClientBadRequest, qtssMsgBadRTSPMethod, &theParsedData);

    //no longer assume this is a space... instead, just consume whitespace
    parser.ConsumeWhitespace();

    //now parse the uri
    ret = ParseRtspURI(parser);
    if (ret < 0)
        return -1;

    //no longer assume this is a space... instead, just consume whitespace
    parser.ConsumeWhitespace();

    //if there is a version, consume the version string
    StrPtrLen versionStr;
    parser.ConsumeUntil(&versionStr, StringParser::sEOLMask);

    //check the version
    if (versionStr.Len < 0 || RTSPProtocol::k10Version != RTSPProtocol::GetVersion(versionStr))
        return -1;

    //go past the end of line
    //if (!parser.ExpectEOL())
    //    return QTSSModuleUtils::SendErrorResponse(this, qtssClientBadRequest, qtssMsgNoRTSPVersion,&theParsedData);
    return 0;//QTSS_NoErr;

}
Beispiel #27
0
void SenMLPack::fromCbor(char* source, int length, SenMLStreamMethod format)
{
    SenMLCborParser parser(this, format);
    parser.parse(source, length);
}
/**
 * Initialise Controller
 */
void Controller::init(const char *goalPath)
{
	//initialise Nero in sleep mode
	mWakeUp = false;
	mBusy = false;
	respondedSurprised = false;
	mPathingEnabled = false;

	//initialise map
	stringToValue[""]		 = NOTHING;
	stringToValue["wake up"] = WAKE_UP;
	stringToValue["eva"]	 = EVA;
	stringToValue["stop"]	 = STOP;
	stringToValue["beer"]	 = BEER;
	stringToValue["cola"]	 = COLA;
	stringToValue["coke"]	 = COKE;
	stringToValue["juice"]   = JUICE;
	stringToValue["give"]	 = GIVE;
	stringToValue["got"]	 = GOT;
	stringToValue["sleep"]	 = SLEEP;
	stringToValue["break"]	 = BREAK;
	stringToValue["break"]	 = BREAK;

	mNodeHandle.param<double>("distance_tolerance", mDistanceTolerance, 0.2);

	//initialise subscribers
	mSpeechSubscriber 			= mNodeHandle.subscribe("/processedSpeechTopic", 1, &Controller::speechCB, this);
	mBaseGoalSubscriber 		= mNodeHandle.subscribe("/path_length", 1, &Controller::baseGoalCB, this);
	mHeadSpeedSubscriber		= mNodeHandle.subscribe("/headSpeedFeedbackTopic", 1, &Controller::headSpeedCB, this);
	mBaseSpeedSubscriber		= mNodeHandle.subscribe("/speedFeedbackTopic", 1, &Controller::baseSpeedCB, this);
	mArmSpeedSubscriber			= mNodeHandle.subscribe("/armJointSpeedFeedbackTopic", 1, &Controller::armSpeedCB, this);
	mGripperStateSubscriber		= mNodeHandle.subscribe("/gripper_state", 1, &Controller::gripperStateCB, this);
	mPathFollowStateSubscriber	= mNodeHandle.subscribe("/follow_state", 1, &Controller::navigationStateCB, this);

	//initialise publishers
	mBaseGoalPublisher 			= mNodeHandle.advertise<geometry_msgs::PoseStamped>("/move_base_simple/goal", 1);
	mArmPositionPublisher 		= mNodeHandle.advertise<geometry_msgs::Pose>("/cmd_arm_position", 1);
	mHeadPositionPublisher		= mNodeHandle.advertise<nero_msgs::PitchYaw>("/cmd_head_position", 1);
	mRotateBasePublisher		= mNodeHandle.advertise<std_msgs::Float32>("/cmd_mobile_turn", 1);
	mPositionBasePublisher		= mNodeHandle.advertise<std_msgs::Float32>("/cmd_mobile_position", 1);
	mGripperCommandPublisher	= mNodeHandle.advertise<std_msgs::Bool>("/cmd_gripper", 1);
	mGripperClosePublisher		= mNodeHandle.advertise<std_msgs::Bool>("/cmd_gripper_state", 1);

	mEmotionPublisher			= mNodeHandle.advertise<std_msgs::UInt8>("/cmd_emotion", 1, true);
	mBaseSpeedPublisher			= mNodeHandle.advertise<geometry_msgs::Twist>("/cmd_vel", 1);
	stopPublisher				= new ros::Publisher(mNodeHandle.advertise<std_msgs::Bool>("/emergencyStop", 1));
	mSetPathingServer			= mNodeHandle.advertiseService("/set_pathing", &Controller::setPathingCB, this);

	if (waitForServiceClient(&mNodeHandle, "/cmd_object_recognition"))
		mFindObjectClient		= mNodeHandle.serviceClient<nero_msgs::FindObject>("/cmd_object_recognition", true);

	if (waitForServiceClient(&mNodeHandle, "/set_focus_face"))
		mSetFaceFocusClient		= mNodeHandle.serviceClient<nero_msgs::SetActive>("/set_focus_face", true);

	if (waitForServiceClient(&mNodeHandle, "/KinectServer/ForceDepthControl"))
		mForceDepthClient		= mNodeHandle.serviceClient<nero_msgs::SetActive>("/KinectServer/ForceDepthControl", true);

	setDepthForced(false);

	//Store goal position

	signal(SIGUSR1, stopHandler);

	std::ifstream fin(goalPath);
	if (fin.fail())
	{
		ROS_ERROR("Failed to open YAML file.");
		return;
	}

	YAML::Parser parser(fin);
	YAML::Node doc;
	parser.GetNextDocument(doc);

	float yaw;
	try
	{
		doc["goal"][0] >> mGoal.position.x;
		doc["goal"][1] >> mGoal.position.y;
		doc["goal"][2] >> yaw;

		convertQuaternion(mGoal.orientation, tf::createQuaternionFromYaw(yaw));

	} catch (YAML::InvalidScalar)
	{
		ROS_ERROR("No goal found in yaml file");
		return;
	}
	ROS_INFO("x: %f, y: %f, yaw: %f", mGoal.position.x, mGoal.position.y, yaw);

	usleep(1000000);

	wakeUp();
	ROS_INFO("Initialised Controller");
}
Beispiel #29
0
void UserAgentParser::Parse(StrPtrLen *inStream)
{
    StrPtrLen tempID;
    StrPtrLen tempData;
    StringParser parser(inStream);
    StrPtrLen startFields;
        

    memset(&fFieldData,0,sizeof(fFieldData) );
    
    parser.ConsumeUntil(&startFields, '(' ); // search for '(' if not found does nothing
    
    // parse through everything between the '(' and ')'.
    while (startFields.Len != 0)
    {
        //stop when we reach an empty line.
        tempID.Set(NULL,0);
        tempData.Set(NULL,0);
        
        parser.ConsumeLength(NULL, 1); // step past '(' or ';' if not found or at end of line does nothing
        parser.ConsumeWhitespace(); // search for non-white space if not found does nothing
        parser.ConsumeUntil(&tempID, sEOLWhitespaceEqualMask ); // search for end of id (whitespace or =)if not found does nothing
        if (tempID.Len == 0) break;
    
        parser.ConsumeUntil(NULL, '=' ); // find the '='
        parser.ConsumeLength(NULL, 1); // step past if not found or at end of line does nothing
        parser.ConsumeUntil(&tempData, sEOLSemicolonCloseParenMask ); // search for end of data if not found does nothing
        if (tempData.Len == 0) break;
        
        StrPtrLen   testID;
        UInt32      fieldID;
        for (short testField = 0; testField < UserAgentParser::eNumAttributes; testField++)
        {
            testID.Set(sFieldIDs[testField].fFieldName,sFieldIDs[testField].fLen);
            fieldID = sFieldIDs[testField].fID;
            if ( (fFieldData[fieldID].fFound == false) && testID.Equal(tempID) ) 
            {   
                fFieldData[fieldID].fData = tempData;
                fFieldData[fieldID].fFound = true;              
            }
        }
        
    }
    // If we parsed the OS field but not the OSVer field then check and see if
    // the OS field contains the OS version. If it does copy it from there.
    // (e.g. 'os=Mac%209.2.2' or 'os=Windows%20NT%204.0'.)
    if (fFieldData[eOs].fFound && !fFieldData[eOsver].fFound)
    {
        UInt16 len = (UInt16)fFieldData[eOs].fData.Len;
        char* cp = (char*)fFieldData[eOs].fData.Ptr;
        // skip up to the blank space if it exists.
        // (i.e. the blank is URL encoded as '%20')
        while(*cp != '%')
        {
            len--;
            if (*cp == '\0' || len == 0)
            {
                // no blank space...so we're all done.
                return;
            }
            cp++;
        }
        // skip over the blank space.
        cp += 3; len -= 3;
        // the remaining string is the OS version.
        fFieldData[eOsver].fData.Set(cp, len);
        fFieldData[eOsver].fFound = true;
        // and truncate the version from the OS field.
        fFieldData[eOs].fData.Len -= len+3;
    }
}
Beispiel #30
0
//**********************************************************************************************************************
SRACommand::SRACommand(string option)  {
	try {
		abort = false; calledHelp = false;
		
		//allow user to run help
		if(option == "help") { help(); abort = true; calledHelp = true; }
		else if(option == "citation") { citation(); abort = true; calledHelp = true;}
		
		else {
			//valid paramters for this command
			vector<string> myArray = setParameters();
			
			OptionParser parser(option);
			map<string,string> parameters = parser.getParameters();
			
			ValidParameters validParameter;
			map<string,string>::iterator it;
			//check to make sure all parameters are valid for command
			for (it = parameters.begin(); it != parameters.end(); it++) {
				if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
			}
			
            vector<string> tempOutNames;
            outputTypes["xml"] = tempOutNames;
			
			//if the user changes the input directory command factory will send this info to us in the output parameter
			string inputDir = validParameter.validFile(parameters, "inputdir", false);
			if (inputDir == "not found"){	inputDir = "";		}
			else {
            
                string path;
				it = parameters.find("sff");
				//user has given a template file
				if(it != parameters.end()){
					path = m->hasPath(it->second);
					//if the user has not given a path then, add inputdir. else leave path alone.
					if (path == "") {	parameters["sff"] = inputDir + it->second;		}
				}
				
				it = parameters.find("fastq");
				//user has given a template file
				if(it != parameters.end()){
					path = m->hasPath(it->second);
					//if the user has not given a path then, add inputdir. else leave path alone.
					if (path == "") {	parameters["fastq"] = inputDir + it->second;		}
				}
                
                it = parameters.find("file");
				//user has given a template file
				if(it != parameters.end()){
					path = m->hasPath(it->second);
					//if the user has not given a path then, add inputdir. else leave path alone.
					if (path == "") {	parameters["file"] = inputDir + it->second;		}
				}
                
                it = parameters.find("group");
				//user has given a template file
				if(it != parameters.end()){
					path = m->hasPath(it->second);
					//if the user has not given a path then, add inputdir. else leave path alone.
					if (path == "") {	parameters["group"] = inputDir + it->second;		}
				}
                
                it = parameters.find("oligos");
				//user has given a template file
				if(it != parameters.end()){
					path = m->hasPath(it->second);
					//if the user has not given a path then, add inputdir. else leave path alone.
					if (path == "") {	parameters["oligos"] = inputDir + it->second;		}
				}
            }
            
			//check for parameters
            fastqfile = validParameter.validFile(parameters, "fastq", true);
			if (fastqfile == "not open") { fastqfile = "";  abort = true; }
			else if (fastqfile == "not found") { fastqfile = ""; }
			
			sfffile = validParameter.validFile(parameters, "sff", true);
			if (sfffile == "not open") {  sfffile = "";  abort = true; }
			else if (sfffile == "not found") { sfffile = ""; }
            
            file = validParameter.validFile(parameters, "file", true);
			if (file == "not open") {  file = "";  abort = true; }
			else if (file == "not found") { file = ""; }
            
            groupfile = validParameter.validFile(parameters, "group", true);
			if (groupfile == "not open") {  groupfile = "";  abort = true; }
			else if (groupfile == "not found") { groupfile = ""; }
            else {  m->setGroupFile(groupfile); }
            
            oligosfile = validParameter.validFile(parameters, "oligos", true);
			if (oligosfile == "not found")      {	oligosfile = "";	}
			else if(oligosfile == "not open")	{	abort = true;		}
			else {	m->setOligosFile(oligosfile); }
            
            
            file = validParameter.validFile(parameters, "file", true);
			if (file == "not open") {  file = "";  abort = true; }
			else if (file == "not found") { file = ""; }
			
			if ((fastqfile == "") && (sfffile == "") && (sfffile == "")) {
                m->mothurOut("[ERROR]: You must provide a file, sff file or fastq file before you can use the sra command."); m->mothurOutEndLine(); abort = true;
            }
            
            if ((groupfile != "") && (oligosfile != "")) {
                m->mothurOut("[ERROR]: You may not use a group file and an oligos file, only one."); m->mothurOutEndLine(); abort = true;
            }
            
            if ((fastqfile != "") || (sfffile != "")) {
                if ((groupfile == "") && (oligosfile == "")) {
                    oligosfile = m->getOligosFile();
					if (oligosfile != "") {  m->mothurOut("Using " + oligosfile + " as input file for the oligos parameter."); m->mothurOutEndLine(); }
					else {
						groupfile = m->getGroupFile();
                        if (groupfile != "") {  m->mothurOut("Using " + groupfile + " as input file for the group parameter."); m->mothurOutEndLine(); }
                        else {
                            m->mothurOut("[ERROR]: You must provide groupfile or oligos file if splitting a fastq or sff file."); m->mothurOutEndLine(); abort = true;
                        }
					}
                }
            }
			            
            //use only one Mutliple type
			platform = validParameter.validFile(parameters, "platform", false);
			if (platform == "not found") { platform = "454"; }
			
			if ((platform == "454") || (platform == "????") || (platform == "????") || (platform == "????")) { }
			else { m->mothurOut("Not a valid platform option.  Valid platform options are 454, ...."); m->mothurOutEndLine(); abort = true; }
            
            
            string temp = validParameter.validFile(parameters, "bdiffs", false);		if (temp == "not found"){	temp = "0";		}
			m->mothurConvert(temp, bdiffs);
			
			temp = validParameter.validFile(parameters, "pdiffs", false);		if (temp == "not found"){	temp = "0";		}
			m->mothurConvert(temp, pdiffs);
			
            temp = validParameter.validFile(parameters, "ldiffs", false);		if (temp == "not found") { temp = "0"; }
			m->mothurConvert(temp, ldiffs);
            
            temp = validParameter.validFile(parameters, "sdiffs", false);		if (temp == "not found") { temp = "0"; }
			m->mothurConvert(temp, sdiffs);
			
			temp = validParameter.validFile(parameters, "tdiffs", false);		if (temp == "not found") { int tempTotal = pdiffs + bdiffs + ldiffs + sdiffs;  temp = toString(tempTotal); }
			m->mothurConvert(temp, tdiffs);
			
			if(tdiffs == 0){	tdiffs = bdiffs + pdiffs + ldiffs + sdiffs;	}
            			
		}
		
	}
	catch(exception& e) {
		m->errorOut(e, "SRACommand", "SRACommand");
		exit(1);
	}
}