Пример #1
0
 void FllImporter::processOutputVariable(const std::string& block, Engine* engine) const {
     std::istringstream reader(block);
     std::string line;
     OutputVariable* outputVariable = new OutputVariable;
     engine->addOutputVariable(outputVariable);
     while (std::getline(reader, line)) {
         std::pair<std::string, std::string> keyValue = parseKeyValue(line, ':');
         if ("OutputVariable" == keyValue.first) {
             outputVariable->setName(keyValue.second);
         } else if ("enabled" == keyValue.first) {
             outputVariable->setEnabled(parseBoolean(keyValue.second));
         } else if ("range" == keyValue.first) {
             std::pair<scalar, scalar> range = parseRange(keyValue.second);
             outputVariable->setRange(range.first, range.second);
         } else if ("default" == keyValue.first) {
             outputVariable->setDefaultValue(Op::toScalar(keyValue.second));
         } else if ("lock-valid" == keyValue.first) {
             outputVariable->setLockValidOutput(parseBoolean(keyValue.second));
         } else if ("lock-range" == keyValue.first) {
             outputVariable->setLockOutputRange(parseBoolean(keyValue.second));
         } else if ("defuzzifier" == keyValue.first) {
             outputVariable->setDefuzzifier(parseDefuzzifier(keyValue.second));
         } else if ("accumulation" == keyValue.first) {
             outputVariable->fuzzyOutput()->setAccumulation(parseSNorm(keyValue.second));
         } else if ("term" == keyValue.first) {
             outputVariable->addTerm(parseTerm(keyValue.second, engine));
         } else {
             throw fl::Exception("[import error] key <" + keyValue.first + "> not "
                     "recognized in pair <" + keyValue.first + ":" + keyValue.second + ">", FL_AT);
         }
     }
 }
