示例#1
0
BasicTestingSetup::BasicTestingSetup(const std::string& chainName, const std::string& fedpegscript)
    : m_path_root(fs::temp_directory_path() / "test_bitcoin" / strprintf("%lu_%i", (unsigned long)GetTime(), (int)(InsecureRandRange(1 << 30))))
{
    SHA256AutoDetect();
    RandomInit();
    ECC_Start();
    SetupEnvironment();
    SetupNetworking();
    InitSignatureCache();
    InitScriptExecutionCache();
    InitRangeproofCache();
    InitSurjectionproofCache();
    fCheckBlockIndex = true;
    // Hack to allow testing of fedpeg args
    if (!fedpegscript.empty()) {
        gArgs.SoftSetArg("-fedpegscript", fedpegscript);
        gArgs.SoftSetBoolArg("-con_has_parent_chain", true);
        gArgs.SoftSetBoolArg("-validatepegin", false);
    }
    // CreateAndProcessBlock() does not support building SegWit blocks, so don't activate in these tests.
    // TODO: fix the code to support SegWit blocks.
    gArgs.ForceSetArg("-vbparams", strprintf("segwit:0:%d", (int64_t)Consensus::BIP9Deployment::NO_TIMEOUT));
    SelectParams(chainName);

    // ELEMENTS:
    // Set policy asset for correct fee output generation
    policyAsset = CAsset();

    noui_connect();
}
示例#2
0
void GQAP::GRASPInit_reduced(double alpha) {
	// GRASP-Initialization using the provided alpa-value
	// works similar to GRASPInit, but considers just one random equipment during the list construction
	
	// if Random-Initialization is choosen, then do random initialization, since it is much faster
	// GRASP-Init with alpha = 0 is equal to random initialization
	if (alpha == 1) {
		RandomInit();
		
	// do GRASP-Init, if alpha > 0
	} else {
		// Define a Vector holing the Restricted Candidate List with maximum size
		std::vector<RCL_element> candidateList(numLocation);
	
		// current Assignment
		Assignment cAssign;
	
		// set the current solution to an undefined representation to distinguish it from valid partial solution
		//solution = std::vector<int>(numEquip, -1);
		solution = eoVector<eoMinimizingFitness, int>(numEquip, -1);
	
		// reset the values for capacity violations
		numViolatedLocations = 0;
		numViolatedCapacityUnits = 0;
	
		// Initialize the RCL
		GRASPInitReducedCandiateList(candidateList);
	
		// Add Assignments, until solution has been constructed
		for (int i = 0; i < numEquip; i++) {
			GRASPAddAssignment_CostBased(candidateList, alpha);
			GRASPUpdateReducedCandiateList(candidateList);
		}
	}
}
示例#3
0
 // constructor:                                                                         
 TRanrotBGenerator::TRanrotBGenerator(uint32 seed) {                                     
   RandomInit(seed);                                                                     
   // detect computer architecture                                                       
   union {double f; uint32 i[2];} convert;                                               
   convert.f = 1.0;                                                                      
   if (convert.i[1] == 0x3FF00000) Architecture = LITTLEENDIAN;                          
   else if (convert.i[0] == 0x3FF00000) Architecture = BIGENDIAN;                        
   else Architecture = NONIEEE;}                                                         
示例#4
0
void AppInit (void)
{

  RandomInit (time (NULL));
  CameraInit ();
  RenderInit ();
  TextureInit ();
  WorldInit ();

}
示例#5
0
// constructor:
TRanrotWGenerator::TRanrotWGenerator(uint32 seed)
:UniformGenerator()
 {
  RandomInit(seed);
  // detect computer architecture
  randbits[2] = 0; randp1 = 1.0;
  if (randbits[2] == 0x3FFF) Architecture = EXTENDEDPRECISIONLITTLEENDIAN;
  else if (randbits[1] == 0x3FF00000) Architecture = LITTLEENDIAN;
  else if (randbits[0] == 0x3FF00000) Architecture = BIGENDIAN;
  else Architecture = NONIEEE;}
示例#6
0
    pixel_city()
    {
	RandomInit (time (NULL));
        RenderInit ();
	CameraInit ();
        TextureInit ();
        WorldInit ();
        resetviewport();
        
    }
