Exemple #1
0
int main(int argc, char *argv[]) {
  CommandLine cl;
  MathRandom<MathMersenneTwister> rng;
  Error error;
  ya_check_debug();

  YA_MatD input_matrix;
  YA_MatD output_matrix;

  // Parse the command line
  HandleArgs(cl,argc,argv,&error);

  string outputfile="";
  if (cl.argsize(' ')>0) {
    load(cl.argstring(' ',0),input_matrix);
    if (cl.argsize(' ')>1)
      outputfile=cl.argstring(' ',1);
  } else
    read(cin,input_matrix);

  // Select rows
  if (cl['r']) {
    output_matrix=input_matrix(YA_RowI(cl.argstring('r',0)),":");
    input_matrix=output_matrix;
  }
  
  // Select cols
  if (cl['c']) {
    output_matrix=input_matrix(":",YA_RowI(cl.argstring('c',0)));
    input_matrix=output_matrix;
  }

  // Reorder rows using modulus
  else if (cl['z']) {
    ya_sizet mod=cl.argint('z',0);
    if (mod==0)
      error.generate_error(0,"vm_slice","Cannot specify a mod_num of 0.");
    if (input_matrix.rows()%mod!=0) {
      error.buffer() << "When using -z, the number of rows in the matrix "
                     << "must be evenly divisible by the mod_num.";
      error.addbuf(0,"vm_slice");
    }
    YA_VecI row_order(input_matrix.rows());
    ya_sizet offset=input_matrix.rows()/mod;
    for (ya_sizet i=0; i<input_matrix.rows(); i++) {
      div_t index=div(int(i),int(mod));
      row_order(i)=index.quot+index.rem*offset;
    }
    output_matrix=input_matrix(row_order,":");
  } else    
    output_matrix=input_matrix;

  ya_sizet file_format=YA_DEFAULT_IO;
  if (cl['t'])
    file_format=YA_PRETTY_IO;
  if (cl['b'])
    file_format=YA_BINARY_IO;

  // Random subset
  if (cl['s']) {
    double percent=cl.argdouble('s',0);
    if (percent>1)
      error.generate_error(0,"mat_convert",
        "Random percentage must be between 0 and 1");
    YA_RowI rand_perm(randperm(output_matrix.rows(),rng));
    output_matrix=copy(output_matrix(rand_perm,":"));
    ya_sizet cut_frac=ya_sizet(percent*output_matrix.rows());
    if (cl.argstring('s',1)!="NO_OUTPUT")
      save(cl.argstring('s',1),
           output_matrix(vmcount(cut_frac,":",output_matrix.rows()-1),":"),
           file_format);
    output_matrix=copy(output_matrix(vmcount(cut_frac),":"));
  }

  if (cl['q'])
    ip_transpose(output_matrix);

  if (outputfile=="")
    write(cout,output_matrix,file_format);
  else
    save(outputfile,output_matrix,file_format);
  return 0;
}
Result Par1Repairer::Process(const CommandLine &commandline, bool dorepair) {
	// How noisy should we be
	noiselevel = commandline.GetNoiseLevel();

	// Do we want to purge par files on success ?
	bool purgefiles = commandline.GetPurgeFiles();

	// Get filesnames from the command line
	string par1filename = commandline.GetParFilename();
	const list<CommandLine::ExtraFile> &extrafiles = commandline.GetExtraFiles();

	// Determine the searchpath from the location of the main PAR file
	string name;
	DiskFile::SplitFilename(par1filename, searchpath, name);

	// Load the main PAR file
	if (!LoadRecoveryFile(searchpath + name))
		return eLogicError;

	// Load other PAR files related to the main PAR file
	if (!LoadOtherRecoveryFiles(par1filename))
		return eLogicError;

	// Load any extra PAR files specified on the command line
	if (!LoadExtraRecoveryFiles(extrafiles))
		return eLogicError;

	if (noiselevel > CommandLine::nlQuiet)
		cout << endl << "Verifying source files:" << endl << endl;

	// Check for the existence of and verify each of the source files
	if (!VerifySourceFiles())
		return eFileIOError;

	if (completefilecount<sourcefiles.size()) {
		if (noiselevel > CommandLine::nlQuiet)
			cout << endl << "Scanning extra files:" << endl << endl;

		// Check any other files specified on the command line to see if they are
		// actually copies of the source files that have the wrong filename
		if (!VerifyExtraFiles(extrafiles))
			return eLogicError;
	}

	// Find out how much data we have found
	UpdateVerificationResults();

	if (noiselevel > CommandLine::nlSilent)
		cout << endl;

	// Check the verification results and report the details
	if (!CheckVerificationResults())
		return eRepairNotPossible;

	// Are any of the files incomplete
	if (completefilecount<sourcefiles.size()) {
		// Do we want to carry out a repair
		if (dorepair) {
			if (noiselevel > CommandLine::nlSilent)
				cout << endl;

			// Rename any damaged or missnamed target files.
			if (!RenameTargetFiles())
				return eFileIOError;

			// Are we still missing any files
			if (completefilecount<sourcefiles.size()) {
				// Work out which files are being repaired, create them, and allocate
				// target DataBlocks to them, and remember them for later verification.
				if (!CreateTargetFiles())
					return eFileIOError;

				// Work out which data blocks are available, which need to be recreated,
				// and compute the appropriate Reed Solomon matrix.
				if (!ComputeRSmatrix()) {
					// Delete all of the partly reconstructed files
					DeleteIncompleteTargetFiles();
					return eFileIOError;
				}

				// Allocate memory buffers for reading and writing data to disk.
				if (!AllocateBuffers(commandline.GetMemoryLimit())) {
					// Delete all of the partly reconstructed files
					DeleteIncompleteTargetFiles();
					return eMemoryError;
				}
				if (noiselevel > CommandLine::nlSilent)
					cout << endl;

				// Set the total amount of data to be processed.
				progress = 0;
				totaldata = blocksize * sourcefiles.size() * verifylist.size();

				// Start at an offset of 0 within a block.
				u64 blockoffset = 0;
				while (blockoffset < blocksize) { // Continue until the end of the block.
					// Work out how much data to process this time.
					size_t blocklength = (size_t)min((u64)chunksize, blocksize-blockoffset);

					// Read source data, process it through the RS matrix and write it to disk.
					if (!ProcessData(blockoffset, blocklength)) {
						// Delete all of the partly reconstructed files
						DeleteIncompleteTargetFiles();
						return eFileIOError;
					}

					// Advance to the need offset within each block
					blockoffset += blocklength;
				}

				if (noiselevel > CommandLine::nlSilent)
					cout << endl << "Verifying repaired files:" << endl << endl;

				// Verify that all of the reconstructed target files are now correct
				if (!VerifyTargetFiles()) {
					// Delete all of the partly reconstructed files
					DeleteIncompleteTargetFiles();
					return eFileIOError;
				}
			}

			// Are all of the target files now complete?
			if (completefilecount<sourcefiles.size()) {
				cerr << "Repair Failed." << endl;
				return eRepairFailed;
			} else {
				if (noiselevel > CommandLine::nlSilent)
					cout << endl << "Repair complete." << endl;
			}
		} else {
			return eRepairPossible;
		}
	}

	if (purgefiles == true) {
		RemoveBackupFiles();
		RemoveParFiles();
	}

	return eSuccess;
}
Exemple #3
0
int main(int argc,char **argv) {
 
  CommandLine *parms = CommandLine::Instance();

  parms->add_valid_parm("ref","Reference sequence for alignment");
  parms->add_valid_parm("seq","Sequences to align (fastq)");

  cout << "SmallAlign" << endl;
  cout << parms->usage() << endl; 

  parms->process_args (argc, argv);

  SmallAlign<> aligner(true);

  //Perform alignment, calculate error rate
  
  // Load reference sequence
  FastaReader<> reference_fastafile(parms->get_parm("ref"));
  bool openok = reference_fastafile.open();

  if(openok == false) cerr << "Could not open reference file: " << parms->get_parm("ref") << endl;
  else                cerr << "Opened reference file: " << parms->get_parm("ref") << endl;
  bool fasta_eof=false;

  if(openok) {
    for(;!fasta_eof;) {
      FastaSequence reference = reference_fastafile.next_sequence(fasta_eof);
      if(!fasta_eof) {
        // Forward and Reverse? (true/false)
        aligner.add_reference(reference.sequence,true);
      }
    }
  }
  
  FastPrbReader<BaseProbability<4> > sequences_fastq(parms->get_parm("seq"));

  openok=true;
  if(openok == false) cerr << "Could not open sequences file: " << parms->get_parm("seq") << endl;
  else                cerr << "Opened sequences file: " << parms->get_parm("seq") << endl;
  fasta_eof=false;
 

  int max_cycles=40;
  int max_quality=100;
  int printevery=1000;
  vector<int> errors_by_cycle(max_cycles,0);
  vector<int> errors_by_quality(max_quality,0);
  vector<int> quality_count(max_quality,0);
  vector<int> total_by_cycle (max_cycles,0);
  
  vector<int> errors_count(max_cycles,0);

  if(openok) {
    int n=0;
    for(;!sequences_fastq.eof();) {
      ProbabilitySequence<BaseProbability<4> > seq = sequences_fastq.get_sequence();
      
      SequenceAlignment<> alm;
      alm = aligner.align(seq.string_sequence());

      if(alm.score > 30)
      for(unsigned int m=0;m<alm.matchstring.size();m++) {
        if(alm.matchstring[m] == false) {
          errors_by_quality[seq.sequence()[m].max_probability()*max_quality]++;
          errors_by_cycle[m]++;
        }
        quality_count[seq.sequence()[m].max_probability()*max_quality]++;
        total_by_cycle[m]++;
      }
      errors_count[alm.score]++;

      if((n%printevery == 0) || sequences_fastq.eof()) {
        // Errors by cycle
        cout << "Error rates" << endl;
        for(int cycle=0;(cycle < max_cycles) && (total_by_cycle[cycle] > 0);cycle++) {
          cout << setw(5) << cycle << " ";
          cout << setw(10) << (static_cast<double>(errors_by_cycle[cycle])/static_cast<double>(total_by_cycle[cycle]))*100 << " ";
          cout << setw(10) << errors_by_cycle[cycle] << " ";
          cout << setw(10) << total_by_cycle[cycle] << endl;
        }
        cout << "Score count" << endl;
        for(int errs=0;(errs < max_cycles);errs++) {
          cout << setw(5) << errs << " ";
          cout << setw(10) << errors_count[errs] << endl;
        }
        
        // Errors by quality
        cout << "Error by quality" << endl;
        for(int quality=0;(quality < max_quality);quality++) {
          if(quality_count[quality] != 0) {
            cout << setw(5) << quality << " ";
            cout << setw(5) << errors_by_quality[quality] << " ";
            cout << setw(5) << quality_count[quality] << " ";
            cout << setw(10) << 1-(static_cast<double>(errors_by_quality[quality])/static_cast<double>(quality_count[quality])) << endl;
          }  
        }
      }
      n++;
    }
  } else {
    cerr << "Could not open sequences file" << endl;
  }

}
Exemple #4
0
int main(int argc, char** argv)
{
  std::vector<Pathname> files;
  enum { 
    kTitle       = (1<<0),
    kDescription = (1<<1),
    kLevels      = (1<<2),
    kFilename    = (1<<3)
  };

  unsigned int mode = 0;

  CommandLine argp;
  argp.add_usage("[OPTIONS]... [FILE]...");

  argp.add_option('h', "help",    "", "Displays this help");

  argp.add_option('t', "title", "", "Display title of the levelset");
  argp.add_option('d', "description", "", "Display description of the levelset");
  argp.add_option('l', "levels", "", "Display levels in this levelset");
  argp.add_option('f', "filename", "", "Display filename of the level");

  argp.parse_args(argc, argv);
  argp.set_help_indent(20);

  while (argp.next())
  {
    switch (argp.get_key()) 
    {          
      case 'h':
        argp.print_help();
        exit(EXIT_SUCCESS);
        break;

      case 't':
        mode |= kTitle;
        break;

      case 'd':
        mode |= kDescription;
        break;

      case 'l':
        mode |= kLevels;
        break;

      case 'f':
        mode |= kFilename;
        break;

      case CommandLine::REST_ARG:
        files.push_back(Pathname(argp.get_argument(), Pathname::SYSTEM_PATH));
        break;
    }
  }

  if (files.empty())
  {
    argp.print_help();
    exit(EXIT_SUCCESS);
  }
  else
  {
    // FIXME: a little ugly that levelset loads sprites and savegames
    g_path_manager.set_path("data/");
    SavegameManager savegame_manager("savegames/savegames.scm");
    StatManager stat_manager("savegames/variables.scm");
    Resource::init();
    globals::framebuffer_type  = NULL_FRAMEBUFFER;
    Display::set_video_mode(Size(), false);

    for(auto it = files.begin(); it != files.end(); ++it)
    {
      const Pathname& path = *it;
      Levelset levelset(path);

      if (mode == 0)
      {
        std::cout << "filename      : " << path << std::endl;
        std::cout << "title         : " << levelset.get_title() << std::endl;
        std::cout << "description   : " << levelset.get_description() << std::endl;
        std::cout << "levels        : " << std::endl;
        for(int i = 0; i < levelset.get_level_count(); ++i)
        {
          std::cout << "  " << levelset.get_level(i)->resname << std::endl;
        }
        std::cout << std::endl;
      }
      else
      {
        if (mode & kFilename)
        {
          std::cout << path << ": ";
        }

        if (mode & kTitle)
        {
          std::cout << levelset.get_title() << std::endl;
        }

        if (mode & kDescription)
        {
          std::cout << levelset.get_description() << std::endl;
        }

        if (mode & kLevels)
        {
          for(int i = 0; i < levelset.get_level_count(); ++i)
          {
            std::cout << "  " << levelset.get_level(i)->resname << std::endl;
          }
          std::cout << std::endl;
        }
      }
    }

    Resource::deinit();
  }

  return 0;
}
Result Par2Creator::Process(const CommandLine &commandline)
{
  // Get information from commandline
  noiselevel = commandline.GetNoiseLevel();
  blocksize = commandline.GetBlockSize();
  sourceblockcount = commandline.GetBlockCount();
  const list<CommandLine::ExtraFile> extrafiles = commandline.GetExtraFiles();
  sourcefilecount = (u32)extrafiles.size();
  u32 redundancy = commandline.GetRedundancy();
  u64 redundancysize = commandline.GetRedundancySize();
  recoveryblockcount = commandline.GetRecoveryBlockCount();
  recoveryfilecount = commandline.GetRecoveryFileCount();
  firstrecoveryblock = commandline.GetFirstRecoveryBlock();
  recoveryfilescheme = commandline.GetRecoveryFileScheme();
  string par2filename = commandline.GetParFilename();
  string basepath = commandline.GetBasePath();
  size_t memorylimit = commandline.GetMemoryLimit();
  largestfilesize = commandline.GetLargestSourceSize();

  // Compute block size from block count or vice versa depending on which was
  // specified on the command line
  if (!ComputeBlockSizeAndBlockCount(extrafiles))
    return eInvalidCommandLineArguments;

  // Determine how many recovery blocks to create based on the source block
  // count and the requested level of redundancy.
  if ((redundancy > 0 || redundancysize >0) && !ComputeRecoveryBlockCount(redundancy, redundancysize))
    return eInvalidCommandLineArguments;

  // Determine how much recovery data can be computed on one pass
  if (!CalculateProcessBlockSize(memorylimit))
    return eLogicError;

  // Determine how many recovery files to create.
  if (!ComputeRecoveryFileCount())
    return eInvalidCommandLineArguments;

  if (noiselevel > CommandLine::nlQuiet)
  {
    // Display information.
    cout << "Block size: " << blocksize << endl;
    cout << "Source file count: " << sourcefilecount << endl;
    cout << "Source block count: " << sourceblockcount << endl;
    if (redundancy>0 || recoveryblockcount==0)
      cout << "Redundancy: " << redundancy << '%' << endl;
    cout << "Recovery block count: " << recoveryblockcount << endl;
    cout << "Recovery file count: " << recoveryfilecount << endl;
    cout << endl;
  }

  // Open all of the source files, compute the Hashes and CRC values, and store
  // the results in the file verification and file description packets.
  if (!OpenSourceFiles(extrafiles, basepath))
    return eFileIOError;

  // Create the main packet and determine the setid to use with all packets
  if (!CreateMainPacket())
    return eLogicError;

  // Create the creator packet.
  if (!CreateCreatorPacket())
    return eLogicError;

  // Initialise all of the source blocks ready to start reading data from the source files.
  if (!CreateSourceBlocks())
    return eLogicError;

  // Create all of the output files and allocate all packets to appropriate file offets.
  if (!InitialiseOutputFiles(par2filename))
    return eFileIOError;

  if (recoveryblockcount > 0)
  {
    // Allocate memory buffers for reading and writing data to disk.
    if (!AllocateBuffers())
      return eMemoryError;

    // Compute the Reed Solomon matrix
    if (!ComputeRSMatrix())
      return eLogicError;

    // Set the total amount of data to be processed.
    progress = 0;
    totaldata = blocksize * sourceblockcount * recoveryblockcount;

    // Start at an offset of 0 within a block.
    u64 blockoffset = 0;
    while (blockoffset < blocksize) // Continue until the end of the block.
    {
      // Work out how much data to process this time.
      size_t blocklength = (size_t)min((u64)chunksize, blocksize-blockoffset);

      // Read source data, process it through the RS matrix and write it to disk.
      if (!ProcessData(blockoffset, blocklength))
        return eFileIOError;

      blockoffset += blocklength;
    }

    if (noiselevel > CommandLine::nlQuiet)
      cout << "Writing recovery packets" << endl;

    // Finish computation of the recovery packets and write the headers to disk.
    if (!WriteRecoveryPacketHeaders())
      return eFileIOError;

    // Finish computing the full file hash values of the source files
    if (!FinishFileHashComputation())
      return eLogicError;
  }

  // Fill in all remaining details in the critical packets.
  if (!FinishCriticalPackets())
    return eLogicError;

  if (noiselevel > CommandLine::nlQuiet)
    cout << "Writing verification packets" << endl;

  // Write all other critical packets to disk.
  if (!WriteCriticalPackets())
    return eFileIOError;

  // Close all files.
  if (!CloseFiles())
    return eFileIOError;

  if (noiselevel > CommandLine::nlSilent)
    cout << "Done" << endl;

  return eSuccess;
}
CommandLine::CommandLine(const CommandLine &other)
    : impl_(new Impl(other.argv(), other.argc()))
{
}
int main (int argc, char *argv[])
{
  uint32_t nWifis = 2;
  uint32_t nStas = 2;
  bool sendIp = true;
  bool writeMobility = false;

  CommandLine cmd;
  cmd.AddValue ("nWifis", "Number of wifi networks", nWifis);
  cmd.AddValue ("nStas", "Number of stations per wifi network", nStas);
  cmd.AddValue ("SendIp", "Send Ipv4 or raw packets", sendIp);
  cmd.AddValue ("writeMobility", "Write mobility trace", writeMobility);
  cmd.Parse (argc, argv);

  NodeContainer backboneNodes;
  NetDeviceContainer backboneDevices;
  Ipv4InterfaceContainer backboneInterfaces;
  std::vector<NodeContainer> staNodes;
  std::vector<NetDeviceContainer> staDevices;
  std::vector<NetDeviceContainer> apDevices;
  std::vector<Ipv4InterfaceContainer> staInterfaces;
  std::vector<Ipv4InterfaceContainer> apInterfaces;

  InternetStackHelper stack;
  CsmaHelper csma;
  Ipv4AddressHelper ip;
  ip.SetBase ("192.168.0.0", "255.255.255.0");

  backboneNodes.Create (nWifis);
  stack.Install (backboneNodes);

  backboneDevices = csma.Install (backboneNodes);

  double wifiX = 0.0;

  YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default ();
  wifiPhy.SetPcapDataLinkType (YansWifiPhyHelper::DLT_IEEE802_11_RADIO); 

  for (uint32_t i = 0; i < nWifis; ++i)
    {
      // calculate ssid for wifi subnetwork
      std::ostringstream oss;
      oss << "wifi-default-" << i;
      Ssid ssid = Ssid (oss.str ());

      NodeContainer sta;
      NetDeviceContainer staDev;
      NetDeviceContainer apDev;
      Ipv4InterfaceContainer staInterface;
      Ipv4InterfaceContainer apInterface;
      MobilityHelper mobility;
      BridgeHelper bridge;
      WifiHelper wifi = WifiHelper::Default ();
      NqosWifiMacHelper wifiMac = NqosWifiMacHelper::Default ();
      YansWifiChannelHelper wifiChannel = YansWifiChannelHelper::Default ();
      wifiPhy.SetChannel (wifiChannel.Create ());

      sta.Create (nStas);
      mobility.SetPositionAllocator ("ns3::GridPositionAllocator",
                                     "MinX", DoubleValue (wifiX),
                                     "MinY", DoubleValue (0.0),
                                     "DeltaX", DoubleValue (5.0),
                                     "DeltaY", DoubleValue (5.0),
                                     "GridWidth", UintegerValue (1),
                                     "LayoutType", StringValue ("RowFirst"));


      // setup the AP.
      mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
      mobility.Install (backboneNodes.Get (i));
      wifiMac.SetType ("ns3::ApWifiMac",
                       "Ssid", SsidValue (ssid));
      apDev = wifi.Install (wifiPhy, wifiMac, backboneNodes.Get (i));

      NetDeviceContainer bridgeDev;
      bridgeDev = bridge.Install (backboneNodes.Get (i), NetDeviceContainer (apDev, backboneDevices.Get (i)));

      // assign AP IP address to bridge, not wifi
      apInterface = ip.Assign (bridgeDev);

      // setup the STAs
      stack.Install (sta);
      mobility.SetMobilityModel ("ns3::RandomWalk2dMobilityModel",
                                 "Mode", StringValue ("Time"),
                                 "Time", StringValue ("2s"),
                                 "Speed", StringValue ("ns3::ConstantRandomVariable[Constant=1.0]"),
                                 "Bounds", RectangleValue (Rectangle (wifiX, wifiX+5.0,0.0, (nStas+1)*5.0)));
      mobility.Install (sta);
      wifiMac.SetType ("ns3::StaWifiMac",
                       "Ssid", SsidValue (ssid),
                       "ActiveProbing", BooleanValue (false));
      staDev = wifi.Install (wifiPhy, wifiMac, sta);
      staInterface = ip.Assign (staDev);

      // save everything in containers.
      staNodes.push_back (sta);
      apDevices.push_back (apDev);
      apInterfaces.push_back (apInterface);
      staDevices.push_back (staDev);
      staInterfaces.push_back (staInterface);

      wifiX += 20.0;
    }

  Address dest;
  std::string protocol;
  if (sendIp)
    {
      dest = InetSocketAddress (staInterfaces[1].GetAddress (1), 1025);
      protocol = "ns3::UdpSocketFactory";
    }
  else
    {
      PacketSocketAddress tmp;
      tmp.SetSingleDevice (staDevices[0].Get (0)->GetIfIndex ());
      tmp.SetPhysicalAddress (staDevices[1].Get (0)->GetAddress ());
      tmp.SetProtocol (0x807);
      dest = tmp;
      protocol = "ns3::PacketSocketFactory";
    }

  OnOffHelper onoff = OnOffHelper (protocol, dest);
  onoff.SetConstantRate (DataRate ("500kb/s"));
  ApplicationContainer apps = onoff.Install (staNodes[0].Get (0));
  apps.Start (Seconds (0.5));
  apps.Stop (Seconds (3.0));

  wifiPhy.EnablePcap ("wifi-wired-bridging", apDevices[0]);
  wifiPhy.EnablePcap ("wifi-wired-bridging", apDevices[1]);

  if (writeMobility)
    {
      AsciiTraceHelper ascii;
      MobilityHelper::EnableAsciiAll (ascii.CreateFileStream ("wifi-wired-bridging.mob"));
    }

  Simulator::Stop (Seconds (5.0));
  Simulator::Run ();
  Simulator::Destroy ();
}
int
main(int argc, char* argv[])
{
  // setting default parameters for Wifi
  // enable rts cts all the time.
  Config::SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold", StringValue ("0"));
  // disable fragmentation
  Config::SetDefault ("ns3::WifiRemoteStationManager::FragmentationThreshold", StringValue ("2200"));
  Config::SetDefault("ns3::WifiRemoteStationManager::NonUnicastMode",
                     StringValue("OfdmRate24Mbps"));

  // setting default parameters for PointToPoint links and channels
  Config::SetDefault("ns3::PointToPointNetDevice::DataRate", StringValue("1Mbps"));
  Config::SetDefault("ns3::PointToPointChannel::Delay", StringValue("10ms"));
  Config::SetDefault("ns3::DropTailQueue::MaxPackets", StringValue("20"));


  std::uint32_t max_routers = 1;
  std::string cSize = "100";
  std::string cSplit = "75";

  // Read optional command-line parameters (e.g., enable visualizer with ./waf --run=<> --visualize
  CommandLine cmd;
  cmd.AddValue("cSize", "Cache Size", cSize);
  cmd.AddValue("cSplit", "Cache Split", cSplit);
  cmd.AddValue("routers", "number of routers", max_routers);
  cmd.Parse(argc, argv);


  Packet::EnablePrinting ();

  // Wifi config

  WifiHelper wifi = WifiHelper::Default ();


  // Nodes
  NodeContainer sta_consumers;
  NodeContainer sta_mobile_consumers;
  NodeContainer ap;
  NodeContainer routers;
  NodeContainer producers;

  // ??
  NetDeviceContainer staDevs;
  PacketSocketHelper packetSocket;

  // 5 stationary consumers, 5 mobile, 4 APs and 1 router
  sta_consumers.Create(3*max_routers);
  sta_mobile_consumers.Create(7*max_routers);
  ap.Create (5*max_routers);
  routers.Create(max_routers);
  producers.Create(1);

  // give packet socket powers to nodes.
  packetSocket.Install(sta_mobile_consumers);
  packetSocket.Install(sta_consumers);
  packetSocket.Install (ap);

  // Wifi Config
  NqosWifiMacHelper wifiMac = NqosWifiMacHelper::Default ();
  YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default ();
  YansWifiChannelHelper wifiChannel = YansWifiChannelHelper::Default ();
  wifiPhy.SetChannel (wifiChannel.Create ());
  wifiPhy.Set("TxPowerStart", DoubleValue(5));
  wifiPhy.Set("TxPowerEnd", DoubleValue(5));
  Ssid ssid = Ssid ("wifi-default");
  wifi.SetRemoteStationManager ("ns3::ArfWifiManager");
  // setup stas.
  wifiMac.SetType ("ns3::StaWifiMac",
                   "Ssid", SsidValue (ssid),
                   "ActiveProbing", BooleanValue (false));
  // install wifi
  wifi.Install(wifiPhy, wifiMac, sta_mobile_consumers);
  wifi.Install(wifiPhy, wifiMac, sta_consumers);
  // setup ap.
  wifiMac.SetType ("ns3::ApWifiMac",
                   "Ssid", SsidValue (ssid));
  wifi.Install (wifiPhy, wifiMac, ap);


  // Mobility config -- Change max_routers value to change size of sim
  int number_rows = sqrt(max_routers);
  int x = 0;
  int y = 0;
  int pos_counter = 0;
  Ptr<UniformRandomVariable> randomizerX = CreateObject<UniformRandomVariable>();
  Ptr<UniformRandomVariable> randomizerY = CreateObject<UniformRandomVariable>();

  MobilityHelper stationary_mobility;
  stationary_mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");

  MobilityHelper mobility;
  mobility.SetMobilityModel("ns3::GaussMarkovMobilityModel", "Bounds", BoxValue(Box (0, number_rows*10, 0, number_rows*10, 0, 0)), 
	  "TimeStep", TimeValue(Seconds(1)));

  // Place router in center of box
  randomizerX->SetAttribute("Min", DoubleValue(5));
  randomizerX->SetAttribute("Max", DoubleValue(5));
  randomizerY->SetAttribute("Min", DoubleValue(5));
  randomizerY->SetAttribute("Max", DoubleValue(5));
  stationary_mobility.SetPositionAllocator("ns3::RandomBoxPositionAllocator", "X", PointerValue(randomizerX),
	  "Y", PointerValue(randomizerY));

  // Install on routers
  stationary_mobility.Install(producers.Get(0));

  // p2p helper
  PointToPointHelper p2p;
  // for each row
  for (int i=0; i < number_rows; i++)
  {
	  x = i * 10 + 5;
	  // for each column
	  for (int j=0; j < number_rows; j++)
	  {
		  y = j * 10 + 5;

		  // Place router in center of box
		  randomizerX->SetAttribute("Min", DoubleValue(x));
		  randomizerX->SetAttribute("Max", DoubleValue(x));
		  randomizerY->SetAttribute("Min", DoubleValue(y));
		  randomizerY->SetAttribute("Max", DoubleValue(y));
		  stationary_mobility.SetPositionAllocator("ns3::RandomBoxPositionAllocator", "X", PointerValue(randomizerX),
			  "Y", PointerValue(randomizerY));

		  // Install on routers
		  stationary_mobility.Install(routers.Get(pos_counter));

		  // Set box (center +/-5)
		  randomizerX->SetAttribute("Min", DoubleValue(x-5));
		  randomizerX->SetAttribute("Max", DoubleValue(x+5));
		  randomizerY->SetAttribute("Min", DoubleValue(y-5));
		  randomizerY->SetAttribute("Max", DoubleValue(y+5));
		  // Connect router to previous if not 1
		  if (pos_counter == 0)
		  {
			  p2p.Install(routers.Get(0), producers.Get(0));
		  }
		  else  // Otherwise connect to router behind you
		  {
			  p2p.Install(routers.Get(pos_counter), routers.Get(pos_counter-1));
		  }
		  // APs
		  for (int k=0; k < 5; k++)
		  {
			  stationary_mobility.SetPositionAllocator("ns3::RandomBoxPositionAllocator", "X", PointerValue(randomizerX),
				  "Y", PointerValue(randomizerY));
			  stationary_mobility.Install(ap.Get(pos_counter * 5 + k));
			  p2p.Install(routers.Get(pos_counter), ap.Get(pos_counter * 5 + k));

		  }

		  // Consumers (stationary)
		  for (int l=0; l < 3; l++)
		  {
			  stationary_mobility.SetPositionAllocator("ns3::RandomBoxPositionAllocator", "X", PointerValue(randomizerX),
				  "Y", PointerValue(randomizerY));
			  stationary_mobility.Install(sta_consumers.Get(pos_counter * 3 + l));
		  }

		  // Consumers (Mobile)
		  for (int m=0; m < 7; m++)
		  {
			  mobility.SetPositionAllocator("ns3::RandomBoxPositionAllocator", "X", PointerValue(randomizerX),
				  "Y", PointerValue(randomizerY));
			  mobility.Install(sta_mobile_consumers.Get(pos_counter * 7 + m));
		  }
	  // Keep track of overall position
	  pos_counter++;
	  }
  }
  // Install NDN stack on all nodes
  ndn::StackHelper ndnHelper;
  ndnHelper.SetDefaultRoutes(true);
  
  ndnHelper.SetOldContentStore("ns3::ndn::cs::Splitcache",
							   "NormalPolicy", "ns3::ndn::cs::Lru", 
							   "SpecialPolicy", "ns3::ndn::cs::Lfu", 
							   "TotalCacheSize", cSize, 
							   "Configure", cSplit); 
  //                       Percentage Special^
  
  //ndnHelper.SetOldContentStore("ns3::ndn::cs::Lru");

  ndnHelper.Install(ap);
  ndnHelper.Install(routers);
  ndnHelper.SetOldContentStore("ns3::ndn::cs::Nocache");
  ndnHelper.Install(sta_consumers);
  ndnHelper.Install(sta_mobile_consumers);
  ndnHelper.Install(producers);

  // Choosing forwarding strategy
  ndn::StrategyChoiceHelper::Install(sta_consumers, "/", "/localhost/nfd/strategy/best-route");
  ndn::StrategyChoiceHelper::Install(sta_mobile_consumers, "/", "/localhost/nfd/strategy/best-route");
  ndn::StrategyChoiceHelper::Install(ap, "/", "/localhost/nfd/strategy/best-route");
  ndn::StrategyChoiceHelper::Install(routers, "/", "/localhost/nfd/strategy/best-route");
  ndn::StrategyChoiceHelper::Install(producers, "/", "/localhost/nfd/strategy/best-route");

  // Installing applications

  // Consumer (basic and special data)
  ndn::AppHelper consumerHelper("ns3::ndn::ConsumerZipfMandelbrot");
  consumerHelper.SetAttribute("NumberOfContents", StringValue("100")); // 10 different contents
  // Consumer will request /prefix/0, /prefix/1, ...

  // Basic consumers request basic data (and pumpkin spice coffee)
  consumerHelper.SetPrefix("data/basic");
  consumerHelper.SetAttribute("Frequency", StringValue("10")); // 1 interests a second
  consumerHelper.Install(sta_consumers);   

  // Mobile consumers request special data only
  consumerHelper.SetPrefix("data/special");
  consumerHelper.SetAttribute("Frequency", StringValue("10")); //  2 interests a second
  consumerHelper.Install(sta_mobile_consumers);



  // Producer
  ndn::AppHelper producerHelper("ns3::ndn::Producer");
  // Producer will reply to all requests starting with /prefix
  producerHelper.SetPrefix("/data");
  producerHelper.SetAttribute("PayloadSize", StringValue("1024"));
  producerHelper.SetAttribute("Freshness", TimeValue(Seconds(-1.0))); // unlimited freshness
  producerHelper.Install(producers); 

  // Tracers 'n stuff
  //AthstatsHelper athstats;
  //athstats.EnableAthstats("athstats-sta", sta_mobile_consumers);
  //athstats.EnableAthstats("athstats-sta", sta_consumers);
  //athstats.EnableAthstats ("athstats-ap", ap);

  ndn::AppDelayTracer::Install(sta_consumers, "app-delays-trace-stationary-03.txt");
  ndn::AppDelayTracer::Install(sta_mobile_consumers, "app-delays-trace-mobile-03.txt");
  ndn::CsTracer::Install(ap, "cs-trace-ap-03.txt", Seconds(1));
  ndn::CsTracer::Install(routers, "cs-trace-routers-03.txt", Seconds(1));

  // 10 min
  Simulator::Stop(Seconds(600.0));

  Simulator::Run();
  Simulator::Destroy();

  return 0;
}
void
PingusMain::parse_args(int argc, char** argv)
{
  CommandLine argp;
  argp.add_usage(_("[OPTIONS]... [FILE]"));
  argp.add_doc(_("Pingus is a puzzle game where you need to guide a bunch of little penguins around the world."));

  argp.add_group(_("General Options:"));
  argp.add_option('h', "help", "", 
                  _("Displays this help"));
  argp.add_option('V', "version", "", 
                  _("Print version number and exit"));
  argp.add_option('v', "verbose", "",
                  _("Enable info level log output"));
  argp.add_option('D', "debug", "", 
                  _("Enable debug level log output"));
  argp.add_option('Q', "quiet", "", 
                  _("Disable all log output"));   

  argp.add_group(_("Display Options:"));
  argp.add_option('w', "window", "",
                  _("Start in Window Mode"));
  argp.add_option('f', "fullscreen", "",
                  _("Start in Fullscreen"));
  argp.add_option('r', "renderer", "RENDERER",
                  _("Use the given renderer (default: sdl)"));
  argp.add_option('g', "geometry", "{width}x{height}",  
                  _("Set the window resolution for pingus (default: 800x600)"));
  argp.add_option('R', "fullscreen-resolution", "{width}x{height}",  
                  _("Set the resolution used in fullscreen mode (default: 800x600)"));
  argp.add_option(346, "software-cursor", "",
                  _("Enable software cursor"));

  argp.add_group(_("Game Options:"));
  argp.add_option(337, "no-auto-scrolling", "",
                  _("Disable automatic scrolling"));
  argp.add_option(338, "drag-drop-scrolling", "",
                  _("Enable drag'n drop scrolling"));

  argp.add_group(_("Sound Options:"));
  argp.add_option('s', "disable-sound", "", 
                  _("Disable sound"));
  argp.add_option('m', "disable-music", "", 
                  _("Disable music"));

  argp.add_group("Language Options:");
  argp.add_option('l', "language", "LANG",
                  _("Select language to use with Pingus"));
  argp.add_option(365, "list-languages", "",
                  _("List all available languages"));

  argp.add_group("Editor Options:");
  argp.add_option('e', "editor", "",
                  _("Loads the level editor"));

  argp.add_group(_("Directory Options:"));
  argp.add_option('d', "datadir", _("DIR"),
                  _("Load game datafiles from DIR"));
  argp.add_option('u', "userdir", _("DIR"),
                  _("Load config files and store savegames in DIR"));
  argp.add_option('a', "addon", _("DIR"),
                  _("Load game modifications from DIR"));
  argp.add_option(342, "no-cfg-file", "",
                  _("Don't read ~/.pingus/config"));
  argp.add_option('c', "config", _("FILE"),
                  _("Read config options from FILE"));
  argp.add_option(360, "controller", "FILE",
                  _("Uses the controller given in FILE"));

  argp.add_group(_("Debug Options:"));
  argp.add_option(334, "developer-mode",  "",  
                  _("Enables some special features for developers"));
  argp.add_option('t', "speed", "SPEED",
                  _("Set the game speed (0=fastest, >0=slower)"));
  argp.add_option('k', "fps", "FPS",
                  _("Set the desired game framerate (frames per second)"));
  argp.add_option(344, "tile-size", "INT",
                  _("Set the size of the map tiles (default: 32)"));

  argp.parse_args(argc, argv);
  argp.set_help_indent(20);

  while (argp.next())
  {
    switch (argp.get_key()) 
    {          
      case 'r': // --renderer
        if (argp.get_argument() == "help")
        {
          std::cout << "Available renderers: " << std::endl;
          std::cout << "   delta: Software rendering with dirty-rectangles" << std::endl;
          std::cout << "     sdl: Software rendering" << std::endl;
          std::cout << "  opengl: Hardware accelerated graphics" << std::endl;
          std::cout << "    null: No rendering at all, for debugging" << std::endl;
          exit(EXIT_SUCCESS);
        }
        else
        {
          cmd_options.framebuffer_type.set(framebuffer_type_from_string(argp.get_argument()));

          //FIXME:
          //std::cout << "Unknown renderer: " << argp.get_argument()
          //<< " use '--renderer help' to get a list of available renderer" << std::endl;
          //exit(EXIT_FAILURE);
        }
        break;

      case 'e': // -e, --editor
        cmd_options.editor.set(true);
        break;

      case 't': // -t, --set-speed
        cmd_options.speed.set(StringUtil::to<int>(argp.get_argument()));  
        break;

      case 'k': // -k, --set-fps
        cmd_options.desiredfps.set(StringUtil::to<float>(argp.get_argument()));
        break;

      case 's': // -s, --disable-sound
        cmd_options.disable_sound.set(true);
        break;

      case 'm': // -m, --disable-music
        cmd_options.disable_music.set(true);
        break;
            
      case 'g':
      {
        Size size; 
        if (sscanf(argp.get_argument().c_str(), "%dx%d", &size.width, &size.height) != 2)
        {
          std::cout << "Resolution std::string is wrong, it should be like: \n"
                    << "\"640x480\" or \"800x600\"" << std::endl;
          exit(EXIT_FAILURE);
        }
        cmd_options.geometry.set(size);
      }
      break;

      case 'R':
      {
        Size size; 
        if (sscanf(argp.get_argument().c_str(), "%dx%d", &size.width, &size.height) != 2)
        {
          std::cout << "Resolution std::string is wrong, it should be like: \n"
                    << "\"640x480\" or \"800x600\"" << std::endl;
          exit(EXIT_FAILURE);
        }
        cmd_options.fullscreen_resolution.set(size);
      }
      break;

      case 'd': // -d, --datadir
        cmd_options.datadir.set(argp.get_argument());
        break;

      case 'a': // -a, --addon
        g_path_manager.add_overlay_path(argp.get_argument());
        break;

      case 'u': // -u, --userdir
        cmd_options.userdir.set(argp.get_argument());
        break;

      case 'V':
        std::cout <<
          "Pingus 0.7.6\n"
          "Copyright (C) 1998-2011 Ingo Ruhnke <*****@*****.**>\n"
          "See the file AUTHORS for a complete list of contributors.\n"
          "Pingus comes with ABSOLUTELY NO WARRANTY. This is free software, and you are\n"
          "welcome to redistribute it under certain conditions; see the file COPYING for details."
                  << std::endl;
        exit(EXIT_SUCCESS);
        break;
          
      case 'f': // --fullscreen
        cmd_options.fullscreen.set(true);
        break;
          
      case 'w': // --window
        cmd_options.fullscreen.set(false);
        break;

      case 334: // --developer-mode
        cmd_options.developer_mode.set(true);
        globals::developer_mode = true;
        break;

      case 337:
        cmd_options.auto_scrolling.set(false);
        break;

      case 338:
        cmd_options.drag_drop_scrolling.set(true);
        break;

      case 342: // --no-cfg-file
        cmd_options.no_config_file.set(true); 
        break;

      case 344:
        cmd_options.tile_size.set(StringUtil::to<int>(argp.get_argument()));
        break;

      case 346:
        cmd_options.software_cursor.set(true);
        break;

      case 'c':
        cmd_options.merge(Options::from_file(Pathname(argp.get_argument(), Pathname::SYSTEM_PATH)));
        break;

      case 'D':
        g_logger.set_log_level(Logger::kDebug);
        break;

      case 'v':
        g_logger.set_log_level(Logger::kInfo);
        break;

      case 'Q':
        g_logger.set_log_level(Logger::kNone);
        break;

      case 360:
        cmd_options.controller.set(argp.get_argument());
        break;

      case 'l': // language
        cmd_options.language.set(argp.get_argument());
        break;

      case 365: // list-languages
        cmd_options.list_languages.set(true);
        break;

      case 'h':
        argp.print_help();
        exit(EXIT_SUCCESS);
        break;

      case CommandLine::REST_ARG:
        if (!cmd_options.rest.is_set())
        {
          cmd_options.rest.set(argp.get_argument());
        }
        else
        {
          std::cout << "Wrong argument: '" << argp.get_argument() << "'" << std::endl;
          std::cout << "You can only give one file argument," << std::endl;
          exit(EXIT_FAILURE);
        }
        break;

      default:
        std::cout << "Error: Got " << argp.get_key() << " " << argp.get_argument() << std::endl;
        break;
    }
  }
}
/**
 * This scenario simulates a one-node two-custom-app scenario:
 *
 *   +------+ <-----> (CustomApp)
 *   | Node |
 *   +------+ <-----> (Hijacker)
 *
 *     NS_LOG=CustomApp ./waf --run=ndn-custom-apps
 */
