void load(std::string xmlFilename) {
    if (inputPanelIsLoaded) {
        return;
    }
    inputPanelIsLoaded = true;
    rapidxml::xml_node<>* doc = xmlutils::openXmlDocument(xmlFilename, "inputpanel");
    for (rapidxml::xml_node<>* category : xmlutils::getChildNodes(doc, "category")) {
        std::string categoryName = xmlutils::getAttribute(category, "name");
        inputpanel::addInputCategory(categoryName);
        for (rapidxml::xml_node<>* button : xmlutils::getChildNodes(category, "button")) {
            std::string text = xmlutils::getAttribute(button, "text");
            std::string input = text;
            if (xmlutils::hasAttribute(button, "input")) {
                input = xmlutils::getAttribute(button, "input");
                
                // allow stuff like \n, \\, &quot; from XML to C++
                input = stringReplace(input, "\\n", "\n");
                input = stringReplace(input, "\\t", "\t");
                input = stringReplace(input, "\\r", "\r");
                input = stringReplace(input, "\\f", "\f");
                input = stringReplace(input, "\\\\", "\\");
                input = stringReplace(input, "&nbsp;", " ");
                input = stringReplace(input, "&lt;", "<");
                input = stringReplace(input, "&gt;", ">");
                input = stringReplace(input, "&amp;", "&");
                input = stringReplace(input, "&quot;", "\"");
            }
            inputpanel::addInputButton(text, input);
        }
    }
}
示例#2
0
std::string Unit::printString(const unsigned int mode)
{
    std::string result;
    std::string unicodeExp[10] = {"⁰", "¹", "²", "³", "⁴", "⁵", "⁶", "⁷", "⁸", "⁹"};
    
    if(prefixes != 0)
    {
        std::string strPre = numberToString<int>(prefixes);
        
        if(mode == UNIT_EXP)
        {
            for(int j = 0; j < 10; j++)
            {
                stringReplace(strPre, numberToString<int>(j), unicodeExp[j]);
            }
            
            stringReplace(strPre, "-", "⁻");
            
            result.append("10" + strPre);
        }
        else
        {
            result.append("10^" + strPre);
        }
    }
    
    for(size_t i = 0; i < UNIT_NUMBER_BASE_UNITS; i++)
    {
        if(units[i] == 1)
        {
            result.append(" " + baseUnitList[i]);
        }
        else if(units[i] != 0)
        {
            std::string strExp = numberToString<int>(units[i]);
            
            if(mode == UNIT_EXP)
            {
                for(int j = 0; j < 10; j++)
                {
                    stringReplace(strExp, numberToString<int>(j), unicodeExp[j]);
                }
                
                stringReplace(strExp, "-", "⁻");
                
                result.append(" " + baseUnitList[i] + strExp);
            }
            else
            {
                result.append(" " + baseUnitList[i] + "^" + strExp);
            }
        }
    }
    
    stringTrim(result);
    
    return result;
}
static bool autograderYesOrNo(std::string prompt, std::string reprompt = "", std::string defaultValue = "") {
    if (STATIC_VARIABLE(FLAGS).graphicalUI) {
        prompt = stringReplace(prompt, " (Y/n)", "");
        prompt = stringReplace(prompt, " (y/N)", "");
        prompt = stringReplace(prompt, " (y/n)", "");
        prompt = stringReplace(prompt, " (Y/N)", "");
        return GOptionPane::showConfirmDialog(prompt) == GOptionPane::ConfirmResult::YES;
    } else {
        return getYesOrNo(prompt, reprompt, defaultValue);
    }
}
示例#4
0
void configSave()
{
	wchar_t iniPath[MAX_PATH];
	std::wstring ws;

	getIniFilePath(iniPath, MAX_PATH);

	// Completely delete the file
	DeleteFile(iniPath);

	// [DoxyIt]
	WritePrivateProfileString(NPP_PLUGIN_NAME, TEXT("active_commenting"), BOOLTOSTR(do_active_commenting), iniPath);
	WritePrivateProfileString(NPP_PLUGIN_NAME, TEXT("version"), VERSION_LINEAR_TEXT, iniPath);
	WritePrivateProfileString(NPP_PLUGIN_NAME, TEXT("version_stage"), VERSION_STAGE, iniPath);

	for(auto const &p : parsers)
	{
		const ParserSettings *ps = &(p.ps);

		// Wrap everything in quotes to preserve whitespace
		ws = TEXT("\"") + toWideString(ps->doc_start) + TEXT("\"");
		WritePrivateProfileString(p.lang.c_str(), TEXT("doc_start"), ws.c_str(), iniPath);

		ws = TEXT("\"") + toWideString(ps->doc_line) + TEXT("\"");
		WritePrivateProfileString(p.lang.c_str(), TEXT("doc_line_"), ws.c_str(), iniPath);

		ws = TEXT("\"") + toWideString(ps->doc_end) + TEXT("\"");
		WritePrivateProfileString(p.lang.c_str(), TEXT("doc_end__"), ws.c_str(), iniPath);

		ws = TEXT("\"") + toWideString(ps->command_prefix) + TEXT("\"");
		WritePrivateProfileString(p.lang.c_str(), TEXT("command_prefix"), ws.c_str(), iniPath);

		// Encode \r\n as literal "\r\n" in the ini file
		ws = TEXT("\"") + toWideString(stringReplace(std::string(ps->file_format), "\r\n", "\\r\\n")) + TEXT("\"");
		WritePrivateProfileString(p.lang.c_str(), TEXT("file_format"), ws.c_str(), iniPath);

		// Encode \r\n as literal "\r\n" in the ini file
		ws = TEXT("\"") + toWideString(stringReplace(std::string(ps->function_format), "\r\n", "\\r\\n")) + TEXT("\"");
		WritePrivateProfileString(p.lang.c_str(), TEXT("function_format"), ws.c_str(), iniPath);

		// Write out interal parser attributes
		if(!p.external)
		{
			WritePrivateProfileString(p.lang.c_str(), TEXT("align"), BOOLTOSTR(ps->align), iniPath);
		}
		else // add it to the list of external settings
		{
			WritePrivateProfileString(TEXT("External"), p.language_name.c_str(), TEXT(""), iniPath);
		}
	}
}
示例#5
0
int main()
{
	std::cout << "Text: ";
	char str[DEFAULT_LENGTH];
	std::cin.getline(str, DEFAULT_LENGTH);

	std::cout << "What: ";
	char what[DEFAULT_LENGTH];
	std::cin.getline(what, DEFAULT_LENGTH);

	std::cout << "With: ";
	char with[DEFAULT_LENGTH];
	std::cin.getline(with, DEFAULT_LENGTH);

	std::cout << "Result: ";
	char* result = stringReplace(str, what, with);
	int index = 0;
	while (result[index] != '\0')
	{
		std::cout << result[index];
		index++;
	}

	std::cout << std::endl;

	return 0;
}
示例#6
0
文件: gcc.cpp 项目: Meique/Meique
bool Gcc::shouldCompile(const std::string& source, const std::string& output) const
{
    if (OS::timestampCompare(source, output) < 0)
        return true;

    std::ifstream f((output + ".d").c_str());
    if (!f)
        return true;

    std::string line;
    std::getline(f, line);
    stringReplace(line, output + ": ", "");

    do {
        if (line.length() > 2) {
            if (*line.rbegin() == '\\')
            line.erase(line.length()-2);

            StringList deps = split(line, ' ');
            for (const std::string& dep : deps) {
                if (OS::timestampCompare(dep, output) < 0)
                    return true;
            }
        }
        std::getline(f, line);
        trim(line);
    } while (f);
    return false;
}
static std::string addAutograderButton(GWindow& gui, const std::string& text, const std::string& icon) {
    static Set<char> usedMnemonics;

    std::string html = "<html><center>" + stringReplace(text, "\n", "<br>") + "</center></html>";
    GButton* button = new GButton(html);
    STATIC_VARIABLE(AUTOGRADER_BUTTONS).add(button);

    // set mnemonic shortcut
    char mnemonic = '\0';
    for (int i = 0; i < (int) text.length(); i++) {
        if (isalpha(text[i]) && !usedMnemonics.contains(text[i])) {
            mnemonic = text[i];
            break;
        }
    }
    if (mnemonic) {
        usedMnemonics.add(mnemonic);
        button->setMnemonic(mnemonic);
        button->setAccelerator("ctrl " + charToString(mnemonic));
    }

    if (!icon.empty()) {
        button->setIcon(icon);
        button->setTextPosition(SwingConstants::SWING_CENTER, SwingConstants::SWING_BOTTOM);
    }
    gui.addToRegion(button, "SOUTH");
    return html;
}
示例#8
0
std::string getTimestampString(const std::string & timestampFormat) {
	std::stringstream str;
	auto now = std::chrono::system_clock::now();
	auto t = std::chrono::system_clock::to_time_t(now);
    std::chrono::duration<double> s = now - std::chrono::system_clock::from_time_t(t);
    int ms = s.count() * 1000;
	auto tm = *std::localtime(&t);
	const int bufsize = 256;
	char buf[bufsize];

	// Beware! an invalid timestamp string crashes windows apps.
	// so we have to filter out %i (which is not supported by vs)
	// earlier.

    std::ostringstream msStr;
	msStr << std::fixed << std::setfill('0') << std::setw(3) << ms;

	auto tmpTimestampFormat = timestampFormat;
    tmpTimestampFormat = stringReplace(tmpTimestampFormat, "%i", msStr.str());

	if(strftime(buf,bufsize, tmpTimestampFormat.c_str(),&tm) != 0){
		str << buf;
	}
	auto ret = str.str();

    return ret;
}
示例#9
0
文件: XmlGen.cpp 项目: lzxm160/ngrest
xml::Element& operator<<(xml::Element& elemServices, const Service& service)
{
    xml::Element& elemService = elemServices.createElement("service");

    std::string serviceNs = (service.ns.substr(0, 2) == "::") ?
                service.ns.substr(2) : service.ns;
    stringReplace(serviceNs, "::", ".", true);

    elemService.createElement("name", service.name);
    elemService.createElement("ns", service.ns);
    elemService.createElement("nsName", service.ns + service.name);
    elemService.createElement("serviceNs", serviceNs);
    elemService.createElement("serviceNsName", serviceNs + service.name);
    elemService.createElement("description", service.description);
    elemService.createElement("details", service.details);

    xml::Element& elemOptions = elemService.createElement("options");
    for (StringMap::const_iterator itOption = service.options.begin();
         itOption != service.options.end(); ++itOption)
        elemOptions.createElement(itOption->first, itOption->second);

    xml::Element& elemModules = elemService.createElement("modules");
    for (StringList::const_iterator itModule = service.modules.begin();
         itModule != service.modules.end(); ++itModule)
        elemModules.createElement("module", *itModule);

    elemService.createElement("operations") << service.operations;

    writeCppNs(elemService, service.ns);

    return elemServices;
}
示例#10
0
void styleCheckAddFile(const std::string& filename, const std::string& styleCheckXmlFileName) {
    std::string styleFile = styleCheckXmlFileName;
    if (styleCheckXmlFileName.empty()) {
        // "Foo.cpp" -> "stylecheck-foo-cpp.xml"
        styleFile = toLowerCase(filename);
        styleFile = stringReplace(styleFile, ".", "-");
        styleFile = "stylecheck-" + styleFile + ".xml";
    }
    STATIC_VARIABLE(FLAGS).styleCheckFiles.add(filename);
    STATIC_VARIABLE(FLAGS).styleCheckFileMap.put(filename, styleFile);
}
/*!
 *  pixSetText()
 *
 *      Input:  pix
 *              textstring (can be null)
 *      Return: 0 if OK, 1 on error
 *
 *  Notes:
 *      (1) This removes any existing textstring and puts a copy of
 *          the input textstring there.
 */