示例#7
0
//normal random could accerlate the speed of convergence 
void MFBiasApp() {
  if (!FLAGS_flag_mfbias) {
    return;
  }
  SpMat train;
  SpMat test;
  std::pair<int, int> p = ReadData(FLAGS_train_path, &train);
  ReadData(FLAGS_test_path, &test);
  MF mf;
  RandomInit(p.second, p.first, FLAGS_k, &mf);
  SGD(FLAGS_it_num, FLAGS_eta, FLAGS_lambda, train, test, &mf);
}
示例#8
0
BasicTestingSetup::BasicTestingSetup(const std::string& chainName)
{
        RandomInit();
        ECC_Start();
        SetupEnvironment();
        SetupNetworking();
        InitSignatureCache();
        fPrintToDebugLog = false; // don't want to write to debug.log file
        fCheckBlockIndex = true;
        SelectParams(chainName);
        noui_connect();
}
TEST(Util, NormalSampleTest) {
    VReal tmp;
    for (int i = 0; i < 1000000; i++) {
        tmp.push_back(NormalSample() / 100);
    }
    EXPECT_LT(std::abs(0.0 - Mean(tmp)), 0.00001);
    EXPECT_LT(std::abs(0.0001 - Var(tmp)), 0.00001);
    VVVReal tmp2;
    RandomInit(100, 100, 100, &tmp2);
    EXPECT_LT(std::abs(0.0 - Mean(tmp2)), 0.00001);
    EXPECT_LT(std::abs(0.0001 - Var(tmp2)), 0.00001);
}
int main(int argc, char** argv)
{
    SetupBenchArgs();
    std::string error;
    if (!gArgs.ParseParameters(argc, argv, error)) {
        fprintf(stderr, "Error parsing command line arguments: %s\n", error.c_str());
        return EXIT_FAILURE;
    }

    if (HelpRequested(gArgs)) {
        std::cout << gArgs.GetHelpMessage();

        return EXIT_SUCCESS;
    }

    // Set the datadir after parsing the bench options
    const fs::path bench_datadir{SetDataDir()};

    SHA256AutoDetect();
    RandomInit();
    ECC_Start();
    SetupEnvironment();

    int64_t evaluations = gArgs.GetArg("-evals", DEFAULT_BENCH_EVALUATIONS);
    std::string regex_filter = gArgs.GetArg("-filter", DEFAULT_BENCH_FILTER);
    std::string scaling_str = gArgs.GetArg("-scaling", DEFAULT_BENCH_SCALING);
    bool is_list_only = gArgs.GetBoolArg("-list", false);

    double scaling_factor;
    if (!ParseDouble(scaling_str, &scaling_factor)) {
        fprintf(stderr, "Error parsing scaling factor as double: %s\n", scaling_str.c_str());
        return EXIT_FAILURE;
    }

    std::unique_ptr<benchmark::Printer> printer(new benchmark::ConsolePrinter());
    std::string printer_arg = gArgs.GetArg("-printer", DEFAULT_BENCH_PRINTER);
    if ("plot" == printer_arg) {
        printer.reset(new benchmark::PlotlyPrinter(
            gArgs.GetArg("-plot-plotlyurl", DEFAULT_PLOT_PLOTLYURL),
            gArgs.GetArg("-plot-width", DEFAULT_PLOT_WIDTH),
            gArgs.GetArg("-plot-height", DEFAULT_PLOT_HEIGHT)));
    }

    benchmark::BenchRunner::RunAll(*printer, evaluations, scaling_factor, regex_filter, is_list_only);

    fs::remove_all(bench_datadir);

    ECC_Stop();

    return EXIT_SUCCESS;
}
示例#11
0
bool
StarServer::InitGame()
{
    if (!Game::InitGame())
    return false;

    RandomInit();
    ModConfig::Initialize();
    NetServerConfig::Initialize();
    SystemDesign::Initialize("sys.def");
    WeaponDesign::Initialize("wep.def");
    Ship::Initialize();
    Galaxy::Initialize();
    CombatRoster::Initialize();
    Campaign::Initialize();

    Drive::Initialize();
    Explosion::Initialize();
    FlightDeck::Initialize();
    Ship::Initialize();
    Shot::Initialize();
    RadioTraffic::Initialize();

    time_mark = Game::GameTime();
    minutes   = 0;

    NetServerConfig* server_config = NetServerConfig::GetInstance();
    if (!server_config)
    return false;

    ::Print("\n\n\nStarshatter Server Init\n");
    ::Print("-----------------------\n");
    ::Print("Server Name:       %s\n", (const char*) server_config->Name());
    ::Print("Server Type:       %d\n", server_config->GetGameType());

    if (server_config->GetMission().length() > 0)
    ::Print("Server Mission:    %s\n", (const char*) server_config->GetMission());

    ::Print("Lobby Server Port: %d\n", server_config->GetLobbyPort());
    ::Print("Admin Server Port: %d\n", server_config->GetAdminPort());
    ::Print("-----------------------\n");

    NetLobbyServer* nls = new(__FILE__,__LINE__) NetLobbyServer;
    NetAdminServer* nas = NetAdminServer::GetInstance(server_config->GetAdminPort());
    nas->SetServerName(server_config->Name());

    lobby_server = nls;
    admin_server = nas;

    return true;
}
示例#12
0
BasicTestingSetup::BasicTestingSetup(const std::string& chainName)
    : m_path_root(fs::temp_directory_path() / "test_bitcoin" / strprintf("%lu_%i", (unsigned long)GetTime(), (int)(InsecureRandRange(1 << 30))))
{
    SHA256AutoDetect();
    RandomInit();
    ECC_Start();
    SetupEnvironment();
    SetupNetworking();
    InitSignatureCache();
    InitScriptExecutionCache();
    fCheckBlockIndex = true;
    SelectParams(chainName);
    noui_connect();
}
示例#13
0
int main(int argc, char* argv[])
{
#ifdef WIN32
    util::WinCmdLineArgs winArgs;
    std::tie(argc, argv) = winArgs.get();
#endif
    SetupEnvironment();
    RandomInit();
    try {
        if (!WalletAppInit(argc, argv)) return EXIT_FAILURE;
    } catch (const std::exception& e) {
        PrintExceptionContinue(&e, "WalletAppInit()");
        return EXIT_FAILURE;
    } catch (...) {
        PrintExceptionContinue(nullptr, "WalletAppInit()");
        return EXIT_FAILURE;
    }

    std::string method {};
    for(int i = 1; i < argc; ++i) {
        if (!IsSwitchChar(argv[i][0])) {
            if (!method.empty()) {
                fprintf(stderr, "Error: two methods provided (%s and %s). Only one method should be provided.\n", method.c_str(), argv[i]);
                return EXIT_FAILURE;
            }
            method = argv[i];
        }
    }

    if (method.empty()) {
        fprintf(stderr, "No method provided. Run `bitcoin-wallet -help` for valid methods.\n");
        return EXIT_FAILURE;
    }

    // A name must be provided when creating a file
    if (method == "create" && !gArgs.IsArgSet("-wallet")) {
        fprintf(stderr, "Wallet name must be provided when creating a new wallet.\n");
        return EXIT_FAILURE;
    }

    std::string name = gArgs.GetArg("-wallet", "");

    ECCVerifyHandle globalVerifyHandle;
    ECC_Start();
    if (!WalletTool::ExecuteWalletToolFunc(method, name))
        return EXIT_FAILURE;
    ECC_Stop();
    return EXIT_SUCCESS;
}
示例#14
0
文件: vfbn2.c 项目: burnmg/vfml
static void _InitializeGlobals(int argc, char *argv[]) {
   char fileName[255];

   _processArgs(argc, argv);

   MSetAllocFailFunction(_AllocFailed);   

   if(gUseStartingNet) {
      gPriorNet = BNReadBIF(gStartingNetFile);
      if(gPriorNet == 0) {
         DebugError(1, "couldn't read net specified by -startFrom\n");
      }

      gEs = BNGetExampleSpec(gPriorNet);
   } else {
      sprintf(fileName, "%s/%s.names", gSourceDirectory, gFileStem);
      gEs = ExampleSpecRead(fileName);
      DebugError(gEs == 0, "Unable to open the .names file");

      gPriorNet = BNNewFromSpec(gEs);
   }

   gInitialParameterCount = BNGetNumParameters(gPriorNet);
   gBranchFactor = BNGetNumNodes(gPriorNet) * BNGetNumNodes(gPriorNet);
   if(gLimitBytes != -1) {
      gMaxBytesPerModel = gLimitBytes / BNGetNumNodes(gPriorNet);
      //gMaxBytesPerModel = gLimitBytes / gBranchFactor;
      DebugMessage(1, 2, "Limit models to %.4lf megs\n", 
                     gMaxBytesPerModel / (1024.0 * 1024.0));
   }

   gCurrentNet = BNClone(gPriorNet);
   BNZeroCPTs(gCurrentNet);

   RandomInit();
   /* seed */
   if(gSeed != -1) {
      RandomSeed(gSeed);
   } else {
      gSeed = RandomRange(1, 30000);
      RandomSeed(gSeed);
   }

   DebugMessage(1, 1, "running with seed %d\n", gSeed);
   DebugMessage(1, 1, "allocation %ld\n", MGetTotalAllocation());
   DebugMessage(1, 1, "initial parameters %ld\n", gInitialParameterCount);

}
示例#15
0
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
        RandomInit();
        break;
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
        break;
    case DLL_PROCESS_DETACH:
        RandomClose();
        break;
    }
    return TRUE;
}
示例#16
0
void Init(char *langs, char *dialects, int anamorph)
{
  Starting = 1;
  GenOnAssert = 1;
  LexEntryOff = 0;
  SaveTime = 1;
    /* SaveTime = 1: no spell correction hashing or phrase derivation,
     *               saves memory.
     * SaveTime = 0: uses more time and memory.
     */
  qallocInit();
  DbgInit();
  DbgSet(DBGALL, DBGBAD);
  DbgSetStdoutLevel(DBGOK);
  NoticePrint(stderr);
  NoticePrint(Log);
  EnvInit();
  StringInit();
  RandomInit();
  GridInit();
  ObjInit();
  ObjListInit();
  DbInit();
  ContextInit();
  TsInit();
  TsRangeInit();
  LexEntryInit();
  Lex_WordForm2Init();
  MorphInit(anamorph);
  WordFormInit();
  InferenceInit();
  ReportInit();
  CommentaryInit();
  TranslateInit();
  LearnInit();
  StopAtInit();
  TT_HTML_Init();
  StdDiscourse = DiscourseCreate(langs, dialects);
  DiscourseSetLang(StdDiscourse, F_ENGLISH);
  Starting = 0;
}
示例#17
0
int
main(int argc, char** argv)
{
    SetupBenchArgs();
    gArgs.ParseParameters(argc, argv);

    if (HelpRequested(gArgs)) {
        std::cout << gArgs.GetHelpMessage();

        return 0;
    }

    SHA256AutoDetect();
    RandomInit();
    ECC_Start();
    SetupEnvironment();

    int64_t evaluations = gArgs.GetArg("-evals", DEFAULT_BENCH_EVALUATIONS);
    std::string regex_filter = gArgs.GetArg("-filter", DEFAULT_BENCH_FILTER);
    std::string scaling_str = gArgs.GetArg("-scaling", DEFAULT_BENCH_SCALING);
    bool is_list_only = gArgs.GetBoolArg("-list", false);

    double scaling_factor = boost::lexical_cast<double>(scaling_str);


    std::unique_ptr<benchmark::Printer> printer(new benchmark::ConsolePrinter());
    std::string printer_arg = gArgs.GetArg("-printer", DEFAULT_BENCH_PRINTER);
    if ("plot" == printer_arg) {
        printer.reset(new benchmark::PlotlyPrinter(
            gArgs.GetArg("-plot-plotlyurl", DEFAULT_PLOT_PLOTLYURL),
            gArgs.GetArg("-plot-width", DEFAULT_PLOT_WIDTH),
            gArgs.GetArg("-plot-height", DEFAULT_PLOT_HEIGHT)));
    }

    benchmark::BenchRunner::RunAll(*printer, evaluations, scaling_factor, regex_filter, is_list_only);

    ECC_Stop();
}
示例#18
0
TInt TouchMemory(TAny*)
	{
	RThread::Rendezvous(KErrNone);	// Signal that this thread has started running.
	RandomInit(TouchData.iSize);
	while (!TouchDataStop)
		{
		TUint8* p = Chunk.Base();
		TUint8* pEnd = p + ChunkCommitEnd;
		TUint8* fragPEnd = p + TouchData.iFrequency;
		for (TUint8* fragP = p + TouchData.iSize; fragPEnd < pEnd && !TouchDataStop;)
			{
			TUint8* data = fragP;
			for (; data < fragPEnd && !TouchDataStop; data += PageSize)
				{
				*data = (TUint8)(data - fragP);
				TUint random = Random();
				if (random & 0x8484)
					User::After(random & 0xFFFF);
				}
			for (data = fragP; data < fragPEnd && !TouchDataStop; data += PageSize)
				{
				if (*data != (TUint8)(data - fragP))
					{
					RDebug::Printf("Error unexpected data 0x%x read from 0x%08x", *data, data);
					return KErrGeneral;
					}
				TUint random = Random();
				if (random & 0x8484)
					User::After(random & 0xFFFF);
				}
			fragP = fragPEnd + TouchData.iSize;
			fragPEnd += TouchData.iFrequency;
			}
		}
	return KErrNone;
	}
