static TInt KillProcess(const TDesC& aProcessName)
	{
	TFullName name;
	//TheTest.Printf(_L("Find and kill \"%S\" process.\n"), &aProcessName);
	TBuf<64> pattern(aProcessName);
	TInt length = pattern.Length();
	pattern += _L("*");
	TFindProcess procFinder(pattern);

	while (procFinder.Next(name) == KErrNone)
		{
		if (name.Length() > length)
			{//If found name is a string containing aProcessName string.
			TChar c(name[length]);
			if (c.IsAlphaDigit() ||
				c == TChar('_') ||
				c == TChar('-'))
				{
				// If the found name is other valid application name
				// starting with aProcessName string.
				//TheTest.Printf(_L(":: Process name: \"%S\".\n"), &name);
				continue;
				}
			}
		RProcess proc;
		if (proc.Open(name) == KErrNone)
			{
			//RPorcess::Kill() is expected to be used here.
			//But it is impossible, because the test application will need "PowerMgmt" capability.
			//But if the test application has "PowerMgmt" capability, then it won't be possible to use the 
			//sqlite3_secure library, which has "ProtServ" capability only.
			}
		proc.Close();
		}
	return KErrNone;
	}
Пример #2
0
void PreLearnWords::InitZi(){
    char line[1024];
    QFile fdic("dic_utf8.txt");
    DBControler::OpenDB();
    DBControler::CreateZITable();
    int index=0;
    if ( fdic.open( QIODevice::ReadOnly | QIODevice::Text ) ){
        while( !fdic.atEnd() ){
            memset((char *)line,0,1024);
            fdic.readLine(line,1024);
            QString str = QString::fromUtf8(line);
            if( str.startsWith("*")){
                QString pattern("\\*(.*) ([abcdefghijklmnopqrstuvwxyzīíǐìāáǎàōóǒòūúǔùüǖǘǚǜēéěèńň,]*)笔划:(.*)部首:(.*)五笔输入法");
                QRegExp rx(pattern);

                int pos = str.indexOf(rx);
                if(pos < 0){
                }else{
                    QStringList pinyin = rx.cap(2).split(",");
                    if( pinyin.size() == 0 || pinyin.at(0).length() == 0){
                        //qDebug() << rx.cap(1) << rx.cap(2) << rx.cap(3) << rx.cap(4);
                        DBControler::AddZItoTable(index++,rx.cap(1),rx.cap(2),rx.cap(3),rx.cap(4));
                    }else{
                        for( int i = 0 ; i < pinyin.size() ; i++){
                            if( pinyin.at(i).length() == 0) break;
                            else
                                DBControler::AddZItoTable(index++,rx.cap(1),pinyin.at(i),rx.cap(3),rx.cap(4));
                        }
                    }
                }
            }
        }

        fdic.close();
    }
}
static jlong NativeDecimalFormat_open(JNIEnv* env, jclass, jstring pattern0,
        jstring currencySymbol, jchar decimalSeparator, jchar digit, jstring exponentSeparator,
        jchar groupingSeparator, jstring infinity,
        jstring internationalCurrencySymbol, jstring minusSign,
        jchar monetaryDecimalSeparator, jstring nan, jchar patternSeparator,
        jstring percent, jchar perMill, jchar zeroDigit) {
    UErrorCode status = U_ZERO_ERROR;
    UParseError parseError;
    ScopedJavaUnicodeString pattern(env, pattern0);
    if (!pattern.valid()) {
      return 0;
    }
    DecimalFormatSymbols* symbols = makeDecimalFormatSymbols(env,
            currencySymbol, decimalSeparator, digit, exponentSeparator, groupingSeparator,
            infinity, internationalCurrencySymbol, minusSign,
            monetaryDecimalSeparator, nan, patternSeparator, percent, perMill,
            zeroDigit);
    DecimalFormat* fmt = new DecimalFormat(pattern.unicodeString(), symbols, parseError, status);
    if (fmt == NULL) {
        delete symbols;
    }
    maybeThrowIcuException(env, "DecimalFormat::DecimalFormat", status);
    return reinterpret_cast<uintptr_t>(fmt);
}
Пример #4
0
// removes thumbnails that don't belong to any frequently used item in file history
void CleanUpThumbnailCache(const FileHistory& fileHistory) {
    AutoFreeW thumbsPath(AppGenDataFilename(THUMBNAILS_DIR_NAME));
    if (!thumbsPath)
        return;
    AutoFreeW pattern(path::Join(thumbsPath, L"*.png"));

    WStrVec files;
    WIN32_FIND_DATA fdata;

    HANDLE hfind = FindFirstFile(pattern, &fdata);
    if (INVALID_HANDLE_VALUE == hfind)
        return;
    do {
        if (!(fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
            files.Append(str::Dup(fdata.cFileName));
    } while (FindNextFile(hfind, &fdata));
    FindClose(hfind);

    Vec<DisplayState*> list;
    fileHistory.GetFrequencyOrder(list);
    for (size_t i = 0; i < list.size() && i < FILE_HISTORY_MAX_FREQUENT * 2; i++) {
        AutoFreeW bmpPath(GetThumbnailPath(list.at(i)->filePath));
        if (!bmpPath)
            continue;
        int idx = files.Find(path::GetBaseName(bmpPath));
        if (idx != -1) {
            CrashIf(idx < 0 || files.size() <= (size_t)idx);
            free(files.PopAt(idx));
        }
    }

    for (size_t i = 0; i < files.size(); i++) {
        AutoFreeW bmpPath(path::Join(thumbsPath, files.at(i)));
        file::Delete(bmpPath);
    }
}
Пример #5
0
FieldEditor* SymChooserImpl::add_filter(
    Style* s,
    const char* pattern_attribute, const char* default_pattern,
    const char* caption_attribute, const char* default_caption,
    Glyph* body, FieldEditorAction* action
) {
    String pattern(default_pattern);
    s->find_attribute(pattern_attribute, pattern);
    String caption(default_caption);
    s->find_attribute(caption_attribute, caption);
    FieldEditor* e = DialogKit::instance()->field_editor(pattern, s, action);
    fchooser_->append_input_handler(e);
    WidgetKit& kit = *kit_;
    LayoutKit& layout = *LayoutKit::instance();
    body->append(
	layout.hbox(
	    layout.vcenter(kit.fancy_label(caption), 0.5),
	    layout.hspace(2.0),
	    layout.vcenter(e, 0.5)
	)
    );
    body->append(layout.vspace(10.0));
    return e;
}
Пример #6
0
void bservInitMaps()
{
	WIN32_FIND_DATA fData;
    wstring pattern(getPesInfo()->gdbDir);
    pattern += L"GDB\\balls\\*";

	HANDLE hff = FindFirstFile(pattern.c_str(), &fData);
    if (hff != INVALID_HANDLE_VALUE)
    {
        while(true)
        {
            // check if this is a file
            if ((fData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0
                    && wcsicmp(fData.cFileName,L"map.txt")!=0)
            {
                ball_t ball;
                ball._file = fData.cFileName;

                if (ball._file.size() > 0x2f)
                {
                    LOG1S1N(L"ERROR: Ball filename too long for {%s}: %d characters. Must be 0-47. Skipping.", ball._file.c_str(), ball._file.size());
                }
                else
                {
                    _balls.insert(pair<wstring,ball_t>(
                                fData.cFileName, ball
                    ));
                }
            }

            // proceed to next file
            if (!FindNextFile(hff, &fData)) break;
        }
        FindClose(hff);
    }

    // read home-ball map
    hash_map<WORD,wstring> entries;
    wstring mapFile(getPesInfo()->gdbDir);
    mapFile += L"GDB\\balls\\map.txt";
    if (readMap(mapFile.c_str(), entries))
    {
        for (hash_map<WORD,wstring>::iterator it = entries.begin();
                it != entries.end();
                it++)
        {
            wstring dir(it->second);
            string_strip(dir);
            string_strip_quotes(dir);

            // find this ball in the normal map
            ball_iter_t sit = _balls.find(dir);
            if (sit != _balls.end())
                _home_balls.insert(pair<WORD,ball_iter_t>(
                            it->first, sit));
            else
                LOG1S(L"ERROR in home-balls map: ball {%s} not found. Skipping.", dir.c_str());
        }
    }

    LOG1N(L"total balls: %d", _balls.size());
    LOG1N(L"home balls assigned: %d", _home_balls.size());

    // reset the iterator
    _ball_iter = _balls.end();
}
void CanvasPattern::setTransform(SVGMatrixTearOff* transform)
{
    pattern()->setPatternSpaceTransform(transform ? transform->value() : AffineTransform(1, 0, 0, 1, 0, 0));
}
Пример #8
0
Component& Component::version(const std::string& version,const std::string& message) {
	std::string new_version;
	std::string tag_message = message;
	std::string current_version = Component::version();

	boost::regex pattern("^(\\d+)\\.(\\d+)\\.(\\d+)$");

	auto regex_uint = [](const boost::smatch& matches,unsigned int index){
		return boost::lexical_cast<unsigned int>(std::string(matches[index].first,matches[index].second));
	};

	// Extract the semantic parts of the current version
	unsigned int current_major = 0;
	unsigned int current_minor = 0;
	unsigned int current_patch = 0;
	boost::smatch matches;
	if(boost::regex_match(current_version,matches,pattern)){
		current_major = regex_uint(matches,1);
		current_minor = regex_uint(matches,2);
		current_patch = regex_uint(matches,3);
	}

	if(version=="patch"){
		// Increment the patch number
		new_version = str(boost::format("%d.%d.%d")%current_major%current_minor%(current_patch+1));
	}
	else if(version=="minor"){
		// Increment the minor version number
		new_version = str(boost::format("%d.%d.0")%current_major%(current_minor+1));
	}
	else if(version=="major"){
		// Increment the minor version number
		new_version = str(boost::format("%d.0.0")%(current_major+1));
	}
	else {
		// Check that the supplied version is greater, or equal to the current
		// version
		unsigned int new_major,new_minor,new_patch;
		boost::smatch matches;
		if(boost::regex_match(version,matches,pattern)){
			new_major = regex_uint(matches,1);
			if(new_major<current_major) throw Exception(str(
				boost::format("Major version supplied is less than current major version (%d): %d")%current_major%new_major
			));
			new_minor = regex_uint(matches,2);
			if(new_major==current_major and new_minor<current_minor) throw Exception(str(
				boost::format("Minor version supplied is less than current minor version (%d): %d")%current_minor%new_minor
			));
			new_patch = regex_uint(matches,3);
			if(new_major==current_major and new_minor==current_minor and new_patch<current_patch) throw Exception(str(
				boost::format("Path version supplied is less than current path version (%d): %d")%current_patch%new_patch
			));
		} else {
			STENCILA_THROW(Exception,"Version supplied is not in correct format (e.g. 1.3.2): "+version);
		}
		new_version = version;
	}

	if(tag_message.length()==0) tag_message = "Versioned changed to " + new_version;
	std::string name = "";
	std::string email = "";
	// Get, or create, repository for the component and tag it.
	Repository* repo = this->repo(true);
	if(repo->head()=="<none>") STENCILA_THROW(Exception,"Component has not been commited. Please do a commit() before a version().");
	repo->tag(new_version,tag_message,name,email);
	return *this;
}
Пример #9
0
void Image::drawPattern(GraphicsContext* ctxt, const FloatRect& tileRect, const AffineTransform& patternTransform,
                        const FloatPoint& phase, ColorSpace styleColorSpace, CompositeOperator op, const FloatRect& destRect)
{
    if (!nativeImageForCurrentFrame())
        return;

    ASSERT(patternTransform.isInvertible());
    if (!patternTransform.isInvertible())
        // Avoid a hang under CGContextDrawTiledImage on release builds.
        return;

    CGContextRef context = ctxt->platformContext();
    ctxt->save();
    CGContextClipToRect(context, destRect);
    ctxt->setCompositeOperation(op);
    CGContextTranslateCTM(context, destRect.x(), destRect.y() + destRect.height());
    CGContextScaleCTM(context, 1, -1);
    
    // Compute the scaled tile size.
    float scaledTileHeight = tileRect.height() * narrowPrecisionToFloat(patternTransform.d());
    
    // We have to adjust the phase to deal with the fact we're in Cartesian space now (with the bottom left corner of destRect being
    // the origin).
    float adjustedX = phase.x() - destRect.x() + tileRect.x() * narrowPrecisionToFloat(patternTransform.a()); // We translated the context so that destRect.x() is the origin, so subtract it out.
    float adjustedY = destRect.height() - (phase.y() - destRect.y() + tileRect.y() * narrowPrecisionToFloat(patternTransform.d()) + scaledTileHeight);

    CGImageRef tileImage = nativeImageForCurrentFrame();
    float h = CGImageGetHeight(tileImage);

    RetainPtr<CGImageRef> subImage;
    if (tileRect.size() == size())
        subImage = tileImage;
    else {
        // Copying a sub-image out of a partially-decoded image stops the decoding of the original image. It should never happen
        // because sub-images are only used for border-image, which only renders when the image is fully decoded.
        ASSERT(h == height());
        subImage.adoptCF(CGImageCreateWithImageInRect(tileImage, tileRect));
    }

    // Adjust the color space.
    subImage = imageWithColorSpace(subImage.get(), styleColorSpace);
    
#ifndef BUILDING_ON_TIGER
    // Leopard has an optimized call for the tiling of image patterns, but we can only use it if the image has been decoded enough that
    // its buffer is the same size as the overall image.  Because a partially decoded CGImageRef with a smaller width or height than the
    // overall image buffer needs to tile with "gaps", we can't use the optimized tiling call in that case.
    // FIXME: Could create WebKitSystemInterface SPI for CGCreatePatternWithImage2 and probably make Tiger tile faster as well.
    // FIXME: We cannot use CGContextDrawTiledImage with scaled tiles on Leopard, because it suffers from rounding errors.  Snow Leopard is ok.
    float scaledTileWidth = tileRect.width() * narrowPrecisionToFloat(patternTransform.a());
    float w = CGImageGetWidth(tileImage);
#ifdef BUILDING_ON_LEOPARD
    if (w == size().width() && h == size().height() && scaledTileWidth == tileRect.width() && scaledTileHeight == tileRect.height())
#else
    if (w == size().width() && h == size().height())
#endif
        CGContextDrawTiledImage(context, FloatRect(adjustedX, adjustedY, scaledTileWidth, scaledTileHeight), subImage.get());
    else {
#endif

    // On Leopard, this code now only runs for partially decoded images whose buffers do not yet match the overall size of the image.
    // On Tiger this code runs all the time.  This code is suboptimal because the pattern does not reference the image directly, and the
    // pattern is destroyed before exiting the function.  This means any decoding the pattern does doesn't end up cached anywhere, so we
    // redecode every time we paint.
    static const CGPatternCallbacks patternCallbacks = { 0, drawPatternCallback, NULL };
    CGAffineTransform matrix = CGAffineTransformMake(narrowPrecisionToCGFloat(patternTransform.a()), 0, 0, narrowPrecisionToCGFloat(patternTransform.d()), adjustedX, adjustedY);
    matrix = CGAffineTransformConcat(matrix, CGContextGetCTM(context));
    // The top of a partially-decoded image is drawn at the bottom of the tile. Map it to the top.
    matrix = CGAffineTransformTranslate(matrix, 0, size().height() - h);
    RetainPtr<CGPatternRef> pattern(AdoptCF, CGPatternCreate(subImage.get(), CGRectMake(0, 0, tileRect.width(), tileRect.height()),
                                             matrix, tileRect.width(), tileRect.height(), 
                                             kCGPatternTilingConstantSpacing, true, &patternCallbacks));
    if (!pattern) {
        ctxt->restore();
        return;
    }

    RetainPtr<CGColorSpaceRef> patternSpace(AdoptCF, CGColorSpaceCreatePattern(0));
    
    CGFloat alpha = 1;
    RetainPtr<CGColorRef> color(AdoptCF, CGColorCreateWithPattern(patternSpace.get(), pattern.get(), &alpha));
    CGContextSetFillColorSpace(context, patternSpace.get());

    // FIXME: Really want a public API for this.  It is just CGContextSetBaseCTM(context, CGAffineTransformIdentiy).
    wkSetPatternBaseCTM(context, CGAffineTransformIdentity);
    CGContextSetPatternPhase(context, CGSizeZero);

    CGContextSetFillColorWithColor(context, color.get());
    CGContextFillRect(context, CGContextGetClipBoundingBox(context));

#ifndef BUILDING_ON_TIGER
    }
#endif

    ctxt->restore();

    if (imageObserver())
        imageObserver()->didDraw(this);
}
Пример #10
0
static void test_parcom(const char *testcode)
{
	int found=0;
	struct parser_s *parser;

	puts("Testing parser combinators");

	if (!testcode) testcode="ALL";

	if (!strcmp(testcode, "keyword") || !strcmp(testcode, "ALL")) {
		found=1;
		puts(" keyword (int)");
		parser=keyword("int");
		test_ulong("int i;\\n", 3, do_parse(parser, "int i;\n", 0));
		test_ulong("int", 3, do_parse(parser, "int", 0));
		test_ulong("integer", 0, do_parse(parser, "integer", 0));
	}
	
	if (!strcmp(testcode, "pattern-1") || !strcmp(testcode, "ALL")) {
		found=1;
		puts(" pattern ([:ident:][:idnum:]*)");
		parser=pattern("[:ident:][:idnum:]*");
		test_ulong("a", 1, do_parse(parser, "a", 0));
		test_ulong("aa", 2, do_parse(parser, "aa", 0));
		test_ulong("1aa", 0, do_parse(parser, "1aa", 0));
		test_ulong("a1aa", 4, do_parse(parser, "a1aa", 0));
	}
	
	if (!strcmp(testcode, "pattern-2") || !strcmp(testcode, "ALL")) {
		found=1;
		puts(" pattern ( *)");
		parser=pattern(" *");
		test_ulong(" ", 1, do_parse(parser, " ", 0));
		test_ulong("  ", 2, do_parse(parser, "  ", 0));
		test_ulong("   ", 3, do_parse(parser, "   ", 0));
		test_ulong(" .  ", 1, do_parse(parser, " .  ", 0));
	}
	
	if (!strcmp(testcode, "sequence") || !strcmp(testcode, "ALL")) {
		found=1;
		puts(" sequence (([:ident:][:idnum:]*), ( *), ([:digit:]))");
		parser=sequence(pattern("[:ident:][:idnum:]*"), 
			pattern(" *"), 
			pattern("[:digit:]"), 
			NULL);
		test_ulong("a 3", 3, do_parse(parser,"a 3", 0));
		test_ulong("a  3", 4, do_parse(parser,"a  3", 0));
		test_ulong("a1  3", 5, do_parse(parser,"a1  3", 0));
	}

	if (!strcmp(testcode, "Choice") || !strcmp(testcode, "ALL")) {
		found=1;
		puts(" choice (([:ident:][:idnum:]*), ([:digit:]*))");
		parser=choice(pattern("[:ident:][:idnum:]*"),
			pattern("[:digit:]*"),
			NULL);
		test_ulong("a1", 2, do_parse(parser, "a1", 0));
		test_ulong("99", 2, do_parse(parser, "99", 0));
		test_ulong("##", 0, do_parse(parser, "##", 0));
	}
	
	if (!found) fprintf(stderr, "Unknown test code %s\n", testcode);

}
Пример #11
0
void ConfusabledataBuilder::build(const char * confusables, int32_t confusablesLen,
               UErrorCode &status) {

    // Convert the user input data from UTF-8 to UChar (UTF-16)
    int32_t inputLen = 0;
    if (U_FAILURE(status)) {
        return;
    }
    u_strFromUTF8(NULL, 0, &inputLen, confusables, confusablesLen, &status);
    if (status != U_BUFFER_OVERFLOW_ERROR) {
        return;
    }
    status = U_ZERO_ERROR;
    fInput = static_cast<UChar *>(uprv_malloc((inputLen+1) * sizeof(UChar)));
    if (fInput == NULL) {
        status = U_MEMORY_ALLOCATION_ERROR;
        return;
    }
    u_strFromUTF8(fInput, inputLen+1, NULL, confusables, confusablesLen, &status);


    // Regular Expression to parse a line from Confusables.txt.  The expression will match
    // any line.  What was matched is determined by examining which capture groups have a match.
    //   Capture Group 1:  the source char
    //   Capture Group 2:  the replacement chars
    //   Capture Group 3-6  the table type, SL, SA, ML, or MA
    //   Capture Group 7:  A blank or comment only line.
    //   Capture Group 8:  A syntactically invalid line.  Anything that didn't match before.
    // Example Line from the confusables.txt source file:
    //   "1D702 ;	006E 0329 ;	SL	# MATHEMATICAL ITALIC SMALL ETA ... "
    UnicodeString pattern(
        "(?m)^[ \\t]*([0-9A-Fa-f]+)[ \\t]+;"      // Match the source char
        "[ \\t]*([0-9A-Fa-f]+"                    // Match the replacement char(s)
           "(?:[ \\t]+[0-9A-Fa-f]+)*)[ \\t]*;"    //     (continued)
        "\\s*(?:(SL)|(SA)|(ML)|(MA))"             // Match the table type
        "[ \\t]*(?:#.*?)?$"                       // Match any trailing #comment
        "|^([ \\t]*(?:#.*?)?)$"       // OR match empty lines or lines with only a #comment
        "|^(.*?)$", -1, US_INV);      // OR match any line, which catches illegal lines.
    // TODO: Why are we using the regex C API here? C++ would just take UnicodeString...
    fParseLine = uregex_open(pattern.getBuffer(), pattern.length(), 0, NULL, &status);

    // Regular expression for parsing a hex number out of a space-separated list of them.
    //   Capture group 1 gets the number, with spaces removed.
    pattern = UNICODE_STRING_SIMPLE("\\s*([0-9A-F]+)");
    fParseHexNum = uregex_open(pattern.getBuffer(), pattern.length(), 0, NULL, &status);

    // Zap any Byte Order Mark at the start of input.  Changing it to a space is benign
    //   given the syntax of the input.
    if (*fInput == 0xfeff) {
        *fInput = 0x20;
    }

    // Parse the input, one line per iteration of this loop.
    uregex_setText(fParseLine, fInput, inputLen, &status);
    while (uregex_findNext(fParseLine, &status)) {
        fLineNum++;
        if (uregex_start(fParseLine, 7, &status) >= 0) {
            // this was a blank or comment line.
            continue;
        }
        if (uregex_start(fParseLine, 8, &status) >= 0) {
            // input file syntax error.
            status = U_PARSE_ERROR;
            return;
        }

        // We have a good input line.  Extract the key character and mapping string, and
        //    put them into the appropriate mapping table.
        UChar32 keyChar = SpoofImpl::ScanHex(fInput, uregex_start(fParseLine, 1, &status),
                          uregex_end(fParseLine, 1, &status), status);

        int32_t mapStringStart = uregex_start(fParseLine, 2, &status);
        int32_t mapStringLength = uregex_end(fParseLine, 2, &status) - mapStringStart;
        uregex_setText(fParseHexNum, &fInput[mapStringStart], mapStringLength, &status);

        UnicodeString  *mapString = new UnicodeString();
        if (mapString == NULL) {
            status = U_MEMORY_ALLOCATION_ERROR;
            return;
        }
        while (uregex_findNext(fParseHexNum, &status)) {
            UChar32 c = SpoofImpl::ScanHex(&fInput[mapStringStart], uregex_start(fParseHexNum, 1, &status),
                                 uregex_end(fParseHexNum, 1, &status), status);
            mapString->append(c);
        }
        U_ASSERT(mapString->length() >= 1);

        // Put the map (value) string into the string pool
        // This a little like a Java intern() - any duplicates will be eliminated.
        SPUString *smapString = stringPool->addString(mapString, status);

        // Add the UChar32 -> string mapping to the appropriate table.
        UHashtable *table = uregex_start(fParseLine, 3, &status) >= 0 ? fSLTable :
                            uregex_start(fParseLine, 4, &status) >= 0 ? fSATable :
                            uregex_start(fParseLine, 5, &status) >= 0 ? fMLTable :
                            uregex_start(fParseLine, 6, &status) >= 0 ? fMATable :
                            NULL;
        if (U_SUCCESS(status) && table == NULL) {
            status = U_PARSE_ERROR;
        }
        if (U_FAILURE(status)) {
            return;
        }

        // For Unicode 8, the SL, SA and ML tables have been discontinued.
        //                All input data from confusables.txt is tagged MA.
        //                ICU spoof check functions should ignore the specified table and always
        //                use this MA Data.
        //                For now, implement by populating the MA data into all four tables, and
        //                keep the multiple table implementation in place, in case it comes back
        //                at some time in the future.
        //                There is no run time size penalty to keeping the four table implementation -
        //                the data is shared when it's the same betweeen tables.
        if (table != fMATable) {
            status = U_PARSE_ERROR;
            return;
        };
        //  uhash_iput(table, keyChar, smapString, &status);
        uhash_iput(fSLTable, keyChar, smapString, &status);
        uhash_iput(fSATable, keyChar, smapString, &status);
        uhash_iput(fMLTable, keyChar, smapString, &status);
        uhash_iput(fMATable, keyChar, smapString, &status);
        fKeySet->add(keyChar);
        if (U_FAILURE(status)) {
            return;
        }
    }

    // Input data is now all parsed and collected.
    // Now create the run-time binary form of the data.
    //
    // This is done in two steps.  First the data is assembled into vectors and strings,
    //   for ease of construction, then the contents of these collections are dumped
    //   into the actual raw-bytes data storage.

    // Build up the string array, and record the index of each string therein
    //  in the (build time only) string pool.
    // Strings of length one are not entered into the strings array.
    // At the same time, build up the string lengths table, which records the
    // position in the string table of the first string of each length >= 4.
    // (Strings in the table are sorted by length)
    stringPool->sort(status);
    fStringTable = new UnicodeString();
    fStringLengthsTable = new UVector(status);
    int32_t previousStringLength = 0;
    int32_t previousStringIndex  = 0;
    int32_t poolSize = stringPool->size();
    int32_t i;
    for (i=0; i<poolSize; i++) {
        SPUString *s = stringPool->getByIndex(i);
        int32_t strLen = s->fStr->length();
        int32_t strIndex = fStringTable->length();
        U_ASSERT(strLen >= previousStringLength);
        if (strLen == 1) {
            // strings of length one do not get an entry in the string table.
            // Keep the single string character itself here, which is the same
            //  convention that is used in the final run-time string table index.
            s->fStrTableIndex = s->fStr->charAt(0);
        } else {
            if ((strLen > previousStringLength) && (previousStringLength >= 4)) {
                fStringLengthsTable->addElement(previousStringIndex, status);
                fStringLengthsTable->addElement(previousStringLength, status);
            }
            s->fStrTableIndex = strIndex;
            fStringTable->append(*(s->fStr));
        }
        previousStringLength = strLen;
        previousStringIndex  = strIndex;
    }
    // Make the final entry to the string lengths table.
    //   (it holds an entry for the _last_ string of each length, so adding the
    //    final one doesn't happen in the main loop because no longer string was encountered.)
    if (previousStringLength >= 4) {
        fStringLengthsTable->addElement(previousStringIndex, status);
        fStringLengthsTable->addElement(previousStringLength, status);
    }

    // Construct the compile-time Key and Value tables
    //
    // For each key code point, check which mapping tables it applies to,
    //   and create the final data for the key & value structures.
    //
    //   The four logical mapping tables are conflated into one combined table.
    //   If multiple logical tables have the same mapping for some key, they
    //     share a single entry in the combined table.
    //   If more than one mapping exists for the same key code point, multiple
    //     entries will be created in the table

    for (int32_t range=0; range<fKeySet->getRangeCount(); range++) {
        // It is an oddity of the UnicodeSet API that simply enumerating the contained
        //   code points requires a nested loop.
        for (UChar32 keyChar=fKeySet->getRangeStart(range);
                keyChar <= fKeySet->getRangeEnd(range); keyChar++) {
            addKeyEntry(keyChar, fSLTable, USPOOF_SL_TABLE_FLAG, status);
            addKeyEntry(keyChar, fSATable, USPOOF_SA_TABLE_FLAG, status);
            addKeyEntry(keyChar, fMLTable, USPOOF_ML_TABLE_FLAG, status);
            addKeyEntry(keyChar, fMATable, USPOOF_MA_TABLE_FLAG, status);
        }
    }

    // Put the assembled data into the flat runtime array
    outputData(status);

    // All of the intermediate allocated data belongs to the ConfusabledataBuilder
    //  object  (this), and is deleted in the destructor.
    return;
}
Пример #12
0
bool
InverseAngstromsUnitFactory::canInterpret(const std::string &unitString) const {
    boost::regex pattern("(Angstrom\\^-1)");
    boost::smatch match; // Unused.
    return boost::regex_search(unitString, match, pattern);
}
Пример #13
0
void IntlDateTimeFormat::initializeDateTimeFormat(ExecState& exec, JSValue locales, JSValue originalOptions)
{
    VM& vm = exec.vm();
    auto scope = DECLARE_THROW_SCOPE(vm);

    // 12.1.1 InitializeDateTimeFormat (dateTimeFormat, locales, options) (ECMA-402 2.0)
    // 1. If dateTimeFormat.[[initializedIntlObject]] is true, throw a TypeError exception.
    // 2. Set dateTimeFormat.[[initializedIntlObject]] to true.

    // 3. Let requestedLocales be CanonicalizeLocaleList(locales).
    Vector<String> requestedLocales = canonicalizeLocaleList(exec, locales);
    // 4. ReturnIfAbrupt(requestedLocales),
    RETURN_IF_EXCEPTION(scope, void());

    // 5. Let options be ToDateTimeOptions(options, "any", "date").
    JSObject* options = toDateTimeOptionsAnyDate(exec, originalOptions);
    // 6. ReturnIfAbrupt(options).
    RETURN_IF_EXCEPTION(scope, void());

    // 7. Let opt be a new Record.
    HashMap<String, String> localeOpt;

    // 8. Let matcher be GetOption(options, "localeMatcher", "string", «"lookup", "best fit"», "best fit").
    String localeMatcher = intlStringOption(exec, options, vm.propertyNames->localeMatcher, { "lookup", "best fit" }, "localeMatcher must be either \"lookup\" or \"best fit\"", "best fit");
    // 9. ReturnIfAbrupt(matcher).
    RETURN_IF_EXCEPTION(scope, void());
    // 10. Set opt.[[localeMatcher]] to matcher.
    localeOpt.add(vm.propertyNames->localeMatcher.string(), localeMatcher);

    // 11. Let localeData be the value of %DateTimeFormat%.[[localeData]].
    // 12. Let r be ResolveLocale( %DateTimeFormat%.[[availableLocales]], requestedLocales, opt, %DateTimeFormat%.[[relevantExtensionKeys]], localeData).
    const HashSet<String> availableLocales = exec.jsCallee()->globalObject()->intlDateTimeFormatAvailableLocales();
    HashMap<String, String> resolved = resolveLocale(exec, availableLocales, requestedLocales, localeOpt, relevantExtensionKeys, WTF_ARRAY_LENGTH(relevantExtensionKeys), localeData);

    // 13. Set dateTimeFormat.[[locale]] to the value of r.[[locale]].
    m_locale = resolved.get(vm.propertyNames->locale.string());
    if (m_locale.isEmpty()) {
        throwTypeError(&exec, scope, ASCIILiteral("failed to initialize DateTimeFormat due to invalid locale"));
        return;
    }
    // 14. Set dateTimeFormat.[[calendar]] to the value of r.[[ca]].
    m_calendar = resolved.get(ASCIILiteral("ca"));
    // Switch to preferred aliases.
    if (m_calendar == "gregory")
        m_calendar = ASCIILiteral("gregorian");
    else if (m_calendar == "islamicc")
        m_calendar = ASCIILiteral("islamic-civil");
    else if (m_calendar == "ethioaa")
        m_calendar = ASCIILiteral("ethiopic-amete-alem");
    // 15. Set dateTimeFormat.[[numberingSystem]] to the value of r.[[nu]].
    m_numberingSystem = resolved.get(ASCIILiteral("nu"));
    // 16. Let dataLocale be the value of r.[[dataLocale]].
    String dataLocale = resolved.get(ASCIILiteral("dataLocale"));

    // 17. Let tz be Get(options, "timeZone").
    JSValue tzValue = options->get(&exec, vm.propertyNames->timeZone);
    // 18. ReturnIfAbrupt(tz).
    RETURN_IF_EXCEPTION(scope, void());

    // 19. If tz is not undefined, then
    String tz;
    if (!tzValue.isUndefined()) {
        // a. Let tz be ToString(tz).
        String originalTz = tzValue.toWTFString(&exec);
        // b. ReturnIfAbrupt(tz).
        RETURN_IF_EXCEPTION(scope, void());
        // c. If the result of IsValidTimeZoneName(tz) is false, then i. Throw a RangeError exception.
        // d. Let tz be CanonicalizeTimeZoneName(tz).
        tz = canonicalizeTimeZoneName(originalTz);
        if (tz.isNull()) {
            throwRangeError(&exec, scope, String::format("invalid time zone: %s", originalTz.utf8().data()));
            return;
        }
    } else {
        // 20. Else,
        // a. Let tz be DefaultTimeZone().
        tz = defaultTimeZone();
    }

    // 21. Set dateTimeFormat.[[timeZone]] to tz.
    m_timeZone = tz;

    // 22. Let opt be a new Record.
    // Rather than building a record, build the skeleton pattern.
    StringBuilder skeletonBuilder;

    // 23. For each row of Table 3, except the header row, do:
    // a. Let prop be the name given in the Property column of the row.
    // b. Let value be GetOption(options, prop, "string", «the strings given in the Values column of the row», undefined).
    // c. ReturnIfAbrupt(value).
    // d. Set opt.[[<prop>]] to value.
    auto narrowShortLong = { "narrow", "short", "long" };
    auto twoDigitNumeric = { "2-digit", "numeric" };
    auto twoDigitNumericNarrowShortLong = { "2-digit", "numeric", "narrow", "short", "long" };
    auto shortLong = { "short", "long" };

    String weekday = intlStringOption(exec, options, vm.propertyNames->weekday, narrowShortLong, "weekday must be \"narrow\", \"short\", or \"long\"", nullptr);
    RETURN_IF_EXCEPTION(scope, void());
    if (!weekday.isNull()) {
        if (weekday == "narrow")
            skeletonBuilder.appendLiteral("EEEEE");
        else if (weekday == "short")
            skeletonBuilder.appendLiteral("EEE");
        else if (weekday == "long")
            skeletonBuilder.appendLiteral("EEEE");
    }

    String era = intlStringOption(exec, options, vm.propertyNames->era, narrowShortLong, "era must be \"narrow\", \"short\", or \"long\"", nullptr);
    RETURN_IF_EXCEPTION(scope, void());
    if (!era.isNull()) {
        if (era == "narrow")
            skeletonBuilder.appendLiteral("GGGGG");
        else if (era == "short")
            skeletonBuilder.appendLiteral("GGG");
        else if (era == "long")
            skeletonBuilder.appendLiteral("GGGG");
    }

    String year = intlStringOption(exec, options, vm.propertyNames->year, twoDigitNumeric, "year must be \"2-digit\" or \"numeric\"", nullptr);
    RETURN_IF_EXCEPTION(scope, void());
    if (!year.isNull()) {
        if (year == "2-digit")
            skeletonBuilder.appendLiteral("yy");
        else if (year == "numeric")
            skeletonBuilder.append('y');
    }

    String month = intlStringOption(exec, options, vm.propertyNames->month, twoDigitNumericNarrowShortLong, "month must be \"2-digit\", \"numeric\", \"narrow\", \"short\", or \"long\"", nullptr);
    RETURN_IF_EXCEPTION(scope, void());
    if (!month.isNull()) {
        if (month == "2-digit")
            skeletonBuilder.appendLiteral("MM");
        else if (month == "numeric")
            skeletonBuilder.append('M');
        else if (month == "narrow")
            skeletonBuilder.appendLiteral("MMMMM");
        else if (month == "short")
            skeletonBuilder.appendLiteral("MMM");
        else if (month == "long")
            skeletonBuilder.appendLiteral("MMMM");
    }

    String day = intlStringOption(exec, options, vm.propertyNames->day, twoDigitNumeric, "day must be \"2-digit\" or \"numeric\"", nullptr);
    RETURN_IF_EXCEPTION(scope, void());
    if (!day.isNull()) {
        if (day == "2-digit")
            skeletonBuilder.appendLiteral("dd");
        else if (day == "numeric")
            skeletonBuilder.append('d');
    }

    String hour = intlStringOption(exec, options, vm.propertyNames->hour, twoDigitNumeric, "hour must be \"2-digit\" or \"numeric\"", nullptr);
    RETURN_IF_EXCEPTION(scope, void());

    // We need hour12 to make the hour skeleton pattern decision, so do this early.
    // 32. Let hr12 be GetOption(options, "hour12", "boolean", undefined, undefined).
    bool isHour12Undefined;
    bool hr12 = intlBooleanOption(exec, options, vm.propertyNames->hour12, isHour12Undefined);
    // 33. ReturnIfAbrupt(hr12).
    RETURN_IF_EXCEPTION(scope, void());

    if (!hour.isNull()) {
        if (isHour12Undefined) {
            if (hour == "2-digit")
                skeletonBuilder.appendLiteral("jj");
            else if (hour == "numeric")
                skeletonBuilder.append('j');
        } else if (hr12) {
            if (hour == "2-digit")
                skeletonBuilder.appendLiteral("hh");
            else if (hour == "numeric")
                skeletonBuilder.append('h');
        } else {
            if (hour == "2-digit")
                skeletonBuilder.appendLiteral("HH");
            else if (hour == "numeric")
                skeletonBuilder.append('H');
        }
    }

    String minute = intlStringOption(exec, options, vm.propertyNames->minute, twoDigitNumeric, "minute must be \"2-digit\" or \"numeric\"", nullptr);
    RETURN_IF_EXCEPTION(scope, void());
    if (!minute.isNull()) {
        if (minute == "2-digit")
            skeletonBuilder.appendLiteral("mm");
        else if (minute == "numeric")
            skeletonBuilder.append('m');
    }

    String second = intlStringOption(exec, options, vm.propertyNames->second, twoDigitNumeric, "second must be \"2-digit\" or \"numeric\"", nullptr);
    RETURN_IF_EXCEPTION(scope, void());
    if (!second.isNull()) {
        if (second == "2-digit")
            skeletonBuilder.appendLiteral("ss");
        else if (second == "numeric")
            skeletonBuilder.append('s');
    }

    String timeZoneName = intlStringOption(exec, options, vm.propertyNames->timeZoneName, shortLong, "timeZoneName must be \"short\" or \"long\"", nullptr);
    RETURN_IF_EXCEPTION(scope, void());
    if (!timeZoneName.isNull()) {
        if (timeZoneName == "short")
            skeletonBuilder.append('z');
        else if (timeZoneName == "long")
            skeletonBuilder.appendLiteral("zzzz");
    }

    // 24. Let dataLocaleData be Get(localeData, dataLocale).
    // 25. Let formats be Get(dataLocaleData, "formats").
    // 26. Let matcher be GetOption(options, "formatMatcher", "string", «"basic", "best fit"», "best fit").
    intlStringOption(exec, options, vm.propertyNames->formatMatcher, { "basic", "best fit" }, "formatMatcher must be either \"basic\" or \"best fit\"", "best fit");
    // 27. ReturnIfAbrupt(matcher).
    RETURN_IF_EXCEPTION(scope, void());

    // Always use ICU date format generator, rather than our own pattern list and matcher.
    // Covers steps 28-36.
    UErrorCode status = U_ZERO_ERROR;
    UDateTimePatternGenerator* generator = udatpg_open(dataLocale.utf8().data(), &status);
    if (U_FAILURE(status)) {
        throwTypeError(&exec, scope, ASCIILiteral("failed to initialize DateTimeFormat"));
        return;
    }

    String skeleton = skeletonBuilder.toString();
    StringView skeletonView(skeleton);
    Vector<UChar, 32> patternBuffer(32);
    status = U_ZERO_ERROR;
    auto patternLength = udatpg_getBestPattern(generator, skeletonView.upconvertedCharacters(), skeletonView.length(), patternBuffer.data(), patternBuffer.size(), &status);
    if (status == U_BUFFER_OVERFLOW_ERROR) {
        status = U_ZERO_ERROR;
        patternBuffer.grow(patternLength);
        udatpg_getBestPattern(generator, skeletonView.upconvertedCharacters(), skeletonView.length(), patternBuffer.data(), patternLength, &status);
    }
    udatpg_close(generator);
    if (U_FAILURE(status)) {
        throwTypeError(&exec, scope, ASCIILiteral("failed to initialize DateTimeFormat"));
        return;
    }

    StringView pattern(patternBuffer.data(), patternLength);
    setFormatsFromPattern(pattern);

    status = U_ZERO_ERROR;
    StringView timeZoneView(m_timeZone);
    m_dateFormat = std::unique_ptr<UDateFormat, UDateFormatDeleter>(udat_open(UDAT_PATTERN, UDAT_PATTERN, m_locale.utf8().data(), timeZoneView.upconvertedCharacters(), timeZoneView.length(), pattern.upconvertedCharacters(), pattern.length(), &status));
    if (U_FAILURE(status)) {
        throwTypeError(&exec, scope, ASCIILiteral("failed to initialize DateTimeFormat"));
        return;
    }

    // 37. Set dateTimeFormat.[[boundFormat]] to undefined.
    // Already undefined.

    // 38. Set dateTimeFormat.[[initializedDateTimeFormat]] to true.
    m_initializedDateTimeFormat = true;

    // 39. Return dateTimeFormat.
}
Пример #14
0
void small_blocks(::std::vector<table_entry*> & links, map<unsigned long long, string> &chains, unsigned int len,
                  map<unsigned long long, unsigned long long>& mapping){
    map<unsigned long long, string>::iterator ch_iter;
    ::std::vector<small_frag> short_blocks;
    stack<unsigned int> s;
    for(unsigned int i=0; i<links.size(); ++i){
        for(unsigned int j=0; j<links.size(); ++j){
            if(i!=j && links[i]->size_D_link() != 0 && links[i]->size_A_link() == 0
               && links[j]->size_D_link() == 0 && links[j]->size_A_link() != 0 ){
                
                string s1,s2;
                ::seqan::assign(s1,links[i]->get_short_read()->get_RNA_seq_sequence());
                ::seqan::assign(s2,links[j]->get_short_read()->get_RNA_seq_sequence());
                
		//Overlap between s1 and s2 grater or equal than s1/2
                unsigned int overlap = overlappedStringLength(s1,s2);
                
                if(overlap > 0 && overlap <= s1.length()/2){
                    assign(s2,::seqan::suffix(s2,overlap));
                    s1.append(s2);
                    //::std::cout << s1 << " " << s1.length() << ::std::endl;
                    small_frag f;
                    f.frag_links.D_chain = i;
                    f.frag_links.A_chain = j;
                    f.frag = ::seqan::infix(s1,len, s1.length() - len);
                    //::std::cout << overlap << " " << f.frag << " " << length(f.frag) << ::std::endl;
                    short_blocks.push_back(f);
                }
            }
        }
    }
    for(unsigned int i=0; i<short_blocks.size(); ++i){
        bool sub_seq = false;
        for(unsigned int k=0; k<short_blocks.size(); ++k){
            if(short_blocks[i].frag == short_blocks[k].frag && i>k){
                links_pair erased_links;
                erased_links.D_chain = short_blocks[i].frag_links.D_chain;
                erased_links.A_chain = short_blocks[i].frag_links.A_chain;
                short_blocks[k].other_links.push_back(erased_links);
                sub_seq = true;
            }
            if(i!=k && (::seqan::length(short_blocks[i].frag)) > (::seqan::length(short_blocks[k].frag))){
                Finder<CharString> finder(short_blocks[i].frag);
                Pattern<CharString, ShiftAnd> pattern(short_blocks[k].frag);
                if(find(finder,pattern)){
                    links_pair erased_links;
                    erased_links.D_chain = short_blocks[i].frag_links.D_chain;
                    erased_links.A_chain = short_blocks[i].frag_links.A_chain;
                    //::std::cout << i << k << " - " << beginPosition(finder) << " " << endPosition(finder) << ::std::endl;
                    short_blocks[k].other_links.push_back(erased_links);
                    sub_seq = true;
                }
            }
        }
        if(sub_seq){
            s.push(i);
        }
    }
    
    while(!s.empty()){
        short_blocks.erase(short_blocks.begin()+s.top());
        s.pop();
    }

    for(unsigned int i=0; i<short_blocks.size(); ++i){
        //::std::cout << short_blocks[i].frag << " " << length(short_blocks[i].frag) << ::std::endl;
        string ch;
        assign(ch,::seqan::prefix(short_blocks[i].frag,len));
        //::std::cout << ch << " " << ch.length() << ::std::endl;
        if(chains.find(fingerprint(ch)) == chains.end()){
            chains[fingerprint(ch)] = ::seqan::toCString(short_blocks[i].frag);
            //::std::cout << ::seqan::toCString(short_blocks[i].frag) << " " << length(short_blocks[i].frag) << ::std::endl;
            mapping[fingerprint(ch)] = fingerprint(ch);
            links[short_blocks[i].frag_links.D_chain]->push_A_link(fingerprint(ch));
            links[short_blocks[i].frag_links.A_chain]->push_D_link(fingerprint(ch));
        }
        for(unsigned int j=0; j<short_blocks[i].other_links.size(); ++j){
            links[short_blocks[i].other_links[j].D_chain]->push_A_link(fingerprint(ch));
            links[short_blocks[i].other_links[j].A_chain]->push_D_link(fingerprint(ch));
        }
    }
}
Пример #15
0
void check_overlapping_nodes(::std::vector<table_entry*> & links, map<unsigned long long, string> & chains, int len,
                             ::std::map<unsigned long long, unsigned long long>& mapping, unsigned int min_overlap,
                             int ov_perc){
    ::std::map<unsigned long long, string>::iterator chain_it;
    ::std::map<unsigned long long, string>::iterator chain_it_2;
    ::std::vector<small_frag> short_blocks;
    stack<unsigned int> s;
    queue<unsigned long long> q;
    for(chain_it = chains.begin(); chain_it != chains.end(); ++chain_it){
        for(chain_it_2 = chains.begin(); chain_it_2 != chains.end(); ++chain_it_2){
            unsigned int ov = overlappedStringLength(chain_it->second,chain_it_2->second);
            if(chain_it != chain_it_2 && ov < (ov_perc*chain_it->second.length())/100 &&
               (ov_perc*ov < chain_it_2->second.length())/100 && ov > min_overlap){
                bool new_node = false;
                CharString pat_text=prefix(chain_it_2->second,ov);
                //::std::cout << chain_it->second << ::std::endl;
                //::std::cout << chain_it_2->second << ::std::endl;
                //::std::cout << ov << ::std::endl;
                Pattern<CharString, ShiftAnd> pattern(pat_text);
                for(unsigned int i=0; i<links.size();++i){
                    CharString link_read = links[i]->get_short_read()->get_RNA_seq_sequence();
                    Finder<CharString> finder(link_read);
                    if(find(finder,pattern) && (
                       prefix(link_read,beginPosition(finder)) == infix(chain_it->second,chain_it->second.length()-ov-beginPosition(finder),chain_it->second.length()-ov) ||
                       suffix(link_read,length(link_read) - endPosition(finder)) == infix(chain_it_2->second,ov,ov+endPosition(finder)))){
                        //::std::cout << link_read << ::std::endl;
                        //::std::cout << prefix(link_read,beginPosition(finder)) << ::std::endl;
                        //::std::cout << infix(chain_it->second,chain_it->second.length()-ov-beginPosition(finder),chain_it->second.length()-ov) << ::std::endl;
                        //::std::cout << suffix(link_read,length(link_read) - endPosition(finder)) << ::std::endl;
                        //::std::cout << infix(chain_it_2->second,ov,ov+endPosition(finder)) << ::std::endl;
                      
                        new_node = true;
                    }
                }
                if(new_node){
                    small_frag f;
                    f.frag_links.D_chain = chain_it->first;
                    f.frag_links.A_chain = chain_it_2->first;
                    f.frag = prefix(chain_it_2->second,ov);
                    short_blocks.push_back(f);
                }
            }else{
                if(chain_it != chain_it_2 && ov>=(ov_perc*chain_it->second.length())/100){
                    //::std::cout << "Chain_it sub-node of Chain_it_2" << ::std::endl;
                    //::std::cout << "Chain_it " << chain_it->second << ::std::endl;
                    //::std::cout << "Chain_it_2 " << chain_it_2->second << ::std::endl;
                    //::std::cout << ov << ::std::endl;
                    q.push(chain_it->first);
                }else{
                    if(chain_it != chain_it_2 && ov>=(ov_perc*chain_it_2->second.length())/100){
                        //::std::cout << "Chain_it_2 sub-node of Chain_it" << ::std::endl;
                        //::std::cout << "Chain_it " << chain_it->second << ::std::endl;
                        //::std::cout << "Chain_it_2 " <<chain_it_2->second << ::std::endl;
                        //::std::cout << ov << ::std::endl;
                        q.push(chain_it_2->first);
                    }
                }
            }
        }
    }

    for(unsigned int i=0; i<short_blocks.size(); ++i){
        bool sub_seq = false;
        for(unsigned int k=0; k<short_blocks.size(); ++k){
            if(short_blocks[i].frag == short_blocks[k].frag && i<k){
                links_pair erased_links;
                erased_links.D_chain = short_blocks[i].frag_links.D_chain;
                erased_links.A_chain = short_blocks[i].frag_links.A_chain;
                short_blocks[k].other_links.push_back(erased_links);
                sub_seq = true;
            }
            if(i!=k && (::seqan::length(short_blocks[i].frag)) < (::seqan::length(short_blocks[k].frag))){
                Finder<CharString> finder(short_blocks[k].frag);
                Pattern<CharString, ShiftAnd> pattern(short_blocks[i].frag);
                if(find(finder,pattern)){
                    links_pair erased_links;
                    erased_links.D_chain = short_blocks[i].frag_links.D_chain;
                    erased_links.A_chain = short_blocks[i].frag_links.A_chain;
                    //::std::cout << i << k << " - " << beginPosition(finder) << " " << endPosition(finder) << ::std::endl;
                    short_blocks[k].other_links.push_back(erased_links);
                    sub_seq = true;
                }
            }
        }
        if(sub_seq){
            s.push(i);
        }
    }

    while(!s.empty()){
        short_blocks.erase(short_blocks.begin()+s.top());
        s.pop();
    }
    while(!q.empty()){
        chains.erase(q.front());
        q.pop();
    }

    for(unsigned int i=0; i<short_blocks.size(); ++i){
        //::std::cout << short_blocks[i].frag << " " << length(short_blocks[i].frag) << ::std::endl; 
        string ch = "";
        for(unsigned int z = 0; z<len-length(short_blocks[i].frag); ++z){
            ch.append("A");
        }
        ch.append(toCString(short_blocks[i].frag));
        //if(chains.find(fingerprint(ch)) == chains.end()){//Start_If_5
            //chains[fingerprint(ch)] = ::seqan::toCString(short_blocks[i].frag);
            //::std::cout << ::seqan::toCString(short_blocks[i].frag) <<" "<< length(short_blocks[i].frag)<<::std::endl;
            //mapping[fingerprint(ch)] = fingerprint(ch);
            //Add the first link
            string first_half;
            assign(first_half,prefix(chains[short_blocks[i].frag_links.D_chain],len));
            string new_link_1 = first_half;
            new_link_1.append(ch);
            table_entry* link_1 = new table_entry(new_link_1,fingerprint(first_half),fingerprint(ch));
            link_1->push_D_link(short_blocks[i].frag_links.D_chain);
            link_1->push_A_link(short_blocks[i].frag_links.A_chain);
            links.push_back(link_1);
            /*
            //Add the second link
            string second_half;
            assign(second_half,prefix(chains[short_blocks[i].frag_links.A_chain],len));
            string new_link_2 = ch;
            new_link_2.append(second_half);
            table_entry* link_2 = new table_entry(new_link_2,fingerprint(ch),fingerprint(second_half));
            link_2->push_D_link(short_blocks[i].frag_links.D_chain);
            link_2->push_A_link(short_blocks[i].frag_links.A_chain);
            links.push_back(link_2);
            */
            //::std::cout<<links[short_blocks[i].frag_links.D_chain]->get_short_read()->get_RNA_seq_sequence()<<::std::endl;
            //::std::cout<<links[short_blocks[i].frag_links.A_chain]->get_short_read()->get_RNA_seq_sequence()<<::std::endl;

            for(unsigned int j=0; j<short_blocks[i].other_links.size(); ++j){//Start_For_6
                string second_half;
                assign(first_half,prefix(chains[short_blocks[i].other_links[j].D_chain],len));
                string new_link_2 = second_half;
                new_link_2.append(ch);
                table_entry* link_2 = new table_entry(new_link_2,fingerprint(second_half),fingerprint(ch));
                link_2->push_D_link(short_blocks[i].other_links[j].D_chain);
                link_2->push_A_link(short_blocks[i].other_links[j].A_chain);
                links.push_back(link_1);
            }//End_For_6
            //}//End_If_5
    }
}
Пример #16
0
bool
network_interface_to_ip(char const *interface_param_name,char const *interface_pattern,std::string &ip,std::set< std::string > *network_interface_ips)
{
	ASSERT( interface_pattern );
	if( !interface_param_name ) {
		interface_param_name = "";
	}

	if( network_interface_ips ) {
		network_interface_ips->clear();
	}

	condor_sockaddr addr;
	if (addr.from_ip_string(interface_pattern)) {
		ip = interface_pattern;
		if( network_interface_ips ) {
			network_interface_ips->insert( ip );
		}

		dprintf(D_HOSTNAME,"%s=%s, so choosing IP %s\n",
				interface_param_name,
				interface_pattern,
				ip.c_str());

		return true;
	}

	StringList pattern(interface_pattern);

	std::string matches_str;
	std::vector<NetworkDeviceInfo> dev_list;
	std::vector<NetworkDeviceInfo>::iterator dev;

	sysapi_get_network_device_info(dev_list);

		// Order of preference:
		//   * non-private IP
		//   * private IP (e.g. 192.168.*)
		//   * loopback
		// In case of a tie, choose the first device in the list.

	int best_so_far = -1;

	for(dev = dev_list.begin();
		dev != dev_list.end();
		dev++)
	{
		bool matches = false;
		if( strcmp(dev->name(),"")!=0 &&
			pattern.contains_anycase_withwildcard(dev->name()) )
		{
			matches = true;
		}
		else if( strcmp(dev->IP(),"")!=0 &&
				 pattern.contains_anycase_withwildcard(dev->IP()) )
		{
			matches = true;
		}

		if( !matches ) {
			dprintf(D_HOSTNAME,"Ignoring network interface %s (%s) because it does not match %s=%s.\n",
					dev->name(), dev->IP(), interface_param_name, interface_pattern);
			continue;
		}

		condor_sockaddr this_addr;
		if (!this_addr.from_ip_string(dev->IP())) {
		//if( !is_ipaddr_no_wildcard(dev->IP(),&this_sin_addr) ) {
			dprintf(D_HOSTNAME,"Ignoring network interface %s (%s) because it does not have a useable IP address.\n",
					dev->name(), dev->IP());
			continue;
		}

		if( matches_str.size() ) {
			matches_str += ", ";
		}
		matches_str += dev->name();
		matches_str += " ";
		matches_str += dev->IP();

		if( network_interface_ips ) {
			network_interface_ips->insert( dev->IP() );
		}

		int desireability;

		if (this_addr.is_loopback()) {
			desireability = 1;
		}
		else if (this_addr.is_private_network()) {
			desireability = 2;
		}
		else {
			desireability = 3;
		}

		if(dev->is_up()) { desireability *= 10; }

		//dprintf(D_HOSTNAME, "Considering %s (Ranked at %d) as possible local hostname versus %s (%d)\n", addr.to_ip_string().Value(), desireability, ip.c_str(), desireability);

		if( desireability > best_so_far ) {
			best_so_far = desireability;
			ip = dev->IP();
		}
	}

	if( best_so_far < 0 ) {
		dprintf(D_ALWAYS,"Failed to convert %s=%s to an IP address.\n",
				interface_param_name ? interface_param_name : "",
				interface_pattern);
		return false;
	}

	dprintf(D_HOSTNAME,"%s=%s matches %s, choosing IP %s\n",
			interface_param_name,
			interface_pattern,
			matches_str.c_str(),
			ip.c_str());

	return true;
}
Пример #17
0
/*** Trigger a quote download ***/
bool mmStocksPanel::onlineQuoteRefresh(wxString& sError)
{
    if(listCtrlAccount_->m_stocks.size() < 1)
    {
        sError = _("Nothing to update");
        return false;
    }

    //Symbol, (Amount, Name)
    std::map<wxString, std::pair<double, wxString> > stocks_data;
    wxString site = "";

    for (const auto &stock : listCtrlAccount_->m_stocks)
    {
        const wxString symbol = stock.SYMBOL.Upper();
        if (!symbol.IsEmpty())
        {
            if (stocks_data.find(symbol) == stocks_data.end())
            {
                stocks_data[symbol] = std::make_pair(stock.CURRENTPRICE, "");
                site << symbol << "+";
            }
        }
    }
    if (site.Right(1).Contains("+")) site.RemoveLast(1);

    //Sample: http://finance.yahoo.com/d/quotes.csv?s=SBER.ME+GAZP.ME&f=sl1c4n&e=.csv
    //Sample CSV: "SBER.ME",85.49,"RUB","SBERBANK"
    site = wxString::Format(mmex::weblink::YahooQuotes, site);

    refresh_button_->SetBitmapLabel(wxBitmap(wxImage(led_yellow_xpm).Scale(16,16)));
    stock_details_->SetLabelText(_("Connecting..."));
    wxString sOutput;

    int err_code = site_content(site, sOutput);
    if (err_code != wxURL_NOERR)
    {
        sError = sOutput;
        return false;
    }

    //--//
    wxString StockSymbolWithSuffix, sName, StockQuoteCurrency;
    double dPrice = 0.0;

    wxStringTokenizer tkz(sOutput, "\r\n");
    while (tkz.HasMoreTokens())
    {
        const wxString csvline = tkz.GetNextToken();
        StockSymbolWithSuffix = "";
        StockQuoteCurrency = "";
        wxRegEx pattern("\"([^\"]+)\",([^,][0-9.]+),\"([^\"]*)\",\"([^\"]*)\"");
        if (pattern.Matches(csvline))
        {
            StockSymbolWithSuffix = pattern.GetMatch(csvline, 1);
            pattern.GetMatch(csvline, 2).ToDouble(&dPrice);
            StockQuoteCurrency = pattern.GetMatch(csvline, 3);
            sName = pattern.GetMatch(csvline, 4);
        }

        bool updated = !StockSymbolWithSuffix.IsEmpty();

        /* HACK FOR GBP
        http://sourceforge.net/p/moneymanagerex/bugs/414/
        http://sourceforge.net/p/moneymanagerex/bugs/360/
        1. If the share has GBp as currency, its downloaded value in pence
        2. If the share has another currency, we don't need to modify the price
        */

        if (updated && dPrice > 0)
        {
            if (StockQuoteCurrency == "GBp")
                dPrice = dPrice / 100;
            stocks_data[StockSymbolWithSuffix].first = dPrice;
            stocks_data[StockSymbolWithSuffix].second = sName;
            sError << wxString::Format(_("%s\t -> %s\n")
                , StockSymbolWithSuffix, wxString::Format("%0.4f", dPrice));
        }
    }

    for (auto &s: listCtrlAccount_->m_stocks)
    {
        std::map<wxString, std::pair<double, wxString> >::const_iterator it = stocks_data.find(s.SYMBOL.Upper());
        if (it == stocks_data.end()) continue;
        dPrice = it->second.first;

        s.CURRENTPRICE = dPrice;
        s.VALUE = dPrice * s.NUMSHARES;
        if (s.STOCKNAME.empty()) s.STOCKNAME = it->second.second;
        Model_Stock::instance().save(&s);
    }

    // Now refresh the display
    int selected_id = -1;
    if (listCtrlAccount_->get_selectedIndex() > -1)
        selected_id = listCtrlAccount_->m_stocks[listCtrlAccount_->get_selectedIndex()].STOCKID;
    listCtrlAccount_->doRefreshItems(selected_id);

    // We are done!
    LastRefreshDT_       = wxDateTime::Now();
    StocksRefreshStatus_ = true;
    refresh_button_->SetBitmapLabel(wxBitmap(wxImage(led_green_xpm).Scale(16,16)));

    strLastUpdate_.Printf(_("%s on %s"), LastRefreshDT_.FormatTime()
        , LastRefreshDT_.FormatDate());
    Model_Infotable::instance().Set("STOCKS_LAST_REFRESH_DATETIME", strLastUpdate_);

    return true;
}
Пример #18
0
/**
 * Get some summary statistics on the specified field in a human-readable
 * format.  The exact content of the summary depends on the data type of the
 * field.  The summary is with respect to the current filter, not the entire
 * database (unless an all-inclusive filter is selected, of course).
 *
 * @param colIndex The position index of the field to get statistics for
 * @return A list of individual "Name: value" statistics formatted as rows
 *         of an HTML table
 */
QStringList View::getStatistics(int colIndex)
{
    QStringList lines;
    if (rowCnt == 0) {
        lines.append(QString("<tr><td>%1</td></tr>")
                     .arg(tr("No data to summarize")));
        return lines;
    }
    int type = dataTypes[colIndex];
    QLocale locale = QLocale::system();
    QString pattern("<tr><td align=\"right\"><font color=\"#0000ff\">%1</font>: </td><td>%2</td></tr>");
    if (type == INTEGER || type == SEQUENCE) {
        c4_IntProp prop(ids[colIndex]);
        int value = prop (dbview[0]);
        int total = value;
        int min = value;
        int max = value;
        for (int i = 1; i < rowCnt; i++) {
            int value = prop (dbview[i]);
            total += value;
            min = qMin(min, value);
            max = qMax(max, value);
        }
        float mean = total / (float)rowCnt;
        lines.append(pattern.arg(tr("Total")).arg(locale.toString(total)));
        lines.append(pattern.arg(tr("Average")).arg(locale.toString(mean)));
        lines.append(pattern.arg(tr("Minimum")).arg(locale.toString(min)));
        lines.append(pattern.arg(tr("Maximum")).arg(locale.toString(max)));
    }
    else if (type == FLOAT || type == CALC) {
        c4_FloatProp prop(ids[colIndex]);
        c4_StringProp stringProp(scIds[colIndex]);
        double value = prop (dbview[0]);
        double total = value;
        double min = value;
        double max = value;
        QString minString = QString::fromUtf8(stringProp (dbview[0]));
        QString maxString = minString;
        for (int i = 1; i < rowCnt; i++) {
            double value = prop (dbview[i]);
            total += value;
            if (value < min) {
                min = value;
                minString = QString::fromUtf8(stringProp (dbview[i]));
            }
            if (value > max) {
                max = value;
                maxString = QString::fromUtf8(stringProp (dbview[i]));
            }
        }
        double mean = total / rowCnt;
        lines.append(pattern.arg(tr("Total"))
                            .arg(locale.toString(total, 'f', 2)));
        lines.append(pattern.arg(tr("Average"))
                            .arg(locale.toString(mean, 'f', 2)));
        lines.append(pattern.arg(tr("Minimum"))
                            .arg(Formatting::toLocalDouble(minString)));
        lines.append(pattern.arg(tr("Maximum"))
                            .arg(Formatting::toLocalDouble(maxString)));
    }
    else if (type == BOOLEAN) {
        c4_IntProp prop(ids[colIndex]);
        int checked = 0;
        for (int i = 0; i < rowCnt; i++) {
            int value = prop (dbview[i]);
            if (value == 1) {
                checked++;
            }
        }
        lines.append(pattern.arg(tr("Checked"))
                            .arg(locale.toString(checked)));
        lines.append(pattern.arg(tr("Unchecked"))
                            .arg(locale.toString(rowCnt - checked)));
    }
    else if (type == DATE) {
        c4_IntProp prop(ids[colIndex]);
        int value = prop (dbview[0]);
        int min = value;
        int max = value;
        for (int i = 1; i < rowCnt; i++) {
            int value = prop (dbview[i]);
            if (value != 17520914) {
                min = (min == 17520914) ? value : qMin(min, value);
                max = qMax(max, value);
            }
        }
        lines.append(pattern.arg(tr("Earliest"))
                            .arg(Formatting::dateToString(min)));
        lines.append(pattern.arg(tr("Latest"))
                            .arg(Formatting::dateToString(max)));
    }
    else if (type == TIME) {
        c4_IntProp prop(ids[colIndex]);
        int value = prop (dbview[0]);
        int min = value;
        int max = value;
        for (int i = 1; i < rowCnt; i++) {
            int value = prop (dbview[i]);
            if (value != -1) {
                min = (min == -1) ? value : qMin(min, value);
                max = qMax(max, value);
            }
        }
        lines.append(pattern.arg(tr("Earliest"))
                            .arg(Formatting::timeToString(min)));
        lines.append(pattern.arg(tr("Latest"))
                            .arg(Formatting::timeToString(max)));
    }
    else if (type == STRING || type == NOTE) {
        c4_StringProp prop(ids[colIndex]);
        QString value = QString::fromUtf8(prop (dbview[0]));
        int length = value.length();
        int total = length;
        int min = length;
        int max = length;
        for (int i = 1; i < rowCnt; i++) {
            QString svalue = QString::fromUtf8(prop (dbview[i]));
            length = svalue.length();
            total += length;
            min = qMin(min, length);
            max = qMax(max, length);
        }
        int mean = total / rowCnt;
        lines.append(pattern.arg(tr("Total length"))
                            .arg(tr("%Ln character(s)", "", total)));
        lines.append(pattern.arg(tr("Average length"))
                            .arg(tr("%Ln character(s)", "", mean)));
        lines.append(pattern.arg(tr("Minimum length"))
                            .arg(tr("%Ln character(s)", "", min)));
        lines.append(pattern.arg(tr("Maximum length"))
                            .arg(tr("%Ln character(s)", "", max)));
    }
    else if (type == IMAGE) {
        c4_StringProp stringProp(scIds[colIndex]);
        int missing = 0;
        for (int i = 0; i < rowCnt; i++) {
            QString value(stringProp (dbview[i]));
            if (value.isEmpty()) {
                missing++;
            }
        }
        lines.append(pattern.arg(tr("Image available"))
                            .arg(locale.toString(rowCnt - missing)));
        lines.append(pattern.arg(tr("No image"))
                            .arg(locale.toString(missing)));
    }
    else if (type >= FIRST_ENUM) {
        c4_StringProp prop(ids[colIndex]);
        QStringList options = db->listEnumOptions(type);
        int optionCount = options.count();
        int *tallies = new int[optionCount];
        int i;
        for (i = 0; i < optionCount; i++) {
            tallies[i] = 0;
        }
        for (i = 0; i < rowCnt; i++) {
            int index = options.indexOf(QString::fromUtf8(prop (dbview[i])));
            tallies[index] = tallies[index] + 1;
        }
        for (i = 0; i < optionCount; i++) {
            lines.append(pattern.arg(options[i])
                                .arg(locale.toString(tallies[i])));
        }
        delete[] tallies;
    }
    return lines;
}
Пример #19
0
QVariant Cell::parseMember(const QString &formula, SpreadSheet *widget) const
{
    int fOp = firstOperatorPosition(formula);
    if (fOp == -1)
        fOp = formula.length();
    QChar first = formula.at(0);
    
    QRegExp importedData("([\\w\\s]+:[A-Z][1-9][0-9]*)");
    QRegExp cellId("([A-Z][1-9][0-9]*)");
    
    //paranteza
    if (first=='(')
    {
        int end = 0;
        int open_p_count = 0;
        int closed_p_count = 0;
        for (int c=0; c<formula.length(); c++)
        {
            if (formula.at(c) == '(')
                open_p_count++;
            else if (formula.at(c) == ')')
                closed_p_count++;
            if (open_p_count == closed_p_count)
            {
                end = c;
                break;
            }
        }
        return computeFormula(formula.mid(1,end-1), widget);
    }
    //numar 0 sau 0.0
    else if (first.isDigit())
    {
        QString s = formula.left(fOp);
        if (s.count('.') <= 1)
        {
            bool ok;
            double x = s.toDouble(&ok);
            if (ok)
                return x;
        }
        emit invalidFormula(QString("Invalid number or number format in %1").arg(s));
        return "#####";
    }
    //tabela:identificator
    else if (formula.indexOf(importedData) == 0)
    {
        int idx = 0;
        QHash<QString,QString> matches = QHash<QString,QString>();
        while ((idx = formula.indexOf(importedData, idx)) != -1)
        {
            QString match = formula.mid(idx, importedData.matchedLength());
            int delim = match.indexOf(':');
            QString table = match.left(delim);
            QString id = match.mid(delim+1);
            matches.insertMulti(table, id);
            idx += importedData.matchedLength();
        }
        QString result = widget->getLinkData(formula, matches);
        if (isValidFormula(result))
            return display(result);
        else
            return result;
    }
    //celula A2
    else if (cellId.exactMatch(formula))
    {
        QVariant cellVal = getCellValue(formula,widget);
        if (cellVal == "#####")
            emit invalidFormula(QString("Invalid cell data in %1").arg(formula));
        return cellVal;
    }
    //functie nume_functie(A1;A2;A3)
    else if (first.isLower())
    {
        QStringList simple_function_names;
        QStringList cond_function_names;
        QStringList parameters;
        simple_function_names << "sum" << "avg" << "count";
        cond_function_names << "if" << "countif";
        QString s = formula.left(fOp);

        QString params = s.mid(s.lastIndexOf('(')+1,
                               s.indexOf(')')-s.lastIndexOf('(')-1);
        if (s.count('(') == s.count(')'))
            parameters = params.split(';');
        else
        {
            emit invalidFormula(QString("Invalid paranthesis number ").append(s));
            return "#####";
        }
        s = formula.left(formula.indexOf('('));
        if (simple_function_names.contains(s))
        {
            QVariantList values;
            QListIterator<QString> it(parameters);
            while (it.hasNext())
            {
                QString str = it.next();
                QVariant val = parseMember(str, widget);
                if (val != "#####")
                    values.append(val);
            }

            if (s == "sum")
            {
                double tmp = 0;
                bool ok = true;
                QListIterator<QVariant> valIt(values);
                while (valIt.hasNext())
                {
                    QVariant aux = valIt.next();
                    tmp += aux.toDouble(&ok);
                    if (!ok)
                    {
                        emit invalidFormula(QString("Not a number: ").append(aux.toString()));
                        return "#####";
                    }
                }
                return tmp;
            }
            else if (s == "avg")
            {
                double tmp = 0;
                bool ok = true;
                QListIterator<QVariant> valIt(values);
                while (valIt.hasNext())
                {
                    QVariant aux = valIt.next();
                    tmp += aux.toDouble(&ok);
                    if (!ok)
                    {
                        emit invalidFormula(QString("Not a number: ").append(aux.toString()));
                        return "#####";
                    }
                }
                tmp /= parameters.length();
                return tmp;
            }
            else if (s == "count")
            {
                return values.length();
            }
        }
        else if (cond_function_names.contains(s))
        {
            int param_no = parameters.length();
            if (param_no < 2)
            {
                emit invalidFormula(QString("Invalid parameter number: %1").arg(param_no));
                return "#####";
            }
            
            if (s == "if")
            {
                //if(A1<5;"Picat";n)
                //if(A1<5;4)
                QRegExp pattern("^(([\\w\\s]+:)?[A-Z][1-9][0-9]*"
                                "(<|<=|>|>=|<>|=)"
                                "((([\\w\\s]+:)?[A-Z][1-9][0-9]*)|(\\d+(\\.\\d+)?)))$");
                QString condition = parameters.at(0);
                if (pattern.exactMatch(condition) && param_no <= 3)
                {
                    int length = 1;
                    int opPos = condition.indexOf(QRegExp("(<|>|=)"));
                    if (condition.indexOf(QRegExp("(<=|>=|<>)")) > -1)
                        length = 2;
                    QString op = condition.mid(opPos,length);
                    bool ok1, ok2;
                    double firstOperand = parseMember(condition.left(opPos), widget).toDouble(&ok1);
                    double secondOperand = parseMember(condition.mid(opPos+length), widget).toDouble(&ok2);
                    if (!ok1 || !ok2)
                    {
                        emit invalidFormula(QString("Invalid condition parameters: %1").arg(condition));
                        return "#####";
                    }
                    if (param_no == 2)
                        return compareMembers(param_no, op,
                                              firstOperand, secondOperand,
                                              parameters.at(1), "#####");
                    else if (param_no == 3)
                        return compareMembers(param_no, op,
                                              firstOperand, secondOperand,
                                              parameters.at(1), parameters.at(2));
                }
                else
                {
                    emit invalidFormula(QString("Invalid formula syntax: ").append(condition));
                    return "#####";
                }
            }
            else if (s == "countif")
            {
                //countif(A1;A2...An;>5)
                if (param_no > 2)
                {
                    int count = 0;
                    int length = 1;
                    QString condition = parameters.last();
                    int opPos = condition.indexOf(QRegExp("(<|>|=)"));
                    if (condition.indexOf(QRegExp("(<=|>=|<>)")) > -1)
                        length = 2;
                    if (opPos == -1)
                    {
                        emit invalidFormula(QString("Invalid condition syntax: ").append(condition));
                        return "#####";
                    } 
                    QString op = condition.mid(opPos,length);
                    bool ok;
                    double firstOperand;
                    double secondOperand = parseMember(condition.mid(opPos+length), widget).toDouble(&ok);
                    if (!ok)
                    {
                        emit invalidFormula(QString("Invalid second operand: %1").
                                            arg(condition.mid(opPos+length)));
                        return "#####";
                    }
                    for (int i=0; i<param_no-1; i++)
                    {
                        firstOperand = parseMember(parameters.at(i), widget).toDouble(&ok);
                        if (!ok)
                        {
                            emit invalidFormula(QString("Invalid operand: %1").
                                                arg(parameters.at(i)));
                            return "#####";
                        }
                        if (compareMembers(op, firstOperand, secondOperand))
                            count++;
                    }
                    return count;
                }
            }
        }
        else
        {
            emit invalidFormula("Invalid formula");
            return "#####";
        }
    }
    return formula;
}
Пример #20
0
int
ACE_TMAIN(int argc, ACE_TCHAR *argv[])
{
  ACE_SOCK_Stream connection_stream;
  int c;

  printf("HZ = %d\n", HZ);
  if (argc < 2)
    goto usage;

  while ((c = getopt (argc, argv, "drstU:uvBDTb:f:l:n:p:A:O:L:xh:")) != -1)
    {
      switch (c)
        {
        case 'h':
          host = optarg;
          break;
        case 'x':
          new_line = 1;
          break;
        case 'L':
          title = optarg;
          break;
        case 'B':
          b_flag = 1;
          break;
        case 't':
          trans = 1;
          break;
        case 'r':
          trans = 0;
          break;
        case 'd':
          options |= SO_DEBUG;
          break;
        case 'D':
        #ifdef TCP_NODELAY
          nodelay = 1;
        #else
          fprintf (stderr,
                   "ttcp: -D option ignored: TCP_NODELAY socket option not supported\n");
        #endif
          break;
        case 'n':
          nbuf = atoi (optarg);
          break;
        case 'l':
          data_buf_len = atoi (optarg);
          break;
        case 's':
          sinkmode = !sinkmode;
          break;
        case 'p':
          port = atoi (optarg);
          break;
        case 'U':
          domain = PF_UNIX;
          domainname = optarg;
          break;
        case 'u':
          udp = 1;
          break;
        case 'v':
          verbose = 1;
          break;
        case 'A':
          bufalign = atoi (optarg);
          break;
        case 'O':
          bufoffset = atoi (optarg);
          break;
        case 'b':
        #if defined(SO_SNDBUF) || defined(SO_RCVBUF)
          sockbufsize = atoi (optarg);
        #else
          fprintf (stderr,
                   "ttcp: -b option ignored: SO_SNDBUF/SO_RCVBUF socket options not supported\n");
        #endif
          break;
        case 'f':
          fmt = *optarg;
          break;
        case 'T':
          touchdata = 1;
          break;

        default:
          goto usage;
      }
    }

  /* if transmitter, create remote address to transmit to.  */

  if (trans)
    {
      if (address.set (port, host) == -1)
        perror ("address.set"), exit (1);
    }

  /* else, receiver create address to listen on */
  else
    {
      address.set (port);
    }

  total_msg_len = sizeof (long) + data_buf_len;

  // allocate the buffer
  message_buf = (Data_Control_Message *) malloc (total_msg_len);
  if (message_buf == 0)
    err ("malloc");

//  if (bufalign != 0)
//    message_buf += (bufalign - ((int) message_buf % bufalign) + bufoffset) % bufalign;

  // let's go ahead and set the control message for every send right now
  message_buf->size_ = data_buf_len;

  session_control_buf.nbuf_ = nbuf;
  session_control_buf.size_ = data_buf_len;

  //
  // print out option values for trans and receiver
  //

  if (trans)
    {
      fprintf (stdout,
               "ttcp-t: data_buf_len=%d, nbuf=%d, align=%d/%d, port=%d",
               data_buf_len, nbuf, bufalign, bufoffset, port);
      if (sockbufsize)
        fprintf (stdout, ", sockbufsize=%d", sockbufsize);
      fprintf (stdout, "  %s  -> %s\n",
               domain == PF_INET ? (udp ? "udp" : "tcp") : "unix",
               host == 0 ? domainname : host);
    }
  else // receiver
    {
      fprintf (stdout,
               "ttcp-r: data_buf_len=%d, nbuf=%d, align=%d/%d, port=%d",
               data_buf_len, nbuf, bufalign, bufoffset, port);
      if (sockbufsize)
        fprintf (stdout, ", sockbufsize=%d", sockbufsize);
      fprintf (stdout, "  %s\n", domain == PF_INET ? (udp ? "udp" : "tcp") : "unix");
    }

  mes ("socket");

  //
  // connect and accept
  //

  if (!udp)
    {
      signal (SIGPIPE, (SIG_TYP) sigpipe);

      /* the transmitter will set options and connect to receiver */
      if (trans)
        {
          // turn off weird ack things
          if (nodelay)
            {
              struct protoent *p = getprotobyname ("tcp");

              if (p && connection_stream.set_option (p->p_proto,
                                                    TCP_NODELAY,
                                                    (char *)& one,
                                                    sizeof (one)))
                err ("setsockopt: nodelay");
              mes ("nodelay");
            }
          if (connector_factory.connect (connection_stream, address) == -1)
            perror ("connection failed"), exit (1);
          fprintf (stdout,
                  "ttcp-t: data_buf_len=%d, nbuf=%d, align=%d/%d, port=%d",
                  data_buf_len, nbuf, bufalign, bufoffset, port);

          if (sockbufsize)
            {
              if (connection_stream.set_option (SOL_SOCKET,
                                                SO_SNDBUF,
                                                (char *) &sockbufsize,
                                                sizeof sockbufsize) == -1)
                err ("acceptor_factory.set_option");
              mes ("sndbuf");
            }
        }

      /* receiver will listen for connections from the transmitter */
      else
        {
          if (acceptor_factory.open (address, 1) == -1)
            perror ("acceptor open"), exit (1);

          if (sockbufsize)
            {
              if (connection_stream.set_option (SOL_SOCKET,
                                                SO_RCVBUF,
                                                (char *) &sockbufsize,
                                                sizeof sockbufsize) == -1)
                err ("acceptor_factory.set_option");
              mes ("rcvbuf");
            }

          ACE_INET_Addr remote_address;

          if (acceptor_factory.accept (connection_stream,
                                      (ACE_Addr *) &remote_address) == -1)
            perror ("acceptor accept"), exit (1);

          // set the window size

          fprintf (stderr,
                  "ttcp-r: accept from %s\n",
                  remote_address.get_host_name());
        }
    }

  //
  // start timer
  //

  errno = 0;
  if (trans)
    {
      pattern (& (message_buf->data_), data_buf_len);
      prep_timer ();

      ACE_DEBUG ((LM_DEBUG, "Sending session control message"
                  " nbuf %d, size %d\n", session_control_buf.nbuf_,
                  session_control_buf.size_));
      if (connection_stream.send_n ((char *) &session_control_buf,
                                    sizeof (Session_Control_Message))
          != sizeof (Session_Control_Message))
        ACE_ERROR_RETURN ((LM_ERROR,
                           "%p send session control failed\n",
                           "ttcp"),
                          -1);

      long ack;
      int send_result;
      while (nbuf--)
        {
          send_result = connection_stream.send_n ((char *) message_buf,
                                                  total_msg_len);
          if (send_result != total_msg_len)
            ACE_ERROR_RETURN ((LM_ERROR,
                               "%p only sent %d of %d bytes on call %d\n",
                               "ttcp", send_result, total_msg_len, numCalls + 1),
                              -1);
          numCalls++;
          nbytes += data_buf_len;

          if (connection_stream.recv_n ((char *) &ack, sizeof ack) != sizeof ack)
            ACE_ERROR_RETURN ((LM_ERROR, "%p recv of ack failed\n", "ttcp"), -1);

          if (ack != data_buf_len)
            ACE_DEBUG ((LM_DEBUG, "received ack for only %d bytes\n", ack));
        }
      printf("Client finished.\n");
    }
  else
    {
      prep_timer ();

      if (connection_stream.recv_n ((char *) &session_control_buf,
                                    sizeof (Session_Control_Message))
          != sizeof (Session_Control_Message))
        ACE_ERROR_RETURN ((LM_ERROR,
                           "%p recv session control failed\n",
                           "ttcp"),
                          -1);

      ACE_DEBUG ((LM_DEBUG, "received session control message"
                  " nbuf %d, size %d\n", session_control_buf.nbuf_,
                  session_control_buf.size_));

      nbuf = session_control_buf.nbuf_;
      // ignore session_control_buf.size_ for now

      long cnt;

      while (nbuf--)
        {
          if (connection_stream.recv_n ((char *) message_buf, sizeof (long))
              != sizeof (long))
            ACE_ERROR_RETURN ((LM_ERROR,
                               "%p recv data control failed\n",
                               "ttcp"),
                              -1);

          cnt = connection_stream.recv_n (& (message_buf->data_), message_buf->size_);
          if (cnt != message_buf->size_)
            ACE_ERROR_RETURN ((LM_ERROR, "recv data failed\n"), -1);

          numCalls++;
          nbytes += cnt;

          if (connection_stream.send_n ((char *) &cnt, sizeof cnt)
              != sizeof cnt)
            ACE_ERROR_RETURN ((LM_ERROR,
                               "%p send ack failed\n",
                               "ttcp"),
                              -1);
        }
      printf("Server finished.\n");
    }

  /*  if (errno)
    err ("IO");
    */
  //
  // stop the timer
  //

  (void) read_timer (stats, sizeof (stats));
  if (udp && trans)
    {
      (void) Nwrite (connection_stream, message_buf, 4); /* rcvr end */
      (void) Nwrite (connection_stream, message_buf, 4); /* rcvr end */
      (void) Nwrite (connection_stream, message_buf, 4); /* rcvr end */
      (void) Nwrite (connection_stream, message_buf, 4); /* rcvr end */
    }
  if (cput <= 0.0)
    cput = 0.001;
  if (realt <= 0.0)
    realt = 0.001;

#if defined (LM_RESULTS)
  if (trans && (title != 0))
    {
      double tmp;
      FILE *fd;
      char filename[BUFSIZ];
      ACE_OS::sprintf (filename, "%s.results", title);
      fd = fopen(filename,"a+");
      if (new_line)
        fprintf(fd,"\n  -l %ldk \t", data_buf_len/1024);
      tmp = ((double) nbytes) / realt;
      fprintf(fd,"%.2f ", tmp * 8.0 / 1024.0 / 1024.0);
      fclose(fd);
    }
#endif

  fprintf (stdout,
           "ttcp%s: %ld bytes in %.2f real seconds = %s/sec +++\n",
           trans ? "-t" : "-r",
           nbytes, realt, outfmt (((double) nbytes) / realt));
  if (verbose)
    {
      fprintf (stdout,
               "ttcp%s: %ld bytes in %.2f CPU seconds = %s/cpu sec\n",
               trans ? "-t" : "-r",
               nbytes, cput, outfmt (((double) nbytes) / cput));
    }
  fprintf (stdout,
           "ttcp%s: %d I/O calls, msec/call = %.2f, calls/sec = %.2f\n",
           trans ? "-t" : "-r",
           numCalls,
           1024.0 * realt / ((double) numCalls),
           ((double) numCalls) / realt);
  fprintf (stdout, "ttcp%s: %s\n", trans ? "-t" : "-r", stats);
  if (verbose)
    {
      fprintf (stdout,
               "ttcp%s: buffer address %#x\n",
               trans ? "-t" : "-r",
               message_buf);
    }
  exit (0);

usage:
  fprintf (stderr, Usage);
  return 1;
}
Пример #21
0
SkPDFImageShader::SkPDFImageShader(SkPDFShader::State* state) : fState(state) {
    fState.get()->fImage.lockPixels();

    SkMatrix finalMatrix = fState.get()->fCanvasTransform;
    finalMatrix.preConcat(fState.get()->fShaderTransform);
    SkRect surfaceBBox;
    surfaceBBox.set(fState.get()->fBBox);
    transformBBox(finalMatrix, &surfaceBBox);

    SkMatrix unflip;
    unflip.setTranslate(0, SkScalarRound(surfaceBBox.height()));
    unflip.preScale(SK_Scalar1, -SK_Scalar1);
    SkISize size = SkISize::Make(SkScalarRound(surfaceBBox.width()),
                                 SkScalarRound(surfaceBBox.height()));
    SkPDFDevice pattern(size, size, unflip);
    SkCanvas canvas(&pattern);
    canvas.translate(-surfaceBBox.fLeft, -surfaceBBox.fTop);
    finalMatrix.preTranslate(surfaceBBox.fLeft, surfaceBBox.fTop);

    const SkBitmap* image = &fState.get()->fImage;
    int width = image->width();
    int height = image->height();
    SkShader::TileMode tileModes[2];
    tileModes[0] = fState.get()->fImageTileModes[0];
    tileModes[1] = fState.get()->fImageTileModes[1];

    canvas.drawBitmap(*image, 0, 0);
    SkRect patternBBox = SkRect::MakeXYWH(-surfaceBBox.fLeft, -surfaceBBox.fTop,
                                          width, height);

    // Tiling is implied.  First we handle mirroring.
    if (tileModes[0] == SkShader::kMirror_TileMode) {
        SkMatrix xMirror;
        xMirror.setScale(-1, 1);
        xMirror.postTranslate(2 * width, 0);
        canvas.drawBitmapMatrix(*image, xMirror);
        patternBBox.fRight += width;
    }
    if (tileModes[1] == SkShader::kMirror_TileMode) {
        SkMatrix yMirror;
        yMirror.setScale(SK_Scalar1, -SK_Scalar1);
        yMirror.postTranslate(0, 2 * height);
        canvas.drawBitmapMatrix(*image, yMirror);
        patternBBox.fBottom += height;
    }
    if (tileModes[0] == SkShader::kMirror_TileMode &&
            tileModes[1] == SkShader::kMirror_TileMode) {
        SkMatrix mirror;
        mirror.setScale(-1, -1);
        mirror.postTranslate(2 * width, 2 * height);
        canvas.drawBitmapMatrix(*image, mirror);
    }

    // Then handle Clamping, which requires expanding the pattern canvas to
    // cover the entire surfaceBBox.

    // If both x and y are in clamp mode, we start by filling in the corners.
    // (Which are just a rectangles of the corner colors.)
    if (tileModes[0] == SkShader::kClamp_TileMode &&
            tileModes[1] == SkShader::kClamp_TileMode) {
        SkPaint paint;
        SkRect rect;
        rect = SkRect::MakeLTRB(surfaceBBox.fLeft, surfaceBBox.fTop, 0, 0);
        if (!rect.isEmpty()) {
            paint.setColor(image->getColor(0, 0));
            canvas.drawRect(rect, paint);
        }

        rect = SkRect::MakeLTRB(width, surfaceBBox.fTop, surfaceBBox.fRight, 0);
        if (!rect.isEmpty()) {
            paint.setColor(image->getColor(width - 1, 0));
            canvas.drawRect(rect, paint);
        }

        rect = SkRect::MakeLTRB(width, height, surfaceBBox.fRight,
                                surfaceBBox.fBottom);
        if (!rect.isEmpty()) {
            paint.setColor(image->getColor(width - 1, height - 1));
            canvas.drawRect(rect, paint);
        }

        rect = SkRect::MakeLTRB(surfaceBBox.fLeft, height, 0,
                                surfaceBBox.fBottom);
        if (!rect.isEmpty()) {
            paint.setColor(image->getColor(0, height - 1));
            canvas.drawRect(rect, paint);
        }
    }

    // Then expand the left, right, top, then bottom.
    if (tileModes[0] == SkShader::kClamp_TileMode) {
        SkIRect subset = SkIRect::MakeXYWH(0, 0, 1, height);
        if (surfaceBBox.fLeft < 0) {
            SkBitmap left;
            SkAssertResult(image->extractSubset(&left, subset));

            SkMatrix leftMatrix;
            leftMatrix.setScale(-surfaceBBox.fLeft, 1);
            leftMatrix.postTranslate(surfaceBBox.fLeft, 0);
            canvas.drawBitmapMatrix(left, leftMatrix);

            if (tileModes[1] == SkShader::kMirror_TileMode) {
                leftMatrix.postScale(SK_Scalar1, -SK_Scalar1);
                leftMatrix.postTranslate(0, 2 * height);
                canvas.drawBitmapMatrix(left, leftMatrix);
            }
            patternBBox.fLeft = 0;
        }

        if (surfaceBBox.fRight > width) {
            SkBitmap right;
            subset.offset(width - 1, 0);
            SkAssertResult(image->extractSubset(&right, subset));

            SkMatrix rightMatrix;
            rightMatrix.setScale(surfaceBBox.fRight - width, 1);
            rightMatrix.postTranslate(width, 0);
            canvas.drawBitmapMatrix(right, rightMatrix);

            if (tileModes[1] == SkShader::kMirror_TileMode) {
                rightMatrix.postScale(SK_Scalar1, -SK_Scalar1);
                rightMatrix.postTranslate(0, 2 * height);
                canvas.drawBitmapMatrix(right, rightMatrix);
            }
            patternBBox.fRight = surfaceBBox.width();
        }
    }

    if (tileModes[1] == SkShader::kClamp_TileMode) {
        SkIRect subset = SkIRect::MakeXYWH(0, 0, width, 1);
        if (surfaceBBox.fTop < 0) {
            SkBitmap top;
            SkAssertResult(image->extractSubset(&top, subset));

            SkMatrix topMatrix;
            topMatrix.setScale(SK_Scalar1, -surfaceBBox.fTop);
            topMatrix.postTranslate(0, surfaceBBox.fTop);
            canvas.drawBitmapMatrix(top, topMatrix);

            if (tileModes[0] == SkShader::kMirror_TileMode) {
                topMatrix.postScale(-1, 1);
                topMatrix.postTranslate(2 * width, 0);
                canvas.drawBitmapMatrix(top, topMatrix);
            }
            patternBBox.fTop = 0;
        }

        if (surfaceBBox.fBottom > height) {
            SkBitmap bottom;
            subset.offset(0, height - 1);
            SkAssertResult(image->extractSubset(&bottom, subset));

            SkMatrix bottomMatrix;
            bottomMatrix.setScale(SK_Scalar1, surfaceBBox.fBottom - height);
            bottomMatrix.postTranslate(0, height);
            canvas.drawBitmapMatrix(bottom, bottomMatrix);

            if (tileModes[0] == SkShader::kMirror_TileMode) {
                bottomMatrix.postScale(-1, 1);
                bottomMatrix.postTranslate(2 * width, 0);
                canvas.drawBitmapMatrix(bottom, bottomMatrix);
            }
            patternBBox.fBottom = surfaceBBox.height();
        }
    }

    SkRefPtr<SkPDFArray> patternBBoxArray = new SkPDFArray;
    patternBBoxArray->unref();  // SkRefPtr and new both took a reference.
    patternBBoxArray->reserve(4);
    patternBBoxArray->appendScalar(patternBBox.fLeft);
    patternBBoxArray->appendScalar(patternBBox.fTop);
    patternBBoxArray->appendScalar(patternBBox.fRight);
    patternBBoxArray->appendScalar(patternBBox.fBottom);

    // Put the canvas into the pattern stream (fContent).
    SkRefPtr<SkStream> content = pattern.content();
    content->unref();  // SkRefPtr and content() both took a reference.
    pattern.getResources(&fResources);

    setData(content.get());
    insertName("Type", "Pattern");
    insertInt("PatternType", 1);
    insertInt("PaintType", 1);
    insertInt("TilingType", 1);
    insert("BBox", patternBBoxArray.get());
    insertScalar("XStep", patternBBox.width());
    insertScalar("YStep", patternBBox.height());
    insert("Resources", pattern.getResourceDict());
    insert("Matrix", SkPDFUtils::MatrixToArray(finalMatrix))->unref();

    fState.get()->fImage.unlockPixels();
}
Пример #22
0
MStatus AbcExport::doIt(const MArgList & args)
{
try
{
    MStatus status;

    MTime oldCurTime = MAnimControl::currentTime();

    MArgParser argData(syntax(), args, &status);

    if (argData.isFlagSet("help"))
    {
        MGlobal::displayInfo(util::getHelpText());
        return MS::kSuccess;
    }

    bool verbose = argData.isFlagSet("verbose");

    // If skipFrame is true, when going through the playback range of the
    // scene, as much frames are skipped when possible.  This could cause
    // a problem for, time dependent solutions like
    // particle system / hair simulation
    bool skipFrame = true;
    if (argData.isFlagSet("dontSkipUnwrittenFrames"))
        skipFrame = false;

    double startEvaluationTime = DBL_MAX;
    if (argData.isFlagSet("preRollStartFrame"))
    {
        double startAt = 0.0;
        argData.getFlagArgument("preRollStartFrame", 0, startAt);
        startEvaluationTime = startAt;
    }

    unsigned int jobSize = argData.numberOfFlagUses("jobArg");

    if (jobSize == 0)
        return status;

    // the frame range we will be iterating over for all jobs,
    // includes frames which are not skipped and the startAt offset
    std::set<double> allFrameRange;

    // this will eventually hold only the animated jobs.
    // its a list because we will be removing jobs from it
    std::list < AbcWriteJobPtr > jobList;

    for (unsigned int jobIndex = 0; jobIndex < jobSize; jobIndex++)
    {
        JobArgs jobArgs;
        MArgList jobArgList;
        argData.getFlagArgumentList("jobArg", jobIndex, jobArgList);
        MString jobArgsStr = jobArgList.asString(0);
        MStringArray jobArgsArray;

        {
            // parse the job arguments
            // e.g. -perFrameCallbackMel "print \"something\"" will be splitted to
            //    [0] -perFrameCallbackMel
            //    [1] print "something"
            enum State {
                kArgument,               // parsing an argument (not quoted)
                kDoubleQuotedString,     // parsing a double quoted string
                kSingleQuotedString,     // parsing a single quoted string
            };

            State state = kArgument;
            MString stringBuffer;
            for (unsigned int charIdx = 0; charIdx < jobArgsStr.numChars();
                charIdx++)
            {
                MString ch = jobArgsStr.substringW(charIdx, charIdx);
                switch (state)
                {
                case kArgument:
                    if (ch == " ")
                    {
                        // space terminates the current argument
                        if (stringBuffer.length() > 0) {
                            jobArgsArray.append(stringBuffer);
                            stringBuffer.clear();
                        }
                        // goto another argument
                        state = kArgument;
                    }
                    else if (ch == "\"")
                    {
                        if (stringBuffer.length() > 0)
                        {
                            // double quote is part of the argument
                            stringBuffer += ch;
                        }
                        else
                        {
                            // goto double quoted string
                            state = kDoubleQuotedString;
                        }
                    }
                    else if (ch == "'")
                    {
                        if (stringBuffer.length() > 0)
                        {
                            // single quote is part of the argument
                            stringBuffer += ch;
                        }
                        else
                        {
                            // goto single quoted string
                            state = kSingleQuotedString;
                        }
                    }
                    else
                    {
                        stringBuffer += ch;
                    }
                break;

                case kDoubleQuotedString:
                    // double quote terminates the current string
                    if (ch == "\"")
                    {
                        jobArgsArray.append(stringBuffer);
                        stringBuffer.clear();
                        state = kArgument;
                    }
                    else if (ch == "\\")
                    {
                        // escaped character
                        MString nextCh = (++charIdx < jobArgsStr.numChars())
                            ? jobArgsStr.substringW(charIdx, charIdx) : "\\";
                        if (nextCh == "n")       stringBuffer += "\n";
                        else if (nextCh == "t")  stringBuffer += "\t";
                        else if (nextCh == "r")  stringBuffer += "\r";
                        else if (nextCh == "\\") stringBuffer += "\\";
                        else if (nextCh == "'")  stringBuffer += "'";
                        else if (nextCh == "\"") stringBuffer += "\"";
                        else                     stringBuffer += nextCh;
                    }
                    else
                    {
                        stringBuffer += ch;
                    }
                break;

                case kSingleQuotedString:
                    // single quote terminates the current string
                    if (ch == "'")
                    {
                        jobArgsArray.append(stringBuffer);
                        stringBuffer.clear();
                        state = kArgument;
                    }
                    else if (ch == "\\")
                    {
                        // escaped character
                        MString nextCh = (++charIdx < jobArgsStr.numChars())
                            ? jobArgsStr.substringW(charIdx, charIdx) : "\\";
                        if (nextCh == "n")       stringBuffer += "\n";
                        else if (nextCh == "t")  stringBuffer += "\t";
                        else if (nextCh == "r")  stringBuffer += "\r";
                        else if (nextCh == "\\") stringBuffer += "\\";
                        else if (nextCh == "'")  stringBuffer += "'";
                        else if (nextCh == "\"") stringBuffer += "\"";
                        else                     stringBuffer += nextCh;
                    }
                    else
                    {
                        stringBuffer += ch;
                    }
                break;
                }
            }

            // the rest of the argument
            if (stringBuffer.length() > 0)
            {
                jobArgsArray.append(stringBuffer);
            }
        }

        // the frame range within this job
        std::vector< FrameRangeArgs > frameRanges(1);
        frameRanges.back().startTime = oldCurTime.value();
        frameRanges.back().endTime = oldCurTime.value();
        frameRanges.back().strideTime = 1.0;

        bool hasRange = false;
        bool hasRoot = false;
        bool sampleGeo  = true; // whether or not to subsample geometry
        std::string fileName;
        bool asOgawa = true;

        unsigned int numJobArgs = jobArgsArray.length();
        for (unsigned int i = 0; i < numJobArgs; ++i)
        {
            MString arg = jobArgsArray[i];
            arg.toLowerCase();

            if (arg == "-f" || arg == "-file")
            {
                if (i+1 >= numJobArgs)
                {
                    MGlobal::displayError("File incorrectly specified.");
                    return MS::kFailure;
                }
                fileName = jobArgsArray[++i].asChar();
            }

            else if (arg == "-fr" || arg == "-framerange")
            {
                if (i+2 >= numJobArgs || !jobArgsArray[i+1].isDouble() ||
                    !jobArgsArray[i+2].isDouble())
                {
                    MGlobal::displayError("Frame Range incorrectly specified.");
                    return MS::kFailure;
                }

                // this is not the first -frameRange argument, we are going
                // to add one more frame range to the frame range array.
                if (hasRange)
                {
                    frameRanges.push_back(FrameRangeArgs());
                }

                hasRange = true;
                frameRanges.back().startTime = jobArgsArray[++i].asDouble();
                frameRanges.back().endTime = jobArgsArray[++i].asDouble();

                // make sure start frame is smaller or equal to endTime
                if (frameRanges.back().startTime > frameRanges.back().endTime)
                {
                    std::swap(frameRanges.back().startTime,
                        frameRanges.back().endTime);
                }
            }

            else if (arg == "-frs" || arg == "-framerelativesample")
            {
                if (i+1 >= numJobArgs || !jobArgsArray[i+1].isDouble())
                {
                    MGlobal::displayError(
                        "Frame Relative Sample incorrectly specified.");
                    return MS::kFailure;
                }
                frameRanges.back().shutterSamples.insert(
                    jobArgsArray[++i].asDouble());
            }

            else if (arg == "-nn" || arg == "-nonormals")
            {
                jobArgs.noNormals = true;
            }

            else if (arg == "-pr" || arg == "-preroll")
            {
                frameRanges.back().preRoll = true;
            }

            else if (arg == "-ro" || arg == "-renderableonly")
            {
                jobArgs.excludeInvisible = true;
            }

            else if (arg == "-s" || arg == "-step")
            {
                if (i+1 >= numJobArgs || !jobArgsArray[i+1].isDouble())
                {
                    MGlobal::displayError("Step incorrectly specified.");
                    return MS::kFailure;
                }
                frameRanges.back().strideTime = jobArgsArray[++i].asDouble();
            }

            else if (arg == "-sl" || arg == "-selection")
            {
                jobArgs.useSelectionList = true;
            }

            else if (arg == "-sn" || arg == "-stripnamespaces")
            {
                if (i+1 >= numJobArgs || !jobArgsArray[i+1].isUnsigned())
                {
                    // the strip all namespaces case
                    // so we pick a very LARGE number
                    jobArgs.stripNamespace = 0xffffffff;
                }
                else
                {
                    jobArgs.stripNamespace = jobArgsArray[++i].asUnsigned();
                }
            }

            else if (arg == "-uv" || arg == "-uvwrite")
            {
                jobArgs.writeUVs = true;
            }

            else if (arg == "-wcs" || arg == "-writecolorsets")
            {
                jobArgs.writeColorSets = true;
            }

            else if (arg == "-wfs" || arg == "-writefacesets")
            {
                jobArgs.writeFaceSets = true;
            }

            else if (arg == "-wfg" || arg == "-wholeframegeo")
            {
                sampleGeo = false;
            }

            else if (arg == "-ws" || arg == "-worldspace")
            {
                jobArgs.worldSpace = true;
            }

            else if (arg == "-wuvs" || arg == "-writeuvsets")
            {
                jobArgs.writeUVSets = true;
            }

            else if (arg == "-wv" || arg == "-writevisibility")
            {
                jobArgs.writeVisibility = true;
            }

            else if (arg == "-as" || arg == "-autosubd")
            {
                jobArgs.autoSubd = true;
            }

            else if (arg == "-mfc" || arg == "-melperframecallback")
            {
                if (i+1 >= numJobArgs)
                {
                    MGlobal::displayError(
                        "melPerFrameCallback incorrectly specified.");
                    return MS::kFailure;
                }
                jobArgs.melPerFrameCallback = jobArgsArray[++i].asChar();
            }

            else if (arg == "-pfc" || arg == "-pythonperframecallback")
            {
                if (i+1 >= numJobArgs)
                {
                    MGlobal::displayError(
                        "pythonPerFrameCallback incorrectly specified.");
                    return MS::kFailure;
                }
                jobArgs.pythonPerFrameCallback = jobArgsArray[++i].asChar();
            }

            else if (arg == "-mpc" || arg == "-melpostjobcallback")
            {
                if (i+1 >= numJobArgs)
                {
                    MGlobal::displayError(
                        "melPostJobCallback incorrectly specified.");
                    return MS::kFailure;
                }
                jobArgs.melPostCallback = jobArgsArray[++i].asChar();
            }

            else if (arg == "-ppc" || arg == "-pythonpostjobcallback")
            {
                if (i+1 >= numJobArgs)
                {
                    MGlobal::displayError(
                        "pythonPostJobCallback incorrectly specified.");
                    return MS::kFailure;
                }
                jobArgs.pythonPostCallback = jobArgsArray[++i].asChar();
            }

            // geomArbParams - attribute filtering stuff
            else if (arg == "-atp" || arg == "-attrprefix")
            {
                if (i+1 >= numJobArgs)
                {
                    MGlobal::displayError(
                        "attrPrefix incorrectly specified.");
                    return MS::kFailure;
                }
                jobArgs.prefixFilters.push_back(jobArgsArray[++i].asChar());
            }

            else if (arg == "-a" || arg == "-attr")
            {
                if (i+1 >= numJobArgs)
                {
                    MGlobal::displayError(
                        "attr incorrectly specified.");
                    return MS::kFailure;
                }
                jobArgs.attribs.insert(jobArgsArray[++i].asChar());
            }

            // userProperties - attribute filtering stuff
            else if (arg == "-uatp" || arg == "-userattrprefix")
            {
                if (i+1 >= numJobArgs)
                {
                    MGlobal::displayError(
                        "userAttrPrefix incorrectly specified.");
                    return MS::kFailure;
                }
                jobArgs.userPrefixFilters.push_back(jobArgsArray[++i].asChar());
            }

            else if (arg == "-u" || arg == "-userattr")
            {
                if (i+1 >= numJobArgs)
                {
                    MGlobal::displayError(
                        "userAttr incorrectly specified.");
                    return MS::kFailure;
                }
                jobArgs.userAttribs.insert(jobArgsArray[++i].asChar());
            }

            else if (arg == "-rt" || arg == "-root")
            {
                if (i+1 >= numJobArgs)
                {
                    MGlobal::displayError(
                        "root incorrectly specified.");
                    return MS::kFailure;
                }
                hasRoot = true;
                MString root = jobArgsArray[++i];

                MSelectionList sel;
                if (sel.add(root) != MS::kSuccess)
                {
                    MString warn = root;
                    warn += " could not be select, skipping.";
                    MGlobal::displayWarning(warn);
                    continue;
                }

                unsigned int numRoots = sel.length();
                for (unsigned int j = 0; j < numRoots; ++j)
                {
                    MDagPath path;
                    if (sel.getDagPath(j, path) != MS::kSuccess)
                    {
                        MString warn = path.fullPathName();
                        warn += " (part of ";
                        warn += root;
                        warn += " ) not a DAG Node, skipping.";
                        MGlobal::displayWarning(warn);
                        continue;
                    }
                    jobArgs.dagPaths.insert(path);
                }
            }
            else if (arg == "-ef" || arg == "-eulerfilter")
            {
                jobArgs.filterEulerRotations = true;
            }
            else if (arg == "-df" || arg == "-dataformat")
            {
                if (i+1 >= numJobArgs)
                {
                    MGlobal::displayError(
                        "dataFormat incorrectly specified.");
                    return MS::kFailure;
                }
                MString dataFormat = jobArgsArray[++i];
                dataFormat.toLowerCase();
                if (dataFormat == "hdf")
                {
                    asOgawa = false;
                }
                else if (dataFormat == "ogawa")
                {
                    asOgawa = true;
                }
            }
            else
            {
                MString warn = "Ignoring unsupported flag: ";
                warn += jobArgsArray[i];
                MGlobal::displayWarning(warn);
            }
        } //  for i

        if (fileName == "")
        {
            MString error = "-file not specified.";
            MGlobal::displayError(error);
            return MS::kFailure;
        }

        {
            MString fileRule, expandName;
            MString alembicFileRule = "alembicCache";
            MString alembicFilePath = "cache/alembic";

            MString queryFileRuleCmd;
            queryFileRuleCmd.format("workspace -q -fre \"^1s\"",
                alembicFileRule);

            MString queryFolderCmd;
            queryFolderCmd.format("workspace -en `workspace -q -fre \"^1s\"`",
                alembicFileRule);

            // query the file rule for alembic cache
            MGlobal::executeCommand(queryFileRuleCmd, fileRule);
            if (fileRule.length() > 0)
            {
                // we have alembic file rule, query the folder
                MGlobal::executeCommand(queryFolderCmd, expandName);
            }
            else
            {
                // alembic file rule does not exist, create it
                MString addFileRuleCmd;
                addFileRuleCmd.format("workspace -fr \"^1s\" \"^2s\"",
                    alembicFileRule, alembicFilePath);
                MGlobal::executeCommand(addFileRuleCmd);

                // save the workspace. maya may discard file rules on exit
                MGlobal::executeCommand("workspace -s");

                // query the folder
                MGlobal::executeCommand(queryFolderCmd, expandName);
            }

            // resolve the expanded file rule
            if (expandName.length() == 0)
            {
                expandName = alembicFilePath;
            }

            // get the path to the alembic file rule
            MFileObject directory;
            directory.setRawFullName(expandName);
            MString directoryName = directory.resolvedFullName();

            // make sure the cache folder exists
            if (!directory.exists())
            {
                // create the cache folder
                MString createFolderCmd;
                createFolderCmd.format("sysFile -md \"^1s\"", directoryName);
                MGlobal::executeCommand(createFolderCmd);
            }

            // resolve the relative path
            MFileObject absoluteFile;
            absoluteFile.setRawFullName(fileName.c_str());
#if MAYA_API_VERSION < 201300
            if (absoluteFile.resolvedFullName() !=
                absoluteFile.expandedFullName())
            {
#else
            if (!MFileObject::isAbsolutePath(fileName.c_str())) {
#endif
                // this is a relative path
                MString absoluteFileName = directoryName + "/" +
                    fileName.c_str();
                absoluteFile.setRawFullName(absoluteFileName);
                fileName = absoluteFile.resolvedFullName().asChar();
            }
            else
            {
                fileName = absoluteFile.resolvedFullName().asChar();
            }

            // check the path must exist before writing
            MFileObject absoluteFilePath;
            absoluteFilePath.setRawFullName(absoluteFile.path());
            if (!absoluteFilePath.exists()) {
                MString error;
                error.format("Path ^1s does not exist!", absoluteFilePath.resolvedFullName());
                MGlobal::displayError(error);
                return MS::kFailure;
            }

            // check the file is used by any AlembicNode in the scene
            MItDependencyNodes dgIter(MFn::kPluginDependNode);
            for (; !dgIter.isDone(); dgIter.next()) {
                MFnDependencyNode alembicNode(dgIter.thisNode());
                if (alembicNode.typeName() != "AlembicNode") {
                    continue;
                }

                MPlug abcFilePlug = alembicNode.findPlug("abc_File");
                if (abcFilePlug.isNull()) {
                    continue;
                }

                MFileObject alembicFile;
                alembicFile.setRawFullName(abcFilePlug.asString());
                if (!alembicFile.exists()) {
                    continue;
                }

                if (alembicFile.resolvedFullName() == absoluteFile.resolvedFullName()) {
                    MString error = "Can't export to an Alembic file which is in use.";
                    MGlobal::displayError(error);
                    return MS::kFailure;
                }
            }

            std::ofstream ofs(fileName.c_str());
            if (!ofs.is_open()) {
                MString error = MString("Can't write to file: ") + fileName.c_str();
                MGlobal::displayError(error);
                return MS::kFailure;
            }
            ofs.close();
        }

        // if -frameRelativeSample argument is not specified for a frame range,
        // we are assuming a -frameRelativeSample 0.0
        for (std::vector<FrameRangeArgs>::iterator range =
            frameRanges.begin(); range != frameRanges.end(); ++range)
        {
            if (range->shutterSamples.empty())
                range->shutterSamples.insert(0.0);
        }

        if (jobArgs.prefixFilters.empty())
        {
            jobArgs.prefixFilters.push_back("ABC_");
        }

        // the list of frame ranges for sampling
        std::vector<FrameRangeArgs> sampleRanges;
        std::vector<FrameRangeArgs> preRollRanges;
        for (std::vector<FrameRangeArgs>::const_iterator range =
            frameRanges.begin(); range != frameRanges.end(); ++range)
        {
            if (range->preRoll)
                preRollRanges.push_back(*range);
            else
                sampleRanges.push_back(*range);
        }

        // the list of frames written into the abc file
        std::set<double> geoSamples;
        std::set<double> transSamples;
        for (std::vector<FrameRangeArgs>::const_iterator range =
            sampleRanges.begin(); range != sampleRanges.end(); ++range)
        {
            for (double frame = range->startTime;
                frame <= range->endTime;
                frame += range->strideTime)
            {
                for (std::set<double>::const_iterator shutter =
                    range->shutterSamples.begin();
                    shutter != range->shutterSamples.end(); ++shutter)
                {
                    double curFrame = *shutter + frame;
                    if (!sampleGeo)
                    {
                        double intFrame = (double)(int)(
                            curFrame >= 0 ? curFrame + .5 : curFrame - .5);

                        // only insert samples that are close to being an integer
                        if (fabs(curFrame - intFrame) < 1e-4)
                        {
                            geoSamples.insert(curFrame);
                        }
                    }
                    else
                    {
                        geoSamples.insert(curFrame);
                    }
                    transSamples.insert(curFrame);
                }
            }

            if (geoSamples.empty())
            {
                geoSamples.insert(range->startTime);
            }

            if (transSamples.empty())
            {
                transSamples.insert(range->startTime);
            }
        }

        bool isAcyclic = false;
        if (sampleRanges.empty())
        {
            // no frame ranges or all frame ranges are pre-roll ranges
            hasRange = false;
            geoSamples.insert(frameRanges.back().startTime);
            transSamples.insert(frameRanges.back().startTime);
        }
        else
        {
            // check if the time range is even (cyclic)
            // otherwise, we will use acyclic
            // sub frames pattern
            std::vector<double> pattern(
                sampleRanges.begin()->shutterSamples.begin(),
                sampleRanges.begin()->shutterSamples.end());
            std::transform(pattern.begin(), pattern.end(), pattern.begin(),
                std::bind2nd(std::plus<double>(),
                    sampleRanges.begin()->startTime));

            // check the frames against the pattern
            std::vector<double> timeSamples(
                transSamples.begin(), transSamples.end());
            for (size_t i = 0; i < timeSamples.size(); i++)
            {
                // next pattern
                if (i % pattern.size() == 0 && i / pattern.size() > 0)
                {
                    std::transform(pattern.begin(), pattern.end(),
                        pattern.begin(), std::bind2nd(std::plus<double>(),
                            sampleRanges.begin()->strideTime));
                }

                // pattern mismatch, we use acyclic time sampling type
                if (timeSamples[i] != pattern[i % pattern.size()])
                {
                    isAcyclic = true;
                    break;
                }
            }
        }

        // the list of frames to pre-roll
        std::set<double> preRollSamples;
        for (std::vector<FrameRangeArgs>::const_iterator range =
            preRollRanges.begin(); range != preRollRanges.end(); ++range)
        {
            for (double frame = range->startTime;
                frame <= range->endTime;
                frame += range->strideTime)
            {
                for (std::set<double>::const_iterator shutter =
                    range->shutterSamples.begin();
                    shutter != range->shutterSamples.end(); ++shutter)
                {
                    double curFrame = *shutter + frame;
                    preRollSamples.insert(curFrame);
                }
            }

            if (preRollSamples.empty())
            {
                preRollSamples.insert(range->startTime);
            }
        }

        if (jobArgs.dagPaths.size() > 1)
        {
            // check for validity of the DagPath relationships complexity : n^2

            util::ShapeSet::const_iterator m, n;
            util::ShapeSet::const_iterator end = jobArgs.dagPaths.end();
            for (m = jobArgs.dagPaths.begin(); m != end; )
            {
                MDagPath path1 = *m;
                m++;
                for (n = m; n != end; n++)
                {
                    MDagPath path2 = *n;
                    if (util::isAncestorDescendentRelationship(path1,path2))
                    {
                        MString errorMsg = path1.fullPathName();
                        errorMsg += " and ";
                        errorMsg += path2.fullPathName();
                        errorMsg += " have an ancestor relationship.";
                        MGlobal::displayError(errorMsg);
                        return MS::kFailure;
                    }
                }  // for n
            }  // for m
        }
        // no root is specified, and we aren't using a selection
        // so we'll try to translate the whole Maya scene by using all
        // children of the world as roots.
        else if (!hasRoot && !jobArgs.useSelectionList)
        {
            MSelectionList sel;
#if MAYA_API_VERSION >= 201100
            sel.add("|*", true);
#else
            // older versions of Maya will not be able to find top level nodes
            // within namespaces
            sel.add("|*");
#endif
            unsigned int numRoots = sel.length();
            for (unsigned int i = 0; i < numRoots; ++i)
            {
                MDagPath path;
                sel.getDagPath(i, path);
                jobArgs.dagPaths.insert(path);
            }
        }
        else if (hasRoot && jobArgs.dagPaths.empty())
        {
            MString errorMsg = "No valid root nodes were specified.";
            MGlobal::displayError(errorMsg);
            return MS::kFailure;
        }
        else if (jobArgs.useSelectionList)
        {
            MSelectionList activeList;
            MGlobal::getActiveSelectionList(activeList);
            if (activeList.length() == 0)
            {
                MString errorMsg =
                    "-selection specified but nothing is actively selected.";
                MGlobal::displayError(errorMsg);
                return MS::kFailure;
            }
        }

        AbcA::TimeSamplingPtr transTime, geoTime;

        if (hasRange)
        {
            if (isAcyclic)
            {
                // acyclic, uneven time sampling
                // e.g. [0.8, 1, 1.2], [2.8, 3, 3.2], .. not continuous
                //      [0.8, 1, 1.2], [1.7, 2, 2.3], .. shutter different
                std::vector<double> samples(
                    transSamples.begin(), transSamples.end());
                std::transform(samples.begin(), samples.end(), samples.begin(),
                    std::bind2nd(std::multiplies<double>(), util::spf()));
                transTime.reset(new AbcA::TimeSampling(AbcA::TimeSamplingType(
                    AbcA::TimeSamplingType::kAcyclic), samples));
            }
            else
            {
                // cyclic, even time sampling between time periods
                // e.g. [0.8, 1, 1.2], [1.8, 2, 2.2], ...
                std::vector<double> samples;
                double startTime = sampleRanges[0].startTime;
                double strideTime = sampleRanges[0].strideTime;
                for (std::set<double>::const_iterator shutter =
                    sampleRanges[0].shutterSamples.begin();
                    shutter != sampleRanges[0].shutterSamples.end();
                    ++shutter)
                {
                    samples.push_back((startTime + *shutter) * util::spf());
                }

                if (samples.size() > 1)
                {
                    Alembic::Util::uint32_t numSamples =
                        static_cast<Alembic::Util::uint32_t>(samples.size());
                    transTime.reset(
                        new AbcA::TimeSampling(AbcA::TimeSamplingType(
                            numSamples, strideTime * util::spf()), samples));
                }
                // uniform sampling
                else
                {
                    transTime.reset(new AbcA::TimeSampling(
                        strideTime * util::spf(), samples[0]));
                }
            }
        }
        else
        {
            // time ranges are not specified
            transTime.reset(new AbcA::TimeSampling());
        }

        if (sampleGeo || !hasRange)
        {
            geoTime = transTime;
        }
        else
        {
            // sampling geo on whole frames
            if (isAcyclic)
            {
                // acyclic, uneven time sampling
                std::vector<double> samples(
                    geoSamples.begin(), geoSamples.end());
                // one more sample for setup()
                if (*transSamples.begin() != *geoSamples.begin())
                    samples.insert(samples.begin(), *transSamples.begin());
                std::transform(samples.begin(), samples.end(), samples.begin(),
                    std::bind2nd(std::multiplies<double>(), util::spf()));
                geoTime.reset(new AbcA::TimeSampling(AbcA::TimeSamplingType(
                    AbcA::TimeSamplingType::kAcyclic), samples));
            }
            else
            {
                double geoStride = sampleRanges[0].strideTime;
                if (geoStride < 1.0)
                    geoStride = 1.0;

                double geoStart = *geoSamples.begin() * util::spf();
                geoTime.reset(new AbcA::TimeSampling(
                    geoStride * util::spf(), geoStart));
            }
        }

        AbcWriteJobPtr job(new AbcWriteJob(fileName.c_str(), asOgawa,
            transSamples, transTime, geoSamples, geoTime, jobArgs));

       jobList.push_front(job);

        // make sure we add additional whole frames, if we arent skipping
        // the inbetween ones
        if (!skipFrame && !allFrameRange.empty())
        {
            double localMin = *(transSamples.begin());
            std::set<double>::iterator last = transSamples.end();
            last--;
            double localMax = *last;

            double globalMin = *(allFrameRange.begin());
            last = allFrameRange.end();
            last--;
            double globalMax = *last;

            // if the min of our current frame range is beyond
            // what we know about, pad a few more frames
            if (localMin > globalMax)
            {
                for (double f = globalMax; f < localMin; f++)
                {
                    allFrameRange.insert(f);
                }
            }

            // if the max of our current frame range is beyond
            // what we know about, pad a few more frames
            if (localMax < globalMin)
            {
                for (double f = localMax; f < globalMin; f++)
                {
                    allFrameRange.insert(f);
                }
            }
        }

        // right now we just copy over the translation samples since
        // they are guaranteed to contain all the geometry samples
        allFrameRange.insert(transSamples.begin(), transSamples.end());

        // copy over the pre-roll samples
        allFrameRange.insert(preRollSamples.begin(), preRollSamples.end());
    }

    // add extra evaluation run up, if necessary
    if (startEvaluationTime != DBL_MAX && !allFrameRange.empty())
    {
        double firstFrame = *allFrameRange.begin();
        for (double f = startEvaluationTime; f < firstFrame; ++f)
        {
            allFrameRange.insert(f);
        }
    }

    std::set<double>::iterator it = allFrameRange.begin();
    std::set<double>::iterator itEnd = allFrameRange.end();

    MComputation computation;
    computation.beginComputation();

    // loop through every frame in the list, if a job has that frame in it's
    // list of transform or shape frames, then it will write out data and
    // call the perFrameCallback, if that frame is also the last one it has
    // to work on then it will also call the postCallback.
    // If it doesn't have this frame, then it does nothing
    for (; it != itEnd; it++)
    {
        if (verbose)
        {
            double frame = *it;
            MString info;
            info = frame;
            MGlobal::displayInfo(info);
        }

        MGlobal::viewFrame(*it);
        std::list< AbcWriteJobPtr >::iterator j = jobList.begin();
        std::list< AbcWriteJobPtr >::iterator jend = jobList.end();
        while (j != jend)
        {
            if (computation.isInterruptRequested())
                return MS::kFailure;

            bool lastFrame = (*j)->eval(*it);

            if (lastFrame)
            {
                j = jobList.erase(j);
            }
            else
                j++;
        }
    }
    computation.endComputation();

    // set the time back
    MGlobal::viewFrame(oldCurTime);

    return MS::kSuccess;
}
catch (Alembic::Util::Exception & e)
{
    MString theError("Alembic Exception encountered: ");
    theError += e.what();
    MGlobal::displayError(theError);
    return MS::kFailure;
}
catch (std::exception & e)
{
    MString theError("std::exception encountered: ");
    theError += e.what();
    MGlobal::displayError(theError);
    return MS::kFailure;
}

}
Пример #23
0
double LMQueryMKN<t_idx, t_atom>::append_symbol(const t_atom& symbol)
{
    if (symbol == PAT_START_SYM && m_pattern.size() == 1 && m_pattern.front() == PAT_START_SYM)
        return 1;

    m_pattern.push_back(symbol);
    while (m_ngramsize > 0 && m_pattern.size() > m_ngramsize)
        m_pattern.pop_front();
    std::vector<t_atom> pattern(m_pattern.begin(), m_pattern.end());
#ifdef STATELESS_QUERY
    // slow way
    return prob_mod_kneser_ney_single(*m_idx, pattern.begin(), pattern.end(), m_ngramsize);
#else
    // fast way, tracking state
    typedef typename t_idx::cst_type::node_type t_node;
    double p = 1.0 / (m_idx->m_vocab.size() - 4); // p -- FIXME: should we subtract away sentinels? //ehsan: not sure why -4 works! but it works!
    t_node node_incl = m_idx->m_cst.root(); // v_F^all matching the full pattern, including last item
    auto node_excl_it = m_last_nodes_incl.begin(); // v_F     matching only the context, excluding last item
    t_node node_excl = *node_excl_it;
    auto pattern_begin = pattern.begin();
    auto pattern_end = pattern.end();

    size_t size = std::distance(pattern_begin, pattern_end);
    bool unk = (*(pattern_end - 1) == UNKNOWN_SYM);
    bool ok = !unk;
    std::vector<t_node> node_incl_vec({ node_incl });

    for (unsigned i = 1; i <= size; ++i) {
        auto start = pattern_end - i;
        if (i > 1 && *start == UNKNOWN_SYM)
            break;

        //LOG(INFO) << "pattern is: " << m_idx->m_vocab.id2token(start, pattern_end);

        // update the two searches into the CST
        if (ok) {
            ok = backward_search_wrapper(m_idx->m_cst, node_incl, *start);
            //LOG(INFO) << "\tpattern lookup, ok=" << ok << " node=" << node_incl;
            if (ok)
                node_incl_vec.push_back(node_incl);
        }
        if (i >= 2) {
            node_excl_it++;
            //LOG(INFO) << "context query for: " << m_idx->m_vocab.id2token(start, pattern_end-1);
            if (node_excl_it == m_last_nodes_incl.end()) {
                //LOG(INFO) << "\tfailed context lookup; quitting";
                break;
            } else {
                node_excl = *node_excl_it;
            }
        }

        // compute the count and normaliser
        double D1, D2, D3p;
        //LOG(INFO) << "test for continuation counts: " << (i == 1 || i != ngramsize) << " i: " << i << " ngramsize: " << ngramsize;
        m_idx->mkn_discount(i, D1, D2, D3p, i == 1 || i != m_ngramsize);

        double c, d;
        uint64_t n1 = 0, n2 = 0, n3p = 0;
        if ((i == m_ngramsize && m_ngramsize != 1) || (*start == PAT_START_SYM)) {
            c = (ok) ? m_idx->m_cst.size(node_incl) : 0;
            d = m_idx->m_cst.size(node_excl);
            m_idx->N123PlusFront(node_excl, start, pattern_end - 1, n1, n2, n3p); // does this work for node_excl = root?
            //LOG(INFO) << "highest level c=" << c << " d=" << d << " n1=" << n1 << " n2=" << n2 << " n3p=" << n3p;
        } else {
            c = (ok) ? m_idx->N1PlusBack_from_forward(node_incl, start, pattern_end) : 0;
            if (i == 1 || m_ngramsize == 1) {
                // lowest level
                d = m_idx->m_precomputed.N1plus_dotdot;
                n1 = m_idx->m_precomputed.n1_cnt[1];
                n2 = m_idx->m_precomputed.n2_cnt[1];
                n3p = m_idx->m_precomputed.N3plus_dot;
            } else {
                // mid level (most cases arrive here)
                d = m_idx->N1PlusFrontBack_from_forward(node_excl, start, pattern_end - 1); // is this right?
                m_idx->N123PlusFrontBack_from_forward(node_excl, start, pattern_end - 1, n1, n2, n3p);
            }
            //LOG(INFO) << "mid/low level c=" << c << " d=" << d << " n1=" << n1 << " n2=" << n2 << " n3p=" << n3p;
        }

        // update the running probability
        if (c == 1) {
            c -= D1;
        } else if (c == 2) {
            c -= D2;
        } else if (c >= 3) {
            c -= D3p;
        }

        double gamma = D1 * n1 + D2 * n2 + D3p * n3p;
        p = (c + gamma * p) / d;
        //LOG(INFO) << "adjusted c=" << c << " gamma=" << gamma << " gamma/d=" << (gamma/d) << " p=" << p << " log(p)=" << log10(p);
        //LOG(INFO) << "\tdiscounts: D1=" << D1 << " D2=" << D2 << " D3p=" << D3p;
    }

    //LOG(INFO) << "FINAL prob " << p;
    // update the state for the next call
    m_last_nodes_incl = node_incl_vec;
    while (m_pattern.size() > m_last_nodes_incl.size())
        m_pattern.pop_front();

    return p;
#endif
}
Пример #24
0
// Verification Main Functions
void
V3VrfSIM::startVerify(const uint32_t& pIndex) {
   // Initialize
   V3Ntk* const ntk = _handler->getNtk(); assert (ntk);
   V3AlgSimulate* simulator = 0;
   if (dynamic_cast<V3BvNtk*>(ntk)) simulator = new V3AlgBvSimulate(_handler);
   else simulator = new V3AlgAigSimulate(_handler); assert (simulator);
   const V3NetId& pId = ntk->getOutput(pIndex); assert (V3NetUD != pId);
   const uint32_t logMaxWidth = (uint32_t)(ceil(log10(_maxDepth)));
   const string flushSpace = string(100, ' ');
   uint32_t cycle = V3NtkUD, cycleReached = 0;
   double runtime = clock(), timeBound = clock() + (CLOCKS_PER_SEC * _maxTime);
   
   // Start SIM Based Verification
   const uint32_t Cycle = 10000;
   uint32_t i = 0, j = 0;
   for (uint32_t k = 0, n = (uint32_t)(ceil(_maxDepth / Cycle)); k < n; ++k) {
      j = Cycle + i; if (j > _maxDepth) j = _maxDepth;
      for (i = Cycle * k; i < j; ++i) {
         // Update FF Next State Values
         simulator->updateNextStateValue();
         // Purely Random Simulation
         simulator->setSourceFree(V3_PI, true);
         simulator->setSourceFree(V3_PIO, true);
         // Simulate for One Cycle
         simulator->simulate();
         // Record Simulation Data
         simulator->recordSimValue();
         // Check if Property Asserted
         if (simulator->getSimValue(pId).exist1()) { cycle = i; break; }
      }
      if (V3NtkUD != cycle) break;
      // Report Verification Progress
      if (intactON()) {
         if (!endLineON()) Msg(MSG_IFO) << "\r" + flushSpace + "\r";
         Msg(MSG_IFO) << "Simulation completed under cycle = " << setw(logMaxWidth) << i;
         if (endLineON()) Msg(MSG_IFO) << endl; else Msg(MSG_IFO) << flush;
         // Check if Time Bound Reached
         if (clock() >= timeBound) { cycleReached = i; break; }
      }
   }

   // Report Verification Result
   if (reportON()) {
      runtime = (clock()- runtime) / CLOCKS_PER_SEC;
      if (intactON()) {
         if (endLineON()) Msg(MSG_IFO) << endl;
         else Msg(MSG_IFO) << "\r" << flushSpace << "\r";
      }
      if (V3NtkUD != cycle) Msg(MSG_IFO) << "Counter-example found at cycle = " << ++cycle;
      else Msg(MSG_IFO) << "UNDECIDED at cycle = " << ((clock() >= timeBound) ? cycleReached : _maxDepth);
      if (usageON()) Msg(MSG_IFO) << "  (time = " << setprecision(5) << runtime << "  sec)" << endl;
      if (profileON()) { /* Report some profiling here ... */ }
   }

   // Record CounterExample Trace
   if (V3NtkUD == cycle) return;
   // Compute Pattern Size and Initialize Trace
   V3CexTrace* const cex = new V3CexTrace(cycle); assert (cex);
   _result[pIndex].setCexTrace(cex); assert (_result[pIndex].isCex());
   uint32_t patternSize = 0;
   for (uint32_t i = 0; i < ntk->getInputSize(); ++i) patternSize += ntk->getNetWidth(ntk->getInput(i));
   for (uint32_t i = 0; i < ntk->getInoutSize(); ++i) patternSize += ntk->getNetWidth(ntk->getInout(i));
   if (!patternSize) return;
   // Record Counter-Example
   V3SimTrace pattern(ntk->getInputSize()); V3BitVecX trace(patternSize);
   if (dynamic_cast<V3BvNtk*>(ntk)) {
      for (uint32_t i = 0; i < cycle; ++i) {
         simulator->getSimRecordData(i, pattern);
         uint32_t k = 0;
         for (uint32_t j = 0; j < ntk->getInputSize(); ++j) {
            assert (pattern[j].size() == ntk->getNetWidth(ntk->getInput(j)));
            for (uint32_t x = 0; x < pattern[j].size(); ++x, ++k)
               if ('1' == pattern[j][x]) trace.set1(k);
               else if ('0' == pattern[j][x]) trace.set0(k);
         }
         for (uint32_t j = 0; j < ntk->getInoutSize(); ++j) {
            assert (pattern[j].size() == ntk->getNetWidth(ntk->getInout(j)));
            for (uint32_t x = 0; x < pattern[j].size(); ++x, ++k)
               if ('1' == pattern[j][x]) trace.set1(k);
               else if ('0' == pattern[j][x]) trace.set0(k);
         }
         cex->pushData(trace); trace.clear();
      }
   }
   else {
      const uint32_t p = simulator->getSimValue(pId).first1(); assert (p < simulator->getSimValue(pId).size());
      assert (pattern.size() == trace.size());
      for (uint32_t i = 0; i < cycle; ++i) {
         simulator->getSimRecordData(i, pattern);
         for (uint32_t j = 0; j < pattern.size(); ++j)
            if ('1' == pattern[j][p]) trace.set1(j);
            else if ('0' == pattern[j][p]) trace.set0(j);
         cex->pushData(trace); trace.clear();
      }
   }
}
void cairo_renderer<T>::process(polygon_pattern_symbolizer const& sym,
                                mapnik::feature_impl & feature,
                                proj_transform const& prj_trans)
{
    composite_mode_e comp_op = get<composite_mode_e, keys::comp_op>(sym, feature, common_.vars_);
    std::string filename = get<std::string, keys::file>(sym, feature, common_.vars_);
    value_bool clip = get<value_bool, keys::clip>(sym, feature, common_.vars_);
    value_double simplify_tolerance = get<value_double, keys::simplify_tolerance>(sym, feature, common_.vars_);
    value_double smooth = get<value_double, keys::smooth>(sym, feature, common_.vars_);
    value_double opacity = get<value_double, keys::opacity>(sym, feature, common_.vars_);
    agg::trans_affine image_tr = agg::trans_affine_scaling(common_.scale_factor_);
    auto image_transform = get_optional<transform_type>(sym, keys::image_transform);
    if (image_transform) evaluate_transform(image_tr, feature, common_.vars_, *image_transform);

    cairo_save_restore guard(context_);
    context_.set_operator(comp_op);

    boost::optional<mapnik::marker_ptr> marker = mapnik::marker_cache::instance().find(filename,true);
    if (!marker || !(*marker)) return;

    unsigned offset_x=0;
    unsigned offset_y=0;
    box2d<double> const& clip_box = clipping_extent(common_);
    pattern_alignment_enum alignment = get<pattern_alignment_enum, keys::alignment>(sym, feature, common_.vars_);
    if (alignment == LOCAL_ALIGNMENT)
    {
        double x0 = 0.0;
        double y0 = 0.0;

        if (feature.num_geometries() > 0)
        {
            using clipped_geometry_type = agg::conv_clip_polygon<geometry_type>;
            using path_type = transform_path_adapter<view_transform,clipped_geometry_type>;
            clipped_geometry_type clipped(feature.get_geometry(0));
            clipped.clip_box(clip_box.minx(), clip_box.miny(),
                             clip_box.maxx(), clip_box.maxy());
            path_type path(common_.t_, clipped, prj_trans);
            path.vertex(&x0, &y0);
        }
        offset_x = std::abs(clip_box.width() - x0);
        offset_y = std::abs(clip_box.height() - y0);
    }

    if ((*marker)->is_bitmap())
    {
        cairo_pattern pattern(**((*marker)->get_bitmap_data()), opacity);
        pattern.set_extend(CAIRO_EXTEND_REPEAT);
        pattern.set_origin(offset_x, offset_y);
        context_.set_pattern(pattern);
    }
    else
    {
        mapnik::rasterizer ras;
        image_ptr image = render_pattern(ras, **marker, image_tr, 1.0); //
        cairo_pattern pattern(*image, opacity);
        pattern.set_extend(CAIRO_EXTEND_REPEAT);
        pattern.set_origin(offset_x, offset_y);
        context_.set_pattern(pattern);
    }

    agg::trans_affine tr;
    auto geom_transform = get_optional<transform_type>(sym, keys::geometry_transform);
    if (geom_transform) {
        evaluate_transform(tr, feature, common_.vars_, *geom_transform, common_.scale_factor_);
    }

    vertex_converter<cairo_context,clip_poly_tag,transform_tag,affine_transform_tag,simplify_tag,smooth_tag>
    converter(clip_box, context_,sym,common_.t_,prj_trans,tr,feature,common_.vars_,common_.scale_factor_);

    if (prj_trans.equal() && clip) converter.set<clip_poly_tag>(); //optional clip (default: true)
    converter.set<transform_tag>(); //always transform
    converter.set<affine_transform_tag>();
    if (simplify_tolerance > 0.0) converter.set<simplify_tag>(); // optional simplify converter
    if (smooth > 0.0) converter.set<smooth_tag>(); // optional smooth converter

    for ( geometry_type & geom : feature.paths())
    {
        if (geom.size() > 2)
        {
            converter.apply(geom);
        }
    }
    // fill polygon
    context_.set_fill_rule(CAIRO_FILL_RULE_EVEN_ODD);
    context_.fill();
}
void  agg_renderer<T0,T1>::process(line_pattern_symbolizer const& sym,
                                   mapnik::feature_impl & feature,
                                   proj_transform const& prj_trans)
{

    using color = agg::rgba8;
    using order = agg::order_rgba;
    using blender_type = agg::comp_op_adaptor_rgba_pre<color, order>;
    using pattern_filter_type = agg::pattern_filter_bilinear_rgba8;
    using pattern_type = agg::line_image_pattern<pattern_filter_type>;
    using pixfmt_type = agg::pixfmt_custom_blend_rgba<blender_type, agg::rendering_buffer>;
    using renderer_base = agg::renderer_base<pixfmt_type>;
    using renderer_type = agg::renderer_outline_image<renderer_base, pattern_type>;
    using rasterizer_type = agg::rasterizer_outline_aa<renderer_type>;

    std::string filename = get<std::string>(sym, keys::file, feature, common_.vars_);
    if (filename.empty()) return;
    boost::optional<mapnik::marker_ptr> marker_ptr = marker_cache::instance().find(filename, true);
    if (!marker_ptr || !(*marker_ptr)) return;
    boost::optional<image_ptr> pat;
    // TODO - re-implement at renderer level like polygon_pattern symbolizer
    double opacity = get<value_double>(sym, keys::opacity, feature, common_.vars_,1.0);
    if ((*marker_ptr)->is_bitmap())
    {
        pat = (*marker_ptr)->get_bitmap_data();
    }
    else
    {
        agg::trans_affine image_tr = agg::trans_affine_scaling(common_.scale_factor_);
        auto image_transform = get_optional<transform_type>(sym, keys::image_transform);
        if (image_transform) evaluate_transform(image_tr, feature, common_.vars_, *image_transform);
        pat = render_pattern(*ras_ptr, **marker_ptr, image_tr, 1.0);
    }

    if (!pat) return;

    bool clip = get<value_bool>(sym, keys::clip, feature, common_.vars_, false);
    double offset = get<value_double>(sym, keys::offset, feature, common_.vars_, 0.0);
    double simplify_tolerance = get<value_double>(sym, keys::simplify_tolerance, feature, common_.vars_, 0.0);
    double smooth = get<value_double>(sym, keys::smooth, feature, common_.vars_, false);

    agg::rendering_buffer buf(current_buffer_->raw_data(),current_buffer_->width(),current_buffer_->height(), current_buffer_->width() * 4);
    pixfmt_type pixf(buf);
    pixf.comp_op(static_cast<agg::comp_op_e>(get<composite_mode_e>(sym, keys::comp_op, feature, common_.vars_, src_over)));
    renderer_base ren_base(pixf);
    agg::pattern_filter_bilinear_rgba8 filter;

    pattern_source source(*(*pat), opacity);
    pattern_type pattern (filter,source);
    renderer_type ren(ren_base, pattern);
    rasterizer_type ras(ren);

    agg::trans_affine tr;
    auto transform = get_optional<transform_type>(sym, keys::geometry_transform);
    if (transform) evaluate_transform(tr, feature, common_.vars_, *transform, common_.scale_factor_);

    box2d<double> clip_box = clipping_extent(common_);
    if (clip)
    {
        double padding = (double)(common_.query_extent_.width()/pixmap_.width());
        double half_stroke = (*marker_ptr)->width()/2.0;
        if (half_stroke > 1)
            padding *= half_stroke;
        if (std::fabs(offset) > 0)
            padding *= std::fabs(offset) * 1.2;
        padding *= common_.scale_factor_;
        clip_box.pad(padding);
    }

    using conv_types = boost::mpl::vector<clip_line_tag, transform_tag,
          affine_transform_tag,
          simplify_tag,smooth_tag,
          offset_transform_tag>;
    vertex_converter<box2d<double>, rasterizer_type, line_pattern_symbolizer,
                     view_transform, proj_transform, agg::trans_affine, conv_types, feature_impl>
                     converter(clip_box,ras,sym,common_.t_,prj_trans,tr,feature,common_.vars_,common_.scale_factor_);

    if (clip) converter.set<clip_line_tag>(); //optional clip (default: true)
    converter.set<transform_tag>(); //always transform
    if (simplify_tolerance > 0.0) converter.set<simplify_tag>(); // optional simplify converter
    if (std::fabs(offset) > 0.0) converter.set<offset_transform_tag>(); // parallel offset
    converter.set<affine_transform_tag>(); // optional affine transform
    if (smooth > 0.0) converter.set<smooth_tag>(); // optional smooth converter

    for (geometry_type & geom : feature.paths())
    {
        if (geom.size() > 1)
        {
            converter.apply(geom);
        }
    }
}
Пример #27
0
bool KWebKitPart::openUrl(const QUrl &_u)
{
    QUrl u (_u);

    kDebug() << u;

    // Ignore empty requests...
    if (u.isEmpty())
        return false;

    // If the URL given is a supported local protocol, e.g. "bookmark" but lacks
    // a path component, we set the path to "/" here so that the security context
    // will properly allow access to local resources.
    if (u.host().isEmpty() && u.path().isEmpty()
        && KProtocolInfo::protocolClass(u.scheme()) == QL1S(":local")) {
        u.setPath(QL1S("/"));
    }

    // Do not emit update history when url is typed in since the embedding part
    // should handle that automatically itself. At least Konqueror does that.
    m_emitOpenUrlNotify = false;

    // Pointer to the page object...
    WebPage* p = page();
    Q_ASSERT(p);

    // Handle error conditions...
    if (u.scheme() == QL1S("error")) {
        /**
         * The format of the error url is that two variables are passed in the query:
         * error = int kio error code, errText = QString error text from kio
         * and the URL where the error happened is passed as a sub URL.
         */
        const QUrl mainUrl(u.fragment());

        if (mainUrl.isValid()) {
            QString query = u.query(QUrl::FullyDecoded);
            QRegularExpression pattern("error=(\\d+)&errText=(.*)");
            QRegularExpressionMatch match = pattern.match(query);
            int error = match.captured(1).toInt();
            // error=0 isn't a valid error code, so 0 means it's missing from the URL
            if (error == 0) {
                error = KIO::ERR_UNKNOWN;
            }
            const QString errorText = match.captured(2);

            emit m_browserExtension->setLocationBarUrl(mainUrl.toDisplayString());
            if (p) {
                m_webView->setHtml(p->errorPage(error, errorText, mainUrl));
                return true;
            }
        }

        return false;
    }

    KParts::BrowserArguments bargs (m_browserExtension->browserArguments());
    KParts::OpenUrlArguments args (arguments());

    if (u != *globalBlankUrl) {
        // Get the SSL information sent, if any...
        if (args.metaData().contains(QL1S("ssl_in_use"))) {
            WebSslInfo sslInfo;
            sslInfo.restoreFrom(KIO::MetaData(args.metaData()).toVariant());
            sslInfo.setUrl(u);
            p->setSslInfo(sslInfo);
        }
    }

    // Set URL in KParts before emitting started; konq plugins rely on that.
    setUrl(u);
    m_doLoadFinishedActions = true;
    m_webView->loadUrl(u, args, bargs);
    return true;
}
Пример #28
0
 inline message recv(Types&&... types)
 {
     return a_->recv(pattern().match(std::forward<Types>(types)...));
 }
Пример #29
0
/*
================
Sys_ListFiles
================
*/
int Sys_ListFiles( const char* directory, const char* extension, idStrList& list )
{
	struct dirent* d;
	DIR* fdir;
	bool dironly = false;
	char search[MAX_OSPATH];
	struct stat st;
	bool debug;
	
	list.Clear();
	
	debug = cvarSystem->GetCVarBool( "fs_debug" );
	// DG: we use fnmatch for shell-style pattern matching
	// so the pattern should at least contain "*" to match everything,
	// the extension will be added behind that (if !dironly)
	idStr pattern( "*" );
	
	// passing a slash as extension will find directories
	if( extension[0] == '/' && extension[1] == 0 )
	{
		dironly = true;
	}
	else
	{
		// so we have *<extension>, the same as in the windows code basically
		pattern += extension;
	}
	// DG end
	
	// NOTE: case sensitivity of directory path can screw us up here
	if( ( fdir = opendir( directory ) ) == NULL )
	{
		if( debug )
		{
			common->Printf( "Sys_ListFiles: opendir %s failed\n", directory );
		}
		return -1;
	}
	
	// DG: use readdir_r instead of readdir for thread safety
	// the following lines are from the readdir_r manpage.. fscking ugly.
	int nameMax = pathconf( directory, _PC_NAME_MAX );
	if( nameMax == -1 )
		nameMax = 255;
	int direntLen = offsetof( struct dirent, d_name ) + nameMax + 1;
	
	struct dirent* entry = ( struct dirent* )Mem_Alloc( direntLen, TAG_CRAP );
	
	if( entry == NULL )
	{
		common->Warning( "Sys_ListFiles: Mem_Alloc for entry failed!" );
		closedir( fdir );
		return 0;
	}
	
	while( readdir_r( fdir, entry, &d ) == 0 && d != NULL )
	{
		// DG end
		idStr::snPrintf( search, sizeof( search ), "%s/%s", directory, d->d_name );
		if( stat( search, &st ) == -1 )
			continue;
		if( !dironly )
		{
			// DG: the original code didn't work because d3 bfg abuses the extension
			// to match whole filenames and patterns in the savegame-code, not just file extensions...
			// so just use fnmatch() which supports matching shell wildcard patterns ("*.foo" etc)
			// if we should ever need case insensitivity, use FNM_CASEFOLD as third flag
			if( fnmatch( pattern.c_str(), d->d_name, 0 ) != 0 )
				continue;
			// DG end
		}
		if( ( dironly && !( st.st_mode & S_IFDIR ) ) ||
				( !dironly && ( st.st_mode & S_IFDIR ) ) )
			continue;
			
		list.Append( d->d_name );
	}
	
	closedir( fdir );
	Mem_Free( entry );
	
	if( debug )
	{
		common->Printf( "Sys_ListFiles: %d entries in %s\n", list.Num(), directory );
	}
	
	return list.Num();
}
Пример #30
0
bool RegExpController::loadFromFile(const QString &filename)
{
    QFile file(filename);
    if (!file.open(QFile::ReadOnly|QFile::Text))
    {
        return false;
    }

    QRegExp keyValuePattern("\\s*(\\w+)\\s*=\\s*(.*)");
    QTextStream stream(&file);
    QString line;
    QString pattern("");
    QRegExp::PatternSyntax patternSyntax = QRegExp::RegExp;
    QRegExp::CaretMode caretMode = QRegExp::CaretAtZero;
    Qt::CaseSensitivity caseSensitivity = Qt::CaseSensitive;
    bool minimal = false;
    QString key;
    QString value;
    int lineNum = 0;
    bool parseSuccessful = false;

    _fileError.clear();

    try
    {
        while (!stream.atEnd())
        {
            lineNum ++;
            line = stream.readLine().trimmed();
            if (!keyValuePattern.exactMatch(line))
            {
                continue;
            }
            key = keyValuePattern.cap(1);
            value = keyValuePattern.cap(2).trimmed();
            // qDebug() << QString("%1 = %2").arg(key).arg(value);
            if (key.compare("pattern", Qt::CaseInsensitive) == 0)
            {
                pattern = value;
            }
            else if (key.compare("patternSyntax", Qt::CaseInsensitive) == 0)
            {
                patternSyntax = patternSyntaxStringToId(value);
            }
            else if (key.compare("caretMode", Qt::CaseInsensitive) == 0)
            {
                caretMode = caretModeStringToId(value);
            }
            else if (key.compare("caseSensitivity", Qt::CaseInsensitive) == 0)
            {
                caseSensitivity = STRING_TO_BOOL(value) ? Qt::CaseSensitive : Qt::CaseInsensitive;
            }
            else if (key.compare("minimal", Qt::CaseInsensitive) == 0)
            {
                minimal = STRING_TO_BOOL(value);
            }
        }
        parseSuccessful = true;
    }
    catch (...)
    {
        _fileError = QString("Error(line#=%1) bad syntax or unknown items").arg(lineNum);
    }

    file.close();

    if (parseSuccessful)
    {
        _regexp->setPattern(pattern);
        _regexp->setPatternSyntax(patternSyntax);
        _caretMode = caretMode;
        _regexp->setCaseSensitivity(caseSensitivity);
        _regexp->setMinimal(minimal);
        _filename = filename;
    }

    return parseSuccessful;
}