Пример #1
0
Type *checkArrayVar(Absyn * node, Table * symtab)
{
	Type *tmp;
	if (checkNode(node->u.arrayVar.index, symtab) != builtinType_int)
		error("illegal indexing with a non-integer in line %d",
		      node->line);
	tmp = checkNode(node->u.arrayVar.var, symtab);
	// check that tmp is an array
	if (tmp->kind != TYPE_KIND_ARRAY)
		error("illegal indexing a non-array in line %d", node->line);

	node->type_t = tmp->u.arrayType.baseType;
	return node->type_t;
}
Пример #2
0
// readFile
int readFile(FILE* in) {
  int aorq = fastaOrQ(in);
  rewind(in);
  int count = 0;
  while (fgets(hline, MAX_SIZE, in) != NULL) {
    if (hline[0] == '#')
      continue;

    count++;
    if (fgets(line, MAX_SIZE, in) == NULL)
      exit(error("", ERRSEQ));
    int len = strlen(line) - 1;
    if (line[len] == '\n')
      line[len] = '\0';

    // add read to trie
    Node* n = checkNode(root, 0, len);
    if (n->child[0] == NULL && n->head == NULL) {
      n->head = (char*) memalloc(HEADER);
      int i;
      for (i = 1; hline[i] != '\0' && hline[i] != '\n' && i < HEADER; i++)
        n->head[i - 1] = hline[i];
      n->head[i - 1] = '\0';
    }

    // skip next 2 lines if fastq
    if (aorq)
      for (int i = 0; i < 2; i++)
        if (fgets(line, MAX_SIZE, in) == NULL)
          exit(error("", ERRSEQ));
  }
  printf("  reads: %d\n", count);
  return count;
}
Пример #3
0
void animate(int i)
{
	GLfloat x, y;
	pointNode * last;
	if(!bPaused && !bComplete)
	{
		GLfloat displacement = calcDisplacement(minX, maxX, minY, maxY);
		
		last = curr;
		randomDisplacement(displacement, x, y);
		curr = AddNode(curr, curr->x + x, curr->y + y);
		count = pointCount(head);

		glutPostRedisplay();
		//We only want to keep going if 
		if(checkNode(curr, minX, maxX, minY, maxY))
		{
			//keep a roughly constat fps
			glutTimerFunc(17, animate, 0);
		}else
		{
			findExitPoint(last, curr);
			bComplete = true;
		}
	}
}
Пример #4
0
result_t XmlDocument::appendChild(XmlNode_base *newChild, obj_ptr<XmlNode_base> &retVal)
{
    result_t hr = checkNode(newChild);
    if (hr < 0)
        return hr;

    return m_childs->appendChild(newChild, retVal);
}
Пример #5
0
/**
 * Adds provided data to the storage.
 * @param checkPrefix If @a TRUE than all nodes with absolute URIs will be
 *                    checked to have /obix prefix.
 * @return @a 0 on success; error code otherwise.
 */
static int xmldb_putDOMHelper(IXML_Element* data, BOOL checkPrefix)
{
    IXML_Node* node = ixmlElement_getNode(data);
    IXML_Node* newNode = NULL;

    // shortcut for cleaning all resources if error occurs.
    void onError()
    {
        if (newNode != NULL)
        {
            ixmlNode_free(newNode);
        }
    }

    const char* href = checkNode(node, checkPrefix);
    if (href == NULL)
    {
        // error is already logged.
        onError();
        return -1;
    }

    // append node to the storage
    int error = ixmlDocument_importNode(_storage, node, TRUE, &newNode);
    if (error != IXML_SUCCESS)
    {
        log_warning("Unable to write to the storage (error %d).", error);
        onError();
        return error;
    }

    // look for available node with the same href
    IXML_Node* nodeInStorage = getNodeByHref(_storage, href, NULL);
    if (nodeInStorage != NULL)
    {
        log_warning("Unable to write to the storage: The object with the same "
                    "URI (%s) already exists.", href);
        onError();
        return -2;
        // overwrite existing node
        //ixmlNode_replaceChild(ixmlNode_getParentNode(nodeInStorage),
        //                      newNode,
        //                      nodeInStorage,
        //                      &nodeInStorage);
        //ixmlNode_free(nodeInStorage);
    }

    // append as a new node
    error = ixmlNode_appendChild(ixmlDocument_getNode(_storage), newNode);
    if (error != IXML_SUCCESS)
    {
        log_warning("Unable to write to the storage (error %d).", error);
        onError();
        return error;
    }

    return 0;
}
Пример #6
0
    void populate() const
    {
			NodeListT dummy;
      nodes_.swap(dummy);

      checkNode(rootNode_);

      changes_ = ownerDoc_->changes();
    } // populate
