Ejemplo n.º 1
0
int main () {
    double * log = natural_log ();
    double * approx = approximation ();
    double * percent = percentage(log, approx);
    file_output (log, approx, percent);
    return 0;
}
Ejemplo n.º 2
0
static void gcf_compress(){
    char*source;
    char target[LTSMIN_PATHNAME_MAX];
    while((source=HREnextArg())){
        if (is_a_file(source)){
            sprintf(target,"%s.gzf",source);
            stream_t is=file_input(source);
            stream_t os=file_output(target);
            char *code=SSMcall(compression_policy,source);
            DSwriteS(os,code);
            os=stream_add_code(os,code);
            char buf[blocksize];
            for(;;){
                int len=stream_read_max(is,buf,blocksize);
                if (len) stream_write(os,buf,len);
                if(len<blocksize) break;
            }
            stream_close(&is);
            stream_close(&os);
            if (!keep) recursive_erase(source);
        } else if (is_a_dir(source)){
            sprintf(target,"%s.gcf",source);
            archive_t arch_in=arch_dir_open(source,blocksize);
            archive_t arch_out=arch_gcf_create(raf_unistd(target),blocksize,blocksize*blockcount,0,1);
            archive_copy(arch_in,arch_out,compression_policy,blocksize,NULL);
            arch_close(&arch_in);
            arch_close(&arch_out);
            if (!keep) recursive_erase(source);
        } else {
            Abort("source %s is neither a file nor a directory",source);
        }
    }
}
Ejemplo n.º 3
0
int main(int argc, char **argv)
{
    if (argc > 1 && !strcmp(argv[1], "-h")) {
        file_output("README.txt");
        return 0;
    }
    FILE *text_file, *bin_file;
    int text_num = 0, bin_num = 0;
    text_file = fopen(TEXT, "w+");
    bin_file = fopen(BIN, "w");
    text_num = file_filling(text_file, TEXT);
    bin_num = file_filling(bin_file, BIN);
    fclose(bin_file);
    fclose(text_file);   
    file_output(TEXT);
    file_output(BIN);
    numbers_remove(bin_num, text_num);
    file_output(TEXT);
    return 0;
}
Ejemplo n.º 4
0
int main(){
	char A[MAX_N], B[MAX_N], C[MAX_N][2];
	char header[MAX_N];
	FILE *input, *output;
	input = fopen("in.txt", "r");
	output = fopen("out.txt", "w");
	if (!input)
		fail("Failed to open input file. Closing...");
	if (!output)
		fail("Failed to open output file for writing. Closing...");
	file_input(input, header,A,B );
	decart_magic(A,B,C);
	file_output(output, header, C, strlen(A), strlen(B));
	return 0;
};
Ejemplo n.º 5
0
static void gcf_decompress(){
    char*source;
    char target[LTSMIN_PATHNAME_MAX];
    while((source=HREnextArg())){
        if (has_extension(source,".gzf")){
            strncpy(target,source,strlen(source)-4);
            target[strlen(source)-4]=0;
            stream_t is=file_input(source);
            stream_t os=file_output(target);
            char *code=DSreadSA(is);
            is=stream_add_code(is,code);
            char buf[blocksize];
            for(;;){
                int len=stream_read_max(is,buf,blocksize);
                if (len) stream_write(os,buf,len);
                if(len<blocksize) break;
            }
            stream_close(&is);
            stream_close(&os);
            if (!keep) recursive_erase(source);
        } else if (has_extension(source,".gcf")||has_extension(source,".zip")){
            strncpy(target,source,strlen(source)-4);
            target[strlen(source)-4]=0;
            archive_t arch_in;
            if (has_extension(source,".gcf")){
                arch_in=arch_gcf_read(raf_unistd(source));
            } else {
                arch_in=arch_zip_read(source,blocksize);
            }
            archive_t arch_out=arch_dir_create(target,blocksize,force?DELETE_ALL:DELETE_NONE);
            archive_copy(arch_in,arch_out,NULL,blocksize,NULL);
            arch_close(&arch_in);
            arch_close(&arch_out);
            if (!keep) recursive_erase(source);
        } else {
            Abort("source %s does not have known extension",source);
        }
    }
}
//-------------------------------------------------------------//
void main(){
  int i,j,k;

  phi_allocate_memory();
  phi_initialize();
  phi_boundary(phi_old);
  phi_boundary(mu_old);

  lbm_allocate_memory();
  lbm_init();

  for (t = 1; t <= tsteps; t++) {

    if(t < SMOOTH){
      #ifdef PHI
        phi_solver();
      #endif
    }else{
      #ifdef LBM
        lbm_solver();
      #endif
      #ifdef PHI
        phi_solver();
      #endif
    }

    if(t%savet == 0){
      file_output();
    }
    printf("iteration no. %d \n",t);
  }
#ifdef LBM
  lbm_free_memory();
#endif
#ifdef PHI
  phi_free_memory();
#endif
}
Ejemplo n.º 7
0
void MyApp::DoStreamDemo5(wxCommandEvent& WXUNUSED(event))
{
    wxTextCtrl& textCtrl = * GetTextCtrl();

    textCtrl.Clear();
    textCtrl << _T("\nTesting wxFileInputStream's Peek():\n\n");

    char ch;
    wxString str;

    textCtrl.WriteText( _T("Writing number 0 to 9 to wxFileOutputStream:\n\n") );

    wxFileOutputStream file_output( file_name );
    for (ch = 0; ch < 10; ch++)
        file_output.Write( &ch, 1 );

    file_output.Sync();

    wxFileInputStream file_input( file_name );

    ch = file_input.Peek();
    str.Printf( wxT("First char peeked: %d\n"), (int) ch );
    textCtrl.WriteText( str );

    ch = file_input.GetC();
    str.Printf( wxT("First char read: %d\n"), (int) ch );
    textCtrl.WriteText( str );

    ch = file_input.Peek();
    str.Printf( wxT("Second char peeked: %d\n"), (int) ch );
    textCtrl.WriteText( str );

    ch = file_input.GetC();
    str.Printf( wxT("Second char read: %d\n"), (int) ch );
    textCtrl.WriteText( str );

    ch = file_input.Peek();
    str.Printf( wxT("Third char peeked: %d\n"), (int) ch );
    textCtrl.WriteText( str );

    ch = file_input.GetC();
    str.Printf( wxT("Third char read: %d\n"), (int) ch );
    textCtrl.WriteText( str );


    textCtrl << _T("\n\n\nTesting wxMemoryInputStream's Peek():\n\n");

    char buf[] = { 0,1,2,3,4,5,6,7,8,9,10 };
    wxMemoryInputStream input( buf, 10 );

    ch = input.Peek();
    str.Printf( wxT("First char peeked: %d\n"), (int) ch );
    textCtrl.WriteText( str );

    ch = input.GetC();
    str.Printf( wxT("First char read: %d\n"), (int) ch );
    textCtrl.WriteText( str );

    ch = input.Peek();
    str.Printf( wxT("Second char peeked: %d\n"), (int) ch );
    textCtrl.WriteText( str );

    ch = input.GetC();
    str.Printf( wxT("Second char read: %d\n"), (int) ch );
    textCtrl.WriteText( str );

    ch = input.Peek();
    str.Printf( wxT("Third char peeked: %d\n"), (int) ch );
    textCtrl.WriteText( str );

    ch = input.GetC();
    str.Printf( wxT("Third char read: %d\n"), (int) ch );
    textCtrl.WriteText( str );
}
Ejemplo n.º 8
0
void MyApp::DoStreamDemo4(wxCommandEvent& WXUNUSED(event))
{
    wxTextCtrl& textCtrl = * GetTextCtrl();

    wxString msg;

    textCtrl.Clear();
    textCtrl << _T("\nTesting wxStreamBuffer:\n\n");

    // bigger than buffer
    textCtrl.WriteText( _T("Writing 2000x 1 to wxFileOutputStream.\n\n") );

    wxFileOutputStream file_output( file_name );
    for (int i = 0; i < 2000; i++)
    {
        char ch = 1;
        file_output.Write( &ch, 1 );
    }

    textCtrl.WriteText( _T("Opening with a buffered wxFileInputStream:\n\n") );

    wxFileInputStream file_input( file_name );
    wxBufferedInputStream buf_input( file_input );

    textCtrl.WriteText( _T("wxBufferedInputStream.GetLastError() returns: ") );
    switch (buf_input.GetLastError())
    {
        case wxSTREAM_NO_ERROR:      textCtrl.WriteText( _T("wxSTREAM_NO_ERROR\n") ); break;
        case wxSTREAM_EOF:          textCtrl.WriteText( _T("wxSTREAM_EOF\n") ); break;
        case wxSTREAM_READ_ERROR:   textCtrl.WriteText( _T("wxSTREAM_READ_ERROR\n") ); break;
        case wxSTREAM_WRITE_ERROR:  textCtrl.WriteText( _T("wxSTREAM_WRITE_ERROR\n") ); break;
        default: textCtrl.WriteText( _T("Huh?\n") ); break;
    }
    msg.Printf( wxT("wxBufferedInputStream.LastRead() returns: %d\n"), (int)buf_input.LastRead() );
    textCtrl.WriteText( msg );
    msg.Printf( wxT("wxBufferedInputStream.TellI() returns: %d\n"), (int)buf_input.TellI() );
    textCtrl.WriteText( msg );
    textCtrl.WriteText( _T("\n\n") );


    textCtrl.WriteText( _T("Seeking to position 300:\n\n") );

    buf_input.SeekI( 300 );

    textCtrl.WriteText( _T("wxBufferedInputStream.GetLastError() returns: ") );
    switch (buf_input.GetLastError())
    {
        case wxSTREAM_NO_ERROR:      textCtrl.WriteText( _T("wxSTREAM_NO_ERROR\n") ); break;
        case wxSTREAM_EOF:          textCtrl.WriteText( _T("wxSTREAM_EOF\n") ); break;
        case wxSTREAM_READ_ERROR:   textCtrl.WriteText( _T("wxSTREAM_READ_ERROR\n") ); break;
        case wxSTREAM_WRITE_ERROR:  textCtrl.WriteText( _T("wxSTREAM_WRITE_ERROR\n") ); break;
        default: textCtrl.WriteText( _T("Huh?\n") ); break;
    }
    msg.Printf( wxT("wxBufferedInputStream.LastRead() returns: %d\n"), (int)buf_input.LastRead() );
    textCtrl.WriteText( msg );
    msg.Printf( wxT("wxBufferedInputStream.TellI() returns: %d\n"), (int)buf_input.TellI() );
    textCtrl.WriteText( msg );
    textCtrl.WriteText( _T("\n\n") );


    char buf[2000];

    textCtrl.WriteText( _T("Reading 500 bytes:\n\n") );

    buf_input.Read( buf, 500 );

    textCtrl.WriteText( _T("wxBufferedInputStream.GetLastError() returns: ") );
    switch (buf_input.GetLastError())
    {
        case wxSTREAM_NO_ERROR:      textCtrl.WriteText( _T("wxSTREAM_NO_ERROR\n") ); break;
        case wxSTREAM_EOF:          textCtrl.WriteText( _T("wxSTREAM_EOF\n") ); break;
        case wxSTREAM_READ_ERROR:   textCtrl.WriteText( _T("wxSTREAM_READ_ERROR\n") ); break;
        case wxSTREAM_WRITE_ERROR:  textCtrl.WriteText( _T("wxSTREAM_WRITE_ERROR\n") ); break;
        default: textCtrl.WriteText( _T("Huh?\n") ); break;
    }
    msg.Printf( wxT("wxBufferedInputStream.LastRead() returns: %d\n"), (int)buf_input.LastRead() );
    textCtrl.WriteText( msg );
    msg.Printf( wxT("wxBufferedInputStream.TellI() returns: %d\n"), (int)buf_input.TellI() );
    textCtrl.WriteText( msg );
    textCtrl.WriteText( _T("\n\n") );

    textCtrl.WriteText( _T("Reading another 500 bytes:\n\n") );

    buf_input.Read( buf, 500 );

    textCtrl.WriteText( _T("wxBufferedInputStream.GetLastError() returns: ") );
    switch (buf_input.GetLastError())
    {
        case wxSTREAM_NO_ERROR:      textCtrl.WriteText( _T("wxSTREAM_NO_ERROR\n") ); break;
        case wxSTREAM_EOF:          textCtrl.WriteText( _T("wxSTREAM_EOF\n") ); break;
        case wxSTREAM_READ_ERROR:   textCtrl.WriteText( _T("wxSTREAM_READ_ERROR\n") ); break;
        case wxSTREAM_WRITE_ERROR:  textCtrl.WriteText( _T("wxSTREAM_WRITE_ERROR\n") ); break;
        default: textCtrl.WriteText( _T("Huh?\n") ); break;
    }
    msg.Printf( wxT("wxBufferedInputStream.LastRead() returns: %d\n"), (int)buf_input.LastRead() );
    textCtrl.WriteText( msg );
    msg.Printf( wxT("wxBufferedInputStream.TellI() returns: %d\n"), (int)buf_input.TellI() );
    textCtrl.WriteText( msg );
    textCtrl.WriteText( _T("\n\n") );

    textCtrl.WriteText( _T("Reading another 500 bytes:\n\n") );

    buf_input.Read( buf, 500 );

    textCtrl.WriteText( _T("wxBufferedInputStream.GetLastError() returns: ") );
    switch (buf_input.GetLastError())
    {
        case wxSTREAM_NO_ERROR:      textCtrl.WriteText( _T("wxSTREAM_NO_ERROR\n") ); break;
        case wxSTREAM_EOF:          textCtrl.WriteText( _T("wxSTREAM_EOF\n") ); break;
        case wxSTREAM_READ_ERROR:   textCtrl.WriteText( _T("wxSTREAM_READ_ERROR\n") ); break;
        case wxSTREAM_WRITE_ERROR:  textCtrl.WriteText( _T("wxSTREAM_WRITE_ERROR\n") ); break;
        default: textCtrl.WriteText( _T("Huh?\n") ); break;
    }
    msg.Printf( wxT("wxBufferedInputStream.LastRead() returns: %d\n"), (int)buf_input.LastRead() );
    textCtrl.WriteText( msg );
    msg.Printf( wxT("wxBufferedInputStream.TellI() returns: %d\n"), (int)buf_input.TellI() );
    textCtrl.WriteText( msg );
    textCtrl.WriteText( _T("\n\n") );

    textCtrl.WriteText( _T("Reading another 500 bytes:\n\n") );

    buf_input.Read( buf, 500 );

    textCtrl.WriteText( _T("wxBufferedInputStream.GetLastError() returns: ") );
    switch (buf_input.GetLastError())
    {
        case wxSTREAM_NO_ERROR:      textCtrl.WriteText( _T("wxSTREAM_NO_ERROR\n") ); break;
        case wxSTREAM_EOF:          textCtrl.WriteText( _T("wxSTREAM_EOF\n") ); break;
        case wxSTREAM_READ_ERROR:   textCtrl.WriteText( _T("wxSTREAM_READ_ERROR\n") ); break;
        case wxSTREAM_WRITE_ERROR:  textCtrl.WriteText( _T("wxSTREAM_WRITE_ERROR\n") ); break;
        default: textCtrl.WriteText( _T("Huh?\n") ); break;
    }
    msg.Printf( wxT("wxBufferedInputStream.LastRead() returns: %d\n"), (int)buf_input.LastRead() );
    textCtrl.WriteText( msg );
    msg.Printf( wxT("wxBufferedInputStream.TellI() returns: %d\n"), (int)buf_input.TellI() );
    textCtrl.WriteText( msg );
    textCtrl.WriteText( _T("\n\n") );
}
Ejemplo n.º 9
0
void MyApp::DoStreamDemo3(wxCommandEvent& WXUNUSED(event))
{
    wxTextCtrl& textCtrl = * GetTextCtrl();

    textCtrl.Clear();
    textCtrl << _T("\nTesting wxFileInputStream's and wxFFileInputStream's error handling:\n\n");

    char ch,ch2;

    textCtrl.WriteText( _T("Writing number 0 to 9 to wxFileOutputStream:\n\n") );

    wxFileOutputStream file_output( file_name );
    for (ch = 0; ch < 10; ch++)
        file_output.Write( &ch, 1 );

    // Testing wxFileInputStream

    textCtrl.WriteText( _T("Reading 0 to 10 to wxFileInputStream:\n\n") );

    wxFileInputStream file_input( file_name );
    for (ch2 = 0; ch2 < 11; ch2++)
    {
        file_input.Read( &ch, 1 );
        textCtrl.WriteText( _T("Value read: ") );
        textCtrl.WriteText( (wxChar)(ch + '0') );
        textCtrl.WriteText( _T(";  stream.GetLastError() returns: ") );
        switch (file_input.GetLastError())
        {
            case wxSTREAM_NO_ERROR:      textCtrl.WriteText( _T("wxSTREAM_NO_ERROR\n") ); break;
            case wxSTREAM_EOF:          textCtrl.WriteText( _T("wxSTREAM_EOF\n") ); break;
            case wxSTREAM_READ_ERROR:   textCtrl.WriteText( _T("wxSTREAM_READ_ERROR\n") ); break;
            case wxSTREAM_WRITE_ERROR:  textCtrl.WriteText( _T("wxSTREAM_WRITE_ERROR\n") ); break;
            default: textCtrl.WriteText( _T("Huh?\n") ); break;
        }
    }
    textCtrl.WriteText( _T("\n") );

    textCtrl.WriteText( _T("Seeking to 0;  stream.GetLastError() returns: ") );
    file_input.SeekI( 0 );
    switch (file_input.GetLastError())
    {
        case wxSTREAM_NO_ERROR:      textCtrl.WriteText( _T("wxSTREAM_NO_ERROR\n") ); break;
        case wxSTREAM_EOF:          textCtrl.WriteText( _T("wxSTREAM_EOF\n") ); break;
        case wxSTREAM_READ_ERROR:   textCtrl.WriteText( _T("wxSTREAM_READ_ERROR\n") ); break;
        case wxSTREAM_WRITE_ERROR:  textCtrl.WriteText( _T("wxSTREAM_WRITE_ERROR\n") ); break;
        default: textCtrl.WriteText( _T("Huh?\n") ); break;
    }
    textCtrl.WriteText( _T("\n") );

    file_input.Read( &ch, 1 );
    textCtrl.WriteText( _T("Value read: ") );
    textCtrl.WriteText( (wxChar)(ch + _T('0')) );
    textCtrl.WriteText( _T(";  stream.GetLastError() returns: ") );
    switch (file_input.GetLastError())
    {
        case wxSTREAM_NO_ERROR:      textCtrl.WriteText( _T("wxSTREAM_NO_ERROR\n") ); break;
        case wxSTREAM_EOF:          textCtrl.WriteText( _T("wxSTREAM_EOF\n") ); break;
        case wxSTREAM_READ_ERROR:   textCtrl.WriteText( _T("wxSTREAM_READ_ERROR\n") ); break;
        case wxSTREAM_WRITE_ERROR:  textCtrl.WriteText( _T("wxSTREAM_WRITE_ERROR\n") ); break;
        default: textCtrl.WriteText( _T("Huh?\n") ); break;
    }
    textCtrl.WriteText( _T("\n\n") );


    // Testing wxFFileInputStream

    textCtrl.WriteText( _T("Reading 0 to 10 to wxFFileInputStream:\n\n") );

    wxFFileInputStream ffile_input( file_name );
    for (ch2 = 0; ch2 < 11; ch2++)
    {
        ffile_input.Read( &ch, 1 );
        textCtrl.WriteText( _T("Value read: ") );
        textCtrl.WriteText( (wxChar)(ch + '0') );
        textCtrl.WriteText( _T(";  stream.GetLastError() returns: ") );
        switch (ffile_input.GetLastError())
        {
            case wxSTREAM_NO_ERROR:      textCtrl.WriteText( _T("wxSTREAM_NO_ERROR\n") ); break;
            case wxSTREAM_EOF:          textCtrl.WriteText( _T("wxSTREAM_EOF\n") ); break;
            case wxSTREAM_READ_ERROR:   textCtrl.WriteText( _T("wxSTREAM_READ_ERROR\n") ); break;
            case wxSTREAM_WRITE_ERROR:  textCtrl.WriteText( _T("wxSTREAM_WRITE_ERROR\n") ); break;
            default: textCtrl.WriteText( _T("Huh?\n") ); break;
        }
    }
    textCtrl.WriteText( _T("\n") );

    textCtrl.WriteText( _T("Seeking to 0;  stream.GetLastError() returns: ") );
    ffile_input.SeekI( 0 );
    switch (ffile_input.GetLastError())
    {
        case wxSTREAM_NO_ERROR:      textCtrl.WriteText( _T("wxSTREAM_NO_ERROR\n") ); break;
        case wxSTREAM_EOF:          textCtrl.WriteText( _T("wxSTREAM_EOF\n") ); break;
        case wxSTREAM_READ_ERROR:   textCtrl.WriteText( _T("wxSTREAM_READ_ERROR\n") ); break;
        case wxSTREAM_WRITE_ERROR:  textCtrl.WriteText( _T("wxSTREAM_WRITE_ERROR\n") ); break;
        default: textCtrl.WriteText( _T("Huh?\n") ); break;
    }
    textCtrl.WriteText( _T("\n") );

    ffile_input.Read( &ch, 1 );
    textCtrl.WriteText( _T("Value read: ") );
    textCtrl.WriteText( (wxChar)(ch + '0') );
    textCtrl.WriteText( _T(";  stream.GetLastError() returns: ") );
    switch (ffile_input.GetLastError())
    {
        case wxSTREAM_NO_ERROR:      textCtrl.WriteText( _T("wxSTREAM_NO_ERROR\n") ); break;
        case wxSTREAM_EOF:          textCtrl.WriteText( _T("wxSTREAM_EOF\n") ); break;
        case wxSTREAM_READ_ERROR:   textCtrl.WriteText( _T("wxSTREAM_READ_ERROR\n") ); break;
        case wxSTREAM_WRITE_ERROR:  textCtrl.WriteText( _T("wxSTREAM_WRITE_ERROR\n") ); break;
        default: textCtrl.WriteText( _T("Huh?\n") ); break;
    }
    textCtrl.WriteText( _T("\n\n") );

    // Testing wxFFileInputStream

    textCtrl.WriteText( _T("Reading 0 to 10 to buffered wxFFileInputStream:\n\n") );

    wxFFileInputStream ffile_input2( file_name );
    wxBufferedInputStream buf_input( ffile_input2 );
    for (ch2 = 0; ch2 < 11; ch2++)
    {
        buf_input.Read( &ch, 1 );
        textCtrl.WriteText( _T("Value read: ") );
        textCtrl.WriteText( (wxChar)(ch + '0') );
        textCtrl.WriteText( _T(";  stream.GetLastError() returns: ") );
        switch (buf_input.GetLastError())
        {
            case wxSTREAM_NO_ERROR:      textCtrl.WriteText( _T("wxSTREAM_NO_ERROR\n") ); break;
            case wxSTREAM_EOF:          textCtrl.WriteText( _T("wxSTREAM_EOF\n") ); break;
            case wxSTREAM_READ_ERROR:   textCtrl.WriteText( _T("wxSTREAM_READ_ERROR\n") ); break;
            case wxSTREAM_WRITE_ERROR:  textCtrl.WriteText( _T("wxSTREAM_WRITE_ERROR\n") ); break;
            default: textCtrl.WriteText( _T("Huh?\n") ); break;
        }
    }
    textCtrl.WriteText( _T("\n") );

    textCtrl.WriteText( _T("Seeking to 0;  stream.GetLastError() returns: ") );
    buf_input.SeekI( 0 );
    switch (buf_input.GetLastError())
    {
        case wxSTREAM_NO_ERROR:      textCtrl.WriteText( _T("wxSTREAM_NO_ERROR\n") ); break;
        case wxSTREAM_EOF:          textCtrl.WriteText( _T("wxSTREAM_EOF\n") ); break;
        case wxSTREAM_READ_ERROR:   textCtrl.WriteText( _T("wxSTREAM_READ_ERROR\n") ); break;
        case wxSTREAM_WRITE_ERROR:  textCtrl.WriteText( _T("wxSTREAM_WRITE_ERROR\n") ); break;
        default: textCtrl.WriteText( _T("Huh?\n") ); break;
    }
    textCtrl.WriteText( _T("\n") );

    buf_input.Read( &ch, 1 );
    textCtrl.WriteText( _T("Value read: ") );
    textCtrl.WriteText( (wxChar)(ch + '0') );
    textCtrl.WriteText( _T(";  stream.GetLastError() returns: ") );
    switch (buf_input.GetLastError())
    {
        case wxSTREAM_NO_ERROR:      textCtrl.WriteText( _T("wxSTREAM_NO_ERROR\n") ); break;
        case wxSTREAM_EOF:          textCtrl.WriteText( _T("wxSTREAM_EOF\n") ); break;
        case wxSTREAM_READ_ERROR:   textCtrl.WriteText( _T("wxSTREAM_READ_ERROR\n") ); break;
        case wxSTREAM_WRITE_ERROR:  textCtrl.WriteText( _T("wxSTREAM_WRITE_ERROR\n") ); break;
        default: textCtrl.WriteText( _T("Huh?\n") ); break;
    }
}
Ejemplo n.º 10
0
void MyApp::DoStreamDemo2(wxCommandEvent& WXUNUSED(event))
{
    wxTextCtrl& textCtrl = * GetTextCtrl();

    textCtrl.Clear();
    textCtrl << _T("\nTesting wxBufferedStream:\n\n");

    char ch,ch2;

    textCtrl.WriteText( _T("Writing number 0 to 9 to buffered wxFileOutputStream:\n\n") );

    wxFileOutputStream file_output( file_name );
    wxBufferedOutputStream buf_output( file_output );
    for (ch = 0; ch < 10; ch++)
        buf_output.Write( &ch, 1 );
    buf_output.Sync();

    wxFileInputStream file_input( file_name );
    for (ch2 = 0; ch2 < 10; ch2++)
    {
        file_input.Read( &ch, 1 );
        textCtrl.WriteText( (wxChar)(ch + _T('0')) );
    }
    textCtrl.WriteText( _T("\n\n\n") );

    textCtrl.WriteText( _T("Writing number 0 to 9 to buffered wxFileOutputStream, then\n") );
    textCtrl.WriteText( _T("seeking back to #3 and writing 0:\n\n") );

    wxFileOutputStream file_output2( file_name2 );
    wxBufferedOutputStream buf_output2( file_output2 );
    for (ch = 0; ch < 10; ch++)
        buf_output2.Write( &ch, 1 );
    buf_output2.SeekO( 3 );
    ch = 0;
    buf_output2.Write( &ch, 1 );
    buf_output2.Sync();

    wxFileInputStream file_input2( file_name2 );
    for (ch2 = 0; ch2 < 10; ch2++)
    {
        file_input2.Read( &ch, 1 );
        textCtrl.WriteText( (wxChar)(ch + _T('0')) );
    }
    textCtrl.WriteText( _T("\n\n\n") );

    // now append 2000 bytes to file (bigger than buffer)
    buf_output2.SeekO( 0, wxFromEnd );
    ch = 1;
    for (int i = 0; i < 2000; i++)
       buf_output2.Write( &ch, 1 );
    buf_output2.Sync();

    textCtrl.WriteText( _T("Reading number 0 to 9 from buffered wxFileInputStream, then\n") );
    textCtrl.WriteText( _T("seeking back to #3 and reading the 0:\n\n") );

    wxFileInputStream file_input3( file_name2 );
    wxBufferedInputStream buf_input3( file_input3 );
    for (ch2 = 0; ch2 < 10; ch2++)
    {
        buf_input3.Read( &ch, 1 );
        textCtrl.WriteText( (wxChar)(ch + _T('0')) );
    }
    for (int j = 0; j < 2000; j++)
       buf_input3.Read( &ch, 1 );
    textCtrl.WriteText( _T("\n") );
    buf_input3.SeekI( 3 );
    buf_input3.Read( &ch, 1 );
    textCtrl.WriteText( (wxChar)(ch + _T('0')) );
    textCtrl.WriteText( _T("\n\n\n") );

}
Ejemplo n.º 11
0
void MyApp::DoStreamDemo(wxCommandEvent& WXUNUSED(event))
{
    wxTextCtrl& textCtrl = * GetTextCtrl();

    textCtrl.Clear();
    textCtrl << _T("\nTest fstream vs. wxFileStream:\n\n");

    textCtrl.WriteText( _T("Writing to ofstream and wxFileOutputStream:\n") );

    wxSTD ofstream std_file_output( "test_std.dat" );
    wxFileOutputStream file_output( file_name );
    wxBufferedOutputStream buf_output( file_output );
    wxTextOutputStream text_output( buf_output );

    wxString tmp;
    signed int si = 0xFFFFFFFF;
    tmp.Printf( _T("Signed int: %d\n"), si );
    textCtrl.WriteText( tmp );
    text_output << si << _T("\n");
    std_file_output << si << "\n";

    unsigned int ui = 0xFFFFFFFF;
    tmp.Printf( _T("Unsigned int: %u\n"), ui );
    textCtrl.WriteText( tmp );
    text_output << ui << _T("\n");
    std_file_output << ui << "\n";

    double d = 2.01234567890123456789;
    tmp.Printf( _T("Double: %f\n"), d );
    textCtrl.WriteText( tmp );
    text_output << d << _T("\n");
    std_file_output << d << "\n";

    float f = (float)0.00001;
    tmp.Printf( _T("Float: %f\n"), f );
    textCtrl.WriteText( tmp );
    text_output << f << _T("\n");
    std_file_output << f << "\n";

    wxString str( _T("Hello!") );
    tmp.Printf( _T("String: %s\n"), str.c_str() );
    textCtrl.WriteText( tmp );
    text_output << str << _T("\n");
    std_file_output << str.ToAscii() << "\n";

    textCtrl.WriteText( _T("\nReading from ifstream:\n") );

    wxSTD ifstream std_file_input( "test_std.dat" );

    std_file_input >> si;
    tmp.Printf( _T("Signed int: %d\n"), si );
    textCtrl.WriteText( tmp );

    std_file_input >> ui;
    tmp.Printf( _T("Unsigned int: %u\n"), ui );
    textCtrl.WriteText( tmp );

    std_file_input >> d;
    tmp.Printf( _T("Double: %f\n"), d );
    textCtrl.WriteText( tmp );

    std_file_input >> f;
    tmp.Printf( _T("Float: %f\n"), f );
    textCtrl.WriteText( tmp );

    char std_buf[200];
    std_file_input >> std_buf;
    str = wxString::FromAscii(std_buf);
    tmp.Printf( _T("String: %s\n"), str.c_str() );
    textCtrl.WriteText( tmp );

    textCtrl.WriteText( _T("\nReading from wxFileInputStream:\n") );

    buf_output.Sync();

    wxFileInputStream file_input( file_name );
    wxBufferedInputStream buf_input( file_input );
    wxTextInputStream text_input( file_input );

    text_input >> si;
    tmp.Printf( _T("Signed int: %d\n"), si );
    textCtrl.WriteText( tmp );

    text_input >> ui;
    tmp.Printf( _T("Unsigned int: %u\n"), ui );
    textCtrl.WriteText( tmp );

    text_input >> d;
    tmp.Printf( _T("Double: %f\n"), d );
    textCtrl.WriteText( tmp );

    text_input >> f;
    tmp.Printf( _T("Float: %f\n"), f );
    textCtrl.WriteText( tmp );

    text_input >> str;
    tmp.Printf( _T("String: %s\n"), str.c_str() );
    textCtrl.WriteText( tmp );



    textCtrl << _T("\nTest for wxDataStream:\n\n");

    textCtrl.WriteText( _T("Writing to wxDataOutputStream:\n") );

    file_output.SeekO( 0 );
    wxDataOutputStream data_output( buf_output );

    wxInt16 i16 = (unsigned short)0xFFFF;
    tmp.Printf( _T("Signed int16: %d\n"), (int)i16 );
    textCtrl.WriteText( tmp );
    data_output.Write16( i16 );

    wxUint16 ui16 = 0xFFFF;
    tmp.Printf( _T("Unsigned int16: %u\n"), (unsigned int) ui16 );
    textCtrl.WriteText( tmp );
    data_output.Write16( ui16 );

    d = 2.01234567890123456789;
    tmp.Printf( _T("Double: %f\n"), d );
    textCtrl.WriteText( tmp );
    data_output.WriteDouble( d );

    str = _T("Hello!");
    tmp.Printf( _T("String: %s\n"), str.c_str() );
    textCtrl.WriteText( tmp );
    data_output.WriteString( str );

    buf_output.Sync();

    textCtrl.WriteText( _T("\nReading from wxDataInputStream:\n") );

    file_input.SeekI( 0 );
    wxDataInputStream data_input( buf_input );

    i16 = data_input.Read16();
    tmp.Printf( _T("Signed int16: %d\n"), (int)i16 );
    textCtrl.WriteText( tmp );

    ui16 = data_input.Read16();
    tmp.Printf( _T("Unsigned int16: %u\n"), (unsigned int) ui16 );
    textCtrl.WriteText( tmp );

    d = data_input.ReadDouble();
    tmp.Printf( _T("Double: %f\n"), d );
    textCtrl.WriteText( tmp );

    str = data_input.ReadString();
    tmp.Printf( _T("String: %s\n"), str.c_str() );
    textCtrl.WriteText( tmp );
}
Ejemplo n.º 12
0
// This function is based on Pindel's main function.  Todo: integrate with pindel's main structure.
int searchMEImain(ControlState& current_state, Genome& genome, UserDefinedSettings* userSettings) {
    
    // Reset genome before traversal.
    g_genome.reset();
    
    std::ofstream file_output(userSettings->getMEIOutputFilename().c_str());
    MEI_data mei_data;
    int result;
    
    std::string CurrentChrName;
	std::string PreviousChrName = "";
    
    // Loop over BED-regions defined in control state.
	for (unsigned bed_index = 0; bed_index < current_state.IncludeBed.size(); bed_index++) {
		std::string Bed_ChrName = current_state.IncludeBed[bed_index].ChrName;
		unsigned Bed_start = current_state.IncludeBed[bed_index].Start;
		unsigned Bed_end = current_state.IncludeBed[bed_index].End;
        
		const Chromosome* currentChromosome = g_genome.getChr(Bed_ChrName);
        
		if (currentChromosome == NULL) {
			std::cout << "There is no " << CurrentChrName << " in the reference file." << std::endl;
			return 1;
		}
        
		LOG_INFO(*logStream << time_log() << "Dispersed Duplication detection current window: " << Bed_ChrName <<
                 ", " << Bed_start << "--" << Bed_end << std::endl);
        
		CurrentChrMask.resize(currentChromosome->getCompSize());
		for (unsigned int i = 0; i < currentChromosome->getCompSize(); i++) {
            CurrentChrMask[i] = 'N';
		}
        
		userSettings->getRegion()->SetRegion(Bed_ChrName, Bed_start, Bed_end);
		LoopingSearchWindow currentWindow( userSettings->getRegion(), currentChromosome, WINDOW_SIZE, Bed_start, Bed_end );
        
        // loop over one bed region
        do {
            result = load_discordant_reads(mei_data, current_state.bams_to_parse, currentChromosome->getName(),
                                           currentWindow, userSettings);
            if (result) {
                // something went wrong loading the reads, return error code.
                return result;
            }
            
            searchMEIBreakpoints(mei_data, current_state.bams_to_parse, currentChromosome, userSettings);
            cleanup_reads(mei_data.discordant_reads);
            
			currentWindow.next();
        } while (!currentWindow.finished());
	}
    
    // Reset genome for subsequent traversals.
    g_genome.reset();
    
    std::map<int, std::string> seq_name_dictionary = get_sequence_name_dictionary(current_state);
   
    searchMEI(mei_data, genome, seq_name_dictionary, userSettings, current_state, file_output);
    file_output.close();
    return 0;
}
Ejemplo n.º 13
0
int main(int argc, char *argv[]){
    int mode=0;
	int n = 1;
	int t = 3;
	int max = 10;
	double *A;
    double *b;
	double t1;
	FILE* input;
	int ret = 0;
	opterr = 0;
	while ((ret = getopt( argc, argv, "f::g:N:t:")) != -1) {
		switch (ret) {
		case 'N':
			if (optarg == NULL) return -1;
			max = atoi(optarg);
			printf("максимальный выходной размер: %d\n", max);
			break;
		case 't':
			if (optarg == NULL) return -1;
			t = atoi(optarg);
			break;		
		case 'f':
			mode = 1;
			if (optarg != NULL){
				printf ("ввод из файла %s\n", optarg);
				if ((input = fopen (optarg, "r")) == NULL) {
					perror ("невозможно открыть файл\n");
					return -1;
				}
			} else {
				printf ("ввод из файла input.txt\n");
				if ((input = fopen ("input.txt", "r")) == NULL) {
					perror ("невозможно открыть файл\n");
					return -1;
				}
			}
			break;
		case 'g':
			if (mode == 1) break;
			if (optarg == NULL) return -1;
			printf("ввод из функции\n");
			mode = 2;
			n = atoi(optarg);
			printf("матрица размера: %d\n", n);
			break;
		case '?':
			printf("неизвестная опция -%c\n", optopt);
			printf("поддерживаемые опции:\n");
			printf("f - ввод матрицы из файла, являющегося аргументом, или, если аргумента нет, ввод матрицы из файла input.txt;\n");
			printf("g - ввод матрицы из функции. Аргумент функции (обязателен) является размером матрицы;\n");
			printf("t - количество нитей;\n");
			printf("N - максимальный выходной размер.\n");
			return -1;
		}
	}
	printf("Используется %d нитей.\n", t); 	
	if (mode == 1){
		if(fscanf (input, "%d", &n) == 0){
			printf ("не получилось сосканировать размер матрицы из файла\n");	
			return -1;
		}
		A = new double [n*(n+1)];
		if (A == NULL){
			printf("не удалось выделить память под матрицу А\n");
			return -1;
		}
		if (file_input(input, n, A) != 0){
			return -1;
		}			
		fclose(input);
	} else if (mode == 2){
		A = new double [n*(n+1)];
		if (func_input(A, n) != 0){
			return -1;
		}
	} else {
		printf("Требуется запустить программу с какими-либо параметрами\n");
		printf("Поддерживаемые параметры запуска:\n");
		printf("f - ввод матрицы из файла, являющегося аргументом, или, если аргумента нет, ввод матрицы из файла input.txt;\n");
		printf("g - ввод матрицы из функции. Аргумент функции (обязателен) является размером матрицы;\n");
		printf("t - количество нитей;\n");
		printf("N - опция, аргумент которой (обязателен) задает максимальный выходной размер.\n");
		return -1;
	}
	pthread_t *threads = new pthread_t [t];                     //инициализируем нити, выделяем под них память
	if (threads == NULL){
		printf("не удалось выделить память под массив нитей\n");
		return -1;
	}
	b = new double [n];
	if (b == NULL){
		printf("не удалось выделить память под вектор b\n");
		return -1;
	}
    for (int z=0;z<n;z++){
        b[z] = -A[z*(n+1)+n];
    }
   	int MAX_OUTPUT_SIZE = 10;

   	PrintMatrix(n, A, b, MAX_OUTPUT_SIZE);
	delete []b;
	printf("\n");	
	
	FILE *out;
	out = fopen("output.txt", "wr");
	if(out == NULL){
		printf("не могу открыть выходной файл\n");
		return -1;
	}
	
	double *x = new double [n];                    //сюда пишем решение
	if (x == NULL){
		printf("не удалось выделить память под вектор x\n");
		return -1;
	}
	double *E = new double [(n+1)*(n+1)];          //здесь будут храниться базисы
	if (E == NULL){
		printf("не удалось выделить память под матрицу Е\n");
		return -1;
	}
	solve *args = new solve [t];                   //массив структур для нитей
	if (args == NULL){
		printf("не удалось выделить память под аргументы нитей\n");
		return -1;
	}
	double *v = new double [n+1];                  //сюда запоминается вектор для master
	if (v == NULL){
		printf("не удалось выделить память под вектор v\n");
		return -1;
	}
	printf("\nрешение системы...\n");
	t1 = get_full_time();                         //get_full_time для счета астрономического времени
	Solve(n,A,x,t,threads,E,args,v);
	t1 = get_full_time() - t1;
	
	Nevyaska * arg = new Nevyaska [t];
	if (args == NULL){
		printf("не удалось выделить память под структуру значений для невязки\n");
		return -1;
	}
	printf("\n");
	file_output(out,n,max,x);
	printf("время решения системы = %f\n", t1);
	printf("\nподсчет невязки...\n");
	printf("невязка = %e\n", nev(n,A,x,t,threads,arg));
	if (mode == 2){
		printf("норма погрешности = %e\n", error_rate(n,x));
	}	
	delete []A;
	delete []x;
	delete []E;
	delete []v;
	delete []args;
	delete []threads;
	delete []arg;
	fclose(out); 
	return 0;
}
Ejemplo n.º 14
0
int main(int argc, char *argv[]){
    int mode=0;
	int n = 1;
   	int MAX_OUTPUT_SIZE = 5;
	double *A;
	double *values;
	double eps = 1e-10;
	double t1,t2,p;
	double inv1 = 0.;
	double inv2 = 0.;
	FILE* input;
	int ret = 0;
	opterr = 0;
	while ((ret = getopt( argc, argv, "f::g:N:e:")) != -1) {
		switch (ret) {
		case 'e':
			eps = atof(optarg);
			break;
		case 'N':
			MAX_OUTPUT_SIZE = atoi(optarg);
			printf("Максимальный выходной размер: %d\n", MAX_OUTPUT_SIZE);
			break;
		case 'f':
			mode = 1;
			if (optarg != NULL){
				printf ("Ввод из файла %s\n", optarg);
				if ((input = fopen (optarg, "r")) == NULL) {
					perror ("Невозможно открыть файл\n");
					return -1;
				}
			} else {
				printf ("Ввод из файла input.txt\n");
				if ((input = fopen ("input.txt", "r")) == NULL) {
					perror ("Невозможно открыть файл\n");
					return -1;
				}
			}
			break;
		case 'g':
			if (mode == 1){
				break;
			}
			printf("Ввод из функции\n");
			mode = 2;
			n = atoi(optarg);
			printf("Матрица размера: %d\n", n);
			break;
		case '?':
			printf("Неизвестная опция -%c\n", optopt);
			printf("Поддерживаемые опции:\n");
			printf("f - ввод матрицы из файла, являющегося аргументом, или, если аргумента нет, ввод матрицы из файла input.txt;\n");
			printf("g - ввод матрицы из функции. Аргумент функции (обязателен) является размером матрицы;\n");
			printf("N - опция, аргумент которой (обязателен) задает максимальный выходной размер.\n");
			printf("e - точность. Аргумент обязателен.\n");
			return -1;
		}
	}
	if (mode == 1){
		if(fscanf (input, "%d", &n) == 0){
			printf ("не получилось сосканировать размер матрицы из файла\n");
			return -1;
		}
		A = new double [n*n];
		if (A == NULL){
			printf("не удалось выделить память под матрицу А\n");
			return -1;
		}
		if (file_input(input, n, A) != 0){
			return -1;
		}
		fclose(input);
	} else if (mode == 2){
		A = new double [n*n];
		if (A == NULL){
			printf("не удалось выделить память под матрицу А\n");
			return -1;
		}				
		if (func_input(A, n) != 0){
			return -1;
		}
	} else {
		printf("Требуется запустить программу с какими-либо параметрами\n");
		printf("Поддерживаемые параметры запуска:\n");
		printf("f - ввод матрицы из файла, являющегося аргументом, или, если аргумента нет, ввод матрицы из файла input.txt;\n");
		printf("g - ввод матрицы из функции. Аргумент функции (обязателен) является размером матрицы;\n");
		printf("N - опция, аргумент которой (обязателен) задает максимальный выходной размер.\n");
		printf("e - точность. Аргумент обязателен.\n");
		return -1;
	}
	for (int i = 0; i < n; i++){
		inv1 += A[i*n+i];
		for (int j = 0; j < n; j++){
			inv2 += A[i*n+j]*A[i*n+j];
		}
	}
	inv2 = sqrt(inv2);

   	PrintMatrix(n, A, MAX_OUTPUT_SIZE);
	printf("\n");
	FILE *out;
	out = fopen("output.txt", "wr");
	if(out == NULL){
		printf("не могу открыть выходной файл\n");
		return -1;
	}

	values = new double [n];
	if (values==NULL){
		printf("Не удалoсь выделить память под ответ\n");
		delete [] A;
		return -1;
	}

	
	double* sin = new double [n];
	if (sin==NULL){
		printf("Не удалoсь выделить память под синусы\n");
		delete [] A;
		delete [] values;
		return -1;
	}
	double* cos = new double [n];	
	if (cos==NULL){
		printf("Не удалoсь выделить память под косинусы\n");
		delete [] A;
		delete [] values;
		delete [] sin;
		return -1;
	}


	t1 = get_time();
	FindValues(n, A, values, eps, sin, cos);
	t2 = get_time();

	printf("Решение:\n");
	PrintVector(n, values, MAX_OUTPUT_SIZE);
	
	p = 0.;
	for (int i = 0; i < n; i++){
		inv1 -= values[i];
		p += values[i]*values[i];
	}
	inv2 -= sqrt(p);
	printf("\n");
		
	file_output(out,n, values);
	printf("время = %f\n", t2-t1);
	printf("невязка следа матрицы = %e\n", inv1);
	printf("норма вектора собственных значений = %g\n", inv2);
	delete []A;
	delete []values;
	delete []cos;
	delete []sin;
	fclose(out);
	return 0;
}
Ejemplo n.º 15
0
int main(int argc, char *argv[]) {
    int q = 0;
    int n = 1;
    int max = 10;
    double t1,t2;
    int max_matrix_size = 10;
    double *A;
    double *b;
    double *A1;
    FILE* f;
    int ret = 0;
    opterr = 0;
    while ((ret = getopt( argc, argv, "f::g:N:")) != -1) {
        switch (ret) {
        case 'N':
            max = atoi(optarg);
            printf("Max output size: %d\n", max);
            break;
        case 'f':
            q = 1;
            if (optarg != NULL) {
                printf ("Input from file %s\n", optarg);
                if ((f = fopen (optarg, "r")) == NULL) {
                    perror ("Can't open file.\n");
                    return -1;
                }
            } else {
                printf ("Input from file input.txt\n");
                if ((f = fopen ("input.txt", "r")) == NULL) {
                    perror ("Can't open file.\n");
                    return -1;
                }
            }
            break;
        case 'g':
            printf("Input from function in file input_function.cpp\n");
            q = 2;
            n = atoi(optarg);
            printf("Size of matrix: %d\n", n);
            break;
        case '?':
            printf("Unknown option -%c\n", optopt);
            printf("Supported options:\n");
            printf("-f -- Input matrix from the argument file, or, if there is no argument, input matrix from the file input.txt;\n");
            printf("-g -- Input matrix from the function. Argument of this option means size of matrix and it is required;\n");
            printf("-N -- Maximum size of the solution, displayed on the screen. Argument is required.\n");
            return -1;
        }
    }
    if (q == 1) {
        if(fscanf (f, "%d", &n) == 0) {
            printf ("Problem with size of matrix.\n");
            return -1;
        }
        A = new double [n*(n+1)];
        b = new double [n];
        A1 = new double [n*n];
        if (A == NULL || b == NULL || A1 == NULL) {
            printf ("Problem with memory allocation.\n");
            return -1;
        }
        if(file_input(f, n, A, A1, b) != 0) {
            return -1;
        }
        fclose(f);
    } else if (q == 2) {
        A = new double [n*(n+1)];
        b = new double [n];
        if (A == NULL || b == NULL) {
            printf ("Problem with memory allocation.\n");
            return -1;
        }
        if (func_input(A, b, n) != 0) {
            return -1;
        }
    } else {
        printf("It's recommended to run the program with boot options\n");
        printf("Supported options:\n");
        printf("-f -- Input matrix from the argument file, or, if there is no argument, input matrix from the file input.txt;\n");
        printf("-g -- Input matrix from the function. Argument of this option means size of the matrix and it's required;\n");
        printf("-N -- Maximum size of the solution, displayed on the screen. Argument is required.\n");
        printf ("\n\n");
        printf("Choose, where to take the matrix from:\n");
        printf("1 -- from file input.txt\n");
        printf("2 -- from input function in file input_function.cpp\n");
        scanf("%d", &q);
        if (q == 1) {
            f = fopen("input.txt","r");
            if(f == NULL) {
                printf("Can't open input file.\n");
                return -1;
            }
            if(fscanf (f, "%d", &n) == 0) {
                printf("Problem with size of matrix.\n");
                return -1;
            }
            A = new double [n*(n+1)/2];
            b = new double [n];
            A1 = new double [n*n];
            if (A == NULL || b == NULL || A1 == NULL) {
                printf ("Problem with memory allocation.\n");
                return -1;
            }
            if(file_input(f, n, A,A1, b) != 0) {
                return -1;
            }
            fclose(f);
        } else if (q == 2) {
            printf("Size of matrix: ");
            scanf("%d", &n);
            A = new double [n*(n+1)/2];
            b = new double [n];
            if (A == NULL || b == NULL) {
                printf ("Problem with memory allocation.\n");
                return -1;
            }
            if (func_input(A, b, n) != 0) {
                return -1;
            }
        } else {
            printf("Incorrect input way.\n");
            return -1;
        }
    }
    FILE *g;
    g = fopen("output.txt", "wr");
    if(g == NULL) {
        printf("Can't open output file.\n");
        return -1;
    }

    PrintMatrix(n,A,b,max_matrix_size);

    double *Y = new double [n];
    t1 = get_time();

    Solve(A,b,n,Y);

    t2 = get_time();

    file_output(g,n,max,Y);
    printf("Time = %f\n", t2-t1);
    if (q == 1) {
        printf("Residual norm = %e\n", residual_norm1(n,A1,b,Y));
        delete []A1;
    } else if(q == 2) {
        printf("Residual norm = %e\n", residual_norm(n,b,Y));
        printf("Error rate = %e\n", error_rate(n,Y));
    }
    delete []A;
    delete []b;
    delete []Y;
    fclose(g);
    return 0;
}
Ejemplo n.º 16
0
void MyApp::DoStreamDemo7(wxCommandEvent& WXUNUSED(event))
{
    wxTextCtrl& textCtrl = * GetTextCtrl();

    textCtrl.Clear();
    textCtrl.WriteText( _T("\nTesting Ungetch() in buffered input stream:\n\n") );

    char ch = 0;
    wxString str;

    textCtrl.WriteText( _T("Writing number 0 to 9 to wxFileOutputStream...\n\n") );

    wxFileOutputStream file_output( file_name );
    for (ch = 0; ch < 10; ch++)
        file_output.Write( &ch, 1 );

    file_output.Sync();

    textCtrl.WriteText( _T("Reading char from wxBufferedInputStream via wxFileInputStream:\n\n") );

    wxFileInputStream file_input( file_name );
    wxBufferedInputStream buf_input( file_input );

    ch = buf_input.GetC();
    size_t pos = (size_t)buf_input.TellI();
    str.Printf( wxT("Read char: %d. Now at position %d\n\n"), (int) ch, (int) pos );
    textCtrl.WriteText( str );

    textCtrl.WriteText( _T("Reading another char from wxBufferedInputStream:\n\n") );

    ch = buf_input.GetC();
    pos = (size_t)buf_input.TellI();
    str.Printf( wxT("Read char: %d. Now at position %d\n\n"), (int) ch, (int) pos );
    textCtrl.WriteText( str );

    textCtrl.WriteText( _T("Reading yet another char from wxBufferedInputStream:\n\n") );

    ch = buf_input.GetC();
    pos = (size_t)buf_input.TellI();
    str.Printf( wxT("Read char: %d. Now at position %d\n\n"), (int) ch, (int) pos );
    textCtrl.WriteText( str );

    textCtrl.WriteText( _T("Now calling Ungetch( 5 ) from wxBufferedInputStream...\n\n") );

    buf_input.Ungetch( 5 );
    pos = (size_t)buf_input.TellI();
    str.Printf( wxT("Now at position %d\n\n"), (int) pos );
    textCtrl.WriteText( str );

    textCtrl.WriteText( _T("Reading char from wxBufferedInputStream:\n\n") );

    ch = buf_input.GetC();
    pos = (size_t)buf_input.TellI();
    str.Printf( wxT("Read char: %d. Now at position %d\n\n"), (int) ch, (int) pos );
    textCtrl.WriteText( str );

    textCtrl.WriteText( _T("Reading another char from wxBufferedInputStream:\n\n") );

    ch = buf_input.GetC();
    pos = (size_t)buf_input.TellI();
    str.Printf( wxT("Read char: %d. Now at position %d\n\n"), (int) ch, (int) pos );
    textCtrl.WriteText( str );

    textCtrl.WriteText( _T("Now calling Ungetch( 5 ) from wxBufferedInputStream again...\n\n") );

    buf_input.Ungetch( 5 );
    pos = (size_t)buf_input.TellI();
    str.Printf( wxT("Now at position %d\n\n"), (int) pos );
    textCtrl.WriteText( str );

    textCtrl.WriteText( _T("Seeking to pos 3 in wxBufferedInputStream. This invalidates the writeback buffer.\n\n") );

    buf_input.SeekI( 3 );

    ch = buf_input.GetC();
    pos = (size_t)buf_input.TellI();
    str.Printf( wxT("Read char: %d. Now at position %d\n\n"), (int) ch, (int) pos );
    textCtrl.WriteText( str );
}
Ejemplo n.º 17
0
void 
statsrequest(void)
{ 
    int i;
    int columns;
    int columnsread;
    double v[2];
    static char *file_name = NULL;

    /* Vars to hold data and results */
    long n;                /* number of records retained */
    long max_n;

    static double *data_x = NULL;
    static double *data_y = NULL;   /* values read from file */
    long invalid;          /* number of missing/invalid records */
    long blanks;           /* number of blank lines */
    long doubleblanks;     /* number of repeated blank lines */
    long out_of_range;     /* number pts rejected, because out of range */

    struct file_stats res_file;
    struct sgl_column_stats res_x, res_y;
    struct two_column_stats res_xy;
    
    float *matrix;            /* matrix data. This must be float. */
    int nc, nr;               /* matrix dimensions. */
    int index;

    /* Vars for variable handling */
    static char *prefix = NULL;       /* prefix for user-defined vars names */

    /* Vars that control output */
    TBOOLEAN do_output = TRUE;     /* Generate formatted output */ 
    
    c_token++;

    /* Parse ranges */
    AXIS_INIT2D(FIRST_X_AXIS, 0);
    AXIS_INIT2D(FIRST_Y_AXIS, 0);
    parse_range(FIRST_X_AXIS);
    parse_range(FIRST_Y_AXIS);

    /* Initialize */
    columnsread = 2;
    invalid = 0;          /* number of missing/invalid records */
    blanks = 0;           /* number of blank lines */
    doubleblanks = 0;     /* number of repeated blank lines */
    out_of_range = 0;     /* number pts rejected, because out of range */
    n = 0;                /* number of records retained */
    nr = 0;               /* Matrix dimensions */
    nc = 0;
    max_n = INITIAL_DATA_SIZE;
    
    free(data_x);
    free(data_y);
    data_x = vec(max_n);       /* start with max. value */
    data_y = vec(max_n);

    if ( !data_x || !data_y )
      int_error( NO_CARET, "Internal error: out of memory in stats" );

    n = invalid = blanks = doubleblanks = out_of_range = nr = 0;

    /* Get filename */
    free ( file_name );
    file_name = try_to_get_string();

    if ( !file_name )
	int_error(c_token, "missing filename");

    /* ===========================================================
    v923z: insertion for treating matrices 
      EAM: only handles ascii matrix with uniform grid,
           and fails to apply any input data transforms
      =========================================================== */
    if ( almost_equals(c_token, "mat$rix") ) {
	df_open(file_name, 3, NULL);
	index = df_num_bin_records - 1;
	
	/* We take these values as set by df_determine_matrix_info
	See line 1996 in datafile.c */
	nc = df_bin_record[index].scan_dim[0];
	nr = df_bin_record[index].scan_dim[1];
	n = nc * nr;
	
	matrix = (float *)df_bin_record[index].memory_data;
	
	/* Fill up a vector, so that we can use the existing code. */
	if ( !redim_vec(&data_x, n ) ) {
	    int_error( NO_CARET, 
		   "Out of memory in stats: too many datapoints (%d)?", n );
	}
	for( i=0; i < n; i++ ) {
	    data_y[i] = (double)matrix[i];  
	}
	/* We can close the file here, there is nothing else to do */
	df_close();
	/* We will invoke single column statistics for the matrix */
	columns = 1;

    } else { /* Not a matrix */
	columns = df_open(file_name, 2, NULL); /* up to 2 using specs allowed */

	if (columns < 0)
	    int_error(NO_CARET, "Can't read data file"); 

	if (columns > 2 )
	    int_error(c_token, "Need 0 to 2 using specs for stats command");

	/* If the user has set an explicit locale for numeric input, apply it
	   here so that it affects data fields read from the input file. */
	/* v923z: where exactly should this be? here or before the matrix case? 
	 * I think, we should move everything here to before trying to open the file. 
	 * There is no point in trying to read anything, if the axis is logarithmic, e.g.
	 */
	set_numeric_locale();   

	/* For all these below: we could save the state, switch off, then restore */
	if ( axis_array[FIRST_X_AXIS].log || axis_array[FIRST_Y_AXIS].log )
	    int_error( NO_CARET, "Stats command not available with logscale active");

	if ( axis_array[FIRST_X_AXIS].datatype == DT_TIMEDATE || axis_array[FIRST_Y_AXIS].datatype == DT_TIMEDATE )
	    int_error( NO_CARET, "Stats command not available in timedata mode");

	if ( polar )
	    int_error( NO_CARET, "Stats command not available in polar mode" );

	if ( parametric )
	    int_error( NO_CARET, "Stats command not available in parametric mode" );

	/* The way readline and friends work is as follows:
	 - df_open will return the number of columns requested in the using spec
	   so that "columns" will be 0, 1, or 2 (no using, using 1, using 1:2)
	 - readline always returns the same number of columns (for us: 1 or 2)
	 - using 1:2 = return two columns, skipping lines w/ bad data
	 - using 1   = return sgl column (supply zeros (0) for the second col)
	 - no using  = return two columns (first two), fail on bad data 

	 We need to know how many columns to process. If columns==1 or ==2
	 (that is, if there was a using spec), all is clear and we use the
	 value of columns. 
	 But: if columns is 0, then we need to figure out the number of cols
	 read from the return value of readline. If readline ever returns
	 1, we take that; only if it always returns 2 do we assume two cols.
	 */
  
	while( (i = df_readline(v, 2)) != DF_EOF ) {
	    columnsread = ( i > columnsread ? i : columnsread );

	    if ( n >= max_n ) {
		max_n = (max_n * 3) / 2; /* increase max_n by factor of 1.5 */
	  
		/* Some of the reallocations went bad: */
		if ( 0 || !redim_vec(&data_x, max_n) || !redim_vec(&data_y, max_n) ) {
		    df_close();
		    int_error( NO_CARET, 
		       "Out of memory in stats: too many datapoints (%d)?",
		       max_n );
		} 
	    } /* if (need to extend storage space) */

	    switch (i) {
	    case DF_MISSING:
	    case DF_UNDEFINED:
	      /* Invalids are only recognized if the syntax is like this:
		     stats "file" using ($1):($2)
		 If the syntax is simply:
		     stats "file" using 1:2
		 then df_readline simply skips invalid records (does not
		 return anything!) Status: 2009-11-02 */
	      invalid += 1;
	      continue;
	      
	    case DF_FIRST_BLANK: 
	      blanks += 1;
	      continue;

	    case DF_SECOND_BLANK:      
	      blanks += 1;
	      doubleblanks += 1;
	      continue;
	      
	    case 0:
	      int_error( NO_CARET, "bad data on line %d of file %s",
	  		df_line_number, df_filename ? df_filename : "" );
	      break;

	    case 1: /* Read single column successfully  */
	      if ( validate_data(v[0], FIRST_Y_AXIS) )  {
		data_y[n] = v[0];
		n++;
	      } else {
		out_of_range++;
	      }
	      break;

	    case 2: /* Read two columns successfully  */
	      if ( validate_data(v[0], FIRST_X_AXIS) &&
		  validate_data(v[1], FIRST_Y_AXIS) ) {
		data_x[n] = v[0];
		data_y[n] = v[1];
		n++;
	      } else {
		out_of_range++;
	      }
	      break;
	    }
	} /* end-while : done reading file */
	df_close();

	/* now resize fields to actual length: */
	redim_vec(&data_x, n);
	redim_vec(&data_y, n);

	/* figure out how many columns where really read... */
	if ( columns == 0 )
	    columns = columnsread;

    }  /* end of case when the data file is not a matrix */

    /* Now finished reading user input; return to C locale for internal use*/
    reset_numeric_locale();

    /* PKJ - TODO: similar for logscale, polar/parametric, timedata */

    /* No data! Try to explain why. */
    if ( n == 0 ) {
	if ( out_of_range > 0 )
	    int_error( NO_CARET, "All points out of range" );
	else 
	    int_error( NO_CARET, "No valid data points found in file" );
    }

    /* Parse the remainder of the command line: 0 to 2 tokens possible */
    while( !(END_OF_COMMAND) ) {
	if ( almost_equals( c_token, "out$put" ) ) {
		do_output = TRUE;
		c_token++;

	} else if ( almost_equals( c_token, "noout$put" ) ) {
		do_output = FALSE;
		c_token++;

	} else if ( almost_equals(c_token, "pre$fix") 
	       ||   equals(c_token, "name")) {
	    c_token++;
	    free ( prefix );
	    prefix = try_to_get_string();
	    if (!legal_identifier(prefix) || !strcmp ("GPVAL_", prefix))
		int_error( --c_token, "illegal prefix" );

	}  else {
	    int_error( c_token, "Expecting [no]output or prefix");
	}

    }

    /* Set defaults if not explicitly set by user */
    if (!prefix)
	prefix = gp_strdup("STATS_");
    i = strlen(prefix);
    if (prefix[i-1] != '_') {
	prefix = gp_realloc(prefix, i+2, "prefix");
	strcat(prefix,"_");
    }

    /* Do the actual analysis */
    res_file = analyze_file( n, out_of_range, invalid, blanks, doubleblanks );
    if ( columns == 1 ) {
	res_y = analyze_sgl_column( data_y, n, nr );
    }

    if ( columns == 2 ) {
	/* If there are two columns, then the data file is not a matrix */
	res_x = analyze_sgl_column( data_x, n, 0 );
	res_y = analyze_sgl_column( data_y, n, 0 );
	res_xy = analyze_two_columns( data_x, data_y, res_x, res_y, n );
    }

    /* Store results in user-accessible variables */
    /* Clear out any previous use of these variables */
    del_udv_by_name( prefix, TRUE );

    file_variables( res_file, prefix );

    if ( columns == 1 ) {
	sgl_column_variables( res_y, prefix, "" );
    }
    
    if ( columns == 2 ) {
	sgl_column_variables( res_x, prefix, "_x" );
	sgl_column_variables( res_y, prefix, "_y" );
	two_column_variables( res_xy, prefix );
    }

    /* Output */
    if ( do_output ) {
	file_output( res_file );
	if ( columns == 1 )
	    sgl_column_output( res_y, res_file.records );
	else
	    two_column_output( res_x, res_y, res_xy, res_file.records );
    }

    /* Cleanup */
      
    free(data_x);
    free(data_y);

    data_x = NULL;
    data_y = NULL;
    
    free( file_name );
    file_name = NULL;
    
    free( prefix );
    prefix = NULL;
}
void
FetcherScholarshipPositions::fetch()
{
    const std::string now = "spgmail" + currentDateTime();
    std::size_t count = 0;
    
    std::ifstream file_input(m_FilenameHtmlScholarshipPositionsGmail.c_str());
    std::ofstream file_output(m_FilenameInputScholarshipPositionsGmail.c_str());
    
    if (!file_input.is_open())
    {
        std::cerr << "Cannot open file \"" << m_FilenameHtmlScholarshipPositionsGmail << "\" for reading!" << std::endl;
        return;
    }
    
    if (!file_output.is_open())
    {
        std::cerr << "Cannot open file \"" << m_FilenameInputScholarshipPositionsGmail << "\" for writing!" << std::endl;
        return;
    }
    
    std::string content_gmail((std::istreambuf_iterator<char>(file_input)), std::istreambuf_iterator<char>());
    
    HTML::ParserDom parser;
    tree<HTML::Node> dom = parser.parseTree(content_gmail);
    
    tree<HTML::Node>::iterator beg = dom.begin();
    tree<HTML::Node>::iterator end = dom.end();
    
    std::string ct = "";
    std::string link_title_str = "";
    std::string deadline_str = "";
    
    tree<HTML::Node>::iterator previous_bold_it = NULL;
    
    for (tree<HTML::Node>::iterator it = beg; it != end; ++it)
    {
        if (it->tagName() == "strong" || it->tagName() == "b")
        {
            ct = it->content(content_gmail);
            
            // 20150908:
            // The link to the scholarship can be in the text content of this node or the previous node with tag <strong>.
            //
            if (ct == "Provided by:")
            {
                link_title_str = it->content(content_gmail);
                if (link_title_str.find("href=\"") == std::string::npos) link_title_str = previous_bold_it->content(content_gmail);
                assert(link_title_str.find("href=\"") != std::string::npos);
            }
            if (ct.find("Application Deadline") != std::string::npos)
            {
                tree<HTML::Node>::iterator jt = it;
                
                // To deal with the following form:
                // <strong><span style="background: white">Application Deadline</span></strong>
                // <span style="background: white">&nbsp;22 September 2014</span><br />
                ++jt;
                ++jt;
                ++jt;
                deadline_str = jt->content(content_gmail);
                
                //
                // To deal with the following form:
                // <strong>Application Deadline</strong> 31 October 2014<br />
                //
                if (deadline_str == "")
                {
                    for (jt = it; jt != end; ++jt)
                    {
                        if (jt->tagName() == "br")
                        {
                            jt--;
                            deadline_str = jt->text();
                            break;
                        }
                    }
                }
                
                fetchOneScholarshipPosition(file_output, now, count,
                                            link_title_str, deadline_str);
            }
            previous_bold_it = it;
        }
    }
    
    DBGINFO("Fetched " << count << " scholarship items from ScholarshipPositions-Gmail!")
}