예제 #1
0
/*
Use string "(value, lt, rt)" to restore a tree. For example,
(5,(3,(1,null,null),(4,null,null)),(8,null,(9,null,null))

*/
TreeNode* parseStringToTree::parseTree(string input, int& idx) {
	if (idx == input.length())
		return NULL;
	if (input[idx] == 'n') {
		idx += 4;
		return NULL;
	}

	TreeNode* root = NULL;
	if (input[idx] == '(') {
		root = new TreeNode(0);
		idx++;
		int num = 0;
		while (idx < input.length() && '0' <= input[idx] && input[idx] <= '9') {
			num = 10 * num + (input[idx] - '0');
			idx++;
		}
		root->val = num;
		idx++; // skip the ','
		root->left = parseTree(input, idx);
		idx++; // skip the ','
		root->right = parseTree(input, idx);
		idx++; // skip the ')'
	}
	return root;
}
예제 #2
0
파일: tree.cpp 프로젝트: dominicwhite/mdh
std::unique_ptr<std::vector<std::array<int, 2>>> Tree::getBranchList(int start_id, int stop_id)
{
    // TODO: refactor to avoid start and stop nodes
    std::unique_ptr<std::vector<std::array<int, 2>>> branchList = std::make_unique<std::vector<std::array<int, 2>>>();
    if (start_id == 0 && root_node != nullptr) {
        parseTree(branchList, root_node, stop_id);
    }
    else if (start_id > 0) {
        std::shared_ptr<Node> start_node = getNode(start_id, root_node);
        if (start_node != nullptr){
            parseTree(branchList, start_node, stop_id);
        }
    }
    return branchList;
}
예제 #3
0
    void CrwImage::readMetadata()
    {
#ifdef DEBUG
        std::cerr << "Reading CRW file " << io_->path() << "\n";
#endif
        if (io_->open() != 0) {
            throw Error(9, io_->path(), strError());
        }
        IoCloser closer(*io_);
        // Ensure that this is the correct image type
        if (!isThisType(*io_, false)) {
            if (io_->error() || io_->eof()) throw Error(14);
            throw Error(33);
        }
        clearMetadata();

        // Read the image into a memory buffer
        long imageSize = io_->size();
        DataBuf image(imageSize);
        io_->read(image.pData_, imageSize);
        if (io_->error() || io_->eof()) throw Error(14);

        // Parse the image
        RawMetadata::AutoPtr parseTree(new CiffHeader);
        parseTree->read(image.pData_, image.size_, 0, invalidByteOrder);
#ifdef DEBUG
        parseTree->print(std::cerr, invalidByteOrder);
#endif
        parseTree->extract(*this, invalidByteOrder);

    } // CrwImage::readMetadata