Пример #7
0
result_t XmlDocument::insertAfter(XmlNode_base *newChild, XmlNode_base *refChild,
                                  obj_ptr<XmlNode_base> &retVal)
{
    result_t hr = checkNode(newChild);
    if (hr < 0)
        return hr;

    return m_childs->insertAfter(newChild, refChild, retVal);
}
Пример #8
0
Type *checkCallStm(Absyn * node, Table * symtab)
{
	Entry *entry;
	ParamTypes *p;
	Absyn *args, *arg;
	int n = 0;

	entry = lookup(symtab, node->u.callStm.name);
	if (entry == NULL)
		error("undefined procedure '%s' in line %d",
		      symToString(node->u.callStm.name), node->line);
	if (entry->kind != ENTRY_KIND_PROC)
		error("call of non-procedure '%s' in line %d",
		      symToString(node->u.callStm.name), node->line);

	p = entry->u.procEntry.paramTypes;
	args = node->u.callStm.args;
	if (args->type != ABSYN_EXPLIST)
		error
		    ("error in abstract syntax. should not happen; internal compiler error.");
	arg = args;

	while (p && !p->isEmpty) {
		n++;
		if (arg->u.expList.isEmpty)	// (n < soll_n)
			error
			    ("procedure '%s' called with too few arguments in line %d",
			     symToString(node->u.callStm.name), node->line);
		if (p->type != checkNode(arg->u.expList.head, symtab)) {
			error
			    ("procedure '%s' argument %d type mismatch in line %d",
			     symToString(node->u.callStm.name), n, node->line);
		}

		arg = arg->u.expList.tail;
		p = p->next;
	}
	if (!(arg->u.expList.isEmpty))	// (n > soll_n)
		error
		    ("procedure '%s' called with too many arguments in line %d",
		     symToString(node->u.callStm.name), node->line);

	// check ref params for being a variable explicitly.
	arg = args;
	p = entry->u.procEntry.paramTypes;
	while (p && !p->isEmpty) {
		if (p->isRef && arg->u.expList.head->type != ABSYN_VAREXP) {
			error
			    ("procedure '%s' argument %d must be a variable in line %d",
			     symToString(node->u.callStm.name), n, node->line);
		}
		arg = arg->u.expList.tail;
		p = p->next;
	}

	return NULL;
}
Пример #9
0
    virtual void visit(AstSel* nodep, AstNUser*) {
	nodep->fromp()->iterateAndNext(*this);
	{   // Only the 'from' is part of the assignment LHS
	    bool prevAssign = m_assignLhs;
	    m_assignLhs = false;
	    nodep->lsbp()->iterateAndNext(*this);
	    nodep->widthp()->iterateAndNext(*this);
	    m_assignLhs = prevAssign;
	}
	checkNode(nodep); }
Пример #10
0
// 0 -> not valid; 1 -> valid
int Xmlvalidator::checkNode(Item* node) {
	Tag* tagNode = dynamic_cast<Tag *>(node);

	if (tagNode) {
		string name = tagNode->getName();
		string transfo = "";

		vector<Item *> children = tagNode->getChildren();
		for(vector<Item *>::iterator itCh = children.begin(); itCh != children.end(); itCh++) {
			Element* elNode = dynamic_cast<Element *>(*itCh);
			if (elNode)
			{
				transfo += "<"+elNode->getName()+">";
			}
			else
			{
				Content* ctNode = dynamic_cast<Content *>(*itCh);
				if (ctNode)
				{
					transfo += ctNode->textContent();
				}

			}

			// Recursive call for each children
			if (checkNode((*itCh)) == 0)
			{
				// if it is not valid
				return 0;
			}
		}

		std::map<string,string>::iterator itRegex = mapRegex.find(name);

		if (itRegex == mapRegex.end())
		{
			std::map<string,string>::iterator itType = mapType.find(name);
		 	itRegex = mapRegex.find(itType->second);
			
			if (itRegex == mapRegex.end())
			{
		 		cerr << "XSD not exhaustive for this xml. Missing regex for the type " << itType->second << endl;
		 	}
		}

		string regex = itRegex->second;

		// cout << "DO THE CHECK " << regex << " on " << transfo << " for the node " << name << endl;
		std::regex rx(regex);
		return regex_match(transfo.begin(), transfo.end(), rx);
	}

	return 1;
}
Пример #11
0
    virtual void visit(AstNodeCond* nodep, AstNUser*) {
	nodep->iterateChildren(*this);
	if (nodep->expr1p()->isWide()
	    && !nodep->condp()->castConst()
	    && !nodep->condp()->castVarRef()) {
	    // We're going to need the expression several times in the expanded code,
	    // so might as well make it a common expression
	    createDeepTemp(nodep->condp(), false);
	}
	checkNode(nodep);
    }
