static bool CheckGLSL (bool vertex, bool gles, const std::string& testName, const char* prefix, const std::string& source)
{
#if !GOT_GFX
	return true; // just assume it's ok
#else
	#if !GOT_MORE_THAN_GLSL_120
	if (source.find("#version 140") != std::string::npos)
		return true;
	#endif

	const bool need3 =
		(source.find("#version 150") != std::string::npos) ||
		(source.find("#version 300") != std::string::npos);
	
#	ifdef __APPLE__
	// Mac core context does not accept any older shader versions, so need to switch to
	// either legacy context or core one.
	if (need3)
	{
		if (!s_GL3Active)
			CGLSetCurrentContext(s_GLContext3);
		s_GL3Active = true;
	}
	else
	{
		if (s_GL3Active)
			CGLSetCurrentContext(s_GLContext);
		s_GL3Active = false;
	}
#	endif // ifdef __APPLE__
	
	
	std::string src;
	if (gles)
	{
		src += "#define lowp\n";
		src += "#define mediump\n";
		src += "#define highp\n";
		src += "#define texture2DLodEXT texture2DLod\n";
		src += "#define texture2DProjLodEXT texture2DProjLod\n";
		src += "#define texture2DGradEXT texture2DGradARB\n";
		src += "#define textureCubeGradEXT textureCubeGradARB\n";
		src += "#define gl_FragDepthEXT gl_FragDepth\n";
		if (!need3)
		{
			src += "#define gl_LastFragData _glesLastFragData\n";
			src += "varying lowp vec4 _glesLastFragData[4];\n";
		}
		if (!need3)
		{
			src += "float shadow2DEXT (sampler2DShadow s, vec3 p) { return shadow2D(s,p).r; }\n";
			src += "float shadow2DProjEXT (sampler2DShadow s, vec4 p) { return shadow2DProj(s,p).r; }\n";
		}
	}
	src += source;
	if (gles)
	{
		replace_string (src, "GL_EXT_shader_texture_lod", "GL_ARB_shader_texture_lod", 0);
		replace_string (src, "GL_EXT_draw_instanced", "GL_ARB_draw_instanced", 0);
		replace_string (src, "gl_InstanceIDEXT", "gl_InstanceIDARB	", 0);
		replace_string (src, "#extension GL_OES_standard_derivatives : require", "", 0);
		replace_string (src, "#extension GL_EXT_shadow_samplers : require", "", 0);
		replace_string (src, "#extension GL_EXT_frag_depth : require", "", 0);
		replace_string (src, "#extension GL_OES_standard_derivatives : enable", "", 0);
		replace_string (src, "#extension GL_EXT_shadow_samplers : enable", "", 0);
		replace_string (src, "#extension GL_EXT_frag_depth : enable", "", 0);
		replace_string (src, "#extension GL_EXT_draw_buffers : enable", "", 0);
		replace_string (src, "#extension GL_EXT_draw_buffers : require", "", 0);
		replace_string (src, "precision ", "// precision ", 0);
		replace_string (src, "#version 300 es", "", 0);
	}
	
	// can't check FB fetch on PC
	if (src.find("#extension GL_EXT_shader_framebuffer_fetch") != std::string::npos)
		return true;

	if (gles && need3)
	{
		src = "#version 330\n" + src;
	}
	const char* sourcePtr = src.c_str();

	
	GLuint shader = glCreateShader (vertex ? GL_VERTEX_SHADER : GL_FRAGMENT_SHADER);
	glShaderSource (shader, 1, &sourcePtr, NULL);
	glCompileShader (shader);
	GLint status;
	
	glGetShaderiv (shader, GL_COMPILE_STATUS, &status);
	
	bool res = true;
	if (status != GL_TRUE)
	{
		char log[20000];
		log[0] = 0;
		GLsizei logLength;
		glGetShaderInfoLog (shader, sizeof(log), &logLength, log);
		printf ("\n  %s: real glsl compiler error on %s:\n%s\n", testName.c_str(), prefix, log);
		res = false;
	}
	glDeleteShader (shader);
	return res;
#endif

}
Exemple #2
0
// virtual
LLIOPipe::EStatus LLHTTPResponder::process_impl(
	const LLChannelDescriptors& channels,
	buffer_ptr_t& buffer,
	bool& eos,
	LLSD& context,
	LLPumpIO* pump)
{
	PUMP_DEBUG;
	LLMemType m1(LLMemType::MTYPE_IO_HTTP_SERVER);
	LLIOPipe::EStatus status = STATUS_OK;

	// parsing headers
	if((STATE_NOTHING == mState) || (STATE_READING_HEADERS == mState))
	{
		PUMP_DEBUG;
		status = STATUS_BREAK;
		mState = STATE_READING_HEADERS;
		const S32 HEADER_BUFFER_SIZE = 1024;
		char buf[HEADER_BUFFER_SIZE + 1];  /*Flawfinder: ignore*/
		S32 len = HEADER_BUFFER_SIZE;

#if 0
		if(true)
		{
		LLBufferArray::segment_iterator_t seg_iter = buffer->beginSegment();
		char buf[1024];	  /*Flawfinder: ignore*/
		while(seg_iter != buffer->endSegment())
		{
			memcpy(buf, (*seg_iter).data(), (*seg_iter).size());	  /*Flawfinder: ignore*/
			buf[(*seg_iter).size()] = '\0';
			llinfos << (*seg_iter).getChannel() << ": " << buf
					<< llendl;
			++seg_iter;
		}
		}
#endif
		
		PUMP_DEBUG;
		if(readLine(channels, buffer, (U8*)buf, len))
		{
			bool read_next_line = false;
			bool parse_all = true;
			if(mVerb.empty())
			{
				read_next_line = true;
				LLMemoryStream header((U8*)buf, len);
				header >> mVerb;

				if((HTTP_VERB_GET == mVerb)
				   || (HTTP_VERB_POST == mVerb)
				   || (HTTP_VERB_PUT == mVerb)
				   || (HTTP_VERB_DELETE == mVerb)
				   || (HTTP_VERB_OPTIONS == mVerb))
				{
					header >> mAbsPathAndQuery;
					header >> mVersion;

					lldebugs << "http request: "
							 << mVerb
							 << " " << mAbsPathAndQuery
							 << " " << mVersion << llendl;

					std::string::size_type delimiter
						= mAbsPathAndQuery.find('?');
					if (delimiter == std::string::npos)
					{
						mPath = mAbsPathAndQuery;
						mQuery = "";
					}
					else
					{
						mPath = mAbsPathAndQuery.substr(0, delimiter);
						mQuery = mAbsPathAndQuery.substr(delimiter+1);
					}

					if(!mAbsPathAndQuery.empty())
					{
						if(mVersion.empty())
						{
							// simple request.
							parse_all = false;
							mState = STATE_DONE;
							mVersion.assign("HTTP/1.0");
						}
					}
				}
Exemple #3
0
        virtual void handle( OperationContext* txn,
                             const char *rq, const std::string& url, BSONObj params,
                             string& responseMsg, int& responseCode,
                             vector<string>& headers,  const SockAddr &from ) {

            string::size_type first = url.find( "/" , 1 );
            if ( first == string::npos ) {
                responseCode = 400;
                return;
            }

            string method = MiniWebServer::parseMethod( rq );
            string dbname = url.substr( 1 , first - 1 );
            string coll = url.substr( first + 1 );
            string action = "";

            string::size_type last = coll.find_last_of( "/" );
            if ( last == string::npos ) {
                action = coll;
                coll = "_defaultCollection";
            }
            else {
                action = coll.substr( last + 1 );
                coll = coll.substr( 0 , last );
            }

            for ( string::size_type i=0; i<coll.size(); i++ )
                if ( coll[i] == '/' )
                    coll[i] = '.';

            string fullns = MiniWebServer::urlDecode(dbname + "." + coll);

            headers.push_back( (string)"x-action: " + action );
            headers.push_back( (string)"x-ns: " + fullns );

            bool html = false;

            stringstream ss;

            if ( method == "GET" ) {
                responseCode = 200;
                html = handleRESTQuery( fullns , action , params , responseCode , ss  );
            }
            else if ( method == "POST" ) {
                responseCode = 201;
                handlePost( fullns , MiniWebServer::body( rq ) , params , responseCode , ss  );
            }
            else {
                responseCode = 400;
                headers.push_back( "X_err: bad request" );
                ss << "don't know how to handle a [" << method << "]";
                log() << "don't know how to handle a [" << method << "]" << endl;
            }

            if( html )
                headers.push_back("Content-Type: text/html;charset=utf-8");
            else
                headers.push_back("Content-Type: text/plain;charset=utf-8");

            responseMsg = ss.str();
        }
  void
  xml_compiler::remapclasses_initialize_vector_loader::handle_autogen(const std::string& autogen,
                                                                      const std::string& raw_autogen)
  {
    // ------------------------------------------------------------
    // preprocess
    //

    // MODIFIERFLAG_EITHER_LEFT_OR_RIGHT_*
    {
      static const struct {
        const std::string name;
        const std::string flags[2];
      } info[] = {
        { "MODIFIERFLAG_EITHER_LEFT_OR_RIGHT_COMMAND", { "ModifierFlag::COMMAND_L", "ModifierFlag::COMMAND_R" } },
        { "MODIFIERFLAG_EITHER_LEFT_OR_RIGHT_CONTROL", { "ModifierFlag::CONTROL_L", "ModifierFlag::CONTROL_R" } },
        { "MODIFIERFLAG_EITHER_LEFT_OR_RIGHT_SHIFT",   { "ModifierFlag::SHIFT_L",   "ModifierFlag::SHIFT_R"   } },
        { "MODIFIERFLAG_EITHER_LEFT_OR_RIGHT_OPTION",  { "ModifierFlag::OPTION_L",  "ModifierFlag::OPTION_R"  } },

        // for backwards compatibility
        { "VK_COMMAND", { "ModifierFlag::COMMAND_L", "ModifierFlag::COMMAND_R" } },
        { "VK_CONTROL", { "ModifierFlag::CONTROL_L", "ModifierFlag::CONTROL_R" } },
        { "VK_SHIFT",   { "ModifierFlag::SHIFT_L",   "ModifierFlag::SHIFT_R"   } },
        { "VK_OPTION",  { "ModifierFlag::OPTION_L",  "ModifierFlag::OPTION_R"  } },
      };

      for (const auto& it : info) {
        if (autogen.find(it.name) != std::string::npos) {
          for (const auto& f : it.flags) {
            handle_autogen(boost::replace_all_copy(autogen, it.name, f),
                           raw_autogen);
          }
          return;
        }
      }
    }

    // MODIFIERFLAGS_*
    {
      static const struct {
        const std::string name;
        const std::string flag;
      } info[] = {
        { "MODIFIERFLAGS_CCOS_L",
          "ModifierFlag::COMMAND_L|ModifierFlag::CONTROL_L|ModifierFlag::OPTION_L|ModifierFlag::SHIFT_L" },
        { "MODIFIERFLAGS_CCS_L",
          "ModifierFlag::COMMAND_L|ModifierFlag::CONTROL_L|ModifierFlag::SHIFT_L" },
        { "MODIFIERFLAGS_CCO_L",
          "ModifierFlag::COMMAND_L|ModifierFlag::CONTROL_L|ModifierFlag::OPTION_L" },

        // for backwards compatibility
        { "VK_MOD_CCOS_L", "ModifierFlag::COMMAND_L|ModifierFlag::CONTROL_L|ModifierFlag::OPTION_L|ModifierFlag::SHIFT_L" },
        { "VK_MOD_CCS_L",  "ModifierFlag::COMMAND_L|ModifierFlag::CONTROL_L|ModifierFlag::SHIFT_L" },
        { "VK_MOD_CCO_L",  "ModifierFlag::COMMAND_L|ModifierFlag::CONTROL_L|ModifierFlag::OPTION_L" },
      };
      for (const auto& it : info) {
        if (autogen.find(it.name) != std::string::npos) {
          handle_autogen(boost::replace_all_copy(autogen, it.name, it.flag),
                         raw_autogen);
          return;
        }
      }
    }

    // MODIFIERFLAGS_ANY
    {
      static const struct {
        const std::string name;
      } info[] = {
        "MODIFIERFLAGS_ANY",

        // for backwards compatibility
        "VK_MOD_ANY",
      };
      for (const auto& it : info) {
        if (autogen.find(it.name) != std::string::npos) {
          // Making combination at the first time. (reuse it since 2nd time.)
          static std::vector<std::shared_ptr<std::vector<std::string> > > combination;
          if (combination.empty()) {
            // to reduce combination, we ignore same modifier combination such as (COMMAND_L | COMMAND_R).
            const char* seeds[] = { "MODIFIERFLAG_EITHER_LEFT_OR_RIGHT_COMMAND",
                                    "MODIFIERFLAG_EITHER_LEFT_OR_RIGHT_CONTROL",
                                    "ModifierFlag::FN",
                                    "MODIFIERFLAG_EITHER_LEFT_OR_RIGHT_OPTION",
                                    "MODIFIERFLAG_EITHER_LEFT_OR_RIGHT_SHIFT" };
            pqrs::vector::make_combination(combination, seeds, sizeof(seeds) / sizeof(seeds[0]));
          }

          for (const auto& v : combination) {
            handle_autogen(boost::replace_all_copy(autogen, it.name, boost::join(*v, "|") + "|ModifierFlag::NONE"),
                           raw_autogen);
          }
          return;
        }
      }
    }

    // FROMKEYCODE_HOME, FROMKEYCODE_END, ...
    {
      struct preprocess_info {
        std::string fromkeycode;                   // FROMKEYCODE_HOME
        std::string fromkeycode_with_modifierflag; // FROMKEYCODE_HOME,ModifierFlag::
        std::string fromkeycode_with_comma;        // FROMKEYCODE_HOME,
        std::string keycode;                       // KeyCode::HOME
        std::string other_keycode_with_fn_pipe;    // KeyCode::CURSOR_LEFT,ModifierFlag::FN|
        std::string other_keycode_with_fn;         // KeyCode::CURSOR_LEFT,ModifierFlag::FN
      };
      static std::vector<preprocess_info> info;
      // initialize info
      if (info.empty()) {
        const char* keys[][2] = {
          { "HOME",           "CURSOR_LEFT"  },
          { "END",            "CURSOR_RIGHT" },
          { "PAGEUP",         "CURSOR_UP"    },
          { "PAGEDOWN",       "CURSOR_DOWN"  },
          { "FORWARD_DELETE", "DELETE"       },
        };
        for (const auto& k : keys) {
          preprocess_info i;
          i.fromkeycode                   = std::string("FROMKEYCODE_") + k[0];
          i.fromkeycode_with_modifierflag = std::string("FROMKEYCODE_") + k[0] + ",ModifierFlag::";
          i.fromkeycode_with_comma        = std::string("FROMKEYCODE_") + k[0] + ",";
          i.keycode                       = std::string("KeyCode::") + k[0];
          i.other_keycode_with_fn_pipe    = std::string("KeyCode::") + k[1] + ",ModifierFlag::FN|";
          i.other_keycode_with_fn         = std::string("KeyCode::") + k[1] + ",ModifierFlag::FN";
          info.push_back(i);
        }
      }

      for (const auto& it : info) {
        // FROMKEYCODE_HOME,ModifierFlag::
        if (autogen.find(it.fromkeycode_with_modifierflag) != std::string::npos) {
          // FROMKEYCODE_HOME -> KeyCode::HOME
          handle_autogen(boost::replace_all_copy(autogen, it.fromkeycode, it.keycode),
                         raw_autogen);
          // FROMKEYCODE_HOME, -> KeyCode::CURSOR_LEFT,ModifierFlag::FN|
          handle_autogen(boost::replace_all_copy(autogen, it.fromkeycode_with_comma, it.other_keycode_with_fn_pipe),
                         raw_autogen);
          return;
        }
        // FROMKEYCODE_HOME (without ModifierFlag)
        if (autogen.find(it.fromkeycode) != std::string::npos) {
          // FROMKEYCODE_HOME -> KeyCode::HOME
          handle_autogen(boost::replace_all_copy(autogen, it.fromkeycode, it.keycode),
                         raw_autogen);
          // FROMKEYCODE_HOME -> KeyCode::CURSOR_LEFT,ModifierFlag::FN
          handle_autogen(boost::replace_all_copy(autogen, it.fromkeycode, it.other_keycode_with_fn),
                         raw_autogen);
          return;
        }
      }
    }

    // ------------------------------------------------------------
    // For compatibility
    if (boost::starts_with(autogen, "__KeyOverlaidModifierWithRepeat__")) {
      handle_autogen(boost::replace_first_copy(autogen,
                                               "__KeyOverlaidModifierWithRepeat__",
                                               "__KeyOverlaidModifier__Option::KEYOVERLAIDMODIFIER_REPEAT,"),
                     raw_autogen);
      return;
    }

    if (boost::starts_with(autogen, "__StripModifierFromScrollWheel__")) {
      handle_autogen(boost::replace_first_copy(autogen,
                                               "__StripModifierFromScrollWheel__",
                                               "__ScrollWheelToScrollWheel__") + ",ModifierFlag::NONE",
                     raw_autogen);
      return;
    }

    // ------------------------------------------------------------
    // add to remapclasses_initialize_vector_
    //

    {
      static const std::string symbol("__ShowStatusMessage__");
      if (boost::starts_with(autogen, symbol)) {
        std::string params = autogen.substr(symbol.length());
        boost::trim(params);

        size_t length = params.size();
        remapclasses_initialize_vector_.push_back(static_cast<uint32_t>(length + 1));
        remapclasses_initialize_vector_.push_back(BRIDGE_STATUSMESSAGE);

        for (const auto& c : params) {
          remapclasses_initialize_vector_.push_back(c);
        }
        // no need filter_vector
        return;
      }
    }

    {
      static const std::string symbol("__SimultaneousKeyPresses__");
      if (boost::starts_with(autogen, symbol)) {
        std::string params = autogen.substr(symbol.length());
        std::string newkeycode = std::string("VK_SIMULTANEOUSKEYPRESSES_") +
                                 boost::lexical_cast<std::string>(simultaneous_keycode_index_);
        symbol_map_.add("KeyCode", newkeycode);
        ++simultaneous_keycode_index_;

        params = std::string("KeyCode::") + newkeycode + "," + params;
        add_to_initialize_vector(params, BRIDGE_REMAPTYPE_SIMULTANEOUSKEYPRESSES);
        return;
      }
    }

    static const struct {
      const std::string symbol;
      uint32_t type;
    } info[] = {
      { "__KeyToKey__",                       BRIDGE_REMAPTYPE_KEYTOKEY },
      { "__KeyToConsumer__",                  BRIDGE_REMAPTYPE_KEYTOKEY }, // for backwards compatibility
      { "__KeyToPointingButton__",            BRIDGE_REMAPTYPE_KEYTOKEY }, // for backwards compatibility
      { "__DoublePressModifier__",            BRIDGE_REMAPTYPE_DOUBLEPRESSMODIFIER },
      { "__HoldingKeyToKey__",                BRIDGE_REMAPTYPE_HOLDINGKEYTOKEY },
      { "__IgnoreMultipleSameKeyPress__",     BRIDGE_REMAPTYPE_IGNOREMULTIPLESAMEKEYPRESS },
      { "__KeyOverlaidModifier__",            BRIDGE_REMAPTYPE_KEYOVERLAIDMODIFIER },
      { "__ConsumerToConsumer__",             BRIDGE_REMAPTYPE_KEYTOKEY }, // for backwards compatibility
      { "__ConsumerToKey__",                  BRIDGE_REMAPTYPE_KEYTOKEY }, // for backwards compatibility
      { "__PointingButtonToPointingButton__", BRIDGE_REMAPTYPE_KEYTOKEY }, // for backwards compatibility
      { "__PointingButtonToKey__",            BRIDGE_REMAPTYPE_KEYTOKEY }, // for backwards compatibility
      { "__PointingRelativeToKey__",          BRIDGE_REMAPTYPE_POINTINGRELATIVETOKEY },
      { "__PointingRelativeToScroll__",       BRIDGE_REMAPTYPE_POINTINGRELATIVETOSCROLL },
      { "__DropKeyAfterRemap__",              BRIDGE_REMAPTYPE_DROPKEYAFTERREMAP },
      { "__SetKeyboardType__",                BRIDGE_REMAPTYPE_SETKEYBOARDTYPE },
      { "__ForceNumLockOn__",                 BRIDGE_REMAPTYPE_FORCENUMLOCKON },
      { "__DropPointingRelativeCursorMove__", BRIDGE_REMAPTYPE_DROPPOINTINGRELATIVECURSORMOVE },
      { "__DropScrollWheel__",                BRIDGE_REMAPTYPE_DROPSCROLLWHEEL },
      { "__FlipPointingRelative__",           BRIDGE_REMAPTYPE_FLIPPOINTINGRELATIVE },
      { "__FlipScrollWheel__",                BRIDGE_REMAPTYPE_FLIPSCROLLWHEEL },
      { "__ScrollWheelToScrollWheel__",       BRIDGE_REMAPTYPE_SCROLLWHEELTOSCROLLWHEEL },
      { "__ScrollWheelToKey__",               BRIDGE_REMAPTYPE_SCROLLWHEELTOKEY },
    };
    for (const auto& it : info) {
      if (boost::starts_with(autogen, it.symbol)) {
        std::string params = autogen.substr(it.symbol.length());
        add_to_initialize_vector(params, it.type);
        return;
      }
    }

    throw xml_compiler_runtime_error(boost::format("Invalid <autogen>:\n"
                                                   "\n"
                                                   "<autogen>%1%</autogen>") %
                                     raw_autogen);
  }
bool ZLXMLReader::BrokenNamePredicate::accepts(const ZLXMLReader &reader, const std::string &name) const {
	return myName == name.substr(name.find(':') + 1);
}
	bool Helper4::isType(const std::string& type, const std::string& entity_types)const
	{
		return (std::string::npos != entity_types.find(type));
	}
double task4_6::solution::calculate_rpn( const std::string& rpn_expression )
{
     std::stack< double > calc_stack;
     std::istringstream input( rpn_expression );
     std::string token;
     vars_map::iterator it;
     while( input >> token )
     {
         if( token.length() == 1 && operators.find( token[0] ) != token.npos )
         {
             // token is operator
             double r = 0;

             if( calc_stack.empty() )
             {
                 throw std::logic_error( "not correct expression at %1% line" );
             }
             double y = calc_stack.top();
             calc_stack.pop();

             if( calc_stack.empty() )
             {
                 throw std::logic_error( "not correct expression at %1% line" );
             }
             double x = calc_stack.top();
             calc_stack.pop();
             switch ( token[0] )
             {
             case '+': r = x + y; break;
             case '-': r = x - y; break;
             case '*': r = x * y; break;
             case '/': r = x / y;
                 if ( y == 0 )
                 {
                     throw std::logic_error( "zero div (%1%)" );
                 }
                 break;
             default:
                 throw std::logic_error( "not correct expression at %1% line" );
             }
             calc_stack.push( r );
         }
         else if( ( it = vars_.find( token ) ) != vars_.end() )
         {
              // token is var
             calc_stack.push( it->second );
         }
         else
         {
             // maybe token is number
             try
             {
                 calc_stack.push( boost::lexical_cast<double>( token ) );
             }
             catch ( const boost::bad_lexical_cast& )
             {
             	 throw std::logic_error(
                     ( boost::format( "'%1%' variable not defined at line %2%" )
                     % token % "%1%" ).str() );
             }
         }
     }
     if( calc_stack.empty() )
     {
         throw std::logic_error( "not correct expression at %1% line" );
     }
     return calc_stack.top();
}
Exemple #8
0
int eServiceWebTS::openHttpConnection(std::string url)
{
	std::string host;
	int port = 80;
	std::string uri;

	int slash = url.find("/", 7);
	if (slash > 0) {
		host = url.substr(7, slash-7);
		uri = url.substr(slash, url.length()-slash);
	} else {
		host = url.substr(7, url.length()-7);
		uri = "";
	}
	int dp = host.find(":");
	if (dp == 0) {
		port = atoi(host.substr(1, host.length()-1).c_str());
		host = "localhost";
	} else if (dp > 0) {
		port = atoi(host.substr(dp+1, host.length()-dp-1).c_str());
		host = host.substr(0, dp);
	}

	struct hostent* h = gethostbyname(host.c_str());
	if (h == NULL || h->h_addr_list == NULL)
		return -1;
	int fd = socket(PF_INET, SOCK_STREAM, 0);
	if (fd == -1)
		return -1;

	struct sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = *((in_addr_t*)h->h_addr_list[0]);
	addr.sin_port = htons(port);

	eDebug("connecting to %s", url.c_str());

	if (connect(fd, (sockaddr*)&addr, sizeof(addr)) == -1) {
		std::string msg = "connect failed for: " + url;
		eDebug(msg.c_str());
		return -1;
	}

	std::string request = "GET ";
	request.append(uri).append(" HTTP/1.1\r\n");
	request.append("Host: ").append(host).append("\r\n");
	request.append("Accept: */*\r\n");
	request.append("Connection: close\r\n");
	request.append("\r\n");
	//eDebug(request.c_str());
	write(fd, request.c_str(), request.length());

	int rc;
	size_t buflen = 1000;
	char* linebuf = (char*)malloc(1000);

	rc = getline(&linebuf, &buflen, fd);
	//eDebug("RECV(%d): %s", rc, linebuf);
	if (rc <= 0)
	{
		close(fd);
		free(linebuf);
		return -1;
	}

	char proto[100];
	int statuscode = 0;
	char statusmsg[100];
	rc = sscanf(linebuf, "%99s %d %99s", proto, &statuscode, statusmsg);
	if (rc != 3 || statuscode != 200) {
		eDebug("wrong response: \"200 OK\" expected.\n %d --- %d",rc,statuscode);
		free(linebuf);
		close(fd);
		return -1;
	}
	eDebug("proto=%s, code=%d, msg=%s", proto, statuscode, statusmsg);
	while (rc > 0)
	{
		rc = getline(&linebuf, &buflen, fd);
		//eDebug("RECV(%d): %s", rc, linebuf);
	}
	free(linebuf);

	return fd;
}
bool ShaderInfoHelper::buildShaderInfo(const ImagineRendererInfo& iri, FnKat::GroupBuilder& rendererObjectInfo, const std::string& name,
								  const FnKat::GroupAttribute inputAttr)
{
	std::vector<std::string> typeTags;
	std::string location = name;
	std::string fullPath;

	FnKat::Attribute containerHintsAttribute;

	typeTags.push_back("surface");
	typeTags.push_back("op");
	typeTags.push_back("texture");
	typeTags.push_back("bump");
	typeTags.push_back("medium");
	typeTags.push_back("displacement");
	typeTags.push_back("alpha");
	typeTags.push_back("light");

	Foundry::Katana::RendererInfo::RendererInfoBase::configureBasicRenderObjectInfo(rendererObjectInfo, kFnRendererObjectTypeShader,
																					typeTags, location, fullPath,
																					kFnRendererObjectValueTypeUnknown, containerHintsAttribute);

	std::string buildName;
	std::string typeName; // for network materials
	if (name.find("/") == std::string::npos)
	{
		// just a single standard material
		buildName = name;
	}
	else
	{
		// ImagineShadingNode item, so split out the two items from the name
		size_t sepPos = name.find("/");
		typeName = name.substr(0, sepPos);
		buildName = name.substr(sepPos + 1);
	}

	if (buildName == "Standard")
	{
		buildStandardShaderParams(iri, rendererObjectInfo);
	}
	else if (buildName == "StandardImage")
	{
		buildStandardImageShaderParams(iri, rendererObjectInfo);
	}
	else if (buildName == "Glass")
	{
		buildGlassShaderParams(iri, rendererObjectInfo);
	}
	else if (buildName == "Metal")
	{
		buildMetalShaderParams(iri, rendererObjectInfo);
	}
	else if (buildName == "Plastic")
	{
		buildPlasticShaderParams(iri, rendererObjectInfo);
	}
	else if (buildName == "Brushed Metal")
	{
		buildBrushedMetalShaderParams(iri, rendererObjectInfo);
	}
	else if (buildName == "Metallic Paint")
	{
		buildMetallicPaintShaderParams(iri, rendererObjectInfo);
	}
	else if (buildName == "Translucent")
	{
		buildTranslucentShaderParams(iri, rendererObjectInfo);
	}
	else if (buildName == "Velvet")
	{
		buildVelvetShaderParams(iri, rendererObjectInfo);
	}
	else if (buildName == "Luminous")
	{
		buildLuminousShaderParams(iri, rendererObjectInfo);
	}
	// lights
	else if (buildName == "Point")
	{
		buildPointLightShaderParams(iri, rendererObjectInfo);
	}
	else if (buildName == "Spot")
	{
		buildSpotLightShaderParams(iri, rendererObjectInfo);
	}
	else if (buildName == "Area")
	{
		buildAreaLightShaderParams(iri, rendererObjectInfo);
	}
	else if (buildName == "Distant")
	{
		buildDistantLightShaderParams(iri, rendererObjectInfo);
	}
	else if (buildName == "SkyDome")
	{
		buildSkydomeLightShaderParams(iri, rendererObjectInfo);
	}
	else if (buildName == "Environment")
	{
		buildEnvironmentLightShaderParams(iri, rendererObjectInfo);
	}
	else if (buildName == "PhysicalSky")
	{
		buildPhysicalSkyLightShaderParams(iri, rendererObjectInfo);
	}


	//
	else if (buildName == "ImageTextureBump")
	{
		buildBumpTextureShaderParams(iri, rendererObjectInfo);
	}
	else if (buildName == "ImageTextureAlpha")
	{
		buildAlphaTextureShaderParams(iri, rendererObjectInfo);
	}

	if (typeName == "Texture")
	{
		if (buildName == "Constant")
		{
			buildConstantTextureParams(iri, rendererObjectInfo);
		}
		else if (buildName == "Checkerboard")
		{
			buildCheckerboardTextureParams(iri, rendererObjectInfo);
		}
		else if (buildName == "Grid")
		{
			buildGridTextureParams(iri, rendererObjectInfo);
		}
		else if (buildName == "Swatch")
		{
			buildSwatchTextureParams(iri, rendererObjectInfo);
		}
		else if (buildName == "TextureRead")
		{
			buildWireframeTextureParams(iri, rendererObjectInfo);
		}
		else if (buildName == "Wireframe")
		{
			buildWireframeTextureParams(iri, rendererObjectInfo);
		}
	}
	else if (typeName == "Op")
	{
		if (buildName == "Adjust")
		{
			buildAdjustOpParams(iri, rendererObjectInfo);
		}
		else if (buildName == "Mix")
		{
			buildMixOpParams(iri, rendererObjectInfo);
		}
	}

	return true;
}
Exemple #10
0
std::string
strip( const std::string & func ) 
{
  size_t pos = func.find( "test" );
  return func.substr( pos, func.length() - pos - 2 );
}
Exemple #11
0
std::string GetTerm(std::string l)
{
    size_t found=l.find("=");
    if(found==string::npos) return l;
    else return l.substr(0, found);
}
Exemple #12
0
static void getIncomingVars(
	std::unordered_multimap<std::string, std::string> &params,
	const std::string &uri
) {
	const size_t start = uri.find('?');

	if (std::string::npos == start) {
		return;
	}

	const size_t finish = uri.find('#');

	if (finish < start) {
		return;
	}

	for (
		size_t var_pos = start + 1, var_end = 0;
		std::string::npos != var_end;
		var_pos = var_end + 1
	) {
		var_end = uri.find('&', var_pos);

		if (var_end > finish) {
			var_end = std::string::npos;
		}

		size_t delimiter = uri.find('=', var_pos);

		if (delimiter >= var_end) {
			std::string var_name = Utils::urlDecode(
				uri.substr(
					var_pos,
					std::string::npos != var_end
						? var_end - var_pos
						: std::string::npos
				)
			);

			params.emplace(
				std::move(var_name),
				std::string()
			);
		} else {
			std::string var_name = Utils::urlDecode(
				uri.substr(
					var_pos,
					delimiter - var_pos
				)
			);

			++delimiter;

			std::string var_value = Utils::urlDecode(
				uri.substr(
					delimiter,
					std::string::npos != var_end
						? var_end - delimiter
						: std::string::npos
				)
			);

			params.emplace(
				std::move(var_name),
				std::move(var_value)
			);
		}
	}
}
void SystemData::populateFolder(FileData* folder)
{
	const fs::path& folderPath = folder->getPath();
	if(!fs::is_directory(folderPath))
	{
		LOG(LogWarning) << "Error - folder with path \"" << folderPath << "\" is not a directory!";
		return;
	}

	const std::string folderStr = folderPath.generic_string();

	//make sure that this isn't a symlink to a thing we already have
	if(fs::is_symlink(folderPath))
	{
		//if this symlink resolves to somewhere that's at the beginning of our path, it's gonna recurse
		if(folderStr.find(fs::canonical(folderPath).generic_string()) == 0)
		{
			LOG(LogWarning) << "Skipping infinitely recursive symlink \"" << folderPath << "\"";
			return;
		}
	}

	fs::path filePath;
	std::string extension;
	bool isGame;
	for(fs::directory_iterator end, dir(folderPath); dir != end; ++dir)
	{
		filePath = (*dir).path();

		if(filePath.stem().empty())
			continue;

		//this is a little complicated because we allow a list of extensions to be defined (delimited with a space)
		//we first get the extension of the file itself:
		extension = filePath.extension().string();
		
		//fyi, folders *can* also match the extension and be added as games - this is mostly just to support higan
		//see issue #75: https://github.com/Aloshi/EmulationStation/issues/75

		isGame = false;
		if(std::find(mSearchExtensions.begin(), mSearchExtensions.end(), extension) != mSearchExtensions.end())
		{
			FileData* newGame = new FileData(GAME, filePath.generic_string(), this);
			folder->addChild(newGame);
			isGame = true;
		}

		//add directories that also do not match an extension as folders
		if(!isGame && fs::is_directory(filePath))
		{
			FileData* newFolder = new FileData(FOLDER, filePath.generic_string(), this);
			populateFolder(newFolder);

			//ignore folders that do not contain games
			if(newFolder->getChildren().size() == 0)
				delete newFolder;
			else
				folder->addChild(newFolder);
		}
	}
}
Exemple #14
0
    Status MMAPV1Engine::repairDatabase( OperationContext* txn,
                                         const std::string& dbName,
                                         bool preserveClonedFilesOnFailure,
                                         bool backupOriginalFiles ) {
        // We must hold some form of lock here
        invariant(txn->lockState()->threadState());
        invariant( dbName.find( '.' ) == string::npos );

        scoped_ptr<RepairFileDeleter> repairFileDeleter;
        doingRepair dr;

        log() << "repairDatabase " << dbName << endl;

        BackgroundOperation::assertNoBgOpInProgForDb(dbName);

        txn->recoveryUnit()->syncDataAndTruncateJournal(); // Must be done before and after repair

        intmax_t totalSize = dbSize( dbName );
        intmax_t freeSize = File::freeSpace(storageGlobalParams.repairpath);

        if ( freeSize > -1 && freeSize < totalSize ) {
            return Status( ErrorCodes::OutOfDiskSpace,
                           str::stream() << "Cannot repair database " << dbName
                           << " having size: " << totalSize
                           << " (bytes) because free disk space is: " << freeSize << " (bytes)" );
        }

        txn->checkForInterrupt();

        Path reservedPath =
            uniqueReservedPath( ( preserveClonedFilesOnFailure || backupOriginalFiles ) ?
                                "backup" : "_tmp" );
        MONGO_ASSERT_ON_EXCEPTION( boost::filesystem::create_directory( reservedPath ) );
        string reservedPathString = reservedPath.string();

        if ( !preserveClonedFilesOnFailure )
            repairFileDeleter.reset( new RepairFileDeleter( txn,
                                                            dbName,
                                                            reservedPathString,
                                                            reservedPath ) );

        {
            Database* originalDatabase =
                            dbHolder().get(txn, dbName);
            if (originalDatabase == NULL) {
                return Status(ErrorCodes::NamespaceNotFound, "database does not exist to repair");
            }

            scoped_ptr<Database> tempDatabase;
            {
                MMAPV1DatabaseCatalogEntry* entry =
                    new MMAPV1DatabaseCatalogEntry( txn,
                                                    dbName,
                                                    reservedPathString,
                                                    storageGlobalParams.directoryperdb,
                                                    true );
                invariant( !entry->exists() );
                tempDatabase.reset( new Database( txn,
                                                  dbName,
                                                  entry ) );

            }

            map<string,CollectionOptions> namespacesToCopy;
            {
                string ns = dbName + ".system.namespaces";
                Client::Context ctx(txn,  ns );
                Collection* coll = originalDatabase->getCollection( txn, ns );
                if ( coll ) {
                    scoped_ptr<RecordIterator> it( coll->getIterator( DiskLoc(),
                                                                          false,
                                                                          CollectionScanParams::FORWARD ) );
                    while ( !it->isEOF() ) {
                        DiskLoc loc = it->getNext();
                        BSONObj obj = coll->docFor( loc );

                        string ns = obj["name"].String();

                        NamespaceString nss( ns );
                        if ( nss.isSystem() ) {
                            if ( nss.isSystemDotIndexes() )
                                continue;
                            if ( nss.coll() == "system.namespaces" )
                                continue;
                        }

                        if ( !nss.isNormal() )
                            continue;

                        CollectionOptions options;
                        if ( obj["options"].isABSONObj() ) {
                            Status status = options.parse( obj["options"].Obj() );
                            if ( !status.isOK() )
                                return status;
                        }
                        namespacesToCopy[ns] = options;
                    }
                }
            }

            for ( map<string,CollectionOptions>::const_iterator i = namespacesToCopy.begin();
                  i != namespacesToCopy.end();
                  ++i ) {
                string ns = i->first;
                CollectionOptions options = i->second;

                Collection* tempCollection = NULL;
                {
                    Client::Context tempContext(txn, ns, tempDatabase );
                    tempCollection = tempDatabase->createCollection( txn, ns, options, true, false );
                }

                Client::Context readContext(txn, ns, originalDatabase);
                Collection* originalCollection = originalDatabase->getCollection( txn, ns );
                invariant( originalCollection );

                // data

                MultiIndexBlock indexBlock(txn, tempCollection );
                {
                    vector<BSONObj> indexes;
                    IndexCatalog::IndexIterator ii =
                        originalCollection->getIndexCatalog()->getIndexIterator( false );
                    while ( ii.more() ) {
                        IndexDescriptor* desc = ii.next();
                        indexes.push_back( desc->infoObj() );
                    }

                    Client::Context tempContext(txn, ns, tempDatabase);
                    Status status = indexBlock.init( indexes );
                    if ( !status.isOK() )
                        return status;

                }

                scoped_ptr<RecordIterator> iterator( originalCollection->getIterator( DiskLoc(),
                                                                                          false,
                                                                                          CollectionScanParams::FORWARD ) );
                while ( !iterator->isEOF() ) {
                    DiskLoc loc = iterator->getNext();
                    invariant( !loc.isNull() );

                    BSONObj doc = originalCollection->docFor( loc );

                    Client::Context tempContext(txn, ns, tempDatabase);
                    StatusWith<DiskLoc> result = tempCollection->insertDocument( txn, doc, indexBlock );
                    if ( !result.isOK() )
                        return result.getStatus();

                    txn->recoveryUnit()->commitIfNeeded();
                    txn->checkForInterrupt(false);
                }

                {
                    Client::Context tempContext(txn, ns, tempDatabase);
                    Status status = indexBlock.commit();
                    if ( !status.isOK() )
                        return status;
                }

            }

            txn->recoveryUnit()->syncDataAndTruncateJournal();
            globalStorageEngine->flushAllFiles(true); // need both in case journaling is disabled

            txn->checkForInterrupt(false);
        }

        // at this point if we abort, we don't want to delete new files
        // as they might be the only copies

        if ( repairFileDeleter.get() )
            repairFileDeleter->success();

        Client::Context ctx(txn, dbName);
        Database::closeDatabase(txn, dbName);

        if ( backupOriginalFiles ) {
            _renameForBackup( dbName, reservedPath );
        }
        else {
            // first make new directory before deleting data
            Path newDir = Path(storageGlobalParams.dbpath) / dbName;
            MONGO_ASSERT_ON_EXCEPTION(boost::filesystem::create_directory(newDir));

            // this deletes old files
            _deleteDataFiles( dbName );

            if ( !boost::filesystem::exists(newDir) ) {
                // we deleted because of directoryperdb
                // re-create
                MONGO_ASSERT_ON_EXCEPTION(boost::filesystem::create_directory(newDir));
            }
        }

        _replaceWithRecovered( dbName, reservedPathString.c_str() );

        if ( !backupOriginalFiles )
            MONGO_ASSERT_ON_EXCEPTION( boost::filesystem::remove_all( reservedPath ) );

        return Status::OK();
    }
Exemple #15
0
/****** Replace substring 'from' to 'to' in string 'str' ******/
bool StrReplace(std::string& str, const std::string& from, const std::string& to) {
    size_t start_pos = str.find(from);
    if(start_pos == std::string::npos) return false;
    str.replace(start_pos, from.length(), to);
    return true;
}
GEOMap
GEOGSEParser::readGSEFile(const std::string& filename)
{
	GEOMap result;
	std::map<std::string, std::vector<double>> clone2expression_values;
	std::string gsm = "";
	bool within_sample_table = false;

	std::ifstream file(filename.c_str(),
	                   std::ios_base::in | std::ios_base::binary);
	if(!file) {
		std::cerr << "ERROR: Cannot open file: " << filename << std::endl;
		return result;
	}

	boost::iostreams::filtering_istream input;
	if(filename.find(".gz") != std::string::npos) {
		input.push(boost::iostreams::gzip_decompressor());
		input.push(file);
	} else {
		input.push(file);
	}

	int value_idx = -1;
	for(std::string line; std::getline(input, line);) {
		if(line != "") {
			if(boost::starts_with(line, "!Series_platform_id")) {
				result.platform = line.substr(line.find("GPL"));
				std::cout << "INFO: Platform: " << result.platform << std::endl;
			}
			// start extraction for found sample
			if(boost::starts_with(line, "^SAMPLE")) {
				if(line.find("GSM") != std::string::npos) {
					// extract GSM number
					gsm = line.substr(line.find("GSM"));
					result.sampleNames.push_back(gsm);
					std::cout << "INFO: Parsing - " << gsm << std::endl;
					continue;
				}
			}

			if(boost::starts_with(line, "!sample_table_begin")) {
				within_sample_table = true;
				continue;
			}

			if(within_sample_table && (gsm != "")) {

				if(line[0] == '#') {
					continue;
				}
				// skip header line
				if(boost::starts_with(line, "ID_REF")) {
					std::vector<std::string> entries;
					boost::split(entries, line, boost::is_any_of("\t"),
					             boost::token_compress_on);

					for(value_idx = 0; (size_t)value_idx < entries.size() &&
					                       (entries[value_idx] != "VALUE");
					    ++value_idx) {
					}

					continue;
				}

				if(value_idx == -1) {
					continue;
				}

				typedef boost::split_iterator<std::string::iterator>
				string_split_iterator;

				std::string probeset;
				std::string value;

				int i = 0;
				for(string_split_iterator
				        it = boost::make_split_iterator(
				            line, boost::first_finder("\t", boost::is_equal()));
				    (i <= value_idx) && (it != string_split_iterator());
				    ++it, ++i) {
					if(i == 0) {
						probeset = boost::copy_range<std::string>(*it);
					} else if(i == value_idx) {
						value = boost::copy_range<std::string>(*it);
					}
				}

				if(i > value_idx) {
					double expression_value;
					try
					{
						expression_value = boost::lexical_cast<double>(value);
					}
					catch(boost::bad_lexical_cast& e)
					{
						expression_value =
						    std::numeric_limits<double>::quiet_NaN();
					}
					// new clone id
					if(clone2expression_values.find(probeset) ==
					   clone2expression_values.end()) {
						if(boost::trim_copy(probeset) != "") {
							std::vector<double> tmp_vec;
							tmp_vec.push_back(expression_value);
							clone2expression_values[probeset] = tmp_vec;
						}
					} else // clone id is known... just append the expression
					       // value
					{
						if(boost::trim_copy(probeset) != "") {
							clone2expression_values[probeset]
							    .push_back(expression_value);
						}
					}
				}
			}

			if(boost::starts_with(line, "!sample_table_end")) {
				within_sample_table = false;
				gsm = "";
				value_idx = -1;
			}
		}
	}

	input.auto_close();
	result.gene2exprs = clone2expression_values;
	return result;
}
//static
bool LLTextureEntry::isMediaVersionString(const std::string &version_string)
{
	return std::string::npos != version_string.find(MEDIA_VERSION_STRING_PREFIX);
}
Exemple #18
0
bool BalancedConnection::setSource(std::string serverloc) {
	if ( _started )
		return false;

	_rsarray.clear();

	size_t p1,p2;

	/*
	 * Format of source is:
	 *  type1/source1;type2/source2;...;typeN/sourceN
	 * where
	 *  sourceN is either source or (source)
	 */

	while (true) {
		// Find first slash
		p1 = serverloc.find('/');
		string type1;

		if ( p1 == string::npos ) {
			type1 = "slink";
			p1 = 0;
		}
		else {
			type1 = serverloc.substr(0, p1);
			// Move behind '/'
			++p1;
		}

		string source1;

		// Extract source1
		if ( p1 >= serverloc.size() ) {
			SEISCOMP_ERROR("Invalid RecordStream URL '%s': missing source",
				       serverloc.c_str());
			throw RecordStreamException("Invalid RecordStream URL");
		}

		// Source sourrounded by parenthesis
		if ( serverloc[p1] == '(' ) {
			++p1;
			// Find closing parenthesis
			p2 = findClosingParenthesis(serverloc, p1);
			if ( p2 == string::npos ) {
				SEISCOMP_ERROR("Invalid RecordStream URL '%s': expected closing parenthesis",
					       serverloc.c_str());
				throw RecordStreamException("Invalid RecordStream URL");
			}

			source1 = serverloc.substr(p1, p2-p1);
			++p2;
		}
		else {
			p2 = serverloc.find(';', p1);
			if ( p2 == string::npos ) {
				p2 = serverloc.length();
			}

			source1 = serverloc.substr(p1, p2-p1);
		}

		SEISCOMP_DEBUG("Type   : %s", type1.c_str());
		SEISCOMP_DEBUG("Source : %s", source1.c_str());

		RecordStreamPtr rs = RecordStream::Create(type1.c_str());

		if ( rs == NULL ) {
			SEISCOMP_ERROR("Invalid RecordStream type: %s", type1.c_str());
			return false;
		}

		if ( !rs->setSource(source1) ) {
			SEISCOMP_ERROR("Invalid RecordStream source: %s", source1.c_str());
			return false;
		}

		_rsarray.push_back(make_pair(rs, 0));

		if ( p2 == serverloc.length() )
			break;

		serverloc = serverloc.substr(p2 + 1, string::npos);
	}

	return true;
}
Exemple #19
0
static bool findInsensitive(std::string haystack, const std::string& needle_upper)
{
    LLStringUtil::toUpper(haystack);
    return haystack.find(needle_upper) != std::string::npos;
}
int main(int argc, char **argv){
	ros::init(argc, argv, "unitylink");
	ros::NodeHandle n;
	initializeULRegs(n);
	tx_pub = n.advertise<fmMsgs::serial>("S0_tx_msg", 20);
	ros::Rate loop_rate(100);
	serial_tx_msg.header.seq = 0;
	ros::Subscriber serialsub = n.subscribe("S0_rx_msg", 20, serialCallback);
	data_received = true;
	int cur_reg = 0;
	std_msgs::String string_msg;
	bool first_msg = true;
	int data_not_rcvd_cntr = 0;


	while (ros::ok())
	{
		if(data_received){
			//Handling old register
			data_received = false;
			data_not_rcvd_cntr = 0;
			if(ulregs[cur_reg].direction == IN){
				if(first_msg){
					first_msg = false;
				} else {
					if(received_data.find("#S_R")==0){//Sync
						string_msg.data = received_data = received_data.substr(5, 8);
						ROS_DEBUG("DATA_RECEIVED R0%d: %s", cur_reg, received_data.c_str());
						ulregs[cur_reg].publisher.publish(string_msg);
					}
				}
			} else {
				ROS_DEBUG("Received reply on W0%d", cur_reg);
			}
			cur_reg++;
			if(cur_reg > 7) cur_reg = 0;
			//Handling next register
			if(ulregs[cur_reg].direction == IN){
				sendMsg(ulregs[cur_reg].command);
			} else {
				std::stringstream ss;
				ss << "#W:0" << cur_reg << " " << ulregs[cur_reg].data << "\n";
				sendMsg(ss.str());
			}
		} else {
			if(++data_not_rcvd_cntr > 100){
				data_not_rcvd_cntr = 0;
				first_msg = true;
				data_received = true;
			}
		}


		ros::spinOnce();

		loop_rate.sleep();
	}


	return 0;
}
std::string VmsSocketFactory::ParseProtocol( const std::string &strAddress )
{
	size_t iPos = strAddress.find(":");
	return strAddress.substr(0, iPos);
}
void GameObjectManager::parser(const std::string& command)
{
	std::size_t found = 0;
	std::string args;
	command_e key;
	found = command.find(" ");
	if (found != std::string::npos)
	{
		//MessageBox(NULL, command.substr(0, found).c_str(), "", MB_OK);
		key = m_commands.find(command.substr(0, found))->second;
		args = command.substr(found + 1);
	}
	else {
		key = m_commands.find(command)->second;
	}
	switch (key)
	{
	case command_e::obj:
	{
		m_object = new GameObject();
		m_object->m_name = args;
		m_items.insert(std::pair<std::string, GameObject*>(args, m_object));
		break;
	}
	case command_e::size:
	{
		std::size_t pos = 0;
		game_object_size_t size;
		found = args.find(" ");
		size.x = std::stoi(args.substr(0, found));
		pos = found + 1;
		found = args.find(" ", pos);
		size.y = std::stoi(args.substr(pos, found - pos));
		pos = found + 1;
		size.z = std::stoi(args.substr(pos));
		m_object->m_size = size;
		m_object->set_tile_direction(ObjectDirection_Down);
		break;
	}
	case command_e::weight:
	{
		m_object->m_weight = std::stof(args);
		break;
	}
	case command_e::layer:
	{
		m_object->m_layer = std::stoi(args);
		break;
	}
	case command_e::tile_manager_single:
	{
		m_object->m_tile_manager = new TileManager_Single();
		m_object->m_tile_manager->load_from_file(args, ObjectDirection_Down, 0);
		break;
	}
	case command_e::tile_manager_map:
	{	
		if (m_object->m_tile_manager == nullptr)
		{
			m_object->m_tile_manager = new TileManager_Map();
		}
		ObjectDirection dir;
		int frame;
		std::string name;
		std::size_t pos = 0;
		found = args.find(" ");
		name = args.substr(0, found);
		pos = found + 1;
		found = args.find(" ", pos);
		dir = static_cast<ObjectDirection>(std::stoi(args.substr(pos, found - pos)));
		pos = found + 1;
		frame = std::stoi(args.substr(pos));
		m_object->m_tile_manager->load_from_file(name, dir, frame);
		break;
	}
	case command_e::tile_manager_rotating:
	{
		if (m_object->m_tile_manager == nullptr)
		{
			m_object->m_tile_manager = new TileManager_rotating();
		}
		ObjectDirection dir;
		std::string name;
		std::size_t pos = 0;
		found = args.find(" ");
		name = args.substr(0, found);
		pos = found + 1;
		found = args.find(" ", pos);
		dir = static_cast<ObjectDirection>(std::stoi(args.substr(pos, found - pos)));
		m_object->m_tile_manager->load_from_file(name, dir, 0);
		break;
	}
	case command_e::light:
	{
		std::size_t pos = 0;
		light_t* light = new light_t( 0, 0, 0);
		found = args.find(" ");
		light->R = std::stoi(args.substr(0, found));
		pos = found + 1;
		found = args.find(" ", pos);
		light->G = std::stoi(args.substr(pos, found - pos));
		pos = found + 1;
		light->B = std::stoi(args.substr(pos));
		m_object->m_light = light;
		break;
	}
	case command_e::action_move:
	{
		m_object->m_actions.push_back(Application::instance().m_actions[action_e::move]);
		break;
	}
	case command_e::property_permit_move:
	{
		m_object->m_properties.push_back(new GameObjectProperty(property_e::permit_move));
		break;
	}
	case command_e::property_container:
	{
		std::size_t pos = 0;
		std::string name;
		int x;
		int y;
		found = args.find(" ");
		name = args.substr(0, found);
		pos = found + 1;
		found = args.find(" ", pos);
		x = std::stoi(args.substr(pos, found - pos));
		pos = found + 1;
		y = std::stoi(args.substr(pos));
		m_object->m_properties.push_back(new Property_Container(x, y, name));
		break;
	}
	case command_e::property_strenght:
	{
		m_object->m_properties.push_back(new GameObjectParameter(property_e::strength, std::stof(args)));
		break;
	}
	}
}
Exemple #23
0
// the str should contain 
bool test_str_contains(const std::string & str, const std::string & find) {
    return str.find(find) != std::string::npos;
}
std::vector<std::string *> SQL_ROW::parse_row(std::string &s) {
  // parses a SQL row of the format "value,value,value,value", 
  // where value can be of the form:
  //   number      (i.e. 10)
  //   "string"
  //   'string'
  //   LIST{value,value,value}
  //   ROW(value,value,value)::typename
  // the passed string is consumed by this routine.
  // WARNING: NOT THREAD SAFE
  std::string::size_type comma,dquote,quote,p;
  std::vector<std::string *>::iterator i;
  std::vector<std::string *> rv;
  static bool outer=true;

  while (s.size()) {  // While there's still bits of string left to process
    // get rid of leading spaces and commas
    while (isspace(s[0]) && s.size()) s.erase(0,1);
    while (s[0]==',') s.erase(0,1);

    // Handle the special cases first...
    if (s.find("LIST")==0) {
      // only parse a LIST if the entire string passed to parse_row was a list
      if (outer) {
        outer=false;
        std::vector<std::string *> tmprow(parse_list(s));
        for (i=tmprow.begin();i<tmprow.end();i++) {
          rv.push_back(*i);
        }
      } else {
        rv.push_back(string_delimited(s,'L','}'));
      }
    } else if (s.find("ROW")==0) {
      // only parse a LIST if the entire string passed to parse_row was a ROW
      // type
      if (outer) {
        outer=false;
        std::vector<std::string *> tmprow(parse_type(s));
        for (i=tmprow.begin();i<tmprow.end();i++) {
          rv.push_back(*i);
        }
      } else {
        rv.push_back(string_delimited(s,'R',')'));
      }
    } else if (s.find("<BYTE")==0) {
      rv.push_back(parse_blob(s));
    } else {
    // now for the non-special cases...  We need to find the delimiting
    // commas for the item at the head of the line...
      comma=s.find(',');
    // but beware that the item we're parsing might be a string
      quote=s.find('\'');
      dquote=s.find('\"');
      p=std::min(std::min(comma,quote),dquote);
    // if we found none of the above, we're done.
      if (!found(p)) {
        rv.push_back(new std::string(s));
#ifdef DEBUG_ALLOCATIONS
        fprintf(stderr,"std::string allocated at 0x%p\n",rv[rv.size()-1]);
        fflush(stderr);
#endif
	s.erase();
      } else {
        switch (s[p]) {
        case ',':  // if we found a comma, this is a non quoted entry
	  rv.push_back(new std::string(s,0,p));
#ifdef DEBUG_ALLOCATIONS
          fprintf(stderr,"std::string allocated at 0x%p\n",rv[rv.size()-1]);
          fflush(stderr);
#endif
	  s.erase(0,p+1);
          break;
	case '\'': // if we found a quote we need to find the close quote 
          quote=s.find('\'',p+1);
	  if (found(quote)) {
	    // if we found it, use the quoted entity
	    rv.push_back(new std::string(s,p+1,quote-p-1));
#ifdef DEBUG_ALLOCATIONS
            fprintf(stderr,"std::string allocated at 0x%p\n",rv[rv.size()-1]);
            fflush(stderr);
#endif
	    s.erase(0,quote+2); // Assume that the character after our quote is
	                        // our comma.
	  } else {
	    // if we didn't find it, we guess that everything up to the next 
	    // comma is OK.
	    rv.push_back(new std::string(s,0,comma));
#ifdef DEBUG_ALLOCATIONS
            fprintf(stderr,"std::string allocated at 0x%p\n",rv[rv.size()-1]);
            fflush(stderr);
#endif
	    s.erase(0,comma+1);
	  }
	  break;
	case '\"': // if we found a dquote we need to find the close quote 
          dquote=s.find('\"',p+1);
	  if (found(dquote)) {
	    // if we found it, use the quoted entity
	    rv.push_back(new std::string(s,p+1,dquote-p-1));
#ifdef DEBUG_ALLOCATIONS
            fprintf(stderr,"std::string allocated at 0x%p\n",rv[rv.size()-1]);
            fflush(stderr);
#endif
	    s.erase(0,dquote+2); // Assume that the character after our quote is
	                        // our comma.
	  } else {
	    // if we didn't find it, we guess that everything up to the next 
	    // comma is OK.
	    rv.push_back(new std::string(s,0,comma));
#ifdef DEBUG_ALLOCATIONS
            fprintf(stderr,"std::string allocated at 0x%p\n",rv[rv.size()-1]);
            fflush(stderr);
#endif
	    s.erase(0,comma+1);
	  }
	  break;
	default:
	  // this should never happen
	  abort();
	}
      }
    }
    outer=false;
  }
  outer=true;
  return rv;
}
Exemple #25
0
	void parse_magnet_uri(std::string const& uri, add_torrent_params& p, error_code& ec)
	{
		ec.clear();
		std::string name;
		std::string tracker;

		error_code e;
		std::string display_name = url_has_argument(uri, "dn");
		if (!display_name.empty()) name = unescape_string(display_name.c_str(), e);

		// parse trackers out of the magnet link
		std::string::size_type pos = std::string::npos;
		std::string url = url_has_argument(uri, "tr", &pos);
		while (pos != std::string::npos)
		{
			error_code e;
			url = unescape_string(url, e);
			if (e) continue;
			p.trackers.push_back(url);
			pos = uri.find("&tr=", pos);
			if (pos == std::string::npos) break;
			pos += 4;
			url = uri.substr(pos, uri.find('&', pos) - pos);
		}
	
		std::string btih = url_has_argument(uri, "xt");
		if (btih.empty())
		{
			ec = errors::missing_info_hash_in_uri;
			return;
		}

		if (btih.compare(0, 9, "urn:btih:") != 0)
		{
			ec = errors::missing_info_hash_in_uri;
			return;
		}

#ifndef TORRENT_DISABLE_DHT
		std::string::size_type node_pos = std::string::npos;
		std::string node = url_has_argument(uri, "dht", &node_pos);
		while (!node.empty())
		{
			std::string::size_type divider = node.find_last_of(':');
			if (divider != std::string::npos)
			{
				int port = atoi(node.c_str()+divider+1);
				if (port != 0)
					p.dht_nodes.push_back(std::make_pair(node.substr(0, divider), port));
			}
			
			node_pos = uri.find("&dht=", node_pos);
			if (node_pos == std::string::npos) break;
			node_pos += 5;
			node = uri.substr(node_pos, uri.find('&', node_pos) - node_pos);
		}
#endif

		sha1_hash info_hash;
		if (btih.size() == 40 + 9) from_hex(&btih[9], 40, (char*)&info_hash[0]);
		else info_hash.assign(base32decode(btih.substr(9)));

		p.info_hash = info_hash;
		if (!name.empty()) p.name = name;
	}
/*
 * Writes the given CaOmexManifest to filename.
 *
 * If the filename ends with @em .gz, the file will be compressed by @em gzip.
 * Similary, if the filename ends with @em .zip or @em .bz2, the file will be
 * compressed by @em zip or @em bzip2, respectively. Otherwise, the fill will be
 * uncompressed.
 *
 * @note To create a gzip/zip file, underlying libCombine needs to be linked with zlib at 
 * compile time. Also, underlying libCombine needs to be linked with bzip2 to create a 
 * bzip2 file.
 * File unwritable error will be logged and @c false will be returned if a compressed 
 * file name is given and underlying libCombine is not linked with the corresponding 
 * required library.
 * CaWriter::hasZlib() and CaWriter::hasBzip2() can be used to check whether
 * underlying libCombine is linked with the library.
 *
 * @return true on success and false if the filename could not be opened
 * for writing.
 */
bool
CaWriter::writeOMEX (const CaOmexManifest* d, const std::string& filename)
{
  std::ostream* stream = NULL;

  try
  {
    // open an uncompressed XML file.
    if ( string::npos != filename.find(".xml", filename.length() - 4) )
    {
      stream = new(std::nothrow) std::ofstream(filename.c_str());
    }
    // open a gzip file
    else if ( string::npos != filename.find(".gz", filename.length() - 3) )
    {
     stream = OutputCompressor::openGzipOStream(filename);
    }
    // open a bz2 file
    else if ( string::npos != filename.find(".bz2", filename.length() - 4) )
    {
      stream = OutputCompressor::openBzip2OStream(filename);
    }
    // open a zip file
    else if ( string::npos != filename.find(".zip", filename.length() - 4) )
    {
      std::string filenameinzip = filename.substr(0, filename.length() - 4);
  
      if ( ( string::npos == filenameinzip.find(".xml",  filenameinzip.length() - 4) ) &&
           ( string::npos == filenameinzip.find(".omex", filenameinzip.length() - 5) )
         )
      {
        filenameinzip += ".xml";
      }


#if defined(WIN32) && !defined(CYGWIN)
      char sepr = '\\';
#else
      char sepr = '/';
#endif
      size_t spos = filenameinzip.rfind(sepr, filenameinzip.length() - 1);
      if( spos != string::npos )
      {
        filenameinzip = filenameinzip.substr(spos + 1, filenameinzip.length() - 1);
      }

      
      stream = OutputCompressor::openZipOStream(filename, filenameinzip);
    }
    else
    {
      stream = new(std::nothrow) std::ofstream(filename.c_str());
    }
  }
  catch ( ZlibNotLinked& )
  {
    // libCombine is not linked with zlib.
    XMLErrorLog *log = (const_cast<CaOmexManifest *>(d))->getErrorLog();
    std::ostringstream oss;
    oss << "Tried to write " << filename << ". Writing a gzip/zip file is not enabled because "
        << "underlying libCombine is not linked with zlib."; 
    log->add(XMLError( XMLFileUnwritable, oss.str(), 0, 0) );
    return false;
  } 
  catch ( Bzip2NotLinked& )
  {
    // libCombine is not linked with bzip2.
    XMLErrorLog *log = (const_cast<CaOmexManifest *>(d))->getErrorLog();
    std::ostringstream oss;
    oss << "Tried to write " << filename << ". Writing a bzip2 file is not enabled because "
        << "underlying libCombine is not linked with bzip2."; 
    log->add(XMLError( XMLFileUnwritable, oss.str(), 0, 0) );
    return false;
  } 


  if ( stream == NULL || stream->fail() || stream->bad())
  {
    CaErrorLog *log = (const_cast<CaOmexManifest *>(d))->getErrorLog();
    log->logError(XMLFileUnwritable);
    delete stream;
    return false;
  }

   bool result = writeOMEX(d, *stream);
   delete stream;

   return result;

}
Exemple #27
0
/*
 * Changes relative paths to absolute, removes ".", "..", and trailing "/"
 * "drive:./blah" is absolute (ignore the dot) and "/blah" is relative (because it's missing "drive:")
 * babel (and possibly other games) use "/directoryThatDoesNotExist/../directoryThatExists/filename"
 */
static bool RealPath(const std::string &currentDirectory, const std::string &inPath, std::string &outPath)
{
	size_t inLen = inPath.length();
	if (inLen == 0)
	{
		WARN_LOG(HLE, "RealPath: inPath is empty");
		outPath = currentDirectory;
		return true;
	}

	size_t inColon = inPath.find(':');
	if (inColon + 1 == inLen)
	{
		WARN_LOG(HLE, "RealPath: inPath is all prefix and no path: \"%s\"", inPath.c_str());

		outPath = inPath;
		return true;
	}

	bool relative = (inColon == std::string::npos);
	
	std::string prefix, inAfterColon;
	std::vector<std::string> cmpnts;  // path components
	size_t outPathCapacityGuess = inPath.length();

	if (relative)
	{
		size_t curDirLen = currentDirectory.length();
		if (curDirLen == 0)
		{
			ERROR_LOG(HLE, "RealPath: inPath \"%s\" is relative, but current directory is empty", inPath.c_str());
			return false;
		}
		
		size_t curDirColon = currentDirectory.find(':');
		if (curDirColon == std::string::npos)
		{
			ERROR_LOG(HLE, "RealPath: inPath \"%s\" is relative, but current directory \"%s\" has no prefix", inPath.c_str(), currentDirectory.c_str());
			return false;
		}
		if (curDirColon + 1 == curDirLen)
		{
			ERROR_LOG(HLE, "RealPath: inPath \"%s\" is relative, but current directory \"%s\" is all prefix and no path. Using \"/\" as path for current directory.", inPath.c_str(), currentDirectory.c_str());
		}
		else
		{
			const std::string curDirAfter = currentDirectory.substr(curDirColon + 1);
			if (! ApplyPathStringToComponentsVector(cmpnts, curDirAfter) )
			{
				ERROR_LOG(HLE,"RealPath: currentDirectory is not a valid path: \"%s\"", currentDirectory.c_str());
				return false;
			}

			outPathCapacityGuess += curDirLen;
		}

		prefix = currentDirectory.substr(0, curDirColon + 1);
		inAfterColon = inPath;
	}
	else
	{
		prefix = inPath.substr(0, inColon + 1);
		inAfterColon = inPath.substr(inColon + 1);
	}

	// Special case: "disc0:" is different from "disc0:/", so keep track of the single slash.
	if (inAfterColon == "/")
	{
		outPath = prefix + inAfterColon;
		return true;
	}

	if (! ApplyPathStringToComponentsVector(cmpnts, inAfterColon) )
	{
		WARN_LOG(HLE, "RealPath: inPath is not a valid path: \"%s\"", inPath.c_str());
		return false;
	}

	outPath.clear();
	outPath.reserve(outPathCapacityGuess);

	outPath.append(prefix);

	size_t numCmpnts = cmpnts.size();
	for (size_t i = 0; i < numCmpnts; i++)
	{
		outPath.append(1, '/');
		outPath.append(cmpnts[i]);
	}

	return true;
}
Exemple #28
0
int parse_options(int argc, char *argv[], std::map<std::string, std::string>& aopt) {
	aopt.clear();
	int c = 0,
	option_index = 0;

	static struct option long_options[] =
	{
		{"analyzer", required_argument, 0, 'a'},
		{"max-frames", required_argument, 0, 'm'},
		{"skip-frames", required_argument, 0, 's'},
		{"reference", required_argument, 0, 'r'},
		{"log-level", required_argument, 0, 'l'},
		{"save-frames", no_argument, 0, 'I'},
		{"video-size", required_argument, 0, 'v'},
		{"ignore-fps", no_argument, 0, 'G'},
		{"help", no_argument, 0, 'h'},
		{"aopts", required_argument, 0, 'o'},
		{"json", required_argument, 0, 'j'},
		{0, 0, 0, 0}
	};

	while ((c = getopt_long (argc, argv, "a:j:l:m:o:r:s:v:hIG", long_options, &option_index)) != -1) {
		switch (c) {
			case 'a':
			{
				settings::ANALYZER = optarg;
				break;
			}
			case 'v':
			{
				const char *p_x = strchr(optarg, 'x');
				if (!p_x)
					p_x = strchr(optarg, 'X');
				if (!p_x)
					throw std::runtime_error("Invalid video size specified (use WIDTHxHEIGHT format, ie. 1280x720)");
				const std::string s_x(optarg, p_x-optarg);
				const std::string s_y(p_x+1);
				if (s_x.empty() || s_y.empty())
					throw std::runtime_error("Invalid video size specified (use WIDTHxHEIGHT format, ie. 1280x720)");
				
				const int i_x = atoi(s_x.c_str());
				const int i_y = atoi(s_y.c_str());
				if (i_x <=0 || i_y <=0)
					throw std::runtime_error("Invalid video size specified, negative or 0 width/height");

				settings::VIDEO_SIZE_W = i_x;
				settings::VIDEO_SIZE_H = i_y;
				
				break;
			}
			case 's':
				{
					const int skip_frames = atoi(optarg);
					if (skip_frames > 0 ) settings::SKIP_FRAMES = skip_frames;
				}
				break;
			case 'r':
			{
				settings::REF_VIDEO = optarg;
				break;
			}
			case 'm':
			{
				const int max_frames = atoi(optarg);
				if (max_frames > 0 )
					settings::MAX_FRAMES = max_frames;
				break;
			}
			case 'l':
				if (isdigit(optarg[0])) {
					char log_level[2];
					log_level[0] = optarg[0];
					log_level[1] = '\0';
					const int log_ilev = atoi(log_level);
					switch (log_ilev) {
						case 0:
							settings::LOG = 0x00;
							break;
						case 1:
							settings::LOG = 0x01;
							break;
						case 2:
							settings::LOG = 0x03;
							break;
						case 3:
							settings::LOG = 0x07;
							break;
						case 4:
							settings::LOG = 0x0F;
							break;
						default:
							break;
					}
				}
				break;
			case 'h':
				print_help();
				exit(0);
				break;
			case 'I':
				settings::SAVE_IMAGES = true;
				break;
			case 'j':
				settings::OUTPUT = optarg;
				break;
			case 'G':
				settings::IGNORE_FPS = true;
				break;
			case 'o':
				{
					const char 	*p_opts = optarg,
							*p_colon = 0;
					while((p_colon = strchr(p_opts, ':'))) {
						const std::string	c_opt(p_opts, (p_colon-p_opts));
						const size_t 		p_equal = c_opt.find('=');
						if (std::string::npos != p_equal)
							aopt[c_opt.substr(0, p_equal)] = c_opt.substr(p_equal+1);
						p_opts = p_colon+1;
					}
					const std::string	c_opt(p_opts);
					const size_t 		p_equal = c_opt.find('=');
					if (std::string::npos != p_equal)
						aopt[c_opt.substr(0, p_equal)] = c_opt.substr(p_equal+1);
				}
				break;
			case '?':
				if (strchr("almorsv", optopt)) {
					std::cerr << "Option -" << (char)optopt << " requires an argument" << std::endl;
					print_help();
					exit(1);
				} else if (isprint (optopt)) {
					std::cerr << "Option -" << (char)optopt << " is unknown" << std::endl;
					print_help();
					exit(1);
				}
				break;
			default:
				std::cerr << "Invalid option: " << c << std::endl;
				print_help();
				exit(1);
				break;
		}
	}
	// fix here the frame limit
	if (settings::SKIP_FRAMES > 0 && settings::MAX_FRAMES>0) settings::MAX_FRAMES += settings::SKIP_FRAMES;
	return optind;
}
Exemple #29
0
void MDFN_CheckFIROPSafe(const std::string &path)
{
 //
 // First, check for any 8-bit characters, and print a warning about portability.
 //
 for(size_t x = 0; x < path.size(); x++)
 {
  if(path[x] & 0x80)
  {
   MDFN_printf(_("WARNING: Referenced path \"%s\" contains at least one 8-bit non-ASCII character; this may cause portability issues.\n"), path.c_str());
   break;
  }
 }

 if(!MDFN_GetSettingB("filesys.untrusted_fip_check"))
  return;

 // We could make this more OS-specific, but it shouldn't hurt to try to weed out usage of characters that are path
 // separators in one OS but not in another, and we'd also run more of a risk of missing a special path separator case
 // in some OS.
 std::string unsafe_reason;

#ifdef WIN32
 if(!UTF8_validate(path, true))
  unsafe_reason += _("Invalid UTF-8. ");
#endif

 if(path.find('\0') != string::npos)
  unsafe_reason += _("Contains null(0). ");

 if(path.find(':') != string::npos)
  unsafe_reason += _("Contains colon. ");

 if(path.find('\\') != string::npos)
  unsafe_reason += _("Contains backslash. ");

 if(path.find('/') != string::npos)
  unsafe_reason += _("Contains forward slash. ");

 if(path == "..")
  unsafe_reason += _("Is parent directory. ");

#if defined(DOS) || defined(WIN32)
 //
 // http://support.microsoft.com/kb/74496
 // http://googleprojectzero.blogspot.com/2016/02/the-definitive-guide-on-win32-to-nt.html
 //
 {
  static const char* dev_names[] = 
  {
   "CON", "PRN", "AUX", "CLOCK$", "NUL", "CONIN$", "CONOUT$",
   "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "COM¹", "COM²", "COM³",
   "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", "LPT¹", "LPT²", "LPT³",
   NULL
  };
  //
  const char* pcs = path.c_str();
  for(const char** ls = dev_names; *ls != NULL; ls++)
  {
   size_t lssl = strlen(*ls);

   if(!MDFN_strazicmp(*ls, pcs, lssl))
   {
    if(pcs[lssl] == 0 || pcs[lssl] == ':' || pcs[lssl] == '.' || pcs[lssl] == ' ')
    {
     unsafe_reason += _("Is (likely) a reserved device name. ");
     break;
    }
   }
  }
 }
#endif

 if(unsafe_reason.size() > 0)
  throw MDFN_Error(0, _("Referenced path \"%s\" is potentially unsafe.  %s Refer to the documentation about the \"filesys.untrusted_fip_check\" setting.\n"), path.c_str(), unsafe_reason.c_str());
}
Exemple #30
0
void Sentence::wordSplit(std::string& queryInput)
{
    size_t start = queryInput.find("'s");  //Find and replace 's and ' 
    //cout<<start<<endl;
    if( start != std::string::npos) {
        //cout<<"First place\n";
        queryInput.replace(start, std::string("'s").length(), " ");
    }
    //cout<<queryInput<<endl;
    //cout<<start;
    start = queryInput.find("' ");
    if( start != std::string::npos) {
        //cout<<"Second place\n";
        queryInput.replace(start, std::string("' ").length(), " ");
    }
    std::string curWord = "";

    while(queryInput[queryInput.length()-1] == '.' || queryInput[queryInput.length()-1] == ' '  || queryInput[queryInput.length()-1] == '?' || queryInput[queryInput.length()-1] == '\t' || queryInput[queryInput.length()-1] == '\n') // remove the ending ?, ., and so forth;
    {
        //cout<<"coming in here";
        //queryInput.replace(queryInput[queryInput.length()-2], 1, " ");
        //cout<<queryInput<<endl;
        //cout<<queryInput[queryInput.length()-1]<<endl;
        queryInput.replace(queryInput.length()-1, 1, "");
        //queryInput.replace(10, 1, " ");
        //cout<<queryInput<<endl;
        //cout<<queryInput.length()<<endl;
    }
    queryInput.append(" ");
    //cout<<start;
    //cout<<queryInput[queryInput.length()-1]<<endl;
    bool ifCited = false;
    for(unsigned int i = 0; i < queryInput.length(); i++) {
        char c = queryInput[i];
        //cout<<c<<endl;
		if(c == '\t' || c == '\n' || c == ' ') {
		    if(ifCited == false) {
                wordList.push_back(curWord); 
				curWord = ""; 
				while(i < queryInput.length()-1 && (queryInput[i+1] == '\t' || queryInput[i+1] == '\n' 
					|| queryInput[i+1] == ' ' || queryInput[i+1] == ',')) {
						i++; 
				}
			}
			else {
			    curWord += queryInput[i]; 
		    }
		} else if(c == '\'') {
            if(ifCited == false) {
				if(queryInput[i+1] == 't') {
                    curWord += queryInput[i]; 
                } else {
                    wordList.push_back(curWord); 
                    wordList.push_back("\'s"); 
					curWord = ""; 
					if(i < queryInput.length()-1 && queryInput[i+1] == 's') {
                        i++; 
					}
					i++; 
				}
			} else {
					curWord += queryInput[i]; 
			}				
		} else if(c == ',') {
            if(ifCited == false) {
				wordList.push_back(curWord); 
				wordList.push_back(","); 
				curWord = ""; 
                while(i < queryInput.length()-1 && (queryInput[i+1] == '\t' || queryInput[i+1] == '\n' || queryInput[i+1] == ' ' 
					|| queryInput[i+1] == ',')) {
						i++; 
				}
			} else {
				curWord += queryInput[i]; 
			}
		} else if(c == '\"') { 
            if(ifCited == false) {
			    ifCited = true; 
			} else {
				ifCited = false; 
			}
		} else {
			curWord += queryInput[i]; 				
		}
		
    }
}