示例#19
0
int TAGMFast::FindComsByCV(TIntV& ComsV, const double HOFrac, const int NumThreads, const TStr PlotLFNm, const double StepAlpha, const double StepBeta) {
  if (ComsV.Len() == 0) {
    int MaxComs = G->GetNodes() / 5;
    ComsV.Add(2);
    while(ComsV.Last() < MaxComs) { ComsV.Add(ComsV.Last() * 2); }
  }
  TIntPrV EdgeV(G->GetEdges(), 0);
  for (TUNGraph::TEdgeI EI = G->BegEI(); EI < G->EndEI(); EI++) {
    EdgeV.Add(TIntPr(EI.GetSrcNId(), EI.GetDstNId()));
  }
  EdgeV.Shuffle(Rnd);
  int MaxIterCV = 3;

  TVec<TVec<TIntSet> > HoldOutSets(MaxIterCV);
  if (EdgeV.Len() > 50) { //if edges are many enough, use CV
    printf("generating hold out set\n");
    TIntV NIdV1, NIdV2;
    G->GetNIdV(NIdV1);
    G->GetNIdV(NIdV2);
    for (int IterCV = 0; IterCV < MaxIterCV; IterCV++) {
      // generate holdout sets
      HoldOutSets[IterCV].Gen(G->GetNodes());
      const int HOTotal = int(HOFrac * G->GetNodes() * (G->GetNodes() - 1) / 2.0);
      int HOCnt = 0;
      int HOEdges = (int) TMath::Round(HOFrac * G->GetEdges());
      printf("holding out %d edges...\n", HOEdges);
      for (int he = 0; he < (int) HOEdges; he++) {
        HoldOutSets[IterCV][EdgeV[he].Val1].AddKey(EdgeV[he].Val2);
        HoldOutSets[IterCV][EdgeV[he].Val2].AddKey(EdgeV[he].Val1);
        HOCnt++;
      }
      printf("%d Edges hold out\n", HOCnt);
      while(HOCnt++ < HOTotal) {
        int SrcNID = Rnd.GetUniDevInt(G->GetNodes());
        int DstNID = Rnd.GetUniDevInt(G->GetNodes());
        HoldOutSets[IterCV][SrcNID].AddKey(DstNID);
        HoldOutSets[IterCV][DstNID].AddKey(SrcNID);
      }
    }
    printf("hold out set generated\n");
  }

  TFltV HOLV(ComsV.Len());
  TIntFltPrV ComsLV;
  for (int c = 0; c < ComsV.Len(); c++) {
    const int Coms = ComsV[c];
    printf("Try number of Coms:%d\n", Coms);
    NeighborComInit(Coms);
    printf("Initialized\n");

    if (EdgeV.Len() > 50) { //if edges are many enough, use CV
      for (int IterCV = 0; IterCV < MaxIterCV; IterCV++) {
        HOVIDSV = HoldOutSets[IterCV];

        if (NumThreads == 1) {
          printf("MLE without parallelization begins\n");
          MLEGradAscent(0.05, 10 * G->GetNodes(), "", StepAlpha, StepBeta);
        } else {
          printf("MLE with parallelization begins\n");
          MLEGradAscentParallel(0.05, 100, NumThreads, "", StepAlpha, StepBeta);
        }
        double HOL = LikelihoodHoldOut();
        HOL = HOL < 0? HOL: TFlt::Mn;
        HOLV[c] += HOL;
      }
    }
    else {
      HOVIDSV.Gen(G->GetNodes());
      MLEGradAscent(0.0001, 100 * G->GetNodes(), "");
      double BIC = 2 * Likelihood() - (double) G->GetNodes() * Coms * 2.0 * log ( (double) G->GetNodes());
      HOLV[c] = BIC;
    }
  }
  int EstComs = 2;
  double MaxL = TFlt::Mn;
  printf("\n");
  for (int c = 0; c < ComsV.Len(); c++) {
    ComsLV.Add(TIntFltPr(ComsV[c].Val, HOLV[c].Val));
    printf("%d(%f)\t", ComsV[c].Val, HOLV[c].Val);
    if (MaxL < HOLV[c]) {
      MaxL = HOLV[c];
      EstComs = ComsV[c];
    }
  }
  printf("\n");
  RandomInit(EstComs);
  HOVIDSV.Gen(G->GetNodes());
  if (! PlotLFNm.Empty()) {
    TGnuPlot::PlotValV(ComsLV, PlotLFNm, "hold-out likelihood", "communities", "likelihood");
  }
  return EstComs;
}
示例#20
0
/*********************************************************************
 * Function:        void StackInit(void)
 *
 * PreCondition:    None
 *
 * Input:           None
 *
 * Output:          Stack and its componets are initialized
 *
 * Side Effects:    None
 *
 * Note:            This function must be called before any of the
 *                  stack or its component routines are used.
 *
 ********************************************************************/