int
main(int argc, char* argv[])
{
  // Read optional command-line parameters (e.g., enable visualizer with ./waf --run=<> --visualize
  CommandLine cmd;
  cmd.Parse(argc, argv);

  AnnotatedTopologyReader topologyReader("", 1);
//  topologyReader.SetFileName("src/ndnSIM/examples/topologies/topo-custom1.txt");
//  topologyReader.SetFileName("src/ndnSIM/examples/topologies/topo-custom2.txt");
  topologyReader.SetFileName("src/ndnSIM/examples/topologies/topo-custom3.txt");
  topologyReader.Read();

  // Creating nodes
//  Ptr<Node> node = CreateObject<Node>();
  // Install Content Store stack on cache node
  ndn::StackHelper ndnHelperCache;
  ndnHelperCache.SetOldContentStore("ns3::ndn::cs::Lru", "MaxSize", "10");
  ndnHelperCache.Install(Names::Find<Node>("cacheServer")); 

  // Install NDN stack on all nodes
/*  ndn::StackHelper ndnHelper;
  ndnHelper.SetDefaultRoutes(true);
  ndnHelper.InstallAll();*/

// Install NDN stack on rest of the nodes
  ndn::StackHelper ndnHelper;
  ndnHelper.Install(Names::Find<Node>("client1"));
  ndnHelper.Install(Names::Find<Node>("client2"));
  ndnHelper.Install(Names::Find<Node>("client3"));
  ndnHelper.Install(Names::Find<Node>("originServer"));


// Choosing forwarding strategy
  ndn::StrategyChoiceHelper::InstallAll("/prefix", "/localhost/nfd/strategy/best-route");

//  Ptr<Node> consumers1 = Names::Find<Node>("client1");
//  Ptr<Node> consumers2 = Names::Find<Node>("client2");
//  Ptr<Node> consumers3 = Names::Find<Node>("client3");
  Ptr<Node> consumers[3] = {Names::Find<Node>("client1"), Names::Find<Node>("client2"), Names::Find<Node>("client3")};
  Ptr<Node> producer = Names::Find<Node>("originServer");

  cout << "Installing Global routing interface on all nodes";

// Installing global routing interface on all nodes
  ndn::GlobalRoutingHelper ndnGlobalRoutingHelper;
  ndnGlobalRoutingHelper.InstallAll();

  cout << " Creating app1....";
  // App1
  /*ndn::AppHelper app1("CustomApp");
  app1.SetPrefix("/root");
  app1.Install(consumers1);
  app1.Install(consumers2);
  app1.Install(consumers3);*/

//  for (int i = 0; i < 3; i++) {
 //   std::cout << "i: " << i;
    ndn::AppHelper consumerHelper1("ns3::ndn::ConsumerCbr");
    consumerHelper1.SetAttribute("Frequency", StringValue("1")); 
    consumerHelper1.SetPrefix("/root/" + Names::FindName(consumers[0]));
//    consumerHelper.Install(consumers[i]);
    ns3::ApplicationContainer ac1 = consumerHelper1.Install(consumers[0]);
    ac1.Start(Seconds (1.0));
    ac1.Stop(Seconds (2.0));
//  }
    
    ndn::AppHelper consumerHelper2("ns3::ndn::ConsumerCbr");
    consumerHelper2.SetAttribute("Frequency", StringValue("1")); 
    consumerHelper2.SetPrefix("/root/" + Names::FindName(consumers[1]));
//    consumerHelper.Install(consumers[i]);
    //consumerHelper2.Install(consumers[1]).Start(Seconds (2.0));
    ns3::ApplicationContainer ac2 = consumerHelper2.Install(consumers[1]);
    ac2.Start(Seconds (2.0));
    ac2.Stop(Seconds (3.0));
    //consumerHelper2.Install(consumers[0]).Stop(Seconds (3.0));
    
    ndn::AppHelper consumerHelper3("ns3::ndn::ConsumerCbr");
    consumerHelper3.SetAttribute("Frequency", StringValue("1")); 
    consumerHelper3.SetPrefix("/root/" + Names::FindName(consumers[2]));
//    consumerHelper.Install(consumers[i]);
    //consumerHelper3.Install(consumers[2]).Start(Seconds (3.0));
    ns3::ApplicationContainer ac3 = consumerHelper3.Install(consumers[2]);
    ac3.Start(Seconds (3.0));
    ac3.Stop(Seconds (4.0));
    //consumerHelper3.Install(consumers[0]).Stop(Seconds (4.0));

  // App2
  //ndn::AppHelper app2("Hijacker");
  //app2.Install(producer); // last node

  cout << " Creating Producer";

  ndn::AppHelper producerHelper("ns3::ndn::Producer");
  // Producer will reply to all requests starting with /prefix
  producerHelper.SetAttribute("PayloadSize", StringValue("1024"));

  ndnGlobalRoutingHelper.AddOrigins("/root", producer);
  producerHelper.SetPrefix("/root");
  producerHelper.Install(producer);

  // Calculate and install FIBs
  ndn::GlobalRoutingHelper::CalculateRoutes();

  Simulator::Stop(Seconds(4.0));

  Simulator::Run();
  Simulator::Destroy();

  return 0;
}
int
main(int argc, char* argv[])
{
  // setting default parameters for PointToPoint links and channels
  Config::SetDefault("ns3::PointToPointNetDevice::DataRate", StringValue("1Mbps"));
  Config::SetDefault("ns3::PointToPointChannel::Delay", StringValue("10ms"));
  Config::SetDefault("ns3::QueueBase::MaxSize", StringValue("20p"));

  // Read optional command-line parameters (e.g., enable visualizer with ./waf --run=<> --visualize
  CommandLine cmd;
  cmd.Parse(argc, argv);

  // Creating nodes
  Ptr<Node> consumer = CreateObject<Node>();
  Ptr<Node> intRouter = CreateObject<Node>();
  NodeContainer uclaRegion;
  uclaRegion.Create(3);

  // Connecting nodes using two links
  PointToPointHelper p2p;
  p2p.Install(consumer, intRouter);
  p2p.Install(intRouter, uclaRegion.Get(0));
  p2p.Install(intRouter, uclaRegion.Get(1));
  p2p.Install(uclaRegion.Get(0), uclaRegion.Get(1));
  p2p.Install(uclaRegion.Get(1), uclaRegion.Get(2));

  // Install NDN stack on all nodes
  ndn::StackHelper ndnHelper;
  ndnHelper.SetDefaultRoutes(true);
  ndnHelper.InstallAll();

  // Install Routes Manually
  ndn::FibHelper::AddRoute(intRouter, ndn::Name("/ucla"), uclaRegion.Get(1), 1);

  // Configure NetworkRegionTable
  ndn::NetworkRegionTableHelper::AddRegionName(uclaRegion, ndn::Name("/ucla"));

  // Installing applications

  // Consumer
  ndn::AppHelper requesterHelper("RequesterApp");
  requesterHelper.SetAttribute("Name", StringValue("/ndnSIM/someData"));
  requesterHelper.SetAttribute("Delegation", StringValue("/ucla1"));
  requesterHelper.Install(consumer).Start(Seconds(1));

  requesterHelper.SetAttribute("Name", StringValue("/ndnSIM/anotherData"));
  requesterHelper.Install(consumer).Start(Seconds(2));

  requesterHelper.SetAttribute("Name", StringValue("/ndnSIM/yetAnotherData"));
  requesterHelper.SetAttribute("Delegation", StringValue("/non-existing"));
  requesterHelper.Install(consumer).Start(Seconds(3));

  // Producer
  ndn::AppHelper producerHelper("ns3::ndn::Producer");
  producerHelper.SetPrefix("/ndnSIM");
  producerHelper.SetAttribute("PayloadSize", StringValue("1024"));
  producerHelper.Install(uclaRegion.Get(0));

  Simulator::Stop(Seconds(20.0));

  Simulator::Run();
  Simulator::Destroy();

  return 0;
}
int
main(int argc, char* argv[])
{
  // setting default parameters for PointToPoint links and channels
  Config::SetDefault("ns3::PointToPointNetDevice::DataRate", StringValue("10Mbps"));
  Config::SetDefault("ns3::PointToPointChannel::Delay", StringValue("10ms"));
  Config::SetDefault("ns3::DropTailQueue::MaxPackets", StringValue("20"));

  // Read optional command-line parameters (e.g., enable visualizer with ./waf --run=<> --visualize
  CommandLine cmd;
  cmd.Parse(argc, argv);

  // Creating nodes
  NodeContainer nodes;
  nodes.Create(3); // 3 nodes, connected: 0 <---> 1 <---> 2

  // Connecting nodes using two links
  PointToPointHelper p2p;
  p2p.Install(nodes.Get(0), nodes.Get(1));
  p2p.Install(nodes.Get(1), nodes.Get(2));

  // Install NDN stack on all nodes
  ndn::StackHelper ndnHelper;
  ndnHelper.SetDefaultRoutes(true);
  ndnHelper.setCsSize(0);
  ndnHelper.SetOldContentStore("ns3::ndn::cs::Lru", "MaxSize", "100");
  ndnHelper.InstallAll();

  // Choosing forwarding strategy
  ndn::StrategyChoiceHelper::InstallAll("/myprefix", "/localhost/nfd/strategy/best-route");

  ns3::ndn::AppHelper consumerHelper("ns3::ndn::FileConsumerCbr::MultimediaConsumer");
  consumerHelper.SetAttribute("AllowUpscale", BooleanValue(true));
  consumerHelper.SetAttribute("AllowDownscale", BooleanValue(false));
  consumerHelper.SetAttribute("ScreenWidth", UintegerValue(1920));
  consumerHelper.SetAttribute("ScreenHeight", UintegerValue(1080));
  consumerHelper.SetAttribute("StartRepresentationId", StringValue("auto"));
  consumerHelper.SetAttribute("MaxBufferedSeconds", UintegerValue(30));
  consumerHelper.SetAttribute("StartUpDelay", StringValue("0.1"));

  consumerHelper.SetAttribute("AdaptationLogic", StringValue("dash::player::RateAndBufferBasedAdaptationLogic"));
  consumerHelper.SetAttribute("MpdFileToRequest", StringValue(std::string("/myprefix/FakeVid1/vid1.mpd" )));

  //consumerHelper.SetPrefix (std::string("/Server_" + boost::lexical_cast<std::string>(i%server.size ()) + "/layer0"));
  ApplicationContainer app1 = consumerHelper.Install (nodes.Get(2));

  ndn::AppHelper fakeDASHProducerHelper("ns3::ndn::FakeMultimediaServer");

  // This fake multimedia producer will reply to all requests starting with /myprefix/FakeVid1
  fakeDASHProducerHelper.SetPrefix("/myprefix/FakeVid1");
  fakeDASHProducerHelper.SetAttribute("MetaDataFile", StringValue("representations/netflix_vid1.csv"));
  // We just give the MPD file a name that makes it unique
  fakeDASHProducerHelper.SetAttribute("MPDFileName", StringValue("vid1.mpd"));

  fakeDASHProducerHelper.Install(nodes.Get(0));

  // We can install more then one fake multimedia producer on one node:

  // This fake multimedia producer will reply to all requests starting with /myprefix/FakeVid2
  fakeDASHProducerHelper.SetPrefix("/myprefix/FakeVid2");
  fakeDASHProducerHelper.SetAttribute("MetaDataFile", StringValue("representations/netflix_vid2.csv"));
  // We just give the MPD file a name that makes it unique
  fakeDASHProducerHelper.SetAttribute("MPDFileName", StringValue("vid2.mpd"));


  // This fake multimedia producer will reply to all requests starting with /myprefix/FakeVid3
  fakeDASHProducerHelper.SetPrefix("/myprefix/FakeVid3");
  fakeDASHProducerHelper.SetAttribute("MetaDataFile", StringValue("representations/netflix_vid3.csv"));
  // We just give the MPD file a name that makes it unique
  fakeDASHProducerHelper.SetAttribute("MPDFileName", StringValue("vid3.mpd"));

  ndn::GlobalRoutingHelper ndnGlobalRoutingHelper;
  ndnGlobalRoutingHelper.InstallAll();

  ndnGlobalRoutingHelper.AddOrigins("/myprefix", nodes.Get(0));
  ndn::GlobalRoutingHelper::CalculateRoutes();

  Simulator::Stop(Seconds(60.0));

  Simulator::Run();
  Simulator::Destroy();

  NS_LOG_UNCOND("Simulation Finished.");

  return 0;
}
int main (int argc, char *argv[])
{
  std::string phyMode ("DsssRate1Mbps");
  double rss = -80;  // -dBm
  uint32_t packetSize = 1000; // bytes
  uint32_t numPackets = 1;
  double interval = 1.0; // seconds
  bool verbose = false;

  CommandLine cmd;

  cmd.AddValue ("phyMode", "Wifi Phy mode", phyMode);
  cmd.AddValue ("rss", "received signal strength", rss);
  cmd.AddValue ("packetSize", "size of application packet sent", packetSize);
  cmd.AddValue ("numPackets", "number of packets generated", numPackets);
  cmd.AddValue ("interval", "interval (seconds) between packets", interval);
  cmd.AddValue ("verbose", "turn on all WifiNetDevice log components", verbose);

  cmd.Parse (argc, argv);
  // Convert to time object
  Time interPacketInterval = Seconds (interval);

  // disable fragmentation for frames below 2200 bytes
  Config::SetDefault ("ns3::WifiRemoteStationManager::FragmentationThreshold", StringValue ("2200"));
  // turn off RTS/CTS for frames below 2200 bytes
  Config::SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold", StringValue ("2200"));
  // Fix non-unicast data rate to be the same as that of unicast
  Config::SetDefault ("ns3::WifiRemoteStationManager::NonUnicastMode", 
                      StringValue (phyMode));

  NodeContainer c;
  c.Create (2);

  // The below set of helpers will help us to put together the wifi NICs we want
  WifiHelper wifi;
  if (verbose)
    {
      wifi.EnableLogComponents ();  // Turn on all Wifi logging
    }
  wifi.SetStandard (WIFI_PHY_STANDARD_80211b);

  YansWifiPhyHelper wifiPhy =  YansWifiPhyHelper::Default ();
  // This is one parameter that matters when using FixedRssLossModel
  // set it to zero; otherwise, gain will be added
  wifiPhy.Set ("RxGain", DoubleValue (0) ); 
  // ns-3 supports RadioTap and Prism tracing extensions for 802.11b
  wifiPhy.SetPcapDataLinkType (YansWifiPhyHelper::DLT_IEEE802_11_RADIO); 

  YansWifiChannelHelper wifiChannel;
  wifiChannel.SetPropagationDelay ("ns3::ConstantSpeedPropagationDelayModel");
  // The below FixedRssLossModel will cause the rss to be fixed regardless
  // of the distance between the two stations, and the transmit power
  wifiChannel.AddPropagationLoss ("ns3::FixedRssLossModel","Rss",DoubleValue (rss));
  wifiPhy.SetChannel (wifiChannel.Create ());

  // Add a non-QoS upper mac, and disable rate control
  NqosWifiMacHelper wifiMac = NqosWifiMacHelper::Default ();
  wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager",
                                "DataMode",StringValue (phyMode),
                                "ControlMode",StringValue (phyMode));

  // Setup the rest of the upper mac
  Ssid ssid = Ssid ("wifi-default");
  // setup sta.
  wifiMac.SetType ("ns3::StaWifiMac",
                   "Ssid", SsidValue (ssid),
                   "ActiveProbing", BooleanValue (false));
  NetDeviceContainer staDevice = wifi.Install (wifiPhy, wifiMac, c.Get (0));
  NetDeviceContainer devices = staDevice;
  // setup ap.
  wifiMac.SetType ("ns3::ApWifiMac",
                   "Ssid", SsidValue (ssid));
  NetDeviceContainer apDevice = wifi.Install (wifiPhy, wifiMac, c.Get (1));
  devices.Add (apDevice);

  // Note that with FixedRssLossModel, the positions below are not 
  // used for received signal strength. 
  MobilityHelper mobility;
  Ptr<ListPositionAllocator> positionAlloc = CreateObject<ListPositionAllocator> ();
  positionAlloc->Add (Vector (0.0, 0.0, 0.0));
  positionAlloc->Add (Vector (5.0, 0.0, 0.0));
  mobility.SetPositionAllocator (positionAlloc);
  mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
  mobility.Install (c);

  InternetStackHelper internet;
  internet.Install (c);

  Ipv4AddressHelper ipv4;
  NS_LOG_INFO ("Assign IP Addresses.");
  ipv4.SetBase ("10.1.1.0", "255.255.255.0");
  Ipv4InterfaceContainer i = ipv4.Assign (devices);

  TypeId tid = TypeId::LookupByName ("ns3::UdpSocketFactory");
  Ptr<Socket> recvSink = Socket::CreateSocket (c.Get (0), tid);
  InetSocketAddress local = InetSocketAddress (Ipv4Address::GetAny (), 80);
  recvSink->Bind (local);
  recvSink->SetRecvCallback (MakeCallback (&ReceivePacket));

  Ptr<Socket> source = Socket::CreateSocket (c.Get (1), tid);
  InetSocketAddress remote = InetSocketAddress (Ipv4Address ("255.255.255.255"), 80);
  source->SetAllowBroadcast (true);
  source->Connect (remote);

  // Tracing
  wifiPhy.EnablePcap ("wifi-simple-infra", devices);

  // Output what we are doing
  NS_LOG_UNCOND ("Testing " << numPackets  << " packets sent with receiver rss " << rss );

  Simulator::ScheduleWithContext (source->GetNode ()->GetId (),
                                  Seconds (1.0), &GenerateTraffic, 
                                  source, packetSize, numPackets, interPacketInterval);

  Simulator::Stop (Seconds (30.0));
  Simulator::Run ();
  Simulator::Destroy ();

  return 0;
}
Exemple #14
0
int 
main (int argc, char *argv[])
{

  //
  // Set up some default values for the simulation.
  //
  Config::SetDefault ("ns3::OnOffApplication::PacketSize", UintegerValue (137));

  // ??? try and stick 15kb/s into the data rate
  Config::SetDefault ("ns3::OnOffApplication::DataRate", StringValue ("14kb/s"));

  //
  // Default number of nodes in the star.  Overridable by command line argument.
  //
  uint32_t nSpokes = 8;

  CommandLine cmd;
  cmd.AddValue ("nSpokes", "Number of nodes to place in the star", nSpokes);
  cmd.Parse (argc, argv);

  NS_LOG_INFO ("Build star topology.");
  PointToPointHelper pointToPoint;
  pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
  pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms"));
  PointToPointStarHelper star (nSpokes, pointToPoint);

  NS_LOG_INFO ("Install internet stack on all nodes.");
  InternetStackHelper internet;
  star.InstallStack (internet);

  NS_LOG_INFO ("Assign IP Addresses.");
  star.AssignIpv4Addresses (Ipv4AddressHelper ("10.1.1.0", "255.255.255.0"));

  NS_LOG_INFO ("Create applications.");
  //
  // Create a packet sink on the star "hub" to receive packets.
  // 
  uint16_t port = 50000;
  Address hubLocalAddress (InetSocketAddress (Ipv4Address::GetAny (), port));
  PacketSinkHelper packetSinkHelper ("ns3::TcpSocketFactory", hubLocalAddress);
  ApplicationContainer hubApp = packetSinkHelper.Install (star.GetHub ());
  hubApp.Start (Seconds (1.0));
  hubApp.Stop (Seconds (10.0));

  //
  // Create OnOff applications to send TCP to the hub, one on each spoke node.
  //
  OnOffHelper onOffHelper ("ns3::TcpSocketFactory", Address ());
  onOffHelper.SetAttribute ("OnTime", StringValue ("ns3::ConstantRandomVariable[Constant=1]"));
  onOffHelper.SetAttribute ("OffTime", StringValue ("ns3::ConstantRandomVariable[Constant=0]"));

  ApplicationContainer spokeApps;

  for (uint32_t i = 0; i < star.SpokeCount (); ++i)
    {
      AddressValue remoteAddress (InetSocketAddress (star.GetHubIpv4Address (i), port));
      onOffHelper.SetAttribute ("Remote", remoteAddress);
      spokeApps.Add (onOffHelper.Install (star.GetSpokeNode (i)));
    }
  spokeApps.Start (Seconds (1.0));
  spokeApps.Stop (Seconds (10.0));

  NS_LOG_INFO ("Enable static global routing.");
  //
  // Turn on global static routing so we can actually be routed across the star.
  //
  Ipv4GlobalRoutingHelper::PopulateRoutingTables ();

  NS_LOG_INFO ("Enable pcap tracing.");
  //
  // Do pcap tracing on all point-to-point devices on all nodes.
  //
  pointToPoint.EnablePcapAll ("star");

  NS_LOG_INFO ("Run Simulation.");
  Simulator::Run ();
  Simulator::Destroy ();
  NS_LOG_INFO ("Done.");

  return 0;
}
Exemple #15
0
int main(int argc, char *argv[])
{
   int retval = 0;

   QCoreApplication::setOrganizationName("SLART");
   QCoreApplication::setOrganizationDomain("svolli.org");
   QCoreApplication::setApplicationName("TestAppXxtea");
   QCoreApplication app( argc, argv );

   QTextStream qStdOut( stdout );
   QTextStream qStdErr( stderr );
   QSettings   settings;

   QString progName( QFileInfo( QCoreApplication::arguments().at(0) ).fileName() );
   bool help = false;
   bool encrypt = false;
   bool decrypt = false;
   QString key;
   QStringList files;
   CommandLine cl;
   cl.option( "-help",    "show help",     &help,    true );
   cl.option( "-encrypt", "encrypt files", &encrypt, true );
   cl.option( "-decrypt", "decrypt files", &decrypt, true );
   cl.option( "-key",     "set key",       &key );
   cl.parse( &files );

   if( cl.check() )
   {
      qStdErr << "fail! try '-help'\n";
      return 0;
   }

   if( help )
   {
      qStdErr <<
      "\nthis program encrypts and decrypts files using the xxtea algorithm\n"
      "see http://en.wikipedia.org/wiki/XXTEA for details\n"
      "\noptions:\n" << cl.help() << "\n\nexamples:\n"
      << progName << " -key secret                # writes the key secret in the registry\n"
      << progName << " -encrypt file1 (file2 ...) # encryptes the files\n"
      << progName << " -decrypt file1 (file2 ...) # decryptes the files\n"
      << progName << " -key secret -encrypt file  # set key and encrypt in one pass\n\n"
      ;
      return 0;
   }

   if( key.isNull() )
   {
      key = settings.value( "Key" ).toByteArray();
   }
   else
   {
      if( key.isEmpty() )
      {
         settings.remove( "Key" );
         qStdOut << "deleting key\n";
      }
      else
      {
         QCryptographicHash hash( QCryptographicHash::Md5 );
         hash.addData( key.toUtf8() );
         settings.setValue( "Key", hash.result() );
         qStdOut << "setting key to: " << settings.value( "Key" ).toByteArray().toHex() << "\n";
      }

      if( !encrypt && !decrypt )
      {
         return 0;
      }
   }

   if( encrypt == decrypt )
   {
      qStdErr << "you need to specify exactly one of -encrypt or -decrypt\n";
      return 1;
   }

   QFile       file;
   QByteArray  fileData;
   Xxtea       xxtea;
   bool        success = false;

   QByteArray hashedKey( settings.value( "Key" ).toByteArray() );
   if( hashedKey.size() != 16 )
   {
      qStdOut << "key is invalid\n";
      return 1;
   }
   else
   {
      qStdOut << "key is: " << hashedKey.toHex() << "\n";
   }
   xxtea.setKey( hashedKey );
   xxtea.setData( &fileData );
   foreach( const QString &fileName, files )
   {
      qStdOut << fileName << ": ";
      file.setFileName( fileName );
      file.open( QIODevice::ReadWrite );
      qStdOut << "reading, ";
      fileData = file.readAll();
      if( encrypt )
      {
         qStdOut << "encrypting, ";
         success = xxtea.encode();
      }
      if( decrypt )
      {
         qStdOut << "decrypting, ";
         success = xxtea.decode();
      }
      if( !success )
      {
         qStdOut << "some or all data could not be processed, ";
      }
      file.seek( 0 );
      qStdOut << "writing, ";
      file.write( fileData );
      file.close();
      qStdOut << "done.\n";
   }
int
main (int argc, char *argv[])
{
#ifdef NS3_MPI
  // Distributed simulation setup
  MpiInterface::Enable (&argc, &argv);
  GlobalValue::Bind ("SimulatorImplementationType",
                     StringValue ("ns3::DistributedSimulatorImpl"));

  LogComponentEnable ("BriteMPITest", LOG_LEVEL_ALL);
  LogComponentEnable ("TcpSocketBase", LOG_LEVEL_INFO);

  uint32_t systemId = MpiInterface::GetSystemId ();
  uint32_t systemCount = MpiInterface::GetSize ();

  // Check for valid distributed parameters.
  // For just this particular example, must have 2 and only 2 Logical Processors (LPs)
  NS_ASSERT_MSG (systemCount == 2, "This demonstration requires 2 and only 2 logical processors.");

  // BRITE needs a configuration file to build its graph. By default, this
  // example will use the TD_ASBarabasi_RTWaxman.conf file. There are many others
  // which can be found in the BRITE/conf_files directory
  std::string confFile = "src/brite/examples/conf_files/TD_ASBarabasi_RTWaxman.conf";
  bool tracing = false;
  bool nix = false;

  CommandLine cmd;
  cmd.AddValue ("confFile", "BRITE conf file", confFile);
  cmd.AddValue ("tracing", "Enable or disable ascii tracing", tracing);
  cmd.AddValue ("nix", "Enable or disable nix-vector routing", nix);

  cmd.Parse (argc,argv);

  // Invoke the BriteTopologyHelper and pass in a BRITE
  // configuration file and a seed file. This will use
  // BRITE to build a graph from which we can build the ns-3 topology
  BriteTopologyHelper bth (confFile);

  PointToPointHelper p2p;

  Ipv4StaticRoutingHelper staticRouting;
  Ipv4GlobalRoutingHelper globalRouting;
  Ipv4ListRoutingHelper listRouting;
  Ipv4NixVectorHelper nixRouting;

  InternetStackHelper stack;

  if (nix)
    {
      listRouting.Add (staticRouting, 0);
      listRouting.Add (nixRouting, 10);
    }
  else
    {
      listRouting.Add (staticRouting, 0);
      listRouting.Add (globalRouting, 10);
    }

  stack.SetRoutingHelper (listRouting);

  Ipv4AddressHelper address;
  address.SetBase ("10.0.0.0", "255.255.255.252");

  //build topology as normal but also pass systemCount
  bth.BuildBriteTopology (stack, systemCount);
  bth.AssignIpv4Addresses (address);

  NS_LOG_LOGIC ("Number of AS created " << bth.GetNAs ());

  uint16_t port = 5001;

  NodeContainer client;
  NodeContainer server;

  //For this example will use AS 0 and AS 1 which will be on seperate systems
  //due to the mod divide used to assign AS to system.

  //GetSystemNumberForAs (uint32_t) can be used to determine which system an
  //AS is assigned to
  NS_LOG_LOGIC ("AS 0 has been assigned to system " << bth.GetSystemNumberForAs (0));
  NS_LOG_LOGIC ("As 1 has been assigned to system " << bth.GetSystemNumberForAs (1));

  //install client node on last leaf node of AS 0
  client.Add (CreateObject<Node> (0));
  stack.Install (client);
  int numLeafNodesInAsZero = bth.GetNLeafNodesForAs (0);
  client.Add (bth.GetLeafNodeForAs (0, numLeafNodesInAsZero - 1));

  //install server node on last leaf node on AS 1
  server.Add (CreateObject<Node> (1));
  stack.Install (server);
  int numLeafNodesInAsOne = bth.GetNLeafNodesForAs (1);
  server.Add (bth.GetLeafNodeForAs (1, numLeafNodesInAsOne - 1));

  p2p.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
  p2p.SetChannelAttribute ("Delay", StringValue ("2ms"));

  NetDeviceContainer p2pClientDevices;
  NetDeviceContainer p2pServerDevices;

  p2pClientDevices = p2p.Install (client);
  p2pServerDevices = p2p.Install (server);

  address.SetBase ("10.1.0.0", "255.255.0.0");
  Ipv4InterfaceContainer clientInterfaces;
  clientInterfaces = address.Assign (p2pClientDevices);

  address.SetBase ("10.2.0.0", "255.255.0.0");
  Ipv4InterfaceContainer serverInterfaces;
  serverInterfaces = address.Assign (p2pServerDevices);

  if (!nix)
    {
      Ipv4GlobalRoutingHelper::PopulateRoutingTables ();
    }

  //only has two systems in this example.  Install applications only on nodes in my system


  //Moved here to get totalRX at end
  ApplicationContainer sinkApps;

  if (systemId == 1)
    {

      Address sinkLocalAddress (InetSocketAddress (Ipv4Address::GetAny (), port));
      PacketSinkHelper packetSinkHelper ("ns3::TcpSocketFactory", sinkLocalAddress);
      sinkApps.Add (packetSinkHelper.Install (server.Get (0)));
      sinkApps.Start (Seconds (0.0));
      sinkApps.Stop (Seconds (10.0));
    }

  if (systemId == 0)
    {
      OnOffHelper clientHelper ("ns3::TcpSocketFactory", Address ());
      clientHelper.SetAttribute ("OnTime", StringValue ("ns3::ConstantRandomVariable[Constant=1]"));
      clientHelper.SetAttribute ("OffTime", StringValue ("ns3::ConstantRandomVariable[Constant=0]"));

      ApplicationContainer clientApps;
      AddressValue remoteAddress (InetSocketAddress (serverInterfaces.GetAddress (0), port));
      clientHelper.SetAttribute ("Remote", remoteAddress);
      clientApps.Add (clientHelper.Install (client.Get (0)));
      clientApps.Start (Seconds (1.0)); // Start 1 second after sink
      clientApps.Stop (Seconds (9.0)); // Stop before the sink
    }

  if (!nix)
    {
      Ipv4GlobalRoutingHelper::PopulateRoutingTables ();
    }

  if (tracing)
    {
      AsciiTraceHelper ascii;
      p2p.EnableAsciiAll (ascii.CreateFileStream ("briteLeaves.tr"));
    }

  // Run the simulator
  Simulator::Stop (Seconds (200.0));
  Simulator::Run ();
  Simulator::Destroy ();

  if (systemId == 1)
    {
      Ptr<PacketSink> sink1 = DynamicCast<PacketSink> (sinkApps.Get (0));
      NS_LOG_DEBUG ("Total Bytes Received: " << sink1->GetTotalRx ());
    }

  MpiInterface::Disable ();

  return 0;

#else
  NS_FATAL_ERROR ("Can't use distributed simulator without MPI compiled in");
#endif
}
Exemple #17
0
sint32 ui_HandleKeypress(WPARAM wParam, LPARAM lParam)
{
    WORLD_DIRECTION	d;
    BOOL			move = FALSE;
#ifdef _PLAYTEST
    int i;
#endif
	BOOL isMyTurn = !g_network.IsActive() || g_network.IsMyTurn();
	Unit city;

	
	if ( g_isKMScreen) {
		switch(wParam) {
			case VK_ESCAPE:
			case VK_LEFT + 256:
			case VK_RIGHT + 256:
			case VK_UP + 256:
			case VK_DOWN + 256:
			case 29: 
			case 28: 
				
				return TRUE;
			default:
				
				km_screen_remapKey( wParam, lParam );
				return TRUE;
		}
	}
	
#ifdef _PLAYTEST
	if(commandMode) {
		switch(wParam) {
			case '\r' + 128: wParam = '\r'; break;
			case '\t' + 128: wParam = '\t'; break;
			case 8 + 128: wParam = 8; break;
		}
		commandMode = g_commandLine.AddKey(static_cast<char>(wParam));
		return TRUE;
	}
#endif






	
	if (wParam == VK_ESCAPE) {
		
		extern OptionsWindow *g_optionsWindow;
		
		if(g_c3ui->TopWindow() && g_c3ui->TopWindow() == DipWizard::GetWindow()) {
			
			
		} else if(g_keyboardHandlers.GetTail()) {
			g_keyboardHandlers.GetTail()->kh_Close();
		} else if (g_civApp->IsGameLoaded()) {
			if(g_currentMessageWindow && 
			   g_currentMessageWindow->GetMessage() &&
			   (g_theMessagePool->IsValid(*g_currentMessageWindow->GetMessage()))) {
				g_currentMessageWindow->GetMessage()->Minimize();
			} else if(g_modalMessage) {
				
				Message *msg = g_modalMessage->GetMessage();
				if(msg && g_theMessagePool->IsValid(*msg)) {
					Assert(msg->IsAlertBox());
					MessageData *data = msg->AccessData();
					if(data->GetNumButtons() <= 2 && data->GetNumButtons() > 0) {
						data->GetButton(0)->Callback();
					}
				}	
			} else if (g_optionsWindow && g_c3ui->GetWindow(g_optionsWindow->Id())) {
				
				optionsscreen_removeMyWindow(AUI_BUTTON_ACTION_EXECUTE);
			} else if(g_c3ui->TopWindow() && g_c3ui->TopWindow()->HandleKey(wParam)) {
				
			} else if(g_battleViewWindow) {
				battleview_ExitButtonActionCallback( NULL, AUI_BUTTON_ACTION_EXECUTE, 0, NULL);
			} else {
				
				optionsscreen_Initialize();
				optionsscreen_displayMyWindow(1);
			}
		}
		return TRUE;
	}

	
	aui_Window *topWindow = g_c3ui->TopWindow();
	if(topWindow && (!g_controlPanel || topWindow != g_controlPanel->GetWindow()) && topWindow != g_statusWindow) {
		if(topWindow->HandleKey(wParam))
			return 0;
	}

	
	
	if (!theKeyMap) return 0;

	
	if (g_slicEngine && g_slicEngine->RunKeyboardTrigger(static_cast<char>(wParam))) 
	{
		return 0;
	}

	if (!g_civApp->IsGameLoaded()) {
		return TRUE;
	}

	KEY_FUNCTION	kf = theKeyMap->get_function(wParam); 
	if (kf != KEY_FUNCTION_NOOP) 
	{
		g_selected_item->RegisterUIClick();
	}

	if (topWindow->IsStronglyModal() /*&& keypress_IsGameFunction(kf)*/) // I should not be able to open other windows if I have have open strongly modal windows like the DipWizzard
	{
		return 0;
	}

#if 0
	MapPoint point;
	g_tiledMap->GetMouseTilePos(point);
#endif

	switch (kf) {
#ifdef _PLAYTEST
	case KEY_FUNCTION_ENTER_COMMAND: 
		segmentlist_Display();
		break;
	case KEY_FUNCTION_ENTER_COMMAND_ALTERNATE:
		commandMode = TRUE; 
		move = FALSE; 
		break;
#endif
    case KEY_FUNCTION_NOOP: return FALSE; 
    case KEY_FUNCTION_MOVE_NORTHWEST: d = NORTHWEST; move = TRUE; break;
    case KEY_FUNCTION_MOVE_NORTH: d = NORTH; move = TRUE; break; 
    case KEY_FUNCTION_MOVE_NORTHEAST: d = NORTHEAST; move = TRUE; break; 
    case KEY_FUNCTION_MOVE_WEST: d = WEST; move = TRUE; break; 
    case KEY_FUNCTION_MOVE_EAST: d = EAST; move = TRUE; break; 
    case KEY_FUNCTION_MOVE_SOUTHWEST: d = SOUTHWEST; move = TRUE; break; 
    case KEY_FUNCTION_MOVE_SOUTH: d = SOUTH; move = TRUE; break; 
    case KEY_FUNCTION_MOVE_SOUTHEAST: d = SOUTHEAST; move = TRUE; break;

	case KEY_FUNCTION_ENTRENCH:
		if(isMyTurn) g_selected_item->Entrench();
		break;









	case KEY_FUNCTION_UNLOAD_TRANS:
	{
		sint32 order;
		if(!g_theOrderDB->GetNamedItem("ORDER_UNLOAD", order))
			return 0;

		Army a;
		if(g_selected_item->GetSelectedArmy(a))
			g_controlPanel->BeginOrderDelivery(g_theOrderDB->Access(order));
	}
	break;
	case KEY_FUNCTION_SETTLE:
	{
		g_selected_item->Settle();
		move = FALSE;
		break;
	}
	case KEY_FUNCTION_SPACE_LAUNCH:
		if(isMyTurn) {
			sint32 index;
			if(g_theOrderDB->GetNamedItem("ORDER_SPACE_LAUNCH", index)) {
				g_controlPanel->BeginOrderDelivery(g_theOrderDB->Access(index));
			}
			
			return TRUE;
		}
		break;
	case KEY_FUNCTION_DESCEND:		
		g_selected_item->Descend();
		break;
	case KEY_FUNCTION_PILLAGE:
	{
		sint32 order;
		if(!g_theOrderDB->GetNamedItem("ORDER_PILLAGE", order))
			return 0;

		Army a;
		if(g_selected_item->GetSelectedArmy(a) && a.CanPillage()) {
			g_controlPanel->BeginOrderDelivery(g_theOrderDB->Access(order));
		} else {
			g_selected_item->Pillage();
			return 0;
		}
	}
		break;
	case KEY_FUNCTION_BOMBARD:
	{
		sint32 order;
		if(!g_theOrderDB->GetNamedItem("ORDER_BOMBARD", order))
			return 0;

		Army a;
		if(g_selected_item->GetSelectedArmy(a) && a.CanBombard()) {
			g_controlPanel->BeginOrderDelivery(g_theOrderDB->Access(order));
		} else {
			return 0;
		}
	}
		




		break;
	case KEY_FUNCTION_EXPEL:		
	{
		sint32 order;
		if(!g_theOrderDB->GetNamedItem("ORDER_EXPEL", order))
			return 0;

		Army a;
		if(g_selected_item->GetSelectedArmy(a) && a.CanExpel()) {
			g_controlPanel->BeginOrderDelivery(g_theOrderDB->Access(order));
		} else {
			return 0;
		}
	}
			



		break;
	case KEY_FUNCTION_SLEEP:
		if(isMyTurn) {
			move = FALSE;

			g_selected_item->Sleep();
		}
		break;
    case KEY_FUNCTION_NEXT_ITEM: 
        g_selected_item->NextItem(); 
		move = FALSE;
        break;

	case KEY_FUNCTION_PARADROP:
		if(isMyTurn) {
			MapPoint point;
			g_tiledMap->GetMouseTilePos(point);
			g_selected_item->Paradrop(point);
			return TRUE;
		}
		break;

	case KEY_FUNCTION_INVESTIGATE_CITY:
        {
            MapPoint    point;
            g_tiledMap->GetMouseTilePos(point);
		    g_selected_item->InvestigateCity(point);
        }
		break;

	case KEY_FUNCTION_PLANT_NUKE:				
	{
		sint32 order;
		if(!g_theOrderDB->GetNamedItem("ORDER_PLANT_NUKE", order))
			return 0;

		Army a;
		double chance, escape_chance;
		if(g_selected_item->GetSelectedArmy(a) && a.CanPlantNuke(chance, escape_chance)) {
			g_controlPanel->BeginOrderDelivery(g_theOrderDB->Access(order));
		} else {
			return 0;
		}
	}
	
		break;
	case KEY_FUNCTION_BIOINFECT:				
	{
		sint32 order;
		if(!g_theOrderDB->GetNamedItem("ORDER_BIO_INFECT", order))
			return 0;

		Army a;
		double chance;
		if(g_selected_item->GetSelectedArmy(a) && a.CanBioInfect(chance)) {
			g_controlPanel->BeginOrderDelivery(g_theOrderDB->Access(order));
		} else {
			return 0;
		}
	}
	
		break;
	case KEY_FUNCTION_NANOTERROR:				
	{
		sint32 order;
		if(!g_theOrderDB->GetNamedItem("ORDER_NANO_INFECT", order))
			return 0;

		Army a;
		double chance;
		if(g_selected_item->GetSelectedArmy(a) && a.CanNanoInfect(chance)) {
			g_controlPanel->BeginOrderDelivery(g_theOrderDB->Access(order));
		} else {
			return 0;
		}
	}
	
		break;
	case KEY_FUNCTION_CREATE_PARK:				
	{
		sint32 order;
		if(!g_theOrderDB->GetNamedItem("ORDER_CREATE_PARK", order))
			return 0;

		Army a;
		if(g_selected_item->GetSelectedArmy(a) && a.AccessData()->CanCreatePark()) {
			g_controlPanel->BeginOrderDelivery(g_theOrderDB->Access(order));
		} else {
			return 0;
		}
	}
	
		break;
	case KEY_FUNCTION_REFORM:
	{
		sint32 order;
		if(!g_theOrderDB->GetNamedItem("ORDER_REFORM", order))
			return 0;

		Army a;
		if(g_selected_item->GetSelectedArmy(a) && a.AccessData()->CanReformCity()) {
			g_controlPanel->BeginOrderDelivery(g_theOrderDB->Access(order));
		} else {
			return 0;
		}
	}
	
		break;

	case KEY_FUNCTION_OPEN_WORK_VIEW:
		ArmyManagerWindow::Toggle();
		break;
	case KEY_FUNCTION_OPEN_CITY_VIEW:
		if(!g_modalWindow) {
			close_AllScreens();
			open_CityView();
		}
		break;
	case KEY_FUNCTION_OPEN_CITY_STATUS:
		if ( !g_modalWindow ) {
			close_AllScreens();
			open_CityStatus();
		}
		break;
	case KEY_FUNCTION_OPEN_CIV_STATUS:
		if ( !g_modalWindow ) {
			close_AllScreens();
			open_CivStatus();
		}
		break;
	case KEY_FUNCTION_OPEN_SCIENCE_STATUS:
		if ( !g_modalWindow ) {
			close_AllScreens();
			open_ScienceStatus();
		}
		break;
	case KEY_FUNCTION_OPEN_UNIT_STATUS:
		if ( !g_modalWindow ) {
			close_AllScreens();
			open_UnitStatus();
		}
		break;
	case KEY_FUNCTION_OPEN_TRADE_STATUS:
		if ( !g_modalWindow ) {
			close_AllScreens();
			TradeManager::Display();
			TradeManager::SetMode(TRADE_MANAGER_MARKET);
			
		}
		break;
	case KEY_FUNCTION_OPEN_DIPLOMACY:
		if ( !g_modalWindow ) {
			close_AllScreens();
			open_Diplomacy();
		}
		break;
	case KEY_FUNCTION_OPEN_INFO_SCREEN:
		if ( !g_modalWindow ) {
			InfoWindow::SelectScoreTab();
			InfoWindow::Open();
		}
		break;
	case KEY_FUNCTION_OPEN_GREAT_LIBRARY:
		if ( !g_modalWindow ) {
			close_AllScreens();
			open_GreatLibrary();
		}
		break;
	case KEY_FUNCTION_OPEN_OPTIONS_SCREEN:
		if ( !g_modalWindow ) {
			close_AllScreens();
			open_OptionsScreen(1);
		}
		break;

	case KEY_FUNCTION_OPEN_SCENARIO_EDITOR:
		if(!g_modalWindow
		&& !g_turn->IsEmail()
		){
			close_AllScreens();
			optionsscreen_mapeditorPress(NULL, AUI_BUTTON_ACTION_EXECUTE, 0, NULL);
		}
		break;
		
		
		
    case KEY_FUNCTION_ZOOM_IN1:
        if (g_tiledMap) {
			g_tiledMap->ZoomIn();
		}
		break;

    case KEY_FUNCTION_ZOOM_OUT1:
        if (g_tiledMap) {
			g_tiledMap->ZoomOut();
        }

		break;

	case KEY_FUNCTION_CENTER_MAP:
	{
		PLAYER_INDEX s_player; 
		ID s_item; 
		SELECT_TYPE s_state; 
		g_selected_item->GetTopCurItem(s_player, s_item, s_state);

        MapPoint pos;
		switch(s_state) {
			case SELECT_TYPE_LOCAL_ARMY:
			{	
				Army army(s_item);
				army.GetPos(pos);
				g_radarMap->CenterMap(pos);
				g_tiledMap->Refresh();
				g_tiledMap->InvalidateMap();
				break;
			}
			case SELECT_TYPE_LOCAL_CITY:
			{	
				Unit unit(s_item);
				unit.GetPos(pos);
				g_radarMap->CenterMap(pos);
				g_tiledMap->Refresh();
				g_tiledMap->InvalidateMap();

				break;
			}
		}
	}
	break;

	case KEY_FUNCTION_SAVE_GAME:
		if(g_network.IsActive()) {
			if(g_network.IsHost()) {
				
				
				g_isScenario = FALSE;
				loadsavescreen_displayMyWindow(LSS_SAVE_MP);
			}
		} else {
			
			
			g_isScenario = FALSE;

			loadsavescreen_displayMyWindow(LSS_SAVE_GAME);
		}
		break;
	case KEY_FUNCTION_LOAD_GAME:
		if(!g_network.IsActive()) {
			loadsavescreen_displayMyWindow(LSS_LOAD_GAME);
		}
		break;						
	case KEY_FUNCTION_REMAP_KEYBOARD:	
		open_KeyMappingScreen();
		break;
	
    case KEY_FUNCTION_KEYBOARD_SELECT_UNIT:
         g_selected_item->KeyboardSelectFirstUnit(); 
		 move = FALSE;
		 break; 

#ifdef _PLAYTEST
    case KEY_FUNCTION_RAND_TEST:
       g_is_rand_test=TRUE; 
         return TRUE; 
		 break;
#endif
        
#if 0
	case KEY_FUNCTION_ENDSLICE:
		if(g_network.IsActive()) {
			if(g_network.IsMyTurn() ||
			   (g_network.IsHost() && 
				g_player[g_selected_item->GetCurPlayer()]->IsRobot())) {
				g_turn->EndThisSliceBeginNewSlice();
			}
		} else {
			g_turn->EndThisSliceBeginNewSlice();
		}
		move = FALSE;
		break;
#endif
    case KEY_FUNCTION_ENDTURN: 
#ifdef _PLAYTEST
        if (g_selected_item->GetCurPlayer() != g_selected_item->GetVisiblePlayer()) 
           break; 

		if(g_network.IsActive()) {
			g_turn->NetworkEndTurn();
		} else {
            g_selected_item->Deselect(g_selected_item->GetCurPlayer());

			

			
			NewTurnCount::StartNextPlayer(true);

 			
          	
            
            
			

			
			
            
            

			g_tiledMap->InvalidateMix();
			g_tiledMap->InvalidateMap();
			g_tiledMap->Refresh();
			g_radarMap->Update();
			g_turn->InformMessages();
		}
		move = FALSE;
        break;
#endif
    
    case KEY_FUNCTION_NEXT_ROUND:   

		
		
		if(g_modalMessage) {
			Message *msg = g_modalMessage->GetMessage();
			if(g_theMessagePool->IsValid(*msg)) {
				Assert(msg->IsAlertBox());
				MessageData *data = msg->AccessData();
				if(data->GetNumButtons() <= 2 && data->GetNumButtons() > 0) {
					data->GetButton(0)->Callback();
				}
			}	
		} else if(g_utilityTextMessage) {
			g_utilityTextMessage->m_callback(FALSE);
			g_utilityTextMessage->RemoveWindow();
		} else {
			
			
			if(g_selected_item->GetVisiblePlayer() == g_selected_item->GetCurPlayer()) {
				DPRINTF(k_DBG_GAMESTATE, ("Keypress end turn, %d\n", g_selected_item->GetCurPlayer()));
				g_selected_item->RegisterManualEndTurn();
				g_director->AddEndTurn(); 
			}
			else
			{
				
				
				
			}
		}
        break; 

    case KEY_FUNCTION_SAVE_WORLD :
		if (g_civApp->IsGameLoaded() && !g_network.IsClient()) {
			g_civApp->AutoSave(g_selected_item->GetVisiblePlayer(), true);

			
			
			

			
		}
		move = FALSE ;
		break ;
        
    case KEY_FUNCTION_LOAD_WORLD :
		if (g_civApp->IsGameLoaded() && !g_network.IsActive()) {
			{
				g_civApp->PostLoadQuickSaveAction(g_selected_item->GetVisiblePlayer());
				
				
				
				
				
			}
			move = FALSE ;
		}
		break ;

    case KEY_FUNCTION_QUIT:
		optionwarningscreen_displayMyWindow(OWS_QUIT);


        return 1;
        break;

#ifdef _PLAYTEST
    case KEY_FUNCTION_GAMESTATE_DEBUG:
        g_theWorld->GamestateDebug();
        for (i=0; i<2; i++) { 
            g_player[i]->GamestateDebug(); 
        }
        return TRUE; 
		break;
#endif
	
    case KEY_FUNCTION_GROUP_ARMY:
	{
		Army a;
		if(g_selected_item->GetSelectedArmy(a)) {
			if(g_network.IsClient()) 
            {
				CellUnitList units;
				Cell *cell = g_theWorld->GetCell(a->RetPos());
				for (sint32 i = 0; i < cell->GetNumUnits(); i++) {
					if(cell->AccessUnit(i).GetArmy().m_id != a.m_id) {
						units.Insert(cell->AccessUnit(i));
					}
				}
				if(units.Num() > 0) {
					g_network.SendGroupRequest(units, a);
				}
			} else {
				g_gevManager->AddEvent(GEV_INSERT_Tail, GEV_GroupOrder,
									   GEA_Army, a.m_id,
									   GEA_End);
			}
		}	

		return TRUE;
	}
	break;
	case KEY_FUNCTION_UNGROUP_ARMY:	
	{	
		Army a;
		if(g_selected_item->GetSelectedArmy(a)) {
			if(g_network.IsClient()) {
				g_network.SendUngroupRequest(a, *a.AccessData());
			} else {
				g_gevManager->AddEvent(GEV_INSERT_Tail, GEV_UngroupOrder,
									   GEA_Army, a.m_id,
									   GEA_End);
			}
		}
		

		return TRUE; 
	}
	break;
	case KEY_FUNCTION_PROCESS_UNIT_ORDERS:
		if(isMyTurn) {
			g_gevManager->Pause();
			for 
            (
                sint32 i = 0; 
                i < g_player[g_selected_item->GetVisiblePlayer()]->m_all_armies->Num(); 
                i++
            ) 
            {
				g_gevManager->AddEvent(GEV_INSERT_Tail, GEV_BeginTurnExecute,
									   GEA_Army, g_player[g_selected_item->GetVisiblePlayer()]->m_all_armies->Access(i),
									   GEA_End);
			}
			g_gevManager->Resume();
			
		}
		break;
	case KEY_FUNCTION_EXECUTE_ORDERS:
		if(isMyTurn)
		{
			PLAYER_INDEX s_player; 
			ID s_item; 
			SELECT_TYPE s_state; 
			g_selected_item->GetTopCurItem(s_player, s_item, s_state);
			Army army(s_item);
			if (s_state == SELECT_TYPE_LOCAL_ARMY && army.IsValid())
            {
				army.ExecuteOrders();
			}
		}
		break;

#if defined(CTP1_HAS_RISEN_FROM_THE_GRAVE)
	case KEY_FUNCTION_TOGGLE_SPACE:
	{
		if(!g_network.IsActive()) {
			extern sint32 g_fog_toggle;
			g_fog_toggle = !g_fog_toggle;
			void WhackScreen();
			WhackScreen();
		}
		break;
	}
#endif

	case KEY_FUNCTION_TOGGLE_CITY_NAMES:
		g_theProfileDB->SetShowCityNames(!g_theProfileDB->GetShowCityNames());
		break;

	case KEY_FUNCTION_TOGGLE_TRADE_ROUTES:
		g_theProfileDB->SetShowTradeRoutes(!g_theProfileDB->GetShowTradeRoutes());
		break;
//#if 0
//	case KEY_FUNCTION_TOGGLE_ARMY_NAMES: //emod
//		g_theProfileDB->SetShowArmyNames(!g_theProfileDB->GetShowArmyNames());
//		break;
//#endif

#ifdef _DEBUG
#if 0
	case KEY_FUNCTION_CRC:
		if(g_debugOwner != k_DEBUG_OWNER_CRC) {
            if (!g_dataCheck) { 
                g_dataCheck = new DataCheck();
            }
			g_debugOwner = k_DEBUG_OWNER_CRC;
			g_dataCheck->BeginTurn();
			g_dataCheck->SetDisplay(1);
		} else {
			g_debugOwner = k_DEBUG_OWNER_NONE;
		}
		break;	
#endif
#endif
	case KEY_FUNCTION_HELP_MODE_TOGGLE:
		break;

	case KEY_FUNCTION_CHAT_KEY:
		if (g_chatBox) 
        {
			g_chatBox->SetActive(!g_chatBox->IsActive());
		}
		break;

	case KEY_FUNCTION_UNIT_CITY_TOGGLE:
		g_selected_item->UnitCityToggle();
		break;
	case KEY_FUNCTION_END_UNIT_TURN:
		g_selected_item->EndUnitTurn();
		break;

	case KEY_FUNCTION_NETWORK_PLAYERS_SCREEN:
		if ( !g_networkPlayersScreen ) {
			g_networkPlayersScreen = new c3_UtilityPlayerListPopup((c3_UtilityPlayerListCallback *)network_PlayerListCallback);
		}
		g_networkPlayersScreen->DisplayWindow();
		if ( g_network.IsHost() ) {
			g_networkPlayersScreen->EnableButtons();
		}
		else if ( g_network.IsClient() ) {		
			g_networkPlayersScreen->DisableButtons();
		}
		
		break;
	case KEY_FUNCTION_CIV_TAB:
		if(g_controlPanel) {
			g_controlPanel->SetTab(CP_TAB_CIV);
		}
		break;
	case KEY_FUNCTION_MSG_TAB:
		if(g_controlPanel) {
			g_controlPanel->SetTab(CP_TAB_MSGLOG);
		}
		break;
	case KEY_FUNCTION_CITY_TAB:
		if(g_controlPanel) {
			g_controlPanel->SetTab(CP_TAB_CITY);
		}
		break;
	case KEY_FUNCTION_UNIT_TAB:
		if(g_controlPanel) {
			g_controlPanel->SetTab(CP_TAB_UNIT);
		}
		break;
	case KEY_FUNCTION_TILE_TAB:
		if(g_controlPanel) {
			g_controlPanel->SetTab(CP_TAB_TILEIMP);
		}
		break;
		
	case KEY_FUNCTION_CONTROL_NEXT:
#if 0
		if(g_controlPanel) {

			if(g_cp_productionTab && 
			   (g_cp_productionTab->GetMode() == PRODTAB_MODE_CHANGE ||
				g_cp_productionTab->GetMode() == PRODTAB_MODE_QUEUE)) {
				c3_ListBox *plist = g_cp_productionTab->GetPurchaseList();
				if(plist && plist->NumItems() > 0) {
					sint32 curIndex = plist->GetSelectedItemIndex();
					if(curIndex >= plist->NumItems() - 1) {
						curIndex = -1;
					}
					plist->SelectItem(curIndex + 1);
					plist->GetVerticalRanger()->SetValue(0, curIndex + 1 - 2);
				}
			}
		}
#endif
		break;
	case KEY_FUNCTION_CONTROL_PREV:
#if 0
		if(g_controlPanel) {

			if(g_cp_productionTab && 
			   (g_cp_productionTab->GetMode() == PRODTAB_MODE_CHANGE ||
				g_cp_productionTab->GetMode() == PRODTAB_MODE_QUEUE)) {
				c3_ListBox *plist = g_cp_productionTab->GetPurchaseList();
				if(plist && plist->NumItems() > 0) {
					sint32 curIndex = plist->GetSelectedItemIndex();
					if(curIndex <= 0) {
						curIndex = plist->NumItems();
					}
					plist->SelectItem(curIndex - 1);
					plist->GetVerticalRanger()->SetValue(0, curIndex - 1 - 2);
				}
			}
		}
#endif
		break;
	case KEY_FUNCTION_CLOSE:		
		if(g_currentMessageWindow) {
			if(g_theMessagePool->IsValid(*g_currentMessageWindow->GetMessage())) {
				g_currentMessageWindow->GetMessage()->Kill();
			}
		} else if(g_modalMessage) {
			Message *msg = g_modalMessage->GetMessage();
			if(g_theMessagePool->IsValid(*msg)) {
				Assert(msg->IsAlertBox());
				MessageData *data = msg->AccessData();
				if(data->GetNumButtons() <= 2 && data->GetNumButtons() > 0) {
					data->GetButton(0)->Callback();
				}
			}	
		}

		break;
	case KEY_FUNCTION_YES:
	{
		if(g_modalMessage) {
			Message *msg = g_modalMessage->GetMessage();
			if(g_theMessagePool->IsValid(*msg)) {
				Assert(msg->IsAlertBox());
				MessageData *data = msg->AccessData();
				if(data->GetNumButtons() == 2) {
					data->GetButton(1)->Callback();
				}
			}
		} else if(g_utilityTextMessage) {
			g_utilityTextMessage->m_callback(TRUE);
			g_utilityTextMessage->RemoveWindow();
		}
		break;
	}
	case KEY_FUNCTION_NO:
	{
		if(g_modalMessage) {
			Message *msg = g_modalMessage->GetMessage();
			if(g_theMessagePool->IsValid(*msg)) {
				Assert(msg->IsAlertBox());
				MessageData *data = msg->AccessData();
				if(data->GetNumButtons() == 2) {
					data->GetButton(0)->Callback();
				}
			}
		} else if(g_utilityTextMessage) {
			g_utilityTextMessage->m_callback(FALSE);
			g_utilityTextMessage->RemoveWindow();
		}
		break;
	}
	case KEY_FUNCTION_CLEAR_QUEUE:
		if(g_controlPanel 

			) {
			Unit city;
			if(g_selected_item->GetSelectedCity(city)) {
				city.GetData()->GetCityData()->GetBuildQueue()->Clear();
#if 0
				if(g_cp_productionTab) {
					g_cp_productionTab->LoadCityData(city);
					g_cp_productionTab->FillQueueList(city);
				}
#endif
			}
		}
		break;
	case KEY_FUNCTION_OPEN_MESSAGE: 
		{
			
			
			extern sint32 g_modalWindow;
			if (g_modalWindow == 0) {
				if(g_currentMessageWindow) {
					if(g_currentMessageWindow->GetMinimizeAction()) {
						g_currentMessageWindow->GetMinimizeAction()->Execute(NULL,
																		   AUI_BUTTON_ACTION_EXECUTE,
																		   0);
					}
				} else if(g_selected_item) {
					sint32 visPlayer = g_selected_item->GetVisiblePlayer();
					
					if(g_player[visPlayer] && g_player[visPlayer]->m_messages->Num() > 0) {
						sint32 m;
						for(m = 0; m < g_player[visPlayer]->m_messages->Num(); m++) {
							if(!g_player[visPlayer]->m_messages->Access(m).IsRead()) {
								g_player[visPlayer]->m_messages->Access(m).Show();
								break;
							}
						}
					}
				}
			}
		}
		break;
	case KEY_FUNCTION_EXECUTE_EYEPOINT:
		{
			
			if(g_currentMessageWindow) {
				if(g_theMessagePool->IsValid(*g_currentMessageWindow->GetMessage())) {
					g_currentMessageWindow->GetMessage()->AccessData()->EyePointCallback(0);
				}
			}
			break;
		}
	case KEY_FUNCTION_MOVE_ORDER:
		g_controlPanel->BeginOrderDelivery(g_selected_item->GetMoveOrder());
		break;

	case KEY_FUNCTION_TOGGLE_RADAR:
		radarwindow_Toggle();
		break;

	case KEY_FUNCTION_TOGGLE_CONTROL_PANEL:
		g_controlPanel->Toggle();
		break;

	case KEY_FUNCTION_TOGGLE_ALL:
		if(!g_c3ui->GetWindow(g_controlPanel->GetWindow()->Id())) {
			g_c3ui->AddWindow(g_controlPanel->GetWindow());
			radarwindow_Show();
		} else {
			g_c3ui->RemoveWindow(g_controlPanel->GetWindow()->Id());
			radarwindow_Hide();
		}
		break;

	
	case KEY_FUNCTION_TRADE_SUMMARY:    
		if (!g_modalWindow) {
			close_AllScreens();
			TradeManager::Display();
			TradeManager::SetMode(TRADE_MANAGER_SUMMARY);
		}
		break;

	case KEY_FUNCTION_GAIA:
		if(!g_modalWindow) {
			close_AllScreens();
			ScienceVictoryDialog::Open();
		}
		break;

	case KEY_FUNCTION_BUILD_QUEUE:
	{
		if(!g_modalWindow && g_player[g_selected_item->GetVisiblePlayer()]) {
			Unit city;
			if(g_selected_item->GetSelectedCity(city)) {
				city = g_theWorld->GetCity(g_selected_item->GetCurSelectPos());
			} else if(g_player[g_selected_item->GetVisiblePlayer()]->GetNumCities()) {
				city = g_player[g_selected_item->GetVisiblePlayer()]->m_all_cities->Access(0);
			}
				if(city.IsValid()) {
					close_AllScreens();
					EditQueue::Display(CityWindow::GetCityData(city));
				}
		} 
		break;
	}		
	case KEY_FUNCTION_CITY_MANAGEMENT:
		if(!g_modalWindow && g_player[g_selected_item->GetVisiblePlayer()]) {
			close_AllScreens();
			Unit city;
			if(g_selected_item->GetSelectedCity(city)) {
				CityWindow::Display(city.GetData()->GetCityData());
			} else if(g_player[g_selected_item->GetVisiblePlayer()]->GetNumCities()) {
				city = g_player[g_selected_item->GetVisiblePlayer()]->m_all_cities->Access(0);
				g_selected_item->SetSelectCity(city);
				CityWindow::Display(city.GetData()->GetCityData());
			}
		}
		break;

	case KEY_FUNCTION_NEW_PROPOSAL:
		if(!g_modalWindow) {
			if(DipWizard::CanInitiateRightNow()) {
				DipWizard::Display();
			}
		}
		break;

	case KEY_FUNCTION_TIMELINE:
		if(!g_modalWindow) {
			InfoWindow::SelectWonderTab();
			InfoWindow::Open();
		}
		break;

	case KEY_FUNCTION_RANK:
		if(!g_modalWindow) {
			InfoWindow::SelectRankingTab();
			InfoWindow::Open();
		}
		break;
	
	case KEY_FUNCTION_RESTART:
		//Added by Martin Gühmann to disable also the restart key in network
		//games, hot seat games and email games.
		if(!g_modalWindow 
		&& !g_theProfileDB->IsScenario() 
		&& !g_isScenario
		&& !g_network.IsActive()
		&& !g_turn->IsHotSeat() 
		&& !g_turn->IsEmail()
		) {
			optionwarningscreen_displayMyWindow(OWS_RESTART) ;
		}
		break;

	case KEY_FUNCTION_NEW_GAME:
		if(!g_modalWindow) {

			optionwarningscreen_displayMyWindow(OWS_QUITTOSHELL);	
		}
		break;

	case KEY_FUNCTION_SOUND_OPTIONS:
		if(!g_modalWindow) {
			soundscreen_displayMyWindow();
		}
		break;
		
	// MUSIC added by ahenobarb
	case KEY_FUNCTION_MUSIC_OPTIONS:
		if(!g_modalWindow) {
			musicscreen_displayMyWindow();
		}
		break;
		
	case KEY_FUNCTION_GRAPHICS_OPTIONS:
		if(!g_modalWindow) {
			graphicsscreen_displayMyWindow();
		}
		break;

	case KEY_FUNCTION_GAMEPLAY_OPTIONS:
		if(!g_modalWindow) {
			gameplayoptions_displayMyWindow();
		}
		break;
	case KEY_FUNCTION_ADVANCED_OPTIONS:
		if(!g_modalWindow) {
			ProfileEdit::Display();
		}
		break;
	default :
        Assert(FALSE); 
    }
    
    if (move && isMyTurn) {
		
		PLAYER_INDEX s_player; 
		ID s_item; 
		SELECT_TYPE s_state; 
        
		g_selected_item->GetTopCurItem(s_player, s_item, s_state);
		
		switch(s_state) { 
			case SELECT_TYPE_LOCAL_ARMY:
			{
				Army army(s_item);
				MapPoint pos;
				army.GetPos(pos);
				MapPoint newpos;

				if(pos.GetNeighborPosition(d, newpos)) {
					g_gevManager->AddEvent(GEV_INSERT_Tail, GEV_MoveToOrder,
										   GEA_Army, army.m_id,
										   GEA_Direction, d,
										   GEA_End);
					
					g_selected_item->DidKeyboardMove();
				}
				break;
			}
				
			default: 
				break; 
		}
	}

	return TRUE;
}
    bool GetAppOutput(const CommandLine& cl, std::string* output)
    {
        HANDLE out_read = NULL;
        HANDLE out_write = NULL;

        SECURITY_ATTRIBUTES sa_attr;
        // Set the bInheritHandle flag so pipe handles are inherited.
        sa_attr.nLength = sizeof(SECURITY_ATTRIBUTES);
        sa_attr.bInheritHandle = TRUE;
        sa_attr.lpSecurityDescriptor = NULL;

        // Create the pipe for the child process's STDOUT.
        if(!CreatePipe(&out_read, &out_write, &sa_attr, 0))
        {
            NOTREACHED() << "Failed to create pipe";
            return false;
        }

        // Ensure we don't leak the handles.
        win::ScopedHandle scoped_out_read(out_read);
        win::ScopedHandle scoped_out_write(out_write);

        // Ensure the read handle to the pipe for STDOUT is not inherited.
        if(!SetHandleInformation(out_read, HANDLE_FLAG_INHERIT, 0))
        {
            NOTREACHED() << "Failed to disabled pipe inheritance";
            return false;
        }

        std::wstring writable_command_line_string(cl.GetCommandLineString());

        // Now create the child process
        PROCESS_INFORMATION proc_info = { 0 };
        STARTUPINFO start_info = { 0 };

        start_info.cb = sizeof(STARTUPINFO);
        start_info.hStdOutput = out_write;
        // Keep the normal stdin and stderr.
        start_info.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
        start_info.hStdError = GetStdHandle(STD_ERROR_HANDLE);
        start_info.dwFlags |= STARTF_USESTDHANDLES;

        // Create the child process.
        if(!CreateProcess(NULL,
            &writable_command_line_string[0],
            NULL, NULL,
            TRUE, // Handles are inherited.
            0, NULL, NULL, &start_info, &proc_info))
        {
            NOTREACHED() << "Failed to start process";
            return false;
        }

        // We don't need the thread handle, close it now.
        CloseHandle(proc_info.hThread);

        // Close our writing end of pipe now. Otherwise later read would not be able
        // to detect end of child's output.
        scoped_out_write.Close();

        // Read output from the child process's pipe for STDOUT
        const int kBufferSize = 1024;
        char buffer[kBufferSize];

        for(;;)
        {
            DWORD bytes_read = 0;
            BOOL success = ReadFile(out_read, buffer, kBufferSize,
                &bytes_read, NULL);
            if(!success || bytes_read==0)
            {
                break;
            }
            output->append(buffer, bytes_read);
        }

        // Let's wait for the process to finish.
        WaitForSingleObject(proc_info.hProcess, INFINITE);
        CloseHandle(proc_info.hProcess);

        return true;
    }
int
main(int argc, char* argv[])
{
  // Setting default parameters for PointToPoint links and channels
  Config::SetDefault("ns3::PointToPointNetDevice::DataRate", StringValue("1Mbps"));
  Config::SetDefault("ns3::PointToPointChannel::Delay", StringValue("10ms"));
  Config::SetDefault("ns3::QueueBase::MaxPackets", UintegerValue(10));

  // Read optional command-line parameters (e.g., enable visualizer with ./waf --run=<> --visualize
  CommandLine cmd;
  cmd.Parse(argc, argv);

  // Creating 3x3 topology
  PointToPointHelper p2p;
  PointToPointGridHelper grid(3, 3, p2p);
  grid.BoundingBox(100, 100, 200, 200);

  // Install NDN stack on all nodes
  StackHelper ndnHelper;
  ndnHelper.InstallAll();

  // Installing global routing interface on all nodes
  GlobalRoutingHelper ndnGlobalRoutingHelper;
  ndnGlobalRoutingHelper.InstallAll();

  // Getting containers for the consumer/producer
  Ptr<Node> producer = grid.GetNode(2, 2);
  NodeContainer consumerNodes;
  consumerNodes.Add(grid.GetNode(0, 0));

  // Install NDN applications
  std::string prefix = "/prefix";

  // Install different forwarding strategies
  for (int row = 0; row < 3; row++) {
    for (int column = 0; column < 3; column++) {
      if (row < 2)
        StrategyChoiceHelper::Install(grid.GetNode(row, column), "/prefix",
                                      "/localhost/nfd/strategy/best-route");
      else
        StrategyChoiceHelper::Install(grid.GetNode(row, column), "/prefix",
                                      "/localhost/nfd/strategy/multicast");
    }
  }

  AppHelper consumerHelper("ns3::ndn::ConsumerCbr");
  consumerHelper.SetPrefix(prefix);
  consumerHelper.SetAttribute("Frequency", StringValue("100")); // 100 interests a second
  consumerHelper.Install(consumerNodes);

  AppHelper producerHelper("ns3::ndn::Producer");
  producerHelper.SetPrefix(prefix);
  producerHelper.SetAttribute("PayloadSize", StringValue("1024"));
  producerHelper.Install(producer);

  // Add /prefix origins to ndn::GlobalRouter
  ndnGlobalRoutingHelper.AddOrigins(prefix, producer);

  // Calculate and install FIBs
  GlobalRoutingHelper::CalculateRoutes();

  Simulator::Stop(Seconds(20.0));
  Simulator::Run();
  Simulator::Destroy();

  return 0;
}
    inline Clara::CommandLine<ConfigData> makeCommandLineParser() {

        using namespace Clara;
        CommandLine<ConfigData> cli;

        cli.bindProcessName( &ConfigData::processName );

        cli["-?"]["-h"]["--help"]
            .describe( "display usage information" )
            .bind( &ConfigData::showHelp );

        cli["-l"]["--list-tests"]
            .describe( "list all/matching test cases" )
            .bind( &ConfigData::listTests );

        cli["-t"]["--list-tags"]
            .describe( "list all/matching tags" )
            .bind( &ConfigData::listTags );

        cli["-s"]["--success"]
            .describe( "include successful tests in output" )
            .bind( &ConfigData::showSuccessfulTests );

        cli["-b"]["--break"]
            .describe( "break into debugger on failure" )
            .bind( &ConfigData::shouldDebugBreak );

        cli["-e"]["--nothrow"]
            .describe( "skip exception tests" )
            .bind( &ConfigData::noThrow );

        cli["-i"]["--invisibles"]
            .describe( "show invisibles (tabs, newlines)" )
            .bind( &ConfigData::showInvisibles );

        cli["-o"]["--out"]
            .describe( "output filename" )
            .bind( &ConfigData::outputFilename, "filename" );

        cli["-r"]["--reporter"]
//            .placeholder( "name[:filename]" )
            .describe( "reporter to use (defaults to console)" )
            .bind( &ConfigData::reporterName, "name" );

        cli["-n"]["--name"]
            .describe( "suite name" )
            .bind( &ConfigData::name, "name" );

        cli["-a"]["--abort"]
            .describe( "abort at first failure" )
            .bind( &abortAfterFirst );

        cli["-x"]["--abortx"]
            .describe( "abort after x failures" )
            .bind( &abortAfterX, "no. failures" );

        cli["-w"]["--warn"]
            .describe( "enable warnings" )
            .bind( &addWarning, "warning name" );

// - needs updating if reinstated
//        cli.into( &setVerbosity )
//            .describe( "level of verbosity (0=no output)" )
//            .shortOpt( "v")
//            .longOpt( "verbosity" )
//            .placeholder( "level" );

        cli[_]
            .describe( "which test or tests to use" )
            .bind( &addTestOrTags, "test name, pattern or tags" );

        cli["-d"]["--durations"]
            .describe( "show test durations" )
            .bind( &setShowDurations, "yes/no" );

        cli["-f"]["--input-file"]
            .describe( "load test names to run from a file" )
            .bind( &loadTestNamesFromFile, "filename" );

        // Less common commands which don't have a short form
        cli["--list-test-names-only"]
            .describe( "list all/matching test cases names only" )
            .bind( &ConfigData::listTestNamesOnly );

        cli["--list-reporters"] 
            .describe( "list all reporters" )
            .bind( &ConfigData::listReporters );

        cli["--order"]
            .describe( "test case order (defaults to decl)" )
            .bind( &setOrder, "decl|lex|rand" );

        cli["--rng-seed"]
            .describe( "set a specific seed for random numbers" )
            .bind( &setRngSeed, "'time'|number" );

        cli["--force-colour"]
            .describe( "force colourised output" )
            .bind( &ConfigData::forceColour );

        return cli;
    }
int
main(int argc, char* argv[])
{
  // setting default parameters for PointToPoint links and channels
  Config::SetDefault("ns3::PointToPointNetDevice::DataRate", StringValue("10Mbps"));
  Config::SetDefault("ns3::PointToPointChannel::Delay", StringValue("10ms"));
  Config::SetDefault("ns3::DropTailQueue::MaxPackets", StringValue("20"));

  // Read optional command-line parameters (e.g., enable visualizer with ./waf --run=<> --visualize
  CommandLine cmd;
  cmd.Parse(argc, argv);

  // Creating nodes
  NodeContainer nodes;
  nodes.Create(3); // 3 nodes, connected: 0 <---> 1 <---> 2

  // Connecting nodes using two links
  PointToPointHelper p2p;
  p2p.Install(nodes.Get(0), nodes.Get(1));
  p2p.Install(nodes.Get(1), nodes.Get(2));

  // Install NDN stack on all nodes
  ndn::StackHelper ndnHelper;
  ndnHelper.SetDefaultRoutes(true);
  ndnHelper.setCsSize(0);
  ndnHelper.SetOldContentStore("ns3::ndn::cs::Lru", "MaxSize", "100");
  ndnHelper.InstallAll();

  // Choosing forwarding strategy
  ndn::StrategyChoiceHelper::InstallAll("/myprefix", "/localhost/nfd/strategy/best-route");

  // Installing multimedia consumer
  ns3::ndn::AppHelper consumerHelper("ns3::ndn::FileConsumerCbr::MultimediaConsumer");
  consumerHelper.SetAttribute("AllowUpscale", BooleanValue(true));
  consumerHelper.SetAttribute("AllowDownscale", BooleanValue(false));
  consumerHelper.SetAttribute("ScreenWidth", UintegerValue(1920));
  consumerHelper.SetAttribute("ScreenHeight", UintegerValue(1080));
  consumerHelper.SetAttribute("StartRepresentationId", StringValue("auto"));
  consumerHelper.SetAttribute("MaxBufferedSeconds", UintegerValue(30));
  consumerHelper.SetAttribute("StartUpDelay", StringValue("0.1"));

  consumerHelper.SetAttribute("AdaptationLogic", StringValue("dash::player::SVCBufferBasedAdaptationLogic"));
  consumerHelper.SetAttribute("MpdFileToRequest", StringValue(std::string("/myprefix/SVC/BBB-III.mpd" )));

  ApplicationContainer app1 = consumerHelper.Install (nodes.Get(2));

   // Producer
  ndn::AppHelper producerHelper("ns3::ndn::FileServer");

  // Producer will reply to all requests starting with /myprefix
  producerHelper.SetPrefix("/myprefix");
  producerHelper.SetAttribute("ContentDirectory", StringValue("/home/someuser/multimediaData"));
  producerHelper.Install(nodes.Get(0)); // install to some node from nodelist

  ndn::GlobalRoutingHelper ndnGlobalRoutingHelper;
  ndnGlobalRoutingHelper.InstallAll();

  ndnGlobalRoutingHelper.AddOrigins("/myprefix", nodes.Get(0));
  ndn::GlobalRoutingHelper::CalculateRoutes();

  Simulator::Stop(Seconds(1200.0));

  ndn::DASHPlayerTracer::InstallAll("dash-output.txt");
  ndn::CsTracer::InstallAll("cs-trace.txt", Seconds(1));

  Simulator::Run();
  Simulator::Destroy();

  NS_LOG_UNCOND("Simulation Finished.");

  return 0;
}
Exemple #22
0
int Shell::Exec(const std::string& buf, Client* client, Server* server){
	CommandLine cmd;
	if(cmd.Parse(buf, command_num) < 0) return -1;
	return _Exec(cmd, client, server);
}
Exemple #23
0
int main(int argc, char *argv[]) {
	CommandLine cl;
	cl.addArgument("-i", "input", "Input points", true);
	cl.addArgument("-d", "2", "Number of dimensions", true);
	bool hasArguments = cl.processArgs(argc, argv);
	if(!hasArguments) {
		fprintf(stderr, "Missing arguments\n");
		fprintf(stderr, "Usage:\n\n");
		cl.showUsage();
		exit(1);
	}

  const char *src = cl.getArgString("-i").c_str();
  int dims = cl.getArgInt("-d");
	
	vector<float> inpoints;
	readPoints(src, inpoints, dims);
  int numPts = (int) inpoints.size()/dims;

	
	// Write input for qdelaunay
	FILE *fp = fopen("temp.qhull", "w");
	fprintf(fp, "%d\n", dims);
	fprintf(fp, "%d\n", numPts);
	
	for(unsigned int i=0;i<numPts;i++) {
		for(int d = 0;d<dims;d++) {
			fprintf(fp, "%g ", inpoints[dims*i+d]);
		}
		fprintf(fp, "\n");
	}
	fclose(fp);	

	timestamp t1 = now();
	char cmd[1024];
	sprintf(cmd, "%s/qdelaunay Qt i TO temp.out < temp.qhull", QDELAUNAY_PATH);
	system(cmd);
	timestamp t2 = now();
	fprintf(stderr,"Ellapsed %f\n", t2-t1);
	 
	
	// Read output of qdelaunay
	FILE *fpin = fopen("temp.out","r");
	int numTris;
	fscanf(fpin,"%d", &numTris);
	
	bool **edges = new bool*[numPts];
	for(int i=0;i<numPts;i++) {
		edges[i] = new bool[numPts];
		for(int j=0;j<numPts;j++) {
			edges[i][j] = false;
		}
	}
	
	// Output each edge from qdelaunay output
	int D = dims;
	for(int i=0;i<numTris;i++) {
		int simplex[D+1];
		for(int d=0;d<D+1;d++) {
			fscanf(fpin,"%d", &(simplex[d]));
		}
		for(int d=0;d<D+1;d++) {
			for(int d2=d+1;d2<D+1;d2++) {
				int i1 = simplex[d];
				int i2 = simplex[d2];
				if(!edges[i1][i2] && !edges[i2][i1]) {
					edges[i1][i2] = true;
					edges[i2][i1] = true;
					fprintf(stdout, "%d %d\n", i1, i2);
				}
			}
		}
	}
	fclose(fpin);
	delete[] edges;
}
Exemple #24
0
int Shell::ExecCommand(const CommandLine& cmd, Client* client, Server* server){
	int pid, pgid = 0;
    setenv("PATH", client->shell->env["PATH"].c_str(), 1);
	for(int i=0;i<(int)cmd.size();i++){
		Command c = cmd[i];
		Pipe pipe_in, pipe_out, pipe_err, global_pipe_in, global_pipe_out;;
		pipe_in = pipe_set[cmd.command_num][i];
		if(c.pipe_stdout != NON_PIPE)pipe_out = pipe_set[c.pipe_stdout.first][c.pipe_stdout.second];
		if(c.pipe_stderr != NON_PIPE)pipe_err = pipe_set[c.pipe_stderr.first][c.pipe_stderr.second];
        if(c.global_pipe_stdin != -1)global_pipe_in = server->global_pipe[c.global_pipe_stdin];
        if(c.global_pipe_stdout != -1)global_pipe_in = server->global_pipe[c.global_pipe_stdout];
		if((pid=fork()) == 0){
			if(dup2(pipe_in[0], 0) == -1)perror("dup2 stdin");
			if(c.pipe_stdout != NON_PIPE){
				if(dup2(pipe_out[1], STDOUT_FILENO) == -1)
					perror("dup2 stdout");
			}
			if(c.pipe_stderr != NON_PIPE){
				if(dup2(pipe_err[1], STDERR_FILENO) == -1)
					perror("dup2 stderr");
			}
            if(c.global_pipe_stdin != -1){
                auto& p = server->global_pipe[c.global_pipe_stdin];
                if(dup2(p[0], STDIN_FILENO) == -1)
                    perror("global pipe stdin error");
                char msg[256];
                sprintf(msg, "*** %s (#%d) just received via \'%s\' ***\n", client->nickname.c_str(), client->id, cmd.origin.c_str());
                server->SendAll(msg);
                server->global_pipe.Destruct(c.global_pipe_stdin);
            }
            if(c.global_pipe_stdout != -1){
                auto& p = server->global_pipe[c.global_pipe_stdout];
                if(dup2(p[1], STDOUT_FILENO) == -1)
                    perror("global pipe stdout error");
                char msg[256];
                sprintf(msg, "*** %s (#%d) just piped '%s' ***\n", client->nickname.c_str(), client->id, cmd.origin.c_str());
                server->SendAll(msg);
                server->global_pipe.Destruct(c.global_pipe_stdout);
            }
			if(i == (int)cmd.size() - 1 && cmd.filename != ""){
				int fd = open(cmd.filename.c_str(), O_WRONLY|O_CREAT, 0660);
				if(dup2(fd, STDOUT_FILENO) == -1)
					perror("file redirect");
				close(fd);
			}
			for(int i=0;i<(int)cmd.size();i++){
				Command c = cmd[i];
				if(pipe_set.Find(cmd.command_num, i))
                    pipe_set.Destruct(cmd.command_num, i);
				if(c.pipe_stdout != NON_PIPE && i != cmd.size()-1)
					pipe_set.Destruct(c.pipe_stdout.first, c.pipe_stdout.second);
				if(c.pipe_stderr != NON_PIPE && i != cmd.size()-1)
					pipe_set.Destruct(c.pipe_stderr.first, c.pipe_stderr.second);
			}
			MyExec(c);
		}else if(pid > 0){
			setpgid(pid, pgid);
			if(i == 0) pgid = pid;
            pipe_set.Destruct(cmd.command_num, i);
            if(c.global_pipe_stdin != -1)
                server->global_pipe.Destruct(c.global_pipe_stdin);
		}else{
		}
	}
	for(int i=0;i<(int)cmd.size();i++){
		Command c = cmd[i];
		if(pipe_set.Find(cmd.command_num, i))pipe_set.Destruct(cmd.command_num, i);
		if(c.pipe_stdout != NON_PIPE && i != cmd.size()-1)
			pipe_set.Destruct(c.pipe_stdout.first, c.pipe_stdout.second);
		if(c.pipe_stderr != NON_PIPE && i != cmd.size()-1)
			pipe_set.Destruct(c.pipe_stderr.first, c.pipe_stderr.second);
	}
	for(int i=0;i<(int)cmd.size();i++)
		waitpid(-pgid, NULL, 0);
}
int run()
{
    int sockfd, new_fd;  // listen on sock_fd, new connection on new_fd
    struct addrinfo hints, *servinfo, *p;
    struct sockaddr_storage their_addr; // connector's address information
    socklen_t sin_size;
    struct sigaction sa;
    int yes=1;
    char s[INET6_ADDRSTRLEN];
    int rv,numbytes;
    char inputBuffer[400];
    CommandLine cl;
    FileUtil util;


    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE; // use my IP

    if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
        return 1;
    }

    // loop through all the results and bind to the first we can
    for(p = servinfo; p != NULL; p = p->ai_next) {
        if ((sockfd = socket(p->ai_family, p->ai_socktype,
                p->ai_protocol)) == -1) {
            perror("server: socket");
            continue;
        }

        if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes,
                sizeof(int)) == -1) {
            perror("setsockopt");
            exit(1);
        }

        if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
            close(sockfd);
            perror("server: bind");
            continue;
        }

        break;
    }

    if (p == NULL)  {
        fprintf(stderr, "server: failed to bind\n");
        return 2;
    }

    freeaddrinfo(servinfo); // all done with this structure

    if (listen(sockfd, BACKLOG) == -1) {
        perror("listen");
        exit(1);
    }

    sa.sa_handler = sigchld_handler; // reap all dead processes
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;
    if (sigaction(SIGCHLD, &sa, NULL) == -1) {
        perror("sigaction");
        exit(1);
    }

    printf("server: waiting for connections...\n");

    while(1) {  // main accept() loop
        sin_size = sizeof their_addr;
        new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
        if (new_fd == -1) {
            perror("accept");
            continue;
        }
        //


        numbytes = recv(new_fd, inputBuffer, sizeof inputBuffer, 0);
        inputBuffer[numbytes] = '\0';
        std::string inpbf(inputBuffer);

        //printf("input received:%d  and %s \n",numbytes,inputBuffer);
        //printf("input is:%s \n",inputBuffer[0]);

        std::string inputdata=" ";

        //cout<<"input:"<<inpbf<<endl;

        string::const_iterator start, end;
        boost::match_results<std::string::const_iterator> what;
        boost::match_flag_type flags = boost::match_default;

        //get input from incoming request here
        regex expr_ref("(GET)(\\s+)(\\/)(query=)(.*?)(\\s+)");
        	start = inpbf.begin();
        	end = inpbf.end();
        	while (boost::regex_search(start, end, what, expr_ref, flags)) {
        		inputdata = what[5];
        		break;
        	}

       cout<<"input:"<<inputdata<<endl;

        //input fetch code ends

        inet_ntop(their_addr.ss_family,
            get_in_addr((struct sockaddr *)&their_addr),
            s, sizeof s);
        printf("server: got connection from %s\n", s);
        std::string op;
        std::string response;
        list<size_t> qresp;
        if(inputdata.length()>0){
        	qresp = cl.runQueryWeb(inputdata);
        	response = "data";
        }else{
        	response = "empty";
        }


        std::string html_inner_content;
        std::string html_end_content;

        std::string title = "this is title";
        std::string link = "file path is here";
        std::string description = "description should have come here";

        std::string css = "<style type=\"text/css\">ol,ul,li{border:0;margin:0;padding:0}h3,.med{font-size:medium;font-weight:400}body{color:#222}li.head,li.g,body,html,.std,.c h2,#mbEnd h2,h1{font-size:small;font-family:arial,sans-serif}li.g{margin-top:0;margin-bottom:20px}ol li{list-style:none}li{line-height:1.2}#res h3.r{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.vsc{display:inline-block;position:relative;width:100%}#ires h3,#res h3,#tads h3,#tadsb h3,#mbEnd h3{font-size:medium}.sl,.r{display:inline;font-weight:400;margin:0}.s{max-width:42em;color:#222}div{display:block}.kv,.kvs{display:block;margin-bottom:2px}.f,.f a:link,.m,.c h2,#mbEnd h2,#tads h2,#tadsb h2,#tadsto h2,.descbox{color:#666}.st,.ac{line-height:1.24}.a,cite,cite a:link,cite a:visited,.cite,.cite:link,#mbEnd cite b,#tads cite b,#tadsb cite b,#tadsto cite b,#ans > i,.bc a:link{color:#093;font-style:normal}a:link,.w,.q:active,.q:visited,.tbotu{color:#12C;cursor:pointer}</style>";


        vector<std::string> outputList;
        op="<html><head><title>Falcon Search Engine</title>" + css + "</head><body><h2>Falcon Search Engine - Team Mango</h2><form name=\"input\" action=\"http://localhost:8888\" method=\"post\" id=\"input\">Query: <input type=\"text\" id=\"queryId\" name=\"query\" value=\"query here\" /><input type=\"submit\" value=\"Submit\" /></form><ol>";


        BOOST_FOREACH(size_t t, qresp){

            html_inner_content="<li class=\"g\"><div class=\"vsc\"><h3 class=\"r\"><a href=\"#\">" + util.getStringValue(t) + "</a></h3><div class=\"s\"><div class=\"f kv\"><cite>" + cl.tutil.fileMap[util.getStringValue(t)] + "</cite></div><span class=\"st\">" + description + "</span></div></div></li>";
            op = op + html_inner_content;

        }

        op = op+ "</ol></body></html>";

        if (!fork()) { // this is the child process
            close(sockfd); // child doesn't need the listener
            if (send(new_fd,op.c_str() , op.length(), 0) == -1)
                perror("send");
            close(new_fd);
            exit(0);
        }
        close(new_fd);  // parent doesn't need this
    }
