Пример #1
0
void CTaikaDlg::OnTalletaRaportti()
{
    Parse parse;

    if(m_mainShowMode == SHOW_RAPORTIT && pageRaportit.IsWindowVisible())    // Talleta valitut ID_WORKUNIT/ID_SALESUNIT-tiedostoon (.tta)
	{ parse.talletaTTI(this->GetSafeHwnd(), pageRaportit.getMode()); }
}
Пример #2
0
int accepts(const char *str)
{
    std::string input(str);
	Parse p;
	AstNode *stmt = p.parse(input.begin());
	return (stmt->strtail == input.end());
}
Пример #3
0
void processFile(string *src) {
  const char *source = src->c_str();
  Parse parse = Parse();
  char *out = NULL;
  string from = input; from += "/"; from += source;
  string to = temp; to += "/"; to += source;
  if(rename(from.c_str(), to.c_str()) < 0) {
    cerr << "rename failed" << endl;
    return;
  }
  out = parse.parse(to.c_str());
  if(out == NULL) {
    cerr << "wystąpił błąd przy parsowaniu" << to << endl;
  } else {
    string dest = output; dest += "/"; dest += source;
    FILE *destFile = fopen(dest.c_str(), "w");
    if(destFile == NULL) {
      cerr << "nie można otworzyć pliku " << dest << endl;
      return;
    }
    //printf("%p\n", destFile);
    if(fprintf(destFile, "%s", out) < 0) {
      cerr << "fprintf failed" << endl;
      return;
    }
    fclose(destFile);
  }
  if(remove(to.c_str()) < 0) {
    cerr << "nie można usunąć " << to << endl;
    return;
  }
  delete[] out;
  delete src;
}
Пример #4
0
void CTaikaDlg::OnTalletaListat() 
{
    Parse parse;

    if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible())        // Talleta listat
	{ parse.talletaTTA(this->GetSafeHwnd(), "", 0, 0, 0, 0, MODE_SAVE); }
}
Пример #5
0
void Fixture::getArgsForTable(Parse *table)
{
    QStringList argumentList;
    Parse *parameters = table->parts->parts->more;
    for (; parameters ; parameters = parameters->more)
        argumentList.append(parameters->text());
    args = argumentList;
}
Пример #6
0
Fixture* Fixture::getLinkedFixtureWithArgs(Parse *tables)
{
    Parse *header = tables->at(0, 0, 0);
    Fixture *fixture = loadFixture(header->text());
    fixture->counts = counts;
    fixture->summary = summary;
    fixture->getArgsForTable(tables);
    return fixture;
}
Пример #7
0
/////////////////////////////////////////////////////////////////////////////
// IDM_LISTAT_MENU - Menu itemien viestit
void CTaikaDlg::OnAvaaListat() 
{
    Parse parse;

    if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible())        // Avaa .tta-tiedosto
	{ if(!parse.avaaTTA(this->GetSafeHwnd())) return; }

    paivitaNaytot(FALSE, FALSE, FALSE, SYNC_ALL);
}
Пример #8
0
void Search::process()
{
    Parse parse;
    m_videoList = parse.parseRSS(m_document);

    QDomNodeList entries = m_document.elementsByTagName("channel");

    if (entries.count() == 0)
    {
        m_numResults = 0;
        m_numReturned = 0;
        m_numIndex = 0;
        return;
    }

    QDomNode itemNode = entries.item(0);

    QDomNode Node = itemNode.namedItem(QString("numresults"));
    if (!Node.isNull())
    {
        m_numResults = Node.toElement().text().toUInt();
    }
    else
    {
        QDomNodeList count = m_document.elementsByTagName("item");

        if (count.count() == 0)
            m_numResults = 0;
        else
            m_numResults = count.count();
    }

    Node = itemNode.namedItem(QString("returned"));
    if (!Node.isNull())
    {
        m_numReturned = Node.toElement().text().toUInt();
    }
    else
    {
        QDomNodeList entries = m_document.elementsByTagName("item");

        if (entries.count() == 0)
            m_numReturned = 0;
        else
            m_numReturned = entries.count();
    }

    Node = itemNode.namedItem(QString("startindex"));
    if (!Node.isNull())
    {
        m_numIndex = Node.toElement().text().toUInt();
    }
    else
        m_numIndex = 0;

}
Пример #9
0
int main(int argc, char **argv) {
  if(argc < 2) {
    cerr << "musisz podać plik jako argument" << endl;
    return -1;
  }
  Parse parse;
  char *out = parse.parse((const char*)argv[1]);
  if(out != NULL) printf("%s\n", out);
  return 0;
}
Пример #10
0
/////////////////////////////////////////////////////////////////////////////
// IDM_TYOMATKAT_MENU - Menu itemien viestit
void CTaikaDlg::OnAvaaRaporttiTm() 
{
    //int s;
    Parse parse;

    if(m_mainShowMode == SHOW_TYOMATKAT && pageTyomatkat.IsWindowVisible())  // Avaa .tti-tiedosto
	{ if(!parse.avaaTTI(this->GetSafeHwnd())) return; }

	paivitaNaytot(TRUE, TRUE, FALSE, SYNC_ALL);
}
Пример #11
0
void CTaikaDlg::OnTalletaRaporttiTm() 
{
    Parse parse;
    vector <ItemData_travel*> id_vect;

    // Haetaan GetSaveFileName()-funktiossa valitun tilan mukaan vektoriin talletettavat tiedot
	if(m_mainShowMode != SHOW_TYOMATKAT || !pageTyomatkat.IsWindowVisible()) return;
    pageTyomatkat.haeItemDataList(&id_vect, MODE_TYONTEKIJANTIEDOT);
    if(id_vect.size() > 0)
	{
      parse.talletaTTI_tyomatkat(this->GetSafeHwnd(), id_vect);              // Talletetaan
      pageTyomatkat.vapautaItemDataList(&id_vect, MODE_TYONTEKIJANTIEDOT);   // Vapautetaan muisti
	}
}
Пример #12
0
LRESULT CTaikaDlg::OnMsgUusiRaportti(WPARAM wparam, LPARAM lparam)
{
    //int s;
    Parse parse;

    this->BringWindowToTop();

    parse.parseSaapuneet(PARSE_ADD_FILE);   // Parsitaan saapuneet lista ja päivitetään näytöt

    if(wparam == PARAM_TTI || wparam == PARAM_TTA)
      paivitaNaytot(TRUE, TRUE, FALSE, SYNC_ALL);

    return 0;
}
 bool AttachContextGenerator::containsPunct(Collection<Parse*> *puncts, const std::string &punct)
 {
   if (puncts != 0)
   {
     for (Collection<Parse*>::const_iterator pi = puncts->begin(); pi != puncts->end(); ++pi)
     {
       Parse *p = *pi;
       if (p->getType() == punct)
       {
         return true;
       }
     }
   }
   return false;
 }