void StackInit(void)
{
    static bool once = false;
    smStack = SM_STACK_IDLE;

#if defined(STACK_USE_IP_GLEANING) || defined(STACK_USE_DHCP_CLIENT)
    /*
     * If DHCP or IP Gleaning is enabled,
     * startup in Config Mode.
     */
    AppConfig.Flags.bInConfigMode = true;
#endif

#if defined (WF_CS_TRIS) && defined (STACK_USE_DHCP_CLIENT)
    g_DhcpRenew = false;
    g_DhcpRetryTimer = 0;
#endif

    if (!once) {
        // Seed the LFSRRand() function
        LFSRSeedRand(GenerateRandomDWORD());
        once = true;
    }

    MACInit();

#if defined(WF_CS_TRIS) && defined(STACK_USE_EZ_CONFIG) && !defined(__XC8)
    WFEasyConfigInit();
#endif

    ARPInit();

#if defined(STACK_USE_ANNOUNCE)
    AnnounceInit();
#endif

#if defined(STACK_USE_UDP)
    UDPInit();
#endif

#if defined(STACK_USE_TCP)
    TCPInit();
#endif

#if defined(STACK_USE_BERKELEY_API)
    BerkeleySocketInit();
#endif

#if defined(STACK_USE_HTTP2_SERVER)
    HTTPInit();
#endif

#if defined(STACK_USE_RSA)
    RSAInit();
#endif

#if defined(STACK_USE_SSL)
    SSLInit();
#endif

#if defined(STACK_USE_FTP_SERVER) && defined(STACK_USE_MPFS2)
    FTPInit();
#endif

#if defined(STACK_USE_DHCP_CLIENT)
    DHCPInit(0);

    if(!AppConfig.Flags.bIsDHCPEnabled)
    {
        DHCPDisable(0);
    }
#endif

#if defined(STACK_USE_AUTO_IP)
    AutoIPInit(0);
#endif

#if defined(STACK_USE_DYNAMICDNS_CLIENT)
    DDNSInit();
#endif

#if defined(STACK_USE_RANDOM)
    RandomInit();
#endif

#if defined(STACK_USE_NBNS)
    NBNSInit();
#endif
}
示例#21
0
/*********************************************************************
 * Function:        void StackInit(void)
 *
 * PreCondition:    None
 *
 * Input:           None
 *
 * Output:          Stack and its componets are initialized
 *
 * Side Effects:    None
 *
 * Note:            This function must be called before any of the
 *                  stack or its component routines are used.
 *
 ********************************************************************/