l_int32
pixSetText(PIX         *pix,
           const char  *textstring)
{
    PROCNAME("pixSetText");

    if (!pix)
        return ERROR_INT("pix not defined", procName, 1);

    stringReplace(&pix->text, textstring);
    return 0;
}
void SparDiskPanel::updateIntro()
{
	auto typeId = _selectSparBox->getSpar();
	_introSpar = typeId;
	if(typeId <= 0)
	{
		setSelectSparBox(nullptr);
		return;
	}
	
	auto spar = _sparDisk->getSpar(typeId);
	if(spar == nullptr) return;
	auto owner = dynamic_cast<Player*>(_sparDisk->getOwner());
	if(owner == nullptr) return;
	auto sparPatchNum = owner->getItemBag()->getPropSizeByType(2002005);
	_patchNumLab->setString(a2u("ËéƬ:")+cocos2d::Value(sparPatchNum).asString()+a2u("  Éý¼¶ÏûºÄ:")+cocos2d::Value(spar->getCostPatchNum()).asString());

	std::string nickName;
	std::string introduce;
	nickName = spar->getNickName();
	introduce = spar->getModelByName("introduce").asString();

	stringReplace(introduce, "%rate", cocos2d::Value(int(spar->getRate() * 100)).asString()+"%");
	stringReplace(introduce, "%drate", cocos2d::Value(int(spar->getDrate() * 100)).asString()+"%");

	_nickNameLab->setString(nickName);
	_introLab->setString(introduce);

	if(spar->getRate() >= spar->getMaxRate() || spar->getDrate() >= spar->getMaxDrate())
	{
		_completeLab->setVisible(true);
		_refineBtn->setVisible(false);
	}
	else
	{
		_completeLab->setVisible(false);
		_refineBtn->setVisible(true);
	}
}
/*!
 *  pixAddText()
 *
 *      Input:  pix
 *              textstring
 *      Return: 0 if OK, 1 on error
 *
 *  Notes:
 *      (1) This adds the new textstring to any existing text.
 *      (2) Either or both the existing text and the new text
 *          string can be null.
 */
