Example #1
0
std::string expanduser(const std::string &path) {
    std::string copy(path);
    replace(copy, "~", get_home_directory());
    return copy;
}
Example #2
0
static int parse(RParse *p, const char *data, char *str) {
	int i, len = strlen (data);
	char w0[WSZ];
	char w1[WSZ];
	char w2[WSZ];
	char w3[WSZ];
	char w4[WSZ];
	char *buf, *ptr, *optr, *par;

	// malloc can be slow here :?
	if (!(buf = malloc (len + 1))) {
		return false;
	}
	memcpy (buf, data, len + 1);

	r_str_chop (buf);
	if (*buf) {
		w0[0] = '\0';
		w1[0] = '\0';
		w2[0] = '\0';
		w3[0] = '\0';
		w4[0] = '\0';
		ptr = strchr (buf, ' ');
		if (!ptr) {
			ptr = strchr (buf, '\t');
		}
		if (ptr) {
			*ptr = '\0';
			for (++ptr; *ptr == ' '; ptr++) {
				//nothing to see here
			}
			strncpy (w0, buf, WSZ - 1);
			strncpy (w1, ptr, WSZ - 1);

			optr = ptr;
			par = strchr (ptr, '(');
			if (par && strchr (ptr, ',') > par) {
				ptr = strchr (ptr, ')');
				if (ptr) {
					ptr = strchr (ptr, ',');
				}
			} else {
				ptr = strchr (ptr, ',');
			}
			if (ptr) {
				*ptr = '\0';
				for (++ptr; *ptr == ' '; ptr++) {
					//nothing to see here
				}
				strncpy (w1, optr, WSZ - 1);
				strncpy (w2, ptr, WSZ - 1);
				optr = ptr;
				par = strchr (ptr, '(');
				if (par && strchr (ptr, ',') > par) {
					ptr = strchr (ptr, ')');
					if (ptr) {
						ptr = strchr (ptr, ',');
					}
				} else {
					ptr = strchr (ptr, ',');
				}
				if (ptr) {
					*ptr = '\0';
					for (++ptr; *ptr == ' '; ptr++) {
						//nothing to see here
					}
					strncpy (w2, optr, WSZ - 1);
					strncpy (w3, ptr, WSZ - 1);
					optr = ptr;
					// bonus	
					par = strchr (ptr, '(');
					if (par && strchr (ptr, ',') > par) {
						ptr = strchr (ptr, ')');
						if (ptr) {
							ptr = strchr (ptr, ',');
						}
					} else {
						ptr = strchr (ptr, ',');
					}
					if (ptr) {
						*ptr = '\0';
						for (++ptr; *ptr == ' '; ptr++) {
							//nothing to see here
						}
						strncpy (w3, optr, WSZ - 1);
						strncpy (w4, ptr, WSZ - 1);
					}
				}
			}
		} else {
			strncpy (w0, buf, WSZ - 1);
		}
		{
			const char *wa[] = { w0, w1, w2, w3, w4 };
			int nw = 0;
			for (i = 0; i < 5; i++) {
				if (wa[i][0] != '\0') {
					nw++;
				}
			}
			replace (nw, wa, str);
		}
	}
	free (buf);
	return true;
}
void QuadSetTopologyModifier::removeQuadsProcess(const sofa::helper::vector<unsigned int> &indices,
        const bool removeIsolatedEdges,
        const bool removeIsolatedPoints)
{
    if(!m_container->hasQuads()) // this method should only be called when quads exist
    {
#ifndef NDEBUG
        sout << "Error. [QuadSetTopologyModifier::removeQuadsProcess] quad array is empty." << sendl;
#endif
        return;
    }

    if(m_container->hasEdges() && removeIsolatedEdges)
    {
        if(!m_container->hasEdgesInQuad())
            m_container->createEdgesInQuadArray();

        if(!m_container->hasQuadsAroundEdge())
            m_container->createQuadsAroundEdgeArray();
    }

    if(removeIsolatedPoints)
    {
        if(!m_container->hasQuadsAroundVertex())
            m_container->createQuadsAroundVertexArray();
    }

    sofa::helper::vector<unsigned int> edgeToBeRemoved;
    sofa::helper::vector<unsigned int> vertexToBeRemoved;
    helper::WriteAccessor< Data< sofa::helper::vector<Quad> > > m_quad = m_container->d_quad;

    unsigned int lastQuad = m_container->getNumberOfQuads() - 1;
    for(unsigned int i=0; i<indices.size(); ++i, --lastQuad)
    {
        const Quad &t = m_quad[ indices[i] ];
        const Quad &q = m_quad[ lastQuad ];

        // first check that the quad vertex shell array has been initialized
        if(m_container->hasQuadsAroundVertex())
        {
            for(unsigned int v=0; v<4; ++v)
            {
                sofa::helper::vector< unsigned int > &shell = m_container->m_quadsAroundVertex[ t[v] ];
                shell.erase(remove(shell.begin(), shell.end(), indices[i]), shell.end());
                if(removeIsolatedPoints && shell.empty())
                    vertexToBeRemoved.push_back(t[v]);
            }
        }

        if(m_container->hasQuadsAroundEdge())
        {
            for(unsigned int e=0; e<4; ++e)
            {
                sofa::helper::vector< unsigned int > &shell = m_container->m_quadsAroundEdge[ m_container->m_edgesInQuad[indices[i]][e]];
                shell.erase(remove(shell.begin(), shell.end(), indices[i]), shell.end());
                if(removeIsolatedEdges && shell.empty())
                    edgeToBeRemoved.push_back(m_container->m_edgesInQuad[indices[i]][e]);
            }
        }

        if(indices[i] < lastQuad)
        {
            // now updates the shell information of the quad at the end of the array
            if(m_container->hasQuadsAroundVertex())
            {
                for(unsigned int v=0; v<4; ++v)
                {
                    sofa::helper::vector< unsigned int > &shell = m_container->m_quadsAroundVertex[ q[v] ];
                    replace(shell.begin(), shell.end(), lastQuad, indices[i]);
                }
            }

            if(m_container->hasQuadsAroundEdge())
            {
                for(unsigned int e=0; e<4; ++e)
                {
                    sofa::helper::vector< unsigned int > &shell =  m_container->m_quadsAroundEdge[ m_container->m_edgesInQuad[lastQuad][e]];
                    replace(shell.begin(), shell.end(), lastQuad, indices[i]);
                }
            }
        }

        // removes the edgesInQuads from the edgesInQuadsArray
        if(m_container->hasEdgesInQuad())
        {
            m_container->m_edgesInQuad[ indices[i] ] = m_container->m_edgesInQuad[ lastQuad ]; // overwriting with last valid value.
            m_container->m_edgesInQuad.resize( lastQuad ); // resizing to erase multiple occurence of the quad.
        }

        // removes the quad from the quadArray
        m_quad[ indices[i] ] = m_quad[ lastQuad ]; // overwriting with last valid value.
        m_quad.resize( lastQuad ); // resizing to erase multiple occurence of the quad.
    }

    if(!edgeToBeRemoved.empty())
    {
        /// warn that edges will be deleted
        removeEdgesWarning(edgeToBeRemoved);
        propagateTopologicalChanges();
        /// actually remove edges without looking for isolated vertices
        removeEdgesProcess(edgeToBeRemoved,false);
    }

    if(!vertexToBeRemoved.empty())
    {
        removePointsWarning(vertexToBeRemoved);
        /// propagate to all components
        propagateTopologicalChanges();
        removePointsProcess(vertexToBeRemoved);
    }
}
Example #4
0
void Map::CreateMap( vector<vector<Tile*> >& tiles, char* tmxFile, int numSpritesRow )
{
    //Clear out all the tiles
    backTiles.clear();
    backTiles.shrink_to_fit();

	// open the XML map file
	TiXmlDocument xmlFile( tmxFile );
	if(xmlFile.LoadFile()) {
		cout << "Successfully opened the XML map file.\n";
	} else {
		cout << "ERROR: Unable to open the XML map file.\n";
	}

	// parse the XML
	// this code assumes that the layers exist in the XML file in this order: sprites, then collision, then ladders.
	mapWidth = atoi(xmlFile.FirstChildElement("map")->Attribute("width"));
	mapHeight = atoi(xmlFile.FirstChildElement("map")->Attribute("height"));
	int tileSize = atoi(xmlFile.FirstChildElement("map")->Attribute("tilewidth"));
	string tileImageFilename = xmlFile.FirstChildElement("map")->FirstChildElement("tileset")->FirstChildElement("image")->Attribute("source");
	string spriteLayer = xmlFile.FirstChildElement("map")->FirstChildElement("layer")->FirstChildElement("data")->GetText();
	string collisionLayer = xmlFile.FirstChildElement("map")->FirstChildElement("layer")->NextSibling()->FirstChildElement("data")->GetText();
	string ladderLayer = xmlFile.FirstChildElement("map")->FirstChildElement("layer")->NextSibling()->NextSibling()->FirstChildElement("data")->GetText();
	string enemiesLayer = xmlFile.FirstChildElement("map")->FirstChildElement("layer")->NextSibling()->NextSibling()->NextSibling()->FirstChildElement("data")->GetText();

	// convert the CSV strings into vectors of ints
	// these ints are the sprite numbers for each tile. 0 would be the first sprite in the first row, etc.
	replace(spriteLayer.begin(), spriteLayer.end(), ',', ' '); // convert CSV to space-delimited
	stringstream a(spriteLayer);
	vector<int> spriteInts;
	string temp1;
	while(a >> temp1) {
		spriteInts.push_back(atoi(temp1.c_str()));
	}
	replace(collisionLayer.begin(), collisionLayer.end(), ',', ' '); // convert CSV to space-delimited
	stringstream b(collisionLayer);
	vector<int> collisionInts;
	string temp2;
	while(b >> temp2) {
		collisionInts.push_back(atoi(temp2.c_str()));
	}
	replace(ladderLayer.begin(), ladderLayer.end(), ',', ' '); // convert CSV to space-delimited
	stringstream c(ladderLayer);
	vector<int> ladderInts;
	string temp3;
	while(c >> temp3) {
		ladderInts.push_back(atoi(temp3.c_str()));
	}
	replace(enemiesLayer.begin(), enemiesLayer.end(), ',', ' '); // convert CSV to space-delimited
	stringstream d(enemiesLayer);
	vector<int> enemyInts;
	string temp4;
	while(d >> temp4) {
		enemyInts.push_back(atoi(temp4.c_str()));
	}


	// generate the vectors of tiles
	int i = 0;	
	for(int row = 0; row < mapHeight; row++) {
		vector<Tile*> currentRow;
		for(int column = 0; column < mapWidth; column++) {
			int xPosition = (i % mapWidth) * tileSize;
			int yPosition = (i / mapWidth) * tileSize;
			bool collision = collisionInts[i]; // non-zero sprite number indicates collision region
			bool ladder = ladderInts[i]; // non-zero sprite number indicates ladder region
            Game_Enemies enemy;
			if(enemyInts[i] == 377)
				enemy = CORGI;
			else if(enemyInts[i] == 378)
				enemy = HUSKY;
			else if(enemyInts[i] == 379)
				enemy = GREYHOUND;
			else if(enemyInts[i] == 380)
				enemy = SHIBA;
			else if(enemyInts[i] == 381)
				enemy = BULLDOG;
			else
				enemy = NONE;
			string spriteFilePath = tileImageFilename;
			int spritesPerRow = numSpritesRow;
			int spriteXoffset = ((spriteInts[i] - 1) % spritesPerRow) * tileSize;
			int spriteYoffset = ((spriteInts[i] - 1) / spritesPerRow) * tileSize;
			i++;
			currentRow.push_back( new Tile( xPosition, yPosition, collision, ladder, enemy, spriteXoffset, spriteYoffset ) );
		}
		tiles.push_back(currentRow);

	}

	// for debugging: examine the contents of a tile
	cout << "There are " << tiles.size() << " rows, and " << tiles[0].size() << " columns.\n\n";
	int tileToExamine = 1;
	cout << "Details for tile #" << tileToExamine << ":\n\n";
    cout << "xPosition =       " << tiles[tileToExamine / mapWidth][tileToExamine % mapWidth]->GetDestination().x << "\n";
	cout << "yPosition =       " << tiles[tileToExamine / mapWidth][tileToExamine % mapWidth]->GetDestination().y << "\n";
    cout << "collision =       " << tiles[tileToExamine / mapWidth][tileToExamine % mapWidth]->GetCollision() << "\n";
    cout << "ladder =          " << tiles[tileToExamine / mapWidth][tileToExamine % mapWidth]->GetIsLadder() << "\n";
    cout << "enemy =           " << tiles[tileToExamine / mapWidth][tileToExamine % mapWidth]->GetEnemy() << "\n";
	//cout << "spriteFilePath =  " <<  << "\n";
    cout << "spriteXoffset =   " << tiles[tileToExamine / mapWidth][tileToExamine % mapWidth]->GetClip().x << "\n";
    cout << "spriteYoffset =   " << tiles[tileToExamine / mapWidth][tileToExamine % mapWidth]->GetClip().y << "\n";
	cout << "\nDone.\n";

    
    //Get pixels width and height of the map also
    mapPixWidth = mapWidth * TILE_SIZE;
    mapPixHeight = mapHeight * TILE_SIZE;
}
Example #5
0
/* Parse a VM configuration file */
static bool parse(home_data *data)
{
    FILE *cfgf = fopen(data->cfgf, "r");
    char *ret = NULL, *sp;
    char buf[1024];

    if (cfgf == NULL) {
        log_debug("Can't open %s\n", data->cfgf);
        return (false);
    }

    data->jvms = (home_jvm **)malloc(256 * sizeof(home_jvm *));

    while ((ret = fgets(buf, 1024, cfgf)) != NULL) {
        char *tmp = strchr(ret, '#');
        int pos;

        /* Clear the string at the first occurrence of '#' */
        if (tmp != NULL)
            tmp[0] = '\0';

        /* Trim the string (including leading '-' chars */
        while ((ret[0] == ' ') || (ret[0] == '\t') || (ret[0] == '-'))
            ret++;
        pos = strlen(ret);
        while (pos >= 0) {
            if ((ret[pos] == '\r') || (ret[pos] == '\n') || (ret[pos] == '\t')
                || (ret[pos] == '\0') || (ret[pos] == ' ')) {
                ret[pos--] = '\0';
            }
            else
                break;
        }
        /* Format changed for 1.4 JVMs */
        sp = strchr(ret, ' ');
        if (sp != NULL)
            *sp = '\0';

        /* Did we find something significant? */
        if (strlen(ret) > 0) {
            char *libf = NULL;
            int x = 0;

            log_debug("Found VM %s definition in configuration", ret);
            while (location_jvm_configured[x] != NULL) {
                char *orig = location_jvm_configured[x];
                char temp[1024];
                char repl[1024];
                int k;

                k = replace(temp, 1024, orig, "$JAVA_HOME", data->path);
                if (k != 0) {
                    log_error("Can't replace home in VM library (%d)", k);
                    return (false);
                }
                k = replace(repl, 1024, temp, "$VM_NAME", ret);
                if (k != 0) {
                    log_error("Can't replace name in VM library (%d)", k);
                    return (false);
                }

                log_debug("Checking library %s", repl);
                if (checkfile(repl)) {
                    libf = strdup(repl);
                    break;
                }
                x++;
            }

            if (libf == NULL) {
                log_debug("Cannot locate library for VM %s (skipping)", ret);
            }
            else {
                data->jvms[data->jnum] = (home_jvm *)malloc(sizeof(home_jvm));
                data->jvms[data->jnum]->name = strdup(ret);
                data->jvms[data->jnum]->libr = libf;
                data->jnum++;
                data->jvms[data->jnum] = NULL;
            }
        }
    }
    return (true);
}
Example #6
0
int XC::ElementRecorder::initialize(void)
  {
    const int numEle= eleID.Size();
    if(numEle == 0 || theDomain == 0)
      {
        if(!theDomain)
	  std::cerr << getClassName() << "::" << __FUNCTION__
	            << "; undefined domain." << std::endl;
        if(numEle == 0)
	  std::cerr << getClassName() << "::" << __FUNCTION__
	            << "; there is no elements." << std::endl;
        return -1;
      }

    // Set the response objects:
    //   1. create an array of pointers for them
    //   2. iterate over the elements invoking setResponse() to get the new objects & determine size of data
    //

    int numDbColumns = 0;
    if(echoTimeFlag == true) 
      numDbColumns = 1;  // 1 for the pseudo-time

    theResponses= std::vector<Response *>(numEle,static_cast<Response *>(nullptr));

    Information eleInfo(1.0);
    int i;
    for(i=0; i<numEle; i++)
      {
        Element *theEle = theDomain->getElement(eleID(i));
        if(theEle == 0)
          { theResponses[i]= 0; }
        else
          {
            theResponses[i] = theEle->setResponse(responseArgs, eleInfo);
            if(theResponses[i] != 0)
              {
	        // from the response type determine no of cols for each
	        Information &eleInfo = theResponses[i]->getInformation();
	        const Vector &eleData = eleInfo.getData();
	        numDbColumns += eleData.Size();
              }
          }
      }

    //
    // now create the columns strings for the data description
    // for each element do a getResponse() 
    //
    std::vector<std::string> dbColumns(numDbColumns);
    static std::string aColumn;

    int counter = 0;
    if(echoTimeFlag == true)
      {
        dbColumns[0] = "time";
        counter = 1;
      }
    
    std::string dataToStore= "";
    const size_t numArgs= getNumArgs();
    for(size_t j=0; j<numArgs; j++)
      {
        dataToStore+= responseArgs[j];
        if(j<(numArgs-1))
          dataToStore+= " ";
      }
    
    for(i=0; i<eleID.Size(); i++)
      {
        int eleTag = eleID(i);
        int numVariables = 0;
        if(theResponses[i]!=nullptr)
          {
            const XC::Information &eleInfo = theResponses[i]->getInformation();
            if(eleInfo.theType == IntType || eleInfo.theType == DoubleType)
              {
	      // create column heading for single data item for element
	      numVariables = 0;
	      //sprintf(aColumn, "Element%d_%s", eleTag, dataToStore);
                aColumn= "Element" + boost::lexical_cast<std::string>(eleTag) + "_" 
		+ dataToStore;
                dbColumns[counter] = aColumn;
	      counter++;
              }
            else if(eleInfo.theType == VectorType) 
	    numVariables = eleInfo.theVector->Size();
            else if(eleInfo.theType == IdType) 
	    numVariables = eleInfo.theID->Size();
            else if(eleInfo.theType == MatrixType) 
	    numVariables = eleInfo.theMatrix->noRows()* eleInfo.theMatrix->noCols();

            // create the column headings for multiple data for the element
            for(int j=1; j<=numVariables; j++)
              {
	      //sprintf(aColumn, "Element%d_%s_%d",eleTag, dataToStore, j);
                aColumn= "Element" + boost::lexical_cast<std::string>(eleTag) + "_" 
		                 + dataToStore + "_"
                                   + boost::lexical_cast<std::string>(j);
                dbColumns[counter] = aColumn;
	      counter++;
              }
          }
      }

    // replace spaces with undescore for tables
    for(int kk=0; kk<numDbColumns; kk++)
      replace(dbColumns[kk],' ','_');

    //
    // call open in the handler with the data description
    //

    theHandler->open(dbColumns);

    // create the vector to hold the data
    data= Vector(numDbColumns);

    initializationDone = true;
    return 0;
  }