Пример #2
0
void Config::constructUnitWithXML(Unit* unit, xmlNodePtr node)
{
	xmlChar* szid = xmlGetProp(node, BAD_CAST"id");
	xmlChar* szname = xmlGetProp(node, BAD_CAST"name");
	xmlChar* szlevel = xmlGetProp(node, BAD_CAST"level");
	xmlChar* szAI = xmlGetProp(node, BAD_CAST"ai");
	xmlChar* szAlign = xmlGetProp(node, BAD_CAST"alignment");
	xmlChar* szMaxHealth = xmlGetProp(node, BAD_CAST"maxHealth");
	xmlChar* szAgility = xmlGetProp(node, BAD_CAST"agility");
	xmlChar* szSkills = xmlGetProp(node, BAD_CAST"skills");
	xmlChar* szAttackFreq = xmlGetProp(node, BAD_CAST"attackFreq");
	xmlChar* szAttackRange = xmlGetProp(node, BAD_CAST"attackRange");
	xmlChar *szView = xmlGetProp(node, BAD_CAST"view");

	unit->cid = atoi((const char*)szid);
	unit->name = (char*)szname;
	unit->maxHealth = atoi((const char*)szMaxHealth);
	unit->agility = atoi((const char*)szAgility);
	unit->ai = atoi((const char*)szAI);
	unit->alignment = atoi((const char*)szAlign);

	parseSkills(unit,szSkills);
	unit->attackFreq = atoi((const char*)szAttackFreq);
	parseRange(unit, szAttackRange);
	parseView(unit, szView);
}
void BlobResourceHandle::doStart()
{
    // Do not continue if the request is aborted or an error occurs.
    if (m_aborted || m_errorCode)
        return;

    // If the blob data is not found, fail now.
    if (!m_blobData) {
        m_errorCode = notFoundError;
        notifyResponse();
        return;
    }

    // Parse the "Range" header we care about.
    String range = firstRequest().httpHeaderField("Range");
    if (!range.isEmpty() && !parseRange(range, m_rangeOffset, m_rangeEnd, m_rangeSuffixLength)) {
        m_errorCode = rangeError;
        notifyResponse();
        return;
    }

    if (m_async)
        getSizeForNext();
    else {
        for (size_t i = 0; i < m_blobData->items().size() && !m_aborted && !m_errorCode; ++i)
            getSizeForNext();
        notifyResponse();
    }
}
Пример #4
0
int RtspClientSession::handle_play(RtspClientConnection * rcc, 
								   MediaSubSession * subSession, 
								   std::string & fullRequestStr){

	std::string strScale;
	
	//parse scale
	size_type pos = fullRequestStr.find("Scale:");
	if(pos != std::string::npos){
		pos += 5;
		while(fullRequestStr[++pos] == ' ');
		float fscale = (float)atof(fullRequestStr.c_str() + pos);
		append(strScale, "Scale: %f\r\n", fscale);
	}
	
	const ipaddr & localAddr = rcc->get_localaddr();
	std::string rtspUrl;
	append(rtspUrl, "RTP-Info: rtsp://%s:%u/%s/%s;seq=%u//;rtptime=%u", 
		localAddr.ip, watcher::instance()->tcp_port(),
		m_mediaSession->StreamName().c_str(),
		subSession->GetTrackId().c_str(),
		subSession->SeqNo(),
		subSession->RtpTimestamp());
	


	std::string absstart, absend;
	double startTime = 0, endTime = 0;
	
	int result = parseRange(fullRequestStr, absstart, absend, startTime, endTime);
	std::string response;
	append(response,
		"RTSP/1.0 200 OK\r\n"
		"CSeq: %s\r\n" 
		"%s" 
		"%s"
		"Session: %s\r\n"
		"%s\r\n\r\n",
		rcc->getSeq().c_str(), 
		dateStr().c_str(), 
		strScale.c_str(),
		m_sessionId.c_str(),
		rtspUrl.c_str());
	if(result < 0){
		
	}
	
	debug_log("play: %s\n", response.c_str());

	rcc->post_send(response.c_str(), response.length());
	subSession->StartStream(rcc->get_rtsp());
	
	return 0;
}
Пример #5
0
void decodeXYZdata(char *response, float *bigX, float *bigY, float *bigZ, float *xChroma, float *yChroma, float *YLum, int *redRange, int *greenRange, int *blueRange)
{
	int charIndex;

	/* Decode X */
	charIndex = 2;
	*bigX = string3ToFloat(response, charIndex);

	/* Decode Y */
	charIndex = 5;
	*bigY = string3ToFloat(response, charIndex);

	/* Decode Z */
	charIndex = 8;
	*bigZ = string3ToFloat(response, charIndex);

    float sum = (*bigX) + (*bigY) + (*bigZ);
	*xChroma = *bigX / sum;
    *yChroma = *bigY / sum;
    *YLum    = *bigY;

	/* Decode range */
    int ranges[3];
    parseRange((unsigned char)response[11], ranges);
    *redRange   = ranges[0];
	*greenRange = ranges[1];
	*blueRange  = ranges[2];

	/* Decode Error */
	char errorCode = response[13];	
	if (strncmp(&errorCode,"L",1) == 0)
		mexPrintf(">>>>>>>>>>>>>>> error code: AIMING LIGHTS\n");
	else if (strncmp(&errorCode,"u",1) == 0)
       	mexPrintf(">>>>>>>>>>>>>>> error code: BOTTOM_UNDER_RANGE\n");
	else if (strncmp(&errorCode,"v",1) == 0)
		mexPrintf(">>>>>>>>>>>>>>> error code: TOP_OVER_RANGE\n");
	else if (strncmp(&errorCode,"w",1) == 0)
		mexPrintf(">>>>>>>>>>>>>>> error code: OVER_HIGH_RANGE\n");
	else if (strncmp(&errorCode,"t",1) == 0)
		mexPrintf(">>>>>>>>>>>>>>> error code: BLACK_ZERO\n");
	else if (strncmp(&errorCode,"s",1) == 0) 
		mexPrintf(">>>>>>>>>>>>>>> error code: BLACK_OVERDRIVE\n");
	else if (strncmp(&errorCode,"b",1) == 0)
		mexPrintf(">>>>>>>>>>>>>>> error code: BLACK_EXCESSIVE\n");
	else if (strncmp(&errorCode,"X",1) == 0) 
		mexPrintf(">>>>>>>>>>>>>>> error code: FIRMWARE\n");
	else if (strncmp(&errorCode,"B",1) == 0) 
		mexPrintf(">>>>>>>>>>>>>>> error code: FIRMWARE\n");
}
Пример #6
0
 TreeChains parseChainString(const std::string& chainStr, bool isPrivate) {
     TreeChains treeChains;
     
     const std::string s = StringUtils::split(chainStr)[0]; //trim trailing whitespaces
     
     std::deque<std::string> splitChain = StringUtils::split(s, '/');
     
     //account for root node
     treeChains.push_back(IsPrivateNPathRange(true , Range(NODE_IDX_M_FLAG, NODE_IDX_M_FLAG)));
     
     if (splitChain.back() == "") splitChain.pop_back(); // happens if chainStr has '/' at end
     for (std::string& node : splitChain) {
         if (node.back() == '\'') {
             if (! isPrivate) throw std::runtime_error("Invalid chain "+ chainStr+ ",  not private extended key.");
             
             node = node.substr(0,node.length()-1);
             if (node.front() == '(' && node.back() == ')') {
                 IsPrivateNPathRange range = parseRange(node, true);
                 treeChains.push_back(range);
             } else {
                 uint32_t num = toPrime(std::stoi(node));
                 treeChains.push_back(IsPrivateNPathRange(true , Range(num, num)));
             }
         } else {
             if (node.front() == '(' && node.back() == ')') {
                 IsPrivateNPathRange range = parseRange(node, false);
                 treeChains.push_back(range);
             } else {
                 uint32_t num = std::stoi(node);
                 treeChains.push_back(IsPrivateNPathRange(false , Range(num, num)));
             }
         }
     }
     
     return treeChains;
 }