Exemple #26
0
void Connection::run()
{
    // True while the process list mutex is held.
    // This lets the exception handler know when to unlock the mutex.
    bool locked = false;
    
//    in_addr_t a = ntohl(remote_addr.sin_addr.s_addr);
//    log_printf("Received connection from %d.%d.%d.%d:%d\n", a >> 24, (a >> 16) & 255, (a >> 8) & 255, a & 255, ntohs(remote_addr.sin_port));
    
    try
    {
        // Identify ourselves
        write("Watchdog v2.0\n");
        
        while (1)
        {
            // Read a command
            CommandLine command;
            if (!read_command(command))
            {
                write("Command cancelled\n");
                continue;
            }
            
            int words = command.size();
            
            if (words == 0)
            {
                // Blank line
                continue;
            }
            
#if 0
            printf("%d words:\n", words);
            for (Command::const_iterator i = command.begin(); i != command.end(); ++i)
            {
                printf("    \"%s\"\n", (*i).c_str());
            }
#endif
            
            // Find a handler for this command
            for (int i = 0; command_table[i].command; i++)
            {
                // Check the command name
                if (command[0] == command_table[i].command)
                {
                    // Check the number of words
                    if (command_table[i].words > 0 && words != command_table[i].words)
                    {
                        write("Wrong number of parameters\n");
                        goto next_command;
                    }
                    
                    Process::lock();
                    locked = true;
                    
                    // Check the process name if required by the table
                    Process *process = 0;
                    if (command_table[i].check_process)
                    {
                        // If a process name is given, try to find it.
                        //
                        // This test handles the case where the table
                        // requires zero words but check_process is true.
                        if (words > 1)
                        {
                            process = Process::find(command[1]);
                        }
                        
                        if (!process)
                        {
                            Process::unlock();
                            locked = false;
                            
                            write("No such process\n");
                            goto next_command;
                        }
                    }
                    
                    // Call the handler
                    if (command_table[i].handler)
                    {
                        if ((this->*command_table[i].handler)(command, process))
                        {
                            write("OK\n");
                        }
                    } else {
                        write("Unimplemented command\n");
                    }
                    
                    Process::unlock();
                    locked = false;

                    goto next_command;
                }
            }
            write("Unrecognized command\n");

next_command: ;
        }
    } catch (connection_closed)
    {
    } catch (std::exception &ex)
    {
        log_printf("Connection::run() exception: %s\n", ex.what());
    }

    // Unlock the process list in case an exception was thrown while it was locked.
    if (locked)
    {
        Process::unlock();
    }

//    log_printf("Closed connection from %d.%d.%d.%d:%d\n", a >> 24, (a >> 16) & 255, (a >> 8) & 255, a & 255, ntohs(remote_addr.sin_port));
    close(conn_socket);
}
int main (int argc, char *argv[])
{
  std::string phyMode ("DsssRate1Mbps");
  double distance = 500;  // m
  uint32_t packetSize = 1000; // bytes
  uint32_t numPackets = 1;
  uint32_t numNodes = 25;  // by default, 5x5
  uint32_t sinkNode = 0;
  uint32_t sourceNode = 24;
  double interval = 1.0; // seconds
  bool verbose = false;
  bool tracing = false;

  CommandLine cmd;

  cmd.AddValue ("phyMode", "Wifi Phy mode", phyMode);
  cmd.AddValue ("distance", "distance (m)", distance);
  cmd.AddValue ("packetSize", "size of application packet sent", packetSize);
  cmd.AddValue ("numPackets", "number of packets generated", numPackets);
  cmd.AddValue ("interval", "interval (seconds) between packets", interval);
  cmd.AddValue ("verbose", "turn on all WifiNetDevice log components", verbose);
  cmd.AddValue ("tracing", "turn on ascii and pcap tracing", tracing);
  cmd.AddValue ("numNodes", "number of nodes", numNodes);
  cmd.AddValue ("sinkNode", "Receiver node number", sinkNode);
  cmd.AddValue ("sourceNode", "Sender node number", sourceNode);

  cmd.Parse (argc, argv);
  // Convert to time object
  Time interPacketInterval = Seconds (interval);

  // disable fragmentation for frames below 2200 bytes
  Config::SetDefault ("ns3::WifiRemoteStationManager::FragmentationThreshold", StringValue ("2200"));
  // turn off RTS/CTS for frames below 2200 bytes
  Config::SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold", StringValue ("2200"));
  // Fix non-unicast data rate to be the same as that of unicast
  Config::SetDefault ("ns3::WifiRemoteStationManager::NonUnicastMode", 
                      StringValue (phyMode));

  NodeContainer c;
  c.Create (numNodes);

  // The below set of helpers will help us to put together the wifi NICs we want
  WifiHelper wifi;
  if (verbose)
    {
      wifi.EnableLogComponents ();  // Turn on all Wifi logging
    }

  YansWifiPhyHelper wifiPhy =  YansWifiPhyHelper::Default ();
  // set it to zero; otherwise, gain will be added
  wifiPhy.Set ("RxGain", DoubleValue (-10) ); 
  // ns-3 supports RadioTap and Prism tracing extensions for 802.11b
  wifiPhy.SetPcapDataLinkType (YansWifiPhyHelper::DLT_IEEE802_11_RADIO); 

  YansWifiChannelHelper wifiChannel;
  wifiChannel.SetPropagationDelay ("ns3::ConstantSpeedPropagationDelayModel");
  wifiChannel.AddPropagationLoss ("ns3::FriisPropagationLossModel");
  wifiPhy.SetChannel (wifiChannel.Create ());

  // Add a non-QoS upper mac, and disable rate control
  NqosWifiMacHelper wifiMac = NqosWifiMacHelper::Default ();
  wifi.SetStandard (WIFI_PHY_STANDARD_80211b);
  wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager",
                                "DataMode",StringValue (phyMode),
                                "ControlMode",StringValue (phyMode));
  // Set it to adhoc mode
  wifiMac.SetType ("ns3::AdhocWifiMac");
  NetDeviceContainer devices = wifi.Install (wifiPhy, wifiMac, c);

  MobilityHelper mobility;
  mobility.SetPositionAllocator ("ns3::GridPositionAllocator",
                                 "MinX", DoubleValue (0.0),
                                 "MinY", DoubleValue (0.0),
                                 "DeltaX", DoubleValue (distance),
                                 "DeltaY", DoubleValue (distance),
                                 "GridWidth", UintegerValue (5),
                                 "LayoutType", StringValue ("RowFirst"));
  mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
  mobility.Install (c);

  // Enable OLSR
  OlsrHelper olsr;
  Ipv4StaticRoutingHelper staticRouting;

  Ipv4ListRoutingHelper list;
  list.Add (staticRouting, 0);
  list.Add (olsr, 10);

  InternetStackHelper internet;
  internet.SetRoutingHelper (list); // has effect on the next Install ()
  internet.Install (c);

  Ipv4AddressHelper ipv4;
  NS_LOG_INFO ("Assign IP Addresses.");
  ipv4.SetBase ("10.1.1.0", "255.255.255.0");
  Ipv4InterfaceContainer i = ipv4.Assign (devices);

  TypeId tid = TypeId::LookupByName ("ns3::UdpSocketFactory");
  Ptr<Socket> recvSink = Socket::CreateSocket (c.Get (sinkNode), tid);
  InetSocketAddress local = InetSocketAddress (Ipv4Address::GetAny (), 80);
  recvSink->Bind (local);
  recvSink->SetRecvCallback (MakeCallback (&ReceivePacket));

  Ptr<Socket> source = Socket::CreateSocket (c.Get (sourceNode), tid);
  InetSocketAddress remote = InetSocketAddress (i.GetAddress (sinkNode, 0), 80);
  source->Connect (remote);

  if (tracing == true)
    {
      AsciiTraceHelper ascii;
      wifiPhy.EnableAsciiAll (ascii.CreateFileStream ("wifi-simple-adhoc-grid.tr"));
      wifiPhy.EnablePcap ("wifi-simple-adhoc-grid", devices);
      // Trace routing tables
      Ptr<OutputStreamWrapper> routingStream = Create<OutputStreamWrapper> ("wifi-simple-adhoc-grid.routes", std::ios::out);
      olsr.PrintRoutingTableAllEvery (Seconds (2), routingStream);

      // To do-- enable an IP-level trace that shows forwarding events only
    }

  // Give OLSR time to converge-- 30 seconds perhaps
  Simulator::Schedule (Seconds (30.0), &GenerateTraffic, 
                       source, packetSize, numPackets, interPacketInterval);

  // Output what we are doing
  NS_LOG_UNCOND ("Testing from node " << sourceNode << " to " << sinkNode << " with grid distance " << distance);

  Simulator::Stop (Seconds (32.0));
  Simulator::Run ();
  Simulator::Destroy ();

  return 0;
}
	void Interface()
	{
		SDL_Init(SDL_INIT_EVERYTHING);

		window = SDL_SetVideoMode(1024, 768, 0, SDL_RESIZABLE);
		FlogAssert(window, "could not set video mode");

		SDL_SysWMinfo info;
		SDL_VERSION(&info.version);
		SDL_GetWMInfo(&info);
		std::cout << "window id: " << (intptr_t)info.window << std::endl;

		SDL_Event event;

		CommandLine cli;

		PipePtr sendPipe = Pipe::Create();
		sendPipe->CreatePipe(pipeName);
		
		PipePtr recvPipe = Pipe::Create();
		recvPipe->CreatePipe(LStr(pipeName << L"_r"));
		
		FlogD("waiting for connection");
		sendPipe->WaitForConnection(-1);
		recvPipe->WaitForConnection(-1);
		FlogD("connected");
		
		CommandSenderPtr cmdSend = CommandSender::Create();
		cmdSend->Start(sendPipe);
		
		CommandQueuePtr cmdRecv = CommandQueue::Create();
		cmdRecv->Start(recvPipe);
		
		cli.Init(cmdSend, cmdRecv);

		SDL_FillRect(window, 0, 0x3366aa);
		SDL_Flip(window);

		while(!cli.done){
			while(SDL_PollEvent(&event)){
				if(event.type == SDL_QUIT || (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE))
					cli.done = true;

				if(event.type == SDL_VIDEORESIZE){
					if(window)
						SDL_FreeSurface(window);

					window = SDL_SetVideoMode(event.resize.w, event.resize.h, 0, SDL_RESIZABLE);
					SDL_FillRect(window, 0, 0x3366aa);
					SDL_Flip(window);
					cmdSend->SendCommand(NO_SEQ_NUM, 0, CTUpdateOutputSize, event.resize.w, event.resize.h);
				}
			}

			SDL_Delay(16);
		}
		
		cli.thread->join();
		cli.recvThread->join();

		cmdSend->Stop();
	}
  int
  run(int argc, char* argv[])
  {
    delayFile.open(DELAY_OUTPUT_FILE_NAME);

    // setting default parameters for PointToPoint links and channels
    Config::SetDefault("ns3::PointToPointNetDevice::DataRate", StringValue("1000Mbps"));
    Config::SetDefault("ns3::PointToPointChannel::Delay", StringValue("10ms"));
    Config::SetDefault("ns3::DropTailQueue::MaxPackets", StringValue("4294967295"));

    // Read optional command-line parameters (e.g., enable visualizer with ./waf --run=<> --visualize
    CommandLine cmd;
    cmd.Parse(argc, argv);

    // Creating nodes
    NodeContainer nodes;
    nodes.Create(NUM_OF_CONSUMERS + NUM_OF_ROUTERS + NUM_OF_PRODUCER);

    // Connecting nodes using two links
    // Connecting nodes using two links
    PointToPointHelper p2p;
    // Connecting consumers to edge routers
    int g = 0;
    for (int i = 0; i < GROUP_SIZE; i++, g++)
      p2p.Install (nodes.Get (g), nodes.Get (0 + NUM_OF_CONSUMERS));      // C0 <--> R0
    for (int i = 0; i < GROUP_SIZE; i++, g++)
      p2p.Install (nodes.Get (g), nodes.Get (36 + NUM_OF_CONSUMERS));     // C1 <--> R1
    for (int i = 0; i < GROUP_SIZE; i++, g++)
      p2p.Install (nodes.Get (g), nodes.Get (37 + NUM_OF_CONSUMERS));     // C2 <--> R3
    for (int i = 0; i < GROUP_SIZE; i++, g++)
      p2p.Install (nodes.Get (g), nodes.Get (9 + NUM_OF_CONSUMERS));      // C3 <--> R5
    for (int i = 0; i < GROUP_SIZE; i++, g++)
      p2p.Install (nodes.Get (g), nodes.Get (38 + NUM_OF_CONSUMERS));     // C4 <--> R6
    for (int i = 0; i < GROUP_SIZE; i++, g++)
      p2p.Install (nodes.Get (g), nodes.Get (13 + NUM_OF_CONSUMERS));     // C5 <--> R10
    for (int i = 0; i < GROUP_SIZE; i++, g++)
      p2p.Install (nodes.Get (g), nodes.Get (16 + NUM_OF_CONSUMERS));     // C6 <--> R8
    for (int i = 0; i < GROUP_SIZE; i++, g++)
      p2p.Install (nodes.Get (g), nodes.Get (20 + NUM_OF_CONSUMERS));     // C7 <--> R11
    for (int i = 0; i < GROUP_SIZE; i++, g++)
      p2p.Install (nodes.Get (g), nodes.Get (18 + NUM_OF_CONSUMERS));     // C8 <--> R12
    for (int i = 0; i < GROUP_SIZE; i++, g++)
      p2p.Install (nodes.Get (g), nodes.Get (28 + NUM_OF_CONSUMERS));     // C9 <--> R18
    for (int i = 0; i < GROUP_SIZE; i++, g++)
      p2p.Install (nodes.Get (g), nodes.Get (21 + NUM_OF_CONSUMERS));     // C10 <--> R17
    for (int i = 0; i < GROUP_SIZE; i++, g++)
      p2p.Install (nodes.Get (g), nodes.Get (24 + NUM_OF_CONSUMERS));     // C11 <--> R20
    for (int i = 0; i < GROUP_SIZE; i++, g++)
      p2p.Install (nodes.Get (g), nodes.Get (26 + NUM_OF_CONSUMERS));     // C12 <--> R24
    for (int i = 0; i < GROUP_SIZE; i++, g++)
      p2p.Install (nodes.Get (g), nodes.Get (35 + NUM_OF_CONSUMERS));     // C13 <--> R29
    for (int i = 0; i < GROUP_SIZE; i++, g++)
      p2p.Install (nodes.Get (g), nodes.Get (34 + NUM_OF_CONSUMERS));     // C14 <--> R28
    for (int i = 0; i < GROUP_SIZE; i++, g++)
      p2p.Install (nodes.Get (g), nodes.Get (33 + NUM_OF_CONSUMERS));     // C15 <--> R21
    // Connecting routers
    p2p.Install (nodes.Get (0 + NUM_OF_CONSUMERS), nodes.Get (1 + NUM_OF_CONSUMERS));      // R0 <--> R9
    p2p.Install (nodes.Get (1 + NUM_OF_CONSUMERS), nodes.Get (2 + NUM_OF_CONSUMERS));      // R1 <--> R15
    p2p.Install (nodes.Get (1 + NUM_OF_CONSUMERS), nodes.Get (17 + NUM_OF_CONSUMERS));     // R1 <--> R15
    p2p.Install (nodes.Get (2 + NUM_OF_CONSUMERS), nodes.Get (3 + NUM_OF_CONSUMERS));      // R2 <--> R9
    p2p.Install (nodes.Get (2 + NUM_OF_CONSUMERS), nodes.Get (4 + NUM_OF_CONSUMERS));      // R2 <--> R9
    p2p.Install (nodes.Get (2 + NUM_OF_CONSUMERS), nodes.Get (6 + NUM_OF_CONSUMERS));      // R2 <--> R9
    p2p.Install (nodes.Get (2 + NUM_OF_CONSUMERS), nodes.Get (36 + NUM_OF_CONSUMERS));     // R2 <--> R9
    p2p.Install (nodes.Get (2 + NUM_OF_CONSUMERS), nodes.Get (8 + NUM_OF_CONSUMERS));      // R2 <--> R9
    p2p.Install (nodes.Get (2 + NUM_OF_CONSUMERS), nodes.Get (17 + NUM_OF_CONSUMERS));     // R2 <--> R9
    p2p.Install (nodes.Get (2 + NUM_OF_CONSUMERS), nodes.Get (19 + NUM_OF_CONSUMERS));     // R2 <--> R9
    p2p.Install (nodes.Get (3 + NUM_OF_CONSUMERS), nodes.Get (5 + NUM_OF_CONSUMERS));      // R3 <--> R4
    p2p.Install (nodes.Get (4 + NUM_OF_CONSUMERS), nodes.Get (16 + NUM_OF_CONSUMERS));     // R4 <--> R7
    p2p.Install (nodes.Get (5 + NUM_OF_CONSUMERS), nodes.Get (8 + NUM_OF_CONSUMERS));      // R5 <--> R13
    p2p.Install (nodes.Get (6 + NUM_OF_CONSUMERS), nodes.Get (7 + NUM_OF_CONSUMERS));      // R6 <--> R7
    p2p.Install (nodes.Get (6 + NUM_OF_CONSUMERS), nodes.Get (37 + NUM_OF_CONSUMERS));     // R6 <--> R7
    p2p.Install (nodes.Get (7 + NUM_OF_CONSUMERS), nodes.Get (10 + NUM_OF_CONSUMERS));     // R7 <--> R9
    p2p.Install (nodes.Get (8 + NUM_OF_CONSUMERS), nodes.Get (9 + NUM_OF_CONSUMERS));      // R8 <--> R9
    p2p.Install (nodes.Get (8 + NUM_OF_CONSUMERS), nodes.Get (11 + NUM_OF_CONSUMERS));     // R8 <--> R9
    p2p.Install (nodes.Get (8 + NUM_OF_CONSUMERS), nodes.Get (17 + NUM_OF_CONSUMERS));     // R8 <--> R9
    // 9 done
    p2p.Install (nodes.Get (10 + NUM_OF_CONSUMERS), nodes.Get (11 + NUM_OF_CONSUMERS));    // R10 <--> R14
    p2p.Install (nodes.Get (11 + NUM_OF_CONSUMERS), nodes.Get (16 + NUM_OF_CONSUMERS));    // R11 <--> R13
    p2p.Install (nodes.Get (11 + NUM_OF_CONSUMERS), nodes.Get (38 + NUM_OF_CONSUMERS));    // R11 <--> R13
    p2p.Install (nodes.Get (11 + NUM_OF_CONSUMERS), nodes.Get (12 + NUM_OF_CONSUMERS));    // R11 <--> R13
    p2p.Install (nodes.Get (11 + NUM_OF_CONSUMERS), nodes.Get (13 + NUM_OF_CONSUMERS));    // R11 <--> R13
    p2p.Install (nodes.Get (11 + NUM_OF_CONSUMERS), nodes.Get (23 + NUM_OF_CONSUMERS));    // R11 <--> R13
    p2p.Install (nodes.Get (12 + NUM_OF_CONSUMERS), nodes.Get (13 + NUM_OF_CONSUMERS));    // R12 <--> R13
    p2p.Install (nodes.Get (13 + NUM_OF_CONSUMERS), nodes.Get (23 + NUM_OF_CONSUMERS));    // R13 <--> R14
    p2p.Install (nodes.Get (14 + NUM_OF_CONSUMERS), nodes.Get (16 + NUM_OF_CONSUMERS));    // R14 <--> R15
    p2p.Install (nodes.Get (14 + NUM_OF_CONSUMERS), nodes.Get (15 + NUM_OF_CONSUMERS));    // R14 <--> R18
    p2p.Install (nodes.Get (15 + NUM_OF_CONSUMERS), nodes.Get (39 + NUM_OF_CONSUMERS));    // R15 <--> R16
    p2p.Install (nodes.Get (15 + NUM_OF_CONSUMERS), nodes.Get (17 + NUM_OF_CONSUMERS));    // R15 <--> R19
    p2p.Install (nodes.Get (16 + NUM_OF_CONSUMERS), nodes.Get (17 + NUM_OF_CONSUMERS));    // R16 <--> R23
    p2p.Install (nodes.Get (16 + NUM_OF_CONSUMERS), nodes.Get (19 + NUM_OF_CONSUMERS));    // R16 <--> R27
    p2p.Install (nodes.Get (17 + NUM_OF_CONSUMERS), nodes.Get (18 + NUM_OF_CONSUMERS));    // R17 <--> R23
    p2p.Install (nodes.Get (17 + NUM_OF_CONSUMERS), nodes.Get (19 + NUM_OF_CONSUMERS));    // R17 <--> R23
    p2p.Install (nodes.Get (17 + NUM_OF_CONSUMERS), nodes.Get (29 + NUM_OF_CONSUMERS));    // R17 <--> R23
    p2p.Install (nodes.Get (17 + NUM_OF_CONSUMERS), nodes.Get (32 + NUM_OF_CONSUMERS));    // R17 <--> R23
    p2p.Install (nodes.Get (17 + NUM_OF_CONSUMERS), nodes.Get (31 + NUM_OF_CONSUMERS));    // R17 <--> R23
    p2p.Install (nodes.Get (17 + NUM_OF_CONSUMERS), nodes.Get (39 + NUM_OF_CONSUMERS));    // R17 <--> R23
    // 18 done
    p2p.Install (nodes.Get (19 + NUM_OF_CONSUMERS), nodes.Get (20 + NUM_OF_CONSUMERS));    // R19 <--> R22
    p2p.Install (nodes.Get (19 + NUM_OF_CONSUMERS), nodes.Get (27 + NUM_OF_CONSUMERS));    // R19 <--> R22
    // 20 done
    p2p.Install (nodes.Get (21 + NUM_OF_CONSUMERS), nodes.Get (22 + NUM_OF_CONSUMERS));    // R21 <--> R22
    p2p.Install (nodes.Get (22 + NUM_OF_CONSUMERS), nodes.Get (40 + NUM_OF_CONSUMERS));    // R22 <--> R23
    p2p.Install (nodes.Get (22 + NUM_OF_CONSUMERS), nodes.Get (23 + NUM_OF_CONSUMERS));    // R22 <--> R28
    p2p.Install (nodes.Get (22 + NUM_OF_CONSUMERS), nodes.Get (25 + NUM_OF_CONSUMERS));    // R22 <--> R29
    p2p.Install (nodes.Get (23 + NUM_OF_CONSUMERS), nodes.Get (24 + NUM_OF_CONSUMERS));    // R23 <--> R24
    // 24 done
    p2p.Install (nodes.Get (25 + NUM_OF_CONSUMERS), nodes.Get (27 + NUM_OF_CONSUMERS));    // R26 <--> R27
    p2p.Install (nodes.Get (26 + NUM_OF_CONSUMERS), nodes.Get (27 + NUM_OF_CONSUMERS));    // R26 <--> R27
    p2p.Install (nodes.Get (27 + NUM_OF_CONSUMERS), nodes.Get (40 + NUM_OF_CONSUMERS));    // R26 <--> R27
    p2p.Install (nodes.Get (27 + NUM_OF_CONSUMERS), nodes.Get (30 + NUM_OF_CONSUMERS));    // R26 <--> R27
    p2p.Install (nodes.Get (27 + NUM_OF_CONSUMERS), nodes.Get (31 + NUM_OF_CONSUMERS));    // R26 <--> R27
    p2p.Install (nodes.Get (28 + NUM_OF_CONSUMERS), nodes.Get (29 + NUM_OF_CONSUMERS));    // R26 <--> R27
    p2p.Install (nodes.Get (29 + NUM_OF_CONSUMERS), nodes.Get (30 + NUM_OF_CONSUMERS));    // R26 <--> R27
    p2p.Install (nodes.Get (30 + NUM_OF_CONSUMERS), nodes.Get (31 + NUM_OF_CONSUMERS));    // R26 <--> R27
    p2p.Install (nodes.Get (30 + NUM_OF_CONSUMERS), nodes.Get (41 + NUM_OF_CONSUMERS));    // R26 <--> R27
    p2p.Install (nodes.Get (30 + NUM_OF_CONSUMERS), nodes.Get (35 + NUM_OF_CONSUMERS));    // R26 <--> R27
    p2p.Install (nodes.Get (31 + NUM_OF_CONSUMERS), nodes.Get (41 + NUM_OF_CONSUMERS));    // R26 <--> R27
    p2p.Install (nodes.Get (31 + NUM_OF_CONSUMERS), nodes.Get (32 + NUM_OF_CONSUMERS));    // R26 <--> R27
    p2p.Install (nodes.Get (31 + NUM_OF_CONSUMERS), nodes.Get (34 + NUM_OF_CONSUMERS));    // R26 <--> R27
    p2p.Install (nodes.Get (32 + NUM_OF_CONSUMERS), nodes.Get (33 + NUM_OF_CONSUMERS));    // R26 <--> R27
    // 33 done
    // 34 done
    // 35 done
    // 36 done
    // 37 done
    // 38 done
    // 39 done
    // 40 done
    // 41 done

    // Connecting producer(s)
    int producerId = 0 + NUM_OF_CONSUMERS + NUM_OF_ROUTERS;
    p2p.Install (nodes.Get (producerId), nodes.Get (0 + NUM_OF_CONSUMERS));      // P0 <--> R0


    // Install NDN stack without cache
    ndn::StackHelper ndnHelperNoCache;
    ndnHelperNoCache.SetDefaultRoutes(true);
    ndnHelperNoCache.SetOldContentStore("ns3::ndn::cs::Nocache"); // no cache
    // Install on consumers
    for (int i = 0; i < NUM_OF_CONSUMERS; i++) {
      ndnHelperNoCache.Install(nodes.Get(i));
    }
    // Install on producer(s)
    ndnHelperNoCache.Install(nodes.Get(0 + NUM_OF_CONSUMERS + NUM_OF_ROUTERS));


    // Install NDN stack with cache
    ndn::StackHelper ndnHelperWithCache;
    ndnHelperWithCache.SetDefaultRoutes(true);
    ndnHelperWithCache.SetOldContentStore("ns3::ndn::cs::Freshness::Lru", "MaxSize", "0");
    // Install on routers
    for (int i = NUM_OF_CONSUMERS; i < NUM_OF_CONSUMERS + NUM_OF_ROUTERS; i++) {
      ndnHelperWithCache.InstallWithCallback(nodes.Get(i), (size_t)&ForwardingDelay, i, USE_PINT);
    }

    // Consumers
    ndn::AppHelper consumerHelperHonest("ns3::ndn::AccountingConsumer");
    consumerHelperHonest.SetAttribute("Frequency", StringValue("10")); // 10 interests a second
    consumerHelperHonest.SetAttribute("Randomize", StringValue("uniform"));
    consumerHelperHonest.SetAttribute("StartSeq", IntegerValue(0));
    consumerHelperHonest.SetPrefix("/prefix/A/");
    for(int i=0; i < NUM_OF_CONSUMERS; i++) {
      consumerHelperHonest.SetAttribute("ConsumerID", IntegerValue(i));
      ApplicationContainer consumer = consumerHelperHonest.Install(nodes.Get(i));
      consumer.Start(Seconds(0));

      std::ostringstream node_id;
      node_id << i;
      Config::ConnectWithoutContext("/NodeList/" + node_id.str() + "/ApplicationList/0/ReceivedMeaningfulContent", MakeCallback(ReceivedMeaningfulContent));
    }

    // Producer
    // Producer will reply to all requests starting with /prefix/A
    ndn::AppHelper producerHelper("ns3::ndn::AccountingProducer");
    producerHelper.SetPrefix("/prefix/A");
    producerHelper.SetAttribute("PayloadSize", StringValue("1024"));
    producerHelper.Install(nodes.Get(producerId));

    // Traces
    ndn::L3RateTracer::InstallAll(RATE_OUTPUT_FILE_NAME, Seconds(1.0));

    Simulator::Stop(Seconds(SIMULATION_DURATION));

    Simulator::Run();
    Simulator::Destroy();

    delayFile.close();
    return 0;
  }