Example #7
0
void UmlOperation::import(File & f)
{
    if (scanning) {
        f.skipBlock();
        return;
    }

    QByteArray s;
    UmlTypeSpec t;

    for (;;) {
        switch (f.read(s)) {
        case -1:
            f.eof();
            throw 0;

        case ')':
            set_ReturnType(t);
            return;

        case ATOM:
            break;

        default:
            f.syntaxError(s);
        }

        // atom
        if (s == "parameters") {
            f.read("(");
            f.read("list");
            f.read("Parameters");
            importParameters(f);
        }
        else if (s == "result") {
            if (f.read(s) != STRING)
                f.syntaxError(s, "return type");

            t.explicit_type = s;
        }
        else if (s == "quidu") {
            if (f.read(s) != STRING)
                f.syntaxError(s, "wrong quidu");

            if (UmlClass::replaceType(t, s, "${type}")) {
                switch (((UmlClass *) parent())->language()) {
                case Cplusplus:
                case AnsiCplusplus:
                case VCplusplus:
                    set_CppDecl(replace(cppDecl(), "${type}", s));
                    set_CppDef(replace(cppDef(), "${type}", s));
                    break;

                case Oracle8:
                    break;

                case Corba:
                    set_IdlDecl(replace(idlDecl(), "${type}", s));
                    break;

                case Java:
                    set_JavaDecl(replace(javaDecl(), "${type}", s));
                    break;

                default:
                    break;
                }
            }
        }
        else if (s == "exceptions")
            importExceptions(f);
        else if (s == "opExportControl")
            set_Visibility(f.readVisibility());
        else
            f.skipNextForm();
    }

}
Example #8
0
	ConcreteSite::ConcreteSite (const Media::LyricsQuery& query,
			const ConcreteSiteDesc& desc, ICoreProxy_ptr proxy, QObject *parent)
	: QObject (parent)
	, Query_ (query)
	, Desc_ (desc)
	{
		auto replace = [this] (QString str) -> QString
		{
			for (const auto& c : Desc_.Replacements_.keys ())
				str.replace (c, Desc_.Replacements_ [c]);
			return str;
		};

		const auto& artist = replace (query.Artist_.toLower ());
		const auto& album = replace (query.Album_.toLower ());
		const auto& title = replace (query.Title_.toLower ());

		auto urlStr = Desc_.URLTemplate_;
		urlStr.replace ("{artist}", artist);
		urlStr.replace ("{album}", album);
		urlStr.replace ("{title}", title);
		if (!artist.isEmpty ())
			urlStr.replace ("{a}", artist.at (0).toLower ());

		auto cap = [] (QString str) -> QString
		{
			if (!str.isEmpty ())
				str [0] = str [0].toUpper ();
			return str;
		};
		urlStr.replace ("{Artist}", cap (artist));
		urlStr.replace ("{Album}", cap (album));
		urlStr.replace ("{Title}", cap (title));

#ifdef QT_DEBUG
		qDebug () << Q_FUNC_INFO
				<< "requesting"
				<< urlStr
				<< "from"
				<< Desc_.Name_
				<< "for"
				<< artist
				<< album
				<< title;
#endif

		auto nam = proxy->GetNetworkAccessManager ();

		QUrl url { urlStr };
		QNetworkRequest req { url };

		url.setPath ({});
		url.setQueryItems ({});
		req.setRawHeader ("Referer", url.toString ().toUtf8 ());

		auto reply = nam->get (req);
		connect (reply,
				SIGNAL (finished ()),
				this,
				SLOT (handleReplyFinished ()));
		connect (reply,
				SIGNAL (error (QNetworkReply::NetworkError)),
				this,
				SLOT (handleReplyError ()));
	}