/// GPUmxAssign
void GPUmxAssign(const GPUtype &LHS, const GPUtype &RHS, int dir, int nrhs,
    const mxArray *prhs[]) {

  // simple garbage collection
  MyGCObj<Range> mygc1;


  // rg is the Range we have to populate
  Range *rg;
  parseRange(nrhs, &prhs[0], &rg, mygc1);

  // After creating the Range, I can call
  gm->gputype.mxAssign(LHS, RHS, *rg, dir);

}
/// GPUmxSlice
GPUtype GPUmxSliceDrv(const GPUtype &RHS, int nrhs,
    const mxArray *prhs[]) {

  // simple garbage collection
  MyGCObj<Range> mygc1;

  GPUtype OUT;

  gpuTYPE_t trhs = gm->gputype.getType(RHS);


  // rg is the Range we have to populate
  Range *rg;
  parseRange(nrhs,&prhs[0],&rg, mygc1);

  // After creating the Range, I can call mxSlice
  // mxSlice uses indexes starting from 1 (Fortran/Matlab)
  OUT = gm->gputype.mxSlice(RHS,*rg);

  // I have to handle some particular cases here.
  // 1) The final result should have the same dimensions
  // as the indexes array
  // For example:
  // slice(A,{[1 2;3 4]})
  // size(A) = [2 2]
  //
  // slice(A,:) should generate a Nx1 vector (and not 1xN)
  //
  if (nrhs==1) {
    if (mxGetClassID(prhs[0]) == mxCELL_CLASS) {
      mxArray *mx = mxGetCell(prhs[0], 0);
      const mwSize * mysize = mxGetDimensions(mx);
      int n = mxGetNumberOfDimensions(mx);
      gm->gputype.setSize(OUT, n, mysize);

    } else if (mxGetClassID(prhs[0]) == mxCHAR_CLASS) {
      const int *mysize = gm->gputype.getSize(OUT);
      int newsize[2];
      newsize[0] = mysize[1];
      newsize[1] = mysize[0];

      gm->gputype.setSize(OUT, 2, newsize);
    }
  }

  return OUT;

}
Пример #9
0
Object * parseReferenceOrRange(Collector * c, Tokenizer * tt) {
	Coord * ref = NULL;

	ref = parseReference(c, tt); if (!ref) goto fail;
	char * sp = tt->bp;
	TokenType t = tokenizerNext(tt);
	if (t == TOK_COLON) {
		return parseRange(c, tt, ref);
	} else {
		tokenizerSet(tt, sp);
	}
	return (Object *) ref;

fail:
	return NULL;
}
Пример #10
0
void NetworkDataTaskBlob::resume()
{
    ASSERT(m_state != State::Running);
    if (m_state == State::Canceling || m_state == State::Completed)
        return;

    m_state = State::Running;

    if (m_scheduledFailureType != NoFailure) {
        ASSERT(m_failureTimer.isActive());
        return;
    }

    RunLoop::main().dispatch([this, protectedThis = makeRef(*this)] {
        if (m_state == State::Canceling || m_state == State::Completed || !m_client) {
            clearStream();
            return;
        }

        if (!equalLettersIgnoringASCIICase(m_firstRequest.httpMethod(), "get")) {
            didFail(Error::MethodNotAllowed);
            return;
        }

        // If the blob data is not found, fail now.
        if (!m_blobData) {
            didFail(Error::NotFoundError);
            return;
        }

        // Parse the "Range" header we care about.
        String range = m_firstRequest.httpHeaderField(HTTPHeaderName::Range);
        if (!range.isEmpty() && !parseRange(range, m_rangeOffset, m_rangeEnd, m_rangeSuffixLength)) {
            didReceiveResponse(Error::RangeError);
            return;
        }

        getSizeForNext();
    });
}
Пример #11
0
 void FllImporter::processInputVariable(const std::string& block, Engine* engine) const {
     std::istringstream reader(block);
     std::string line;
     InputVariable* inputVariable = new InputVariable;
     engine->addInputVariable(inputVariable);
     while (std::getline(reader, line)) {
         std::pair<std::string, std::string> keyValue = parseKeyValue(line, ':');
         if ("InputVariable" == keyValue.first) {
             inputVariable->setName(keyValue.second);
         } else if ("enabled" == keyValue.first) {
             inputVariable->setEnabled(parseBoolean(keyValue.second));
         } else if ("range" == keyValue.first) {
             std::pair<scalar, scalar> range = parseRange(keyValue.second);
             inputVariable->setRange(range.first, range.second);
         } else if ("term" == keyValue.first) {
             inputVariable->addTerm(parseTerm(keyValue.second, engine));
         } else {
             throw fl::Exception("[import error] key <" + keyValue.first + "> not "
                     "recognized in pair <" + keyValue.first + ":" + keyValue.second + ">", FL_AT);
         }
     }
 }