l_int32
pixAddText(PIX         *pix,
           const char  *textstring)
{
char  *newstring;

    PROCNAME("pixAddText");

    if (!pix)
        return ERROR_INT("pix not defined", procName, 1);

    newstring = stringJoin(pixGetText(pix), textstring);
    stringReplace(&pix->text, newstring);
    FREE(newstring);
    return 0;
}
示例#14
0
文件: XmlGen.cpp 项目: lzxm160/ngrest
xml::Element& operator<<(xml::Element& elemInterfaces, const Interface& interface)
{
    xml::Element& elemInterface = elemInterfaces.createElement("interface");

    elemInterface.createElement("name", interface.name);
    elemInterface.createElement("ns", interface.ns);
    elemInterface.createElement("nsName", interface.ns + interface.name);
    elemInterface.createElement("fileName", interface.fileName);
    elemInterface.createElement("filePath", interface.filePath);

    xml::Element& elemOptions = elemInterface.createElement("options");
    for (StringMap::const_iterator itOption = interface.options.begin();
         itOption != interface.options.end(); ++itOption) {
        elemOptions.createElement(itOption->first, itOption->second);
    }

    // included files
    xml::Element& elemIncludes = elemInterface.createElement("includes");
    for (std::list<Include>::const_iterator itInclude = interface.includes.begin();
         itInclude != interface.includes.end(); ++itInclude) {
        std::string ns = itInclude->ns.substr(0, 2) == "::" ? itInclude->ns.substr(2) : itInclude->ns;
        stringReplace(ns, "::", ".", true);

        xml::Element& elemInclude = elemIncludes.createElement("include");
        elemInclude.createElement("name", itInclude->interfaceName);
        elemInclude.createElement("ns", itInclude->ns);
        elemInclude.createElement("nsName", ns + itInclude->interfaceName);
        elemInclude.createElement("fileName", itInclude->fileName);
        elemInclude.createElement("filePath", itInclude->filePath);
//        elemInclude.createElement("targetNs", itInclude->targetNs);
    }

    elemInterface.createElement("enums") << interface.enums;
    elemInterface.createElement("structs") << interface.structs;
    elemInterface.createElement("typedefs") << interface.typedefs;
    elemInterface.createElement("services") << interface.services;

    return elemInterfaces;
}
示例#15
0
std::string escape(std::string str)
{
    return std::move(stringReplace(str, "\"", "\\\""));
}
示例#16
0
void ShaderWriter::writeLights(const vector<InstanceInfo>& instances) {

	m_Shader << "void applySceneLights() {";

	for(size_t i = 0; i < instances.size(); i ++) {

		const InstanceInfo& light = instances[i];
        
        if(light.type != "light" && light.type != "spotlight" && light.type != "ambient" && light.type != "directional")
            continue;
        
		SUVector3D colour = { 1, 1, 1 };

		if(light.value != "") {
			//Parse colour value

			stringstream col(light.value);

			col >> colour.x;
			col >> colour.y;
			col >> colour.z;
		}
        
        string colourExpr = vec3string(colour);
        
        float range = (float)atof(light.getAttribute("range", "20.0").c_str());
        float falloff = (float)atof(light.getAttribute("falloff", "2.0").c_str());
        
		
		SUVector3D dir = yaxis * light.transform;

		SUPoint3D pos = {0};
		pos = (pos * light.transform) / g_Scale;
        string posExpr = vec3string(pos);
		string func = light.getAttribute("func",light.type);

		if(light.hasAttribute("cond")) {
			string cond = stringReplace(light.getAttribute("cond"),"$POS",posExpr);
            m_Shader << "if(" << cond << ") ";
		}

		if(light.type == "ambient") {
			m_Shader << "ambientLight = " << colourExpr << ";";
		}

		if(light.type == "spotlight") {

			float outerCone = (float)atoi(light.getAttribute("outerCone", "40").c_str());
			float innerCone = outerCone - 0.5;
            if(light.hasAttribute("innerCone")) {
                outerCone = (float)atoi(light.getAttribute("innerCone").c_str());
            }
            
            m_Shader << func << "(" << posExpr << "," << vec3string(dir) << "," << colourExpr<< "," << outerCone << "," << innerCone << "," << range << "," << falloff << ");";
		}

		if(light.type == "directional") {
            m_Shader << func << "(" << vec3string(dir) << "," << colourExpr << ");";
		}

		if(light.type == "light") {
			m_Shader << func << "(" << posExpr << "," << colourExpr << ",0.00,"<<range<<"," << falloff << ");";
		}
	
		if(m_Debug) m_Shader << endl;
	}
示例#17
0
void ShaderWriter::includeFile(string filename, string fromFile) {

	if(fileExists(currentDir() + "/"+ filename)){
		filename = currentDir() + "/"+ filename;
	} else if (fileExists(dirName(fromFile) + "/"+ filename)){
		filename = dirName(fromFile) + "/"+ filename;
	} else if (fileExists(shaderDir() + "/"+ filename)){
		filename = shaderDir() + "/"+ filename;
	} else if(!fileExists(filename)) {
		cerr << "Could not find file: " << filename << endl;
		return;
	}

	ifstream file;
	file.open(filename);

	bool inComment = false;

	char _buff[200];
	while(!file.eof()) {
		file.getline(_buff,sizeof(_buff));

		string buff(_buff);
        
		if(!m_Debug) {
			if(buff[buff.size()-1] == '\r') {
				buff[buff.size()-1] =0;
			}

			if(inComment) {
				size_t i = buff.find("*/");
				if(i != -1){
					buff = buff.substr(i+2);
					inComment = false;
				} else {
					buff="";
				}

			}else{ 

				size_t i = buff.find("//");
				if(i != -1) {
					buff = buff.substr(0,i);
				}

				i = buff.find("/*");
				if(i != -1) {
					buff = buff.substr(0,i);
					inComment =true;
				}

				buff = stringReplace(buff,"\t","");
			}
		}

		if(buff.substr(0,8) == "#include"){
			includeFile(string(buff).substr(9),filename);
		}else{
			m_Shader << buff << endl;
		}
	}
}
示例#18
0
int autograderTextMain(int argc, char** argv) {
    std::cout << STATIC_VARIABLE(FLAGS).assignmentName << " Autograder" << std::endl
              << AUTOGRADER_OUTPUT_SEPARATOR << std::endl;
    
    // set up buttons to automatically enter user input
    if (STATIC_VARIABLE(FLAGS).showInputPanel) {
        inputpanel::load(STATIC_VARIABLE(FLAGS).inputPanelFilename);
    }
    
    std::string autogradeYesNoMessage = STATIC_VARIABLE(FLAGS).startMessage;
    if (!autogradeYesNoMessage.empty()) {
        autogradeYesNoMessage += "\n\n";
    }
    autogradeYesNoMessage += "Attempt auto-grading (Y/n)? ";
    
    int result = 0;
    bool autograde = autograderYesOrNo(autogradeYesNoMessage, "", "y");
    if (autograde) {
        if (STATIC_VARIABLE(FLAGS).callbackStart) {
            STATIC_VARIABLE(FLAGS).callbackStart();
        }
        
        result = mainRunAutograderTestCases(argc, argv);
        
        // a hook to allow per-assignment code to run at the start
        if (STATIC_VARIABLE(FLAGS).callbackEnd) {
            STATIC_VARIABLE(FLAGS).callbackEnd();
        }
    }
    
    // manual testing
    bool manualGrade = autograderYesOrNo("Run program for manual testing (y/N)? ", "", "n");
    if (manualGrade) {
        gwindowSetExitGraphicsEnabled(false);
        while (manualGrade) {
            studentMain();
            std::cout << AUTOGRADER_OUTPUT_SEPARATOR << std::endl;
            manualGrade = autograderYesOrNo("Run program again (y/N)? ", "", "n");
        }
        gwindowSetExitGraphicsEnabled(true);
    }
    std::cout << AUTOGRADER_OUTPUT_SEPARATOR << std::endl;
    
    // run any custom callbacks that the assignment's autograder added
    for (int i = 0; i < STATIC_VARIABLE(FLAGS).callbackButtons.size(); i++) {
        std::string buttonText = STATIC_VARIABLE(FLAGS).callbackButtons[i].text;
        buttonText = stringReplace(buttonText, "\n", " ");   // GUI often uses multi-line button text strings; strip
        if (autograderYesOrNo(buttonText + " (Y/n)? ", "", "y")) {
            STATIC_VARIABLE(FLAGS).callbackButtons[i].func();
        }
    }
    
    // run Style Checker to point out common possible style issues
    if (!STATIC_VARIABLE(FLAGS).styleCheckFiles.isEmpty()) {
        if (autograderYesOrNo("Run style checker (Y/n)? ", "", "y")) {
            mainRunStyleChecker();
        }
    }
    
    // display turnin time information to decide late days used
    if (STATIC_VARIABLE(FLAGS).showLateDays) {
        showLateDays();
    }
    
    std::cout << "COMPLETE: Autograder terminated successfully. Exiting." << std::endl;
    return result;
}
示例#19
0
int Unit::set(const std::string &value)
{
    this->clear();
    
    std::string unitString = value;
    stringTrim(unitString);
    
    if(unitString.empty()) return 0;
    
    stringReplace(unitString, "**", "");                   // remove exponentiation symbols
    stringReplace(unitString, "^",  "");
    stringReplace(unitString, "*",  " ");                  // replace multiplication symbols with space for tokenising
    stringReplace(unitString, "/",  " /");                 // pad division symbols with space for tokenising
    while(stringReplace(unitString, "/ ", "/") == 0);      // remove all spaces after division symbols
    
    std::vector<std::string> tokens;
    
    // Tokenise string using spaces:
    if(stringTok(unitString, tokens, " ") != 0)
    {
        std::cerr << "Error (Unit): Failed to tokenise unit string." << std::endl;
        this->clear();
        return 1;
    }
    
    if(tokens.size() < 1)
    {
        std::cerr << "Error (Unit): Failed to tokenise unit string." << std::endl;
        this->clear();
        return 1;
    }
    
    // Loop through all tokens:
    for(size_t i = 0; i < tokens.size(); i++)
    {
        int factorDiv = 1;     // Will become -1 if division sign '/' found.
        int exponent  = 1;     // Exponent of the unit; defaults to 1 if unspecified.
        
        
        // Check for division symbol:
        
        if(tokens[i].substr(0, 1) == "/")
        {
            tokens[i] = tokens[i].substr(1, tokens[i].size() - 1);
            factorDiv = -1;
        }
        
        // Extract exponent:
        
        size_t posExp = tokens[i].find_first_of("+-0123456789");
        
        if(posExp != std::string::npos)
        {
            exponent = stringToNumber<int>(tokens[i].substr(posExp));
        }
        
        exponent *= factorDiv;
        
        // Only proceed if unit is not unity:
        if(exponent != 0 and tokens[i] != "1")
        {
            // Extract base unit and prefix:
            bool success = false;
            
            std::map<std::string, std::vector<int> >::const_iterator iterUnit = unitMap.begin();
            do
            {
                std::map<std::string, int>::const_iterator iterPrefix = prefixMap.begin();
                do
                {
                    std::string searchKey = iterPrefix->first + iterUnit->first;
                    
                    if(searchKey == tokens[i].substr(0, posExp))
                    {
                        success = true;
                        
                        int prefix = iterPrefix->second;
                        std::vector<int> unit(iterUnit->second);
                        
                        // Take care of special case 'kg':
                        if(iterUnit->first == "g") prefix -= 3;
                        
                        for(size_t ii = 0; ii < UNIT_NUMBER_BASE_UNITS; ii++)
                        {
                            units[ii] += unit[ii] * exponent;
                        }
                        
                        prefixes += prefix * exponent;
                    }
                    
                    iterPrefix++;
                }
                while(success == false and iterPrefix != prefixMap.end());
                
                iterUnit++;
            }
            while(success == false and iterUnit != unitMap.end());
            
            if(success == false)
            {
                std::cerr << "Error (Unit): Unknown unit: \'" << value << "\'."   << std::endl;
                std::cerr << "              Creating dimensionless unit instead." << std::endl;
                clear();
                return 1;
            }
        }
    }
    
    return 0;
}
示例#20
0
int autograderGraphicalMain(int argc, char** argv) {
    GWindow gui(500, 300, /* visible */ false);
    gui.setTitle(STATIC_VARIABLE(FLAGS).assignmentName + " Autograder");
    gui.setCanvasSize(0, 0);
    gui.setExitOnClose(true);
    
    GLabel startLabel("");
    if (!STATIC_VARIABLE(FLAGS).startMessage.empty()) {
        std::string startMessage = STATIC_VARIABLE(FLAGS).startMessage;
        if (!stringContains(startMessage, "<html>")) {
            startMessage = stringReplace(startMessage, "Note:", "<b>Note:</b>");
            startMessage = stringReplace(startMessage, "NOTE:", "<b>NOTE:</b>");
            startMessage = "<html><body style='width: 500px; max-width: 500px;'>"
                    + startMessage
                    + "</body></html>";
        }
        
        startLabel.setLabel(startMessage);
        gui.addToRegion(&startLabel, "NORTH");
    }
    
    std::string autogradeText = addAutograderButton(gui, "Automated\ntests", "check.gif");
    std::string manualText = addAutograderButton(gui, "Run\nmanually", "play.gif");
    std::string styleCheckText = addAutograderButton(gui, "Style\nchecker", "magnifier.gif");
    for (int i = 0; i < STATIC_VARIABLE(FLAGS).callbackButtons.size(); i++) {
        STATIC_VARIABLE(FLAGS).callbackButtons[i].text = addAutograderButton(gui, STATIC_VARIABLE(FLAGS).callbackButtons[i].text, STATIC_VARIABLE(FLAGS).callbackButtons[i].icon);
    }
    std::string lateDayText = addAutograderButton(gui, "Late days\ninfo", "calendar.gif");
    std::string aboutText = addAutograderButton(gui, "About\nGrader", "help.gif");
    std::string exitText = addAutograderButton(gui, "Exit\nGrader", "stop.gif");
    gui.pack();
    gui.setVisible(true);
    
    int result = 0;
    while (true) {
        GEvent event = waitForEvent(ACTION_EVENT);
        if (event.getEventClass() == ACTION_EVENT) {
            GActionEvent actionEvent(event);
            std::string cmd = actionEvent.getActionCommand();
            if (cmd == autogradeText) {
                if (STATIC_VARIABLE(FLAGS).callbackStart) {
                    STATIC_VARIABLE(FLAGS).callbackStart();
                }
                
                // stanfordcpplib::getPlatform()->autograderunittest_clearTests();
                stanfordcpplib::getPlatform()->autograderunittest_clearTestResults();
                stanfordcpplib::getPlatform()->autograderunittest_setTestingCompleted(false);
                stanfordcpplib::getPlatform()->autograderunittest_setVisible(true);
                result = mainRunAutograderTestCases(argc, argv);
                stanfordcpplib::getPlatform()->autograderunittest_setTestingCompleted(true);
                
                // if style checker is merged, also run it now
                if (stylecheck::isStyleCheckMergedWithUnitTests()) {
                    mainRunStyleChecker();
                }

                if (STATIC_VARIABLE(FLAGS).callbackEnd) {
                    STATIC_VARIABLE(FLAGS).callbackEnd();
                }
            } else if (cmd == manualText) {
                // set up buttons to automatically enter user input
                if (STATIC_VARIABLE(FLAGS).showInputPanel) {
                    inputpanel::load(STATIC_VARIABLE(FLAGS).inputPanelFilename);
                }
                
                // actually run the student's program
                // (While program is running, if we close console, exit entire
                // autograder program because we might be blocked on console I/O.
                // But after it's done running, set behavior to just hide the
                // console, since the grader will probably try to close it and then
                // proceed with more grading and tests afterward.
                // A little wonky, but it avoids most of the surprise cases of
                // "I closed the student's console and it killed the autograder".
                stanfordcpplib::getPlatform()->jbeconsole_clear();
                stanfordcpplib::getPlatform()->jbeconsole_setVisible(true);
                stanfordcpplib::getPlatform()->jbeconsole_toFront();
                // setConsoleCloseOperation(ConsoleCloseOperation::CONSOLE_EXIT_ON_CLOSE);
                autograder::setExitEnabled(false);   // block exit() call
                setConsoleCloseOperation(ConsoleCloseOperation::CONSOLE_HIDE_ON_CLOSE);

                studentMain();

                // gwindowSetExitGraphicsEnabled(true);
            } else if (cmd == styleCheckText) {
                mainRunStyleChecker();
            } else if (cmd == lateDayText) {
                showLateDays();
            } else if (cmd == aboutText) {
                GOptionPane::showMessageDialog(STATIC_VARIABLE(FLAGS).aboutText, "About Autograder",
                                               GOptionPane::MessageType::INFORMATION);
            } else if (cmd == exitText) {
                autograder::setExitEnabled(true);   // don't block exit() call

                // free up memory used by graphical interactors
                for (GButton* button : STATIC_VARIABLE(AUTOGRADER_BUTTONS)) {
                    delete button;
                }
                STATIC_VARIABLE(AUTOGRADER_BUTTONS).clear();

                gui.close();   // exits program; will not return
                break;
            } else {
                for (CallbackButtonInfo buttonInfo : STATIC_VARIABLE(FLAGS).callbackButtons) {
                    if (cmd == buttonInfo.text) {
                        buttonInfo.func();
                        break;
                    }
                }
            }
        }
    }

    // free up memory used by graphical interactors
    for (GButton* button : STATIC_VARIABLE(AUTOGRADER_BUTTONS)) {
        delete button;
    }
    STATIC_VARIABLE(AUTOGRADER_BUTTONS).clear();
    
    return result;
}
示例#21
0
void configLoad()
{
	wchar_t iniPath[MAX_PATH];
	wchar_t tbuffer[512]; // "relatively" large
	wchar_t tbuffer2[512];
	wchar_t *current;
	ParserSettings ps;

	getIniFilePath(iniPath, MAX_PATH);

	// [DoxyIt]
	GetPrivateProfileString(NPP_PLUGIN_NAME, TEXT("active_commenting"), TEXT("true"), tbuffer, MAX_PATH, iniPath);
	do_active_commenting = (lstrcmp(tbuffer, TEXT("true")) == 0);

	// NPPM_SETMENUITEMCHECK does not seem to work unless the 
	// menu item is actually clicked, so lets do it manually
	if(do_active_commenting) CheckMenuItem(GetMenu(nppData._nppHandle), funcItem[3]._cmdID, MF_CHECKED);

	// Don't need these for now
	//version = GetPrivateProfileInt(NPP_PLUGIN_NAME, TEXT("version"), 0, iniPath);
	//version_stage = GetPrivateProfileString(NPP_PLUGIN_NAME, TEXT("version_stage"), TEXT(""), tbuffer, MAX_PATH, iniPath);

	for(auto &p : parsers)
	{
		// NOTE: We cant use the default value because GetPrivateProfileString strips the whitespace,
		// also, wrapping it in quotes doesn't seem to work either. So...use "!!!" as the default text
		// and if we find that the value wasn't found and we have "!!!" then use the default value in the
		// parser, else, use what we pulled from the file.
		GetPrivateProfileString(p.lang.c_str(), TEXT("doc_start"), TEXT("!!!"), tbuffer, 512, iniPath);
		if(lstrcmp(tbuffer, TEXT("!!!")) != 0) p.ps.doc_start = toString(tbuffer);

		GetPrivateProfileString(p.lang.c_str(), TEXT("doc_line_"), TEXT("!!!"), tbuffer, 512, iniPath);
		if(lstrcmp(tbuffer, TEXT("!!!")) != 0) p.ps.doc_line = toString(tbuffer);

		GetPrivateProfileString(p.lang.c_str(), TEXT("doc_end__"), TEXT("!!!"), tbuffer, 512, iniPath);
		if(lstrcmp(tbuffer, TEXT("!!!")) != 0) p.ps.doc_end = toString(tbuffer);

		GetPrivateProfileString(p.lang.c_str(), TEXT("command_prefix"), TEXT("!!!"), tbuffer, 512, iniPath);
		if(lstrcmp(tbuffer, TEXT("!!!")) != 0) p.ps.command_prefix = toString(tbuffer);

		GetPrivateProfileString(p.lang.c_str(), TEXT("function_format"), TEXT("!!!"), tbuffer, 512, iniPath);
		if(lstrcmp(tbuffer, TEXT("!!!")) != 0) p.ps.function_format = stringReplace(toString(tbuffer), "\\r\\n", "\r\n");

		GetPrivateProfileString(p.lang.c_str(), TEXT("file_format"), TEXT("!!!"), tbuffer, 512, iniPath);
		if(lstrcmp(tbuffer, TEXT("!!!")) != 0) p.ps.file_format = stringReplace(toString(tbuffer), "\\r\\n", "\r\n");

		GetPrivateProfileString(p.lang.c_str(), TEXT("align"), BOOLTOSTR(p.ps.align), tbuffer, 512, iniPath);
		p.ps.align = (lstrcmp(tbuffer, TEXT("true")) == 0);
	}


	GetPrivateProfileSection(TEXT("External"), tbuffer, 512, iniPath);
	current = tbuffer;
	while(current[0] != NULL)
	{
		wchar_t *equals = wcschr(current, TEXT('='));

		// Temporarily remove the '=' that was found
		*equals = NULL;

		GetPrivateProfileString(current, TEXT("doc_start"), TEXT("/**"), tbuffer2, 512, iniPath);
		ps.doc_start = toString(tbuffer2);

		GetPrivateProfileString(current, TEXT("doc_line_"), TEXT(" *  "), tbuffer2, 512, iniPath);
		ps.doc_line = toString(tbuffer2);

		GetPrivateProfileString(current, TEXT("doc_end__"), TEXT(" */"), tbuffer2, 512, iniPath);
		ps.doc_end = toString(tbuffer2);

		GetPrivateProfileString(current, TEXT("command_prefix"), TEXT("\\"), tbuffer2, 512, iniPath);
		ps.command_prefix = toString(tbuffer2);

		GetPrivateProfileString(current, TEXT("function_format"), TEXT("!!!"), tbuffer2, 512, iniPath);
		if(lstrcmp(tbuffer2, TEXT("!!!")) != 0) ps.function_format = stringReplace(toString(tbuffer2), "\\r\\n", "\r\n");
		else ps.function_format = default_internal_function_format;

		GetPrivateProfileString(current, TEXT("file_format"), TEXT("!!!"), tbuffer2, 512, iniPath);
		if(lstrcmp(tbuffer2, TEXT("!!!")) != 0) ps.file_format = stringReplace(toString(tbuffer2), "\\r\\n", "\r\n");
		else ps.file_format = default_file_format;

		addNewParser(toString(current), &ps);

		// add back in the equals so we can correctly calculate the length
		*equals = TEXT('=');

		current = &current[lstrlen(current) + 1];
	}
}
示例#22
0
string CTRSeek(string cipher, string key, string newText, int offset){
	string pt=AES128CTR(cipher, key, newString(NULL,0));
	pt=stringReplace(pt,newText,offset);
	return AES128CTR(pt,key,newString(NULL,0));
}
 CompletionType evaluate()
 {
     Register<Value> value;
     switch (method)
     {
     case ToString:
     case ValueOf:
         if (!getThis()->isObject())
         {
             throw getErrorInstance("TypeError");
         }
         value = static_cast<ObjectValue*>(getThis())->getValueProperty();
         if (!value->isString())
         {
             throw getErrorInstance("TypeError");
         }
         break;
     case CharAt:
         value = charAt();
         break;
     case CharCodeAt:
         value = charCodeAt();
         break;
     case Concat:
         value = concat(getThis());
         break;
     case IndexOf:
         value = indexOf(getThis());
         break;
     case LastIndexOf:
         value = lastIndexOf(getThis());
         break;
     case LocaleCompare:
         value = localeCompare(getThis());
         break;
     case Match:
         value = stringMatch();
         break;
     case Replace:
         value = stringReplace();
         break;
     case Search:
         value = stringSearch();
         break;
     case Slice:
         value = slice(getThis());
         break;
     case Split:
         value = stringSplit();
         break;
     case Substring:
         value = substring(getThis());
         break;
     case Substr:
         value = substr(getThis());
         break;
     case ToLowerCase:
     case ToLocaleLowerCase:
         value = toLowerCase(getThis());
         break;
     case ToUpperCase:
     case ToLocaleUpperCase:
         value = toUpperCase(getThis());
         break;
     }
     return CompletionType(CompletionType::Return, value, "");
 }
示例#24
0
std::string FormatBlock(const ParserDefinition *pd, Keywords& keywords, const std::string &format)
{
	std::stringstream ss;
	std::vector<std::string> lines;
	std::vector<std::string> params = keywords["$PARAM"];
	std::string format_copy(format);
	const char *eol = getEolStr();

	// Replace keywords
	stringReplace(format_copy, "$@", pd->command_prefix);
	stringReplace(format_copy, "$FILENAME", keywords["$FILENAME"][0]);
	
	// $FUNCTION may not exist
	if(keywords.find("$FUNCTION") != keywords.end())
		stringReplace(format_copy, "$FUNCTION", keywords["$FUNCTION"][0]);
	else
		stringReplace(format_copy, "$FUNCTION", "");

	lines = splitLines(format_copy, "\r\n");

	for(unsigned int i = 0; i < lines.size(); ++i)
	{
		if(lines[i].find("$PARAM") != std::string::npos)
		{
			// Duplicate the current line for each $PARAM
			std::vector<std::string> formatted_lines;
			for(unsigned int j = 0; j < params.size(); ++j)
			{
				// Make a copy of lines[i] before calling stringReplace
				std::string line = lines[i];
				stringReplace(line, "$PARAM", params[j]);
				formatted_lines.push_back(line);
			}

			// If the align flag is set, align the lines, else remove all "$|" flags
			if(pd->align)
				alignLines(formatted_lines);
			else
				for(unsigned int j = 0; j < formatted_lines.size(); ++j)
					stringReplace(formatted_lines[j], "$|", "");

			// Insert the lines
			for(unsigned int j = 0; j < formatted_lines.size(); ++j)
			{
				if(i == 0 && j == 0)
					ss << pd->doc_start << formatted_lines[j] << eol;
				else if(i == lines.size() - 1 && j == formatted_lines.size() - 1)
					ss << pd->doc_end << formatted_lines[j] << eol;
				else
					ss << pd->doc_line << formatted_lines[j] << eol;
			}
		}
		else
		{
			if(i == 0)
				ss << pd->doc_start << lines[i] << eol;
			else if(i == lines.size() -1)
				ss << pd->doc_end << lines[i];
			else
				ss << pd->doc_line << lines[i] << eol;
		}
	}

	return ss.str();
}
示例#25
0
/*!
 *  gplotRead()
 *
 *      Input:  filename
 *      Return: gplot, or NULL on error
 */
GPLOT *
gplotRead(const char  *filename)
{
char     buf[L_BUF_SIZE];
char    *rootname, *title, *xlabel, *ylabel, *ignores;
l_int32  outformat, ret, version, ignore;
FILE    *fp;
GPLOT   *gplot;

    PROCNAME("gplotRead");

    if (!filename)
        return (GPLOT *)ERROR_PTR("filename not defined", procName, NULL);

    if ((fp = fopenReadStream(filename)) == NULL)
        return (GPLOT *)ERROR_PTR("stream not opened", procName, NULL);

    ret = fscanf(fp, "Gplot Version %d\n", &version);
    if (ret != 1) {
        fclose(fp);
        return (GPLOT *)ERROR_PTR("not a gplot file", procName, NULL);
    }
    if (version != GPLOT_VERSION_NUMBER) {
        fclose(fp);
        return (GPLOT *)ERROR_PTR("invalid gplot version", procName, NULL);
    }

    ignore = fscanf(fp, "Rootname: %s\n", buf);
    rootname = stringNew(buf);
    ignore = fscanf(fp, "Output format: %d\n", &outformat);
    ignores = fgets(buf, L_BUF_SIZE, fp);   /* Title: ... */
    title = stringNew(buf + 7);
    title[strlen(title) - 1] = '\0';
    ignores = fgets(buf, L_BUF_SIZE, fp);   /* X axis label: ... */
    xlabel = stringNew(buf + 14);
    xlabel[strlen(xlabel) - 1] = '\0';
    ignores = fgets(buf, L_BUF_SIZE, fp);   /* Y axis label: ... */
    ylabel = stringNew(buf + 14);
    ylabel[strlen(ylabel) - 1] = '\0';

    if (!(gplot = gplotCreate(rootname, outformat, title, xlabel, ylabel))) {
        fclose(fp);
        return (GPLOT *)ERROR_PTR("gplot not made", procName, NULL);
    }
    FREE(rootname);
    FREE(title);
    FREE(xlabel);
    FREE(ylabel);
    sarrayDestroy(&gplot->cmddata);
    sarrayDestroy(&gplot->datanames);
    sarrayDestroy(&gplot->plotdata);
    sarrayDestroy(&gplot->plottitles);
    numaDestroy(&gplot->plotstyles);

    ignore = fscanf(fp, "Commandfile name: %s\n", buf);
    stringReplace(&gplot->cmdname, buf);
    ignore = fscanf(fp, "\nCommandfile data:");
    gplot->cmddata = sarrayReadStream(fp);
    ignore = fscanf(fp, "\nDatafile names:");
    gplot->datanames = sarrayReadStream(fp);
    ignore = fscanf(fp, "\nPlot data:");
    gplot->plotdata = sarrayReadStream(fp);
    ignore = fscanf(fp, "\nPlot titles:");
    gplot->plottitles = sarrayReadStream(fp);
    ignore = fscanf(fp, "\nPlot styles:");
    gplot->plotstyles = numaReadStream(fp);

    ignore = fscanf(fp, "Number of plots: %d\n", &gplot->nplots);
    ignore = fscanf(fp, "Output file name: %s\n", buf);
    stringReplace(&gplot->outname, buf);
    ignore = fscanf(fp, "Axis scaling: %d\n", &gplot->scaling);

    fclose(fp);
    return gplot;
}
示例#26
0
int main(int    argc,
         char **argv)
{
char        *str1, *str2;
l_int32      i;
size_t       size1, size2;
l_float32    x, y1, y2, pi;
GPLOT       *gplot1, *gplot2, *gplot3, *gplot4, *gplot5;
NUMA        *nax, *nay1, *nay2;
static char  mainName[] = "plottest";

    if (argc != 1)
        return ERROR_INT(" Syntax:  plottest", mainName, 1);

        /* Generate plot data */
    nax = numaCreate(0);
    nay1 = numaCreate(0);
    nay2 = numaCreate(0);
    pi = 3.1415926535;
    for (i = 0; i < 180; i++) {
        x = (pi / 180.) * i;
        y1 = (l_float32)sin(2.4 * x);
        y2 = (l_float32)cos(2.4 * x);
        numaAddNumber(nax, x);
        numaAddNumber(nay1, y1);
        numaAddNumber(nay2, y2);
    }

        /* Show the plot */
    gplot1 = gplotCreate("/tmp/plotroot1", GPLOT_OUTPUT, "Example plots",
                         "theta", "f(theta)");
    gplotAddPlot(gplot1, nax, nay1, GPLOT_STYLE, "sin (2.4 * theta)");
    gplotAddPlot(gplot1, nax, nay2, GPLOT_STYLE, "cos (2.4 * theta)");
    gplotMakeOutput(gplot1);

        /* Also save the plot to png */
    gplot1->outformat = GPLOT_PNG;
    stringReplace(&gplot1->outname, "/tmp/plotroot1.png");
    gplotMakeOutput(gplot1);

        /* Test gplot serialization */
    gplotWrite("/tmp/gplot1", gplot1);
    if ((gplot2 = gplotRead("/tmp/gplot1")) == NULL)
        return ERROR_INT("gplotRead failure!", mainName, 1);
    gplotWrite("/tmp/gplot2", gplot2);

        /* Are the two written gplot files the same? */
    str1 = (char *)l_binaryRead("/tmp/gplot1", &size1);
    str2 = (char *)l_binaryRead("/tmp/gplot2", &size2);
    if (size1 != size2)
        fprintf(stderr, "Error: size1 = %lu, size2 = %lu\n",
                (unsigned long)size1, (unsigned long)size2);
    else
        fprintf(stderr, "Correct: size1 = size2 = %lu\n", (unsigned long)size1);
    if (strcmp(str1, str2))
        fprintf(stderr, "Error: str1 != str2\n");
    else
        fprintf(stderr, "Correct: str1 == str2\n");
    lept_free(str1);
    lept_free(str2);

        /* Read from file and regenerate the plot */
    gplot3 = gplotRead("/tmp/gplot2");
    stringReplace(&gplot3->title , "Example plots regen");
    gplot3->outformat = GPLOT_X11;
    gplotMakeOutput(gplot3);

        /* Build gplot but do not make the output formatted stuff */
    gplot4 = gplotCreate("/tmp/plotroot2", GPLOT_OUTPUT, "Example plots 2",
                         "theta", "f(theta)");
    gplotAddPlot(gplot4, nax, nay1, GPLOT_STYLE, "sin (2.4 * theta)");
    gplotAddPlot(gplot4, nax, nay2, GPLOT_STYLE, "cos (2.4 * theta)");

        /* Write, read back, and generate the plot */
    gplotWrite("/tmp/gplot4", gplot4);
    if ((gplot5 = gplotRead("/tmp/gplot4")) == NULL)
        return ERROR_INT("gplotRead failure!", mainName, 1);
    gplotMakeOutput(gplot5);

    gplotDestroy(&gplot1);
    gplotDestroy(&gplot2);
    gplotDestroy(&gplot3);
    gplotDestroy(&gplot4);
    gplotDestroy(&gplot5);
    numaDestroy(&nax);
    numaDestroy(&nay1);
    numaDestroy(&nay2);
    return 0;
}