int Switch_Manager::DeleteAllWsitch(char* strUrl,char* outPutUrl,char* strSessionID)
{
	LOG_DEBUG("DEBUG - [SWM]: - DeleteAllWsitch fun \n");
	printf("---DeleteAllWsitch fun \n");
	bool bIsReplyflag = false;
		//遍历切流器 时间过长,不加锁
	pthread_mutex_lock(&m_mutexServerList);
	MapSwitchSeverInfo::iterator iterLook = m_mapSwitchServerInfo.begin();
	while(iterLook != m_mapSwitchServerInfo.end())
	{
		//
		SwitchSeverInfo *pFindSeverInfo = iterLook->second;
		if(pFindSeverInfo && pFindSeverInfo->iRunStatus == 0)  //在线的切流器
		{
				//连接server 
			//报文转发
			Stream ptmpRequest;
			int iret = ptmpRequest.ConnectServer(pFindSeverInfo->strServerIPAddr,pFindSeverInfo->iListenPort);
			if(iret != 0)
			{
				//连接失败		
				continue;
			}
			iret = ptmpRequest.Send_str(strUrl);
			if(iret != 0)
			{
				continue;
			}
			char Rcv_buf[1024]={0};
			int iLen = sizeof(Rcv_buf);
			iret = ptmpRequest.Recv_str(Rcv_buf,&iLen);
			if(iret !=0)
				continue;

			memcpy(outPutUrl,Rcv_buf,iLen);
			bIsReplyflag = true;
			outPutUrl[iLen] ='\0';

				cJSON *pcmd = NULL;

					//解析报文数据
			replace(Rcv_buf, "XXEE", "");
			cJSON* pRoot = cJSON_Parse(Rcv_buf);

			int iRet = -1;
			if (pRoot)
			{
				pcmd = cJSON_GetObjectItem(pRoot, "cmd");
				if (pcmd)
				{
					//判断请求类型
					if(strcmp(pcmd->valuestring, "reset_device") == 0)
					{
						iRet = 0;
					}
				}

			}
			if(iRet == 0)
			{
				LOG_INFO_FORMAT("INFO  - [SWM]:切流器[%s] 重置流成功 \n",pFindSeverInfo->strServerIPAddr);
				pFindSeverInfo->iStreamStatus = 0;
				pFindSeverInfo->iCurrentSwitchNumber = 0;
			}
			else
			{
				
				LOG_INFO_FORMAT("INFO  - [SWM]:切流器[%s] 重置流失败 \n",pFindSeverInfo->strServerIPAddr);
				pFindSeverInfo->iStreamStatus = 1;  //流状态异常
			}
		}
		else
			printf("---切流器 不在线 %s \n",pFindSeverInfo->strServerIPAddr);
		
		++iterLook;
	}

	pthread_mutex_unlock(&ManagerFactory::instance()->m_mutexServerList);

	if(!bIsReplyflag)
	{
		ReplyException(strUrl,outPutUrl,Error_ReSet_Device);
		LOG_INFO("INFO  - [SWM]: Delete ALL stream exception \n");
	}

	return 0;

}
Example #10
0
void FilesPageHandler::handle(Client &client) {
	Common::String response =
		"<html>" \
		"<head><title>ScummVM</title></head>" \
		"<body>" \
		"<p>{create_directory_desc}</p>" \
		"<form action=\"create\">" \
		"<input type=\"hidden\" name=\"path\" value=\"{path}\"/>" \
		"<input type=\"text\" name=\"directory_name\" value=\"\"/>" \
		"<input type=\"submit\" value=\"{create_directory_button}\"/>" \
		"</form>" \
		"<hr/>" \
		"<p>{upload_file_desc}</p>" \
		"<form action=\"upload?path={path}\" method=\"post\" enctype=\"multipart/form-data\">" \
		"<input type=\"file\" name=\"upload_file-f\" allowdirs multiple/>" \
		"<span>{or_upload_directory_desc}</span>" \
		"<input type=\"file\" name=\"upload_file-d\" directory webkitdirectory multiple/>" \
		"<input type=\"submit\" value=\"{upload_file_button}\"/>" \
		"</form>"
		"<hr/>" \
		"<h1>{index_of_directory}</h1>" \
		"<table>{content}</table>" \
		"</body>" \
		"</html>";
	Common::String itemTemplate = "<tr><td><img src=\"icons/{icon}\"/></td><td><a href=\"{link}\">{name}</a></td><td>{size}</td></tr>\n"; //TODO: load this template too?

																																		  // load stylish response page from the archive
	Common::SeekableReadStream *const stream = HandlerUtils::getArchiveFile(FILES_PAGE_NAME);
	if (stream)
		response = HandlerUtils::readEverythingFromStream(stream);

	Common::String path = client.queryParameter("path");
	Common::String content = "";

	// show an error message if failed to list directory
	if (!listDirectory(path, content, itemTemplate)) {
		HandlerUtils::setFilesManagerErrorMessageHandler(client, _("ScummVM couldn't list the directory you specified."));
		return;
	}

	//these occur twice:
	replace(response, "{create_directory_button}", _("Create directory"));
	replace(response, "{create_directory_button}", _("Create directory"));
	replace(response, "{path}", encodeDoubleQuotes(client.queryParameter("path")));
	replace(response, "{path}", encodeDoubleQuotes(client.queryParameter("path")));
	replace(response, "{upload_files_button}", _("Upload files")); //tab
	replace(response, "{upload_file_button}", _("Upload files")); //button in the tab
	replace(response, "{create_directory_desc}", _("Type new directory name:"));
	replace(response, "{upload_file_desc}", _("Select a file to upload:"));
	replace(response, "{or_upload_directory_desc}", _("Or select a directory (works in Chrome only):"));
	replace(response, "{index_of_directory}", Common::String::format(_("Index of %s"), encodeHtmlEntities(getDisplayPath(client.queryParameter("path"))).c_str()));
	replace(response, "{content}", content);
	LocalWebserver::setClientGetHandler(client, response);
}
Example #11
0
String String::replace(CStrRef search, CStrRef replacement) const {
  int count;
  return replace(search, replacement, count, true);
}
Example #12
0
void InterpretedIC::cleanup() {
  if (is_empty()) return; // Nothing to cleanup

  switch (send_type()) {
    case Bytecodes::accessor_send:    // fall through
    case Bytecodes::primitive_send:   // fall through
    case Bytecodes::predicted_send:   // fall through
    case Bytecodes::interpreted_send:
      { // check if the interpreted send should be replaced by a compiled send	 
        klassOop receiver_klass = klassOop(second_word());
        assert(receiver_klass->is_klass(), "receiver klass must be a klass");
        methodOop method = methodOop(first_word());
        assert(method->is_method(), "first word in interpreter IC must be method");
        if (!Bytecodes::is_super_send(send_code())) {
	  // super sends cannot be handled since the sending method holder is unknown at this point.
	  LookupKey key(receiver_klass, selector());
          LookupResult result = lookupCache::lookup(&key);
	  if (!result.matches(method)) {
            replace(result, receiver_klass);
	  }
	}
      }
      break;
    case Bytecodes::compiled_send:
      { // check if the current compiled send is valid
        klassOop receiver_klass = klassOop(second_word());
        assert(receiver_klass->is_klass(), "receiver klass must be a klass");
        jumpTableEntry* entry = (jumpTableEntry*) first_word();
        nmethod* nm = entry->method();
        LookupResult result = lookupCache::lookup(&nm->key);
	if (!result.matches(nm)) {
          replace(result, receiver_klass);
	}
      }
      break;
    case Bytecodes::megamorphic_send:
      // Note that with the current definition of is_empty()
      // this will not be called for normal megamorphic sends
      // since they store only the selector.
      { klassOop receiver_klass = klassOop(second_word());
	if (first_word()->is_smi()) {
	  jumpTableEntry* entry = (jumpTableEntry*) first_word();
          nmethod* nm = entry->method();
          LookupResult result = lookupCache::lookup(&nm->key);
          if (!result.matches(nm)) {
	    replace(result, receiver_klass);
	  }
	} else {
          methodOop method = methodOop(first_word());
          assert(method->is_method(), "first word in interpreter IC must be method");
          if (!Bytecodes::is_super_send(send_code())) {
	    // super sends cannot be handled since the sending method holder is unknown at this point.
	    LookupKey key(receiver_klass, selector());
            LookupResult result = lookupCache::lookup(&key);
	    if (!result.matches(method)) {
              replace(result, receiver_klass);
	    }
          }
	}
      }
      break;
    case Bytecodes::polymorphic_send:
      {
        // %implementation note:
	//   when cleaning up we can always preserve the old pic since the
	//   the only transitions are:
	//     (compiled    -> compiled)
	//     (compiled    -> interpreted)
	//     (interpreted -> compiled)
        //   in case of a super send we do not have to cleanup because
	//   no nmethods are compiled for super sends. 
	if (!Bytecodes::is_super_send(send_code())) {
          objArrayOop pic = pic_array();
          for (int index = pic->length(); index > 0; index -= 2) {
            klassOop klass = klassOop(pic->obj_at(index));
	    assert(klass->is_klass(), "receiver klass must be klass");
            oop first = pic->obj_at(index-1);
	    if (first->is_smi()) {
	      jumpTableEntry* entry = (jumpTableEntry*) first;
              nmethod* nm = entry->method();
              LookupResult result = lookupCache::lookup(&nm->key);
              if (!result.matches(nm)) {
                pic->obj_at_put(index-1, result.value());
	      }
	    } else {
              methodOop method = methodOop(first);
              assert(method->is_method(), "first word in interpreter IC must be method");
	      LookupKey key(klass, selector());
              LookupResult result = lookupCache::lookup(&key);
	      if (!result.matches(method)) {
                pic->obj_at_put(index-1, result.value());
	      }
	    }
          }
	}
      }
   }
}
std::string Regex::Match::replace(std::string rp)
{
    ReplaceVector tmp;
    tmp.push_back(rp);
    return replace(tmp);
}
Example #14
0
int main()
{ 
	char insertString[100];
	int caseNum, index, delnum;

	linkedList_h* List;
	List = createLinkedList_h();
	do
	{
		printf("\n----------Linkedlist Menu----------\n");
		printf("\n");
		printf("1. addNode \n2. insertMNode \n3. removeNode \n4. allClear \n5. get \n6. contains \n7. indexOf \n8. size \n9. replace \n0. exit\n");
		printf("\nChoose the number which you want : ");
		scanf("%d", &caseNum);
		switch(caseNum)
		{
			case 1:
				printf("Insert string in the list : ");
	 			scanf("%s", insertString);
    				add(List, insertString);
				printList(List);
				break;
			case 2:
				printf("What is number of index that you insert string? ");
 				scanf("%d",&index);
     				printf("\n");
     				printf("String of inserted index : ");
     				scanf("%s",insertString);
     				insertMNode(List, index, insertString);
				printList(List);
				break;
			case 3:
				printf("\n What number of index that you will delete : ");
				scanf("%d", &delnum);
    				removeNode(List, delnum);
    				printList(List);
				break;
			case 4:
				printf("Delete All\n");
				clear(List);
				printList(List);
				break;
			case 5:
				printf("What is index that you want to see : ");
    				scanf("%d", &index);
    				get(List, index);
				printf("\n");
    				printList(List);
				break;
			case 6:
				printf("If you are curious about what you want, Write string : ");
				scanf("%s", insertString);
				contains(List, insertString);
				break;
			case 7:
				printf("What is word what you want to know?? \n");
				scanf("%s", insertString);
				indexOf(List, insertString);
				break;
			case 8:
				printf("\n");
				printf("Size of List : ");
				size(List);
				break;
			case 9:
				printf("what is the word to be entered? : \n");
				scanf("%s", insertString);
				printf("What is number of index what be replaced? \n");
				scanf("%d", &index);
				replace(List, index, insertString);
				printList(List);
				break;
			case 0:
				printf("EXIT\n");
				break;
			default:
				printf("Wrong number. Please write again : ");
				break;	
		}
	}while(caseNum!=0);
	return 0;
}
Example #15
0
//处理MSI接口
void *SM_Control::Parse_recv_MSI_thread(void * arg)
{
	SM_Control *this0 = (SM_Control*)arg;
	int len;
	char Rcv_buf[4096];
	cJSON *pcmd = NULL;
	char cJsonBuff[1024 * 2];
	int iRecvLen = 0;
	int accept_fd = 0;
	Sockfd::iterator iterList = this0->m_MsiacceptSocket.begin();
	if(iterList != this0->m_MsiacceptSocket.end())
	{
		accept_fd = *iterList;
		this0->m_MsiacceptSocket.erase(iterList);
		printf("111222---accept_fd = %d\n",accept_fd);
		fflush(stdout);
	}
	while(1)
	{
			if(accept_fd == -1)
			{
				printf("error accept socket in msi\n");
				fflush(stdout);
				break;
			}
			memset(Rcv_buf,0,sizeof(Rcv_buf));
			int length = 0;
			int i_rc = 0, i_count = 0;
			do
			{
				i_rc = recv(accept_fd, Rcv_buf + i_count, 2000 - i_count, 0);
				if (i_rc <= 0)break;//异常关闭
				i_count += i_rc;
			} while (strstr(Rcv_buf, "XXEE") == NULL);
			iRecvLen = i_count;
			if (iRecvLen <= 0) break;
	
			printf("recv:%s \n",Rcv_buf);
			fflush(stdout);
	
					//解析报文数据
			replace(Rcv_buf, "XXEE", "");
			cJSON* pRoot = cJSON_Parse(Rcv_buf);	

			if (pRoot)
			{
				pcmd = cJSON_GetObjectItem(pRoot, "cmd");
				if (pcmd)
				{
					
					//判断请求类型
					if (strcmp(pcmd->valuestring, "stream_bind") == 0)
					{
						printf("--bind_stream request \n");
						fflush(stdout);
						//通过
						cJSON* pUserName = cJSON_GetObjectItem(pRoot, "username");
						char strUserName[128] ={0};
						if(pUserName)
							memcpy(strUserName,pUserName->valuestring,strlen(pUserName->valuestring)+1);
						cJSON* pToken = cJSON_GetObjectItem(pRoot, "token");
						char strToken[128] ={0};
						if(pToken) memcpy(strToken,pToken->valuestring,strlen(pToken->valuestring)+1);
						cJSON* pStreamID = cJSON_GetObjectItem(pRoot, "stream_id");
						int iStreamID = -1;
						if(pStreamID) iStreamID = atoi(pStreamID->valuestring);

						cJSON* pRecallAddr = cJSON_GetObjectItem(pRoot, "recall_addr");
						char strRecallAddr[128] ={0};
						if(pRecallAddr) memcpy(strRecallAddr,pRecallAddr->valuestring,strlen(pRecallAddr->valuestring)+1);

						cJSON* pSerialNo = cJSON_GetObjectItem(pRoot,"serialno");
						
						char strSerialNo[128] ={0};
						if(pSerialNo)
							memcpy(strSerialNo,pSerialNo->valuestring,strlen(pSerialNo->valuestring)+1);

						printf("istreamid=%d usename=%s token=%s \n",iStreamID,strUserName,strToken);
						this0->m_cSM_Manager->Bindagain(strUserName,iStreamID);
						fflush(stdout);
					//	printf("---request parse \n");
						int iChannelInfo=0;
						//调manager 中绑定
						int ret = this0->m_cSM_Manager->Bind_OneStream(iStreamID,strUserName,strToken,&iChannelInfo);
						
						//回复
						/*
							{"cmd":"stream_bind","ret_code":"0","serialno":"c0e1758d697841fa8dad428c23b867a7"}XXEE
						*/

						//查询高标清
/*
						StreamResource pTmpResource;
						memset(&pTmpResource,0,sizeof(pTmpResource));
						char strkey_value[64] = {0};
						sprintf(strkey_value,"%d",iStreamID);
						int iret = DBInterfacer::GetInstance()->FindOneStream(4,"iStreamID",strkey_value,&pTmpResource);
						int iwhetherhd;
						if(iret)
						{
							iwhetherhd = pTmpResource.iWherether_HD;
							printf("iWherether_HD = %d\n",iwhetherhd);
							fflush(stdout);
						}

*/
						//报文回复
						Stream ptmpRequest;
						
						ptmpRequest.m_clientSocket = accept_fd;
						//cJSON *pRet_root;
						ptmpRequest.pRet_root = cJSON_CreateObject();
						ptmpRequest.Requst_Json_str(2,"cmd","stream_bind");
					
						char txt[32] ={0};
						sprintf(txt,"%d",ret);
						ptmpRequest.Requst_Json_str(2,"ret_code",txt);

						char strChannelInfo[32]={0};
						sprintf(strChannelInfo,"%d",iChannelInfo);
						ptmpRequest.Requst_Json_str(2,"ChannelInfo",strChannelInfo);
						ptmpRequest.Requst_Json_str(2,"serialno",strSerialNo);
						char csip[128] = {0};
						char csport[64] = {0};
						this0->m_cSM_Manager->Findcsaddr(csip,csport,iStreamID);
				
						ptmpRequest.Requst_Json_str(2,"strNavIP",csip);
						ptmpRequest.Requst_Json_str(2,"iNavPort",csport);
						
	/*				
						char channel_type[12] = {0};
						sprintf(channel_type,"%d",iwhetherhd);
						ptmpRequest.Requst_Json_str(2,"channel_type",channel_type);
	*/				
						ptmpRequest.Send_Jsoon_str();
						if(ret>=0)
						{
							this0->m_cSM_Manager->Userbehav(iStreamID,"B",strUserName,"stream_bind sucess",ret,NULL);
						}
						else
							this0->m_cSM_Manager->Userbehav(iStreamID,"B",strUserName,"stream_bind faild",ret,NULL);
						//补发一路新导航流
						
						if(ret >= 0)
							this0->m_cSM_Manager->AddOneStream(Navigation,iStreamID);			
						
					}
					else if(strcmp(pcmd->valuestring, "vod_play") == 0)
					{
						printf("--Vod_call_stream request \n");
						fflush(stdout);
						//通过
						cJSON* pUserName = cJSON_GetObjectItem(pRoot, "username");
						char strUserName[128] ={0};
						if(pUserName)
							memcpy(strUserName,pUserName->valuestring,strlen(pUserName->valuestring)+1);
						cJSON* pStreamID = cJSON_GetObjectItem(pRoot, "stream_id");
						int iStreamID = -1;
						if(pStreamID) iStreamID = atoi(pStreamID->valuestring);

						cJSON* pUrlAddr = cJSON_GetObjectItem(pRoot, "url");
						char strUrlAddr[128] ={0};
						if(pUrlAddr) memcpy(strUrlAddr,pUrlAddr->valuestring,strlen(pUrlAddr->valuestring)+1);

						cJSON* pSerialNo = cJSON_GetObjectItem(pRoot,"serialno");
						
						char strSerialNo[128] ={0};
						if(pSerialNo)
							memcpy(strSerialNo,pSerialNo->valuestring,strlen(pSerialNo->valuestring)+1);
						
						//vodname
						cJSON* pVodename = cJSON_GetObjectItem(pRoot,"vodname");
						
						char vodname[128] ={0};
						if(pVodename)
						memcpy(vodname,pVodename->valuestring,strlen(pVodename->valuestring)+1);
						printf("vodname = %s\n",vodname);
						fflush(stdout);
						
						//posterurl

						cJSON* pPosterurl = cJSON_GetObjectItem(pRoot,"posterurl");
						char posterurl[128] ={0};
						if(pPosterurl)
						memcpy(posterurl,pPosterurl->valuestring,strlen(pPosterurl->valuestring)+1);
						printf("posterurl = %s\n",posterurl);
						fflush(stdout);
						
						int ret=0;
						printf("======msi connect fd=%d \n",accept_fd);
						fflush(stdout);
						//调manager 中点播			
						 ret = this0->m_cSM_Manager->AddOneVodStream(iStreamID,strUrlAddr,accept_fd,strUserName,vodname,posterurl,strSerialNo);//需要参数
						
						if(ret>=0)
						{
							this0->m_cSM_Manager->Userbehav(iStreamID,"D",strUserName,"vod_play success",ret,NULL);
						}
						if(ret<0)
							this0->m_cSM_Manager->Userbehav(iStreamID,"D",strUserName,"vod_play faild",ret,NULL);
						
					}
					else if (strcmp(pcmd->valuestring, "goback") == 0)
					{
						printf("--bind_stream request \n");
						fflush(stdout);
						//通过
						cJSON* pSeesid = cJSON_GetObjectItem(pRoot, "sessionid");

						int iSeessionID = 0;
						if(pSeesid) iSeessionID = atoi(pSeesid->valuestring);
	
						cJSON* pSerialNo = cJSON_GetObjectItem(pRoot,"serialno");
						char strSerialNo[128] ={0};
						//printf("parse--%s\n",pSerialNo->valuestring);
						if(pSerialNo)
							memcpy(strSerialNo,pSerialNo->valuestring,strlen(pSerialNo->valuestring)+1);

						cJSON* pMsg = cJSON_GetObjectItem(pRoot,"msg");
						char strMsg[128] ={0};
						//printf("parse--%s\n",pSerialNo->valuestring);
						if(pMsg)
							memcpy(strMsg,pMsg->valuestring,strlen(pMsg->valuestring)+1);
						cJSON* pUsername = cJSON_GetObjectItem(pRoot,"username");
						char iUsername[64] = {0};
						if(pUsername)
							memcpy(iUsername,pUsername->valuestring,strlen(pUsername->valuestring)+1);
						//iSeessionID = atoi(strSerialNo);
						
						//vod结束退出处理
						this0->m_cSM_Manager->VodStreamOver(iSeessionID,iUsername);

						this0->m_cSM_Manager->Tellcums(iUsername);

						usleep(1000*8000);
						
						pthread_mutex_lock(&this0->m_cSM_Manager->m_lockerRegion);
						SetUsedRegionID::iterator itused = this0->m_cSM_Manager->m_SetUsedRegionID.find(iSeessionID);
						if(itused != this0->m_cSM_Manager->m_SetUsedRegionID.end())
						{
							//有正在使用的等会释放
							
							char txt[128]={0};
									sprintf(txt,"%d",itused->second);
									printf("-----erase region %s success \n",txt);
									fflush(stdout);
							this0->m_cSM_Manager->m_SetUsedRegionID.erase(itused);
						}
							pthread_mutex_unlock(&this0->m_cSM_Manager->m_lockerRegion);
						this0->m_cSM_Manager->Userbehav(iSeessionID,"E",iUsername,"vod_play_over",0,NULL);
						
					}
					//绑定超时
					else if (strcmp(pcmd->valuestring, "overtime") == 0)
					{	
						printf("bind time------");
						fflush(stdout);
						cJSON* pStreamID = cJSON_GetObjectItem(pRoot, "streamid");
						if(pStreamID->valuestring!=NULL)
						{	
							int iStreamID = -1;
							if(pStreamID) iStreamID = atoi(pStreamID->valuestring);
							this0->m_cSM_Manager->BindOverTime(iStreamID);
						}
					}
					//VOD暂停
					else if(strcmp(pcmd->valuestring,"vod_pause")==0)
					{
						cJSON* pStreamID = cJSON_GetObjectItem(pRoot, "stream_id");
						cJSON* pUsername = cJSON_GetObjectItem(pRoot, "username");
						//vodname
						cJSON* pVodename = cJSON_GetObjectItem(pRoot,"vodname");
						
						char vodname[128] ={0};
						if(pVodename)
						memcpy(vodname,pVodename->valuestring,strlen(pVodename->valuestring)+1);
						printf("vodname = %s\n",vodname);
						fflush(stdout);
						//posterurl

						cJSON* pPosterurl = cJSON_GetObjectItem(pRoot,"posterurl");
						char posterurl[128] ={0};
						if(pPosterurl)
						memcpy(posterurl,pPosterurl->valuestring,strlen(pPosterurl->valuestring)+1);
						printf("posterurl = %s\n",posterurl);
						fflush(stdout);
						
						if(pStreamID->valuestring!=NULL)
						{
							int iStreamID = -1;
							if(pStreamID) iStreamID = atoi(pStreamID->valuestring);
							char iUsername[32] = {0};
							strcpy(iUsername,pUsername->valuestring);
							printf("----1234iUsername = %s\n",iUsername);
							fflush(stdout);
							this0->m_cSM_Manager->PauseVOD(iStreamID,iUsername,vodname,posterurl);
						}
						
						Stream ptmpRequest;

						ptmpRequest.m_clientSocket = accept_fd;
						//cJSON *pRet_root;
						ptmpRequest.pRet_root = cJSON_CreateObject();
						ptmpRequest.Requst_Json_str(2,"cmd","vod_pause");
					
						char txt[32] ={0};
						sprintf(txt,"%d",0);
						ptmpRequest.Requst_Json_str(2,"ret_code",txt);

						ptmpRequest.Requst_Json_str(2,"serialno","ade8976d88d76");
						ptmpRequest.Send_Jsoon_str();
						
				   }
					//暂停超时
				  else if(strcmp(pcmd->valuestring,"pause")==0)
				  {
						char iUsername[32] = {0};
						cJSON* pStreamID = cJSON_GetObjectItem(pRoot, "streamid");
						cJSON* pSUserID = cJSON_GetObjectItem(pRoot, "username");
						strcpy(iUsername,pSUserID->valuestring);
						if(pStreamID->valuestring!=NULL)
						{	
							int iStreamID = -1;
							if(pStreamID) iStreamID = atoi(pStreamID->valuestring);
							this0->m_cSM_Manager->BindOverTime(iStreamID);
							this0->m_cSM_Manager->Tellcums(iUsername);
						}
				  }
				  else if(strcmp(pcmd->valuestring,"vod_resume")==0)
				  {
						
						cJSON* pStreamID = cJSON_GetObjectItem(pRoot, "stream_id");
						if(pStreamID->valuestring!=NULL)
						{	
							int iStreamID = -1;
							printf("1111111111111112222streamid = %s",pStreamID->valuestring);
							fflush(stdout);
							if(pStreamID) iStreamID = atoi(pStreamID->valuestring);
							this0->m_cSM_Manager->RecoverVodPlay(iStreamID,NULL,NULL,NULL);
						}
						Stream ptmpRequest;

						ptmpRequest.m_clientSocket = accept_fd;
						//cJSON *pRet_root;
						ptmpRequest.pRet_root = cJSON_CreateObject();
						ptmpRequest.Requst_Json_str(2,"cmd","vod_resume");
						
						char txt[32] ={0};
						sprintf(txt,"%d",0);
						ptmpRequest.Requst_Json_str(2,"ret_code",txt);
						ptmpRequest.Requst_Json_str(2,"serialno","ade8976d88d76");
						ptmpRequest.Send_Jsoon_str();
				  }
				 else if (strcmp(pcmd->valuestring,"stream_unbind") == 0)
				 {	
					printf("unbind time------");
					fflush(stdout);
					char iusernam[128] = {0};
					char ustreamid[32] = {0};
					int istreamid = 0;
					cJSON* pStreamID = cJSON_GetObjectItem(pRoot, "stream_id");
					if(pStreamID)
					{
						if(pStreamID->valuestring)
						{
							strcpy(ustreamid,pStreamID->valuestring);
							istreamid = atoi(ustreamid);
						}
					}
					cJSON* pStreamuser = cJSON_GetObjectItem(pRoot, "username");
					if(pStreamuser)
					{
						if(pStreamuser->valuestring)
						strcpy(iusernam,pStreamuser->valuestring);
					}
					char iserialno[64]={0};
					cJSON* pSerialno = cJSON_GetObjectItem(pRoot, "iserialno");
					if(pSerialno)
					{
						if(pSerialno->valuestring)
						strcpy(iserialno,pSerialno->valuestring);
					}
		
					this0->m_cSM_Manager->Unbind(iusernam,ustreamid);
					this0->m_cSM_Manager->CleanStream(istreamid);
					usleep(1000*1800);
					this0->m_cSM_Manager->AddOneAdvStream(istreamid);

					Stream ptmpRequest;
					ptmpRequest.m_clientSocket = accept_fd;
						//cJSON *pRet_root;
					ptmpRequest.pRet_root = cJSON_CreateObject();
					ptmpRequest.Requst_Json_str(2,"cmd","stream_unbind");
					
					int ret = 0;
					char txt[32] ={0};
					sprintf(txt,"%d",ret);
					ptmpRequest.Requst_Json_str(2,"ret_code",txt);
					ptmpRequest.Requst_Json_str(2,"serialno",iserialno);
					ptmpRequest.Send_Jsoon_str();
					
				}		 
				else if(strcmp(pcmd->valuestring,"quit")==0)
				{
					cJSON* pStreamID = cJSON_GetObjectItem(pRoot, "stream_id");
					cJSON* pUsername = cJSON_GetObjectItem(pRoot, "username");
					if(pStreamID->valuestring!=NULL)
					{
						int iStreamID = -1;
						if(pStreamID) iStreamID = atoi(pStreamID->valuestring);
						char iUsername[32] = {0};
						strcpy(iUsername,pUsername->valuestring);
						this0->m_cSM_Manager->PauseVOD(iStreamID,iUsername,NULL,NULL,1);
					}
					
					Stream ptmpRequest;
					
					ptmpRequest.m_clientSocket = accept_fd;
					//cJSON *pRet_root;
					ptmpRequest.pRet_root = cJSON_CreateObject();
					ptmpRequest.Requst_Json_str(2,"cmd","quit");
				
					char txt[32] ={0};
					sprintf(txt,"%d",0);
					ptmpRequest.Requst_Json_str(2,"ret_code",txt);

					ptmpRequest.Requst_Json_str(2,"serialno","ade8976d88d76");
					ptmpRequest.Send_Jsoon_str();
						
				}
				
				else if(strcmp(pcmd->valuestring,"recovery")==0)
				 {
						
					cJSON* pStreamID = cJSON_GetObjectItem(pRoot, "stream_id");
					int iStreamID = -1;
					if(pStreamID->valuestring)
					{
						printf("----this is Recovery streamid = %s\n",pStreamID->valuestring);
						fflush(stdout);
						if(pStreamID) iStreamID = atoi(pStreamID->valuestring);
					}
					//username
					char iusername[64]={0};
					cJSON* pUsername = cJSON_GetObjectItem(pRoot, "username");
					if(pUsername)
					{
						memcpy(iusername,pUsername->valuestring,strlen(pUsername->valuestring)+1);
					}	
					printf("----4567iUsername = %s\n",iusername);
					fflush(stdout);
					//vodname
					char ivodname[128] = {0};
					cJSON* pVodname = cJSON_GetObjectItem(pRoot, "vodname");
					if(pVodname)
					{
						memcpy(ivodname,pVodname->valuestring,strlen(pVodname->valuestring)+1);
					}

					//posterurl
					char iposterurl[128] = {0};
					cJSON* pPosterurl = cJSON_GetObjectItem(pRoot, "posterurl");
					if(pPosterurl)
					{
						memcpy(iposterurl,pPosterurl->valuestring,strlen(pPosterurl->valuestring)+1);
					}
					
					this0->m_cSM_Manager->RecoverVodPlay(iStreamID,iusername,ivodname,iposterurl);
					
					Stream ptmpRequest;

					ptmpRequest.m_clientSocket = accept_fd;
					//cJSON *pRet_root;
					ptmpRequest.pRet_root = cJSON_CreateObject();
					ptmpRequest.Requst_Json_str(2,"cmd","recovery");
						
					char txt[32] ={0};
					sprintf(txt,"%d",0);
					ptmpRequest.Requst_Json_str(2,"ret_code",txt);
					ptmpRequest.Requst_Json_str(2,"serialno","ade8976d88d76");
					ptmpRequest.Send_Jsoon_str();
				 }
			}
		}
			
	}

		close(accept_fd);

}
//返回的是关联的会话
int Switch_Manager::AddOneSwitch(char* strUrl,char* outPutUrl,char* strSessionID,char* inputUrl)
{
	printf("-----AddOneSwitch\n");
	LOG_DEBUG("DEBUG - [SWM]: - AddOneSwitch\n");
	
	//查找可用的sever  找使用率最小的
				//遍历切流器
	printf("-----add switch %s \n",strSessionID);
	SwitchSeverInfo **ppFindSeverInfo = (SwitchSeverInfo **)malloc(sizeof(SwitchSeverInfo *));
	memset(ppFindSeverInfo,0,sizeof(ppFindSeverInfo));

	int iRet = FindOneSwitchServer(strSessionID,ppFindSeverInfo);
	//找到对应服务器
	SwitchSeverInfo *pFindSeverInfo = NULL;
	
	if(iRet == 0 && *ppFindSeverInfo!= NULL)
	{
		//找到正在转发的流
		pFindSeverInfo = *ppFindSeverInfo;
	}
	else
	{
		//新增的转发流
		//需要根据inputip来确定使用哪个sever
		//解析出ip 端口
		int iSrcPort = 0;
		char strSrcIP[128]={0};

		char strSrcPort[32]={0};
		FindDataFromString(inputUrl,strSrcIP,strSrcPort);
		iSrcPort = atoi(strSrcPort);
		//根据IP查找sever
		iRet = FindSwitchServerFromIP(strSrcIP,ppFindSeverInfo);
		if(*ppFindSeverInfo ==NULL)
		{
			//如果没有指定ip则由调度分配
		
			iRet = GetOneSwitchServer(ppFindSeverInfo);
			if(*ppFindSeverInfo ==NULL)
			{
				printf("---no can used sever -----\n");
				
				ReplyException(strUrl,outPutUrl,Error_NO_Sever);
				
				return -1; //没有可以用的Switch_Sever;
			}
		}

		pFindSeverInfo = *ppFindSeverInfo;
	}

	//连接server 
	//报文转发
	Stream ptmpRequest;
	int iret = ptmpRequest.ConnectServer(pFindSeverInfo->strServerIPAddr,pFindSeverInfo->iListenPort);
	if(iret != 0)
	{
		//连接失败
		ReplyException(strUrl,outPutUrl,Error_Connect_Sever);
		return -1;
	}
	iret = ptmpRequest.Send_str(strUrl);
	if(iret != 0)
	{
		ReplyException(strUrl,outPutUrl,Error_Connect_Sever);
		return -1;
	}
	char Rcv_buf[1024]={0};
	int iLen = sizeof(Rcv_buf);
	iret = ptmpRequest.Recv_str(Rcv_buf,&iLen);
	if(iret !=0)
	{
		ReplyException(strUrl,outPutUrl,Error_Recv_Sever);
		return -1;
	}

	memcpy(outPutUrl,Rcv_buf,iLen);
	cJSON *pcmd = NULL;
	//解析报文数据
	replace(Rcv_buf, "XXEE", "");
	cJSON* pRoot = cJSON_Parse(Rcv_buf);
	
	if (pRoot)
	{
		pcmd = cJSON_GetObjectItem(pRoot, "cmd");
		if (pcmd)
		{
	
			//判断请求类型
			if (strcmp(pcmd->valuestring, "add_ads_stream") == 0)
			{
				printf("--add_ads_stream return \n");
				//通过
				cJSON* pSeesid = cJSON_GetObjectItem(pRoot, "sessionid");
				char strSeesionID[128] ={0};
				
				int iSeessionID = 0;
				if(pSeesid){
					iSeessionID = atoi(pSeesid->valuestring);
					memcpy(strSeesionID,pSeesid->valuestring,strlen(pSeesid->valuestring)+1);
				}
				cJSON* pTaskID = cJSON_GetObjectItem(pRoot, "task_id");
				int iTaskID = -1;
				if(pTaskID) iTaskID = pTaskID->valueint;
				cJSON* pRetCOde = cJSON_GetObjectItem(pRoot,"ret_code");
				int iRetCode = -1;
				if(pRetCOde) iRetCode = atoi(pRetCOde->valuestring);
				cJSON* pSerialNo = cJSON_GetObjectItem(pRoot,"serialno");
				char strSerialNo[128] ={0};
				if(pSerialNo)
					memcpy(strSerialNo,pSerialNo->valuestring,strlen(pSerialNo->valuestring)+1);
				if(iRetCode >= 0)
				{
					//添加成功增加关联sessionID 和severID 键值对
					
					pthread_mutex_lock(&m_lockerttTaskInfo);
					MapSeverInfo::iterator itlook = m_mapSwitchTaskInfo.find(strSeesionID);
					if(itlook != m_mapSwitchTaskInfo.end())
					{
						//出现两个一样会话ID 先删除 yyd
						m_mapSwitchTaskInfo.erase(itlook);
					}

					pFindSeverInfo->iCurrentSwitchNumber++;
					m_mapSwitchTaskInfo.insert(MapSeverInfo::value_type(strSeesionID,pFindSeverInfo->iServerID));
					printf("----insert to map %s ,size=%d \n",strSeesionID,m_mapSwitchTaskInfo.size());
					pthread_mutex_unlock(&m_lockerttTaskInfo);
					LOG_INFO_FORMAT("----insert to map %s ,size=%d \n",strSeesionID,m_mapSwitchTaskInfo.size());
				}
				
			}
		}
	}

	return 0;
}
Example #17
0
static int s_multiPortal_content_of_page( STPageInfo *pstPageInfo )
{
	
	FILE * fp = pstPageInfo->fp;
	struct list * portal_public = pstPageInfo->lpublic;
	struct list * portal_auth = pstPageInfo->lauth;
	int i, cl = 0;

	char menu[21]="";
	char i_char[10]="";

	/////////////读取数据/////////////////////////
	int ret = 0;
	struct portal_conf portalconf;
	char keyvalue[128] = {0};
	memset( &portalconf, 0, sizeof(struct portal_conf) );
	
	ret = eag_get_portal_conf(ccgi_connection, 
									parameter.local_id,
									parameter.instance_id, 
									&portalconf );

	fprintf(fp,	"<table border=0 cellspacing=0 cellpadding=0>"\
					"<tr>");
	if(pstPageInfo->iUserGroup == 0)
		{
			fprintf(fp,"<td><a id=link href=wp_add_multi_portal.cgi?UN=%s&plotid=%s>%s</a></td>", pstPageInfo->encry,plotid,search(portal_auth,"add_multi_portal") );
		}
	fprintf(fp, "</tr>");
	fprintf(fp,"<tr height=7><td></td></tr>");
	fprintf(fp,"<tr>\n");
	fprintf(fp,"<td>%s</td>",search(portal_auth,"plot_idz"));
	fprintf(fp,"<td><select name=plotid onchange=plotid_change(this)>");
	instance_parameter *pq = NULL;
	char temp[10] = { 0 };
	
	for (pq=paraHead1;(NULL != pq);pq=pq->next)
	{
		memset(temp,0,sizeof(temp));
		snprintf(temp,sizeof(temp)-1,"%d-%d-%d",pq->parameter.slot_id,pq->parameter.local_id,pq->parameter.instance_id);
		
		if (strcmp(plotid, temp) == 0)
			fprintf(cgiOut,"<option value='%s' selected>%s</option>\n",temp,temp);
		else	       
			fprintf(cgiOut,"<option value='%s'>%s</option>\n",temp,temp);
	}
	fprintf(fp,"</select></td>");
	fprintf(fp, "</tr>");
	fprintf(fp,"<tr height=7><td></td></tr>");
	fprintf(fp,"</table>");

	fprintf(fp,"<script type=text/javascript>\n");
   	fprintf(fp,"function plotid_change( obj )\n"\
   	"{\n"\
   	"var plotid = obj.options[obj.selectedIndex].value;\n"\
   	"var url = 'wp_multi_portal.cgi?UN=%s&plotid='+plotid;\n"\
   	"window.location.href = url;\n"\
   	"}\n", pstPageInfo->encry);
    fprintf(fp,"</script>\n" );

	fprintf(fp,	"<table border=0 width=650 cellspacing=0 cellpadding=0>");
	fprintf(fp, "<tr height=30 align=left bgcolor=#eaeff9>");
	fprintf(fp,	"<th width=100>KeyWord</th>");
	fprintf(fp, "<th width=50>Value</th>");
	fprintf(fp,	"<th width=300>URL</th>"\
			"<th width=50>Domain</th>"\
			"<th width=100>%s</th>"\
			"<th width=13>&nbsp;</th>"\
			"</tr>",search(portal_auth,"HS_ACID"));
	for( i=0; i<portalconf.current_num; i++ )
	{		
			memset(menu,0,21);
			strcpy(menu,"menulist");
			sprintf(i_char,"%d",i+1);
			strcat(menu,i_char);

			memset(keyvalue,0,sizeof(keyvalue));
			
			fprintf(fp,	"<tr height=30 align=left bgcolor=%s>", setclour(cl) );
			switch(portalconf.portal_srv[i].key_type) 
			{
				case PORTAL_KEYTYPE_ESSID:
					fprintf(fp, "<td align=left>Essid</td>");
					fprintf(fp, "<td>%s</td>", portalconf.portal_srv[i].key.essid);
					
					//replace_url
					if(replace(portalconf.portal_srv[i].key.essid," ","%20") != NULL)
					{
						strncpy(keyvalue,replace(portalconf.portal_srv[i].key.essid," ","%20"),sizeof(keyvalue)-1);
					}
					else
					{
						strncpy(keyvalue,portalconf.portal_srv[i].key.essid,sizeof(keyvalue)-1);
					}					
					break;
				case PORTAL_KEYTYPE_WLANID:
					fprintf(fp, "<td align=left>Wlanid</td>");
					fprintf(fp, "<td>%u</td>", portalconf.portal_srv[i].key.wlanid);
					snprintf(keyvalue,sizeof(keyvalue)-1,"%u",portalconf.portal_srv[i].key.wlanid);
					break;
				case PORTAL_KEYTYPE_VLANID:
					fprintf(fp, "<td align=left>Vlanid</td>");
					fprintf(fp, "<td>%u</td>", portalconf.portal_srv[i].key.vlanid);
					snprintf(keyvalue,sizeof(keyvalue)-1,"%u",portalconf.portal_srv[i].key.vlanid);
					break;
				case PORTAL_KEYTYPE_WTPID:
					fprintf(fp, "<td align=left>Wtpid</td>");
					fprintf(fp, "<td>%u</td>", portalconf.portal_srv[i].key.wtpid);
					snprintf(keyvalue,sizeof(keyvalue)-1,"%u",portalconf.portal_srv[i].key.wtpid);
					break;
				case PORTAL_KEYTYPE_INTF:
					fprintf(fp, "<td align=left>Intf</td>");
					fprintf(fp, "<td>%s</td>", portalconf.portal_srv[i].key.intf);
					strncpy(keyvalue,portalconf.portal_srv[i].key.intf,sizeof(keyvalue)-1);
					break;					
				default:
					fprintf(fp, "<td align=left colspan=2></td>");
					break;
			}				
			fprintf(fp, "<td>%s</td>", portalconf.portal_srv[i].portal_url);				
			//fprintf(fp, "portal ntfport			:%u\n", portalconf.portal_srv[i].ntf_port);
			if(0 != strcmp(portalconf.portal_srv[i].domain, ""))
			{
				fprintf(fp, "<td>%s</td>", portalconf.portal_srv[i].domain);
			}
			else
			{
				fprintf(fp, "<td>&nbsp;</td>");
			}
			if(0 != strcmp(portalconf.portal_srv[i].acname, ""))
			{
				fprintf(fp, "<td>%s</td>", portalconf.portal_srv[i].acname);
			}
			else
			{
				fprintf(fp, "<td>&nbsp;</td>");
			}
			fprintf(fp,"<td>");
			fprintf(fp, "<div style=\"position:relative; z-index:%d\" onmouseover=\"popMenu('%s');\" onmouseout=\"popMenu('%s');\">",(512-i),menu,menu);
			fprintf(fp, "<img src=/images/detail.gif>"\
			"<div id=%s style=\"display:none; position:absolute; top:5px; left:0;\">",menu);
			fprintf(fp, "<div id=div1>");
			
			char encoder_character_result[256] = { 0 };
			url_encoder(keyvalue, encoder_character_result, escape_character, encoder_character, CHARACTER_NUM);

			fprintf(fp, "<div id=div2 onmouseover=\"this.style.backgroundColor='#b6bdd2'\" onmouseout=\"this.style.backgroundColor='#f9f8f7'\"><a id=link href=wp_multi_portal.cgi?UN=%s&DELRULE=%s&plotid=%s&NODEZ=%d&ATTZ=%s target=mainFrame>%s</a></div>", pstPageInfo->encry , "delete" , plotid,portalconf.portal_srv[i].key_type,encoder_character_result,search(portal_public,"delete"));
			fprintf(fp, "<div id=div2 onmouseover=\"this.style.backgroundColor='#b6bdd2'\" onmouseout=\"this.style.backgroundColor='#f9f8f7'\"><a id=link href=wp_edit_multi_portal.cgi?UN=%s&EDITCONF=%s&plotid=%s&NODEZ=%d&ATTZ=%s target=mainFrame>%s</a></div>", pstPageInfo->encry , "edit" ,plotid,portalconf.portal_srv[i].key_type,encoder_character_result,search(portal_public,"configure"));
			fprintf(fp, "</div>"\
			"</div>"\
			"</div>");
			fprintf(fp,"</td>");
			fprintf(fp,"</tr>");
			cl = !cl;
		}
	fprintf(fp,	"</table>");
	fprintf(fp,"<input type=hidden name=UN value=%s>",pstPageInfo->encry);
	return 0;	
}
int Switch_Manager::DeleteOneSwitch(char* strUrl,char* outPutUrl,char* strSessionID)
{
	printf("----DeleteOneSwitch fun \n");
	LOG_DEBUG("DEBUG - [SWM]: - DeleteOneSwitch fun \n");
	//查找会话
//	printf("---find sessionid %s map size=%d \n",strSessionID,m_mapSwitchTaskInfo.size());

	SwitchSeverInfo** ppSeverSwitch = (SwitchSeverInfo**)malloc(sizeof(SwitchSeverInfo*));
	memset(ppSeverSwitch,0,sizeof(ppSeverSwitch));
	int iRet = FindOneSwitchServer(strSessionID,ppSeverSwitch);
	//找到对应服务器
	
	SwitchSeverInfo *pFindSeverInfo = *ppSeverSwitch;
	if(pFindSeverInfo == NULL)
	{
		printf("---no find sever info or no sessiond \n");
		ReplyException(strUrl,outPutUrl,0);
		return -2;
	}
	//连接server 
	//报文转发
	Stream ptmpRequest;
	int iret = ptmpRequest.ConnectServer(pFindSeverInfo->strServerIPAddr,pFindSeverInfo->iListenPort);
	if(iret != 0)
	{
		//连接失败
		ReplyException(strUrl,outPutUrl,Error_Connect_Sever);
		return -1;
	}
	iret = ptmpRequest.Send_str(strUrl);
	if(iret != 0)
	{
		ReplyException(strUrl,outPutUrl,Error_Connect_Sever);
		return -1;
	}
	char Rcv_buf[1024]={0};
	int iLen = sizeof(Rcv_buf);
	iret = ptmpRequest.Recv_str(Rcv_buf,&iLen);
	if(iret !=0)
	{
		ReplyException(strUrl,outPutUrl,Error_Recv_Sever);
		return -1;
	}

	printf("recv Del strem\n");
	fflush(stdout);
	memcpy(outPutUrl,Rcv_buf,iLen);
	cJSON *pcmd = NULL;
	//解析报文数据
	replace(Rcv_buf, "XXEE", "");
	cJSON* pRoot = cJSON_Parse(Rcv_buf);
	
	if (pRoot)
	{
		pcmd = cJSON_GetObjectItem(pRoot, "cmd");
		if (pcmd)
		{
	
			//判断请求类型
			 if(strcmp(pcmd->valuestring, "del_ads_stream") == 0)
			{
				 cJSON* pSeesid = cJSON_GetObjectItem(pRoot, "sessionid");
				 char strSeesionID[128] ={0};
				 
				 int iSeessionID = 0;
				 if(pSeesid){
					 iSeessionID = atoi(pSeesid->valuestring);
					 memcpy(strSeesionID,pSeesid->valuestring,strlen(pSeesid->valuestring)+1);
				 }

				 cJSON* pRetCOde = cJSON_GetObjectItem(pRoot,"ret_code");
				 int iRetCode = -1;
				 if(pRetCOde) iRetCode = atoi(pRetCOde->valuestring);
				 //printf("parse--%s\n",pRetCOde->valuestring);
				 cJSON* pSerialNo = cJSON_GetObjectItem(pRoot,"serialno");
				 char strSerialNo[128] ={0};
				 //printf("parse--%s\n",pSerialNo->valuestring);
				 if(pSerialNo)
				 memcpy(strSerialNo,pSerialNo->valuestring,strlen(pSerialNo->valuestring)+1);
			 
				 printf("--del_ads_stream return \n");		 

				if(iRetCode >= 0)
				{
					//添加成功增加关联sessionID 和severID 键值对
					
					pthread_mutex_lock(&m_lockerttTaskInfo);
					MapSeverInfo::iterator itlook = m_mapSwitchTaskInfo.find(strSeesionID);
					if(itlook != m_mapSwitchTaskInfo.end())
					{
						//出现两个一样会话ID 先删除 yyd
						m_mapSwitchTaskInfo.erase(itlook);
					}
					//存放sever的map不会在运行中做增删操作
					pFindSeverInfo->iCurrentSwitchNumber--;
					printf("----erase to map %s ,size=%d \n",strSeesionID,m_mapSwitchTaskInfo.size());
					pthread_mutex_unlock(&m_lockerttTaskInfo);
					LOG_INFO_FORMAT("----erase to map %s ,size=%d \n",strSeesionID,m_mapSwitchTaskInfo.size());
				}
				
			}
		}
	}
			
	return 0;
}
Example #19
0
bool calc_float(string& ioString) {
	erase(ioString, " ");
	erase(ioString, " ");
	erase(ioString, "\t");
	replace(ioString, "+", "+");
	replace(ioString, "-", "-");
	replace(ioString, "*", "*");
	replace(ioString, "×", "*");
	replace(ioString, "/", "/");
	replace(ioString, "÷", "/");
	replace(ioString, "<", "<");
	replace(ioString, ">", ">");
	replace(ioString, "=", "=");
	replace(ioString, "!", "!");
	replace(ioString, "&", "&");
	replace(ioString, "|", "|");
	replace(ioString, "(", "(");
	replace(ioString, ")", ")");
	replace(ioString, "0", "0");
	replace(ioString, "1", "1");
	replace(ioString, "2", "2");
	replace(ioString, "3", "3");
	replace(ioString, "4", "4");
	replace(ioString, "5", "5");
	replace(ioString, "6", "6");
	replace(ioString, "7", "7");
	replace(ioString, "8", "8");
	replace(ioString, "9", "9");
	replace(ioString, ".", ".");
	VALUE_TYPE	result;
	if ( !calc_float(ioString.c_str(), &result) )
		return	false;

	char	buf[128];
	sprintf(buf, "%f", result);
	ioString = buf;

	while ( compare_tail(ioString, "0") )
		ioString.assign(ioString.c_str(), ioString.size()-1);
	if ( compare_tail(ioString, ".") )
		ioString.assign(ioString.c_str(), ioString.size()-1);

	return	true;
}
int Switch_Manager::ReplyException(char* strurl,char* strOutUrl,int iRetcode)
{
	printf("-----ReplyException \n");
	LOG_DEBUG("DEBUG - [SWM]: - ReplyException \n");
	if(strOutUrl==NULL)
		return -1;
	char *Rcv_buf=strurl;
		//报文回复
	Stream ptmpRequest;
		cJSON *pcmd = NULL;
			//解析报文数据
	replace(Rcv_buf, "XXEE", "");
	cJSON* pRoot = cJSON_Parse(Rcv_buf);

	if (pRoot)
	{
		pcmd = cJSON_GetObjectItem(pRoot, "cmd");
		if (pcmd)
		{

			//判断请求类型
			if (strcmp(pcmd->valuestring, "add_ads_stream") == 0)
			{
				printf("--Add_stream request exception \n");
				fflush(stdout);
				//通过
				cJSON* psessionid = cJSON_GetObjectItem(pRoot, "sessionid");
				char strsessionid[128] ={0};
				if(psessionid)
					memcpy(strsessionid,psessionid->valuestring,strlen(psessionid->valuestring)+1);
				cJSON* pToken = cJSON_GetObjectItem(pRoot, "input_url");
				char input_url[128] ={0};
				if(pToken) memcpy(input_url,pToken->valuestring,strlen(pToken->valuestring)+1);

				char output_url[128] ={0};
				cJSON* pStreamID = cJSON_GetObjectItem(pRoot, "output_url");
				if(pStreamID) memcpy(output_url,pStreamID->valuestring,strlen(pStreamID->valuestring)+1);

				cJSON* pSerialNo = cJSON_GetObjectItem(pRoot,"serialno");

				char strSerialNo[128] ={0};
				if(pSerialNo)
					memcpy(strSerialNo,pSerialNo->valuestring,strlen(pSerialNo->valuestring)+1);

				//cJSON *pRet_root;
				ptmpRequest.pRet_root = cJSON_CreateObject();
				ptmpRequest.Requst_Json_str(2,"cmd","add_ads_stream");
				ptmpRequest.Requst_Json_str(2,"sessionid",strsessionid);

				ptmpRequest.Requst_Json_str(1,"task_id",strsessionid);
				char txt[32] ={0};
				sprintf(txt,"%d",iRetcode);
				ptmpRequest.Requst_Json_str(2,"ret_code",txt);

				ptmpRequest.Requst_Json_str(2,"serialno",strSerialNo);
				

			}
			else if(strcmp(pcmd->valuestring, "del_ads_stream") == 0)
			{
				printf("--Del_stream request exception\n");
				fflush(stdout);
				//通过
				cJSON* psessionid = cJSON_GetObjectItem(pRoot, "sessionid");
				char strsessionid[128] ={0};
				if(psessionid)
					memcpy(strsessionid,psessionid->valuestring,strlen(psessionid->valuestring)+1);

				cJSON* pSerialNo = cJSON_GetObjectItem(pRoot,"serialno");

				char strSerialNo[128] ={0};
				if(pSerialNo)
					memcpy(strSerialNo,pSerialNo->valuestring,strlen(pSerialNo->valuestring)+1);
				
				ptmpRequest.pRet_root = cJSON_CreateObject();
				ptmpRequest.Requst_Json_str(2,"cmd","del_ads_stream");

				ptmpRequest.Requst_Json_str(2,"sessionid",strsessionid);

				char txt[32] ={0};
				sprintf(txt,"%d",iRetcode);
				ptmpRequest.Requst_Json_str(2,"ret_code",txt);

				ptmpRequest.Requst_Json_str(2,"serialno",strSerialNo);
				
			}
			else if(strcmp(pcmd->valuestring, "reset_device") == 0)
			{
				printf("--reset_stream request exception\n");

				fflush(stdout);
				cJSON* pSerialNo = cJSON_GetObjectItem(pRoot,"serialno");

				char strSerialNo[128] ={0};
				if(pSerialNo)
					memcpy(strSerialNo,pSerialNo->valuestring,strlen(pSerialNo->valuestring)+1);

				//cJSON *pRet_root;
				ptmpRequest.pRet_root = cJSON_CreateObject();
				ptmpRequest.Requst_Json_str(2,"cmd","reset_device");

				char txt[32] ={0};
				sprintf(txt,"%d",iRetcode);
				ptmpRequest.Requst_Json_str(2,"ret_code",txt);

				ptmpRequest.Requst_Json_str(2,"serialno",strSerialNo);
				
			}
			else if (strcmp(pcmd->valuestring, "change_stream") == 0)
			{
				printf("--Change_stream request exception\n");
				fflush(stdout);
				cJSON* old_psessionid = cJSON_GetObjectItem(pRoot, "old_sessionid");
				char old_strsessionid[128] ={0};
				if(old_psessionid)
					memcpy(old_strsessionid,old_psessionid->valuestring,strlen(old_psessionid->valuestring)+1);
				cJSON* psessionid = cJSON_GetObjectItem(pRoot, "sessionid");
				char strsessionid[128] ={0};
				if(psessionid)
					memcpy(strsessionid,psessionid->valuestring,strlen(psessionid->valuestring)+1);
				cJSON* pInterval = cJSON_GetObjectItem(pRoot, "interval");
				char strInterval[128] ={0};
				if(pInterval)
					memcpy(strInterval,pInterval->valuestring,strlen(pInterval->valuestring)+1);


				cJSON* pToken = cJSON_GetObjectItem(pRoot, "input_url");
				char input_url[128] ={0};
				if(pToken) memcpy(input_url,pToken->valuestring,strlen(pToken->valuestring)+1);

				char output_url[128] ={0};
				cJSON* pStreamID = cJSON_GetObjectItem(pRoot, "output_url");
				if(pStreamID) memcpy(output_url,pStreamID->valuestring,strlen(pStreamID->valuestring)+1);

				cJSON* pSerialNo = cJSON_GetObjectItem(pRoot,"serialno");

				char strSerialNo[128] ={0};
				if(pSerialNo)
					memcpy(strSerialNo,pSerialNo->valuestring,strlen(pSerialNo->valuestring)+1);

				//cJSON *pRet_root;
				ptmpRequest.pRet_root = cJSON_CreateObject();
				ptmpRequest.Requst_Json_str(2,"cmd","change_stream");

				char txt[32] ={0};
				sprintf(txt,"%d",iRetcode);
				ptmpRequest.Requst_Json_str(2,"ret_code",txt);

				ptmpRequest.Requst_Json_str(2,"serialno",strSerialNo);
				ptmpRequest.Send_Jsoon_str();


			}
			else if(strcmp(pcmd->valuestring, "check_session") == 0)
			{
				printf("--check_session exception\n");
				//通过
				cJSON* psessionid = cJSON_GetObjectItem(pRoot, "sessionid");
				char strsessionid[128] ={0};
				int iSeessionID = 0;
				if(psessionid)
				{
					memcpy(strsessionid,psessionid->valuestring,strlen(psessionid->valuestring)+1);
					iSeessionID = atoi(strsessionid);
				}

				cJSON* pSerialNo = cJSON_GetObjectItem(pRoot,"serialno");
				char strSerialNo[128] ={0};
				if(pSerialNo)
					memcpy(strSerialNo,pSerialNo->valuestring,strlen(pSerialNo->valuestring)+1);

				//cJSON *pRet_root;
				ptmpRequest.pRet_root = cJSON_CreateObject();
				ptmpRequest.Requst_Json_str(2,"cmd","check_session");

				ptmpRequest.Requst_Json_str(2,"sessionid",strsessionid);

				ptmpRequest.Requst_Json_str(1,"task_id",strsessionid);
				char txt[32] ={0};
				sprintf(txt,"%d",iRetcode);
				ptmpRequest.Requst_Json_str(2,"ret_code",txt);

				ptmpRequest.Requst_Json_str(2,"serialno",strSerialNo);
				
			}
			else if(strcmp(pcmd->valuestring, "req_ads_stream") == 0)
			{
				printf("--req stream_session exception\n");
				//通过
				cJSON* psessionid = cJSON_GetObjectItem(pRoot, "sessionid");
				char strsessionid[128] ={0};
				int iSeessionID = 0;
				if(psessionid)
				{
					memcpy(strsessionid,psessionid->valuestring,strlen(psessionid->valuestring)+1);
					iSeessionID = atoi(strsessionid);
				}

				cJSON* pSerialNo = cJSON_GetObjectItem(pRoot,"serialno");
				char strSerialNo[128] ={0};
				if(pSerialNo)
					memcpy(strSerialNo,pSerialNo->valuestring,strlen(pSerialNo->valuestring)+1);

				//cJSON *pRet_root;
				ptmpRequest.pRet_root = cJSON_CreateObject();
				ptmpRequest.Requst_Json_str(2,"cmd","req_ads_stream");

				ptmpRequest.Requst_Json_str(2,"sessionid",strsessionid);

				char strnoip[128]={0};
				strcpy(strnoip,"1.1.1.1");
				char strport[32]={0};
				strcpy(strport,"1");
				ptmpRequest.Requst_Json_str(1,"switch_ip",strnoip);
				ptmpRequest.Requst_Json_str(1,"switch_port",strport);
				char txt[32] ={0};
				sprintf(txt,"%d",iRetcode);
				ptmpRequest.Requst_Json_str(2,"ret_code",txt);

				ptmpRequest.Requst_Json_str(2,"serialno",strSerialNo);
				
			}


		}
	}
	
	char cJsonBuff[1024 * 2];
	char * m_tmp;
	m_tmp = cJSON_Print(ptmpRequest.pRet_root);
	memset(cJsonBuff, 0, sizeof(cJsonBuff));
	sprintf(cJsonBuff, "%sXXEE", m_tmp);
	free(m_tmp);
	printf("-----%s \n",cJsonBuff);
	fflush(stdout);
	cJSON_Delete(ptmpRequest.pRet_root);
	//copy to output 

	strcpy(strOutUrl,cJsonBuff);
	
	return 0;
}
Example #21
0
 void solve(vector<vector<char>>& board) {
     if (board.size()<3 ||board[0].size()<3) return;
     border(board, 'O', 'Y');
     replace(board, 'O', 'X');
     border(board, 'Y', 'O');
 }