Exemple #30
0
void HandleArgs(CommandLine &cl, int argc, char *argv[], Error *error) {
  // Arguments
  cl.add(' ',2,0);
  cl.addargname(' ',"input_matrix");
  cl.addargname(' ',"output_matrix");

  cl.add('r',1);
  cl.addargname('r',"rows");
  cl.adddescription('r',"Only output a selected set rows specified in the string.");
  cl.add('c',1);
  cl.addargname('c',"columns");
  cl.adddescription('c',"Only output a selected set of columns specified in the string.");
  cl.add('z',1);
  cl.addargname('z',"mod_num");
  cl.adddescription('z',"Reorder the matrix rows using the supplied modulus number. For a mod_num of 3, the first row in the new matrix is 0, followed by 3, 6, 9, ..., 1, 4, 7, ...");
  cl.add('s',2);
  cl.addargname('s',"rand_percent");
  cl.addargname('s',"rest_file");
  cl.adddescription('s',"Output a random subset of rows. rand_percent is the fraction of the matrix to output and must be between 0 and 1. The random selection is taken after any other slicing. If rest_file is not NO_OUTPUT, the remaining slice is output to the specified filename.");
  cl.add('t',0);
  cl.adddescription('t',"Output the matix in 'pretty' format.");
  cl.add('b',0);
  cl.adddescription('b',"Output the matix in binary format.");
  cl.add('q',0);
  cl.adddescription('q',"Transpose the matrix.");

  // Stuff for every executable
  cl.addhelp('h',0);
  cl.adddescription('h',"Print out the man page for help");
  cl.add('n',1);
  cl.addargname('n',"notice_level");
  cl.adddescription('n',"Set the degree of program output.  Use: \n\n\t-n  0\tNo output\n\t-n 10\tNormal program output\n\t-n 20\tParameters useful for reproducing the results\n\t-n 30\tAll output");

  // Short Description
  cl.addtoman_chapter("NAME","Perform matrix slicing");

  // Version
  cl.addtoman_chapter("VERSION","Version "+string(YALA_VERSION));

  // Full Description
  const string desc[4]={
    "Perform matrix slicing. The input file and output file are optional. ",
    "If only one is specified, it is assumed to be the input file. ",
    "If the input file or output file not specified, STDIN or STDOUT ",
    "is used to allow for piping."
  };
  cl.addtoman_chapter("DESCRIPTION",4,desc);

  ya_addftmanpage(cl);

  // Authors
  cl.addtoman_chapter("AUTHORS","W. Michael Brown");

  // Parse the commandline
  if (!cl.parse(argc,argv,error)) {
    Describe(cl,cout);
    error->generate_error(0,a::filenameonly(argv[0]),"Bad Command Line\n");
  }

  // Set the notice level
  if (cl['n'])
    error->note.set_notice_level(cl.argint('n',0));

  // Generate a notice with the command line for records purposes
  string cm=cl.program_name();
  for (int j=1; j<argc; j++)
    cm+=' '+string(argv[j]);
  cm+="\n";
  error->note.notice(19,"CommandLine",cm);

  // Output the help
  if (cl['h']) {
    cl.write_man_page(cout,YALA_VERSION,"YALA Utilities");
    exit(0);
  }
}