void StackInit(void)
{
    smStack                     = SM_STACK_IDLE;

#if defined(STACK_USE_IP_GLEANING) || defined(STACK_USE_DHCP_CLIENT)
    /*
     * If DHCP or IP Gleaning is enabled,
     * startup in Config Mode.
     */
    AppConfig.Flags.bInConfigMode = TRUE;

#endif

	// Seed the LFSRRand() function
	LFSRSeedRand(GenerateRandomDWORD());

    MACInit();

#if defined(WF_CS_TRIS) && defined(STACK_USE_EZ_CONFIG) && !defined(__18CXX)
    WFEasyConfigInit();
#endif    

    ARPInit();

#if defined(STACK_USE_UDP)
    UDPInit();
#endif

#if defined(STACK_USE_TCP)
    TCPInit();
#endif

#if defined(STACK_USE_BERKELEY_API)
	BerkeleySocketInit();
#endif

#if defined(STACK_USE_HTTP2_SERVER)
    HTTPInit();
#endif

#if defined(STACK_USE_RSA)
	RSAInit();
#endif

#if defined(STACK_USE_SSL)
    SSLInit();
#endif

#if defined(STACK_USE_FTP_SERVER) && defined(STACK_USE_MPFS2)
    FTPInit();
#endif

#if defined(STACK_USE_SNMP_SERVER)
	SNMPInit();
#endif

#if defined(STACK_USE_DHCP_CLIENT)
	DHCPInit(0);
    if(!AppConfig.Flags.bIsDHCPEnabled)
    {
        DHCPDisable(0);
    }
#endif

#if defined(STACK_USE_AUTO_IP)
    AutoIPInit(0);
#endif

#if defined(STACK_USE_DYNAMICDNS_CLIENT)
	DDNSInit();
#endif

#if defined(STACK_USE_RANDOM)
	RandomInit();
#endif
}
示例#22
0
文件: shuffledata.c 项目: burnmg/vfml
int main(int argc, char *argv[]) {
   char fileName[255];



   FILE *exampleIn, *names;
   ExampleSpecPtr es;
   ExamplePtr e;
   FILE *outputData;
   VoidAListPtr list;

   _processArgs(argc, argv);

   /* set up the random seed */
   RandomInit();
   if(gSeed != -1) {
      RandomSeed(gSeed);
   }

   /* read the spec file */
   sprintf(fileName, "%s/%s.names", gSourceDirectory, gFileStem);
   /* TODO check that the file exists */
   es = ExampleSpecRead(fileName);

   /* TODO check that the target directory exists */
   sprintf(fileName, "%s/%s.data", gTargetDirectory, gTargetFileStem);
   outputData = fopen(fileName, "w");

   sprintf(fileName, "%s/%s.data", gSourceDirectory, gFileStem);
   /* TODO check that the file exists */
   exampleIn = fopen(fileName, "r");

   list = VALNew();
   e = ExampleRead(exampleIn, es);
   while(e != 0) {
      VALAppend(list, e);
      e = ExampleRead(exampleIn, es);
   }
   fclose(exampleIn);

   if(gMessageLevel >= 1) {
      printf("Done reading, begin outputting...\n");
      fflush(stdout);
   }

   /* now output in random order */
   while(VALLength(list)) {
      e = VALRemove(list, RandomRange(0, VALLength(list) - 1));
      ExampleWrite(e, outputData);

      ExampleFree(e);
   }

   /* close the output file */
   fclose(outputData);

   /* output the names files */
   /* TODO check that the target directory exists */
   sprintf(fileName, "%s/%s.names", gTargetDirectory, gTargetFileStem);
   names = fopen(fileName, "w");
   ExampleSpecWrite(es, names);
   fclose(names);

   return 0;
}
int vtkKMeansClustering::RequestData(vtkInformation *vtkNotUsed(request),
                                     vtkInformationVector **inputVector,
                                     vtkInformationVector *outputVector)
{
    // Get the info objects
    vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
    vtkInformation *outInfoColoredPoints = outputVector->GetInformationObject(0);
    vtkInformation *outInfoClusterCenters = outputVector->GetInformationObject(1);

    // Get the input and ouptut
    vtkPolyData *input = vtkPolyData::SafeDownCast(
                             inInfo->Get(vtkDataObject::DATA_OBJECT()));

    this->Points->ShallowCopy(input->GetPoints());

    vtkPolyData *outputColoredPoints = vtkPolyData::SafeDownCast(
                                           outInfoColoredPoints->Get(vtkDataObject::DATA_OBJECT()));

    vtkPolyData *outputClusterCenters = vtkPolyData::SafeDownCast(
                                            outInfoClusterCenters->Get(vtkDataObject::DATA_OBJECT()));

    // Create a KDTree of the points
    this->KDTree->SetDataSet(input);
    this->KDTree->BuildLocator();

    // Seed a random number generator
    if(this->Random)
    {
        vtkMath::RandomSeed(time(NULL));
    }
    else
    {
        vtkMath::RandomSeed(0);
    }

    // Initialize the structure in which to store the cluster centers
    vtkSmartPointer<vtkPoints> clusterCenters =
        vtkSmartPointer<vtkPoints>::New();
    clusterCenters->SetNumberOfPoints(this->K);

    if(this->InitMethod == RANDOM)
    {
        RandomInit(clusterCenters);
    }
    else if(this->InitMethod == KMEANSPP) // http://en.wikipedia.org/wiki/K-means%2B%2B
    {
        MeansPPInit(clusterCenters);
    }
    else
    {
        std::cerr << "An invalid initialization method has been specified!" << std::endl;
        exit(-1);
    }

    /*
    // Output cluster centers
    std::cout << "Initial cluster centers: " << std::endl;
    for(unsigned int i = 0; i < clusterCenters->GetNumberOfPoints(); i++)
    {
    double p[3];
    clusterCenters->GetPoint(i, p);
    std::cout << "Cluster center " << i << " : " << p[0] << " " << p[1] << " " << p[2] << std::endl;
    }
    */

    // We must store the labels at the previous iteration to determine whether any labels changed at each iteration.
    std::vector<unsigned int> oldLabels(input->GetNumberOfPoints(), 0); // initialize to all zeros

    // Initialize the labels array
    this->Labels.resize(input->GetNumberOfPoints());

    // The current iteration number
    int iter = 0;

    // Track whether any labels changed in the last iteration
    bool changed = true;
    do
    {
        AssignLabels(input->GetPoints(), clusterCenters);

        EstimateClusterCenters(input->GetPoints(), clusterCenters);

        changed = CheckChanged(this->Labels, oldLabels);

        // Save the old labels
        oldLabels = this->Labels;
        iter++;
    } while(changed);
    //}while(iter < 100); // You could use this stopping criteria to make kmeans run for a specified number of iterations

    std::cout << "KMeans finished in " << iter << " iterations." << std::endl;

    // Create the color map
    this->ColorLookupTable->SetTableRange(0, this->K);
    this->ColorLookupTable->Build();

    CreateCentersPolyData(clusterCenters, outputClusterCenters);
    CreateOutputPointsPolyData(outputColoredPoints);

    return 1;
}
示例#24
0
void SkJS::InitializeDisplayables(const SkBitmap& bitmap, JSContext *cx, JSObject *obj, JSObject *proto) {
    SkJSDisplayable::gCanvas = new SkCanvas(bitmap);
    SkJSDisplayable::gPaint = new SkPaint();
#if SK_USE_CONDENSED_INFO == 0
    GenerateTables();
#else
    SkASSERT(0); // !!! compressed version hasn't been implemented
#endif
    AddInit(cx, obj, proto);
    AddCircleInit(cx, obj, proto);
    AddOvalInit(cx, obj, proto);
    AddPathInit(cx, obj, proto);
    AddRectangleInit(cx, obj, proto);
    AddRoundRectInit(cx, obj, proto);
//  AfterInit(cx, obj, proto);
    ApplyInit(cx, obj, proto);
    // AnimateInit(cx, obj, proto);
//  AnimateColorInit(cx, obj, proto);
    AnimateFieldInit(cx, obj, proto);
//  AnimateRotateInit(cx, obj, proto);
//  AnimateScaleInit(cx, obj, proto);
//  AnimateTranslateInit(cx, obj, proto);
    BitmapInit(cx, obj, proto);
//  BaseBitmapInit(cx, obj, proto);
//  BeforeInit(cx, obj, proto);
    BitmapShaderInit(cx, obj, proto);
    BlurInit(cx, obj, proto);
    ClipInit(cx, obj, proto);
    ColorInit(cx, obj, proto);
    CubicToInit(cx, obj, proto);
    DashInit(cx, obj, proto);
    DataInit(cx, obj, proto);
//  DimensionsInit(cx, obj, proto);
    DiscreteInit(cx, obj, proto);
    DrawToInit(cx, obj, proto);
    EmbossInit(cx, obj, proto);
    EventInit(cx, obj, proto);
//  FontInit(cx, obj, proto);
//  FocusInit(cx, obj, proto);
    ImageInit(cx, obj, proto);
    IncludeInit(cx, obj, proto);
//  InputInit(cx, obj, proto);
    LineInit(cx, obj, proto);
    LinearGradientInit(cx, obj, proto);
    LineToInit(cx, obj, proto);
    MatrixInit(cx, obj, proto);
    MoveInit(cx, obj, proto);
    MoveToInit(cx, obj, proto);
    OvalInit(cx, obj, proto);
    PathInit(cx, obj, proto);
    PaintInit(cx, obj, proto);
    DrawPointInit(cx, obj, proto);
    PolyToPolyInit(cx, obj, proto);
    PolygonInit(cx, obj, proto);
    PolylineInit(cx, obj, proto);
    PostInit(cx, obj, proto);
    QuadToInit(cx, obj, proto);
    RadialGradientInit(cx, obj, proto);
    RandomInit(cx, obj, proto);
    RectToRectInit(cx, obj, proto);
    RectangleInit(cx, obj, proto);
    RemoveInit(cx, obj, proto);
    ReplaceInit(cx, obj, proto);
    RotateInit(cx, obj, proto);
    RoundRectInit(cx, obj, proto);
    ScaleInit(cx, obj, proto);
    SetInit(cx, obj, proto);
    SkewInit(cx, obj, proto);
    // 3D_CameraInit(cx, obj, proto);
    // 3D_PatchInit(cx, obj, proto);
    SnapshotInit(cx, obj, proto);
//  StrokeInit(cx, obj, proto);
    TextInit(cx, obj, proto);
    TextOnPathInit(cx, obj, proto);
    TextToPathInit(cx, obj, proto);
    TranslateInit(cx, obj, proto);
//  UseInit(cx, obj, proto);
}
示例#25
0
/*********************************************************************
 * Function:        void StackInit(void)
 *
 * PreCondition:    None
 *
 * Input:           None
 *
 * Output:          Stack and its componets are initialized
 *
 * Side Effects:    None
 *
 * Note:            This function must be called before any of the
 *                  stack or its component routines are used.
 *
 ********************************************************************/