Example #22
0
/* #####  E241: (col 14) 'class String' has not been declared  */
void String::doReplace(size_t pos, size_t n, const char* cb, size_t len)
{
/* #####  E029: (col 22) symbol 'length' has not been declared  */
    size_t thisLen = length();
    size_t newlen;

    //
    // preconditions
    //

    assert(pos <= thisLen);   // if pos == thisLen it's like an append
    assert(cb != 0);
    assert(n <= (thisLen - pos));

    //
    // operations
    //

    newlen = len + (thisLen - n);
    checkOverflow(len, newlen, "String::doReplace");

    if(newlen == 0) {
/* #####  E029: (col 15) symbol 'refDec' has not been declared  */
        refDec();
/* #####  E029: (col 9) symbol 'srep' has not been declared  */
        srep = 0;
        return;
    }

    // prevent against hacks like: s.insert(1, s.cStr() + 2)
    //

/* #####  E029: (col 34) symbol 'srep' has not been declared  */
    if(srep && NORM_ADR(srep->str) <= NORM_ADR(cb)
            && NORM_ADR(cb) <= NORM_ADR(srep->str + thisLen)) {
/* #####  E029: (col 25) symbol 'String' has not been declared  */
        replace(pos, n, String(cb, len));
        return;
    }

/* #####  E029: (col 8) symbol 'needClone' has not been declared  */
    if(needClone(newlen)) {
/* #####  E241: (col 17) 'class String' has not been declared  */
/* #####  E006: (col 31) syntax error; probable cause: missing ';'  */
        String::StringRep *ps = StringRep::getNew(pos, newlen, srep->str);

        if(thisLen > 0)     // copy tail
/* #####  E029: (col 20) symbol 'ps' has not been declared  */
            memcpy(ps->str + pos + len, srep->str + pos + n,
                                      thisLen - (pos + n));
/* #####  E029: (col 9) symbol 'refDec' has not been declared  */
        refDec();
        srep = ps;
    }
    else {
        char* ptarget = srep->str;      // srep != 0

        if(n != len)  // move in place
            MemMove(ptarget + pos + len, ptarget + pos + n,
                thisLen - (pos + n));
    }
    if(len > 0)
        memcpy(srep->str + pos, cb, len);
    srep->setLen(newlen);
    assert(newlen == length());
}
Example #23
0
/* Build a Java Home structure for a path */
static home_data *build(char *path)
{
    home_data *data = NULL;
    char *cfgf = NULL;
    char buf[1024];
    int x = 0;
    int k = 0;

    if (path == NULL)
        return (NULL);

    log_debug("Attempting to locate Java Home in %s", path);
    if (checkdir(path) == false) {
        log_debug("Path %s is not a directory", path);
        return (NULL);
    }

    while (location_jvm_cfg[x] != NULL) {
        if ((k =
             replace(buf, 1024, location_jvm_cfg[x], "$JAVA_HOME",
                     path)) != 0) {
            log_error("Error replacing values for jvm.cfg (%d)", k);
            return (NULL);
        }
        log_debug("Attempting to locate VM configuration file %s", buf);
        if (checkfile(buf) == true) {
            log_debug("Found VM configuration file at %s", buf);
            cfgf = strdup(buf);
            break;
        }
        x++;
    }

    data = (home_data *)malloc(sizeof(home_data));
    data->path = strdup(path);
    data->cfgf = cfgf;
    data->jvms = NULL;
    data->jnum = 0;

    /* We don't have a jvm.cfg configuration file, so all we have to do is
       trying to locate the "default" Java Virtual Machine library */
    if (cfgf == NULL) {
        log_debug("VM configuration file not found");
        x = 0;
        while (location_jvm_default[x] != NULL) {
            char *libr = location_jvm_default[x];

            if ((k = replace(buf, 1024, libr, "$JAVA_HOME", path)) != 0) {
                log_error("Error replacing values for JVM library (%d)", k);
                return (NULL);
            }
            log_debug("Attempting to locate VM library %s", buf);
            if (checkfile(buf) == true) {
                data->jvms = (home_jvm **)malloc(2 * sizeof(home_jvm *));
                data->jvms[0] = (home_jvm *)malloc(sizeof(home_jvm));
                data->jvms[0]->name = NULL;
                data->jvms[0]->libr = strdup(buf);
                data->jvms[1] = NULL;
                data->jnum = 1;
                return (data);
            }
            x++;
        }

        return (data);
    }

    /* If we got here, we most definitely found a jvm.cfg file */
    if (parse(data) == false) {
        log_error("Cannot parse VM configuration file %s", data->cfgf);
    }

    return (data);
}
Example #24
0
void *SM_Control::ts_recv_useract_thread(void *arg)
{
	SM_Control *this0 = (SM_Control*)arg;
	printf("1111111111111111this is ts_recv_useract_thread\n");
	fflush(stdout);
	int BUFFER_SIZE = 4096;
	struct sockaddr_in s_addr;
	int sock;
	socklen_t addr_len;
	
	if ((sock = socket(AF_INET,SOCK_DGRAM,0))  == -1){
		perror("socket");
		return NULL;
	} else
		printf("create socket.\n\r");
		fflush(stdout);
	memset(&s_addr, 0, sizeof(struct sockaddr_in));
	s_addr.sin_family = AF_INET;

	s_addr.sin_port = htons(this0->m_iUseractport);

	s_addr.sin_addr.s_addr = INADDR_ANY;

	int optval = 1;
	if ((setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&optval,sizeof(int))) == -1)
	{
		close(sock);
		printf("11111111111111111111111 setsockopt error\n");
		fflush(stdout);
		return NULL;
	}

	if ((bind(sock, (struct sockaddr*)&s_addr, sizeof(s_addr))) == -1 ) {
		perror("bind");
		return NULL;
	}else
		printf("bind address to socket.\n\r");
	    fflush(stdout);
		char Rcv_buf[4096];
		cJSON *pcmd = NULL;
		socklen_t address_size;	
		char cJsonBuff[1024*2];
		int iRecvLen = 0;
		struct sockaddr_in rin;
		int accept_fd = sock;		
		while(1)
		{
			memset(Rcv_buf,0,sizeof(Rcv_buf));
			int length = 0;
			int i_rc = 0, i_count = 0;
			address_size = sizeof(rin);
			do
			{
				printf("222222222222222222before recv\n");
				fflush(stdout);
				i_rc = recvfrom(accept_fd, Rcv_buf + i_count, 2000 - i_count,NULL,(struct sockaddr *)&rin,&address_size);
				if (i_rc <= 0)break;//异常关闭
				i_count += i_rc;
			} while (strstr(Rcv_buf, "XXEE") == NULL);	
			iRecvLen = i_count;
			if (iRecvLen <= 0) break;
			
			printf("recv:%s \n",Rcv_buf);
			fflush(stdout);
							//解析报文数据
			replace(Rcv_buf, "XXEE", "");	
			cJSON* pRoot = cJSON_Parse(Rcv_buf);
			if(pRoot)
			{
				pcmd = cJSON_GetObjectItem(pRoot, "cmd");
				if(strcmp(pcmd->valuestring,"user_action")==0)
				{
					char iUsername[32] = {0};
					char iUsertype[32] = {0};
					char iUserdate[64] = {0};
					char iUsermsg[32] = {0};
					int iStreamID;
					int result;
					cJSON* pUsertype = cJSON_GetObjectItem(pRoot, "action_type");
					cJSON* pStreamID = cJSON_GetObjectItem(pRoot, "stream_id");
					cJSON* pSUserID = cJSON_GetObjectItem(pRoot, "username");
					cJSON* pUserdate = cJSON_GetObjectItem(pRoot, "action_date");
					cJSON* pUserresult = cJSON_GetObjectItem(pRoot, "action_result");
					cJSON* pUsermsg = cJSON_GetObjectItem(pRoot, "msg");
					if(pSUserID)
					strcpy(iUsername,pSUserID->valuestring);
					if(pUsertype)
					strcpy(iUsertype,pUsertype->valuestring);
					if(pUserdate)
					strcpy(iUserdate,pUserdate->valuestring);
					if(pUsermsg)
					strcpy(iUsermsg,pUsermsg->valuestring);
					if(pUserresult) result = pUserresult->valueint;
					if(pStreamID)
					{
						if(pStreamID->valuestring == NULL)
						{
							iStreamID = 0;
						}
						else
						iStreamID = atoi(pStreamID->valuestring);
					}
					else
					{
						iStreamID = 0;
					}
					printf("77777777777777begin to insert action to DB\n");
					fflush(stdout);
					this0->m_cSM_Manager->Userbehav(iStreamID,iUsertype,iUsername,iUsermsg,result,iUserdate);
				}
			}	
		}
}
Example #25
0
	QVariant ItemsListModel::data (const QModelIndex& index, int role) const
	{
		if (!index.isValid () || index.row () >= rowCount ())
			return QVariant ();

		if (role == Qt::DisplayRole)
		{
			switch (index.column ())
			{
				case 0:
					{
						auto title = CurrentItems_ [index.row ()].Title_;
						auto pos = 0;
						while ((pos = title.indexOf ('<', pos)) != -1)
						{
							auto end = title.indexOf ('>', pos);
							if (end > 0)
								title.remove (pos, end - pos + 1);
							else
								break;
						}

						title.replace ("&laquo;", QString::fromUtf8 ("«"));
						title.replace ("&raquo;", QString::fromUtf8 ("»"));
						title.replace ("&quot;", "\"");
						title.replace ("&ndash;", "-");
						title.replace ("&mdash;", QString::fromUtf8 ("—"));

						return title;
					}
				case 1:
					return CurrentItems_ [index.row ()].PubDate_;
				default:
					return QVariant ();
			}
		}
		//Color mark an items as read/unread
		else if (role == Qt::ForegroundRole)
		{
			bool palette = XmlSettingsManager::Instance ()->
					property ("UsePaletteColors").toBool ();
			if (CurrentItems_ [index.row ()].Unread_)
			{
				if (XmlSettingsManager::Instance ()->
						property ("UnreadCustomColor").toBool ())
					return XmlSettingsManager::Instance ()->
							property ("UnreadItemsColor").value<QColor> ();
				else
					return palette ?
						QApplication::palette ().link ().color () :
						QVariant ();
			}
			else
				return palette ?
					QApplication::palette ().linkVisited ().color () :
					QVariant ();
		}
		else if (role == Qt::FontRole &&
				CurrentItems_ [index.row ()].Unread_)
			return XmlSettingsManager::Instance ()->
				property ("UnreadItemsFont");
		else if (role == Qt::ToolTipRole &&
				XmlSettingsManager::Instance ()->property ("ShowItemsTooltips").toBool ())
		{
			IDType_t id = CurrentItems_ [index.row ()].ItemID_;
			const auto& maybeItem = GetSB ()->GetItem (id);
			if (!maybeItem)
				return {};

			const auto& item = *maybeItem;
			QString result = QString ("<qt><strong>%1</strong><br />").arg (item.Title_);
			if (item.Author_.size ())
			{
				result += tr ("<b>Author</b>: %1").arg (item.Author_);
				result += "<br />";
			}
			if (item.Categories_.size ())
			{
				result += tr ("<b>Categories</b>: %1").arg (item.Categories_.join ("; "));
				result += "<br />";
			}
			if (item.NumComments_ > 0)
			{
				result += tr ("%n comment(s)", "", item.NumComments_);
				result += "<br />";
			}
			if (item.Enclosures_.size () > 0)
			{
				result += tr ("%n enclosure(s)", "", item.Enclosures_.size ());
				result += "<br />";
			}
			if (item.MRSSEntries_.size () > 0)
			{
				result += tr ("%n MediaRSS entry(s)", "", item.MRSSEntries_.size ());
				result += "<br />";
			}
			if (item.CommentsLink_.size ())
			{
				result += tr ("RSS with comments is available");
				result += "<br />";
			}
			result += "<br />";

			const int maxDescriptionSize = 1000;
			auto descr = item.Description_;
			RemoveTag ("img", descr);
			RemovePair ("font", descr);
			RemovePair ("span", descr);
			RemovePair ("p", descr);
			RemovePair ("div", descr);
			for (auto i : { 1, 2, 3, 4, 5, 6 })
				RemovePair ("h" + QString::number (i), descr);
			result += descr.left (maxDescriptionSize);
			if (descr.size () > maxDescriptionSize)
				result += "...";

			return result;
		}
		else if (role == Qt::BackgroundRole)
		{
			const QPalette& p = QApplication::palette ();
			QLinearGradient grad (0, 0, 0, 10);
			grad.setColorAt (0, p.color (QPalette::AlternateBase));
			grad.setColorAt (1, p.color (QPalette::Base));
			return QBrush (grad);
		}
		else if (role == Qt::DecorationRole)
		{
			if (index.column ())
				return QVariant ();

			const auto& item = CurrentItems_ [index.row ()];
			if (GetSB ()->GetItemTags (item.ItemID_).contains ("_important"))
				return StarredIcon_;

			return item.Unread_ ? UnreadIcon_ : ReadIcon_;
		}
		else if (role == ItemRole::IsRead)
			return !CurrentItems_ [index.row ()].Unread_;
		else if (role == ItemRole::ItemId)
			return CurrentItems_ [index.row ()].ItemID_;
		else if (role == ItemRole::ItemShortDescr)
			return QVariant::fromValue (CurrentItems_ [index.row ()]);
		else
			return QVariant ();
	}