void CRangeChooserDialog::initConnections() {
    // Signals from text/list widgets
    QObject::connect(m_rangeList, SIGNAL(currentItemChanged(QListWidgetItem*, QListWidgetItem*)),
                     this, SLOT(editRange(QListWidgetItem*)));

    QObject::connect(m_rangeEdit, SIGNAL(textChanged()),
                     this, SLOT(parseRange()));
    QObject::connect(m_rangeEdit, SIGNAL(textChanged()),
                     this, SLOT(rangeChanged()));

    QObject::connect(m_nameEdit, SIGNAL(textChanged(const QString&)),
                     this, SLOT(nameChanged(const QString&)));

    // Buttons
    QObject::connect(m_buttonBox, SIGNAL(accepted()), this, SLOT(slotOk()));
    QObject::connect(m_buttonBox, SIGNAL(rejected()), this, SLOT(close()));
    QObject::connect(m_newRangeButton, SIGNAL(clicked()), this, SLOT(addNewRange()));
    QObject::connect(m_deleteRangeButton, SIGNAL(clicked()), this, SLOT(deleteCurrentRange()));
    //restore defaults!
    QPushButton* defaultsButton = m_buttonBox->button(QDialogButtonBox::RestoreDefaults);
    QObject::connect(defaultsButton, SIGNAL(clicked()), this, SLOT(slotDefault()));
}
Пример #13
0
 void FllImporter::processOutputVariable(const std::string& block, Engine* engine) const {
     std::istringstream reader(block);
     std::string line;
     FL_unique_ptr<OutputVariable> outputVariable(new OutputVariable);
     while (std::getline(reader, line)) {
         std::pair<std::string, std::string> keyValue = parseKeyValue(line, ':');
         if ("OutputVariable" == keyValue.first) {
             outputVariable->setName(Op::validName(keyValue.second));
         } else if ("enabled" == keyValue.first) {
             outputVariable->setEnabled(parseBoolean(keyValue.second));
         } else if ("range" == keyValue.first) {
             std::pair<scalar, scalar> range = parseRange(keyValue.second);
             outputVariable->setRange(range.first, range.second);
         } else if ("default" == keyValue.first) {
             outputVariable->setDefaultValue(Op::toScalar(keyValue.second));
         } else if ("lock-previous" == keyValue.first or "lock-valid" == keyValue.first) {
             outputVariable->setLockPreviousValue(parseBoolean(keyValue.second));
         } else if ("lock-range" == keyValue.first) {
             outputVariable->setLockValueInRange(parseBoolean(keyValue.second));
         } else if ("defuzzifier" == keyValue.first) {
             outputVariable->setDefuzzifier(parseDefuzzifier(keyValue.second));
         } else if ("aggregation" == keyValue.first) {
             outputVariable->fuzzyOutput()->setAggregation(parseSNorm(keyValue.second));
         } else if ("accumulation" == keyValue.first) {
             outputVariable->fuzzyOutput()->setAggregation(parseSNorm(keyValue.second));
             FL_LOG("[warning] obsolete usage of identifier <accumulation: SNorm> in OutputVariable");
             FL_LOG("[information] from version 6.0, the identifier <aggregation: SNorm> should be used");
             FL_LOG("[backward compatibility] assumed "
                     "<aggregation: " << keyValue.second << "> "
                     "instead of <accumulation: " << keyValue.second << ">");
         } else if ("term" == keyValue.first) {
             outputVariable->addTerm(parseTerm(keyValue.second, engine));
         } else {
             throw Exception("[import error] key <" + keyValue.first + "> not "
                     "recognized in pair <" + keyValue.first + ":" + keyValue.second + ">", FL_AT);
         }
     }
     engine->addOutputVariable(outputVariable.release());
 }
Пример #14
0
void BlobResourceHandle::doStart()
{
    ASSERT(isMainThread());

    // Do not continue if the request is aborted or an error occurs.
    if (m_aborted || m_errorCode)
        return;

    if (!equalLettersIgnoringASCIICase(firstRequest().httpMethod(), "get")) {
        notifyFail(methodNotAllowed);
        return;
    }

    // If the blob data is not found, fail now.
    if (!m_blobData) {
        m_errorCode = notFoundError;
        notifyResponse();
        return;
    }

    // Parse the "Range" header we care about.
    String range = firstRequest().httpHeaderField(HTTPHeaderName::Range);
    if (!range.isEmpty() && !parseRange(range, m_rangeOffset, m_rangeEnd, m_rangeSuffixLength)) {
        m_errorCode = rangeError;
        notifyResponse();
        return;
    }

    if (m_async)
        getSizeForNext();
    else {
        Ref<BlobResourceHandle> protectedThis(*this); // getSizeForNext calls the client
        for (size_t i = 0; i < m_blobData->items().size() && !m_aborted && !m_errorCode; ++i)
            getSizeForNext();
        notifyResponse();
    }
}
Пример #15
0
/*
 *  Parse the request headers. Return true if the header parsed.
 */