Пример #12
0
/* Procedure typeCheck performs type checking
 * by a postorder syntax tree traversal
 */
void typeCheck(TreeNode * t)
{
	if(t != NULL)
	{
		for(int i=0;i < MAXCHILDREN ; i++)
			if(t->child[i] != NULL)
				typeCheck(t -> child[i]);
		checkNode(t);
		typeCheck(t -> sibing);
	}
}
Пример #13
0
Type *checkVarDec(Absyn * node, Table * symtab)
{
	Type *type;
	Entry *entry;
	type = checkNode(node->u.typeDec.ty, symtab);
	entry = newVarEntry(type, FALSE, ENTRY_SOURCE_LOCVAR);
	if (enter(symtab, node->u.typeDec.name, entry) == NULL) {
		error("redeclaration of '%s' in line %d",
		      symToString(node->u.typeDec.name), node->line);
	}
	return NULL;
}
Пример #14
0
int Xmlvalidator::validityCheck(Document *xml) {
	//Insert basic XSD types
	std::map<string,string>::iterator itRegex = mapRegex.find("xsd:string");

	if (itRegex == mapRegex.end()) {
	    mapRegex.insert(pair<string, string>("xsd:string", "^[^*+]+$"));
	    mapRegex.insert(pair<string, string>("xsd:date", "[1-9][0-9]{3}-[01][0-9]-[0-3][0-9]"));
	}

	int valid = checkNode((Item *) xml->getRoot());

	return valid;
}
Пример #15
0
Type *checkOpExp(Absyn * node, Table * symtab)
{
	Type *leftType, *rightType;

	leftType = checkNode(node->u.opExp.left, symtab);
	rightType = checkNode(node->u.opExp.right, symtab);

	if (leftType != rightType)
		error("expression combines different types in line %d",
		      node->line);
	switch (node->u.opExp.op) {
	case ABSYN_OP_EQU:	// case fall-through, following cases same type
	case ABSYN_OP_NEQ:
	case ABSYN_OP_LST:
	case ABSYN_OP_LSE:
	case ABSYN_OP_GRT:
	case ABSYN_OP_GRE:
		if (leftType != builtinType_int)
			error("comparison requires integer operands in line %d",
			      node->line);
		node->type_t = builtinType_bool;
		break;
	case ABSYN_OP_ADD:	// case fall-through, following cases same type
	case ABSYN_OP_SUB:
	case ABSYN_OP_MUL:
	case ABSYN_OP_DIV:
		if (leftType != builtinType_int)
			error("comparison requires integer operands in line %d",
			      node->line);
		node->type_t = builtinType_int;
		break;
	default:
		error("unknown node type %d in checkNode", node->type);
	}
	return node->type_t;
}
Пример #16
0
Type *checkProcDec(Absyn * node, Table * symtab)
{
	Table *localSymtab;
	Entry *entry;

	// loopup procs local symtable here
	entry = lookup(symtab, node->u.procDec.name);
	localSymtab = entry->u.procEntry.localTable;

	// compute local declarations
	checkNode(node->u.procDec.decls, localSymtab);

	// compute procedure body
	checkNode(node->u.procDec.body, localSymtab);

	// optional debug output
	if (local_debug) {
		printf("symbol table at end of procedure '%s':\n",
		       symToString(node->u.procDec.name));
		showTable(localSymtab);
	}

	return NULL;
}
Пример #17
0
void fixLabel(Node* n){
	if(!checkNode(n))return;
	if(n->name==0)return;// HOW? checkNames=false :(
	if(n->name[0]=='"')n->name=n->name+1;

	if(n->name[strlen(n->name)-1]=='"'&&n->name[strlen(n->name)-2]!='"')
		n->name[strlen(n->name)-1]=0;
	if(n->name[strlen(n->name)-1]=='\\')
		n->name[strlen(n->name)-1]=0;
	replaceChar(n->name,'"',' ');
	replaceChar(n->name,'\'',' ');
	replaceChar(n->name,'\\',' ');
	// todo: "'","%27" etc
	//#include <curl/curl.h>
	//char *curl_easy_escape( CURL * curl , char * url , int length );
}
Пример #18
0
    void visitShift (AstNodeBiop* nodep) {
	// Shifts of > 32/64 bits in C++ will wrap-around and generate non-0s
	if (!nodep->user2SetOnce()) {
	    UINFO(4,"  ShiftFix  "<<nodep<<endl);
	    AstConst* shiftp = nodep->rhsp()->castConst();
	    if (shiftp && shiftp->num().mostSetBitP1() > 32) {
		shiftp->v3error("Unsupported: Shifting of by over 32-bit number isn't supported."
				<<" (This isn't a shift of 32 bits, but a shift of 2^32, or 4 billion!)\n");
	    }
	    if (nodep->widthMin()<=64  // Else we'll use large operators which work right
		// C operator's width must be < maximum shift which is based on Verilog width
		&& nodep->width() < (1LL<<nodep->rhsp()->widthMin())) {
		AstNRelinker replaceHandle;
		nodep->unlinkFrBack(&replaceHandle);
		AstNode* constzerop;
		int m1value = nodep->widthMin()-1; // Constant of width-1; not changing dtype width
		if (nodep->signedFlavor()) {
		    // Then over shifting gives the sign bit, not all zeros
		    // Note *NOT* clean output -- just like normal shift!
		    // Create equivalent of VL_SIGNONES_(node_width)
		    constzerop = new AstNegate (nodep->fileline(),
						new AstShiftR(nodep->fileline(),
							      nodep->lhsp()->cloneTree(false),
							      new AstConst(nodep->fileline(),
									   m1value),
							      nodep->width()));
		} else {
		    V3Number zeronum  (nodep->fileline(), nodep->width(), 0);
		    constzerop = new AstConst(nodep->fileline(), zeronum);
		}
		constzerop->dtypeFrom (nodep);  // unsigned

		V3Number widthnum (nodep->fileline(), nodep->rhsp()->widthMin(), m1value);
		AstNode* constwidthp = new AstConst(nodep->fileline(), widthnum);
		constwidthp->dtypeFrom (nodep->rhsp());  // unsigned
		AstCond* newp =
		    new AstCond (nodep->fileline(),
				 new AstGte (nodep->fileline(),
					     constwidthp,
					     nodep->rhsp()->cloneTree(false)),
				 nodep,
				 constzerop);
		replaceHandle.relink(newp);
	    }
	}
	nodep->iterateChildren(*this); checkNode(nodep);
    }
