int main(int argc, char *argv[]) { if (argc < 5) { ERROR("usage: %s baseroot envroot program cmdl..", program_invocation_short_name); } const char *root = poe_init_playground(argv[1], argv[2]); const char *prog = copy_program(root, argv[3]); char **cmdl = construct_cmdl(argc - 4, argv + 4, prog); int stdout_fd[2], stderr_fd[2]; NONNEGATIVE(pipe2(stdout_fd, O_DIRECT)); NONNEGATIVE(pipe2(stderr_fd, O_DIRECT)); // TODO: CLONE_NEWUSER pid_t pid = (pid_t)syscall(SYS_clone, SIGCHLD | CLONE_NEWIPC | CLONE_NEWNS | CLONE_NEWPID | CLONE_NEWUTS | CLONE_NEWNET, 0); NONNEGATIVE(pid); if (pid == 0) { dup2(stdout_fd[1], STDOUT_FILENO); close(stdout_fd[0]); close(stdout_fd[1]); dup2(stderr_fd[1], STDERR_FILENO); close(stderr_fd[0]); close(stderr_fd[1]); child(root, cmdl); } else { sd_event *event = NULL; uint64_t now; int stdout_fileno = STDOUT_FILENO; int stderr_fileno = STDERR_FILENO; int fflags; fflags = fcntl(stdout_fd[0], F_GETFL, 0); NONNEGATIVE(fflags); NONNEGATIVE(fcntl(stdout_fd[0], F_SETFL, fflags | O_NONBLOCK)); fflags = fcntl(stderr_fd[0], F_GETFL, 0); NONNEGATIVE(fflags); NONNEGATIVE(fcntl(stderr_fd[0], F_SETFL, fflags | O_NONBLOCK)); sigset_t mask; sigemptyset(&mask); sigaddset(&mask, SIGCHLD); sigaddset(&mask, SIGINT); sigaddset(&mask, SIGTERM); sigprocmask(SIG_BLOCK, &mask, NULL); NONNEGATIVE(sd_event_default(&event)); NONNEGATIVE(sd_event_add_signal(event, NULL, SIGCHLD, sigchld_handler, &pid)); NONNEGATIVE(sd_event_add_signal(event, NULL, SIGINT, sigint_handler, &pid)); NONNEGATIVE(sd_event_add_signal(event, NULL, SIGTERM, sigint_handler, &pid)); NONNEGATIVE(sd_event_now(event, CLOCK_MONOTONIC, &now)); NONNEGATIVE(sd_event_add_time(event, NULL, CLOCK_MONOTONIC, now + POE_TIME_LIMIT, 0, timer_handler, &pid)); NONNEGATIVE(sd_event_add_io(event, NULL, stdout_fd[0], EPOLLIN, stdout_handler, &stdout_fileno)); NONNEGATIVE(sd_event_add_io(event, NULL, stderr_fd[0], EPOLLIN, stdout_handler, &stderr_fileno)); NONNEGATIVE(ptrace(PTRACE_SEIZE, pid, NULL, PTRACE_O_TRACECLONE | PTRACE_O_TRACEFORK | PTRACE_O_TRACESECCOMP | PTRACE_O_TRACEVFORK)); poe_init_systemd(pid); NONNEGATIVE(sd_event_loop(event)); } ERROR("unreachable"); }
TextWriter& operator()(const std::vector<object_type>& v) { for_each(v.begin(), v.end(), child()); return *this; }
TextWriter& operator()(const SpectrumIdentificationItem& sii) { (*this)("SpectrumIdentificationItem:"); if (!sii.id.empty()) child()("id: ", sii.id); if (!sii.name.empty()) child()("name: ", sii.name); if (!sii.empty()) { child()("rank: ", sii.rank); child()("chargeState: ", sii.chargeState); child()("experimentalMassToCharge: ", sii.experimentalMassToCharge); child()("calculatedMassToCharge: ", sii.calculatedMassToCharge); child()("calculatedPI: ", sii.calculatedPI); child()("passThreshold: ", sii.passThreshold); } if (sii.peptidePtr.get() && !sii.peptidePtr->empty()) child()("peptide_ref: ", sii.peptidePtr->id); if (sii.massTablePtr.get() && !sii.massTablePtr->empty()) child()("massTable_ref: ", sii.massTablePtr->id); if (sii.samplePtr.get() && !sii.samplePtr->empty()) child()("sample_ref: ", sii.samplePtr->id); BOOST_FOREACH(const PeptideEvidencePtr& pe, sii.peptideEvidencePtr) if (pe.get() && !pe->empty()) child()("peptideEvidence_ref: ", pe->id); if (!sii.fragmentation.empty()) child()("fragmentation", sii.fragmentation); child()((const ParamContainer&)sii); return *this; }
TextWriter& operator()(const SelectedIon& selectedIon) { (*this)("selectedIon:"); child()(static_cast<const ParamContainer&>(selectedIon)); return *this; }
int main(int argc, char** argv) { struct datagram conn_gram; struct ifi_info *ifihead, *ifi; struct sockaddr_in servaddr; struct sockaddr_in cliaddr; fd_set rset, allset; socklen_t len; ssize_t n; int nready; int on = 1; int maxfdp1 = 0; int i; int send_flag; pid_t pid; ifihead = get_ifi_head(); printf("Server IP Addresses:\n"); print_ifi_info(ifihead); readfile(); printf("Listening port %d\n", port); count = 0; for (ifi=ifihead;ifi!=NULL;ifi=ifi->ifi_next) { if (!(ifi->ifi_flags & IFF_UP)) continue; addrs[count] = ifi; sockfds[count] = Socket(AF_INET, SOCK_DGRAM, 0); if (sockfds[count] > maxfdp1) maxfdp1 = sockfds[count]; Setsockopt(sockfds[count], SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); memcpy(&servaddr, ifi->ifi_addr, sizeof(servaddr)); servaddr.sin_port = htons(port); Bind(sockfds[count], (SA *) &servaddr, sizeof(servaddr)); count++; if (count >= MAX_IFI_COUNT) break; } FD_ZERO(&allset); FD_ZERO(&rset); for (i=0;i<count;i++) { FD_SET(sockfds[i], &allset); } maxfdp1 = maxfdp1+1; signal(SIGCHLD, sigchld); for(;;) { rset = allset; if ((nready = select(maxfdp1, &rset, NULL, NULL, NULL)) < 0) { if (errno == EINTR) continue; else err_sys("select error"); } for (i=0;i<count;i++) { if (FD_ISSET(sockfds[i], &rset)) { len = sizeof(cliaddr); n = recv_from(sockfds[i], &conn_gram, &cliaddr, &len); send_flag = get_flag(&conn_gram); if (!n || (send_flag & RETRY)) { // client timeout, don't fork new child continue; } printf("Client [%s:%d] connected\n", inet_ntoa(cliaddr.sin_addr), ntohs(cliaddr.sin_port)); pid = fork(); if (!pid) { child(i, &cliaddr, &conn_gram); // exit return 0; } } } } free_ifi_info_plus(ifihead); return 0; }
TextWriter& operator()(const FileContent& fileContent) { (*this)("fileContent:"); child()(static_cast<const ParamContainer&>(fileContent)); return *this; }
TextWriter& operator()(const Target& target) { (*this)("target:"); child()(static_cast<const ParamContainer&>(target)); return *this; }
short ProbeCache::codeGen(Generator *generator) { ExpGenerator * exp_gen = generator->getExpGenerator(); Space * space = generator->getSpace(); MapTable * last_map_table = generator->getLastMapTable(); ex_cri_desc * given_desc = generator->getCriDesc(Generator::DOWN); ex_cri_desc * returned_desc = new(space) ex_cri_desc(given_desc->noTuples() + 1, space); // cri descriptor for work atp has 5 entries: // entry #0 for const // entry #1 for temp // entry #2 for hash value of probe input data in Probe Cache Manager // entry #3 for encoded probe input data in Probe Cache Manager // enrry #4 for inner table row data in this operator's cache buffer Int32 work_atp = 1; ex_cri_desc * work_cri_desc = new(space) ex_cri_desc(5, space); unsigned short hashValIdx = 2; unsigned short encodedProbeDataIdx = 3; unsigned short innerRowDataIdx = 4; // generate code for child tree, and get its tdb and explain tuple. child(0)->codeGen(generator); ComTdb * child_tdb = (ComTdb *)(generator->getGenObj()); ExplainTuple *childExplainTuple = generator->getExplainTuple(); ////////////////////////////////////////////////////// // Generate up to 4 runtime expressions. ////////////////////////////////////////////////////// // Will use child's char. inputs (+ execution count) for the next // two runtime expressions. ValueIdList inputsToUse = child(0).getGroupAttr()->getCharacteristicInputs(); inputsToUse.insert(generator->getOrAddStatementExecutionCount()); // Expression #1 gets the hash value of the probe input data ValueIdList hvAsList; // Executor has hard-coded assumption that the result is long, // so add a Cast node to convert result to a long. ItemExpr *probeHashAsIe = new (generator->wHeap()) HashDistPartHash(inputsToUse.rebuildExprTree(ITM_ITEM_LIST)); probeHashAsIe->bindNode(generator->getBindWA()); NumericType &nTyp = (NumericType &)probeHashAsIe->getValueId().getType(); GenAssert(nTyp.isSigned() == FALSE, "Unexpected signed HashDistPartHash."); GenAssert(probeHashAsIe->getValueId().getType().supportsSQLnullLogical() == FALSE, "Unexpected nullable HashDistPartHash."); ItemExpr *hvAsIe = new (generator->wHeap()) Cast( probeHashAsIe, new (generator->wHeap()) SQLInt(generator->wHeap(), FALSE, // false == unsigned. FALSE // false == not nullable. )); hvAsIe->bindNode(generator->getBindWA()); hvAsList.insert(hvAsIe->getValueId()); ex_expr *hvExpr = NULL; ULng32 hvLength; exp_gen->generateContiguousMoveExpr( hvAsList, 0, // don't add convert node work_atp, hashValIdx, ExpTupleDesc::SQLARK_EXPLODED_FORMAT, hvLength, &hvExpr); GenAssert(hvLength == sizeof(Lng32), "Unexpected length of result of hash function."); // Expression #2 encodes the probe input data for storage in // the ProbeCacheManager. ValueIdList encodeInputAsList; CollIndex inputListIndex; for (inputListIndex = 0; inputListIndex < inputsToUse.entries(); inputListIndex++) { ItemExpr *inputIe = (inputsToUse[inputListIndex].getValueDesc())->getItemExpr(); if (inputIe->getValueId().getType().getVarLenHdrSize() > 0) { // This logic copied from Sort::codeGen(). // Explode varchars by moving them to a fixed field // whose length is equal to the max length of varchar. // 5/8/98: add support for VARNCHAR const CharType& char_type = (CharType&)(inputIe->getValueId().getType()); if (!CollationInfo::isSystemCollation(char_type.getCollation())) { inputIe = new(generator->wHeap()) Cast (inputIe, (new(generator->wHeap()) SQLChar( generator->wHeap(), CharLenInfo(char_type.getStrCharLimit(), char_type.getDataStorageSize()), char_type.supportsSQLnull(), FALSE, FALSE, FALSE, char_type.getCharSet(), char_type.getCollation(), char_type.getCoercibility() ) ) ); } } CompEncode * enode = new(generator->wHeap()) CompEncode(inputIe, FALSE /* ascend/descend doesn't matter*/); enode->bindNode(generator->getBindWA()); encodeInputAsList.insert(enode->getValueId()); } ex_expr *encodeInputExpr = NULL; ULng32 encodedInputLength; exp_gen->generateContiguousMoveExpr(encodeInputAsList, 0, //don't add conv nodes work_atp, encodedProbeDataIdx, ExpTupleDesc::SQLARK_EXPLODED_FORMAT, encodedInputLength, &encodeInputExpr); // Expression #3 moves the inner table data into a buffer pool. // This is also the tuple returned to ProbeCache's parent. ex_expr * innerRecExpr = NULL; ValueIdList innerTableAsList = getGroupAttr()->getCharacteristicOutputs(); ////////////////////////////////////////////////////// // Describe the returned row and add the returned // values to the map table. ////////////////////////////////////////////////////// // determine internal format NABoolean useCif = FALSE; ExpTupleDesc::TupleDataFormat tupleFormat = generator->getInternalFormat(); //tupleFormat = determineInternalFormat( innerTableAsList, this, useCif,generator); ULng32 innerRecLength = 0; ExpTupleDesc * innerRecTupleDesc = 0; MapTable * returnedMapTable = NULL; exp_gen->generateContiguousMoveExpr(innerTableAsList, -1, // do add conv nodes work_atp, innerRowDataIdx, tupleFormat, innerRecLength, &innerRecExpr, &innerRecTupleDesc, ExpTupleDesc::SHORT_FORMAT, &returnedMapTable); returned_desc->setTupleDescriptor(returned_desc->noTuples() - 1, innerRecTupleDesc); // remove all appended map tables and return the returnedMapTable generator->removeAll(last_map_table); generator->appendAtEnd(returnedMapTable); // This returnedMapTable will contain the value ids that are being returned // (the inner table probed). // Massage the atp and atp_index of the innerTableAsList. for (CollIndex i = 0; i < innerTableAsList.entries(); i++) { ValueId innerValId = innerTableAsList[i]; Attributes *attrib = generator->getMapInfo(innerValId)->getAttr(); // All reference to the returned values from this point on // will be at atp = 0, atp_index = last entry in returned desc. attrib->setAtp(0); attrib->setAtpIndex(returned_desc->noTuples() - 1); } // Expression #4 is a selection predicate, to be applied // before returning rows to the parent ex_expr * selectPred = NULL; if (!selectionPred().isEmpty()) { ItemExpr * selPredTree = selectionPred().rebuildExprTree(ITM_AND,TRUE,TRUE); exp_gen->generateExpr(selPredTree->getValueId(), ex_expr::exp_SCAN_PRED, &selectPred); } ////////////////////////////////////////////////////// // Prepare params for ComTdbProbeCache. ////////////////////////////////////////////////////// queue_index pDownSize = (queue_index)getDefault(GEN_PROBE_CACHE_SIZE_DOWN); queue_index pUpSize = (queue_index)getDefault(GEN_PROBE_CACHE_SIZE_UP); // Make sure that the ProbeCache queues can support the childs queues. if(pDownSize < child_tdb->getInitialQueueSizeDown()) { pDownSize = child_tdb->getInitialQueueSizeDown(); pDownSize = MINOF(pDownSize, 32768); } if(pUpSize < child_tdb->getInitialQueueSizeUp()) { pUpSize = child_tdb->getInitialQueueSizeUp(); pUpSize = MINOF(pUpSize, 32768); } ULng32 pcNumEntries = numCachedProbes_; // Number of entries in the probe cache cannot be less than // max parent down queue size. Before testing and adjusting the // max queue size, it is necessary to make sure it is a power of // two, rounding up if necessary. This is to match the logic in // ex_queue::resize. queue_index pdq2 = 1; queue_index bits = pDownSize; while (bits && pdq2 < pDownSize) { bits = bits >> 1; pdq2 = pdq2 << 1; } if (pcNumEntries < pdq2) pcNumEntries = pdq2; numInnerTuples_ = getDefault(GEN_PROBE_CACHE_NUM_INNER); if (innerRecExpr == NULL) { // For semi-join and anti-semi-join, executor need not allocate // a buffer. Set the tdb's buffer size to 0 to be consistent. numInnerTuples_ = 0; } else if (numInnerTuples_ == 0) { // Handle special value, 0, which tells code gen to // decided on buffer size: i.e., large enough to accomodate // all parent up queue entries and all probe cache entries // having a different inner table row. // As we did for the down queue, make sure the up queue size // specified is a power of two. queue_index puq2 = 1; queue_index bits = pUpSize; while (bits && puq2 < pUpSize) { bits = bits >> 1; puq2 = puq2 << 1; } numInnerTuples_ = puq2 + pcNumEntries; }
bool RCCResourceLibrary::interpretResourceFile(QIODevice *inputDevice, const QString &fname, QString currentPath, bool ignoreErrors) { Q_ASSERT(m_errorDevice); const QChar slash = QLatin1Char('/'); if (!currentPath.isEmpty() && !currentPath.endsWith(slash)) currentPath += slash; QXmlStreamReader reader(inputDevice); QStack<RCCXmlTag> tokens; QString prefix; QLocale::Language language = QLocale::c().language(); QLocale::Country country = QLocale::c().country(); QString alias; int compressLevel = m_compressLevel; int compressThreshold = m_compressThreshold; while (!reader.atEnd()) { QXmlStreamReader::TokenType t = reader.readNext(); switch (t) { case QXmlStreamReader::StartElement: if (reader.name() == m_strings.TAG_RCC) { if (!tokens.isEmpty()) reader.raiseError(QLatin1String("expected <RCC> tag")); else tokens.push(RccTag); } else if (reader.name() == m_strings.TAG_RESOURCE) { if (tokens.isEmpty() || tokens.top() != RccTag) { reader.raiseError(QLatin1String("unexpected <RESOURCE> tag")); } else { tokens.push(ResourceTag); QXmlStreamAttributes attributes = reader.attributes(); language = QLocale::c().language(); country = QLocale::c().country(); if (attributes.hasAttribute(m_strings.ATTRIBUTE_LANG)) { QString attribute = attributes.value(m_strings.ATTRIBUTE_LANG).toString(); QLocale lang = QLocale(attribute); language = lang.language(); if (2 == attribute.length()) { // Language only country = QLocale::AnyCountry; } else { country = lang.country(); } } prefix.clear(); if (attributes.hasAttribute(m_strings.ATTRIBUTE_PREFIX)) prefix = attributes.value(m_strings.ATTRIBUTE_PREFIX).toString(); if (!prefix.startsWith(slash)) prefix.prepend(slash); if (!prefix.endsWith(slash)) prefix += slash; } } else if (reader.name() == m_strings.TAG_FILE) { if (tokens.isEmpty() || tokens.top() != ResourceTag) { reader.raiseError(QLatin1String("unexpected <FILE> tag")); } else { tokens.push(FileTag); QXmlStreamAttributes attributes = reader.attributes(); alias.clear(); if (attributes.hasAttribute(m_strings.ATTRIBUTE_ALIAS)) alias = attributes.value(m_strings.ATTRIBUTE_ALIAS).toString(); compressLevel = m_compressLevel; if (attributes.hasAttribute(m_strings.ATTRIBUTE_COMPRESS)) compressLevel = attributes.value(m_strings.ATTRIBUTE_COMPRESS).toString().toInt(); compressThreshold = m_compressThreshold; if (attributes.hasAttribute(m_strings.ATTRIBUTE_THRESHOLD)) compressThreshold = attributes.value(m_strings.ATTRIBUTE_THRESHOLD).toString().toInt(); // Special case for -no-compress. Overrides all other settings. if (m_compressLevel == -2) compressLevel = 0; } } else { reader.raiseError(QString(QLatin1String("unexpected tag: %1")).arg(reader.name().toString())); } break; case QXmlStreamReader::EndElement: if (reader.name() == m_strings.TAG_RCC) { if (!tokens.isEmpty() && tokens.top() == RccTag) tokens.pop(); else reader.raiseError(QLatin1String("unexpected closing tag")); } else if (reader.name() == m_strings.TAG_RESOURCE) { if (!tokens.isEmpty() && tokens.top() == ResourceTag) tokens.pop(); else reader.raiseError(QLatin1String("unexpected closing tag")); } else if (reader.name() == m_strings.TAG_FILE) { if (!tokens.isEmpty() && tokens.top() == FileTag) tokens.pop(); else reader.raiseError(QLatin1String("unexpected closing tag")); } break; case QXmlStreamReader::Characters: if (reader.isWhitespace()) break; if (tokens.isEmpty() || tokens.top() != FileTag) { reader.raiseError(QLatin1String("unexpected text")); } else { QString fileName = reader.text().toString(); if (fileName.isEmpty()) { const QString msg = QString::fromLatin1("RCC: Warning: Null node in XML of '%1'\n").arg(fname); m_errorDevice->write(msg.toUtf8()); } if (alias.isNull()) alias = fileName; alias = QDir::cleanPath(alias); while (alias.startsWith(QLatin1String("../"))) alias.remove(0, 3); alias = QDir::cleanPath(m_resourceRoot) + prefix + alias; QString absFileName = fileName; if (QDir::isRelativePath(absFileName)) absFileName.prepend(currentPath); QFileInfo file(absFileName); if (!file.exists()) { m_failedResources.push_back(absFileName); const QString msg = QString::fromLatin1("RCC: Error in '%1': Cannot find file '%2'\n").arg(fname).arg(fileName); m_errorDevice->write(msg.toUtf8()); if (ignoreErrors) continue; else return false; } else if (file.isFile()) { const bool arc = addFile(alias, RCCFileInfo(alias.section(slash, -1), file, language, country, RCCFileInfo::NoFlags, compressLevel, compressThreshold) ); if (!arc) m_failedResources.push_back(absFileName); } else { QDir dir; if (file.isDir()) { dir.setPath(file.filePath()); } else { dir.setPath(file.path()); dir.setNameFilters(QStringList(file.fileName())); if (alias.endsWith(file.fileName())) alias = alias.left(alias.length()-file.fileName().length()); } if (!alias.endsWith(slash)) alias += slash; QDirIterator it(dir, QDirIterator::FollowSymlinks|QDirIterator::Subdirectories); while (it.hasNext()) { it.next(); QFileInfo child(it.fileInfo()); if (child.fileName() != QLatin1String(".") && child.fileName() != QLatin1String("..")) { const bool arc = addFile(alias + child.fileName(), RCCFileInfo(child.fileName(), child, language, country, child.isDir() ? RCCFileInfo::Directory : RCCFileInfo::NoFlags, compressLevel, compressThreshold) ); if (!arc) m_failedResources.push_back(child.fileName()); } } } } break; default: break; } } if (reader.hasError()) { if (ignoreErrors) return true; int errorLine = reader.lineNumber(); int errorColumn = reader.columnNumber(); QString errorMessage = reader.errorString(); QString msg = QString::fromLatin1("RCC Parse Error: '%1' Line: %2 Column: %3 [%4]\n").arg(fname).arg(errorLine).arg(errorColumn).arg(errorMessage); m_errorDevice->write(msg.toUtf8()); return false; } if (m_root == 0) { const QString msg = QString::fromUtf8("RCC: Warning: No resources in '%1'.\n").arg(fname); m_errorDevice->write(msg.toUtf8()); if (!ignoreErrors && m_format == Binary) { // create dummy entry, otherwise loading with QResource will crash m_root = new RCCFileInfo(QString(), QFileInfo(), QLocale::C, QLocale::AnyCountry, RCCFileInfo::Directory); } } return true; }
int logwrap(int argc, const char* argv[], int background) { pid_t pid; int parent_ptty; int child_ptty; char *child_devname = NULL; /* Use ptty instead of socketpair so that STDOUT is not buffered */ parent_ptty = open("/dev/ptmx", O_RDWR); if (parent_ptty < 0) { LOG(LOG_ERROR, "logwrapper", "Cannot create parent ptty"); return -errno; } if (grantpt(parent_ptty) || unlockpt(parent_ptty) || ((child_devname = (char*)ptsname(parent_ptty)) == 0)) { close(parent_ptty); LOG(LOG_ERROR, "logwrapper", "Problem with /dev/ptmx"); return -1; } pid = fork(); if (pid < 0) { close(parent_ptty); LOG(LOG_ERROR, "logwrapper", "Failed to fork"); return -errno; } else if (pid == 0) { /* * Child */ child_ptty = open(child_devname, O_RDWR); if (child_ptty < 0) { close(parent_ptty); LOG(LOG_ERROR, "logwrapper", "Problem with child ptty"); return -errno; } // redirect stdout and stderr close(parent_ptty); dup2(child_ptty, 1); dup2(child_ptty, 2); close(child_ptty); if (background) { int fd = open("/dev/cpuctl/bg_non_interactive/tasks", O_WRONLY); if (fd >= 0) { char text[64]; sprintf(text, "%d", getpid()); if (write(fd, text, strlen(text)) < 0) { LOG(LOG_WARN, "logwrapper", "Unable to background process (%s)", strerror(errno)); close(fd); } close(fd); } else { LOG(LOG_WARN, "logwrapper", "Unable to background process (%s)", strerror(errno)); } } child(argc, argv); } else { /* * Parent */ int rc = parent(argv[0], parent_ptty); close(parent_ptty); return rc; } return 0; }
void Flu_Choice_Group :: value( int v ) { v++; if( v >= 1 && v < children() ) value( child(v) ); }
bool Stage::loadFrom(std::string identifier) { auto node = ResourceRegistry::get<XMLResource>( "data" )->doc().first_element_by_path( "/kriti/render/" ).find_child_by_attribute( "stage", "name", identifier.c_str()); if(!node) return false; m_name = identifier; int outputs = node.child("outputs").text().as_int(1); int width = -1, height = -1; // TODO: support loading width/height from XML resource initialize(outputs, width, height); // add previous for(auto &child : node.children()) { if(std::strcmp(child.name(), "previous")) continue; std::string pname = child.text().as_string(""); auto prev = ResourceRegistry::get<Stage>(pname); if(!prev) { Message3(Render, Error, "Couldn't find previous stage " << pname); continue; } addPrevious(prev); } for(auto &child : node.children()) { if(std::strcmp(child.name(), "map")) continue; std::string fromString = child.attribute("from").as_string(); int from = 0; for(; from < m_previous.size(); from ++) if(m_previous[from]->name() == fromString) break; if(from == m_previous.size()) { Message3(Render, Error, "No previous stage " << fromString); continue; } std::string whichString = child.attribute("which").as_string(); const std::map<std::string, Framebuffer::Attachment> whichMap = { {"colour0", Framebuffer::ColourBuffer0}, {"colour1", Framebuffer::ColourBuffer1}, {"colour2", Framebuffer::ColourBuffer2}, {"colour3", Framebuffer::ColourBuffer3}, {"depth", Framebuffer::DepthBuffer} }; if(whichMap.count(whichString) == 0) { Message3(Render, Warning, "Unknown attachment: " << whichString); continue; } std::string materialString = child.attribute("material").as_string(); std::string uniform = child.attribute("to").as_string(); auto mat = ResourceRegistry::get<Render::Material>(materialString); addMapping(from, whichMap.at(whichString), mat, uniform); } return true; }
QgsLegendItem* QgsLegendItem::firstChild() { return dynamic_cast<QgsLegendItem *>( child( 0 ) ); }
/*---------------------------------------------------------------------+ | main | | ==================================================================== | | | | Function: Main program (see prolog for more details) | | | | Returns: (0) Successful completion | | (-1) Error occurred | | | +---------------------------------------------------------------------*/ int main (int argc, char **argv) { char *shmptr, /* Shared memory segment address */ value = 0; /* Value written into shared memory segment */ int i; char *ptr; int status; int shmem_size; unsigned long cksum; lockfd = create_lock_file (LOCK_FILE); setup_signal_handlers (); /* * Parse command line arguments and print out program header */ parse_args (argc, argv); printf ("%s: IPC Shared Memory TestSuite program\n", *argv); parent_pid = getpid (); for (i=0; i<num_children; i++) pid [i] = (pid_t)0; /* * Get chunk of shared memory for storing num_children checksum */ shmem_size = sizeof (unsigned long); if ((long)(checksum = (unsigned long *) mmap (0, shmem_size, PROT_READ | PROT_WRITE, MAP_ANON | MAP_SHARED, -1, 0)) < 0) sys_error ("mmap failed", __LINE__); for (i=0; i < num_children; i++) *(checksum + (sizeof (unsigned long) * i)) = 0; /* * Get chunk of memory for writing scratch data */ printf ("\n\tGet shared memory segment (%d bytes)\n", buffer_size); if ((shmptr = mmap (0, buffer_size, PROT_READ | PROT_WRITE, MAP_ANON | MAP_SHARED, -1, 0)) == MAP_FAILED) sys_error ("mmap failed", __LINE__); /* * Parent: * * Fill buffer with data.. */ cksum = value = 0; printf ("\n\tParent: calculate shared memory segment checksum\n"); write_lock (lockfd); for (ptr=shmptr; ptr < (shmptr+buffer_size); ptr++) { *ptr = value++; cksum += *ptr; } unlock_file (lockfd); printf ("\t shared memory checksum %08lx\n", cksum); printf ("\n\tSpawning %d child processes ... \n", num_children); for (i=0; i<num_children; i++) { if ((pid [i] = fork()) == (pid_t)0) { child (i, shmptr); exit (0); } else if (pid [i] < (pid_t)0) sys_error ("fork failed", __LINE__); } /* * Wait for child processes to compute checksum and complete... */ for (i=0; i<num_children; i++) { waitpid (pid [i], &status, 0); if (!WIFEXITED (status)) sys_error ("child process terminated abnormally", __LINE__); if (cksum != *(checksum + (sizeof (unsigned long) * i))) { printf ("checksum [%d] = %08lx\n", i, checksum [i]); error ("checksums do not match", __LINE__); } } printf ("\n\tParent: children calculated segment successfully\n"); /* * Program completed successfully -- exit */ printf ("\nsuccessful!\n"); return (0); }
int main() { char *cp = NULL; int pid, pid1, shmid; int status; key = (key_t) getpid(); sigemptyset(&sigset); sigaddset(&sigset, SIGUSR1); sigprocmask(SIG_BLOCK, &sigset, NULL); pid = fork(); switch (pid) { case -1: tst_brkm(TBROK, NULL, "fork failed"); case 0: child(); } /*------------------------------------------------------*/ if ((shmid = shmget(key, SIZE, IPC_CREAT | 0666)) < 0) { perror("shmget"); tst_resm(TFAIL, "Error: shmget: shmid = %d, errno = %d\n", shmid, errno); /* * kill the child if parent failed to do the attach */ (void)kill(pid, SIGINT); } else { cp = shmat(shmid, NULL, 0); if (cp == (char *)-1) { perror("shmat"); tst_resm(TFAIL, "Error: shmat: shmid = %d, errno = %d\n", shmid, errno); /* kill the child if parent failed to do the attch */ kill(pid, SIGINT); /* remove shared memory segment */ rm_shm(shmid); tst_exit(); } *cp = 'A'; *(cp + 1) = 'B'; *(cp + 2) = 'C'; kill(pid, SIGUSR1); while ((pid1 = wait(&status)) < 0 && (errno == EINTR)) ; if (pid1 != pid) { tst_resm(TFAIL, "Waited on the wrong child"); tst_resm(TFAIL, "Error: wait_status = %d, pid1= %d\n", status, pid1); } } tst_resm(TPASS, "shmget,shmat"); /*---------------------------------------------------------------*/ if (shmdt(cp) < 0) { tst_resm(TFAIL, "shmdt"); } tst_resm(TPASS, "shmdt"); /*-------------------------------------------------------------*/ rm_shm(shmid); tst_exit(); }
TestTreeItem *TestTreeItem::childItem(int row) const { return static_cast<TestTreeItem *>(child(row)); }
void FarDlgContainer::SaveState(PropertyMap & state) { for (size_t Index = 0; Index < childs.size(); Index++) if (child(Index).IsContainer() || (bool)child(Index)(L"Persistent")) child(Index).SaveState(state); }
/** Returns the widget in the selected cell. */ twidget* widget(const unsigned row, const unsigned col) { return child(row, col).widget(); }
TextWriter& operator()(const Contact& contact) { (*this)("contact:"); child()(static_cast<const ParamContainer&>(contact)); return *this; }
void gPanel::create(void) { int i; GtkWidget *ch, *box; bool doReparent = false; bool was_visible = isVisible(); GdkRectangle rect; int bg, fg; gControl *nextSibling; if (border) { getGeometry(&rect); bg = background(); fg = foreground(); nextSibling = next(); parent()->remove(this); for (i = 0; i < childCount(); i++) { ch = child(i)->border; g_object_ref(G_OBJECT(ch)); gtk_container_remove(GTK_CONTAINER(widget), ch); } _no_delete = true; gtk_widget_destroy(border); _no_delete = false; doReparent = true; } if (_bg_set) { border = gtk_event_box_new(); widget = gtk_fixed_new(); box = widget; //gtk_widget_set_app_paintable(border, TRUE); //gtk_widget_set_app_paintable(box, TRUE); } else { border = widget = gtk_fixed_new(); box = NULL; } frame = widget; realize(true); //g_signal_connect(G_OBJECT(border), "size-allocate", G_CALLBACK(cb_size), (gpointer)this); //g_signal_connect(G_OBJECT(border), "expose-event", G_CALLBACK(cb_expose), (gpointer)this); if (doReparent) { if (box) gtk_widget_realize(box); setNext(nextSibling); setBackground(bg); setForeground(fg); updateFont(); bufX = bufY = bufW = bufH = -1; setGeometry(&rect); for (i = 0; i < childCount(); i++) { ch = child(i)->border; gtk_container_add(GTK_CONTAINER(widget), ch); moveChild(child(i), child(i)->x(), child(i)->y()); g_object_unref(G_OBJECT(ch)); } if (was_visible) show(); else hide(); //gApplication::checkHoveredControl(this); if (_inside) { _inside = false; if (gApplication::_enter == this) gApplication::_enter = NULL; gApplication::_ignore_until_next_enter = this; } } }
TextWriter& operator()(const ScanWindow& window) { (*this)("scanWindow:"); for_each(window.cvParams.begin(), window.cvParams.end(), child()); return *this; }
int Desktop::handle(int event) { if (event == FL_KEY) { const int numchildren = children(); int previous = focus()>0?focus():0; int i; if (Fl::focus()==this || Fl::focus() && !contains(Fl::focus())) return 0; int key = navigation_key(); if(key) for (i = previous;;) { if (key == FL_Left || key == FL_Up) { if (i) --i; else { if (parent()) return false; i = numchildren-1; } } else { ++i; if (i >= numchildren) { if (parent()) return false; i = 0; } } if (i == previous) break; if (key == FL_Down || key == FL_Up) { // for up/down, the widgets have to overlap horizontally: Fl_Widget* o = child(i); Fl_Widget* p = child(previous); if (o->x() >= p->x()+p->w() || o->x()+o->w() <= p->x()) continue; } if (child(i)->take_focus()) { redraw(); return true; } } return 1; } int ret = Fl_Double_Window::handle(event); switch(event) { case FL_PUSH: if(Fl::event_button()==3) { popup->Fl_Menu_::popup(Fl::event_x_root(), Fl::event_y_root()); } break; case FL_FOCUS: case FL_UNFOCUS: return 1; case FL_DND_ENTER: return 1; case FL_DND_DRAG: cursor((Fl_Cursor)26, 70, 96); case FL_DND_RELEASE: cursor(FL_CURSOR_DEFAULT, FL_BLACK, FL_WHITE); return 1; case FL_PASTE: create_new_dnd_icon(Fl::event_x_root(), Fl::event_y_root(), (char*)Fl::event_text()); return 1; default: break; } return ret; }
TextWriter& operator()(const MSData& msd) { (*this)("msdata:"); child() ("id: " + msd.id); if (!msd.accession.empty()) child()("accession: " + msd.accession); if (!msd.version.empty()) child()("version: " + msd.version); if (!msd.cvs.empty()) child()("cvList: ", msd.cvs); if (!msd.fileDescription.empty()) child()(msd.fileDescription); if (!msd.paramGroupPtrs.empty()) child()("paramGroupList: ", msd.paramGroupPtrs); if (!msd.samplePtrs.empty()) child()("sampleList: " , msd.samplePtrs); if (!msd.instrumentConfigurationPtrs.empty()) child()("instrumentConfigurationList: ", msd.instrumentConfigurationPtrs); if (!msd.softwarePtrs.empty()) child()("softwareList: ", msd.softwarePtrs); if (!msd.dataProcessingPtrs.empty()) child()("dataProcessingList: ", msd.dataProcessingPtrs); if (!msd.run.empty()) child()(msd.run); return *this; }
String FunctorType::defineHtml() const { return tagOf(L"minor symbol", L"((") + toHtml(cardinalChildren()) + tagOf(L"minor symbol", L")") + "<^>" + tagOf(L"symbol", L"→") + toHtml(child(Returned)) + tagOf(L"minor symbol", L")"); }
TextWriter& operator()(const std::string& label, const std::vector<object_type>& v) { (*this)(label); for_each(v.begin(), v.end(), child()); return *this; }
/** * @return a component by index */ CPcbPath* CPcbOutline::path(int idx) { return (CPcbPath*)child("path",idx); }
TextWriter& operator()(const SpectrumIdentificationProtocol& si) { (*this)("SpectrumIdentificationProtocol:"); (*this)((Identifiable&)si); if (si.analysisSoftwarePtr.get() && !si.analysisSoftwarePtr->empty()) child()("analysisSoftware_ref: "+si.analysisSoftwarePtr->id); if (!si.searchType.empty()) child()("SearchType: ", si.searchType); if (!si.additionalSearchParams.empty()) child()("AdditionalSearchParams", si.additionalSearchParams); if (!si.modificationParams.empty()) child()("ModificationParams", si.modificationParams); if (!si.enzymes.empty()) child()(si.enzymes); if (!si.massTable.empty()) child()(si.massTable); if (!si.fragmentTolerance.empty()) child()("FragmentTolerance", si.fragmentTolerance); if (!si.parentTolerance.empty()) child()("ParentTolerance", si.parentTolerance); if (!si.threshold.empty()) child()("Threshold", si.threshold); if (!si.databaseFilters.empty()) child()("DatabaseFilters", si.databaseFilters); if (si.databaseTranslation.get() && !si.databaseTranslation->empty()) child()("DatabaseTranslation", si.databaseTranslation); return *this; }
const std::string& unit_id = child["value"]; map_location loc(child, resources::gamedata); map_location from(child.child_or_empty("from"), resources::gamedata); if ( !actions::recall_unit(unit_id, current_team, loc, from, show, use_undo) ) { error_handler("illegal recall: unit_id '" + unit_id + "' could not be found within the recall list.\n", true); //when recall_unit returned false nothing happend so we can safety return false; return false; } return true; } SYNCED_COMMAND_HANDLER_FUNCTION(attack, child, /*use_undo*/, show, error_handler) { const config &destination = child.child("destination"); const config &source = child.child("source"); //check_checksums(*cfg); if (!destination) { error_handler("no destination found in attack\n", true); return false; } if (!source) { error_handler("no source found in attack \n", true); return false; } //we must get locations by value instead of by references, because the iterators //may become invalidated later
TextWriter& operator()(const IdentData& mzid) { (*this)("mzid:"); child()((Identifiable)mzid); ("version: " + mzid.version()); if (!mzid.cvs.empty()) child()("cvList: ", mzid.cvs); if (!mzid.analysisSoftwareList.empty()) child()("analysisSoftwareList: ", mzid.analysisSoftwareList); if (!mzid.provider.empty()) child()(mzid.provider); if (!mzid.auditCollection.empty()) child()("auditCollection: ", mzid.auditCollection); if (!mzid.analysisSampleCollection.empty()) child()(mzid.analysisSampleCollection); if (!mzid.sequenceCollection.empty()) child()(mzid.sequenceCollection); if (!mzid.analysisCollection.empty()) child()(mzid.analysisCollection); if (!mzid.analysisProtocolCollection.empty()) child()(mzid.analysisProtocolCollection); if (!mzid.dataCollection.empty()) child()(mzid.dataCollection); if (!mzid.bibliographicReference.empty()) child()(mzid.bibliographicReference); return *this; }
// ItmDoWhileFunction::codeGen // // The DoWhile function executes the code represented by child(0) until // the condition represented by child(1) becomes false. The result of // the DoWhile is the final value of child(0). // // The looping is accomplished by inserting a NOOP/BRANCH pair. The NOOP // is inserted before generating the code for either child and serves as a // branch target. The BRANCH is inserted after generating the code for // both children and is targeted at the NOOP clause based on the result of // child(1). Between the NOOP and the BRANCH the body of the loop (child(0)) // and the termination condition (child(1)) are repeatedly evaluated. After // the branch the final result of the loop body is assigned as the result // of the DoWhile. // short ItmDoWhileFunction::codeGen(Generator * generator) { // Get local handles... // Attributes **attr; Space* space = generator->getSpace(); CollHeap *wHeap = generator->wHeap(); ExpGenerator *exp = generator->getExpGenerator(); // If this DoWhile has already been codeGenned, then bug out... // Otherwise, allocate space for the result if necessary and set // attr[0] to point to the result attribute data. Also, mark this // node as codeGenned. // if (exp->genItemExpr(this, &attr, 2, 0) == 1) return 0; // Insert the NOOP clause to use as the branch target for the // start of the loop body. // ex_clause * branchTarget = new(space) ex_noop_clause(); exp->linkClause(this, branchTarget); // CodeGen the body of the loop. // child(0)->codeGen(generator); // The result of the DoWhile is the result of the body of the loop. Set // the src attribute for the convert (added below) to be the body of // the while loop. The dst attribute has already been set in genItemExpr(). // attr[1] = generator->getMapInfo (child(0)->castToItemExpr()->getValueId())->getAttr(); // CodeGen the loop termination condition. // child(1)->codeGen(generator); // Construct a BRANCH clause to loop back and repeat the expression // and condition if the condition evaluates to TRUE. // Attributes ** branchAttrs = new(wHeap) Attributes*[2]; Attributes *boolAttr = generator->getMapInfo (child(1)->castToItemExpr()->getValueId())->getAttr(); branchAttrs[0] = boolAttr->newCopy(wHeap); branchAttrs[1] = boolAttr->newCopy(wHeap); // branchAttrs[0]->copyLocationAttrs(boolAttr); // branchAttrs[1]->copyLocationAttrs(boolAttr); branchAttrs[0]->resetShowplan(); ex_branch_clause * branchClause = new(space) ex_branch_clause(ITM_OR, branchAttrs, space); branchClause->set_branch_clause(branchTarget); // Insert the branch clause into the expression. // exp->linkClause(this, branchClause); // Allocate a convert clause to move the result from child(0) to the // result of this node. This move is necessary so that future // side-effects of the result of child(0) -- if it is a local variable, // for instance -- will not change the result of the DoWhile. // ex_conv_clause * convClause = new(generator->getSpace()) ex_conv_clause (getOperatorType(), attr, space); exp->linkClause(this, convClause); return 0; }