예제 #4
0
void Trie::parseTree(Node *current, char *s,std::vector<string> &res,bool& loop)
{
    char k[100]={0};
    char a[2]={0};
    if(loop)
    {
        if(current!=NULL)
        {
            if(current->wordMarker()){
                res.push_back(s);
                if(res.size()>15)
                    loop=false;
            }
            vector<Node *> child=current->children();
            for(int i=0;i<child.size() && loop;i++){
                strcpy(k,s);
                a[0]=child[i]->content();
                a[1]='\0';
                strcat(k,a);
                if(loop)
                    parseTree(child[i],k,res,loop);
            }

        }
    }
}
예제 #5
0
LISP_DATA* parseTree(AST_NODE* astNode)
{
	LISP_DATA* currentData = (LISP_DATA*)malloc(sizeof(LISP_DATA));

	if (astNode->payload.type == LPAREN) 
	{
		currentData->type = LIST;
		currentData->data.list = 0;
		AST_NODE_LIST* childList = astNode->children;
		while (childList) 
		{
			currentData->data.list = appendExprNode(currentData->data.list, parseTree(childList->head));
			childList = childList->tail;
		}
	}
	else if (astNode->payload.type == QUOTE)
	{
		currentData->type = QUOTED;
		currentData->data.quoted = parseTree(astNode->children->head);
	}
	else if (astNode->payload.type == ATOM)
	{
		if (isNumber(astNode)) 
		{
			currentData->type = NUMERIC;
			currentData->data.numeric = atof(getTextForToken(astNode->payload));
		}
		else 
		{
			currentData->type = SYMBOL;
			currentData->data.symbol = getTextForToken(astNode->payload);
		}
	}
	else if (astNode->payload.type == BOOLEANTKN)
	{
		currentData->type = BOOLEAN;
		currentData->data.boolean = !stricmp(getTextForToken(astNode->payload), "#t");
	}
	else if (astNode->payload.type == STRINGTKN)
	{
		currentData->type = STRING;
		currentData->data.string = getTextForToken(astNode->payload);
	}

	return currentData;
}
예제 #6
0
void testTreeParser(char* inputString)
{
	int length = strlen(inputString);
	int tokenLength = 0;
	TOKEN* tokens = lex(scan(inputString), length, &tokenLength);
	AST_NODE* root = parse(tokens);
	LISP_DATA* data = parseTree(root);
	printLispData(data);
}
예제 #7
0
void TParam::loadTree(const std::string &file) {
  std::ifstream is(file.c_str());
  if (!is.is_open()) {
    std::cerr << "Error: cannot open file '" << file << "' for loading parameters\n";
    exit(-1);
  }
  std::cerr << "Loading parameters from file '" << file << "'\n";
  parseTree(is);
}
예제 #8
0
파일: tree.cpp 프로젝트: dominicwhite/mdh
void parseTree(std::unique_ptr<std::vector<std::array<int, 2>>> & branchList, const std::shared_ptr<Node>& currentNode, int stop_id)
{
    if (currentNode->get_id() != stop_id) {
        if (currentNode->desc1 != nullptr) {
//            if (currentNode->desc1->get_id() != stop_id) {
                parseTree(branchList, currentNode->desc1, stop_id);
//            }
            std::array<int, 2> branch1 = {currentNode->get_id(), currentNode->desc1->get_id()};
            branchList->push_back(branch1);
        }
        if (currentNode->desc2 != nullptr) {
//            if (currentNode->desc2->get_id() != stop_id) {
                parseTree(branchList, currentNode->desc2, stop_id);
//            }
            std::array<int, 2> branch2 = {currentNode->get_id(), currentNode->desc2->get_id()};
            branchList->push_back(branch2);
        }
    }
}
예제 #9
0
bool TParam::parseTree(std::istream &is)
{
  if (getType() != Invalid) {
    std::cerr << "Error in " << __PRETTY_FUNCTION__ << ": Leaf Param can not be parsed as tree\n";
    return false;
  }
  name = "root";
  clear();
  std::stack<int> indentation;
  indentation.push(-1);
  return parseTree(is, indentation);
}
예제 #10
0
Status WindowsEventSubscriber::Callback(const ECRef& ec, const SCRef& sc) {
  Row r;
  FILETIME cTime;
  GetSystemTimeAsFileTime(&cTime);
  r["time"] = BIGINT(filetimeToUnixtime(cTime));
  r["datetime"] =
      ec->eventRecord.get("Event.System.TimeCreated.<xmlattr>.SystemTime", "");
  r["source"] = ec->eventRecord.get("Event.System.Channel", "");
  r["provider_name"] =
      ec->eventRecord.get("Event.System.Provider.<xmlattr>.Name", "");
  r["provider_guid"] =
      ec->eventRecord.get("Event.System.Provider.<xmlattr>.Guid", "");
  r["eventid"] = INTEGER(ec->eventRecord.get("Event.System.EventID", -1));
  r["task"] = INTEGER(ec->eventRecord.get("Event.System.Task", -1));
  r["level"] = INTEGER(ec->eventRecord.get("Event.System.Level", -1));
  r["keywords"] = BIGINT(ec->eventRecord.get("Event.System.Keywords", -1));

  /*
   * From the MSDN definition of the Event Schema, each event will have
   * an XML choice element containing the event data, if any. The first
   * iteration enumerates this choice, and the second iteration enumerates
   * all data elements belonging to the choice.
   */
  pt::ptree jsonOut;
  std::map<std::string, std::string> results;
  std::string eventDataType;

  for (const auto& node : ec->eventRecord.get_child("Event", pt::ptree())) {
    /// We have already processed the System event data above
    if (node.first == "System" || node.first == "<xmlattr>") {
      continue;
    }
    eventDataType = node.first;
    parseTree(node.second, results);
  }
  for (const auto& val : results) {
    /// Reconstruct the event format as much as possible
    jsonOut.put(eventDataType + "." + val.first, val.second);
  }

  std::stringstream ss;
  boost::property_tree::write_json(ss, jsonOut, false);

  auto s = ss.str();
  if (s.at(s.size() - 1) == '\n') {
    s.erase(s.end());
  }
  r["data"] = s;

  add(r);
  return Status(0, "OK");
}
예제 #11
0
/// Helper function to recursively parse a boost ptree
void parseTree(const pt::ptree& tree, std::map<std::string, std::string>& res) {
  for (const auto& node : tree) {
    auto nodeName = node.second.get("<xmlattr>.Name", "");

    if (nodeName.empty()) {
      nodeName = node.first.empty() ? "DataElement" : node.first;
    }
    res[nodeName] = res[nodeName] == ""
                        ? node.second.data()
                        : res[nodeName] + "," + node.second.data();
    parseTree(node.second, res);
  }
}
예제 #12
0
void BookmarksProtocol::echoIndex()
{
  parseTree();

  echoHead();

  KBookmark bm = tree.first();

  if(bm.isNull()) {
    echo("<p class=\"message\">" + i18n("There are no bookmarks to display yet.") + "</p>");
  }
  else {
    for (int i = 1; i <= columns; i++)
    {
      int size = 0;
      echo("<div class=\"column\">");
      indent++;

      while(!bm.isNull() && (size + sizeOfGroup(bm.toGroup())*2/3 < (totalsize / columns) || size == 0))
      {
        echoFolder(bm.toGroup());
        size += sizeOfGroup(bm.toGroup());
        bm = tree.next(bm);
      }

      if (i == columns)
      {
        while(!bm.isNull())
        {
          echoFolder(bm.toGroup());
          bm = tree.next(bm);
        }
      }
      indent--;
      echo("</div>");
    }
  }
  indent--;
  echo("</body>");
  echo("</html>");
}
예제 #13
0
node *parseXMLTree(const char *filename, char ***classes, int *classCount, leaf **leaves) {
  node *treeRoot;
  xmlDoc *xmlFile = NULL;
  xmlNode *fileRoot = NULL;  /* TODO */

  /* XXX is hard-coding the format sensible? */
  //* TODO check xmlParserOption (third arg) */
  /* libxml whines when moving these two allocs to their own function */
  if(NULL == (xmlFile = xmlReadFile(filename, "UTF-8", 0))) {
    printf("EE|| %s:%d: could not read file '%s'\n", __FILE__, __LINE__, filename);
    return NULL;
  }

  if(NULL == (fileRoot = xmlDocGetRootElement(xmlFile))) {
    printf("EE|| %s:%d: could not read file '%s'\n", __FILE__, __LINE__, filename);
    return NULL;
  }

  /* XXX quick test */
  printf("Testing node: root name: %s\n", fileRoot->name);

  /* TODO parse classes*/
  *classes = parseClasses(fileRoot, classCount);

  /* TODO parse tree into memory*/
  treeRoot = parseTree(fileRoot, *classes, *classCount, leaves);

  //printTree(treeRoot, 0);

  // free tree
  //treeRoot = freeTree(treeRoot);

  /* Clean up libxml2 memory */
  xmlFreeDoc(xmlFile);
  xmlCleanupParser();

  return treeRoot;
}
예제 #14
0
void testInterpreter(char* inputString)
{
	int length = strlen(inputString);
	int tokenLength = 0;
	TOKEN* tokens = lex(scan(inputString), length, &tokenLength);
	AST_NODE* root = parse(tokens);

	LISP_DATA* rootList = (LISP_DATA*)malloc(sizeof(LISP_DATA));
	rootList->type = LIST;
	rootList->data.list = 0;

	AST_NODE_LIST* currentChild = root->children;

	while (currentChild)
	{
		rootList->data.list = consExprNode(parseTree(currentChild->head), rootList->data.list);
		currentChild = currentChild->tail;
	}

	LISP_DATA_LIST* evaluated = evalProgram(rootList);

	printLispDataList(evaluated);
}
예제 #15
0
bool TParam::parseTree(std::istream &is, std::stack<int> &indentation)
{
  // read newline separated parameter file
  if (is.eof())
    return true;
  std::string line;
  getline(is, line);
  std::size_t pos = line.find_first_not_of(' ');
  if (pos == std::string::npos || line[pos] == '#')
    return parseTree(is, indentation);
  assert(line[pos] != '\t');
  std::istringstream linestream(line);
  std::string pName;
  linestream >> pName;
  assert(!linestream.fail());

  // find parent depending on indentation and adapt indentation
  TParam *pParent = this;
  while ((int)pos <= indentation.top()) {
    pParent = pParent->parent;
    indentation.pop();
  }

  // read parameter
  Variant pValue;
  std::string t = pValue.tryRead(linestream);
  if (pValue.getType() == Invalid) {
    if (!t.empty() && t[0] != '#')
      std::cerr << "Warning: Unknown type '" << t << "' of parameter '" << pName << "'. Parsing as category.\n";
    indentation.push(pos); // no leaf node
  }
  TParam p(pName, pValue);
  pParent->addChild(p);
  if (p.getType() == Invalid)
    return pParent->children.find(p.name)->second->parseTree(is, indentation);
  return pParent->parseTree(is, indentation);
}
예제 #16
0
mresult_t ExpressionParser::parse(ASTElement** dst)
{
  return parseTree(dst);
}
예제 #17
0
TreeNode* parseStringToTree::parseTree(string input) {
	int idx = 0;
	return parseTree(input, idx);
}
예제 #18
0
void SessionManager::handleRead()
{
    int count = tcpSocket->bytesAvailable();
    if(count <= 0)
        return;

    char dataIn[count+1];
    memset(dataIn, 0, count+1);

    //从socket中读取数据
    tcpSocket->read(dataIn, count);
    QString data = QString(dataIn);

    /*打印接收到的服务器数据*/
    std::cerr << "<!-- IN -->\n" << dataIn << "\n\n";

    //对数据进行预处理
    /*如果数据包交换已经结束,即已经收到</stream:stream>数据包*/
    if(data.contains(QString("</stream:stream>"), Qt::CaseInsensitive))
    {
        /*****************************************************
         *我们仍然需要处理</stream:stream>之前的部分数据
         *此处我们暂时不考虑,但是要注意时候必须补上,此处一定会出错!
         **************************************************/
        tcpSocket->close();
        return;
    }

    /*如果是第一个数据包,必须在后面加一个</stream:stream>, 否则解析的过程中会报错*/
    if(data.contains(QString("<?xml version='1.0'?>"), Qt::CaseInsensitive))
    {
        data += QString("</stream:stream>");
    }

    /**
     *为了能正确的解析数据,对数据进行预处理
     *所有的非初始数据都将被<stream:stream />对包裹
     */
    else
        data = QString("<stream:stream>")+data+QString("</stream:stream>");

    /*解析xml流,生成xml树*/
    xmlTree->clear();
    QXmlInputSource inputSource;
    inputSource.setData(data);
    QXmlSimpleReader reader;
    reader.setContentHandler(xmlHandler);
    reader.setErrorHandler(xmlHandler);
    reader.parse(inputSource);

    /*解析xmlTree,生成状态信息*/
    if(!parseTree())
    {
        QMessageBox::warning(0, tr("Error"),
                             tr("Error: %1\n").arg(getError()));
        return;
    }

    /*根据解析生成的状态信息,生成回复*/
    outData = generateResponse();

    if(status >= PRESENCEUPDATED)
        return;

    if(outData.isEmpty())
    {
        QMessageBox::warning(0, tr("Error"),
                             tr("Error: %1\n").arg(getError()));
    }else{
        emit send(outData);
    }
}
예제 #19
0
Status PowershellEventSubscriber::Callback(const ECRef& ec, const SCRef& sc) {
  // For script block logging we only care about events with script blocks
  auto eid = ec->eventRecord.get("Event.System.EventID", -1);
  if (eid != kScriptBlockLoggingEid) {
    return Status();
  }

  Row results;
  for (const auto& node : ec->eventRecord.get_child("Event", pt::ptree())) {
    if (node.first == "System" || node.first == "<xmlattr>") {
      continue;
    }
    // #4357: This should make use of RapidJSON
    parseTree(node.second, results);
  }

  FILETIME etime;
  GetSystemTimeAsFileTime(&etime);
  results["time"] = BIGINT(filetimeToUnixtime(etime));
  results["datetime"] =
      ec->eventRecord.get("Event.System.TimeCreated.<xmlattr>.SystemTime", "");

  // If there's only one script block no reassembly is needed
  if (results["MessageTotal"] == "1") {
    addScriptResult(results);
    return Status();
  }

  // Add the script content to the DB for later reassembly
  auto s = setDatabaseValue(kEvents,
                            kScriptBlockPrefix + results["ScriptBlockId"] +
                                "." + results["MessageNumber"],
                            results["ScriptBlockText"]);
  if (!s.ok()) {
    LOG(WARNING) << "Failed to add new Powershell block to database for script "
                 << results["ScriptBlockId"];
  }

  // If we expect more blocks bail out early
  if (results["MessageNumber"] != results["MessageTotal"]) {
    return Status();
  }

  // Otherwise all script blocks should be accounted for so reconstruct
  std::vector<std::string> keys;
  s = scanDatabaseKeys(
      kEvents, keys, kScriptBlockPrefix + results["ScriptBlockId"]);
  if (!s.ok()) {
    LOG(WARNING) << "Failed to look up powershell script blocks for "
                 << results["ScriptBlockId"];
    return Status(1);
  }

  std::string powershell_script{""};
  for (const auto& key : keys) {
    std::string val{""};
    s = getDatabaseValue(kEvents, key, val);
    if (!s.ok()) {
      LOG(WARNING) << "Failed to retrieve script block " << key;
      continue;
    }

    powershell_script += val;

    s = deleteDatabaseValue(kEvents, key);
    if (!s.ok()) {
      LOG(WARNING) << "Failed to delete script block key from db " << key;
    }
  }

  results["ScriptBlockText"] = powershell_script;
  addScriptResult(results);

  return Status();
}