Пример #19
0
    void checkNode(DOM::Node_impl<stringT, string_adaptorT>* node) const
    {
      if(useNamespace_)
      {
        if((node->hasNamespaceURI() && namespaceURI_ == node->getNamespaceURI()) || allNamespaces_)
        {
          if((tagName_ == node->getLocalName()) || (allNames_ && node->getNodeType() == DOM::Node<stringT, string_adaptorT>::ELEMENT_NODE))
            nodes_.push_back(node);
        }
      } 
      else
        if((tagName_ == node->getNodeName()) || (allNames_ && node->getNodeType() == DOM::Node<stringT, string_adaptorT>::ELEMENT_NODE))
          nodes_.push_back(node);

      for(DOM::Node_impl<stringT, string_adaptorT>* child = node->getFirstChild(); child != 0; child = child->getNextSibling())
        if(child->getNodeType() == DOM::Node<stringT, string_adaptorT>::ELEMENT_NODE)
          checkNode(child);
    } // checkNode
Пример #20
0
void StarView::slotConfigChanged()
{
    HostInfoManager::HostMap hostMap = hostInfoManager()->hostMap();
    HostInfoManager::HostMap::ConstIterator it;
    for(it = hostMap.constBegin(); it != hostMap.constEnd(); ++it) {
        if (filterArch(*it))
            checkNode(it.key());
        else
            forceRemoveNode(it.key());
    }

    arrangeHostItems();

    //write settings
    QSettings settings;
    settings.setValue("StarView/NodesPerRing", m_configDialog->nodesPerRing());
    settings.setValue("StarView/ArchFilter", m_configDialog->archFilter());
    settings.setValue("StarView/SupressDomainName", m_configDialog->suppressDomainName());
}
Пример #21
0
result_t XmlDocument::replaceChild(XmlNode_base *newChild, XmlNode_base *oldChild,
                                   obj_ptr<XmlNode_base> &retVal)
{
    if (newChild == oldChild)
    {
        retVal = oldChild;
        return 0;
    }

    if (oldChild == m_element)
        m_element.Release();
    else if (oldChild == m_doctype)
        m_doctype.Release();

    result_t hr = checkNode(newChild);
    if (hr < 0)
        return hr;

    return m_childs->replaceChild(newChild, oldChild, retVal);
}
Пример #22
0
// moreSeq -- check remaining sequence of node
Node* moreSeq(Node* n, Node* par, int ch, int pos, int len) {
  int i;
  for (i = 1; i < n->end - n->st; i++) {

    // read is short
    if (pos + i == len) {
      return splitNode(n, par, ch, i);
      //return n;
    }

    // mismatch at position i
    if (line[pos + i] != n->seq[n->st + i]) {
      Node* m = splitNode(n, par, ch, i);
      return makeNode(m, 1, pos + i, len - pos - i);
    }
  }

  // recurse on child node
  return checkNode(n, pos + i, len);
}
Пример #23
0
int AI::minValue(vector<vector<int>> tempBoard, vector<Piece> teamCopy, vector<Piece> enemyTeamCopy, int depth, Directions direction){

    bool killMove = false;

    if(!checkNode(tempBoard, teamCopy, enemyTeamCopy, direction, true)){
        return OUT_OF_BOUND;
    }

    int x = enemyTeamCopy[enemyCurrentIndex].x;
    int y = enemyTeamCopy[enemyCurrentIndex].y;

    changeWithDirection(x, y, direction, true);
    if(sameTeam(tempBoard[x][y],TEAM_NUMBER)){
        if(!killCheckArea(tempBoard, x, y, direction, true)){
            return OUT_OF_BOUND;
        }
        else{
            changeWithDirection(x, y, direction, true);
            killMove = true;
        }
    }

    //This should move on the tempBoard
    movePiece(tempBoard, enemyTeamCopy, enemyCurrentIndex, x, y);
    updateKings(tempBoard, enemyTeamCopy, true);
    if (killMove) {
        updateTeam(tempBoard, teamCopy, false);
        if (teamCopy.size()<=0) {
            //smallest number
            return -1 * WIN_VALUE;
        }
    }

    if (depth <= 0) {
        return valueCalculator(teamCopy, enemyTeamCopy);
    }
    else{
        return maxMove(tempBoard, teamCopy, enemyTeamCopy, depth-1);
    }

}
Пример #24
0
void sendKeyToKeySensor(const char key, int upDown) {
	int count;
	ppComponent_KeyDevice p = (ppComponent_KeyDevice)gglobal()->Component_KeyDevice.prv;
	if (p->keySink == NULL) return;

	for (count=0; count < p->keySinkCurMax; count++) {
		#ifdef VERBOSE
		printf ("sendKeyToKeySensor, sending key %d to %d of %d\n",key,count,p->keySinkCurMax);
		#endif

        /* make sure this has not been deleted  - we should really re-create list, but
         so few keySensor X3D nodes are in use, who cares? */
        if (checkNode(p->keySink[count],__FILE__,__LINE__)) {
#ifdef _MSC_VER
		if (p->keySink[count]->_nodeType == NODE_KeySensor && (upDown != KeyChar)) sendToKS(p->keySink[count], (int)key&0xFFFF, upDown);
#else
		if (p->keySink[count]->_nodeType == NODE_KeySensor ) sendToKS(p->keySink[count], (int)key&0xFFFF, upDown);
#endif
		if (p->keySink[count]->_nodeType == NODE_StringSensor ) sendToSS(p->keySink[count], (int)key&0xFFFF, upDown);
	}
    }
}
Пример #25
0
int main(int argc, const char *argv[])
{
    if (argc<2) 
        usage(0);

    int arg = 1;
    while (arg < argc)
    {
        if (stricmp(argv[arg], "-crc") == 0)
        {
            checkCRC = true;
        }
        else if (stricmp(argv[arg], "-errorLimit") == 0)
        {
            ++arg;
            if (arg>=argc)
                usage(1);           
            errorLimit = strtoul(argv[arg], NULL, 10);
            if (!errorLimit)
                errorLimit = (unsigned) -1;
        }
        else if (stricmp(argv[arg], "-node") == 0)
        {
            ++arg;
            if (arg>=argc)
                usage(1);           
            nodeAddress = strtoul(argv[arg], NULL, 16);
            checkCRC = true;
        }
        else if (stricmp(argv[arg], "-noleaf") == 0)
        {
            skipLeafLevel = true;
        }
        else if (stricmp(argv[arg], "-quick") == 0)
        {
            quick = true;
        }
        else if (*argv[arg]=='-')
            usage(1);
        ++arg;
    }
    arg = 1;
    while (arg < argc)
    {
        if (*argv[arg]!='-')
        {
            curFileName = argv[arg];
            printf("Processing key file %s\n", curFileName);
            int f = _open(argv[arg], _O_RDONLY|_O_BINARY);
            if (f==-1)
            {
                noteError(0, "Could not open file\n");
            }
            else
            {
                KeyHdr h;
                if (_read(f, &h, sizeof(h)) != sizeof(h))
                {
                    noteError(0, "Could not read key header\n");
                }
                else
                {
                    SwapBigEndian(h);
                    if (nodeAddress)
                    {
                        checkNode(f, h, nodeAddress);
                    }
                    else if (quick)
                    {
                        int levels = countLevels(f, h, h.root);
                        printf("%d levels found\n", levels);
                    }
                    else
                    {
                        unsigned level = 0;
                        checkLevel(f, h, level, h.root);
                    }
                }
                _close(f);
            }
        }
        arg++;
    }
    return errors;
}
Пример #26
0
 inline const AzTreeNode *node(int nx) const {
     checkNode(nx, "point");
     return &nodes[nx];
 }
