void AMEXAFSScanConfiguration::dbLoadRegions(const QString &exafsRegionsString){ if(exafsRegionsString.isEmpty()) return; QStringList allRegions = exafsRegionsString.split("\n", QString::SkipEmptyParts); QStringList oneRegion; bool addRegionSuccess = false; for(int x = 0; x < allRegions.count(); x++){ oneRegion = allRegions.at(x).split(",", QString::SkipEmptyParts); // Legacy Acquaman XAS settings (version 1.0) if (oneRegion.count() == 3) addRegionSuccess = addRegion(x, oneRegion.at(0).toDouble(), oneRegion.at(1).toDouble(), oneRegion.at(2).toDouble()); // Another legacy Acquaman XAS settings version 1.1 else if (oneRegion.at(0) == "xasVersion1.1"){ addRegionSuccess = addRegion(x, oneRegion.at(1).toDouble(), oneRegion.at(2).toDouble(), oneRegion.at(3).toDouble(), oneRegion.at(6).toDouble()); addRegionSuccess &= setRegionElasticStart(x, oneRegion.at(4).toInt() == 1 ? true : false); addRegionSuccess &= setRegionElasticEnd(x, oneRegion.at(5).toInt() == 1 ? true : false); } // Beginning of a more succinct usage of AMRegions. Version 1.0 else if (oneRegion.at(0) == "regionsVersion1.0"){ addRegionSuccess = addRegion(x, oneRegion.at(1).toDouble(), oneRegion.at(2).toDouble(), oneRegion.at(3).toDouble(), oneRegion.at(6).toDouble()); addRegionSuccess &= setRegionElasticStart(x, oneRegion.at(4).toInt() == 1 ? true : false); addRegionSuccess &= setRegionElasticEnd(x, oneRegion.at(5).toInt() == 1 ? true : false); addRegionSuccess &= setRegionUnits(x, oneRegion.at(7)); addRegionSuccess &= setRegionTimeUnits(x, oneRegion.at(8)); } else if (oneRegion.at(0) == "exafsVersion1.0"){ addRegionSuccess = addRegion(x, oneRegion.at(4).toDouble(), oneRegion.at(5).toDouble(), oneRegion.at(6).toDouble(), oneRegion.at(9).toDouble()); addRegionSuccess &= setRegionType(x, oneRegion.at(1) == "Energy" ? AMEXAFSRegion::Energy : AMEXAFSRegion::kSpace); addRegionSuccess &= setRegionIsRelative(x, oneRegion.at(3).toInt() == 1 ? true : false); addRegionSuccess &= setRegionEdgeEnergy(x, oneRegion.at(2).toDouble()); addRegionSuccess &= setRegionElasticStart(x, oneRegion.at(7).toInt() == 1 ? true : false); addRegionSuccess &= setRegionElasticEnd(x, oneRegion.at(8).toInt() == 1 ? true : false); addRegionSuccess &= setRegionUnits(x, oneRegion.at(10)); addRegionSuccess &= setRegionTimeUnits(x, oneRegion.at(11)); if (x == 0){ exafsRegions()->setDefaultEdgeEnergy(regionEdgeEnergy(x)); exafsRegions()->setDefaultIsRelative(regionIsRelative(x)); } } if (!addRegionSuccess) AMErrorMon::report(AMErrorReport(this, AMErrorReport::Alert, 0, QString("There was an error reloading the scan region #%1, when reloading this scan from the database. Your database might be corrupted. Please report this bug to the Acquaman developers.").arg(x))); } }
forAllConstIter(EdgeMap<label>, mapEdgesRegion_, iter) { const edge& e = iter.key(); const label& regionI = iter(); const label startI = e.start(); const label endI = e.end(); addRegion(regionI, boundaryPointRegions[startI]); addRegion(regionI, boundaryPointRegions[endI]); }
void ImageOverlayRegionFinder::findRegions(bool optimizeForPowersOf2) { m_regions.clear(); if (!m_overlay.isValid()) { return; } int rows = m_overlay.getRows(); int columns = m_overlay.getColumns(); unsigned char *data = m_overlay.getData(); // Màscara que indica els píxels visitats QBitArray mask(rows * columns); for (int row = 0, i = 0; row < rows; row++) { for (int column = 0; column < columns; column++, i++) { // Si trobem un objecte no tractat if (data[i] > 0 && !mask.testBit(i)) { QRect region = growRegion(row, column, mask); addPadding(region); addRegion(region, optimizeForPowersOf2); removePadding(region); fillMaskForRegion(mask, region); } } } }
bool CCSRegions::addIfNew(CCSRegion* pRegion) { if (findRegion(pRegion) != -1) return true; return addRegion(pRegion); }
void TextParserImpl::leaveScheme(int lno, SMatches *match, const SchemeNode *schemeNode) { int i; if (schemeNode->innerRegion == true){ leaveScheme(gy, match->s[0], match->s[0], schemeNode->region); } for (i = 0; i < match->cMatch; i++) addRegion(gy, match->s[i], match->e[i], schemeNode->regione[i]); for (i = 0; i < match->cnMatch; i++) addRegion(gy, match->ns[i], match->ne[i], schemeNode->regionen[i]); if (schemeNode->innerRegion == false){ leaveScheme(gy, match->s[0], match->e[0], schemeNode->region); } }
bool SkPictureRecord::clipRegion(const SkRegion& region, SkRegion::Op op) { addDraw(CLIP_REGION); addRegion(region); addInt(ClipParams_pack(op, false)); recordRestoreOffsetPlaceholder(op); validate(); return this->INHERITED::clipRegion(region, op); }
bool PolyRegions::readFepBoundaries(const std::string& filename) { SEISCOMP_DEBUG("reading boundary polygons from file: %s", filename.c_str()); std::ifstream infile(filename.c_str()); if (infile.bad()) return false; boost::regex vertexLine("^\\s*([-+]?[0-9]*\\.?[0-9]+)\\s+([-+]?[0-9]*\\.?[0-9]+)(?:\\s+([^\\d\\s].*)$|\\s*$)"); boost::regex LLine("^\\s*L\\s+(.*)$"); boost::smatch what; std::string line; bool newPolygon = true; GeoFeature *pr = NULL; OPT(Vertex) last; while(std::getline(infile, line)) { if (newPolygon){ pr = new GeoFeature(); newPolygon = false; } if ( boost::regex_match(line, what, vertexLine) ) { if ( last ) pr->addVertex(*last); last = Vertex(atof(what.str(2).c_str()), atof(what.str(1).c_str())); } else if (boost::regex_match(line, what, LLine)) { if ( last && pr->vertices().size() > 0 ) { if ( *last != pr->vertices().back() ) pr->addVertex(*last); } if ( pr->vertices().size() < 3 ) delete pr; else { pr->setName(what.str(1)); pr->setClosedPolygon(true); addRegion(pr); if ( pr->area() < 0 ) SEISCOMP_WARNING("Polygon %s is defined clockwise", pr->name().c_str()); } last = Core::None; newPolygon = true; } else { //std::cout << "Warning: line ignored: " << line << std::endl; } } return true; }
bool SkPictureRecord::clipRegion(const SkRegion& region, SkRegion::Op op) { addDraw(CLIP_REGION); addRegion(region); addInt(op); this->recordOffsetForRestore(op); validate(); return this->INHERITED::clipRegion(region, op); }
int TextParserImpl::searchKW(const SchemeNode *node, int no, int lowlen, int hilen) { if (!node->kwList->num) return MATCH_NOTHING; if (node->kwList->minKeywordLength+gx > lowlen) return MATCH_NOTHING; if (gx < lowlen && !node->kwList->firstChar->inClass((*str)[gx])) return MATCH_NOTHING; int left = 0; int right = node->kwList->num; while(true){ int pos = left + (right-left)/2; int kwlen = node->kwList->kwList[pos].keyword->length(); if (lowlen < gx+kwlen) kwlen = lowlen-gx; int cr; if (node->kwList->matchCase) cr = node->kwList->kwList[pos].keyword->compareTo(DString(*str, gx, kwlen)); else cr = node->kwList->kwList[pos].keyword->compareToIgnoreCase(DString(*str, gx, kwlen)); if (cr == 0 && right-left == 1){ bool badbound = false; if (!node->kwList->kwList[pos].isSymbol){ if (!node->worddiv){ if (gx && (Character::isLetterOrDigit((*str)[gx-1]) || (*str)[gx-1] == '_')) badbound = true; if (gx + kwlen < lowlen && (Character::isLetterOrDigit((*str)[gx + kwlen]) || (*str)[gx + kwlen] == '_')) badbound = true; }else{ // custom check for word bound if (gx && !node->worddiv->inClass((*str)[gx-1])) badbound = true; if (gx + kwlen < lowlen && !node->worddiv->inClass((*str)[gx + kwlen])) badbound = true; }; }; if (!badbound){ CLR_TRACE("TextParserImpl", "KW matched. gx=%d, region=%s", gx, node->kwList->kwList[pos].region->getName()->getChars()); addRegion(gy, gx, gx + kwlen, node->kwList->kwList[pos].region); gx += kwlen; return MATCH_RE; }; }; if (right-left == 1){ left = node->kwList->kwList[pos].ssShorter; if (left != -1){ right = left+1; continue; }; break; }; if (cr == 1) right = pos; if (cr == 0 || cr == -1) left = pos; }; return MATCH_NOTHING; };
bool SkPictureRecord::clipRegion(const SkRegion& region, SkRegion::Op op) { addDraw(CLIP_REGION); addRegion(region); addInt(op); size_t offset = fWriter.size(); addInt(fRestoreOffsetStack.top()); fRestoreOffsetStack.top() = offset; validate(); return this->INHERITED::clipRegion(region, op); }
CRegion* CRegionManager::addRegion(int cx,int cy,int sx,int sy) { CRegion* pRegion = new CRegion(cx,cy,sx,sy); if ( pRegion ) { pRegion->addProperty("region_type",0); pRegion->addProperty("region_flag",0); addRegion(pRegion); return pRegion; } return NULL; }
void G2DRegionGraph::makeWatershedRegions(const GImage* pImage) { GImage gradMag; gradMag.gradientMagnitudeImage(pImage); GImage* pMask = regionMask(); int x, y, u, v, du, dv; size_t region, other; for(y = 0; y < (int)pImage->height(); y++) { for(x = 0; x < (int)pImage->width(); x++) { u = x; v = y; do { region = pMask->pixel(u, v); if(region != 0xffffffff) break; PickTobogganDirection(&gradMag, u, v, &du, &dv); u += du; v += dv; } while(du != 0 || dv != 0); if(region == 0xffffffff) { region = addRegion(); setMaskPixel(u, v, pImage->pixel(u, v), region); } u = x; v = y; do { if(pMask->pixel(u, v) != 0xffffffff) break; setMaskPixel(u, v, pImage->pixel(u, v), region); PickTobogganDirection(&gradMag, u, v, &du, &dv); u += du; v += dv; } while(du != 0 || dv != 0); if(x > 0) { other = pMask->pixel(x - 1, y); if(other != region) makeNeighbors(region, other); } if(y > 0) { other = pMask->pixel(x, y - 1); if(other != region) makeNeighbors(region, other); } } } }
void FaceDatabaseProvider::update() { QAbstractItemModel *faceGroupsModel = m_faceDatabase->faceGroups(XQFaceDatabase::UnnamedGroup); clear(); m_suspectedRegions.clear(); /* Add to our hash all the (faceid, <regions>) */ for (int faceGroupRow = 0; faceGroupRow < faceGroupsModel->rowCount(); faceGroupRow++) { XQFaceGroup faceGroup = m_faceDatabase->faceGroup(faceGroupsModel->index(faceGroupRow, 0).data().toString()); QAbstractItemModel *facesModel = faceGroup.faces(); for (int faceRow = 0; faceRow < facesModel->rowCount(); faceRow++) { QString sourceId = facesModel->index(faceRow, 0).data().toString(); XQFaceRegion faceRegion = faceGroup.faceRegion(sourceId); QStringList faceIds = faceRegion.faceIds(); if (faceIds.isEmpty()) { addRegion(UNKNOWN_CONTACT, faceRegion); continue; } foreach(QString faceId, faceIds) { addRegion(faceId, faceRegion); } } }
static void retrace_malloc(trace::Call &call) { size_t size = call.arg(0).toUInt(); unsigned long long address = call.ret->toUIntPtr(); if (!address) { return; } void *buffer = malloc(size); if (!buffer) { std::cerr << "error: failed to allocated " << size << " bytes."; return; } addRegion(address, buffer, size); }
void CityRegionImplementation::setRadius(float rad) { if (regions.size() <= 0) return; ManagedReference<Region*> oldRegion = regions.get(0).get(); ManagedReference<Region*> newRegion = addRegion(oldRegion->getPositionX(), oldRegion->getPositionY(), rad, true); Locker locker(oldRegion, _this.getReferenceUnsafeStaticCast()); zone->removeObject(oldRegion, NULL, false); regions.drop(oldRegion); oldRegion->destroyObjectFromDatabase(true); locker.release(); if (registered) { Reference<PlanetMapCategory*> cityCat = TemplateManager::instance()->getPlanetMapCategoryByName("city"); newRegion->setPlanetMapCategory(cityCat); newRegion->getZone()->registerObjectWithPlanetaryMap(newRegion); } }
int TextParserImpl::searchRE(SchemeImpl *cscheme, int no, int lowLen, int hiLen) { int i, re_result; SchemeImpl *ssubst = null; SMatches match; ParseCache *OldCacheF = null; ParseCache *OldCacheP = null; ParseCache *ResF = null; ParseCache *ResP = null; CLR_TRACE("TextParserImpl", "searchRE: entered scheme \"%s\"", cscheme->getName()->getChars()); if (!cscheme){ return MATCH_NOTHING; } for(int idx = 0; idx < cscheme->nodes.size(); idx++){ SchemeNode *schemeNode = cscheme->nodes.elementAt(idx); CLR_TRACE("TextParserImpl", "searchRE: processing node:%d/%d, type:%s", idx+1, cscheme->nodes.size(), schemeNodeTypeNames[schemeNode->type]); switch(schemeNode->type){ case SNT_INHERIT: if (!schemeNode->scheme) break; ssubst = vtlist->pushvirt(schemeNode->scheme); if (!ssubst){ bool b = vtlist->push(schemeNode); re_result = searchRE(schemeNode->scheme, no, lowLen, hiLen); if (b) vtlist->pop(); }else{ re_result = searchRE(ssubst, no, lowLen, hiLen); vtlist->popvirt(); }; if (re_result != MATCH_NOTHING) return re_result; break; case SNT_KEYWORDS: if (searchKW(schemeNode, no, lowLen, hiLen) == MATCH_RE) return MATCH_RE; break; case SNT_RE: if (!schemeNode->start->parse(str, gx, schemeNode->lowPriority?lowLen:hiLen, &match, schemeStart)) break; CLR_TRACE("TextParserImpl", "RE matched. gx=%d", gx); for (i = 0; i < match.cMatch; i++) addRegion(gy, match.s[i], match.e[i], schemeNode->regions[i]); for (i = 0; i < match.cnMatch; i++) addRegion(gy, match.ns[i], match.ne[i], schemeNode->regionsn[i]); /* skips regexp if it has zero length */ if (match.e[0] == match.s[0]) break; gx = match.e[0]; return MATCH_RE; case SNT_SCHEME:{ if (!schemeNode->scheme) break; if (!schemeNode->start->parse(str, gx, schemeNode->lowPriority?lowLen:hiLen, &match, schemeStart)) break; CLR_TRACE("TextParserImpl", "Scheme matched. gx=%d", gx); gx = match.e[0]; ssubst = vtlist->pushvirt(schemeNode->scheme); if (!ssubst) ssubst = schemeNode->scheme; SString *backLine = new SString(str); if (updateCache){ ResF = forward; ResP = parent; if (forward){ forward->next = new ParseCache; forward->next->prev = forward; OldCacheF = forward->next; OldCacheP = parent?parent:forward->parent; parent = forward->next; forward = null; }else{ forward = new ParseCache; parent->children = forward; OldCacheF = forward; OldCacheP = parent; parent = forward; forward = null; }; OldCacheF->parent = OldCacheP; OldCacheF->sline = gy+1; OldCacheF->eline = 0x7FFFFFFF; OldCacheF->scheme = ssubst; OldCacheF->matchstart = match; OldCacheF->clender = schemeNode; OldCacheF->backLine = backLine; }; int ogy = gy; bool zeroLength; SchemeImpl *o_scheme = baseScheme; int o_schemeStart = schemeStart; SMatches o_matchend = matchend; SMatches *o_match; DString *o_str; schemeNode->end->getBackTrace((const String**)&o_str, &o_match); baseScheme = ssubst; schemeStart = gx; schemeNode->end->setBackTrace(backLine, &match); enterScheme(no, &match, schemeNode); colorize(schemeNode->end, schemeNode->lowContentPriority); if (gy < gy2){ leaveScheme(gy, &matchend, schemeNode); }; gx = matchend.e[0]; /* (empty-block.test) Check if the consumed scheme is zero-length */ zeroLength = (match.s[0] == matchend.e[0] && ogy == gy); schemeNode->end->setBackTrace(o_str, o_match); matchend = o_matchend; schemeStart = o_schemeStart; baseScheme = o_scheme; if (updateCache){ if (ogy == gy){ delete OldCacheF; if (ResF) ResF->next = null; else ResP->children = null; forward = ResF; parent = ResP; }else{ OldCacheF->eline = gy; OldCacheF->vcache = vtlist->store(); forward = OldCacheF; parent = OldCacheP; }; }else{ delete backLine; }; if (ssubst != schemeNode->scheme){ vtlist->popvirt(); } /* (empty-block.test) skips block if it has zero length and spread over single line */ if (zeroLength) break; return MATCH_SCHEME; }; }; }; return MATCH_NOTHING; };
bool ZInstrument::loadSfz(const QString& s) { _program = 0; QFile f(s); if (!f.open(QIODevice::ReadOnly)) { qDebug("ZInstrument: cannot load %s", qPrintable(s)); return false; } QFileInfo fi(f); QString path = fi.absolutePath(); qint64 total = fi.size(); QString sample; SfzRegion r; SfzRegion g; // group r.init(path); g.init(path); bool groupMode = false; zerberus->setLoadProgress(0); while (!f.atEnd()) { QByteArray ba = f.readLine(); zerberus->setLoadProgress(((qreal)f.pos() * 100) / total); ba = ba.simplified(); if (ba.isEmpty() || ba.startsWith("//")) continue; if (zerberus->loadWasCanceled()) return false; if (ba.startsWith("<group>")) { if (!groupMode && !r.isEmpty()) addRegion(r); g.init(path); r.init(path); groupMode = true; ba = ba.mid(7); } else if (ba.startsWith("<region>")) { if (groupMode) { g = r; groupMode = false; } else { if (!r.isEmpty()) addRegion(r); r = g; // initialize next region with group values } ba = ba.mid(8); } QRegularExpression re("\\s?(\\w+)="); QRegularExpressionMatchIterator i = re.globalMatch(ba); while (i.hasNext()) { QRegularExpressionMatch match = i.next(); int si = match.capturedEnd(); int ei; if (i.hasNext()) { QRegularExpressionMatch nextMatch = i.peekNext(); ei = nextMatch.capturedStart(); } else ei = ba.size(); QString s = ba.mid(si, ei-si); r.readOp(match.captured(1), s); } } zerberus->setLoadProgress(100); if (!groupMode && !r.isEmpty()) addRegion(r); return true; }
std::shared_ptr<TextureAtlas> GdxTextureAtlasLoader::load(std::istream& in) const { assert(_textureManager); auto atlas = std::make_shared<TextureAtlas>(); std::string line; // texture name while(line.empty()) { std::getline(in, line); StringUtils::trim(line); } if(_textureManager) { atlas->setTexture(_textureManager->load(line)); } bool inRegion = false; TextureRegion region; while(in) { std::getline(in, line); std::size_t sep = line.find(':'); std::string n = line.substr(0, sep); std::string v = line.substr(sep+1); if(!inRegion) { if(sep == std::string::npos) { inRegion = true; region = TextureRegion(); region.name = line; } else { // header value } } else { if(line.substr(0, 1) == " ") { StringUtils::trim(n); StringUtils::trim(v); if(n == "rotate") { region.rotate = v == "true"; } else if(n == "xy") { sep = v.find(','); region.x = std::stoi(v.substr(0, sep)); region.y = std::stoi(v.substr(sep+1)); } else if(n == "size") { sep = v.find(','); region.width = std::stoi(v.substr(0, sep)); region.height = std::stoi(v.substr(sep+1)); } else if(n == "orig") { sep = v.find(','); region.originalWidth = std::stoi(v.substr(0, sep)); region.originalHeight = std::stoi(v.substr(sep+1)); } else if(n == "offset") { sep = v.find(','); region.offsetX = std::stoi(v.substr(0, sep)); region.offsetY = std::stoi(v.substr(sep+1)); } else if(n == "index") { region.index = std::stoi(v); } } else { region.origin = TextureRegion::Origin::TopLeft; atlas->addRegion(region); region = TextureRegion(); region.name = line; } } } return std::move(atlas); }
bool TextParserImpl::colorize(CRegExp *root_end_re, bool lowContentPriority) { len = -1; /* Direct check for recursion level */ if (stackLevel > MAX_RECURSION_LEVEL) { return true; } stackLevel++; for (; gy < gy2; ){ CLR_TRACE("TextParserImpl", "colorize: line no %d", gy); // clears line at start, // prevents multiple requests on each line if (clearLine != gy){ clearLine = gy; str = lineSource->getLine(gy); if (str == null){ throw Exception(StringBuffer("null String passed into the parser: ")+SString(gy)); //!!unreachable code //gy = gy2; break; }; regionHandler->clearLine(gy, str); }; // hack to include invisible regions in start of block // when parsing with cache information if (!invisibleSchemesFilled){ invisibleSchemesFilled = true; fillInvisibleSchemes(parent); }; // updates length if (len < 0) len = str->length(); endLine = gy; // searches for the end of parent block int res = 0; if (root_end_re) res = root_end_re->parse(str, gx, len, &matchend, schemeStart); if (!res) matchend.s[0] = matchend.e[0] = len; int parent_len = len; /* BUG: <regexp match="/.{3}\M$/" region="def:Error" priority="low"/> $ at the end of current schema */ if (lowContentPriority){ len = matchend.s[0]; } int ret = LINE_NEXT; for (; gx <= matchend.s[0];){ // '<' or '<=' ??? if (breakParsing){ gy = gy2; break; }; if (picked != null && gx+11 <= matchend.s[0] && (*str)[gx] == 'C'){ int ci; static char id[] = "fnq%Qtrjhg"; for(ci = 0; ci < 10; ci++) if ((*str)[gx+1+ci] != id[ci]-5) break; if (ci == 10){ addRegion(gy, gx, gx+11, picked); gx += 11; continue; }; }; int oy = gy; int re_result = searchRE(baseScheme, gy, matchend.s[0], len); if ((re_result == MATCH_SCHEME && (oy != gy || matchend.s[0] < gx)) || (re_result == MATCH_RE && matchend.s[0] < gx)){ len = -1; ret = LINE_REPARSE; break; }; if (oy == gy) len = parent_len; if (re_result == MATCH_NOTHING) gx++; }; if (ret == LINE_REPARSE) continue; schemeStart = -1; if (res) { stackLevel--; return true; } len = -1; gy++; gx=0; } stackLevel--; return true; };
bool ZInstrument::loadSfz(const QString& s) { _program = 0; QFileInfo fi(s); QString path = fi.absolutePath(); QStringList fileContents = readFile(s); if (fileContents.empty()) { return false; } SfzControl c; c.init(); c.defines.clear(); for (int i = 0;i < 128; i++) c.set_cc[i] = -1; int idx = 0; bool inBlockComment = false; // preprocessor while(idx < fileContents.size()) { QRegularExpression findWithSpaces("\"(.+)\""); QRegularExpression comment("//.*$"); QRegularExpression trailingSpacesOrTab("^[\\s\\t]*"); QRegularExpressionMatch foundWithSpaces; QString curLine = fileContents[idx]; QString curLineCopy = curLine; bool nextIsImportant = false; int idxBlockComment = 0; int from = 0; for (QChar chr : curLineCopy) { bool terminated = false; if (nextIsImportant) { nextIsImportant = false; if (inBlockComment && chr == '/') { // found block end inBlockComment = false; terminated = true; curLine.remove(from, idxBlockComment - from + 1); idxBlockComment = from - 1; } else if (!inBlockComment && chr == '*') { // found block start inBlockComment = true; terminated = true; from = idxBlockComment - 1; } } if (!terminated && inBlockComment && chr == '*') nextIsImportant = true; else if (!terminated && !inBlockComment && chr == '/') nextIsImportant = true; idxBlockComment++; } if (inBlockComment) curLine.remove(from, curLine.size() - from); curLine = curLine.remove(comment); curLine.remove(trailingSpacesOrTab); fileContents[idx] = curLine; if (curLine.startsWith("#define")) { QStringList define = curLine.split(" "); foundWithSpaces = findWithSpaces.match(curLine); if (define.size() == 3) c.defines.insert(std::pair<QString, QString>(define[1], define[2])); else if(foundWithSpaces.hasMatch()) c.defines.insert(std::pair<QString, QString>(define[1], foundWithSpaces.captured(1))); fileContents.removeAt(idx); } else if (curLine.startsWith("#include")) { foundWithSpaces = findWithSpaces.match(curLine); if (foundWithSpaces.hasMatch()) { QString newFilename = foundWithSpaces.captured(1); for(auto define : c.defines) { newFilename.replace(define.first, define.second); } QStringList newFileContents = readFile(path + "/" + newFilename); if (newFileContents.empty()) return false; int offset = 1; for (QString newFileLine : newFileContents) { fileContents.insert(idx+offset, newFileLine); offset++; } fileContents.removeAt(idx); } } else if (curLine.isEmpty()) fileContents.removeAt(idx); else idx++; } int total = fileContents.size(); SfzRegion r; SfzRegion g; // group SfzRegion glob; r.init(path); g.init(path); glob.init(path); bool groupMode = false; bool globMode = false; zerberus->setLoadProgress(0); for (int idx = 0; idx < fileContents.size(); idx++) { QString curLine = fileContents[idx]; zerberus->setLoadProgress(((qreal) idx * 100) / (qreal) total); if (zerberus->loadWasCanceled()) return false; if (curLine.startsWith("<global>")) { if (!globMode && !groupMode && !r.isEmpty()) addRegion(r); glob.init(path); g.init(path); // global also resets group r.init(path); globMode = true; } if (curLine.startsWith("<group>")) { if (!groupMode && !globMode && !r.isEmpty()) addRegion(r); g.init(path); if (globMode) { glob = r; globMode = false; } else { r = glob; // initialize group with global values } groupMode = true; curLine = curLine.mid(7); } else if (curLine.startsWith("<region>")) { if (groupMode) { g = r; groupMode = false; } else if (globMode) { glob = r; g = glob; globMode = false; } else { if (!r.isEmpty()) addRegion(r); r = g; // initialize next region with group values } curLine = curLine.mid(8); } else if (curLine.startsWith("<control>")) c.init(); QRegularExpression re("\\s?([\\w\\$]+)="); // defines often use the $-sign QRegularExpressionMatchIterator i = re.globalMatch(curLine); while (i.hasNext()) { QRegularExpressionMatch match = i.next(); int si = match.capturedEnd(); int ei; if (i.hasNext()) { QRegularExpressionMatch nextMatch = i.peekNext(); ei = nextMatch.capturedStart(); } else ei = curLine.size(); QString s = curLine.mid(si, ei-si); r.readOp(match.captured(1), s, c); } } for (int i = 0; i < 128; i++) _setcc[i] = c.set_cc[i]; zerberus->setLoadProgress(100); if (!groupMode && !globMode && !r.isEmpty()) addRegion(r); return true; }
IVariant::SharedPtr VariantList::buildCompoundVariant(const position startPosition, const std::string& referenceString, const std::vector< IVariant::SharedPtr >& variants) { position referenceEndPosition = referenceString.size() + startPosition; auto compoundVariantPtr = std::make_shared< Variant::SharedPtr >(); std::unordered_map< std::string, IAllele::SharedPtr > sequenceAlleleMap; std::vector< std::string > sequenceKeyOrder; std::vector< Region::SharedPtr > regionPtrs; // since this is a "compound variant" we know that there is going to be more than one reference allele. // They may be the same sequence but they will come from different variants and therefore we want to // create an equivalentAllele and add all the variant's reference alleles auto equivalentRefAllelePtr = std::make_shared< EquivalentAllele >(referenceString); // loop over all the variants for (auto variantPtr : variants) { for (Region::SharedPtr regionPtr : variantPtr->getRegions()) { regionPtrs.emplace_back(regionPtr); } // calculate the reference padding and then add it to the allele and add the allele to the equivalentRefAllele uint16_t refPaddingPrefix = variantPtr->getPosition() - startPosition; uint16_t refPaddingSuffix = referenceString.size() - (refPaddingPrefix + variantPtr->getRefAllelePtr()->getLength()); variantPtr->getRefAllelePtr()->setAlleleMetaData(std::make_shared< AlleleMetaData >(refPaddingPrefix, refPaddingSuffix)); equivalentRefAllelePtr->addAllele(variantPtr->getRefAllelePtr()); // loop over all the alts in the variants for (auto altAllelePtr : variantPtr->getAltAllelePtrs()) { std::string altString = std::string(altAllelePtr->getSequence()); // basically we are replacing the variant's reference with the alt within the aggrigated reference (referenceString) // it's complicated to explain in words but if you follow the code it isn't too bad std::string variantString = referenceString; variantString.erase(variantPtr->getPosition() - startPosition, variantPtr->getRefAllelePtr()->getSequenceString().size()); variantString.insert(variantPtr->getPosition() - startPosition, altString); altAllelePtr->setSequence(variantString); // calculate padding for the alt allele and add it to the allele uint32_t paddingPrefix = variantPtr->getPosition() - startPosition; uint32_t paddingSuffix = variantString.size() - (altString.size() + paddingPrefix); altAllelePtr->setAlleleMetaData(std::make_shared< AlleleMetaData >(paddingPrefix, paddingSuffix)); // if this sequence is not in the map then add it. If it is in the map then // switch it with an equivalentAllele. The equivalentAllele keeps track of // alleles that have the same sequence but are either in different vcfs or // are on different lines of the same vcf. Keeping track of these types // of alleles make it possible to reconstruct the output vcfs to match // the input vcfs exactly. auto seqAlleleIter = sequenceAlleleMap.find(altAllelePtr->getSequenceString()); if (seqAlleleIter != sequenceAlleleMap.end()) // if this is not the first time we have seen this allele sequence { auto equivalentAllelePtr = std::dynamic_pointer_cast< EquivalentAllele >(seqAlleleIter->second); if (!equivalentAllelePtr) // if the seqAllele is not an equivalentallele then create a new one, add the allele in the map and then add the equivalentallele it to the map { equivalentAllelePtr = std::make_shared< EquivalentAllele >(altAllelePtr->getSequenceString()); equivalentAllelePtr->addAllele(seqAlleleIter->second); sequenceAlleleMap[altAllelePtr->getSequenceString()] = equivalentAllelePtr; } equivalentAllelePtr->addAllele(altAllelePtr); } else // if this is the first time we have seen this allele sequence { sequenceAlleleMap[altAllelePtr->getSequenceString()] = altAllelePtr; sequenceKeyOrder.emplace_back(altAllelePtr->getSequenceString()); // add the allelesequence to the keysequencetracker } } } // create the varaintPtr and add all the variant information std::vector< IAllele::SharedPtr > altAllelePtrs; altAllelePtrs.reserve(sequenceAlleleMap.size()); for (auto sequence : sequenceKeyOrder) // add the alleles back in the order they were seen { altAllelePtrs.emplace_back(sequenceAlleleMap[sequence]); } auto variantPtr = std::make_shared< Variant >(startPosition, variants[0]->getChrom(), ".", "0", "PASS", equivalentRefAllelePtr, altAllelePtrs); for (Region::SharedPtr regionPtr : regionPtrs) { variantPtr->addRegion(regionPtr); } return variantPtr; }
void G2DRegionGraph::makeCoarserRegions(G2DRegionGraph* pFineRegions) { // Find every region's closest neighbor GImage* pFineRegionMask = pFineRegions->regionMask(); GImage* pCoarseRegionMask = regionMask(); GAssert(pCoarseRegionMask->width() == pFineRegionMask->width() && pCoarseRegionMask->height() == pFineRegionMask->height()); // size mismatch int* pBestNeighborMap = new int[pFineRegions->regionCount()]; ArrayHolder<int> hBestNeighborMap(pBestNeighborMap); for(size_t i = 0; i < pFineRegions->regionCount(); i++) { struct GRegion* pRegion = pFineRegions->m_regions[i]; struct GRegionEdge* pEdge; double d; double dBestDiff = 1e200; int nBestNeighbor = -1; for(pEdge = pRegion->m_pNeighbors; pEdge; pEdge = pEdge->GetNext(i)) { size_t j = pEdge->GetOther(i); struct GRegion* pOtherRegion = pFineRegions->m_regions[j]; d = MeasureRegionDifference(pRegion, pOtherRegion); if(d < dBestDiff) { dBestDiff = d; nBestNeighbor = (int)j; } } GAssert(nBestNeighbor != -1 || pFineRegions->regionCount() == 1); // failed to find a neighbor pBestNeighborMap[i] = nBestNeighbor; } // Create a mapping to new regions numbers int* pNewRegionMap = new int[pFineRegions->regionCount()]; ArrayHolder<int> hNewRegionMap(pNewRegionMap); memset(pNewRegionMap, 0xff, sizeof(int) * pFineRegions->regionCount()); int nNewRegionCount = 0; for(size_t i = 0; i < pFineRegions->regionCount(); i++) { size_t nNewRegion = -1; size_t j = i; while(pNewRegionMap[j] == -1) { pNewRegionMap[j] = -2; j = pBestNeighborMap[j]; } if(pNewRegionMap[j] == -2) nNewRegion = nNewRegionCount++; else nNewRegion = pNewRegionMap[j]; j = i; while(pNewRegionMap[j] == -2) { pNewRegionMap[j] = (int)nNewRegion; j = pBestNeighborMap[j]; } } // Make the new regions for(size_t i = 0; i < pFineRegions->regionCount(); i++) { struct GRegion* pRegion = pFineRegions->m_regions[i]; size_t j = pNewRegionMap[i]; if(regionCount() <= j) { GAssert(regionCount() == j); // how'd it get two behind? addRegion(); } struct GRegion* pCoarseRegion = m_regions[j]; pCoarseRegion->m_nSumRed += pRegion->m_nSumRed; pCoarseRegion->m_nSumGreen += pRegion->m_nSumGreen; pCoarseRegion->m_nSumBlue += pRegion->m_nSumBlue; pCoarseRegion->m_nPixels += pRegion->m_nPixels; } for(size_t i = 0; i < pFineRegions->regionCount(); i++) { struct GRegion* pRegion = pFineRegions->m_regions[i]; size_t j = pNewRegionMap[i]; struct GRegionEdge* pEdge; for(pEdge = pRegion->m_pNeighbors; pEdge; pEdge = pEdge->GetNext(i)) { size_t k = pNewRegionMap[pEdge->GetOther(i)]; if(j != k) makeNeighbors(j, k); } } // Make the fine region mask unsigned int nOldRegion; int x, y; for(y = 0; y < (int)pFineRegionMask->height(); y++) { for(x = 0; x < (int)pFineRegionMask->width(); x++) { nOldRegion = pFineRegionMask->pixel(x, y); pCoarseRegionMask->setPixel(x, y, pNewRegionMap[nOldRegion]); } } }
bool Map::loadMap(std::string mapDirectory) { GUI *guiPtr = Base::instance()->getGuiPtr(); std::ifstream fileStream; fileStream.open(mapDirectory); if(!fileStream.good()) return false; int linei = 0; bool error = false; while(!fileStream.eof()) { linei+=1; std::string line; std::vector<std::string> translatedLine; //line decryption std::getline(fileStream, line); if(line.size()==0) continue; std::string::iterator it; std::string temporaryCommandContainer; bool nameEnclosure = false; for(it=line.begin();it!=line.end();it++) { if(*it == '#') break; else if(*it == '\"') { nameEnclosure = !nameEnclosure; } else if(*it == ' ' && !nameEnclosure) { translatedLine.push_back(temporaryCommandContainer); temporaryCommandContainer = ""; } else { temporaryCommandContainer += *it; } } if(temporaryCommandContainer.size()>0) { translatedLine.push_back(temporaryCommandContainer); temporaryCommandContainer = ""; } if(translatedLine.size()==0) continue; //command decryption if(translatedLine[0]=="nazwa") { if(translatedLine.size()!=2) error=true; else setMapName(translatedLine[1]); } else if(translatedLine[0]=="mapa") { if(translatedLine.size()!=2) error=true; else { al_destroy_bitmap(mapaPtr); mapaPtr = al_load_bitmap(translatedLine[1].c_str()); al_clear_to_color(al_map_rgb(0, 0, 255)); mapaWidth = al_get_bitmap_width(mapaPtr); mapaHeight = al_get_bitmap_height(mapaPtr); } } else if(translatedLine[0]=="kraj") { if(translatedLine.size()!=6) error=true; else addRealm(translatedLine[1],al_map_rgb(std::stoi(translatedLine[2]), std::stoi(translatedLine[3]),std::stoi(translatedLine[4])), translatedLine[5]); } else if(translatedLine[0]=="koniec") { if(translatedLine.size()!=2) error=true; else if(translatedLine[1]=="krajow") fillDiplomaticStates(); else error=true; } else if(translatedLine[0]=="region") { if(translatedLine.size()!=7) error=true; else if(!addRegion(std::stoi(translatedLine[1]),std::stoi(translatedLine[2]), translatedLine[3],translatedLine[4],std::stoi(translatedLine[5]), std::stoi(translatedLine[6]))) error=true; } else if(translatedLine[0]=="droga") { if(translatedLine.size()!=3) error=true; else if(!addRegionsConnector(translatedLine[1], translatedLine[2])) error=true; } else if(translatedLine[0]=="wojna") { if(translatedLine.size()!=3) error=true; else if(!changeDiplomaticState(WAR, translatedLine[1], translatedLine[2])) error=true; } else if(translatedLine[0]=="handel") { if(translatedLine.size()!=3) error=true; else if(!changeDiplomaticState(TRADE_AGREEMENT, translatedLine[1], translatedLine[2])) error=true; } else if(translatedLine[0]=="sojusz") { if(translatedLine.size()!=3) error=true; else if(!changeDiplomaticState(ALLIANCE, translatedLine[1], translatedLine[2])) error=true; } if(error) { guiPtr->showNotification("Błąd w mapie w linii: " + std::to_string(linei)); return false; } } fillRealmsRegions(); return true; }
void CCRookieGuide::addRegion(CCNode* n, CCCallFunc* func, bool removeOnTouch) { CCRect b = CCRectMake(0, 0, n->getContentSize().width, n->getContentSize().height); CCAffineTransform t = n->nodeToWorldTransform(); b = CCRectApplyAffineTransform(b, t); addRegion(b, func, removeOnTouch); }
regionEditDialog::regionEditDialog(Link *lk, mainWindow *win) { QLabel *label; window = win; link = lk; upload = 0; QHBoxLayout *mainLayout = new QHBoxLayout; QVBoxLayout *regionLayout = new QVBoxLayout; QVBoxLayout *yearLayout = new QVBoxLayout; QVBoxLayout *statsLayout = new QVBoxLayout; QVBoxLayout *calendarLayout = new QVBoxLayout; label = new QLabel(tr("Select Region")); regionLayout->addWidget(label); regionLayout->addWidget(®ionSelector); regionSelector.setSizeAdjustPolicy(QComboBox::AdjustToContents); label = new QLabel(tr("New Region")); regionLayout->addWidget(label); regionLayout->addWidget(®ionEntry); addRegionButton.setText(tr("Add")); regionLayout->addWidget(&addRegionButton); connect(&addRegionButton, SIGNAL(clicked()), this, SLOT(addRegion())); regionLayout->addStretch(); QPushButton *exitButton = new QPushButton; exitButton->setText(tr("Done")); regionLayout->addWidget(exitButton, Qt::AlignRight); connect(exitButton, SIGNAL(clicked()), this, SLOT(cancel())); label = new QLabel(tr("Select Year")); yearLayout->addWidget(label); yearLayout->addWidget(&yearSelector); label = new QLabel(tr("New Year")); yearLayout->addWidget(label); yearLayout->addWidget(&yearEntry); addYearButton.setText(tr("Add")); yearLayout->addWidget(&addYearButton); connect(&addYearButton, SIGNAL(clicked()), this, SLOT(addYear())); yearLayout->addStretch(); label = new QLabel(tr("Statutory days")); statsLayout->addWidget(label); regionSelector.setSizeAdjustPolicy(QComboBox::AdjustToContents); statsLayout->addWidget(&stats); QPushButton *removeButton = new QPushButton; removeButton->setText(tr("Remove")); statsLayout->addWidget(removeButton); connect(removeButton, SIGNAL(clicked()), this, SLOT(remove())); calendarLayout->addWidget(&calendar); QPushButton *addButton = new QPushButton; addButton->setText(tr("Add")); calendarLayout->addWidget(addButton); connect(addButton, SIGNAL(clicked()), this, SLOT(add())); QFrame* line = new QFrame(); line->setFrameShape(QFrame::VLine); line->setFrameShadow(QFrame::Sunken); mainLayout->addLayout(regionLayout); mainLayout->addWidget(line); mainLayout->addLayout(yearLayout); mainLayout->addLayout(statsLayout); mainLayout->addLayout(calendarLayout); setLayout(mainLayout); // Error Message Box setup msgbox.setIcon(QMessageBox::Critical); msgbox.setStandardButtons(QMessageBox::Ok); }
Region* buildRegion(vector< vector<Point> >& cycles){ // first step create a single region from each cycle vector<pair<Region*, bool> > sc_regions; // single cycle regions for(unsigned int i=0;i<cycles.size(); i++){ vector<Point> cycle = cycles[i]; addRegion(sc_regions,cycle); } // split the vector into faces and holes vector<Region*> faces; vector<Region*> holes; for(unsigned int i=0;i<sc_regions.size();i++){ if(sc_regions[i].second){ faces.push_back(sc_regions[i].first); } else { holes.push_back(sc_regions[i].first); } } // subtract all holes from each face if nessecary vector<Region*> faces2; for(unsigned int i=0;i<faces.size();i++){ Region* face = faces[i]; for(unsigned int j=0; j< holes.size(); j++){ Region* hole = holes[j]; if(face->BoundingBox().Intersects(hole->BoundingBox())){ if(!topops::wcontains(hole,face)){ // may be an island Region* tmp = SetOp(*face,*hole,avlseg::difference_op); delete face; face = tmp; } } } if((face->Size())!=0){ faces2.push_back(face); } else { // face was removed completely delete face; } } // the hole regions are not longer needed, delete them for(unsigned int i=0;i<holes.size();i++){ delete holes[i]; } if(faces2.size()<1){ cerr << "no face found within the cycles" << endl; return new Region(0); } // build the union of all faces Region* reg = faces2[0]; for(unsigned int i=1;i<faces2.size();i++){ Region* face2 = faces2[i]; Region* tmp = SetOp(*reg, *face2, avlseg::union_op); delete reg; delete face2; reg = tmp; } return reg; }