Пример #14
0
void GrabberScript::parseDBTree(const QString &feedtitle, const QString &path,
                                const QString &pathThumb, QDomElement& domElem,
                                const ArticleType &type)
{
    QMutexLocker locker(&m_lock);

    Parse parse;
    ResultItem::resultList articles;

    // File Handling
    QDomElement fileitem = domElem.firstChildElement("item");
    while (!fileitem.isNull())
    {   // Fill the article list...
        articles.append(parse.ParseItem(fileitem));
        fileitem = fileitem.nextSiblingElement("item");
    }

    while (!articles.isEmpty())
    {   // Insert the articles in the DB...
        insertTreeArticleInDB(feedtitle, path,
                       pathThumb, articles.takeFirst(), type);
    }

    // Directory Handling
    QDomElement diritem = domElem.firstChildElement("directory");
    while (!diritem.isNull())
    {
        QDomElement subfolder = diritem;
        QString dirname = diritem.attribute("name");
        QString dirthumb = diritem.attribute("thumbnail");
        dirname.replace("/", "|");
        QString pathToUse;

        if (path.isEmpty())
            pathToUse = dirname;
        else
            pathToUse = QString("%1/%2").arg(path).arg(dirname);

        parseDBTree(feedtitle,
                    pathToUse,
                    dirthumb,
                    subfolder,
                    type);
        diritem = diritem.nextSiblingElement("directory");
    }
}
Пример #15
0
int main() {

    string line = "";
    cout << "> ";
    while (getline(cin, line))
    {
        if (line == "quit")
        {
            cout << "\tquit\n";
            return 0;
        }
        Parse parse;
        parse.ReadInput(line);
        line = "";
        cout << "> ";

    }
    return 0;
}
Пример #16
0
int main()
{
	cout << "\nRunning Daniel's Shell\n" << "Created by dyc8av\n" << endl;
	//while there is still input from the user
	while(true) {

		Parse p; // create parse in order to call methods from
		string input = ""; // where raw input is stored
		char* cinput = NULL;
		vector<pid_t> spid;
		int status;
		vector<string> sTokens; //where tokens are stored unorganized
		int nTokens = 0;
		getline(cin,input);

// -------------------- parsing input --------------------------

		if(cin.eof()) { // break if end-of-file
			exit(0);
		}
		else if(input == "exit") { // break if "exit"
			exit(0);
	}
		else if(input.length() > 100) { // reload while loop if over 100 characters
			cout << "Your input is over 100 characters." << endl;
			continue;
		}
		else if(!p.legalChar(input)) { // reload while loop of invalid characters
			cout << "Your input contains invalid characters." << endl;
			continue;
		}
		else if (!p.checkPipe(input)) { // check pipe location is valid
			cout << "Your input ends in a pipe!" << endl;
			continue;
		}
		else if (!p.checkIn(input)) { // check if < location is valid
			cout << "Your input ends in an operator!" << endl;
			continue;
		}
		else if (!p.checkOut(input)) { // check if > location is valid
			cout << "Your input ends in an operator!" << endl;
			continue;
		}
		else {

		//parse the input line into appropiate tokens
			cinput = new char[input.size() +1];
			strcpy(cinput,input.c_str());
			char* tokens = strtok(cinput," ");
		while(tokens != NULL) { //read and split into tokens 
			sTokens.push_back(strdup(tokens));
			nTokens++;
			tokens = strtok(NULL," ");
		}

// ---------------------- end parsing -------------------------------

		//create vector of list of inputs to be execv()
		//combine into token groups with operators
		vector< vector<string> > tokenVec = p.tokenGroup(sTokens,nTokens);

		//execv the commands
		for(int i = 0; i < tokenVec.size(); i++) {
			// if the command is a pipe
			if(tokenVec[i][0] == "|") {
				const char **lastVec1 = p.changev(tokenVec[i-1]);
				const char **lastVec2 = p.changev(tokenVec[i+1]);
				p.pipeThese((char **) lastVec1,(char **) lastVec2);
			}
			// if direction in
			else if(tokenVec[i][0] == "<") {
				const char **execVec = p.changev(tokenVec[i-1]);
				const char **fileVec = p.changev(tokenVec[i+1]);
				p.redirectIN((char **) execVec, fileVec[0]);
			}
			// if direction out
			else if(tokenVec[i][0] == ">") {
				const char **execVec = p.changev(tokenVec[i-1]);
				const char **fileVec = p.changev(tokenVec[i+1]);
				p.redirectOUT((char **) execVec, fileVec[0]);

			}
			else {
				if(i < tokenVec.size()-1) {
					// check if next token is a command, then wait to execv() that command
					if(tokenVec[i+1][0] == "|" || tokenVec[i+1][0] == ">" || tokenVec[i+1][0] == "<" ) {
						continue;
					}
					else {
						pid_t pid;
						pid = fork(); // fork the process
						if(pid == 0) {// child
						//convert vector<string> to appropiate format
							const char **lastVec = p.changev(tokenVec[i]);
							execv(lastVec[0], (char **) lastVec);
						}
						else {
							spid.push_back(pid);
						}
					}
				}
				if(tokenVec.size() == 1) { // for first case
					pid_t pid;
						pid = fork(); // fork the process
						if(pid == 0) { // child
							const char **lastVec = p.changev(tokenVec[i]);
							execv(lastVec[0], (char **) lastVec);
						}
						else {
							spid.push_back(pid);

						}
					}
				}
			}

			// used to wait for children to finish and can check status
			for(int i = 0; i < spid.size(); i++) {
				waitpid(spid[i],&status,0);
			}
		}

	}
	return 0;
}
Пример #17
0
void RSSEditPopup::SlotSave(QNetworkReply* reply)
{
    QDomDocument document;
    document.setContent(reply->read(reply->bytesAvailable()), true);

    QString text = document.toString();

    QString title = m_titleEdit->GetText();
    QString description = m_descEdit->GetText();
    QString author = m_authorEdit->GetText();
    QString file = m_thumbImage->GetFilename();

    LOG(VB_GENERAL, LOG_DEBUG, QString("Text to Parse: %1").arg(text));

    QDomElement root = document.documentElement();
    QDomElement channel = root.firstChildElement ("channel");
    if (!channel.isNull())
    {
        Parse parser;
        if (title.isEmpty())
            title = channel.firstChildElement("title").text().trimmed();
        if (description.isEmpty())
            description = channel.firstChildElement("description").text();
        if (author.isEmpty())
            author = parser.GetAuthor(channel);
        if (author.isEmpty())
            author = channel.firstChildElement("managingEditor").text();
        if (author.isEmpty())
            author = channel.firstChildElement("webMaster").text();

        QString thumbnailURL =
            channel.firstChildElement("image").attribute("url");
        if (thumbnailURL.isEmpty())
        {
            QDomElement thumbElem = channel.firstChildElement("image");
            if (!thumbElem.isNull())
                thumbnailURL = thumbElem.firstChildElement("url").text();
        }
        if (thumbnailURL.isEmpty())
        {
            QDomNodeList nodes = channel.elementsByTagNameNS(
                           "http://www.itunes.com/dtds/podcast-1.0.dtd",
                           "image");
            if (nodes.size())
            {
                thumbnailURL =
                    nodes.at(0).toElement().attributeNode("href").value();
                if (thumbnailURL.isEmpty())
                    thumbnailURL = nodes.at(0).toElement().text();
            }
        }

        bool download;
        if (m_download->GetCheckState() == MythUIStateType::Full)
            download = true;
        else
            download = false;

        QDateTime updated = MythDate::current();
        QString filename("");

        if (!file.isEmpty())
            filename = file;
        else if (!thumbnailURL.isEmpty())
            filename = thumbnailURL;

        QString link = m_urlEdit->GetText();

        RSSSite site(title, filename, VIDEO_PODCAST, description, link,
                     author, download, MythDate::current());
        if (insertInDB(&site))
            emit Saving();
    }

    Close();
}
Пример #18
0
                void ParserEventStream::addParseEvents(std::vector<Event*> &parseEvents, Parse chunks[])
                {
                  /// <summary>
                  /// Frontier nodes built from node in a completed parse.  Specifically,
                  /// they have all their children regardless of the stage of parsing.
                  /// </summary>
                  std::vector<Parse*> rightFrontier = std::vector<Parse*>();
                  std::vector<Parse*> builtNodes = std::vector<Parse*>();
                  /// <summary>
                  /// Nodes which characterize what the parse looks like to the parser as its being built.
                  /// Specifically, these nodes don't have all their children attached like the parents of
                  /// the chunk nodes do.
                  /// </summary>
                  Parse currentChunks[sizeof(chunks) / sizeof(chunks[0])];
                  for (int ci = 0;ci < sizeof(chunks) / sizeof(chunks[0]);ci++)
                  {
                    currentChunks[ci] = static_cast<Parse*>(chunks[ci]->clone());
                    currentChunks[ci]->setPrevPunctuation(chunks[ci]->getPreviousPunctuationSet());
                    currentChunks[ci]->setNextPunctuation(chunks[ci]->getNextPunctuationSet());
                    currentChunks[ci]->setLabel(Parser::COMPLETE);
                    chunks[ci]->setLabel(Parser::COMPLETE);
                  }
                  for (int ci = 0;ci < sizeof(chunks) / sizeof(chunks[0]);ci++)
                  {
                    //System.err.println("parserEventStream.addParseEvents: chunks="+Arrays.asList(chunks));
                    Parse *parent = chunks[ci]->getParent();
                    Parse *prevParent = chunks[ci];
                    int off = 0;
                    //build un-built parents
                    if (!chunks[ci]->isPosTag())
                    {
                      builtNodes.push_back(off++,chunks[ci]);
                    }
                    //perform build stages
                    while (parent->getType() != AbstractBottomUpParser::TOP_NODE && parent->getLabel() == "")
                    {
                      if (parent->getLabel() == "" && prevParent->getType() != parent->getType())
                      {
                        //build level
                        if (debug)
                            System::err::println("Build: " + parent->getType() + " for: " + currentChunks[ci]);
                        if (etype == opennlp::tools::parser::BUILD)
                        {
                          parseEvents.push_back(new Event(parent->getType(), buildContextGenerator->getContext(currentChunks, ci)));
                        }
                        builtNodes.push_back(off++,parent);
                        Parse *newParent = new Parse(currentChunks[ci]->getText(),currentChunks[ci]->getSpan(),parent->getType(),1,0);
                        newParent->add(currentChunks[ci],rules);
                        newParent->setPrevPunctuation(currentChunks[ci]->getPreviousPunctuationSet());
                        newParent->setNextPunctuation(currentChunks[ci]->getNextPunctuationSet());
                        currentChunks[ci]->setParent(newParent);
                        currentChunks[ci] = newParent;
                        newParent->setLabel(Parser::BUILT);
                        //see if chunk is complete
                        if (lastChild(chunks[ci], parent))
                        {
                          if (etype == opennlp::tools::parser::CHECK)
                          {
                            parseEvents.push_back(new Event(Parser::COMPLETE, checkContextGenerator->getContext(currentChunks[ci],currentChunks, ci,false)));
                          }
                          currentChunks[ci]->setLabel(Parser::COMPLETE);
                          parent->setLabel(Parser::COMPLETE);
                        }
                        else
                        {
                          if (etype == opennlp::tools::parser::CHECK)
                          {
                            parseEvents.push_back(new Event(Parser::INCOMPLETE, checkContextGenerator->getContext(currentChunks[ci],currentChunks,ci,false)));
                          }
                          currentChunks[ci]->setLabel(Parser::INCOMPLETE);
                          parent->setLabel(Parser::COMPLETE);
                        }

                        chunks[ci] = parent;
                        //System.err.println("build: "+newParent+" for "+parent);
                      }
                      //TODO: Consider whether we need to set this label or train parses at all.
                      parent->setLabel(Parser::BUILT);
                      prevParent = parent;
                      parent = parent->getParent();
                    }
                    //decide to attach
                    if (etype == opennlp::tools::parser::BUILD)
                    {
                      parseEvents.push_back(new Event(Parser::DONE, buildContextGenerator->getContext(currentChunks, ci)));
                    }
                    //attach node
                    std::string attachType = "";
                    /// <summary>
                    /// Node selected for attachment. </summary>
                    Parse *attachNode = 0;
                    int attachNodeIndex = -1;
                    if (ci == 0)
                    {
                      Parse *top = new Parse(currentChunks[ci]->getText(),new Span(0,currentChunks[ci]->getText()->length()),AbstractBottomUpParser::TOP_NODE,1,0);
                      top->insert(currentChunks[ci]);
                    }
                    else
                    {
                      /// <summary>
                      /// Right frontier consisting of partially-built nodes based on current state of the parse. </summary>
                      std::vector<Parse*> currentRightFrontier = Parser::getRightFrontier(currentChunks[0],punctSet);
                      if (currentRightFrontier.size() != rightFrontier.size())
                      {
                        System::err::println("fontiers mis-aligned: " + currentRightFrontier.size() + " != " + rightFrontier.size() + " " + currentRightFrontier + " " + rightFrontier);
                        exit(1);
                      }
                      Map<Parse*, int> *parents = getNonAdjoinedParent(chunks[ci]);
                      //try daughters first.
                      for (int cfi = 0;cfi < currentRightFrontier.size();cfi++)
                      {
                        Parse *frontierNode = rightFrontier[cfi];
                        Parse *cfn = currentRightFrontier[cfi];
                        if (!Parser::checkComplete || Parser::COMPLETE != cfn->getLabel())
                        {
                          int i = parents->get(frontierNode);
                          if (debug)
                              System::err::println("Looking at attachment site (" + cfi + "): " + cfn->getType() + " ci=" + i + " cs=" + nonPunctChildCount(cfn) + ", " + cfn + " :for " + currentChunks[ci]->getType() + " " + currentChunks[ci] + " -> " + parents);
                          if (attachNode == 0 && i != 0 && i == nonPunctChildCount(cfn))
                          {
                            attachType = Parser::ATTACH_DAUGHTER;
                            attachNodeIndex = cfi;
                            attachNode = cfn;
                            if (etype == opennlp::tools::parser::ATTACH)
                            {
                              parseEvents.push_back(new Event(attachType, attachContextGenerator->getContext(currentChunks, ci, currentRightFrontier, attachNodeIndex)));
                            }
                            //System.err.println("daughter attach "+attachNode+" at "+fi);
                          }
                        }
                        else
                        {
                          if (debug)
                              System::err::println("Skipping (" + cfi + "): " + cfn->getType() + "," + cfn->getPreviousPunctuationSet() + " " + cfn + " :for " + currentChunks[ci]->getType() + " " + currentChunks[ci] + " -> " + parents);
                        }
                        // Can't attach past first incomplete node.
                        if (Parser::checkComplete && cfn->getLabel() == Parser::INCOMPLETE)
                        {
                          if (debug)
                              System::err::println("breaking on incomplete:" + cfn->getType() + " " + cfn);
                          break;
                        }
                      }
                      //try sisters, and generate non-attach events.
                      for (int cfi = 0;cfi < currentRightFrontier.size();cfi++)
                      {
                        Parse *frontierNode = rightFrontier[cfi];
                        Parse *cfn = currentRightFrontier[cfi];
                        if (attachNode == 0 && parents->containsKey(frontierNode->getParent()) && frontierNode->getType() == frontierNode->getParent()->getType()) //&& frontierNode.getParent().getLabel() == null) {
                        {
                          attachType = Parser::ATTACH_SISTER;
                          attachNode = cfn;
                          attachNodeIndex = cfi;
                          if (etype == opennlp::tools::parser::ATTACH)
                          {
                            parseEvents.push_back(new Event(Parser::ATTACH_SISTER, attachContextGenerator->getContext(currentChunks, ci, currentRightFrontier, cfi)));
                          }
                          chunks[ci]->getParent()->setLabel(Parser::BUILT);
                          //System.err.println("in search sister attach "+attachNode+" at "+cfi);
                        }
                        else if (cfi == attachNodeIndex)
                        {
                          //skip over previously attached daughter.
                        }
                        else
                        {
                          if (etype == opennlp::tools::parser::ATTACH)
                          {
                            parseEvents.push_back(new Event(Parser::NON_ATTACH, attachContextGenerator->getContext(currentChunks, ci, currentRightFrontier, cfi)));
                          }
                        }
                        //Can't attach past first incomplete node.
                        if (Parser::checkComplete && cfn->getLabel() == Parser::INCOMPLETE)
                        {
                          if (debug)
                              System::err::println("breaking on incomplete:" + cfn->getType() + " " + cfn);
                          break;
                        }
                      }
                      //attach Node
                      if (attachNode != 0)
                      {
                        if (attachType == Parser::ATTACH_DAUGHTER)
                        {
                          Parse *daughter = currentChunks[ci];
                          if (debug)
                              System::err::println("daughter attach a=" + attachNode->getType() + ":" + attachNode + " d=" + daughter + " com=" + lastChild(chunks[ci], rightFrontier[attachNodeIndex]));
                          attachNode->add(daughter,rules);
                          daughter->setParent(attachNode);
                          if (lastChild(chunks[ci], rightFrontier[attachNodeIndex]))
                          {
                            if (etype == opennlp::tools::parser::CHECK)
                            {
                              parseEvents.push_back(new Event(Parser::COMPLETE, checkContextGenerator->getContext(attachNode,currentChunks,ci,true)));
                            }
                            attachNode->setLabel(Parser::COMPLETE);
                          }
                          else
                          {
                            if (etype == opennlp::tools::parser::CHECK)
                            {
                              parseEvents.push_back(new Event(Parser::INCOMPLETE, checkContextGenerator->getContext(attachNode,currentChunks,ci,true)));
                            }
                          }
                        }
                        else if (attachType == Parser::ATTACH_SISTER)
                        {
                          Parse *frontierNode = rightFrontier[attachNodeIndex];
                          rightFrontier[attachNodeIndex] = frontierNode->getParent();
                          Parse *sister = currentChunks[ci];
                          if (debug)
                              System::err::println("sister attach a=" + attachNode->getType() + ":" + attachNode + " s=" + sister + " ap=" + attachNode->getParent() + " com=" + lastChild(chunks[ci], rightFrontier[attachNodeIndex]));
                          Parse *newParent = attachNode->getParent()->adjoin(sister,rules);

                          newParent->setParent(attachNode->getParent());
                          attachNode->setParent(newParent);
                          sister->setParent(newParent);
                          if (attachNode == currentChunks[0])
                          {
                            currentChunks[0] = newParent;
                          }
                          if (lastChild(chunks[ci], rightFrontier[attachNodeIndex]))
                          {
                            if (etype == opennlp::tools::parser::CHECK)
                            {
                              parseEvents.push_back(new Event(Parser::COMPLETE, checkContextGenerator->getContext(newParent,currentChunks,ci,true)));
                            }
                            newParent->setLabel(Parser::COMPLETE);
                          }
                          else
                          {
                            if (etype == opennlp::tools::parser::CHECK)
                            {
                              parseEvents.push_back(new Event(Parser::INCOMPLETE, checkContextGenerator->getContext(newParent,currentChunks,ci,true)));
                            }
                            newParent->setLabel(Parser::INCOMPLETE);
                          }

                        }
                        //update right frontier
                        for (int ni = 0;ni < attachNodeIndex;ni++)
                        {
                          //System.err.println("removing: "+rightFrontier.get(0));
                          rightFrontier.remove(0);
                        }
                      }
                      else
                      {
                        //System.err.println("No attachment!");
                        throw std::exception("No Attachment: " + chunks[ci]);
                      }
                    }
                    rightFrontier.addAll(0,builtNodes);
                    builtNodes.clear();
                  }
                }