Пример #27
0
 NLPSolver& NLPImplicitSolver::getNLPSolver(){
   casadi_assert(checkNode());
   return (*this)->nlp_solver_;
 }
Пример #28
0
FX ImplicitFunction::getF() const {
  casadi_assert(checkNode());
  return (*this)->f_;
}
Пример #29
0
/* CENTRAL METHOD to parse and render html request*/
int handle(cchar* q0,int conn){
	int len=(int)strlen(q0);
	if(len>1000){
		p("checkSanity len>1000");
		return 0;// SAFETY!
	}
    char* q=editable(q0);
	checkSanity(q,len);
    while(q[0]=='/')q++;
	enum result_format format = html;//txt; html DANGER WITH ROBOTS
	enum result_verbosity verbosity = normal;

	if (eq(q, "favicon.ico"))return 0;
    if(contains(q,"robots.txt")){
        Writeline(conn,"User-agent: *\n");
        Writeline("Disallow: /\n");
        return 0;
    }
	
	char* jsonp=strstr(q,"jsonp");// ?jsonp=fun
	if(jsonp){
		jsonp[-1]=0;
		jsonp+=6;
		format = json;
		}
	else jsonp=(char*)"parseResults";

	if (endsWith(q, ".json")) {
        format = json;
        q[len-5]=0;
    }
    
	if (endsWith(q, ".xml")) {
        format = xml;
        q[len-4]=0;
    }
    
	if (endsWith(q, ".csv")||endsWith(q, ".tsv")) {
        format = csv;
        q[len-4]=0;
    }
    
	if (endsWith(q, ".txt")) {
        format = txt;
        q[len-4]=0;
    }
    
	if (endsWith(q, ".html")) {
		format = html;
		q[len-5]=0;
	}
	if (startsWith(q, ".js")) {
		q[len-3]=0;
		Writeline(conn, jsonp);
		Writeline(conn, "(");
		format = js;
	}
	// todo : dedup!!
	if (startsWith(q, "all/")) {
		cut_to(q," +");
		cut_to(q," -");
		q = q + 4;
		showExcludes=false;
		verbosity = alle;
	}
	if (startsWith(q, "long/")){
		verbosity =  longer;
		q = q + 5;
	}
	if (startsWith(q, "full/")) {
		verbosity =  verbose;
		q = q + 5;
	}
	if (startsWith(q, "verbose/")) {
		verbosity = verbose;
		q = q + 8;
	}
	if (startsWith(q, "short/")) {
		verbosity = shorter;
		q = q + 6;
	}

	if (startsWith(q, "html/")) {
        format = html;
        if(!contains(q,".")&&!contains(q,":"))
			verbosity=verbose;
        q = q + 5;
    }
	if (startsWith(q, "plain/")) {
		format = txt;
		q = q + 6;
	}
	if (startsWith(q, "text/")) {
		format = txt;
		q = q + 5;
	}
	if (startsWith(q, "txt/")) {
		format = txt;
		q = q + 4;
	}
	if (startsWith(q, "xml/")) {
		format = xml;
		q = q + 4;
	}
	if (startsWith(q, "csv/")||startsWith(q, "tsv/")) {
		format = csv;
		q = q + 4;
	}
	if (startsWith(q, "json/")) {
		format = json;
		q = q + 5;
	}
	if (startsWith(q, "js/")) {
		q = q + 3;
		Writeline(conn, jsonp);
		Writeline(conn, "(");
		format = js;
	}
	if (startsWith(q, "long/")) {
		verbosity = longer;
		q = q + 5;
	}
	if (startsWith(q, "verbose/")) {
		verbosity = verbose;
		q = q + 8;
	}
	if (startsWith(q, "short/")) {
		verbosity = shorter;
		q = q + 6;
	}
	if (startsWith(q, "excludes/")||startsWith(q, "includes/")||startsWith(q, "excluded/")||startsWith(q, "included/")||startsWith(q, "showview/")) {
        showExcludes=true;
        verbosity=longer;
		q = q + 9;
	}
    else showExcludes=false;
    excluded.clear();
    included.clear();
    
    if(contains(q,"statement count")){Writeline(conn,itoa((int)context->statementCount).data());return 0;}
    if(contains(q,"node count")){Writeline(conn,itoa(context->nodeCount).data());return 0;}
    
    
	if (startsWith(q, "all/")) {
        cut_to(q," +");
        cut_to(q," -");
		q = q + 4;
		showExcludes=false;
		verbosity = alle;
	}
//	bool get_topic=false;
	bool get_topic=true;
	bool sort=false;
	if (startsWith(q, "ee/")||startsWith(q, "ee ")) {
		q[2]=' ';
		get_topic=true;
	}
	if (startsWith(q, "entities/")) {
		q[8]=' ';
		get_topic=true;
//		verbosity=longer;
	}
	if(hasWord(q)) loadView(q);
    
    if(contains(q,"exclude")||contains(q,"include")){
        verbosity=normal;
        showExcludes=true;
    }
	p(q);
    // !!!!!!!!!!!!!!!!!!!!!!!!!!!
	//
    NodeVector all = parse(q); // <<<<<<<< HANDLE QUERY WITH NETBASE!
    //
    // !!!!!!!!!!!!!!!!!!!!!!!!!!!

	autoIds=false;
    int size=(int)all.size();
    if(showExcludes){
        for (int i = 0; i < size; i++) {
        // todo : own routine!!!
        Node* node = (Node*) all[i];
        if(!contains(all,getAbstract(node->name)))
            all.push_back(getAbstract(node->name));
        N parent= getType(node);
        if(parent){
            if(!contains(all,parent))all.push_back(parent);
            N abs= getAbstract(parent->name);
            if(parent&&!contains(all,abs))all.push_back(abs);
        }
        }
        show(excluded);
    }
    
    const char* html_block="<!DOCTYPE html><html><head><META HTTP-EQUIV='CONTENT-TYPE' CONTENT='text/html; charset=UTF-8'/></head>"\
							"<body><div id='netbase_results'></div>\n<script>var results=";
    //    if((int)all.size()==0)Writeline("0");
	//	Writeline(conn,q);
	char buff[10000];

	bool use_json= format == json || format == js || format == html;
	if (format == xml && (startsWith(q,"select")||contains(q," where "))){Writeline(conn,query2(q));return 0;}
	if (format == xml)Writeline(conn, "<results>\n");
	if (format == html)Writeline(conn,html_block);
	if (use_json)Writeline(conn, "{\"results\":[\n");
	const char* statement_format_xml = "   <statement id='%d' subject=\"%s\" predicate=\"%s\" object=\"%s\" sid='%d' pid='%d' oid='%d'/>\n";
	const char* statement_format_text = "   $%d %s %s %s %d->%d->%d\n";
	const char* statement_format_json = "      { \"id\":%d, \"subject\":\"%s\", \"predicate\":\"%s\", \"object\":\"%s\", \"sid\":%d, \"pid\":%d, \"oid\":%d}";
	const char* statement_format_csv = "%d\t%s\t%s\t%s\t%d\t%d\t%d\n";
	const char* statement_format = 0;
	if (format == xml)statement_format = statement_format_xml;
	if (format == html)statement_format = statement_format_json;
	if (format == json)statement_format = statement_format_json;
	if (format == txt)statement_format = statement_format_text;
	if (format == csv)statement_format = statement_format_csv;
    
	const char* entity_format = 0;
	const char* entity_format_txt = "%s #%d (statements:%d) %s\n";
	const char* entity_format_xml = "<entity name=\"%s\" id='%d' statementCount='%d' description='%s'>\n";
	const char* entity_format_json = "   {\"name\":\"%s\", \"id\":%d, \"statementCount\":%d, \"description\":\"%s\"";
   	const char* entity_format_csv = "%s\t%d\t%d\t%s\n";
    if(all.size()==1)entity_format_csv = "";//statements!
	if (format == xml)entity_format = entity_format_xml;
	if (format == txt)entity_format = entity_format_txt;
	if (format == csv)entity_format = entity_format_csv;
	if (use_json)	  entity_format = entity_format_json;
	Node* last=0;
    warnings=0;
    char* entity=0;
    if(startsWith(q,"all")){
        entity=(char*)cut_to(q," ");
        entity=keep_to(entity,"limit");
    }
   	sortNodes(all);
	int count=(int)all.size();
	int good=0;
	for (int i = 0; i < count && i<resultLimit; i++) {
		Node* node = (Node*) all[i];
		if(!checkNode(node))continue;
		if(node->id==0)continue;
		if(last==node)continue;
		if(eq(node->name,"◊"))continue;
		last=node;
        if(verbosity ==normal && entity&& eq(entity,node->name))continue;
		char* text=getText(node);
//		if(use_json && get_topic){
//			if(empty(text))continue;//! no description = no entity? BAD for amazon etc
//			if(isAbstract(node))continue;
//			N t=getTopic(node);
//		}
		good++;
		if (use_json)if(good>1)Writeline(conn, "},\n");
		sprintf(buff, entity_format, node->name, node->id,node->statementCount,text);
		Writeline(conn, buff);
//        if(verbosity != alle && !get_topic)
//			loadView(node);
		bool got_topic=false;
		if(use_json && get_topic){
			N c=getClass(node);
			N t=getTopic(node);
			N ty=getType(node);
//			if(!c)c=t;
			if(!t)t=ty;
			if(t==node)t=ty;
			if(t!=Entity && checkNode(t)){
				got_topic=true;
				Writeline(conn, ",\n\t \"topicid\":"+itoa(t->id));
				Writeline(conn, ", \"topic\":\""+string(t->name)+"\"");
			}
			if(c && c!=t){
				Writeline(conn, ",\n\t \"classid\":"+itoa(c->id));
				Writeline(conn, ", \"class\":\""+string(c->name)+"\"");
			}
			if(ty&& c!=ty && ty!=t){
				Writeline(conn, ",\n\t \"typeid\":"+itoa(ty->id));
				Writeline(conn, ", \"type\":\""+string(ty->name)+"\"");
			}
		}
		if(use_json)// && (verbosity==verbose||verbosity==shorter))// lol // just name
			Writeline(conn, ", \"kind\":"+itoa(node->kind));
		if((use_json)&&!showExcludes&&node->statementCount>1 && getImage(node)!="")
			Writeline(", \"image\":\""+replace_all(replace_all(getImage(node,150,/*thumb*/true),"'","%27"),"\"","%22")+"\"");
//		if((use_json)&&getText(node)[0]!=0)
//			Writeline(", \"description\":\""+string(getText(node))+"\"");
		Statement* s = 0;
		if (format==csv|| verbosity == verbose || verbosity == longer|| verbosity == alle || showExcludes || ( all.size() == 1 && !(verbosity == shorter))) {
			int count=0;
            //            Writeline(",image:\""+getImage(node->name)+"\"");
			if (use_json)Writeline(conn, ",\n\t \"statements\":[\n");

//			sortStatements(
			deque<Statement*> statements;// sort
			while ((s = nextStatement(node, s))&&count++<lookupLimit){// resultLimit
				if (!checkStatement(s))break;
//				if(!got_topic &&( s->predicate==_Type|| s->predicate==_SuperClass)){
//					addStatementToNode(node, s->id(), true);// next time
//				}
				if(get_topic &&!got_topic && verbosity != verbose && (s->predicate>100 || s->predicate<-100))
					continue;// only important stuff here!
				// filter statements

				if(s->object==0)continue;
//				if(eq(s->Predicate()->name,"Offizielle Website") && !contains(s->Object()->name,"www"))
//					continue;
				if (s->subject==node->id and s->predicate!=4)//_instance
					statements.push_front(s);
				else statements.push_back(s);
			}
//			if(get_topic && verbosity!=shorter){
//				NV topics=getTopics(node);
//				N s=topics[0];
//				for (int j = 0; j < topics.size() && j<=resultLimit; j++) {
//					N s=topics[j];
//					Temporary statement (node,topic,s)
//					statements.push_front(s);
//				}
//			}




			int good=0;
			for (int j = 0; j < statements.size() && j<=resultLimit; j++) {
				s=statements.at(j);
//			while ((s = nextStatement(node, s))&&count++<resultLimit) {
                if(format==csv&&all.size()>1)break;// entities vs statements
                p(s);
				if(verbosity!=alle&&checkHideStatement(s)){warnings++;continue;}
				fixLabels(s);
				if(!(verbosity==verbose||verbosity==alle) && (s->Predicate()==Instance||s->Predicate()==Type))continue;
				if(use_json && good>0)Writeline(conn, ",\n");
				char* objectName=s->Object()->name;

				if(s->Predicate()==Instance){
					N type=findProperty(s->Object(),Type->name,0,50);
					if(  checkNode(type))
						objectName=(char*)(concat(concat(objectName, ": "),type->name));
				}
				sprintf(buff, statement_format, s->id(), s->Subject()->name, s->Predicate()->name, objectName, s->Subject()->id, s->Predicate()->id, s->Object()->id);
				Writeline(conn, buff);
				good++;
			}
			if (use_json)Writeline(conn, "]");
		}
		if (format == xml)Writeline(conn, "</entity>\n");
		//		string img=getImage(node->name);
		//		if(img!="")Writeline(conn,"<img src=\""+img+"\"/>");
	}

	if (use_json || format == html || format == js)Writeline(conn,good>0?"}\n]}":"]}");
	if (format == xml)Writeline(conn, "</results>\n");
	if(format == js)Writeline(conn, ")");// jsonp
		const char* html_end=";\n</script>\n<script src='http://pannous.net/netbase.js'></script></body></html>\n";
	if(format == html)Writeline(conn, html_end);
	//		sprintf(buff,	"<script src='/js/%s'></script>",q0);
	//		Writeline(conn, buff);
	//	}
    pf("Warnings/excluded: %d\n",warnings);
    return 0;// 0K
}
Пример #30
0
void ImplicitFunction::setJacobian(FX &J) {
  casadi_assert(checkNode());
  (*this)->setJacobian(J);
}