Example #26
0
//处理广告流接口
void *SM_Control::Parse_recv_Adver_thread(void * arg)
{
	SM_Control *this0 = (SM_Control*)arg;

	int len;
	char Rcv_buf[4096];

	cJSON *pcmd = NULL;

	char cJsonBuff[1024 * 2];
	int iRecvLen = 0;
	int accept_fd = this0->m_AdvacceptSocket;
	while(1)
	{
			memset(Rcv_buf,0,sizeof(Rcv_buf));
			int length = 0;
			int i_rc = 0, i_count = 0;
			do
			{
				i_rc = recv(accept_fd, Rcv_buf + i_count, 2000 - i_count, 0);
				if (i_rc <= 0)break;//异常关闭
				i_count += i_rc;
			} while (strstr(Rcv_buf, "XXEE") == NULL);
			iRecvLen = i_count;
			if (iRecvLen <= 0) break;
	
			printf("recv:%s \n",Rcv_buf);
			fflush(stdout);
	
					//解析报文数据
			replace(Rcv_buf, "XXEE", "");
			cJSON* pRoot = cJSON_Parse(Rcv_buf);	

			if (pRoot)
			{
				pcmd = cJSON_GetObjectItem(pRoot, "cmd");
				if (pcmd)
				{
					//判断请求类型
					if (strcmp(pcmd->valuestring, "add_ads_stream") == 0)
					{
						printf("--add_ads_stream return \n");
						fflush(stdout);
						//通过
						cJSON* pSeesid = cJSON_GetObjectItem(pRoot, "sessionid");
						//char strSeesionID[128] ={0};
					//	memcpy(strSeesionID,pSeesid->valuestring,strlen(pSeesid->valuestring));
						int iSeessionID = 0;
						if(pSeesid) iSeessionID = atoi(pSeesid->valuestring);
						cJSON* pTaskID = cJSON_GetObjectItem(pRoot, "task_id");
						int iTaskID = -1;
						if(pTaskID) iTaskID = pTaskID->valueint;
						cJSON* pRetCOde = cJSON_GetObjectItem(pRoot,"ret_code");
						int iRetCode = -1;
						if(pRetCOde) iRetCode = atoi(pRetCOde->valuestring);
						cJSON* pSerialNo = cJSON_GetObjectItem(pRoot,"serialno");
						char strSerialNo[128] ={0};
						if(pSerialNo)
							memcpy(strSerialNo,pSerialNo->valuestring,strlen(pSerialNo->valuestring)+1);
										
						
						//更新流信息状态
						//找到流对应数据,
						MapStreamStatus::iterator itFind = this0->m_cSM_Manager->m_mapStreamStatus.find(iSeessionID);
						if(itFind != this0->m_cSM_Manager->m_mapStreamStatus.end())
						{
							//修改内存数据
							StreamStatus *ptmp = itFind->second;
							if(iRetCode >= 0)
							{
								strcpy(ptmp->strStreamType,Status_Adver);
								if(strcmp(ptmp->strBind_userID,"") == 0)
								{
									//未绑定									
								}
								else
								{
									
								}

							}
							else
							{
								// retcode 失败需要处理
							}					
							
							//修改对应数据库
						}
						
					}
					else if(strcmp(pcmd->valuestring, "del_ads_stream") == 0)
					{
						printf("--del_ads_stream return \n");
						fflush(stdout);
						//通过
						cJSON* pSeesid = cJSON_GetObjectItem(pRoot, "sessionid");
						//char strSeesionID[128] ={0};
					//	memcpy(strSeesionID,pSeesid->valuestring,strlen(pSeesid->valuestring));
						int iSeessionID = 0;
						if(pSeesid) iSeessionID = atoi(pSeesid->valuestring);
						cJSON* pRetCOde = cJSON_GetObjectItem(pRoot,"ret_code");
						int iRetCode = -1;
						if(pRetCOde) iRetCode = atoi(pRetCOde->valuestring);
						cJSON* pSerialNo = cJSON_GetObjectItem(pRoot,"serialno");
						char strSerialNo[128] ={0};
						if(pSerialNo)
						memcpy(strSerialNo,pSerialNo->valuestring,strlen(pSerialNo->valuestring)+1);
						
						//更新流信息状态
						//找到流对应数据,
						MapStreamStatus::iterator itFind = this0->m_cSM_Manager->m_mapStreamStatus.find(iSeessionID);
						if(itFind != this0->m_cSM_Manager->m_mapStreamStatus.end())
						{
							//修改内存数据
							StreamStatus *ptmp = itFind->second;
							if(iRetCode >= 0)
							{
								strcpy(ptmp->strStreamType,Status_Adver);
								if(strcmp(ptmp->strBind_userID,"") == 0)
								{
									//未绑定									
								}
								else
								{
									
								}
							}
							else
							{
								// retcode 失败需要处理
							}
							//修改对应数据库
						}						
					}
					else if(strcmp(pcmd->valuestring, "check_session") == 0)
					{
						printf("--check_session return \n");
						fflush(stdout);
						//通过
						cJSON* pSeesid = cJSON_GetObjectItem(pRoot, "sessionid");
						//char strSeesionID[128] ={0};
					//	memcpy(strSeesionID,pSeesid->valuestring,strlen(pSeesid->valuestring));

						int iSeessionID = 0;
						if(pSeesid) iSeessionID = atoi(pSeesid->valuestring);
						cJSON* pRetCOde = cJSON_GetObjectItem(pRoot,"ret_code");
						int iRetCode = -1;
						if(pRetCOde) iRetCode = atoi(pRetCOde->valuestring);
						cJSON* pSerialNo = cJSON_GetObjectItem(pRoot,"serialno");
						char strSerialNo[128] ={0};
						if(pSerialNo)
							memcpy(strSerialNo,pSerialNo->valuestring,strlen(pSerialNo->valuestring)+1);
	
					}
					
				}
			}
			
	}

	if(this0->m_AdvacceptSocket != -1)
		close(this0->m_AdvacceptSocket);
	this0->m_AdvacceptSocket = -1;
}
bool ElementValueModification::replace(MeshLib::Mesh &mesh,
    int const old_value, int const new_value, bool replace_if_exists)
{
    return replace(mesh, "MaterialIDs", old_value, new_value, replace_if_exists);
}
Example #28
0
//处理VOD接口
void *SM_Control::Parse_recv_Vod_thread(void * arg)
{
	SM_Control *this0 = (SM_Control*)arg;

	int len;
	char Rcv_buf[4096];

	cJSON *pcmd = NULL;

	char cJsonBuff[1024 * 2];
	int iRecvLen = 0;
	int accept_fd = this0->m_VodacceptSocket;
	while(1)
	{
			memset(Rcv_buf,0,sizeof(Rcv_buf));
			int length = 0;
			int i_rc = 0, i_count = 0;
			do
			{
				i_rc = recv(accept_fd, Rcv_buf + i_count, 2000 - i_count, 0);
				if (i_rc <= 0)break;//异常关闭
				i_count += i_rc;
			} while (strstr(Rcv_buf, "XXEE") == NULL);
			iRecvLen = i_count;
			if (iRecvLen <= 0) break;
	
			printf("recv:%s \n",Rcv_buf);
			fflush(stdout);
	
					//解析报文数据
			replace(Rcv_buf, "XXEE", "");
			cJSON* pRoot = cJSON_Parse(Rcv_buf);	

			if (pRoot)
			{
					
				pcmd = cJSON_GetObjectItem(pRoot, "cmd");
				if (pcmd)
				{
					//判断请求类型
	/*				if (strcmp(pcmd->valuestring, "add_ads_stream") == 0)
					{
						printf("--add_ads_stream return \n");
					}
					else if(strcmp(pcmd->valuestring, "del_ads_stream") == 0)
					{
						printf("--del_ads_stream return \n");
					}
					else if(strcmp(pcmd->valuestring, "check_session") == 0)
					{
						printf("--check_session return \n");
					}
	*/				
				}
			}
			
	}

	if(this0->m_VodacceptSocket != -1)
		close(this0->m_VodacceptSocket);
	this0->m_VodacceptSocket = -1;
}
Example #29
0
// ********************************************************************** Handle events
void QHexEdit::keyPressEvent(QKeyEvent *event)
{
    // Cursor movements
    if (event->matches(QKeySequence::MoveToNextChar))
    {
        setCursorPosition(_cursorPosition + 1);
        resetSelection(_cursorPosition);
    }
    if (event->matches(QKeySequence::MoveToPreviousChar))
    {
        setCursorPosition(_cursorPosition - 1);
        resetSelection(_cursorPosition);
    }
    if (event->matches(QKeySequence::MoveToEndOfLine))
    {
        setCursorPosition(_cursorPosition | (2 * BYTES_PER_LINE -1));
        resetSelection(_cursorPosition);
    }
    if (event->matches(QKeySequence::MoveToStartOfLine))
    {
        setCursorPosition(_cursorPosition - (_cursorPosition % (2 * BYTES_PER_LINE)));
        resetSelection(_cursorPosition);
    }
    if (event->matches(QKeySequence::MoveToPreviousLine))
    {
        setCursorPosition(_cursorPosition - (2 * BYTES_PER_LINE));
        resetSelection(_cursorPosition);
    }
    if (event->matches(QKeySequence::MoveToNextLine))
    {
        setCursorPosition(_cursorPosition + (2 * BYTES_PER_LINE));
        resetSelection(_cursorPosition);
    }
    if (event->matches(QKeySequence::MoveToNextPage))
    {
        setCursorPosition(_cursorPosition + (((_rowsShown - 1) * 2 * BYTES_PER_LINE)));
        resetSelection(_cursorPosition);
    }
    if (event->matches(QKeySequence::MoveToPreviousPage))
    {
        setCursorPosition(_cursorPosition - (((_rowsShown - 1) * 2 * BYTES_PER_LINE)));
        resetSelection(_cursorPosition);
    }
    if (event->matches(QKeySequence::MoveToEndOfDocument))
    {
        setCursorPosition(_chunks->size() * 2);
        resetSelection(_cursorPosition);
    }
    if (event->matches(QKeySequence::MoveToStartOfDocument))
    {
        setCursorPosition(0);
        resetSelection(_cursorPosition);
    }

    // Select commands
    if (event->matches(QKeySequence::SelectAll))
    {
        resetSelection(0);
        setSelection(2*_chunks->size() + 1);
    }
    if (event->matches(QKeySequence::SelectNextChar))
    {
        qint64 pos = _cursorPosition + 1;
        setCursorPosition(pos);
        setSelection(pos);
    }
    if (event->matches(QKeySequence::SelectPreviousChar))
    {
        qint64 pos = _cursorPosition - 1;
        setSelection(pos);
        setCursorPosition(pos);
    }
    if (event->matches(QKeySequence::SelectEndOfLine))
    {
        qint64 pos = _cursorPosition - (_cursorPosition % (2 * BYTES_PER_LINE)) + (2 * BYTES_PER_LINE);
        setCursorPosition(pos);
        setSelection(pos);
    }
    if (event->matches(QKeySequence::SelectStartOfLine))
    {
        qint64 pos = _cursorPosition - (_cursorPosition % (2 * BYTES_PER_LINE));
        setCursorPosition(pos);
        setSelection(pos);
    }
    if (event->matches(QKeySequence::SelectPreviousLine))
    {
        qint64 pos = _cursorPosition - (2 * BYTES_PER_LINE);
        setCursorPosition(pos);
        setSelection(pos);
    }
    if (event->matches(QKeySequence::SelectNextLine))
    {
        qint64 pos = _cursorPosition + (2 * BYTES_PER_LINE);
        setCursorPosition(pos);
        setSelection(pos);
    }
    if (event->matches(QKeySequence::SelectNextPage))
    {
        qint64 pos = _cursorPosition + (((viewport()->height() / _pxCharHeight) - 1) * 2 * BYTES_PER_LINE);
        setCursorPosition(pos);
        setSelection(pos);
    }
    if (event->matches(QKeySequence::SelectPreviousPage))
    {
        qint64 pos = _cursorPosition - (((viewport()->height() / _pxCharHeight) - 1) * 2 * BYTES_PER_LINE);
        setCursorPosition(pos);
        setSelection(pos);
    }
    if (event->matches(QKeySequence::SelectEndOfDocument))
    {
        qint64 pos = _chunks->size() * 2;
        setCursorPosition(pos);
        setSelection(pos);
    }
    if (event->matches(QKeySequence::SelectStartOfDocument))
    {
        qint64 pos = 0;
        setCursorPosition(pos);
        setSelection(pos);
    }

    // Edit Commands
    if (!_readOnly)
    {
        if ((QApplication::keyboardModifiers() == Qt::NoModifier) ||
                (QApplication::keyboardModifiers() == Qt::KeypadModifier))
        {
            /* Hex input */
            int key = int(event->text()[0].toLatin1());
            if ((key>='0' && key<='9') || (key>='a' && key <= 'f'))
            {
                if (getSelectionBegin() != getSelectionEnd())
                {
                    if (_overwriteMode)
                    {
                        qint64 len = getSelectionEnd() - getSelectionBegin();
                        replace(getSelectionBegin(), (int)len, QByteArray((int)len, char(0)));
                    }
                    else
                    {
                        remove(getSelectionBegin(), getSelectionEnd() - getSelectionBegin());
                        _bPosCurrent = getSelectionBegin();
                    }
                    setCursorPosition(2*_bPosCurrent);
                    resetSelection(2*_bPosCurrent);
                }

                // If insert mode, then insert a byte
                if (_overwriteMode == false)
                    if ((_cursorPosition % 2) == 0)
                        insert(_bPosCurrent, char(0));

                // Change content
                if (_chunks->size() > 0)
                {
                    QByteArray hexValue = _chunks->data(_bPosCurrent, 1).toHex();
                    if ((_cursorPosition % 2) == 0)
                        hexValue[0] = key;
                    else
                        hexValue[1] = key;

                    replace(_bPosCurrent, QByteArray().fromHex(hexValue)[0]);

                    setCursorPosition(_cursorPosition + 1);
                    resetSelection(_cursorPosition);
                }
            }
        }

        /* Cut */
        if (event->matches(QKeySequence::Cut))
        {
            QByteArray ba = _chunks->data(getSelectionBegin(), getSelectionEnd() - getSelectionBegin()).toHex();
            for (qint64 idx = 32; idx < ba.size(); idx +=33)
                ba.insert(idx, "\n");
            QClipboard *clipboard = QApplication::clipboard();
            clipboard->setText(ba);
            if (_overwriteMode)
            {
                qint64 len = getSelectionEnd() - getSelectionBegin();
                replace(getSelectionBegin(), (int)len, QByteArray((int)len, char(0)));
            }
            else
            {
                remove(getSelectionBegin(), getSelectionEnd() - getSelectionBegin());
            }
            setCursorPosition(2*getSelectionBegin());
            resetSelection(2*getSelectionBegin());
        }

        /* Paste */
        if (event->matches(QKeySequence::Paste))
        {
            QClipboard *clipboard = QApplication::clipboard();
            QByteArray ba = QByteArray().fromHex(clipboard->text().toLatin1());
            if (_overwriteMode)
                replace(_bPosCurrent, ba.size(), ba);
            else
                insert(_bPosCurrent, ba);
            setCursorPosition(_cursorPosition + 2 * ba.size());
            resetSelection(getSelectionBegin());
        }

        /* Delete char */
        if (event->matches(QKeySequence::Delete))
        {
            if (getSelectionBegin() != getSelectionEnd())
            {
                _bPosCurrent = getSelectionBegin();
                if (_overwriteMode)
                {
                    QByteArray ba = QByteArray(getSelectionEnd() - getSelectionBegin(), char(0));
                    replace(_bPosCurrent, ba.size(), ba);
                }
                else
                {
                    remove(_bPosCurrent, getSelectionEnd() - getSelectionBegin());
                }
            }
            else
            {
                if (_overwriteMode)
                    replace(_bPosCurrent, char(0));
                else
                    remove(_bPosCurrent, 1);
            }
            setCursorPosition(2 * _bPosCurrent);
            resetSelection(2 * _bPosCurrent);
        }

        /* Backspace */
        if ((event->key() == Qt::Key_Backspace) && (event->modifiers() == Qt::NoModifier))
        {
            if (getSelectionBegin() != getSelectionEnd())
            {
                _bPosCurrent = getSelectionBegin();
                setCursorPosition(2 * _bPosCurrent);
                if (_overwriteMode)
                {
                    QByteArray ba = QByteArray(getSelectionEnd() - getSelectionBegin(), char(0));
                    replace(_bPosCurrent, ba.size(), ba);
                }
                else
                {
                    remove(_bPosCurrent, getSelectionEnd() - getSelectionBegin());
                }
                resetSelection(2 * _bPosCurrent);
            }
            else
            {
                _bPosCurrent -= 1;
                if (_overwriteMode)
                    replace(_bPosCurrent, char(0));
                else
                    remove(_bPosCurrent, 1);
                _bPosCurrent -= 1;
                setCursorPosition(2 * _bPosCurrent);
                resetSelection(2 * _bPosCurrent);
            }
        }

        /* undo */
        if (event->matches(QKeySequence::Undo))
        {
            undo();
        }

        /* redo */
        if (event->matches(QKeySequence::Redo))
        {
            redo();
        }

    }

    /* Copy */
    if (event->matches(QKeySequence::Copy))
    {
        QByteArray ba = _chunks->data(getSelectionBegin(), getSelectionEnd() - getSelectionBegin()).toHex();
        for (qint64 idx = 32; idx < ba.size(); idx +=33)
            ba.insert(idx, "\n");
        QClipboard *clipboard = QApplication::clipboard();
        clipboard->setText(ba);
    }

    // Switch between insert/overwrite mode
    if ((event->key() == Qt::Key_Insert) && (event->modifiers() == Qt::NoModifier))
    {
        setOverwriteMode(!overwriteMode());
        setCursorPosition(_cursorPosition);
    }

    refresh();
}
Example #30
0
int main(int argc, char *argv[]) {
    optparse::OptionParser parser = optparse::OptionParser()
          .description("C++ reimplementation of the classic cowsay.");
    parser.set_defaults("eyes", "oo");
    parser.set_defaults("tongue", "");
    parser.set_defaults("thoughts", std::strstr(argv[0], "think") ? "o" : "\\");
    parser.add_option("-b", "--borg").    action("store_const").dest("eyes").set_const("==");
    parser.add_option("-d", "--dead").    action("store_const").dest("eyes").set_const("xx");
    parser.add_option("-g", "--greedy").  action("store_const").dest("eyes").set_const("$$");
    parser.add_option("-p", "--paranoid").action("store_const").dest("eyes").set_const("@@");
    parser.add_option("-s", "--stoned").  action("store_const").dest("eyes").set_const("**");
    parser.add_option("-t", "--tired").   action("store_const").dest("eyes").set_const("--");
    parser.add_option("-w", "--wired").   action("store_const").dest("eyes").set_const("OO");
    parser.add_option("-y", "--young").   action("store_const").dest("eyes").set_const("..");
    parser.add_option("-e", "--eyes").    action("store").dest("eyes");
    parser.add_option("-T", "--tongue").  action("store").dest("tongue");
    parser.add_option("-l", "--list").action("store_true").dest("list")
                     .help("displays cow file location");
    parser.add_option("-f", "--file").action("store").dest("file")
                     .set_default("default.cow").help("cow file, searches in cowpath. "
                      ".cow is automatically appended");
    parser.add_option("-W", "--wrap").action("store").type("int").dest("wrap")
                     .set_default(70).help("wraps the cow text, default 70");
    parser.add_option("--thoughts").action("store").dest("thoughts")
                     .help("the method of communication cow uses. "
                      "Default to `o` if invoked as cowthink, otherwise `\\`");
    parser.add_option("-c", "--command-line").action("store_true").dest("cmd")
                     .help("treat command line as text, not files");
    std::string cowpath_opts[5] = {"-a", "--add", "--add-cow", "--add-path", "--add-cow-path"};
    parser.add_option(std::vector<std::string>(&cowpath_opts[0], &cowpath_opts[5]))
                     .action("append").dest("cowpath");

    optparse::Values& options = parser.parse_args(argc, argv);
    std::vector<std::string> args = parser.args();
    std::vector<std::string> cowpath(options.all("cowpath").cbegin(), options.all("cowpath").cend());
    std::reverse(cowpath.begin(), cowpath.end());
    add_default_cowpath(cowpath);
    
    std::string tongue, eyes;
    eyes = (options["eyes"] + "  ").substr(0, 2);
    if (options["tongue"].empty()) {
        if (eyes == "xx" || eyes == "**") // one of the predefined dead faces
            tongue = "U ";
        else
            tongue = "  ";
    } else
        tongue = (options["tongue"] + "  ").substr(0, 2);
    
    if (options.is_set("list")) {
        try {
            std::string path = findcow(cowpath, options["file"]);
#ifdef WIN32
            replace(path, "/", "\\");
#endif
            std::cout << path << std::endl;
            return 0;
        } catch (std::string e) {
            std::cerr << argv[0] << ": " << e << std::endl;
            return 1;
        }
    }
    
    std::string cow;
    std::vector<std::string> lines;
    std::string input;
    try {
        cow = loadcow(findcow(cowpath, options["file"]), options["thoughts"], eyes, tongue);
        if (options.get("cmd")) {
            std::stringstream stream;
            for (auto line = args.cbegin(); line < args.cend(); ++line)
                stream << *line << '\n';
            input = stream.str();
        } else
            open_streams(input, args);
        int width = wrap(input, lines, options.get("wrap"));
        write_ballon(stdout, lines, width, options["thoughts"] == "o");
        fputs(cow.c_str(), stdout);
    } catch (std::string e) {
        std::cerr << argv[0] << ": " << e << std::endl;
    }
}