Пример #1
0
void AttachExternalDialog::rebuildProcessList()
{
    m_model->populate(processList(), m_selfPid);
    m_ui->procView->expandAll();
    m_ui->procView->resizeColumnToContents(0);
    m_ui->procView->resizeColumnToContents(1);
}
Пример #2
0
bool CmdPrint::onClient(DebuggerClient *client) {
  if (DebuggerCommand::onClient(client)) return true;
  if (client->argCount() == 0) {
    return help(client);
  }

  bool watch = false;
  int index = 1;
  if (client->arg(1, "always")) {
    watch = true;
    index++;
  } else if (client->arg(1, "list")) {
    return processList(client);
  } else if (client->arg(1, "clear")) {
    return processClear(client);
  }

  const char *format = NULL;
  for (const char **fmt = Formats; *fmt; fmt++) {
    if (client->arg(index, *fmt)) {
      format = *fmt;
      index++;
      break;
    }
  }
  m_body = client->argRest(index);
  if (watch) {
    client->addWatch(format, m_body);
  }
  processWatch(client, format, m_body);
  return true;
}
QString TextDocumentSerializer::processBlock(QTextBlock block,
                                             QTextFrame::iterator &it)
{
    if(block.textList())
        return processList(it);
    else
        return processBlockContent(block);
}
Пример #4
0
int main()
{
    // get current pid
    pid_t pid = getpid();

    // count processes
    std::cout << "Nb process : " << processCount() << std::endl;

    // display basic information for each one
    std::vector<ProcessInfo> process_list = processList();
    for (ProcessInfo pinfo : process_list)
        std::cout << pinfo << std::endl;

    ProcessInfo pinfo(pid);

    /*
    std::cout << "details for PID : " << pid << std::endl;
    std::cout << "fd : " << pinfo.fds.size() << std::endl;
    for (auto const &pair : pinfo.fds)
        std::cout << pair.first << " -> " << pair.second << std::endl;

    std::cout << "cgroup : " << pinfo.cgroups.size() << std::endl;
    for (struct cgroup_hierarchy_t cgroup : pinfo.cgroups)
        std::cout << cgroup.hierarchy_id << ", " << boost::algorithm::join(cgroup.subsystems, " ") << ", " << cgroup.cgroup << std::endl;

    std::cout << "maps : " << pinfo.maps.size() << std::endl;


    for (struct process_info_t pinfo : processList())
    {
        if (!pinfo.cmdline.empty())
        {
            for (std::string arg : pinfo.cmdline)
            {
                std::cout << arg << " ";
            }
            std::cout << std::endl;
            std::cout << pinfo.pid << std::endl;
        }
    }

    std::cout << "nbProcess " << processCount() << std::endl;
    std::cout << "nbCPU " << getNbCPUs() << std::endl;
    std::cout << "nbCores " << getNbCores() << std::endl;

    std::cout << "testing unix sockets" << std::endl;
    std::vector<struct unix_socket_t> unix_socket_list = getSocketUNIX();
    for (struct unix_socket_t unix_sock : unix_socket_list)
        std::cout << "path: " << unix_sock.path << std::endl;

    std::cout << "testing tcp sockets" << std::endl;
    std::vector<struct tcp_socket_t> tcp_socket_list = getSocketTCP();
    for (struct tcp_socket_t tcp_sock : tcp_socket_list)
    {
        std::cout << tcp_sock.local_address << ":" << tcp_sock.local_port << " " << tcp_sock.rem_address << ":" << tcp_sock.rem_port << std::endl;
    }
    */
}
Пример #5
0
int RemoveRareCommand::execute(){
	try {
		
		if (abort == true) { if (calledHelp) { return 0; }  return 2;	}
		
		if (m->control_pressed) { return 0; }
		
		//read through the correct file and output lines you want to keep
		if (sabundfile != "")		{		processSabund();	}
		if (rabundfile != "")		{		processRabund();	}
		if (listfile != "")			{		processList();		}
		if (sharedfile != "")		{		processShared();	}
		
		if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {	m->mothurRemove(outputNames[i]); } return 0; }
			
		if (outputNames.size() != 0) {
			m->mothurOutEndLine();
			m->mothurOut("Output File Names: "); m->mothurOutEndLine();
			for (int i = 0; i < outputNames.size(); i++) {	m->mothurOut(outputNames[i]); m->mothurOutEndLine();	}
			m->mothurOutEndLine();
			
			//set rabund file as new current rabundfile
			string current = "";
			itTypes = outputTypes.find("rabund");
			if (itTypes != outputTypes.end()) {
				if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setRabundFile(current); }
			}
			
			itTypes = outputTypes.find("sabund");
			if (itTypes != outputTypes.end()) {
				if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setSabundFile(current); }
			}
			
			itTypes = outputTypes.find("group");
			if (itTypes != outputTypes.end()) {
				if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setGroupFile(current); }
			}
			
			itTypes = outputTypes.find("list");
			if (itTypes != outputTypes.end()) {
				if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setListFile(current); }
			}
			
			itTypes = outputTypes.find("shared");
			if (itTypes != outputTypes.end()) {
				if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setSharedFile(current); }
			}
		}
		
		return 0;		
	}
	
	catch(exception& e) {
		m->errorOut(e, "RemoveRareCommand", "execute");
		exit(1);
	}
}
Пример #6
0
void CmdPrint::onClientImpl(DebuggerClient &client) {
  if (DebuggerCommand::displayedHelp(client)) return;
  if (client.argCount() == 0) {
    help(client);
    return;
  }

  int index = 1;
  if (client.arg(1, "always")) {
    m_isForWatch = true;
    if (client.argCount() == 1) {
      client.error("'[p]rint [a]lways' needs an expression to watch.");
      return;
    }
    index++;
  } else if (client.arg(1, "list")) {
    m_isForWatch = true;
    processList(client);
    return;
  } else if (client.arg(1, "clear")) {
    m_isForWatch = true;
    processClear(client);
    return;
  }

  const char *format = nullptr;
  for (const char **fmt = Formats; *fmt; fmt++) {
    if (client.arg(index, *fmt)) {
      format = *fmt;
      index++;
      break;
    }
  }
  m_body = client.lineRest(index);
  if (m_isForWatch) {
    client.addWatch(format, m_body);
    return;
  }
  m_bypassAccessCheck = client.getDebuggerBypassCheck();
  m_printLevel = client.getDebuggerPrintLevel();
  assert(m_printLevel <= 0 || m_printLevel >= DebuggerClient::MinPrintLevel);
  m_frame = client.getFrame();
  CmdPrintPtr res = client.xend<CmdPrint>(this);
  if (!res->is(m_type)) {
    assert(client.isApiMode());
    m_incomplete = true;
    res->setClientOutput(client);
  } else {
    m_output = res->m_output;
    m_ret = res->m_ret;
    if (!m_output.empty()) {
      client.output(m_output);
    }
    client.output(FormatResult(format, m_ret));
  }
}
Пример #7
0
bool CmdMacro::onClient(DebuggerClient *client) {
  if (DebuggerCommand::onClient(client)) return true;
  if (client->argCount() == 0) {
    return help(client);
  }

  if (client->arg(1, "start")) {
    client->startMacro(client->argValue(2));
  } else if (client->arg(1, "end")) {
    client->endMacro();
  } else if (client->arg(1, "replay")) {
    if (!client->playMacro(client->argValue(2))) {
      client->error("Unable to find specified macro.");
      processList(client);
    }
  } else if (client->arg(1, "list")) {
    processList(client);
  } else if (client->arg(1, "clear")) {
    string snum = client->argValue(2);
    if (!DebuggerClient::IsValidNumber(snum)) {
      client->error("'& [c]lear' needs an {index} argument.");
      client->tutorial(
        "You will have to run '& [l]ist' first to see a list of valid "
        "numbers or indices to specify."
      );
      return true;
    }

    int num = atoi(snum.c_str());
    if (!client->deleteMacro(num)) {
      client->error("\"%s\" is not a valid macro index. Choose one from "
                    "this list:", snum.c_str());
      processList(client);
      return true;
    }
  }

  return true;
}
Пример #8
0
void CSVHandler::processFile(const QString &csvFile)
{
    QFile file(csvFile);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return;

    QTextStream in(&file);
    in.setCodec(QTextCodec::codecForName("UTF-8"));
    while (!in.atEnd()) {
        _csvLineList << in.readLine();
    }

    processList();
}
Пример #9
0
bool CmdExtension::onServer(DebuggerProxy *proxy) {
  if (m_args.size() <= 1) {
    return processList(proxy);
  }

  string name = m_args[1];
  Extension *ext = Extension::GetExtension(name);
  if (ext) {
    if (m_args.size() == 2) {
      if (ext->debuggerSupport() & IDebuggable::SupportInfo) {
        IDebuggable::InfoVec info;
        ext->debuggerInfo(info);
        m_out = DebuggerClient::FormatInfoVec(info);
      } else {
        m_err = "Extension doesn't have summary information.";
      }
    } else if (DebuggerClient::Match(m_args[2].c_str(), "dump")) {
      if (ext->debuggerSupport() & IDebuggable::SupportDump) {
        m_out = ext->debuggerDump();
        m_out += "\n";
      } else {
        m_err = "Extension doesn't have detailed dumps.";
      }
    } else {
      if (ext->debuggerSupport() & IDebuggable::SupportVerb) {
        string verb = m_args[2];
        StringVec args;
        if (m_args.size() > 3) {
          args.insert(args.end(), m_args.begin() + 3, m_args.end());
        }
        m_out = ext->debuggerVerb(verb, args);
        m_out += "\n";
      } else {
        m_err = "Extension doesn't support any debugger actions.";
      }
    }
  } else {
    m_err = "Unable to find the specified extension: ";
    m_err += String(name);
  }
  return proxy->send(this);
}
Пример #10
0
void JabberClient::listRequest(JabberUserData *data, const char *name, const char *grp, bool bDelete)
{
    string jid = data->ID;
    list<JabberListRequest>::iterator it;
    for (it = m_listRequests.begin(); it != m_listRequests.end(); ++it){
        if (jid == (*it).jid){
            m_listRequests.erase(it);
            break;
        }
    }
    JabberListRequest lr;
    lr.jid = jid;
    if (name)
        lr.name = name;
    if (grp)
        lr.grp = grp;
    lr.bDelete = bDelete;
    m_listRequests.push_back(lr);
    processList();
}
Пример #11
0
listPo flattenList(heapPo H, listPo l) {
  int root = gcAddRoot(H, (ptrPo) &l);
  integer llen = 0;

  processList(l, countEls, &llen);

  listPo reslt = createList(H, llen);

  for (integer ix = 0; ix < listSize(l); ix++) {
    listPo ll = C_LIST(nthEl(l, ix));
    for (integer jx = 0; jx < listSize(ll); jx++) {
      reslt = addToList(H, reslt, nthEl(ll, jx));
    }
  }

  assert(listSize(reslt) == llen);

  gcReleaseRoot(H, root);
  return reslt;
}
Пример #12
0
void processClientMessage(char* command, char* out_buffer)
{
	/*
	 * If other commands have not implemented logic to overwrite the server's output buffer,
	 *    client calling any any valid command after calling "list" causes the server output
	 *    to still display the list output.
	 */
	printf("**processClientMessage: command=%s\n", command);
	if(strcmp(command, "test") == 0) {
		strcpy(out_buffer, command);
	}
	else if(strcmp(command, "list") == 0) {  //process client command: list
		printf("**processClientMessage/processList\n");
		processList(out_buffer);
	}
	else if(strncmp(command, "check", 5) == 0) {  // processes client command: check filename
		printf("**processClientMessage/processCheck\n");
		char filename[MAXDATASIZE];
		strcpy(filename, command+strlen("check"));
		printf("**processClientMessage/processCheck: filename=%s\n", filename);

		processCheck(out_buffer, filename);
	}
	else if(strncmp(command, "get", 3) == 0) {  // processes client command: get filename
		printf("**processClientMessage/processGet\n");
		char filename[MAXDATASIZE];
		strcpy(filename, command+strlen("get"));
		printf("**processClientMessage/processCheck: filename=%s\n", filename);

		processGet(out_buffer, filename);
	}
	else if(strcmp(command, "quit") == 0) {
		strcpy(out_buffer, "goodbye");
	}
	else {
		printf("**processClientMessage/default\n");
		strcpy(out_buffer, "**command not recognized");
	}

	printf("**exiting processClientMessage\n");
}
//this is where the actual drawing happens
void display() {

	glClear(GL_DEPTH_BUFFER_BIT|GL_COLOR_BUFFER_BIT);

	glLoadIdentity();

	camApply(g_Camera);

	drawFPS();

	processList();

	glFlush();

	if (!g_bPicking) {
		glutSwapBuffers();
	}
	else {
		finishPicking();
	}
}
Пример #14
0
bool CmdPrint::onClient(DebuggerClient *client) {
  if (DebuggerCommand::onClient(client)) return true;
  if (client->argCount() == 0) {
    return help(client);
  }

  bool watch = false;
  int index = 1;
  if (client->arg(1, "always")) {
    if (client->argCount() == 1) {
      client->error("'[p]rint [a]lways' needs an expression to watch.");
      return true;
    }
    watch = true;
    index++;
  } else if (client->arg(1, "list")) {
    return processList(client);
  } else if (client->arg(1, "clear")) {
    return processClear(client);
  }

  const char *format = NULL;
  for (const char **fmt = Formats; *fmt; fmt++) {
    if (client->arg(index, *fmt)) {
      format = *fmt;
      index++;
      break;
    }
  }
  m_body = client->argRest(index);
  m_bypassAccessCheck = client->getBypassAccessCheck();
  m_printLevel = client->getPrintLevel();
  ASSERT(m_printLevel <= 0 || m_printLevel >= DebuggerClient::MinPrintLevel);
  if (watch) {
    client->addWatch(format, m_body);
  }
  processWatch(client, format, m_body);
  return true;
}
Пример #15
0
bool CmdPrint::processClear(DebuggerClient *client) {
  DebuggerClient::WatchPtrVec &watches = client->getWatches();
  if (watches.empty()) {
    client->error("There is no watch expression to clear.");
    client->tutorial(
      "Use '[p]rint [a]lways ...' to set new watch expressions. "
      "Use '[p]rint ?|[h]elp' to read how to set them. "
    );
    return true;
  }

  if (client->arg(2, "all")) {
    watches.clear();
    client->info("All watch expressions are cleared.");
    return true;
  }

  string snum = client->argValue(2);
  if (!DebuggerClient::IsValidNumber(snum)) {
    client->error("'[p]rint [c]lear' needs an {index} argument.");
    client->tutorial(
      "You will have to run '[p]rint [l]ist' first to see a list of valid "
      "numbers or indices to specify."
    );
    return true;
  }

  int num = atoi(snum.c_str()) - 1;
  if (num < 0 || num >= (int)watches.size()) {
    client->error("\"%s\" is not a valid index. Choose one from this list:",
                  snum.c_str());
    processList(client);
    return true;
  }

  watches.erase(watches.begin() + num);
  return true;
}
void LoopInductionVariableHandler::setChildren(std::map<llvm::Value*,std::vector<llvm::Value*> > lc)
{
  for(std::map<llvm::Value*,std::vector<llvm::Value*> >::iterator LCI = lc.begin(); LCI != lc.end(); ++LCI)
  {
    indexData[LCI->first].children = LCI->second;
  }
  for(std::map<llvm::Value*,std::vector<llvm::Value*> >::iterator LCI = lc.begin(); LCI != lc.end(); ++LCI)
  {
    llvm::Value* ALIVI = LCI->first;
    std::vector<llvm::Value*> processList(indexData[ALIVI].children.begin(), indexData[ALIVI].children.end());
    //also, set the children of our direct children as children
    while( !processList.empty() )
    {
      llvm::Value* CI = processList.back();
      processList.pop_back();
      for(std::vector<llvm::Value*>::iterator NI = indexData[CI].children.begin(); NI != indexData[CI].children.end(); ++NI)
      {
        processList.push_back(*NI);
        indexData[ALIVI].children.push_back(*NI);
      }
    }
  }
}
//!-----------------------------------
int main()
{
    greeting();
    processList();
    return 0;
}
Пример #18
0
void CmdThread::onClient(DebuggerClient &client) {
  if (DebuggerCommand::displayedHelp(client)) return;
  if (client.argCount() > 1) {
    help(client);
    return;
  }

  if (client.argCount() == 0) {
    m_body = "info";
    auto res = client.xend<CmdThread>(this);
    client.print(res->m_out);
  } else if (client.arg(1, "list")) {
    processList(client);
  } else if (client.arg(1, "normal")) {
    m_body = "normal";
    client.sendToServer(this);
    client.info("Thread is running in normal mode now. Other threads will "
                 "interleave when they hit breakpoints as well.");
  } else if (client.arg(1, "sticky")) {
    m_body = "sticky";
    client.sendToServer(this);
    client.info("Thread is running in sticky mode now. All other threads "
                 "will wait until this thread finishes, when they hit "
                 "breakpoints.");
  } else if (client.arg(1, "exclusive")) {
    m_body = "exclusive";
    client.sendToServer(this);
    client.info("Thread is running in exclusive mode now. All other threads "
                 "will not break, even when they hit breakpoints.");
  } else {
    std::string snum = client.argValue(1);
    if (!DebuggerClient::IsValidNumber(snum)) {
      client.error("'[t]hread {index}' needs a numeric argument.");
      client.tutorial(
        "You will have to run '[t]hread [l]ist' first to see a list of valid "
        "numbers or indices to specify. Thread 1 is always your current "
        "thread. If that's the only thread on the list, you do not have "
        "another thread at break to switch to."
      );
      return;
    }

    int num = atoi(snum.c_str());
    DThreadInfoPtr thread = client.getThread(num);
    if (!thread) {
      processList(client, false);
      thread = client.getThread(num);
      if (!thread) {
        client.error("\"%s\" is not a valid thread index. Choose one from "
                      "this list:", snum.c_str());
        processList(client);
        return;
      }
    }

    if (thread->m_id == client.getCurrentThreadId()) {
      client.info("This is your current thread already.");
      return;
    }

    m_body = "switch";
    m_threads.push_back(thread);
    client.sendToServer(this);
    throw DebuggerConsoleExitException();
  }
}
Пример #19
0
bool CmdBreak::processUpdate(DebuggerClient *client) {
  m_breakpoints = client->getBreakPoints();
  if (m_breakpoints->empty()) {
    client->error("There is no breakpoint to clear or toggle.");
    client->tutorial(
      "Use '[b]reak ?|[h]elp' to read how to set breakpoints. "
    );
    return true;
  }

  if (client->argCount() == 1) {
    BreakPointInfoPtrVec *matched = client->getMatchedBreakPoints();
    BreakPointInfoPtrVec *bps = client->getBreakPoints();
    bool found = false;
    for (unsigned int i = 0; i < matched->size(); i++) {
      BreakPointInfoPtr bpm = (*matched)[i];
      BreakPointInfoPtr bp;
      int index = 0;
      for (; index < (int)bps->size(); index++) {
        if (bpm->same((*bps)[index])) {
          bp = (*bps)[index];
          break;
        }
      }
      if (bp) {
        const char *action;
        if (hasClearArg(client)) {
          action = "cleared";
          bps->erase(bps->begin() + index);
        } else if (hasEnableArg(client)) {
          action = "updated";
          bp->setState(BreakPointInfo::Always);
        } else if (hasDisableArg(client)) {
          action = "updated";
          bp->setState(BreakPointInfo::Disabled);
        } else {
          assert(hasToggleArg(client));
          action = "updated";
          bp->toggle();
        }
        client->info("Breakpoint %d is %s %s", bp->index(),
                     action, bp->site().c_str());
        found = true;
      }
    }
    if (found) {
      updateImpl(client);
      return true;
    }

    client->error("There is no current breakpoint to clear or toggle.");
    return true;
  }

  if (client->arg(2, "all")) {
    if (hasClearArg(client)) {
      m_breakpoints->clear();
      updateImpl(client);
      client->info("All breakpoints are cleared.");
      return true;
    }

    for (unsigned int i = 0; i < m_breakpoints->size(); i++) {
      BreakPointInfoPtr bpi = (*m_breakpoints)[i];
      if (hasEnableArg(client)) {
        bpi->setState(BreakPointInfo::Always);
      }
      else if (hasDisableArg(client)) {
        bpi->setState(BreakPointInfo::Disabled);
      }
      else {
        assert(hasToggleArg(client));
        bpi->toggle();
      }
    }

    updateImpl(client);
    return processList(client);
  }

  string snum = client->argValue(2);
  if (!DebuggerClient::IsValidNumber(snum)) {
    client->error("'[b]reak [c]lear|[t]oggle' needs an {index} argument.");
    client->tutorial(
      "You will have to run '[b]reak [l]ist' first to see a list of valid "
      "numbers or indices to specify."
    );
    return true;
  }

  int index = -1;
  int num = atoi(snum.c_str());
  for (unsigned int i = 0; i < m_breakpoints->size(); i++) {
    if (m_breakpoints->at(i)->index() == num) {
      index = i;
      break;
    }
  }
  if (index < 0) {
    client->error("\"%s\" is not a valid breakpoint index. Choose one from "
                  "this list:", snum.c_str());
    processList(client);
    return true;
  }

  BreakPointInfoPtr bpi = (*m_breakpoints)[index];
  if (hasClearArg(client)) {
    m_breakpoints->erase(m_breakpoints->begin() + index);
    updateImpl(client);
    client->info("Breakpoint %d cleared %s", bpi->index(),
                 bpi->desc().c_str());
  } else if (hasEnableArg(client)) {
    bpi->setState(BreakPointInfo::Always);
    updateImpl(client);
    client->info("Breakpoint %d's state is changed to %s.", bpi->index(),
                 bpi->state(false).c_str());
  } else if (hasDisableArg(client)) {
    bpi->setState(BreakPointInfo::Disabled);
    updateImpl(client);
    client->info("Breakpoint %d's state is changed to %s.", bpi->index(),
                 bpi->state(false).c_str());
  } else {
    assert(hasToggleArg(client));
    bpi->toggle();
    updateImpl(client);
    client->info("Breakpoint %d's state is changed to %s.", bpi->index(),
                 bpi->state(false).c_str());
  }

  return true;
}
Пример #20
0
//**********************************************************************************************************************
int GetOtusCommand::readListGroup(){
	try {
		InputData* input = new InputData(listfile, "list");
		ListVector* list = input->getListVector();
		string lastLabel = list->getLabel();
		
		//using first label seen if none is provided
		if (label == "") { label = lastLabel; }
        
        string thisOutputDir = outputDir;
		if (outputDir == "") {  thisOutputDir += m->hasPath(listfile);  }
        map<string, string> variables;
        variables["[filename]"] = thisOutputDir + m->getRootName(m->getSimpleName(listfile));
        variables["[tag]"] = label;
        variables["[extension]"] = m->getExtension(listfile);
		string outputFileName = getOutputFileName("list", variables);
		
		ofstream out;
		m->openOutputFile(outputFileName, out);
        
        string GroupOutputDir = outputDir;
		if (outputDir == "") {  GroupOutputDir += m->hasPath(groupfile);  }
        variables["[filename]"] = GroupOutputDir + m->getRootName(m->getSimpleName(groupfile));
        variables["[extension]"] = m->getExtension(groupfile);
		string outputGroupFileName = getOutputFileName("group", variables);
		
		ofstream outGroup;
		m->openOutputFile(outputGroupFileName, outGroup);

		
		//if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
		set<string> labels; labels.insert(label);
		set<string> processedLabels;
		set<string> userLabels = labels;
		
		bool wroteSomething = false;

		//as long as you are not at the end of the file or done wih the lines you want
		while((list != NULL) && (userLabels.size() != 0)) {
			
			if (m->control_pressed) {  delete list; delete input; out.close();  outGroup.close(); m->mothurRemove(outputFileName);  m->mothurRemove(outputGroupFileName);return 0;  }
			
			if(labels.count(list->getLabel()) == 1){
				processList(list, groupMap, out, outGroup, wroteSomething);
				
				processedLabels.insert(list->getLabel());
				userLabels.erase(list->getLabel());
			}
			
			if ((m->anyLabelsToProcess(list->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
				string saveLabel = list->getLabel();
				
				delete list; 
				
				list = input->getListVector(lastLabel);
				
				processList(list, groupMap, out, outGroup, wroteSomething);
				
				processedLabels.insert(list->getLabel());
				userLabels.erase(list->getLabel());
				
				//restore real lastlabel to save below
				list->setLabel(saveLabel);
			}
			
			lastLabel = list->getLabel();
			
			delete list; list = NULL;
			
			//get next line to process
			list = input->getListVector();				
		}
		
		
		if (m->control_pressed) {  if (list != NULL) { delete list; } delete input; out.close(); outGroup.close(); m->mothurRemove(outputFileName);  m->mothurRemove(outputGroupFileName); return 0;  }
		
		//output error messages about any remaining user labels
		set<string>::iterator it;
		bool needToRun = false;
		for (it = userLabels.begin(); it != userLabels.end(); it++) {  
			m->mothurOut("Your file does not include the label " + *it); 
			if (processedLabels.count(lastLabel) != 1) {
				m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
				needToRun = true;
			}else {
				m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
			}
		}
		
		//run last label if you need to
		if (needToRun == true)  {
			if (list != NULL) { delete list; }
			
			list = input->getListVector(lastLabel);
			
			processList(list, groupMap, out, outGroup, wroteSomething);
			
			delete list; list = NULL;
		}
					
		out.close();
		outGroup.close();
		
		if (wroteSomething == false) {  m->mothurOut("At distance " + label + " your file does NOT contain any otus containing sequences from the groups you wish to get."); m->mothurOutEndLine();  }
		outputTypes["list"].push_back(outputFileName); outputNames.push_back(outputFileName);
		outputTypes["group"].push_back(outputGroupFileName); outputNames.push_back(outputGroupFileName);
		
		return 0;
		
	}
	catch(exception& e) {
		m->errorOut(e, "GetOtusCommand", "readList");
		exit(1);
	}
}
// returns false if blocked, true otherwise
bool Statsdb::gifLoop ( ) {
	// shortcut
	Msg5 *m = &m_msg5;

	//#ifndef _USEPLOTTER_
	//return true;
	//#endif

	// loop over all the lists in the time range, [m_t1,m_t2]
	for ( ; ! m_done ; ) {
		if ( ! m->getList ( (char)RDB_STATSDB	,
				    "statsdb"		, // coll
				    &m_list		,
				    (char *)&m_startKey	,
				    (char *)&m_endKey	,
				    32000	, // requested scan size
				    true 	, // include tree?
				    false	, // add to cache?
				    0		, // max cache age
				    0		, // start file number
				    -1		, // number of files
				    NULL	, // state
				    gotListWrapper, // callback
				    m_niceness	, // niceness
				    false	, // do error correction?
				    NULL	, // cache key pointer
				    0		, // # retries
				    -1		, // max # retries
				    true	, // compensate for merge?
				    -1		, // sync point
				    NULL	) ) // msg5b
			return false;
		// . process list
		// . returns false with g_errno set on error
		if ( ! processList() ) return true;
	}

	// define time delta - commented out because it's currently not used.
	long dt = m_t2 - m_t1;

	//#ifdef _USEPLOTTER_

	// gif size
	//char tmp[64];
	// dimensions of the gif
	//sprintf ( tmp , "%lix%li", (long)DX+m_bx*2 , (long)DY+m_by*2 );
	//GIFPlotter::parampl ( "BITMAPSIZE" , (void *)tmp );
	// create one
	//GIFPlotter plotter ( NULL , m_fd , NULL );
	// open it
	//plotter.openpl ( );

	// define the space with boundaries 100 unit wide boundaries
	//plotter.space ( 0 , 0 , DX + m_bx * 2 , DY + m_by * 2 );

	// line thickness in user coordinates (pixels for us)
	//plotter.linewidth ( 1 );       
	// set bg color to gray (r/g/b) 
	//plotter.bgcolor ( 0xd600 , 0xce00 , 0xd600 );
	// erase Plotter's graphics display
	//plotter.erase ();                
	// draw axises in black
	//plotter.pencolorname ("black");    

	//
	// main graphing window
	//
	m_gw.safePrintf("<div style=\"position:relative;"
		      "background-color:#c0c0c0;"
		      //"overflow-y:hidden;"
		      "overflow-x:hidden;"
		      "z-index:-10;"
		      // the tick marks we print below are based on it
		      // being a window of the last 20 seconds... and using
		      // DX pixels
		      "min-width:%lipx;"
		      "min-height:%lipx;"
		      //"width:100%%;"
		      //"min-height:600px;"
		      "margin-top:10px;"
		      "margin-bottom:10px;"
		      "margin-right:10px;"
		      "margin-left:10px;\">"
		      ,(long)DX + 2 *m_bx
			,(long)DY + 2*m_by);


	// draw the x-axis
	//plotter.line ( m_bx , m_by , DX + m_bx , m_by  );

	// 10 x-axis tick marks
	for ( int x = DX/20 ; x <= DX ; x += DX/20 ) {
		// tick mark
		//plotter.line ( x , -20 , x , 20 );
		m_gw.safePrintf("<div style=\"position:absolute;"
			      "left:%li;"
			      "bottom:0;"
			      "background-color:#000000;"
			      "z-index:110;"
			      "min-height:20px;"
			      "min-width:3px;\"></div>\n"
			      , m_bx + (long)x-1
			      );
		long xv = (long)(dt * (long long)x/(long long)DX)-(long)dt;
		// LABEL
		m_gw.safePrintf("<div style=\"position:absolute;"
				"left:%li;"
				"bottom:20;"
				//"background-color:#000000;"
				"z-index:110;"
				"min-height:20px;"
				"min-width:3px;\">%lis</div>\n"
				, (long)x-10 + m_bx
				// the label:
				, xv
				);
	}


	HashTableX tmpht;
	tmpht.set(4,0,0,NULL,0,false,m_niceness,"statsparms");

	long col = 0;

	m_sb2->safePrintf("<table border=1 width=100%%>\n");

	// label offset to prevent collisions of superimposing multiple
	// graph calbrations
	long zoff = 0;


	//
	// point to the triplets in m_sb1's buffer (x,y,c)
	//
	char *p    = m_sb1.getBufStart();
	char *pend = p + m_sb1.length();
	for ( ; p < pend ; p += 12 ) {
		// breathe
		QUICKPOLL ( m_niceness );
		// get graph hash of this point
		long  gh = *(long *)(p +8);

		// if we already did this graph, skip it
		if ( tmpht.isInTable ( &gh ) ) continue;

		// . graph this single graph of this color
		// . returns ptr to first point of different color!
		plotGraph ( p , pend , gh , m_gw , zoff );
		// prevent collisions
		zoff += 20;

		// get the label based on graphHash
		Label *bb = getLabel ( gh );

		// add to key
		if ( col == 0 )
			m_sb2->safePrintf("<tr>");

		m_sb2->safePrintf("<td bgcolor=#%06lx>&nbsp; &nbsp;</td>"
				 "<td>%s</td>\n",
				 bb->m_color ,
				 bb->m_keyDesc );

		if ( col == 1 )
			m_sb2->safePrintf("</tr>\n");

		// inc column and wrap
		if ( ++col >= 2 ) col = 0;

		// . do not re-display 
		// . TODO: deal with error
		tmpht.addKey ( &gh );
		
	}



	// clear that up
	m_sb1.reset();

	// now plot the events, horizontal line segments like the performance
	// graph uses
	for ( long i = 0 ; i < m_ht3.m_numSlots ; i++ ) {
		// breathe
		QUICKPOLL ( m_niceness );
		// skip if slot empty
		if ( ! m_ht3.m_flags[i] ) continue;
		// get the offset into m_sb3
		long offset = *(long *)m_ht3.getValueFromSlot(i);
		// get buf start
		char *bufStart = m_sb3.getBufStart();
		// get the ptr
		EventPoint *pp = (EventPoint *)(bufStart + offset);

		// get name of parm
		Parm *m = g_parms.getParmFromParmHash ( pp->m_parmHash );
		// make sure we got it
		if ( ! m ) { 
			log("statsdb: unrecognized parm hash = %li",
			    pp->m_parmHash);
			continue;
			//char *xx=NULL;*xx=0; }
		}

		// set the line width
		//plotter.linewidth ( pp->m_thickness );

		// get parm hash
		long colorHash = pp->m_parmHash;
		// add in old/new values to make it different
		colorHash = hash32h ( (long)pp->m_oldVal , colorHash );
		colorHash = hash32h ( (long)pp->m_newVal , colorHash );
		// . get color
		// . is really the parm hash in disguise
		long c1 = colorHash & 0x00ffffff;
		// use the color specified from addStat_r() for this line/pt
		//plotter.pencolor ( ((c1 >> 16) & 0xff) << 8 ,
		//		   ((c1 >>  8) & 0xff) << 8 ,
		//		   ((c1 >>  0) & 0xff) << 8 );

		long x1 = pp->m_a;
		long x2 = pp->m_b;
		long y1 = *(long *)m_ht3.getKey(i); // i value
		// ensure at least 3 units wide for visibility
		if ( x2 < x1 + 10 ) x2 = x1 + 10;
		// . flip the y so we don't have to scroll the browser down
		// . DY does not include the axis and tick marks
		//long fy1 = DY - y1 + m_by ;
		// plot it
		//plotter.line ( x1 , fy1 , x2 , fy1 );
		drawLine3 ( m_gw , x1 , x2 , y1 , c1 , pp->m_thickness );

		// add to map key? only if we haven't already
		if ( tmpht.isInTable ( &colorHash ) ) continue;

		// add it
		if ( col == 0 )
			m_sb2->safePrintf("<tr>");

		char *title = "unknown parm";
		if ( m ) title = m->m_title;

		m_sb2->safePrintf("<td bgcolor=#%06lx>&nbsp; &nbsp;</td>",c1);

		// print the parm name and old/new values
		m_sb2->safePrintf("<td><b>%s</b>",title);

		if ( pp->m_oldVal != pp->m_newVal )
			m_sb2->safePrintf(" (%.02f -> %.02f)",
					 pp->m_oldVal,pp->m_newVal);

		m_sb2->safePrintf("</td>");

		if ( col == 1 )
			m_sb2->safePrintf("</tr>\n");

		// inc column and wrap
		if ( ++col >= 2 ) col = 0;

		// . do not re-display 
		// . TODO: deal with error
		tmpht.addKey ( &colorHash ) ;
	}
	m_sb2->safePrintf("</table>\n");

	// clear that up
	m_ht3.reset();
	m_sb3.reset();

	// and stat states
	m_ht0.reset();
	m_sb0.reset();

	// all done free some mem
	m_sb1.reset();
	//m_sb2.reset();

	//
	// but not m_sb2 cuz that has the html in it!!
	//

	// all done
	//if ( plotter.closepl () < 0 ) 
	//	log("admin: Could not close performance graph object.");
	// close the file
	//fclose ( m_fd );

	//#endif

	// close main graphing window
	m_gw.safePrintf("</div>\n");

	return true;
}
Пример #22
0
bool CmdMachine::onClient(DebuggerClient *client) {
  if (DebuggerCommand::onClient(client)) return true;
  if (client->argCount() == 0) return help(client);

  bool rpc = client->arg(1, "rpc");
  if (rpc || client->arg(1, "connect")) {
    if (client->argCount() != 2) {
      return help(client);
    }
    string host = client->argValue(2);
    int port = 0;
    size_t pos = host.find(":");
    if (pos != string::npos) {
      if (!DebuggerClient::IsValidNumber(host.substr(pos + 1))) {
        client->error("Port needs to be a number");
        return help(client);
      }
      port = atoi(host.substr(pos + 1).c_str());
      host = host.substr(0, pos);
    }

    if (rpc) {
      if (client->connectRPC(host, port)) {
        throw DebuggerConsoleExitException();
      }
    } else {
      if (client->connect(host, port)) {
        throw DebuggerConsoleExitException();
      }
    }
    client->initializeMachine();
    return true;
  }

  if (client->arg(1, "disconnect")) {
    if (client->disconnect()) {
      throw DebuggerConsoleExitException();
    }
    client->initializeMachine();
    return true;
  }

  if (client->arg(1, "list")) {
    processList(client);
    return true;
  }

  if (client->arg(1, "attach")) {
    DSandboxInfoPtr sandbox;

    string snum = client->argValue(2);
    if (DebuggerClient::IsValidNumber(snum)) {
      int num = atoi(snum.c_str());
      sandbox = client->getSandbox(num);
      if (!sandbox) {
        processList(client, false);
        sandbox = client->getSandbox(num);
        if (!sandbox) {
          client->error("\"%s\" is not a valid sandbox index. Choose one from "
                        "this list:", snum.c_str());
          processList(client);
          return true;
        }
      }
    } else if (client->argCount() == 2) {
      sandbox = DSandboxInfoPtr(new DSandboxInfo());
      sandbox->m_user = Process::GetCurrentUser();
      sandbox->m_name = snum;
    } else if (client->argCount() == 3) {
      sandbox = DSandboxInfoPtr(new DSandboxInfo());
      sandbox->m_user = snum;
      sandbox->m_name = client->argValue(3);
    } else {
      return help(client);
    }

    return AttachSandbox(client, sandbox);
  }

  return help(client);
}
Пример #23
0
/*static*/ int RetroShareLink::process(const QList<RetroShareLink> &linksIn, uint flag /* = RSLINK_PROCESS_NOTIFY_ALL*/)
{
    QList<RetroShareLink>::const_iterator linkIt;

    /* filter dublicate links */
    QList<RetroShareLink> links;
    for (linkIt = linksIn.begin(); linkIt != linksIn.end(); linkIt++) {
        if (links.contains(*linkIt)) {
            continue;
        }

        links.append(*linkIt);
    }

    if (flag & RSLINK_PROCESS_NOTIFY_ASK) {
        /* ask for some types of link */
        QStringList fileAdd;
        QStringList personAdd;

        for (linkIt = links.begin(); linkIt != links.end(); linkIt++) {
            const RetroShareLink &link = *linkIt;

            if (link.valid() == false) {
                continue;
            }

            switch (link.type()) {
            case TYPE_UNKNOWN:
            case TYPE_FORUM:
            case TYPE_CHANNEL:
            case TYPE_SEARCH:
            case TYPE_MESSAGE:
            case TYPE_CERTIFICATE:
                // no need to ask
                break;

            case TYPE_FILE:
                fileAdd.append(link.name());
                break;

            case TYPE_PERSON:
                personAdd.append(PeerDefs::rsid(link.name().toUtf8().constData(), link.hash().toStdString()));
                break;
            }
        }

        QString content;
        if (fileAdd.size()) {
            processList(fileAdd, QObject::tr("Add file"), QObject::tr("Add files"), content);
        }

        if (personAdd.size()) {
            processList(personAdd, QObject::tr("Add friend"), QObject::tr("Add friends"), content);
        }

        if (content.isEmpty() == false) {
            QString question = "<html><body>";
            if (links.size() == 1) {
                question += QObject::tr("Do you want to process the link ?");
            } else {
                question += QObject::tr("Do you want to process %1 links ?").arg(links.size());
            }
            question += "<br><br>" + content + "</body></html>";

            QMessageBox mb(QObject::tr("Confirmation"), question, QMessageBox::Question, QMessageBox::Yes,QMessageBox::No, 0);
            mb.setWindowIcon(QIcon(QString::fromUtf8(":/images/rstray3.png")));
            if (mb.exec() == QMessageBox::No) {
                return 0;
            }
        }
    }

    int countInvalid = 0;
    int countUnknown = 0;
    bool needNotifySuccess = false;

    // file
    QStringList fileAdded;
    QStringList fileExist;

    // person
    QStringList personAdded;
    QStringList personExist;
    QStringList personFailed;
    QStringList personNotFound;

    // forum
    QStringList forumFound;
    QStringList forumMsgFound;
    QStringList forumUnknown;
    QStringList forumMsgUnknown;

    // forum
    QStringList channelFound;
    QStringList channelMsgFound;
    QStringList channelUnknown;
    QStringList channelMsgUnknown;

    // search
    QStringList searchStarted;

    // message
    QStringList messageStarted;
    QStringList messageReceipientNotAccepted;
    QStringList messageReceipientUnknown;

    // Certificate
    QStringList GPGBase64Strings ;
    QStringList SSLIds ;

    // summary
    QList<QStringList*> processedList;
    QList<QStringList*> errorList;

    processedList << &fileAdded << &personAdded << &forumFound << &channelFound << &searchStarted << &messageStarted;
    errorList << &fileExist << &personExist << &personFailed << &personNotFound << &forumUnknown << &forumMsgUnknown << &channelUnknown << &channelMsgUnknown << &messageReceipientNotAccepted << &messageReceipientUnknown;
    // not needed: forumFound, channelFound, messageStarted

    for (linkIt = links.begin(); linkIt != links.end(); linkIt++) {
        const RetroShareLink &link = *linkIt;

        if (link.valid() == false) {
            std::cerr << " RetroShareLink::process invalid request" << std::endl;
            countInvalid++;
            continue;
        }

        switch (link.type())
        {
        case TYPE_UNKNOWN:
            countUnknown++;
            break;

        case TYPE_CERTIFICATE:
        {
#ifdef DEBUG_RSLINK
            std::cerr << " RetroShareLink::process certificate." << std::endl;
#endif
            needNotifySuccess = true;

            QString RS_Certificate ;
            RS_Certificate += "-----BEGIN PGP PUBLIC KEY BLOCK-----\n" ;
            RS_Certificate += "Version: Retroshare Generated cert.\n" ;
            RS_Certificate += "\n" ;

            QString radix = link.GPGRadix64Key() ;

            while(radix.size() > 64)
            {
                RS_Certificate += radix.left(64) + "\n" ;
                radix = radix.right(radix.size() - 64) ;
            }
            RS_Certificate += radix.left(64) + "\n" ;
            RS_Certificate += "=" + link.GPGBase64CheckSum() + "\n" ;
            RS_Certificate += "-----END PGP PUBLIC KEY BLOCK-----\n" ;
            RS_Certificate += "--SSLID--" + link.SSLId() + ";--LOCATION--" + link.location() + ";\n" ;

            if(!link.externalIPAndPort().isNull())
                RS_Certificate += "--EXT--" + link.externalIPAndPort() + ";" ;
            if(!link.localIPAndPort().isNull())
                RS_Certificate += "--LOCAL--" + link.localIPAndPort() + ";" ;
            RS_Certificate += "\n" ;

            std::cerr << "Usign this certificate:" << std::endl;
            std::cerr << RS_Certificate.toStdString() << std::endl;

            ConnectFriendWizard connectFriendWizard;
            connectFriendWizard.setCertificate(RS_Certificate, (link.subType() == RSLINK_SUBTYPE_CERTIFICATE_USER_REQUEST) ? true : false);
            connectFriendWizard.exec();
            needNotifySuccess = false;
        }
        break ;

        case TYPE_FILE:
        {
#ifdef DEBUG_RSLINK
            std::cerr << " RetroShareLink::process FileRequest : fileName : " << link.name().toUtf8().constData() << ". fileHash : " << link.hash().toStdString() << ". fileSize : " << link.size() << std::endl;
#endif

            needNotifySuccess = true;

            // Get a list of available direct sources, in case the file is browsable only.
            std::list<std::string> srcIds;
            FileInfo finfo ;
            rsFiles->FileDetails(link.hash().toStdString(), RS_FILE_HINTS_REMOTE, finfo) ;

            for(std::list<TransferInfo>::const_iterator it(finfo.peers.begin()); it!=finfo.peers.end(); ++it)
            {
#ifdef DEBUG_RSLINK
                std::cerr << "  adding peerid " << (*it).peerId << std::endl ;
#endif
                srcIds.push_back((*it).peerId) ;
            }

            if (rsFiles->FileRequest(link.name().toUtf8().constData(), link.hash().toStdString(), link.size(), "", RS_FILE_HINTS_NETWORK_WIDE, srcIds)) {
                fileAdded.append(link.name());
            } else {
                fileExist.append(link.name());
            }
            break;
        }

        case TYPE_PERSON:
        {
#ifdef DEBUG_RSLINK
            std::cerr << " RetroShareLink::process FriendRequest : name : " << link.name().toStdString() << ". id : " << link.hash().toStdString() << std::endl;
#endif

            needNotifySuccess = true;

            RsPeerDetails detail;
            if (rsPeers->getPeerDetails(link.hash().toStdString(), detail)) {
                if (detail.gpg_id == rsPeers->getGPGOwnId()) {
                    // it's me, do nothing
                    break;
                }

                if (detail.accept_connection) {
                    // peer connection is already accepted
                    personExist.append(PeerDefs::rsid(detail));
                    break;
                }

                if (rsPeers->addFriend("", link.hash().toStdString())) {
                    ConfCertDialog::loadAll();
                    personAdded.append(PeerDefs::rsid(detail));
                    break;
                }

                personFailed.append(PeerDefs::rsid(link.name().toUtf8().constData(), link.hash().toStdString()));
                break;
            }

            personNotFound.append(PeerDefs::rsid(link.name().toUtf8().constData(), link.hash().toStdString()));
            break;
        }

        case TYPE_FORUM:
        {
#ifdef DEBUG_RSLINK
            std::cerr << " RetroShareLink::process ForumRequest : name : " << link.name().toStdString() << ". id : " << link.hash().toStdString() << ". msgId : " << link.msgId().toStdString() << std::endl;
#endif

            ForumInfo fi;
            if (!rsForums->getForumInfo(link.id().toStdString(), fi)) {
                if (link.msgId().isEmpty()) {
                    forumUnknown.append(link.name());
                } else {
                    forumMsgUnknown.append(link.name());
                }
                break;
            }

            ForumMsgInfo msg;
            if (!link.msgId().isEmpty()) {
                if (!rsForums->getForumMessage(fi.forumId, link.msgId().toStdString(), msg)) {
                    forumMsgUnknown.append(link.name());
                    break;
                }
            }

            MainWindow::showWindow(MainWindow::Forums);
            ForumsDialog *forumsDialog = dynamic_cast<ForumsDialog*>(MainWindow::getPage(MainWindow::Forums));
            if (!forumsDialog) {
                return false;
            }

            if (forumsDialog->navigate(fi.forumId, msg.msgId)) {
                if (link.msgId().isEmpty()) {
                    forumFound.append(link.name());
                } else {
                    forumMsgFound.append(link.name());
                }
            } else {
                if (link.msgId().isEmpty()) {
                    forumUnknown.append(link.name());
                } else {
                    forumMsgUnknown.append(link.name());
                }
            }
            break;
        }

        case TYPE_CHANNEL:
        {
#ifdef DEBUG_RSLINK
            std::cerr << " RetroShareLink::process ChannelRequest : name : " << link.name().toStdString() << ". id : " << link.hash().toStdString() << ". msgId : " << link.msgId().toStdString() << std::endl;
#endif

            ChannelInfo ci;
            if (!rsChannels->getChannelInfo(link.id().toStdString(), ci)) {
                if (link.msgId().isEmpty()) {
                    channelUnknown.append(link.name());
                } else {
                    channelMsgUnknown.append(link.name());
                }
                break;
            }

            ChannelMsgInfo msg;
            if (!link.msgId().isEmpty()) {
                if (!rsChannels->getChannelMessage(ci.channelId, link.msgId().toStdString(), msg)) {
                    channelMsgUnknown.append(link.name());
                    break;
                }
            }

            MainWindow::showWindow(MainWindow::Channels);
            ChannelFeed *channelFeed = dynamic_cast<ChannelFeed*>(MainWindow::getPage(MainWindow::Channels));
            if (!channelFeed) {
                return false;
            }

            if (channelFeed->navigate(ci.channelId, msg.msgId)) {
                if (link.msgId().isEmpty()) {
                    channelFound.append(link.name());
                } else {
                    channelMsgFound.append(link.name());
                }
            } else {
                if (link.msgId().isEmpty()) {
                    channelUnknown.append(link.name());
                } else {
                    channelMsgUnknown.append(link.name());
                }
            }
            break;
        }

        case TYPE_SEARCH:
        {
#ifdef DEBUG_RSLINK
            std::cerr << " RetroShareLink::process SearchRequest : string : " << link.name().toStdString() << std::endl;
#endif

            MainWindow::showWindow(MainWindow::Search);
            SearchDialog *searchDialog = dynamic_cast<SearchDialog*>(MainWindow::getPage(MainWindow::Search));
            if (!searchDialog) {
                break;
            }

            searchDialog->searchKeywords(link.name());
            searchStarted.append(link.name());
            break;
        }

        case TYPE_MESSAGE:
        {
#ifdef DEBUG_RSLINK
            std::cerr << " RetroShareLink::process MessageRequest : id : " << link.hash().toStdString() << ", subject : " << link.name().toStdString() << std::endl;
#endif
            RsPeerDetails detail;
            if (rsPeers->getPeerDetails(link.hash().toStdString(), detail)) {
                if (detail.accept_connection || detail.id == rsPeers->getOwnId() || detail.id == rsPeers->getGPGOwnId()) {
                    MessageComposer *msg = MessageComposer::newMsg();
                    msg->addRecipient(MessageComposer::TO, detail.id, false);
                    if (link.subject().isEmpty() == false) {
                        msg->setTitleText(link.subject());
                    }
                    msg->show();
                    messageStarted.append(PeerDefs::nameWithLocation(detail));
                } else {
                    messageReceipientNotAccepted.append(PeerDefs::nameWithLocation(detail));
                }
            } else {
                messageReceipientUnknown.append(PeerDefs::rsidFromId(link.hash().toStdString()));
            }

            break;
        }

        default:
            std::cerr << " RetroShareLink::process unknown type: " << link.type() << std::endl;
            countUnknown++;
        }
    }

    int countProcessed = 0;
    int countError = 0;

    QList<QStringList*>::iterator listIt;
    for (listIt = processedList.begin(); listIt != processedList.end(); ++listIt) {
        countProcessed += (*listIt)->size();
    }
    for (listIt = errorList.begin(); listIt != errorList.end(); ++listIt) {
        countError += (*listIt)->size();
    }

    // success notify needed ?
    if (needNotifySuccess == false) {
        flag &= ~RSLINK_PROCESS_NOTIFY_SUCCESS;
    }
    // error notify needed ?
    if (countError == 0) {
        flag &= ~RSLINK_PROCESS_NOTIFY_ERROR;
    }

    QString result;

    if (flag & (RSLINK_PROCESS_NOTIFY_SUCCESS | RSLINK_PROCESS_NOTIFY_ERROR)) {
        result += (links.count() == 1 ? QObject::tr("%1 of %2 RetroShare link processed.") : QObject::tr("%1 of %2 RetroShare links processed.")).arg(countProcessed).arg(links.count()) + "<br><br>";
    }

    // file
    if (flag & RSLINK_PROCESS_NOTIFY_SUCCESS) {
        if (fileAdded.size()) {
            processList(fileAdded, QObject::tr("File added"), QObject::tr("Files added"), result);
        }
    }
    if (flag & RSLINK_PROCESS_NOTIFY_ERROR) {
        if (fileExist.size()) {
            processList(fileExist, QObject::tr("File exist"), QObject::tr("Files exist"), result);
        }
    }

    // person
    if (flag & RSLINK_PROCESS_NOTIFY_SUCCESS) {
        if (personAdded.size()) {
            processList(personAdded, QObject::tr("Friend added"), QObject::tr("Friends added"), result);
        }
    }
    if (flag & RSLINK_PROCESS_NOTIFY_ERROR) {
        if (personExist.size()) {
            processList(personExist, QObject::tr("Friend exist"), QObject::tr("Friends exist"), result);
        }
        if (personFailed.size()) {
            processList(personFailed, QObject::tr("Friend not added"), QObject::tr("Friends not added"), result);
        }
        if (personNotFound.size()) {
            processList(personNotFound, QObject::tr("Friend not found"), QObject::tr("Friends not found"), result);
        }
    }

    // forum
    if (flag & RSLINK_PROCESS_NOTIFY_ERROR) {
        if (forumUnknown.size()) {
            processList(forumUnknown, QObject::tr("Forum not found"), QObject::tr("Forums not found"), result);
        }
        if (forumMsgUnknown.size()) {
            processList(forumMsgUnknown, QObject::tr("Forum message not found"), QObject::tr("Forum messages not found"), result);
        }
    }

    // channel
    if (flag & RSLINK_PROCESS_NOTIFY_ERROR) {
        if (channelUnknown.size()) {
            processList(channelUnknown, QObject::tr("Channel not found"), QObject::tr("Channels not found"), result);
        }
        if (channelMsgUnknown.size()) {
            processList(channelMsgUnknown, QObject::tr("Channel message not found"), QObject::tr("Channel messages not found"), result);
        }
    }

    // message
    if (flag & RSLINK_PROCESS_NOTIFY_ERROR) {
        if (messageReceipientNotAccepted.size()) {
            processList(messageReceipientNotAccepted, QObject::tr("Recipient not accepted"), QObject::tr("Recipients not accepted"), result);
        }
        if (messageReceipientUnknown.size()) {
            processList(messageReceipientUnknown, QObject::tr("Unkown recipient"), QObject::tr("Unkown recipients"), result);
        }
    }

    if (flag & RSLINK_PROCESS_NOTIFY_ERROR) {
        if (countUnknown) {
            result += QString("<br>%1: %2").arg(QObject::tr("Malformed links")).arg(countUnknown);
        }
        if (countInvalid) {
            result += QString("<br>%1: %2").arg(QObject::tr("Invalid links")).arg(countInvalid);
        }
    }

    if (result.isEmpty() == false) {
        QMessageBox mb(QObject::tr("Result"), "<html><body>" + result + "</body></html>", QMessageBox::Information, QMessageBox::Ok, 0, 0);
        mb.setWindowIcon(QIcon(QString::fromUtf8(":/images/rstray3.png")));
        mb.exec();
    }

    return 0;
}
Пример #24
0
int GetRAbundCommand::execute(){
	try {
	
		if (abort == true) { if (calledHelp) { return 0; }  return 2;	}
		
        map<string, string> variables; 
        variables["[filename]"] = outputDir + m->getRootName(m->getSimpleName(inputfile));
		filename = getOutputFileName("rabund", variables);
		m->openOutputFile(filename, out);
		
        if (countfile != "") {
            processList(out);
        }else {
            InputData input(inputfile, format);
            RAbundVector* rabund = input.getRAbundVector();
            string lastLabel = rabund->getLabel();
            
            //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
            set<string> processedLabels;
            set<string> userLabels = labels;
            
            if (m->control_pressed) {  outputTypes.clear();  out.close(); m->mothurRemove(filename); delete rabund;  return 0; }
            
            while((rabund != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
                
                if(allLines == 1 || labels.count(rabund->getLabel()) == 1){
					m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
					
					if (m->control_pressed) {   outputTypes.clear(); out.close(); m->mothurRemove(filename);   delete rabund;  return 0;  }
					
					if(sorted)	{   rabund->print(out);				}
					else		{	rabund->nonSortedPrint(out);	}
                    
					processedLabels.insert(rabund->getLabel());
					userLabels.erase(rabund->getLabel());
                }
                
                if ((m->anyLabelsToProcess(rabund->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
					string saveLabel = rabund->getLabel();
					
					delete rabund;
					rabund = input.getRAbundVector(lastLabel);
					
					m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
					
					if (m->control_pressed) {   outputTypes.clear(); out.close(); m->mothurRemove(filename);  delete rabund;  return 0;  }
					
					if(sorted)	{   rabund->print(out);				}
					else		{	rabund->nonSortedPrint(out);	}
                    
					processedLabels.insert(rabund->getLabel());
					userLabels.erase(rabund->getLabel());
					
					//restore real lastlabel to save below
					rabund->setLabel(saveLabel);
                }
                
                lastLabel = rabund->getLabel();
                
                delete rabund;
                rabund = input.getRAbundVector();
            }
            
            //output error messages about any remaining user labels
            set<string>::iterator it;
            bool needToRun = false;
            for (it = userLabels.begin(); it != userLabels.end(); it++) {
                m->mothurOut("Your file does not include the label " + *it);
                if (processedLabels.count(lastLabel) != 1) {
                    m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
                    needToRun = true;
                }else {
                    m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
                }
            }
            
            //run last label if you need to
            if (needToRun == true)  {
                if (rabund != NULL) {	delete rabund;	}
                rabund = input.getRAbundVector(lastLabel);
                
                m->mothurOut(rabund->getLabel()); m->mothurOutEndLine();
                
                if (m->control_pressed) {  outputTypes.clear(); out.close(); m->mothurRemove(filename);   delete rabund;  return 0; }
                
                if(sorted)	{   rabund->print(out);				}
                else		{	rabund->nonSortedPrint(out);	}
                
                delete rabund;
            }
		}
        
        if (m->control_pressed) {  outputTypes.clear();  out.close(); m->mothurRemove(filename);  return 0; }
        
		m->mothurOutEndLine();
		m->mothurOut("Output File Names: "); m->mothurOutEndLine();
		m->mothurOut(filename); m->mothurOutEndLine();	outputNames.push_back(filename); outputTypes["rabund"].push_back(filename);
		m->mothurOutEndLine();
		
		out.close(); 
				
		//set rabund file as new current rabundfile
		string current = "";
		itTypes = outputTypes.find("rabund");
		if (itTypes != outputTypes.end()) {
			if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setRabundFile(current); }
		}
		
		return 0;		
	}

	catch(exception& e) {
		m->errorOut(e, "GetRAbundCommand", "execute");
		exit(1);
	}
}
Пример #25
0
bool CmdBreak::onClient(DebuggerClient *client) {
  if (DebuggerCommand::onClient(client)) return true;

  bool regex = false;
  BreakPointInfo::State state = BreakPointInfo::Always;

  int index = 1;
  if (client->arg(1, "regex")) {
    regex = true;
    index++;
  } else if (client->arg(1, "once")) {
    state = BreakPointInfo::Once;
    index++;
  } else if (client->arg(1, "list")) {
    return processList(client);
  } else if (hasUpdateArg(client)) {
    return processUpdate(client);
  }

  string currentFile;
  int currentLine = 0;
  BreakPointInfoPtr loc = client->getCurrentLocation();
  if (loc) {
    currentFile = loc->m_file;
    currentLine = loc->m_line1;
  }

  BreakPointInfoPtr bpi;
  InterruptType interrupt = (InterruptType)(-1);

  if (client->argCount() == 0) {
    if (currentFile.empty() || currentLine == 0) {
      client->error("There is no current file or line to set breakpoint. "
                    "You will have to specify source file location yourself.");
      return true;
    }

    bpi = BreakPointInfoPtr(new BreakPointInfo(regex, state,
                                               currentFile.c_str(),
                                               currentLine));
  } else if (client->arg(index, "start")) {
    interrupt = RequestStarted;
  } else if (client->arg(index, "end")) {
    interrupt = RequestEnded;
  } else if (client->arg(index, "psp")) {
    interrupt = PSPEnded;
  } else {
    bpi = BreakPointInfoPtr(new BreakPointInfo(regex, state, BreakPointReached,
                                               client->argValue(index),
                                               currentFile));
  }

  if (interrupt >= 0) {
    string url;
    if (!client->arg(index + 1, "if") && !client->arg(index + 1, "&&")) {
      url = client->argValue(++index);
    }
    bpi = BreakPointInfoPtr(new BreakPointInfo(regex, state, interrupt, url));
  }

  if (!validate(client, bpi, index)) {
    client->tutorial(
      "This is the order of different arguments:\n"
      "\n"
      "\t[b]reak [o]nce {exp} if|&& {php}\n"
      "\n"
      "These are the components in a breakpoint {exp}:\n"
      "\n"
      "\tfile location: {file}:{line}\n"
      "\tfunction call: {func}()\n"
      "\tmethod invoke: {cls}::{method}()\n"
    );
  }
  return true;
}
Пример #26
0
int main(int argc, char **argv, char **envp)
{
    pid_t pid = 0;
    bool launch_dbus = true;
    bool launch_klauncher = true;
    bool launch_kded = true;
    bool suicide = false;
    bool listProcesses = false;
    bool killProcesses = false;
    bool listAppsInDBus = false;
    bool quitAppsOverDBus = false;
    bool shutdown = false;

    /** Save arguments first... **/
    char **safe_argv = (char **) malloc(sizeof(char *) * argc);
    for (int i = 0; i < argc; i++) {
        safe_argv[i] = strcpy((char *)malloc(strlen(argv[i]) + 1), argv[i]);
        if (strcmp(safe_argv[i], "--no-dbus") == 0) {
            launch_dbus = false;
        }
        if (strcmp(safe_argv[i], "--no-klauncher") == 0) {
            launch_klauncher = false;
        }
        if (strcmp(safe_argv[i], "--no-kded") == 0) {
            launch_kded = false;
        }
        if (strcmp(safe_argv[i], "--suicide") == 0) {
            suicide = true;
        }
#ifdef ENABLE_EXIT
        if (strcmp(safe_argv[i], "--exit") == 0) {
            keep_running = 0;
        }
#endif
        if (strcmp(safe_argv[i], "--verbose") == 0) {
            verbose = 1;
        }
        if (strcmp(safe_argv[i], "--version") == 0) {
            printf("Qt: %s\n", qVersion());
            printf("KDE: %s\n", KINIT_VERSION_STRING);
            exit(0);
        }
        if (strcmp(safe_argv[i], "--help") == 0) {
            printf("Usage: kdeinit5 [options]\n");
#ifdef ENABLE_EXIT
            printf("   --exit                     Terminate when kded has run\n");
#endif
            printf("   --help                     this help page\n");
            printf("   --list                     list kde processes\n");
            printf("   --list-dbus-apps           list all applications registered in dbus\n");
            printf("   --quit-over-dbus           quit all application registered in dbus\n");
            printf("   --no-dbus                  do not start dbus-daemon\n");
            printf("   --no-klauncher             do not start klauncher\n");
            printf("   --no-kded                  do not start kded\n");
            printf("   --shutdown                 safe shutdown of all running kde processes\n");
            printf("                              first over dbus, then using hard kill\n");
#ifdef ENABLE_SUICIDE
            printf("    --suicide                 terminate when no KDE applications are left running\n");
#endif
            printf("   --terminate                hard kill of *all* running kde processes\n");
            printf("   --verbose                  print verbose messages\n");
            printf("   --version                  Show version information\n");
            exit(0);
        }
        if (strcmp(safe_argv[i], "--list") == 0) {
            listProcesses = true;
        }
        if (strcmp(safe_argv[i], "--shutdown") == 0) {
            shutdown = true;
        }
        if (strcmp(safe_argv[i], "--terminate") == 0 || strcmp(safe_argv[i], "--kill") == 0) {
            killProcesses = true;
        }
        if (strcmp(safe_argv[i], "--list-dbus-apps") == 0) {
            listAppsInDBus = true;
        }
        if (strcmp(safe_argv[i], "--quit-over-dbus") == 0) {
            quitAppsOverDBus = true;
        }
    }

    PSID currentSid = getCurrentProcessOwner();
    if (verbose) {
        fprintf(stderr, "current user sid: %s\n", qPrintable(toString(currentSid)));
    }
    ProcessList processList(currentSid);
    freeSid(currentSid);

    if (listProcesses) {
        listAllRunningKDEProcesses(processList);
        return 0;
    } else if (killProcesses) {
        terminateAllRunningKDEProcesses(processList);
        return 0;
    } else if (listAppsInDBus) {
        listAllNamedAppsInDBus();
        return 0;
    } else if (quitAppsOverDBus) {
        quitApplicationsOverDBus();
        return 0;
    } else if (shutdown) {
        quitApplicationsOverDBus();
        Sleep(2000);
        terminateAllRunningKDEProcesses(processList);
    }

#ifdef _DEBUG
    // first try to launch dbus-daemond in debug mode
    if (launch_dbus && processList.find("dbus-daemond")) {
        launch_dbus = false;
    }
    if (launch_dbus) {
        pid = launch("dbus-launchd.exe");
        if (!pid) {
            pid = launch("dbus-launchd.bat");
        }
        launch_dbus = (pid == 0);
    }
#endif
    if (launch_dbus && !processList.find("dbus-daemon")) {
        if (!pid) {
            pid = launch("dbus-launch.exe");
        }
        if (!pid) {
            pid = launch("dbus-launch.bat");
        }
        if (!pid) {
            exit(1);
        }
    }

    if (launch_klauncher && !processList.find("klauncher")) {
        pid = launch("klauncher");
        if (!pid || !checkIfRegisteredInDBus("org.kde.klauncher5", 10)) {
            exit(1);
        }
    }

    if (launch_kded && !processList.find(KDED_EXENAME)) {
        pid = launch(KDED_EXENAME);
        if (!pid || !checkIfRegisteredInDBus("org.kde.kded5", 10)) {
            exit(1);
        }
    }

    for (int i = 1; i < argc; i++) {
        if (safe_argv[i][0] == '+') {
            pid = launch(safe_argv[i] + 1);
        } else if (safe_argv[i][0] == '-') {
            // Ignore
        } else {
            pid = launch(safe_argv[i]);
        }
    }

    /** Free arguments **/
    for (int i = 0; i < argc; i++) {
        free(safe_argv[i]);
    }
    free(safe_argv);

    /** wait for termination of all (core) processes */
#ifdef ENABLE_SUICIDE
    if (suicide) {
        QProcess *proc;
        int can_exit = 1;
        do {
            foreach (proc, startedProcesses) {
                if (proc->state() != QProcess::NotRunning) {
                    can_exit = 0;
                }
            }
            if (!can_exit) {
                Sleep(2000);
            }
        } while (!can_exit);
        return 0;
    }
#endif
    return 0;
}
Пример #27
0
void CmdMachine::onClientImpl(DebuggerClient &client) {
  if (DebuggerCommand::displayedHelp(client)) return;
  if (client.argCount() == 0) {
    help(client);
    return;
  }

  bool rpc = client.arg(1, "rpc");
  if (rpc || client.arg(1, "connect")) {
    if (client.argCount() != 2) {
      help(client);
      return;
    }
    string host = client.argValue(2);
    int port = 0;
    size_t pos = host.find(":");
    if (pos != string::npos) {
      if (!DebuggerClient::IsValidNumber(host.substr(pos + 1))) {
        client.error("Port needs to be a number");
        help(client);
        return;
      }
      port = atoi(host.substr(pos + 1).c_str());
      host = host.substr(0, pos);
    }

    if (rpc) {
      if (client.connectRPC(host, port)) {
        throw DebuggerConsoleExitException();
      }
    } else {
      if (client.connect(host, port)) {
        throw DebuggerConsoleExitException();
      }
    }
    if (!client.initializeMachine()) {
      throw DebuggerConsoleExitException();
    }
    return;
  }

  if (client.arg(1, "disconnect")) {
    if (client.disconnect()) {
      throw DebuggerConsoleExitException();
    }
    if (!client.initializeMachine()) {
      throw DebuggerConsoleExitException();
    }
    return;
  }

  if (client.arg(1, "list")) {
    processList(client);
    return;
  }

  if (client.arg(1, "attach")) {
    DSandboxInfoPtr sandbox;

    string snum = client.argValue(2);
    if (DebuggerClient::IsValidNumber(snum)) {
      int num = atoi(snum.c_str());
      sandbox = client.getSandbox(num);
      if (!sandbox) {
        processList(client, false);
        sandbox = client.getSandbox(num);
        if (!sandbox) {
          client.error("\"%s\" is not a valid sandbox index. Choose one from "
                        "this list:", snum.c_str());
          processList(client);
          return;
        }
      }
    } else {
      int argBase = 2;
      if (client.argCount() >= 2 && client.arg(2, "force")) {
        m_force = true;
        argBase++;
      }
      sandbox = DSandboxInfoPtr(new DSandboxInfo());
      if (client.argCount() < argBase) {
        sandbox->m_user = client.getCurrentUser();
        sandbox->m_name = "default";
      } else if (client.argCount() == argBase) {
        sandbox->m_user = client.getCurrentUser();
        sandbox->m_name = client.argValue(argBase);
      } else if (client.argCount() == argBase + 1) {
        sandbox->m_user = client.argValue(argBase);
        sandbox->m_name = client.argValue(argBase + 1);
      } else {
        help(client);
        return;
      }
    }
    if (AttachSandbox(client, sandbox, m_force)) {
      // Attach succeed, wait for next interrupt
      throw DebuggerConsoleExitException();
    }
    return;
  }

  help(client);
}
static Point _sogouToGoogleMars(const double lo, const double la) {
    // clock_t start = clock();
#ifdef VERBOSE
    printf("Input: %d, %d\n", (int)lo, (int)la);
#endif
	// 初始化数据
    Node heap[NEIBOR_NUM];
    //double buff0[N], buff1[N];
	
	const int lo1e5 = (int)lo;
	const int la1e5 = (int)la;

    int loIndex = GET_LO_IDX(lo1e5);
    int laIndex = GET_LA_IDX(la1e5);
	loIndex = min(max(loIndex, 0), BUCKET_SIZE_LO - 1);
	laIndex = min(max(laIndex, 0), BUCKET_SIZE_LA - 1);
	
	// printf( "Lo Index: %d, La Index: %d\n", loIndex, laIndex); 
	int len = 0;
	int i, j;
	int64 step = 0;


	

	// step * scale (scale == 1)
	while (1) {
	    int step1 = step - 1;
	    int to_continue = (len < NEIBOR_NUM) || (heap[0].dist > (step1 * step1 * 10000000000ll));
#ifdef VERBOSE1
        int64 step2 = (step * step * 10000000000ll);
        printf("ToContinue: %d, %lld, %lld\n", to_continue, heap[0].dist, step2);
#endif
        if (!to_continue) {
            break;
        }
	    if (step == 0) {
			processList(buckets[loIndex][laIndex], lo1e5, la1e5, heap, &len);

	    } else {
			// including both ends
			j = laIndex - step;
			if (j >= 0) {
			    for (i = max(0, loIndex - step); i <= min(loIndex + step, BUCKET_SIZE_LO - 1); i++) {
				    processList(buckets[i][j], lo1e5, la1e5, heap, &len);
			    }	    
			}
			// not including end points
			i = loIndex + step;
			if (i < BUCKET_SIZE_LO) {
			    for (j = max(0, laIndex - step + 1); j <= min(laIndex + step - 1, BUCKET_SIZE_LA - 1); j++) {
				    processList(buckets[i][j], lo1e5, la1e5, heap, &len);
			    }
			}

			// 下面
			j = laIndex + step;
			if (j < BUCKET_SIZE_LA) {
			    for (i = min(BUCKET_SIZE_LO - 1, loIndex + step); i >= max(0, loIndex - step); --i) {
				    processList(buckets[i][j], lo1e5, la1e5, heap, &len);
			    }
			}
			
			// not including end points
			i = loIndex - step;
			if (i >= 0) {
			    for (j = min(BUCKET_SIZE_LA - 1, laIndex + step - 1); j >= min(0, laIndex - step + 1); --j) {
				    processList(buckets[i][j], lo1e5, la1e5, heap, &len);
			    }
			}
	    }

		step++;
	}

	return interpolation(lo, la, heap);
}
Пример #29
0
/**
 * Processes all the POP3 commands such as
 * USER, PASS, LIST, RETR, DELE, NOOP, RSET, STAT
 */
int processPOPCommands(int sockfd, char *msg) {
	char *clientMsg = NULL;
	clientMsg = (char *)malloc(sizeof(char *) * 1024);
	if (clientMsg == NULL) {
		perror("ERROR: Cannot allocate memory");
		return(-1);
	}
	if (strncasecmp(msg, POP_SSL_STARTTLS, strlen(POP_SSL_STARTTLS)) == 0) { //EHLO
		if (setupSSLCommunication(sockfd)) {
			writeClient(sockfd, "OK Begin TLS negotiation now", TRUE);
		}
	}
	else if (strncasecmp(msg, POP_USER, strlen(POP_USER)) == 0) { //USER
		if (checkPOPStates(iPOP_USER)) {
			if (processUser(msg)== -1) {
				strcpy(clientMsg,"User name required");
				writeClient(sockfd, getMessage(TRUE, &clientMsg), TRUE);
			}
			else
				writeClient(sockfd, POP_OK, TRUE);
		}
		else {
			strcpy(clientMsg,"Invalid State");
			writeClient(sockfd, getMessage(TRUE, &clientMsg), TRUE);
		}
	}
	else if (strncasecmp(msg, POP_PASS, strlen(POP_PASS)) == 0) { //PASS
		if (checkPOPStates(iPOP_PASS)) {
			if (processPassword(msg) == -1) {
				strcpy(clientMsg,"Password required");
				writeClient(sockfd, getMessage(TRUE, &clientMsg), TRUE);
			}
			else {
				struct userdata *user;
				if (fetch_user_data(username, password, &user)) { //VALID USER

					//GET MESSAGE LISTING FOR THE USER
					getListMessages(username);

					writeClient(sockfd, POP_OK, TRUE);
					free(user);
				}
				else {
					strcpy(clientMsg,"Invalid User");
					writeClient(sockfd, getMessage(TRUE, &clientMsg), TRUE);
				}
			}
		}
		else {
			strcpy(clientMsg,"Invalid State");
			writeClient(sockfd, getMessage(TRUE, &clientMsg), TRUE);
		}
	}
	else if (strncasecmp(msg, POP_LIST, strlen(POP_LIST)) == 0) { //LIST
		if (checkPOPStates(iPOP_LIST))
			processList(sockfd, msg);
		else {
			strcpy(clientMsg,"Invalid State");
			writeClient(sockfd, getMessage(TRUE, &clientMsg), TRUE);
		}
	}
	else if (strncasecmp(msg, POP_RETR, strlen(POP_RETR)) == 0) { //RETR
		if (checkPOPStates(iPOP_RETR)) {
			if (processRetr(sockfd, msg) == -1) {
				strcpy(clientMsg,"Invalid Syntax");
				writeClient(sockfd, getMessage(TRUE, &clientMsg), TRUE);
			}
		}
		else {
			strcpy(clientMsg,"Invalid State");
			writeClient(sockfd, getMessage(TRUE, &clientMsg), TRUE);
		}
	}
	else if (strncasecmp(msg, POP_DELE, strlen(POP_DELE)) == 0) { //DELE
		if (checkPOPStates(iPOP_DELE)) {
			if (processDelete(sockfd, msg)== -1) {
				strcpy(clientMsg,"Invalid Syntax");
				writeClient(sockfd, getMessage(TRUE, &clientMsg), TRUE);
			}
		}
		else {
			strcpy(clientMsg,"Invalid State");
			writeClient(sockfd, getMessage(TRUE, &clientMsg), TRUE);
		}
	}
	else if (strncasecmp(msg, POP_RSET, strlen(POP_RSET)) == 0) { //RSET
//		if (checkStates(iPOP_RSET))
//			processRset(sockfd, msg);
//		else
//			writeClient(sockfd, POP_RESP_503, TRUE);
	}
	else if (strncasecmp(msg, POP_NOOP, strlen(POP_NOOP)) == 0) { //NOOP
		if (checkPOPStates(iPOP_NOOP))
			writeClient(sockfd, POP_OK, TRUE);
		else
			writeClient(sockfd, POP_ERR, TRUE);
	}
	else if (strncasecmp(msg, POP_STAT, strlen(POP_STAT)) == 0) { //STAT
		if (checkPOPStates(iPOP_STAT)) {
			processStat(sockfd, msg);
		}
		else {
			strcpy(clientMsg,"Invalid State");
			writeClient(sockfd, getMessage(TRUE, &clientMsg), TRUE);
		}
	}
	else {
		strcpy(clientMsg,"Invalid State");
		writeClient(sockfd,getMessage(TRUE, &clientMsg), TRUE);
	}
	free(clientMsg);
	return(0);
}