void StackInit(void)
{
   static BOOL once = FALSE;
    smStack                     = SM_STACK_IDLE;

#if defined(STACK_USE_IP_GLEANING) || defined(STACK_USE_DHCP_CLIENT)
    /*
     * If DHCP or IP Gleaning is enabled,
     * startup in Config Mode.
     */
    AppConfig.Flags.bInConfigMode = TRUE;

#endif

#if defined (WF_CS_TRIS) && defined (STACK_USE_DHCP_CLIENT)
   g_DhcpRenew = FALSE;
   g_DhcpRetryTimer = 0;
#endif

   if (!once) {
      // Seed the LFSRRand() function
      LFSRSeedRand(GenerateRandomDWORD());
      once = TRUE;
   }

    MACInit();

#if defined (WF_AGGRESSIVE_PS) && defined (WF_CS_TRIS)
   WFEnableAggressivePowerSave();
#endif

#if defined(WF_CS_TRIS) && defined(STACK_USE_EZ_CONFIG) && !defined(__18CXX)
    WFEasyConfigInit();
#endif    

    ARPInit();

#if defined(STACK_USE_UDP)
    UDPInit();
#endif

#if defined(STACK_USE_TCP)
    TCPInit();
#endif

#if defined(STACK_USE_BERKELEY_API)
   BerkeleySocketInit();
#endif

#if defined(STACK_USE_HTTP2_SERVER)
    HTTPInit();
#endif

#if defined(STACK_USE_RSA)
   RSAInit();
#endif

#if defined(STACK_USE_SSL)
    SSLInit();
#endif

#if defined(STACK_USE_FTP_SERVER) && defined(STACK_USE_MPFS2)
    FTPInit();
#endif

#if defined(STACK_USE_SNMP_SERVER)
   SNMPInit();
#endif

#if defined(STACK_USE_DHCP_CLIENT)
   DHCPInit(0);
    if(!AppConfig.Flags.bIsDHCPEnabled)
    {
        DHCPDisable(0);
    }
#endif

#if defined(STACK_USE_AUTO_IP)
    AutoIPInit(0);
#endif

#if defined(STACK_USE_DYNAMICDNS_CLIENT)
   DDNSInit();
#endif

#if defined(STACK_USE_RANDOM)
   RandomInit();
#endif

#if defined(STACK_USE_CCS_SMTP)
   SMTPInit();
#endif

#if defined(STACK_USE_CCS_SNTP_CLIENT)
   NTPInit();
#endif

#if defined(STACK_USE_CCS_GRATUITOUS_ARP)
   GratArpInit();
#endif

#if defined(STACK_USE_CCS_HTTP1_SERVER) || defined(STACK_USE_CCS_HTTP2_SERVER)
   HTTPInit();
#endif

   #if defined(STACK_USE_CCS_TFTP_SERVER)
   TFTPSInit();
   #endif
}
示例#26
0
// Host code
int main(int argc, char** argv)
{
    setbuf(stdout, NULL);
    printf("Simple vector addition\n");

    initCL();

    int N = 256;
    size_t size = N * sizeof(float);    

    // Allocate input vectors h_A, h_B and h_C in host memory
    h_A = (float*)malloc(size);
    if (h_A == 0) Cleanup();
    h_B = (float*)malloc(size);
    if (h_B == 0) Cleanup();
    h_C = (float*)malloc(size);
    if (h_C == 0) Cleanup();
    h_E = (float*)malloc(size);
    if (h_E == 0) Cleanup();
    h_D = (float*)malloc(size);
    if (h_D == 0) Cleanup();
	
    // Initialize input vectors
    RandomInit(h_A, N);
    RandomInit(h_B, N);	
    RandomInit(h_D, N);
	
    // Allocate vectors in device memory
    // Copy vectors from host memory to device memory
    d_A = clCreateBuffer(contextHandle,CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, size,   h_A,   &openCLErrorID);
    d_B = clCreateBuffer(contextHandle,CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, size,   h_B,   &openCLErrorID);
    d_C = clCreateBuffer(contextHandle,CL_MEM_READ_WRITE,                       size,   NULL,  &openCLErrorID);
    d_D = clCreateBuffer(contextHandle,CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,size,   h_D,   &openCLErrorID);
    d_E = clCreateBuffer(contextHandle,CL_MEM_READ_WRITE,                       size,   NULL,  &openCLErrorID);

    size_t sourceSize;
    const char* kernelSourceCode = loadKernelSourceCode("VecAdd.cl",&sourceSize);

    kernelProgramm = clCreateProgramWithSource(contextHandle,1,&kernelSourceCode,&sourceSize,&openCLErrorID);
//    printf("clCreateProgramWithSource: %d\n",openCLErrorID);
    size_t retSourceSize;
    openCLErrorID = clGetProgramInfo(kernelProgramm,CL_PROGRAM_SOURCE,NULL,NULL,&retSourceSize);
    char retSource[retSourceSize];
    openCLErrorID = clGetProgramInfo(kernelProgramm,CL_PROGRAM_SOURCE,retSourceSize,retSource,NULL);
    printf("Kernel Source Code:\n--------------\n%s\n--------------\n",retSource);

    // compile an OpenCL Programm
    openCLErrorID = clBuildProgram(kernelProgramm,1,&deviceHandle,NULL,NULL,NULL);
    if(openCLErrorID != 0)
        printBuildLog(kernelProgramm,deviceHandle);

//    printf("clBuildProgram: %d\n",openCLErrorID);

    // create an OpenCL Kernel Object
    kernel = clCreateKernel(kernelProgramm,"VecAdd",&openCLErrorID);
//    printf("clCreateKernel: %d\n",openCLErrorID);

    openCLErrorID = clSetKernelArg(kernel,0,sizeof(cl_mem),&d_A);
    openCLErrorID = clSetKernelArg(kernel,1,sizeof(cl_mem),&d_B);
    openCLErrorID = clSetKernelArg(kernel,2,sizeof(cl_mem),&d_C);
    openCLErrorID = clSetKernelArg(kernel,3,sizeof(cl_mem),&d_D);
    openCLErrorID = clSetKernelArg(kernel,4,sizeof(cl_mem),&d_E);

    size_t globalWorkSize = 256;
    size_t localWorkSize = 1;

    // Invoke kernel
    openCLErrorID = clEnqueueNDRangeKernel(commandQueue,kernel,1,NULL,&globalWorkSize,&localWorkSize,0,NULL,NULL);
//    printf("clEnqueueNDRangeKernel: %d\n",openCLErrorID);

	// Copy result from device memory to host memory
    // h_C contains the result in host memory
    openCLErrorID = clEnqueueReadBuffer(commandQueue,d_C, CL_TRUE, 0, size, h_C, 0, NULL, NULL);
//    printf("clEnqueueReadBuffer C: %d\n",openCLErrorID);

    openCLErrorID = clEnqueueReadBuffer(commandQueue,d_E, CL_TRUE, 0, size, h_E, 0, NULL, NULL);
//    printf("clEnqueueReadBuffer E: %d\n",openCLErrorID);

    // Verify result
    // DONE: Print out E and verify the result.
    int i = 0;
    for (i = 0; i < N; ++i) 
	{
        float sum = h_A[i] + h_B[i];
        //printf("%f + %f = %f\n", h_A[i], h_B[i], h_C[i]);
        if (fabs(h_C[i] - sum) > 1e-5)
            break;

        float sumMult = h_A[i] + h_B[i] * h_D[i];
        //printf("%f + %f * %f= %f\n", h_A[i], h_B[i],h_D[i], h_E[i]);
        if (fabs(h_E[i] - sumMult) > 1e-5)
            break;
    }
    printf("%s, i = %d\n", (i == N) ? "PASSED" : "FAILED",i);

    Cleanup();
}
示例#27
0
文件: xvalidate.c 项目: burnmg/vfml
int main(int argc, char *argv[]) {
   char command[500];
   int i;

   FILE *input;

   float error;
   float size;

   double errorSum;
   double squaredErrorSum;
   double meanError;

   double sizeSum;
   double squaredSizeSum;
   double meanSize;

   double utimeSum;
   double squaredUtimeSum;
   double meanUtime;

   double stimeSum;
   double squaredStimeSum;
   double meanStime;


   //   float prePruneError, postPruneError;
   //   float prePruneAccuracy, postPruneAccuracy;
   //   int prePruneSize, postPruneSize;

   //   float prePruneAccuracySum, postPruneAccuracySum;
   //   int prePruneSizeSum, postPruneSizeSum;

   struct tms startTime;
   struct tms finishTime;

   _processArgs(argc, argv);

   /* set up the random seed */
   RandomInit();
   if(gSeed != -1) {
      RandomSeed(gSeed);
   } else {
      gSeed = RandomRange(1, 10000);
      printf("Running with seed: %d\n", gSeed);
      RandomSeed(gSeed);
   }


   //   if(gShuffleData) {
   //      sprintf(command, "shuffledata -f %s", gFileStem, i);
   //      gFileStem = "shuffled";
   //      if(gMessageLevel >= 1) {
   //         printf("%s\n", command);
   //      }
   //      system(command);
   //   }


   /* do the folding */
   sprintf(command, "folddata -source %s -f %s -folds %d -seed %d", 
                    gSourceDirectory, gFileStem, gFoldCount, gSeed);
   if(gMessageLevel >= 1) {
      printf("%s\n", command);
   }
   system(command);

   utimeSum = 0;
   squaredUtimeSum = 0;
   stimeSum = 0;
   squaredStimeSum = 0;

   for(i = 0 ; i < gFoldCount ; i++) {
     //      if(gc45Format) {
     //         sprintf(command, "%s -u -f %s%d | grep \"<<\" >> %s", gCommand,
     //                    gFileStem, i, gTmpFileName);
     //      } else {

      sprintf(command, "%s %s%d >> %s", gCommand,
                       gFileStem, i, gTmpFileName);
      if(gMessageLevel >= 1) {
         printf("%s\n", command);
      }

      times(&startTime);
      system(command);
      times(&finishTime);

     #if defined(CYGNUS)
      utimeSum += ((double)(finishTime.tms_utime) - 
                   (double)(startTime.tms_utime)) / 100;
      stimeSum += ((double)(finishTime.tms_stime) - 
                   (double)(startTime.tms_stime)) / 100;

      squaredUtimeSum += (((double)(finishTime.tms_utime) - 
                   (double)(startTime.tms_utime)) / 100) *
                   (((double)(finishTime.tms_utime) - 
                   (double)(startTime.tms_utime)) / 100);
      squaredStimeSum += (((double)(finishTime.tms_stime) - 
                   (double)(startTime.tms_stime)) / 100) *
                   (((double)(finishTime.tms_stime) - 
                   (double)(startTime.tms_stime)) / 100);
     #else
      utimeSum += ((double)(finishTime.tms_cutime) - 
                   (double)(startTime.tms_cutime)) / 100;
      stimeSum += ((double)(finishTime.tms_cstime) - 
                   (double)(startTime.tms_cstime)) / 100;

      squaredUtimeSum += (((double)(finishTime.tms_cutime) - 
                   (double)(startTime.tms_cutime)) / 100) *
                   (((double)(finishTime.tms_cutime) - 
                   (double)(startTime.tms_cutime)) / 100);
      squaredStimeSum += (((double)(finishTime.tms_cstime) - 
                   (double)(startTime.tms_cstime)) / 100) *
                   (((double)(finishTime.tms_cstime) - 
                   (double)(startTime.tms_cstime)) / 100);
     #endif

      if(gMessageLevel >= 1) {
         printf("removing tmp files...\n");
      }

      sprintf(command, "%s%d.names", gFileStem, i);
      remove(command);
      sprintf(command, "%s%d.data", gFileStem, i);
      remove(command);
      sprintf(command, "%s%d.test", gFileStem, i);
      remove(command);


      //      if(gc45Format) {
      //         sprintf(command, "rm %s%d.unpruned %s%d.tree", gFileStem, i,
      //                   gFileStem, i);
      //
      //         if(gMessageLevel >= 1) {
      //            printf("%s\n", command);
      //         }
      //         system(command);
      //      }
   }

   errorSum = 0;
   squaredErrorSum = 0;
   sizeSum = 0;
   squaredSizeSum = 0;

   //   prePruneAccuracySum = 0;
   //   prePruneSizeSum = 0;
   //   postPruneAccuracySum = 0;
   //   postPruneSizeSum  = 0;

   input = fopen(gTmpFileName, "r");
   for(i = 0 ; i < gFoldCount ; i++) {
        //if(gc45Format) {
	// HERE something odd, I need to skip some lines of c45 I think
	//         fgets(buffer, 500, input);
        //   fscanf(input, "%d %*d ( %f %% ) %d %*d( %f %% ) ( %*f %% ) <<",
        //             &prePruneSize, &prePruneError,
        //           &postPruneSize, &postPruneError);
        //  prePruneAccuracy = 100.0 - prePruneError;
        //  postPruneAccuracy = 100.0 - postPruneError;
        //} else {
      fscanf(input, "%f %f", &error, &size);
      if(gMessageLevel >=1 ) {
         printf("Errors %f Size %f\n", error, size);
      }
        //}

      errorSum += error;
      squaredErrorSum += error * error;

      sizeSum += size;
      squaredSizeSum += size * size;
	 //      prePruneAccuracySum += prePruneAccuracy;
	 //      postPruneAccuracySum += postPruneAccuracy;
	 //      prePruneSizeSum += prePruneSize;
	 //      postPruneSizeSum += postPruneSize;
   }

   //   if(gc45Format) {
   // printf("%.3f\t%d\t%.3f\t%d\t%.3f\t%.3f\n",
   //                       prePruneAccuracySum / gFoldCount,
   //                       prePruneSizeSum / gFoldCount,
   //                      postPruneAccuracySum / gFoldCount,
   //                       postPruneSizeSum / gFoldCount,
   //                  (((double)(finishTime.tms_cutime) - 
   //                    (double)(startTime.tms_cutime)) / 100) / gFoldCount,
   //                  (((double)(finishTime.tms_cstime) - 
   //                    (double)(startTime.tms_cstime)) / 100) / gFoldCount);
   //} else {

   meanError = errorSum / gFoldCount;
   meanSize = sizeSum / gFoldCount;
   meanUtime = utimeSum / gFoldCount;
   meanStime = stimeSum / gFoldCount;

   if(!gTableOutput) {
      printf("%.3lf (%.3lf) \t%.3lf (%.3lf) \t%.3f (%.3f) \t%.3f (%.3f)\n",
                      meanError,
                      sqrt((squaredErrorSum / gFoldCount) -
                              meanError * meanError) / sqrt(gFoldCount), 
                      meanSize,
                      sqrt((squaredSizeSum / gFoldCount) -
                              meanSize * meanSize) / sqrt(gFoldCount),
                      meanUtime,
                      sqrt((squaredUtimeSum / gFoldCount) -
                              meanUtime * meanUtime) / sqrt(gFoldCount),
                      meanStime,
                      sqrt((squaredStimeSum / gFoldCount) -
                              meanStime * meanStime) / sqrt(gFoldCount));
   } else {
      printf("%.3lf %.3lf\t", meanError, sqrt((squaredErrorSum / gFoldCount) -
                              meanError * meanError) / sqrt(gFoldCount));

   }
   //}

   sprintf(command, "%s", gTmpFileName);
   remove(command);


   //   if(gShuffleData) {
   //      /* clean up if we shuffled */
   //      sprintf(command, "rm shuffled.names shuffled.data");
   //      if(gMessageLevel >= 1) {
   //         printf("%s\n", command);
   //      }
   //
   //      system(command);
   //   }
   return 0;
}
示例#28
0
文件: sampledata.c 项目: burnmg/vfml
int main(int argc, char *argv[]) {
   char fileName[255];
   FILE *exampleIn, *names;
   ExampleSpecPtr es;
   ExamplePtr e;
   FILE *outputData, *outputTest = NULL;

   _processArgs(argc, argv);

   /* set up the random seed */
   RandomInit();
   if(gSeed != -1) {
      RandomSeed(gSeed);
   }

   /* read the spec file */
   sprintf(fileName, "%s/%s.names", gSourceDirectory, gFileStem);
   /* TODO check that the file exists */
   es = ExampleSpecRead(fileName);
   DebugError(es == 0, "Unable to open the .names file");

   if(!gStdout) {
      /* TODO check that the target directory exists */
      sprintf(fileName, "%s/%s.data", gTargetDirectory, gOutputStem);
      outputData = fopen(fileName, "w");
      DebugError(outputData == 0, "Unable to open output files.");
   } else {
      outputData = stdout;
   }

   if(gOutputTest) {
      /* TODO check that the target directory exists */
      sprintf(fileName, "%s/%s.test", gTargetDirectory, gOutputStem);
      outputTest = fopen(fileName, "w");
      DebugError(outputData == 0, "Unable to open test data output files.");
   }

   if(!gStdin) {
      sprintf(fileName, "%s/%s.data", gSourceDirectory, gFileStem);
      exampleIn = fopen(fileName, "r");
      DebugError(exampleIn == 0, "Unable to open .data file");
   } else {
      exampleIn = stdin;
   }

   e = ExampleRead(exampleIn, es);
   while(e != 0) {
      if(gSamplePercent >= RandomDouble()) {
         ExampleWrite(e, outputData);
      } else if(gOutputTest) {
         ExampleWrite(e, outputTest);
      }

      ExampleFree(e);
      e = ExampleRead(exampleIn, es);
   }
   fclose(exampleIn);


   fclose(outputData);

   /* output the names file */
   /* TODO check that the target directory exists */
   sprintf(fileName, "%s/%s.names", gTargetDirectory, gOutputStem);
   names = fopen(fileName, "w");
   DebugError(names == 0, "Unable to open target names file for output.");

   ExampleSpecWrite(es, names);
   fclose(names);

   return 0;
}