static bool parseHeaders(MaConn *conn, MaPacket *packet)
{
    MaHostAddress   *address;
    MaRequest       *req;
    MaHost          *host, *hp;
    MaLimits        *limits;
    MprBuf          *content;
    char            keyBuf[MPR_MAX_STRING];
    char            *key, *value, *cp, *tok;
    int             count, keepAlive;

    req = conn->request;
    host = req->host;
    content = packet->content;
    conn->request->headerPacket = packet;
    limits = &conn->http->limits;
    keepAlive = 0;

    strcpy(keyBuf, "HTTP_");
    mprAssert(strstr((char*) content->start, "\r\n"));

    for (count = 0; content->start[0] != '\r' && !conn->connectionFailed; count++) {

        if (count >= limits->maxNumHeaders) {
            maFailConnection(conn, MPR_HTTP_CODE_BAD_REQUEST, "Too many headers");
            return 0;
        }
        if ((key = getToken(conn, ":")) == 0 || *key == '\0') {
            maFailConnection(conn, MPR_HTTP_CODE_BAD_REQUEST, "Bad header format");
            return 0;
        }

        value = getToken(conn, "\r\n");
        while (isspace((int) *value)) {
            value++;
        }
        if (conn->requestFailed) {
            continue;
        }
        mprStrUpper(key);
        for (cp = key; *cp; cp++) {
            if (*cp == '-') {
                *cp = '_';
            }
        }
        mprLog(req, 8, "Key %s, value %s", key, value);
        if (strspn(key, "%<>/\\") > 0) {
            maFailConnection(conn, MPR_HTTP_CODE_BAD_REQUEST, "Bad header key value");
            continue;
        }

        /*
         *  Define the header with a "HTTP_" prefix
         */
        mprStrcpy(&keyBuf[5], sizeof(keyBuf) - 5, key);
        mprAddDuplicateHash(req->headers, keyBuf, value);

        switch (key[0]) {
        case 'A':
            if (strcmp(key, "AUTHORIZATION") == 0) {
                value = mprStrdup(req, value);
                req->authType = mprStrTok(value, " \t", &tok);
                req->authDetails = tok;

            } else if (strcmp(key, "ACCEPT_CHARSET") == 0) {
                req->acceptCharset = value;

            } else if (strcmp(key, "ACCEPT") == 0) {
                req->accept = value;

            } else if (strcmp(key, "ACCEPT_ENCODING") == 0) {
                req->acceptEncoding = value;
            }
            break;

        case 'C':
            if (strcmp(key, "CONTENT_LENGTH") == 0) {
                if (req->length >= 0) {
                    maFailConnection(conn, MPR_HTTP_CODE_BAD_REQUEST, "Mulitple content length headers");
                    continue;
                }
                req->length = mprAtoi(value, 10);
                if (req->length < 0) {
                    maFailConnection(conn, MPR_HTTP_CODE_BAD_REQUEST, "Bad content length");
                    continue;
                }
                if (req->length >= host->limits->maxBody) {
                    maFailConnection(conn, MPR_HTTP_CODE_REQUEST_TOO_LARGE, 
                        "Request content length %Ld is too big. Limit %Ld", req->length, host->limits->maxBody);
                    continue;
                }
                mprAssert(req->length >= 0);
                req->remainingContent = req->length;
                req->contentLengthStr = value;

            } else if (strcmp(key, "CONTENT_RANGE") == 0) {
                /*
                 *  This headers specifies the range of any posted body data
                 *  Format is:  Content-Range: bytes n1-n2/length
                 *  Where n1 is first byte pos and n2 is last byte pos
                 */
                char    *sp;
                int     start, end, size;

                start = end = size = -1;
                sp = value;
                while (*sp && !isdigit((int) *sp)) {
                    sp++;
                }
                if (*sp) {
                    start = (int) mprAtoi(sp, 10);

                    if ((sp = strchr(sp, '-')) != 0) {
                        end = (int) mprAtoi(++sp, 10);
                    }
                    if ((sp = strchr(sp, '/')) != 0) {
                        /*
                         *  Note this is not the content length transmitted, but the original size of the input of which 
                         *  the client is transmitting only a portion.
                         */
                        size = (int) mprAtoi(++sp, 10);
                    }
                }
                if (start < 0 || end < 0 || size < 0 || end <= start) {
                    maFailRequest(conn, MPR_HTTP_CODE_RANGE_NOT_SATISFIABLE, "Bad content range");
                    continue;
                }
                req->inputRange = maCreateRange(conn, start, end);

            } else if (strcmp(key, "CONTENT_TYPE") == 0) {
                req->mimeType = value;
                req->form = strstr(value, "application/x-www-form-urlencoded") != 0;

            } else if (strcmp(key, "COOKIE") == 0) {
                if (req->cookie && *req->cookie) {
                    req->cookie = mprStrcat(req, -1, req->cookie, "; ", value, NULL);
                } else {
                    req->cookie = value;
                }

            } else if (strcmp(key, "CONNECTION") == 0) {
                req->connection = value;
                if (mprStrcmpAnyCase(value, "KEEP-ALIVE") == 0) {
                    keepAlive++;

                } else if (mprStrcmpAnyCase(value, "CLOSE") == 0) {
                    conn->keepAliveCount = 0;
                }
                if (!host->keepAlive) {
                    conn->keepAliveCount = 0;
                }
            }
            break;

        case 'F':
            req->forwarded = value;
            break;

        case 'H':
            if (strcmp(key, "HOST") == 0) {
                req->hostName = value;
                address = conn->address;
                if (maIsNamedVirtualHostAddress(address)) {
                    hp = maLookupVirtualHost(address, value);
                    if (hp == 0) {
                        maFailRequest(conn, 404, "No host to serve request. Searching for %s", value);
                        mprLog(conn, 1, "Can't find virtual host %s", value);
                        continue;
                    }
                    req->host = hp;
                    /*
                     *  Reassign this request to a new host
                     */
                    maRemoveConn(host, conn);
                    host = hp;
                    conn->host = hp;
                    maAddConn(hp, conn);
                }
            }
            break;

        case 'I':
            if ((strcmp(key, "IF_MODIFIED_SINCE") == 0) || (strcmp(key, "IF_UNMODIFIED_SINCE") == 0)) {
                MprTime     newDate = 0;
                char        *cp;
                bool        ifModified = (key[3] == 'M');

                if ((cp = strchr(value, ';')) != 0) {
                    *cp = '\0';
                }
                if (mprParseTime(conn, &newDate, value, MPR_UTC_TIMEZONE, NULL) < 0) {
                    mprAssert(0);
                    break;
                }
                if (newDate) {
                    setIfModifiedDate(conn, newDate, ifModified);
                    req->flags |= MA_REQ_IF_MODIFIED;
                }

            } else if ((strcmp(key, "IF_MATCH") == 0) || (strcmp(key, "IF_NONE_MATCH") == 0)) {
                char    *word, *tok;
                bool    ifMatch = key[3] == 'M';

                if ((tok = strchr(value, ';')) != 0) {
                    *tok = '\0';
                }
                req->ifMatch = ifMatch;
                req->flags |= MA_REQ_IF_MODIFIED;

                value = mprStrdup(conn, value);
                word = mprStrTok(value, " ,", &tok);
                while (word) {
                    addMatchEtag(conn, word);
                    word = mprStrTok(0, " ,", &tok);
                }

            } else if (strcmp(key, "IF_RANGE") == 0) {
                char    *word, *tok;

                if ((tok = strchr(value, ';')) != 0) {
                    *tok = '\0';
                }
                req->ifMatch = 1;
                req->flags |= MA_REQ_IF_MODIFIED;

                value = mprStrdup(conn, value);
                word = mprStrTok(value, " ,", &tok);
                while (word) {
                    addMatchEtag(conn, word);
                    word = mprStrTok(0, " ,", &tok);
                }
            }
            break;

        case 'P':
            if (strcmp(key, "PRAGMA") == 0) {
                req->pragma = value;
            }
            break;

        case 'R':
            if (strcmp(key, "RANGE") == 0) {
                if (!parseRange(conn, value)) {
                    maFailRequest(conn, MPR_HTTP_CODE_RANGE_NOT_SATISFIABLE, "Bad range");
                }
            } else if (strcmp(key, "REFERER") == 0) {
                /* NOTE: yes the header is misspelt in the spec */
                req->referer = value;
            }
            break;

        case 'T':
            if (strcmp(key, "TRANSFER_ENCODING") == 0) {
                mprStrLower(value);
                if (strcmp(value, "chunked") == 0) {
                    req->flags |= MA_REQ_CHUNKED;
                    /*
                     *  This will be revised by the chunk filter as chunks are processed and will be set to zero when the
                     *  last chunk has been received.
                     */
                    req->remainingContent = MAXINT;
                }
            }
            break;
        
#if BLD_DEBUG
        case 'X':
            if (strcmp(key, "X_APPWEB_CHUNK_SIZE") == 0) {
                mprStrUpper(value);
                conn->response->chunkSize = atoi(value);
                if (conn->response->chunkSize <= 0) {
                    conn->response->chunkSize = 0;
                } else if (conn->response->chunkSize > conn->http->limits.maxChunkSize) {
                    conn->response->chunkSize = conn->http->limits.maxChunkSize;
                }
            }
            break;
#endif

        case 'U':
            if (strcmp(key, "USER_AGENT") == 0) {
                req->userAgent = value;
            }
            break;
        }
    }
    if (conn->protocol == 0 && !keepAlive) {
        conn->keepAliveCount = 0;
    }
    if (!(req->flags & MA_REQ_CHUNKED)) {
        /*  
         *  Step over "\r\n" after headers. As an optimization, don't do this if chunked so chunking can parse a single
         *  chunk delimiter of "\r\nSIZE ...\r\n"
         */
        mprAdjustBufStart(content, 2);
    }
    mprLog(conn, 3, "Select host \"%s\"", conn->host->name);

    if (maSetRequestUri(conn, req->url, "") < 0) {
        maFailConnection(conn, MPR_HTTP_CODE_BAD_REQUEST, "Bad URI format");
        return 0;
    }
    if (conn->host->secure) {
        req->parsedUri->scheme = mprStrdup(req, "https");
    }
    req->parsedUri->port = conn->sock->port;
    req->parsedUri->host = req->hostName ? req->hostName : conn->host->name;
    return 1;
}
Пример #16
0
	void ExcelFile::readSheet(Sheet& sh)
	{
		rapidxml::xml_document<> doc;
		rapidxml::xml_node<> *root, *row, *c, *v, *d;

		_zip->openXML(sh._path.c_str(), doc);

		root = doc.first_node("worksheet");

		d = root->first_node("dimension");
		if (d)
			parseRange(d->first_attribute("ref")->value(), sh._dimension);

		row = root->first_node("sheetData");
		row = row->first_node("row");

		int vecsize = (sh._dimension.lastCol - sh._dimension.firstCol + 1) * (sh._dimension.lastRow - sh._dimension.firstRow + 1);

		sh._cells.resize(vecsize);


		while (row)
		{
			int rowIdx = lexical_cast<int>(row->first_attribute("r")->value());
			c = row->first_node("c");

			while (c)
			{
				int colIdx = 0;
				parseCell(c->first_attribute("r")->value(), rowIdx, colIdx);
				int index = sh.toIndex(rowIdx, colIdx);

				const char *s, *t;

				v = c->first_node("v");

				Cell* cell = new Cell;

				if (v)
				{
					s = v->value();
					if (c->first_attribute("t"))
					{
						t = c->first_attribute("t")->value();
						if (!strcmp(t, "s"))
						{
							cell->value = (char*)_sharedString[atoi(s)].c_str();
							cell->type = "string";
						}
						else if (!strcmp(t, "b"))
						{
							if (!strcmp(s, "0"))
							{
								cell->value = "FALSE";
							}
							else
							{
								cell->value = "TRUE";
							}
							cell->type = "bool";
						}
					}
					else
					{
						cell->type = "unknow";
						cell->value = (char*)s;
					}
				}
				sh._cells[index] = cell;
				c = c->next_sibling("c");
			}

			row = row->next_sibling("row");
		}
	}