Пример #19
0
}


// --------------------------------------------------------------------------------------
#ifndef _WIN32
HttpRequest::HttpRequest(FILE *fil) : HttpTransaction()
, m_server_port(0)
, m_is_ssl(false)
, m_body_file(NULL)
, m_form(NULL)
{
	int i = 0;
DEB(	std::cout << "Initialize HttpRequest from cgi...\n";)
	while (environ[i] && *environ[i])
	{
		Parse pa(environ[i], "=");
		std::string key = pa.getword();
		std::string value = pa.getrest();
		if (key == "REQUEST_METHOD")
			m_method = value;
		else
		if (key == "SERVER_PROTOCOL")
			m_protocol = value;
		else
		if (key == "PATH_INFO")
			m_req_uri = value;
		else
		if (key == "REMOTE_ADDR")
			m_remote_addr = value;
		else
		if (key == "REMOTE_HOST")
Пример #20
0
void RSSEditPopup::slotSave(QNetworkReply* reply)
{
    QDomDocument document;
    document.setContent(reply->read(reply->bytesAvailable()), true);

    QString text = document.toString();

    QString title = m_titleEdit->GetText();
    QString description = m_descEdit->GetText();
    QString author = m_authorEdit->GetText();
    QString file = m_thumbImage->GetFilename();

    bool download;
    if (m_download->GetCheckState() == MythUIStateType::Full)
        download = true;
    else
        download = false;

    VERBOSE(VB_GENERAL|VB_EXTRA, QString("Text to Parse: %1").arg(text));

    QDomElement root = document.documentElement();
    QDomElement channel = root.firstChildElement ("channel");
    if (!channel.isNull ())
    {
        Parse parser;
        if (title.isEmpty())
            title = channel.firstChildElement("title").text().trimmed();
        if (description.isEmpty())
            description = channel.firstChildElement("description").text();
        if (author.isEmpty())
            author = parser.GetAuthor(channel);
        if (author.isEmpty())
            author = channel.firstChildElement("managingEditor").text();
        if (author.isEmpty())
            author = channel.firstChildElement("webMaster").text();

        QString thumbnailURL = channel.firstChildElement("image").attribute("url");
        if (thumbnailURL.isEmpty())
        {
            QDomElement thumbElem = channel.firstChildElement("image");
            if (!thumbElem.isNull())
                thumbnailURL = thumbElem.firstChildElement("url").text();
        }
        if (thumbnailURL.isEmpty())
        {
            QDomNodeList nodes = channel.elementsByTagNameNS(
                           "http://www.itunes.com/dtds/podcast-1.0.dtd", "image");
            if (nodes.size())
            {
                thumbnailURL = nodes.at(0).toElement().attributeNode("href").value();
                if (thumbnailURL.isEmpty())
                    thumbnailURL = nodes.at(0).toElement().text();
            }
        }

        bool download;
        if (m_download->GetCheckState() == MythUIStateType::Full)
            download = true;
        else
            download = false;

        QDateTime updated = QDateTime::currentDateTime();
        QString filename("");

        if (file.isEmpty())
            filename = file;

        QString link = m_urlEdit->GetText();

        if (!thumbnailURL.isEmpty() && filename.isEmpty())
        {
            QString fileprefix = GetConfDir();

            QDir dir(fileprefix);
            if (!dir.exists())
                    dir.mkdir(fileprefix);

            fileprefix += "/MythNetvision";

            dir = QDir(fileprefix);
            if (!dir.exists())
                dir.mkdir(fileprefix);

            fileprefix += "/sitecovers";

            dir = QDir(fileprefix);
            if (!dir.exists())
                dir.mkdir(fileprefix);

            QFileInfo fi(thumbnailURL);
            QString rawFilename = fi.fileName();

            filename = QString("%1/%2").arg(fileprefix).arg(rawFilename);

            bool exists = QFile::exists(filename);
            if (!exists)
                HttpComms::getHttpFile(filename, thumbnailURL, 20000, 1, 2);
        }
        if (insertInDB(new RSSSite(title, filename, VIDEO_PODCAST, description, link,
                author, download, QDateTime::currentDateTime())))
            emit saving();
    }
    Close();
}
Пример #21
0
BOOL CTaikaDlg::OnInitDialog()
{
    int ret;
    RECT trect, crect;
    TCITEM tci;
    CString cs;
    DbSqlite db;
    Parse parse;
    CRect rcSheet;
	string use_db;

	CDialog::OnInitDialog();

	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	// Päällimmäisin dialogi - aluksi raportit
    m_mainShowMode = SHOW_RAPORTIT;

    // Kansiot - luo kansiot, jos niitä ei löydy
    luoKansiot(Props::e().m_app_path);

    // Asetukset - luo perusasetukset, jos ei löydy
    if(Props::i().get(OPTIONS_AIKAJARJESTYS_R) == "")
	{
      use_db = Props::e().m_app_path + DEFAULT_DB_NAME;
      Props::i().set(OPTIONS_DB_PATH, use_db);
      Props::i().set(OPTIONS_DB_NAME, DEFAULT_DB_NAME);
      Props::i().set(OPTIONS_AUTOPARSE, "TRUE");
      Props::i().set(OPTIONS_LASKUTUSOHJELMA, LAS_NONE);
      Props::i().set(OPTIONS_LASKUTUSOHJELMA_POLKU, "c:\\");
      Props::i().set(OPTIONS_LASKUTUSOHJELMA_KOKO_POLKU, "");
      Props::i().set(OPTIONS_KAYNTIKERTAVELOITUS, C_TRUE);
      Props::i().set(OPTIONS_HINNAT, HINNAT_LASKOHJ);
      Props::i().set(OPTIONS_LASKUTUSTILA, LTILA_LASKUTTAMATTOMAT);
	  Props::i().set(OPTIONS_LASKUNMAKSUAIKA, "30");
	  Props::i().set(OPTIONS_YHDISTATAPAHTUMAT, C_TRUE);
      Props::i().set(OPTIONS_OPENPATH, (LPCSTR)Props::e().m_app_path);
      Props::i().set(OPTIONS_SAVEPATH, (LPCSTR)Props::e().m_app_path);
      Props::i().set(OPTIONS_AJAT, StringHelper::itoa(TIME_MINUTES, 10));
      Props::i().set(OPTIONS_ALKAEN_R, DATE_VANHIN_TYO);
      Props::i().set(OPTIONS_PAATTYEN_R, DATE_UUSIN_TYO);
      Props::i().set(OPTIONS_ALKAEN_VIIMEISIN_R, "1.1.2008");
      Props::i().set(OPTIONS_PAATTYEN_VIIMEISIN_R, "1.1.2008");
      Props::i().set(OPTIONS_ALKAEN_T, DATE_VANHIN_TYO);
      Props::i().set(OPTIONS_PAATTYEN_T, DATE_UUSIN_TYO);
      Props::i().set(OPTIONS_ALKAEN_VIIMEISIN_T, "1.1.2008");
      Props::i().set(OPTIONS_PAATTYEN_VIIMEISIN_T, "1.1.2008");
      Props::i().set(OPTIONS_AIKAJARJESTYS_R, DESCENT_S);
      Props::i().set(OPTIONS_AIKAJARJESTYS_T, DESCENT_S);
      Props::i().set(OPTIONS_KMKERROIN, "0.43");
      use_db = Props::e().m_app_path + "varmuuskopiot\\";
      Props::i().set(OPTIONS_DB_BACKUP_PATH, use_db);
      Props::i().set(OPTIONS_EM_RECIPIENTS, "");
      Props::i().set(OPTIONS_EM_FROM, "");
      Props::i().set(OPTIONS_EM_SMTP_SERVER, "");
      Props::i().set(OPTIONS_EM_SMTP_PORT, "25");
      Props::i().set(OPTIONS_PRNT_ASNIMI, PRNT_ASNIMINRO);
      Props::i().set(OPTIONS_PRNT_ASALOITUSPVM, PRNT_PVM_AIKA);
      Props::i().set(OPTIONS_PRNT_ASLOPETUSPVM, PRNT_PVM_AIKA);
      Props::i().set(OPTIONS_PRNT_ASTYOAIKA, PRNT_TYOAIKA_MIN);
      Props::i().set(OPTIONS_PRNT_ASTYOTYYPIT, PRNT_TYOTYYPIT);
      Props::i().set(OPTIONS_PRNT_TTALOITUSPVM, PRNT_PVM_AIKA);
      Props::i().set(OPTIONS_PRNT_TTLOPETUSPVM, PRNT_PVM_AIKA);
      Props::i().set(OPTIONS_PRNT_TTTYOAIKA, PRNT_TYOAIKA_MIN);
      Props::i().set(OPTIONS_PRNT_TTTYOTYYPIT, PRNT_TYOTYYPIT);
      Props::i().set(OPTIONS_PRNT_TMPAIVAYKSET, PRNT_PVM_AIKA_MOLEMMAT);
      Props::i().set(OPTIONS_PRNT_TMMATKA, PRNT_MATKAT_TARKOITUS);
      Props::i().set(OPTIONS_PRNT_TMLUKEMAT, PRNT_LUKEMAT);
      Props::i().set(OPTIONS_PRNT_TMYKSAJOA, PRNT_YKSAJOA);
      Props::i().set(OPTIONS_PRNT_TMTYOAJOA, PRNT_TYOAJOA);
      Props::i().set(OPTIONS_PRNT_SIVUTUS, C_TRUE);
      Props::i().set(OPTIONS_PRNT_YLATUNNISTE_TEXT, "");
      Props::i().set(OPTIONS_PRNT_ALATUNNISTE_TEXT, "");
      Props::i().set(OPTIONS_PRNT_YLATUNNISTE, C_TRUE);
      Props::i().set(OPTIONS_PRNT_ALATUNNISTE, C_TRUE);
      Props::i().set(OPTIONS_PRNT_YLAPAIVAYS, C_TRUE);
      Props::i().set(OPTIONS_PRNT_FONTINKOKO, FONTSIZE_8);
      Props::i().set(OPTIONS_PRNT_FONTINNIMI, "Arial");
      Props::i().set(OPTIONS_PRNT_YHTEENVETO, C_TRUE);
      Props::i().set(OPTIONS_PRNT_KMKORVAUS, C_TRUE);
	  Props::i().set(OPTIONS_PRNT_YHDISTATAPAHTUMAT, C_TRUE);
      Props::i().set(OPTIONS_EM_SMTP_USE_AUTH, C_FALSE);
      Props::i().set(OPTIONS_EM_SMTP_RMBR_UN, C_FALSE);
      Props::i().set(OPTIONS_EM_SMTP_USERNAME, "");
      Props::i().set(OPTIONS_LSTHEADER_RATA, "");
      Props::i().set(OPTIONS_LSTHEADER_RAMY, "");
      Props::i().set(OPTIONS_LSTHEADER_LIAR, "");
      Props::i().set(OPTIONS_LSTHEADER_LIAS, "");
      Props::i().set(OPTIONS_LSTHEADER_LILA, "");
      Props::i().set(OPTIONS_LSTHEADER_LITT, "");
      Props::i().set(OPTIONS_LSTHEADER_LITR, "");
      Props::i().set(OPTIONS_LSTHEADER_LITU, "");
      Props::i().set(OPTIONS_LSTHEADER_TYTY, "");
	}

    // Otetaan tietokannan polku asetuksista, Tarkistetaan tietokanta (luodaan, jos ei ole olemassa)
    Props::e().m_db_path = Props::i().get(OPTIONS_DB_PATH).c_str();
    if((ret = db.check()) != RETURN_OK)
      Props::e().m_db_path = "";   // Virheen sattuessa, ei tietokantaa!!! //EndDialog(IDCANCEL);

    // Tarkistetaan onko saapuneet kansiossa uusia raportteja
    if(ret == RETURN_OK) parse.parseSaapuneet(PARSE_SAAPUNEET);

    // Dialogin otsikko resurssista ja tietokannan nimi asetuksista
    usedDB();

    // Menu paikoilleen (aluksi IDR_RAPORTIT_MENU, asetetaan eri dilogeissa vastaamaan paremmin niiden toimintoja)
	m_pMenu = pageRaportit.createMenu();
    this->SetMenu(m_pMenu);
    AfxGetMainWnd()->DrawMenuBar();

	// Koko ruutu
	ShowWindow(SW_MAXIMIZE);

	// Alustetaan tab-kontolli
    GetClientRect(&crect);
    m_tabMain.SetWindowPos(NULL, 0, 0, crect.right, crect.bottom, SWP_NOMOVE|SWP_NOZORDER);

	tci.mask = TCIF_IMAGE|TCIF_TEXT; tci.iImage = 0; tci.pszText = (LPSTR)(LPCSTR)Props::i().lang("TAIKADLG_1");
    m_tabMain.InsertItem(0, &tci);
    tci.mask = TCIF_IMAGE|TCIF_TEXT; tci.iImage = 0; tci.pszText = (LPSTR)(LPCSTR)Props::i().lang("TAIKADLG_2");
    m_tabMain.InsertItem(1, &tci);
    tci.mask = TCIF_IMAGE|TCIF_TEXT; tci.iImage = 0; tci.pszText = (LPSTR)(LPCSTR)Props::i().lang("TAIKADLG_3");
    m_tabMain.InsertItem(2, &tci);

    // Placeholder ylänurkkaan
    m_tabMain.GetItemRect(0, &trect);                    // tabin headerin koko
    m_tabMain.GetClientRect(&crect);                     // tabin koko
    m_picPlaceHolder.SetWindowPos(NULL, PAGE_LEFT, PAGE_TOP + trect.bottom, crect.right - PAGE_LEFT - PAGE_RIGHT, crect.bottom - trect.bottom - PAGE_TOP - PAGE_BOTTOM, SWP_NOZORDER);

    // Luo dialogit
    pageRaportit.CRHCreateGenericChildDialog(this, IDC_SHEET_PLACEHOLDER, 0, NULL);
    pageListat.CRHCreateGenericChildDialog(this, IDC_SHEET_PLACEHOLDER, 0, NULL);
    pageTyomatkat.CRHCreateGenericChildDialog(this, IDC_SHEET_PLACEHOLDER, 0, NULL);

    // Ja uudestaan menu - dialogien luonti voi sotkea näytettävän menun
	if(m_pMenu) m_pMenu->DestroyMenu();
	m_pMenu = pageRaportit.createMenu();
    this->SetMenu(m_pMenu);
    AfxGetMainWnd()->DrawMenuBar();

	return TRUE;  // return TRUE  unless you set the focus to a control
}
                std::string *AttachContextGenerator::getContext(Parse constituents[], int index, std::vector<Parse*> &rightFrontier, int rfi)
                {
                  std::vector<std::string> features = std::vector<std::string>(100);
                  int nodeDistance = rfi;
                  Parse *fn = rightFrontier[rfi];
                  Parse *fp = 0;
                  if (rfi + 1 < rightFrontier.size())
                  {
                    fp = rightFrontier[rfi + 1];
                  }
                  Parse *p_1 = 0;
                  if (rightFrontier.size() > 0)
                  {
                    p_1 = rightFrontier[0];
                  }
                  Parse *p0 = constituents[index];
                  Parse *p1 = 0;
                  if (index + 1 < sizeof(constituents) / sizeof(constituents[0]))
                  {
                    p1 = constituents[index + 1];
                  }

                  Collection<Parse*> *punct1s = 0;
                  Collection<Parse*> *punct_1s = 0;
                  Collection<Parse*> *punct_1fs = 0;
                  punct_1fs = fn->getPreviousPunctuationSet();
                  punct_1s = p0->getPreviousPunctuationSet();
                  punct1s = p0->getNextPunctuationSet();

                  std::string consfp = cons(fp,-3);
                  std::string consf = cons(fn,-2);
                  std::string consp_1 = cons(p_1,-1);
                  std::string consp0 = cons(p0,0);
                  std::string consp1 = cons(p1,1);

                  std::string consbofp = consbo(fp,-3);
                  std::string consbof = consbo(fn,-2);
                  std::string consbop_1 = consbo(p_1,-1);
                  std::string consbop0 = consbo(p0,0);
                  std::string consbop1 = consbo(p1,1);

                  Cons *cfp = new Cons(consfp,consbofp,-3,true);
                  Cons *cf = new Cons(consf,consbof,-2,true);
                  Cons *c_1 = new Cons(consp_1,consbop_1,-1,true);
                  Cons *c0 = new Cons(consp0,consbop0,0,true);
                  Cons *c1 = new Cons(consp1,consbop1,1,true);

                  //default
                  features.push_back("default");

                  //unigrams
                  features.push_back(consfp);
                  features.push_back(consbofp);
                  features.push_back(consf);
                  features.push_back(consbof);
                  features.push_back(consp_1);
                  features.push_back(consbop_1);
                  features.push_back(consp0);
                  features.push_back(consbop0);
                  features.push_back(consp1);
                  features.push_back(consbop1);

                  //productions
                  std::string prod = production(fn,false);
                  //String punctProd = production(fn,true,punctSet);
                  features.push_back("pn=" + prod);
                  features.push_back("pd=" + prod + "," + p0->getType());
                  features.push_back("ps=" + fn->getType() + "->" + fn->getType() + "," + p0->getType());
                  if (punct_1s != 0)
                  {
                    StringBuffer *punctBuf = new StringBuffer(5);
                    for (Collection<Parse*>::const_iterator pi = punct_1s->begin(); pi != punct_1s->end(); ++pi)
                    {
                      Parse *punct = *pi;
                      punctBuf->append(punct->getType())->append(",");
                    }
                    //features.add("ppd="+punctProd+","+punctBuf.toString()+p0.getType());
                    //features.add("pps="+fn.getType()+"->"+fn.getType()+","+punctBuf.toString()+p0.getType());
                  }

                  //bi-grams
                  //cons(fn),cons(0)
                  cons2(features,cfp,c0,punct_1s,true);
                  cons2(features,cf,c0,punct_1s,true);
                  cons2(features,c_1,c0,punct_1s,true);
                  cons2(features,c0,c1,punct1s,true);
                  cons3(features,cf,c_1,c0,0,punct_1s,true,true,true);
                  cons3(features,cf,c0,c1,punct_1s,punct1s,true,true,true);
                  cons3(features,cfp,cf,c0,0,punct_1s,true,true,true);
                  /*
                  for (int ri=0;ri<rfi;ri++) {
                    Parse jn = (Parse) rightFrontier.get(ri);
                    features.add("jn="+jn.getType());
                  }
                  */
                  int headDistance = (p0->getHeadIndex() - fn->getHeadIndex());
                  features.push_back("hd=" + headDistance);
                  features.push_back("nd=" + nodeDistance);

                  features.push_back("nd=" + p0->getType() + "." + nodeDistance);
                  features.push_back("hd=" + p0->getType() + "." + headDistance);
                  //features.add("fs="+rightFrontier.size());
                  //paired punct features
                  if (containsPunct(punct_1s,"''"))
                  {
                    if (containsPunct(punct_1fs,"``"))
                    {
                      features.push_back("quotematch"); //? not generating feature correctly

                    }
                    else
                    {
                      //features.add("noquotematch");
                    }
                  }
                  return features.toArray(new std::string[features.size()]);
                }
Пример #23
0
void DlgSMTP::OnBtnlaheta() 
{
    // Käyttää tiedostoja: smtp.h, smtp.cpp --- md5.h, md5.cpp --- glob-md5.h --- Base64Coder.h, Base64Coder.cpp
    DWORD e;
    int port;
    time_t tt;
    Parse parse;
    COleDateTime odt;
    CPJNSMTPMessage cmes;
    CPJNSMTPConnection csmtp;
    CPJNSMTPBodyPart cbodypart;
    char temp_path[MAX_PATH * 2];
    CString cs, body, attach_path, subatt;

    this->EnableWindow(FALSE);                       // Kaikki nappulat pois käytöstä
    m_btnLaheta.EnableWindow(FALSE);
    /*m_edtFrom.EnableWindow(FALSE);
    m_edtRecipients.EnableWindow(FALSE);
    m_cmbSMTPServer.EnableWindow(FALSE);
    m_edtSMTPPort.EnableWindow(FALSE);
    m_chkAsiakkaat.EnableWindow(FALSE);
    m_chkLaskuttajat.EnableWindow(FALSE);
    m_chkTyotyypit.EnableWindow(FALSE);
    m_chkTuotteet.EnableWindow(FALSE);
    m_btnPolku.EnableWindow(FALSE); 
    m_btnCancel.EnableWindow(FALSE);
    m_chkKaytaAuth.EnableWindow(FALSE);
    m_chkMuistaUn.EnableWindow(FALSE);
    m_edtUsername.EnableWindow(FALSE);
    m_edtPassword.EnableWindow(FALSE);*/

    try
	{
      if(m_edtRecipients.GetWindowTextLength() == 0) throw(ERR_SMPTP_3);
      if(m_edtFrom.GetWindowTextLength() == 0) throw(ERR_SMPTP_4);
      if(m_cmbSMTPServer.GetWindowTextLength() == 0) throw(ERR_SMPTP_7);
      if(m_edtSMTPPort.GetWindowTextLength() == 0) throw(ERR_SMPTP_8);

	  m_stcInfo.coloredInfo(GetSysColor(COLOR_3DFACE), Props::i().lang("DLGSMTP_4"));

      time(&tt);                                     // Luodaan liitteen ja subject-kentän nimi
      subatt.Format("taikalistat%s%d", _IDENTIFIER_, tt);

      e = GetTempPath(2 * MAX_PATH, temp_path);      // polku TMP- tai TEMP-ympäristömuuttujan kansioon
      if(e == 0 || e > 2 * MAX_PATH) throw(ERR_SMPTP_0);

      // Liite lisätään aina tiedostosta CPJNSMTPBodyPart-luokalle
      if(m_attach_from == IDC_RADLAHDE1)             // Liite t-aika -ohjelmasta (tietokannasta)
	  {
        attach_path = temp_path + subatt + DOT_TTA_EXT;  // polku/tiedostonimi väliaikaiseen tiedostoon
        if(!parse.talletaTTA(this->GetSafeHwnd(), attach_path, m_asiakkaat, m_laskuttajat, m_tyotyypit, m_tuotteet, MODE_ATTACH)) throw(GEN_ERROR);
	  }
      else                                           // Liite tiedostosta
	  {
        attach_path = temp_path + subatt + DOT_TTA_EXT;
        CopyFile(m_attachmentpath, attach_path, FALSE);
	  }

      // NoLoginMethod (HELO), AuthLoginMethod (EHLO -> AUTH LOGIN authentication), CramMD5Method (EHLO -> AUTH CRAM-MD5), LoginPlainMethod (EHLO-> AUTH LOGIN PLAIN)
      port = atoi(m_SMTPPort);
      if(!m_kayta_auth)                              // Ei tunnistautumista palvelimelle
	    csmtp.Connect(m_SMTPServer, CPJNSMTPConnection::AUTH_NONE, "", "", port);
      else                                           // Tunnistaudu palvelimelle
	    csmtp.Connect(m_SMTPServer, CPJNSMTPConnection::AUTH_PLAIN, m_username, m_password, port);

      cmes.SetCharset(_T("iso-8859-1"));                       // : merkistö
      cbodypart.SetCharset(_T("iso-8859-1"));
	  cmes.ParseMultipleRecipients(m_recipients, cmes.m_To);   // :: vastaanottajat
      cmes.m_From = CPJNSMTPAddress(m_from);                   // ::: lähettäjä
      cmes.m_sSubject = subatt;                                // :::: otsikko
      odt = odt.GetCurrentTime();                              // ::::: selkokielinen viesti (jos käyttäjä tutkii sähköpostiaan manuaalisesti)
	  body.Format(Props::i().lang("DLGSMTP_5"), odt.GetDay(), odt.GetMonth(), odt.GetYear(), odt.GetHour(), odt.GetMinute(), odt.GetSecond());
      cmes.AddTextBody(body);
      if(!(cbodypart.SetFilename(attach_path))) throw(ERR_SMPTP_2);	// :::::: liite
      cmes.AddBodyPart(cbodypart);

      csmtp.SendMessage(cmes);                       // Lähetä viesti

	  m_stcInfo.coloredInfo(LIGHTGREEN, Props::i().lang("DLGSMTP_6"));
	}
    catch(int err)
	{
      LPVOID lpMsgBuf;

      e = 0;
      if(err == ERR_SMPTP_0)
	  {
        e = GetLastError();
        FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS, NULL, e, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL/*(va_list *)(DWORD)args*/);
        body.Format(Props::i().lang("DLGSMTP_7"), e, (LPCSTR)lpMsgBuf);
        body.Replace("\r\n", "");
        LocalFree(lpMsgBuf);
	  }
      else if(err == ERR_SMPTP_2) body = Props::i().lang("DLGSMTP_8");
      else if(err == ERR_SMPTP_3) { m_edtRecipients.SetFocus(); body = Props::i().lang("DLGSMTP_9"); }
      else if(err == ERR_SMPTP_4) { m_edtFrom.SetFocus();       body = Props::i().lang("DLGSMTP_10"); }
      else if(err == ERR_SMPTP_7) { m_cmbSMTPServer.SetFocus(); body = Props::i().lang("DLGSMTP_11"); }
      else if(err == ERR_SMPTP_8) { m_edtSMTPPort.SetFocus();   body = Props::i().lang("DLGSMTP_12"); }

      if(e == ERROR_SUCCESS && err == ERR_SMPTP_0) body = Props::i().lang("DLGSMTP_13");

      MessageBox(Props::i().lang("DLGSMTP_14") + body, Props::e().m_app_title, MB_ICONEXCLAMATION|MB_TASKMODAL|MB_TOPMOST|MB_OK);
	  m_stcInfo.coloredInfo(LIGHTRED, Props::i().lang("DLGSMTP_15") + body);
	}
    catch(CPJNSMTPException* pEx)
    {
      CString sMsg;
      if (HRESULT_FACILITY(pEx->m_hr) == FACILITY_ITF)
        sMsg.Format(_T(Props::i().lang("DLGSMTP_16")), pEx->m_hr, pEx->GetErrorMessage().operator LPCTSTR());
      else
        sMsg.Format(_T(Props::i().lang("DLGSMTP_17")), pEx->m_hr, pEx->GetErrorMessage().operator LPCTSTR(), pEx->m_sLastResponse.operator LPCTSTR());

      sMsg.Replace("\r\n", "");
      MessageBox(Props::i().lang("DLGSMTP_18") + sMsg, Props::e().m_app_title, MB_ICONEXCLAMATION|MB_TASKMODAL|MB_TOPMOST|MB_OK);
	  m_stcInfo.coloredInfo(LIGHTRED, Props::i().lang("DLGSMTP_15") + CString(pEx->GetErrorMessage().operator LPCTSTR()));

      pEx->Delete();
	}

    DeleteFile(attach_path);                         // Poista väliaikainen tiedosto

    this->EnableWindow(TRUE);                        // Kaikki nappulat takaisin käyttöön
    m_btnLaheta.EnableWindow(TRUE);
    /*m_edtFrom.EnableWindow(TRUE);
    m_edtRecipients.EnableWindow(TRUE);
    m_cmbSMTPServer.EnableWindow(TRUE);
    m_edtSMTPPort.EnableWindow(TRUE);
    m_btnCancel.EnableWindow(TRUE);
    if(m_attach_from == IDC_RADLAHDE1)
	{
      m_chkAsiakkaat.EnableWindow(TRUE);
      m_chkLaskuttajat.EnableWindow(TRUE);
      m_chkTyotyypit.EnableWindow(TRUE);
      m_chkTuotteet.EnableWindow(TRUE);
      m_btnPolku.EnableWindow(FALSE);
	}
    else
	{
      m_chkAsiakkaat.EnableWindow(TRUE);
      m_chkLaskuttajat.EnableWindow(TRUE);
      m_chkTyotyypit.EnableWindow(FALSE);
      m_chkTuotteet.EnableWindow(FALSE);
      m_btnPolku.EnableWindow(TRUE);
	}
    m_chkKaytaAuth.EnableWindow(TRUE);
    if(m_kayta_auth)
	{
      m_chkMuistaUn.EnableWindow(TRUE);
      m_edtUsername.EnableWindow(TRUE);
      m_edtPassword.EnableWindow(TRUE);
	}
    else
	{
      m_chkMuistaUn.EnableWindow(FALSE);
      m_edtUsername.EnableWindow(FALSE);
      m_edtPassword.EnableWindow(FALSE);
	}*/
}
Пример #24
0
/**
 * Точка входа
 */
int main(int argc, char** argv) {

	struct params_t {
		const char      * config;
		const char      * group;
		const char      * resource;
		unsigned long     idUser;
		unsigned long     idOwner;
		bool               test;
		bool               version;
	} params;

	params.config     = NULL;
	params.group      = NULL;
	params.resource   = NULL;
	params.idUser     = 1;
	params.idOwner    = 0;
	params.test       = false;

	const char *optString = "c:g:r:u:o:tvh?";

	const struct option longOpts[] = {
			{ "config", required_argument, NULL, 'c' },
			{ "group", required_argument, NULL, 'g' },
			{ "resource", required_argument, NULL, 'r' },
			{ "user-id", no_argument, NULL, 'u' },
			{ "owner-id", no_argument, NULL, 'o' },
			{ "test", no_argument, NULL, 't' },
			{ "version", no_argument, NULL, 'v' },
			{ "help", no_argument, NULL, 'h' },
			{ NULL, no_argument, NULL, 0 }
	};

	int opt, longIndex;

	opt = getopt_long(argc, argv, optString, longOpts, &longIndex);

	while (opt != -1) {

		switch (opt) {

			case 'c':
				params.config   = optarg;
				break;

			case 'g':
				params.group    = optarg;
				break;

			case 'r':
				params.resource = optarg;
				break;

			case 'u':
				params.idUser   = atol(optarg);
				break;

			case 'o':
				params.idOwner  = atol(optarg);
				break;

			case 't':
				params.test     = true;
				break;

			case 'v':
				displayVersion();
				return EXIT_SUCCESS;
				break;

			case 'h':
			case '?':
				displayHelp();
				return EXIT_SUCCESS;
				break;

			/* длинная опция без короткого эквивалента */
			case 0:

				break;
		}

		opt = getopt_long(argc, argv, optString, longOpts, &longIndex);
	}

	if (argc == 1) {
		displayHelp();
		return EXIT_SUCCESS;
	}

	if (params.config == NULL) {
		std::cout << "Please, put path to configuration file -c" << std::endl;
		return EXIT_FAILURE;
	}

	if (!params.test &&
			(params.group == NULL || params.resource == NULL) ) {
		std::cout << "Please, put group -g or resource -r" << std::endl;
		return EXIT_FAILURE;
	}


	Parse * parse = NULL;

	try {

		parse = new Parse();
		parse->setSimulate(params.test);
		parse->setFile(new std::ifstream(params.config));
		parse->load();

		if (!params.test) {

			bool allow;

			if (!parse->getGroups().count(params.group)) {
				throw ParseException(
						"Group " + ( (std::string) params.group ) + " not found in configuration file.");
			}

			allow =
					parse->getGroups().at(params.group)
						->getRules()
							->isAllow(
									params.resource,
									params.idUser,
									params.idOwner);

			if (allow) {
				std::cout << "Access allow" << std::endl;
			} else {
				std::cout << "Access denied" << std::endl;
			}

		}

	} catch (ParseException &e) {
		std::cout << "Error: " << e.what() << std::endl;
	} catch (...) {
		std::cout << "Error: unknown. Please, report about this to developers. "
				<< std::endl;
	}

	if (NULL != parse) {
		delete parse;
	}

	return EXIT_SUCCESS;
}