Пример #17
0
seqan::ArgumentParser::ParseResult
parseArgs(SakOptions & options,
          int argc,
          char ** argv)
{
    seqan::ArgumentParser parser("sak");
    setShortDescription(parser, "Slicing and dicing of FASTA/FASTQ files..");
    setVersion(parser, SEQAN_APP_VERSION " [" SEQAN_REVISION "]");
    setDate(parser, SEQAN_DATE);
    setCategory(parser, "Utilities");

    addUsageLine(parser, "[\\fIOPTIONS\\fP] [\\fB-o\\fP \\fIOUT.{fa,fq}\\fP] \\fIIN.{fa,fq}\\fP");
    addDescription(parser, "\"It slices, it dices and it makes the laundry!\"");
    addDescription(parser, "Original SAK tool by David Weese. Rewrite by Manuel Holtgrewe.");

    // The only argument is the input file.
    addArgument(parser, seqan::ArgParseArgument(seqan::ArgParseArgument::INPUT_FILE, "IN"));

    // Only FASTA and FASTQ files are allowed as input.
    setValidValues(parser, 0, seqan::SeqFileIn::getFileExtensions());

    // TODO(holtgrew): I want a custom help text!
    // addOption(parser, seqan::ArgParseOption("h", "help", "This helpful screen."));
    addOption(parser, seqan::ArgParseOption("v", "verbose", "Verbose, log to STDERR."));
    hideOption(parser, "verbose");
    addOption(parser, seqan::ArgParseOption("vv", "very-verbose", "Very verbose, log to STDERR."));
    hideOption(parser, "very-verbose");

    addSection(parser, "Output Options");
    addOption(parser, seqan::ArgParseOption("o", "out-path",
                                            "Path to the resulting file.  If omitted, result is printed to stdout in FastQ format.",
                                            seqan::ArgParseOption::OUTPUT_FILE, "FASTX"));
    setValidValues(parser, "out-path", seqan::SeqFileOut::getFileExtensions());
    addOption(parser, seqan::ArgParseOption("rc", "revcomp", "Reverse-complement output."));
    addOption(parser, seqan::ArgParseOption("l", "max-length", "Maximal number of sequence characters to write out.",
                                            seqan::ArgParseOption::INTEGER, "LEN"));

    addSection(parser, "Filter Options");
    addOption(parser, seqan::ArgParseOption("s", "sequence", "Select the given sequence for extraction by 0-based index.",
                                            seqan::ArgParseOption::INTEGER, "NUM", true));
    addOption(parser, seqan::ArgParseOption("sn", "sequence-name", "Select sequence with name prefix being \\fINAME\\fP.",
                                            seqan::ArgParseOption::STRING, "NAME", true));
    addOption(parser, seqan::ArgParseOption("ss", "sequences",
                                            "Select sequences \\fIfrom\\fP-\\fIto\\fP where \\fIfrom\\fP and \\fIto\\fP "
                                            "are 0-based indices.",
                                            seqan::ArgParseArgument::STRING, "RANGE", true));
    addOption(parser, seqan::ArgParseOption("i", "infix",
                                            "Select characters \\fIfrom\\fP-\\fIto\\fP where \\fIfrom\\fP and \\fIto\\fP "
                                            "are 0-based indices.",
                                            seqan::ArgParseArgument::STRING, "RANGE", true));

    addOption(parser, seqan::ArgParseOption("ll", "line-length",
                                            "Set line length in output file.  See section \\fILine Length\\fP for details.",
                                            seqan::ArgParseArgument::INTEGER, "LEN", false));
    setMinValue(parser, "line-length", "-1");

    addTextSection(parser, "Line Length");
    addText(parser,
            "You can use the setting \\fB--line-length\\fP for setting the resulting line length.  By default, "
            "sequences in FASTA files are written with at most 70 characters per line and sequences in FASTQ files are "
            "written without any line breaks.  The quality sequence in FASTQ file is written in the same way as the "
            "residue sequence.");
    addText(parser,
            "The default is selected with a \\fB--line-length\\fP value of \\fI-1\\fP and line breaks can be disabled "
            "with a value of \\fI0\\fP.");

    addTextSection(parser, "Usage Examples");
    addListItem(parser, "\\fBsak\\fP \\fB-s\\fP \\fI10\\fP \\fIIN.fa\\fP",
                "Cut out 11th sequence from \\fIIN.fa\\fP and write to stdout as FASTA.");
    addListItem(parser, "\\fBsak\\fP \\fB-ss\\fP \\fI10-12\\fP \\fB-ss\\fP \\fI100-200\\fP \\fIIN.fq\\fP",
                "Cut out 11th up to and including 12th and 101th up to and including 199th sequence from \\fIIN.fq\\fP "
                "and write to stdout as FASTA.");

    seqan::ArgumentParser::ParseResult res = parse(parser, argc, argv);

    if (res != seqan::ArgumentParser::PARSE_OK)
        return res;

    getArgumentValue(options.inFastxPath, parser, 0);

    seqan::CharString tmp;
    getOptionValue(tmp, parser, "out-path");

    if (isSet(parser, "out-path"))
        getOptionValue(options.outPath, parser, "out-path");

    if (isSet(parser, "verbose"))
        options.verbosity = 2;
    if (isSet(parser, "very-verbose"))
        options.verbosity = 3;

    if (isSet(parser, "sequence"))
    {
        std::vector<std::string> sequenceIds = getOptionValues(parser, "sequence");
        for (unsigned i = 0; i < seqan::length(sequenceIds); ++i)
        {
            unsigned idx = 0;
            if (!seqan::lexicalCast(idx, sequenceIds[i]))
            {
                std::cerr << "ERROR: Invalid sequence index " << sequenceIds[i] << "\n";
                return seqan::ArgumentParser::PARSE_ERROR;
            }
            appendValue(options.seqIndices, idx);
        }
    }

    if (isSet(parser, "sequences"))
    {
        std::vector<std::string> sequenceRanges = getOptionValues(parser, "sequences");
        seqan::CharString buffer;
        for (unsigned i = 0; i < seqan::length(sequenceRanges); ++i)
        {
            seqan::Pair<uint64_t> range;
            if (!parseRange(range.i1, range.i2, sequenceRanges[i]))
            {
                std::cerr << "ERROR: Invalid range " << sequenceRanges[i] << "\n";
                return seqan::ArgumentParser::PARSE_ERROR;
            }
            appendValue(options.seqIndexRanges, range);
        }
    }

    if (isSet(parser, "infix"))
    {
        seqan::CharString buffer;
        getOptionValue(buffer, parser, "infix");
        if (!parseRange(options.seqInfixBegin, options.seqInfixEnd, buffer))
        {
            std::cerr << "ERROR: Invalid range " << buffer << "\n";
            return seqan::ArgumentParser::PARSE_ERROR;
        }
    }

    options.reverseComplement = isSet(parser, "revcomp");

    if (isSet(parser, "max-length"))
        getOptionValue(options.maxLength, parser, "max-length");

    if (isSet(parser, "sequence-name"))
        getOptionValue(options.readPattern, parser, "sequence-name");

    getOptionValue(options.seqOutOptions.lineLength, parser, "line-length");

    return res;
}