PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label io. Show all posts
Showing posts with label io. Show all posts

Wednesday, November 2, 2022

[FIXED] How do you determine the size of a file in C?

 November 02, 2022     c, file, filesize, io     No comments   

Issue

How can I figure out the size of a file, in bytes?

#include <stdio.h>

unsigned int fsize(char* file){
  //what goes here?
}

Solution

On Unix-like systems, you can use POSIX system calls: stat on a path, or fstat on an already-open file descriptor (POSIX man page, Linux man page).
(Get a file descriptor from open(2), or fileno(FILE*) on a stdio stream).

Based on NilObject's code:

#include <sys/stat.h>
#include <sys/types.h>

off_t fsize(const char *filename) {
    struct stat st; 

    if (stat(filename, &st) == 0)
        return st.st_size;

    return -1; 
}

Changes:

  • Made the filename argument a const char.
  • Corrected the struct stat definition, which was missing the variable name.
  • Returns -1 on error instead of 0, which would be ambiguous for an empty file. off_t is a signed type so this is possible.

If you want fsize() to print a message on error, you can use this:

#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>

off_t fsize(const char *filename) {
    struct stat st;

    if (stat(filename, &st) == 0)
        return st.st_size;

    fprintf(stderr, "Cannot determine size of %s: %s\n",
            filename, strerror(errno));

    return -1;
}

On 32-bit systems you should compile this with the option -D_FILE_OFFSET_BITS=64, otherwise off_t will only hold values up to 2 GB. See the "Using LFS" section of Large File Support in Linux for details.



Answered By - T Percival
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how to check if a file exists based on the files in a directory and indicate which are missing?

 November 02, 2022     file, io, python     No comments   

Issue

how do I check which files are missing from the directory based on a txt of the files I should have?

E.G this is the list of files I should have

A
B
C
D
E
F
G
H
I

But in my directory I only have

A.npy
B.npy
C.npy
D.npy

So I want to do a script that can produce a result.txt like this:

A [exists]
B [exists]
C [exists]
D [exists]
E [does not exist]
F [does not exist]
G [does not exist]
H [does not exist]
I [does not exist]

This is the script I have currently but it doesn't seem to work as it registers all files as "does not exist" :(

import os
import copy
import pandas as pd
import shutil
from pathlib import Path



# read training files.txt 
path_to_file = 'xxxxxxxxxxxxxxxxxx/train_files_CS/all_training_CSmaster.txt'
path = 'xxxxxxxxxxx/train_files_CS'

# list of training npy files in directory
lof = []
for (dirpath, dirnames, filenames) in os.walk(path):
  lof.append(filenames)

lof = [x[:len(x) - 4] for x in lof[0] if x[0] == 'P']
#print(lof)

# new file to be written into
f = open('check_training.txt', 'w')

existing_files = 0
missing_files = 0

trfiles = []
with open(path_to_file) as file:
    for line in file:
        #print(line.rstrip())
        trfiles.append(line)
        
for x in trfiles:    
    if x in lof:
        existing_files+=1
        f.write(x)
        f.write("...[exists] \n")
    else:
        missing_files+=1
        f.write(x)
        f.write("  ...[doesn't exist] \n")
            
f.close()

print("\nthe missing files are:", missing_files,"\n")
print("the existing files are:",existing_files,"\n")

Any help is appreciated, thank you! :)


Solution

Your program works for me after fixing the following two issues:

Issue 1

lof = [x[:len(x) - 4] for x in lof[0] if x[0] == 'P']

I don't think you want to only list files that start with the letter 'P'. Perhaps you left this in by mistake after doing some debugging or something. To get all file names remove the if x[0] == 'P' part:

lof = [x[:len(x) - 4] for x in lof[0]]

Issue 2

with open(path_to_file) as file:
    for line in file:
        #print(line.rstrip())
        trfiles.append(line)

This doesn't remove the line break characters, so you end up with ['a\n', b\n', etc.]` whose elements don't match in the comparisons in the next step. Use this:

with open(path_to_file) as file:
    trfiles = file.read().splitlines()

With these two changes you should find you get the expected output.

Other tips

There are quite a few places where you can make your code more concise and readable by using list comprehensions instead of for loops. E.g.

lof = []
for (dirpath, dirnames, filenames) in os.walk(path):
     lof.append(filenames)

Can be:

lof = [filenames for (dirpath, dirnames, filenames) in os.walk(path)]

Also, x[:len(x) - 4] is not very robust for removing the extension from filenames (as you can have files with 4 letters like .html, .docx, etc.). Use the os library function for splitting extensions:

lof = [os.path.splitext(x)[0] for x in lof[0]]


Answered By - ljdyer
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, October 31, 2022

[FIXED] what does rdstate() return value means?

 October 31, 2022     c++, c++11, eof, io     No comments   

Issue

istream& Read(istream &is)
{
    std::string buf;
    while (is >> buf)       
    {   
        cout << is.eofbit << " " << is.failbit << " " << is.badbit << endl;
        cout << is.rdstate() << endl;
        cout << buf << endl;
    }
    cout << is.eofbit << " " << is.failbit << " " << is.badbit << endl;
    cout << is.rdstate() << endl;
    is.clear();
    cout << is.eofbit << " " << is.failbit << " " << is.badbit << endl;
    cout << is.rdstate() << endl;
    return is;
}

If I input normal characters like "test",the output is 1 2 4 0.
Then I type CTRL+Z (windows),the output is 1 2 4 3 1 2 4 0.

Question : 1. what does rdstate() return value means? (Why does it output 3,not 2? not 1?)

  1. Why did not is.eofbitand is.failbit change after I typed CTRL+Z ? (As C++ Primer 5th Editon says,Reaching end-of-file sets both eofbit and failbit )

Solution

The member std::ios::rdstate() simply returns a combination of the state flags std::ios_base::badbit, std::ios_base::eofbit, and std::ios_base::failbit. Under which conditions which bits gets set isn't entirely consistent but the intent is the following:

  1. std::ios_base::badbit gets set when the stream is in genuinely dysfunctional state and you [probably] won't get anything out of it. For example, this flag is set if there is no stream buffer or when any of the operations on the stream has thrown an exception.
  2. std::ios_base::failbit gets set when an input operation failed, e.g., because a formatted input operation got an unexpected characters. It may be possible to recover from this error by clearing it, ignoring a few characters, and trying again.
  3. std::ios_base::eofbit gets set when [the current] EOF is reached, i.e., when there could be no more characters extracted for now.

Now, in your case you entered a string and reading it was successful, i.e., there are no flags set. Note that reading stopped with the newline character, i.e., you really entered "test\n" and the stream extracted these five characters. When you then ended the stream, the stream reached EOF while trying to read a string, i.e., it set std::ios_base::eofbit and the input failed also setting std::ios_base::failbit.

If you want to see only std::ios_base::eofbit set, you can do so by using a stream which ends with a word right at the end of the stream without any following space character. An easy way to get such a stream is to use an std::istringstream and read from that:

std::istringstream in("test");
Read(in);

Another easy set up is to see std::ios_base::badbit set: you'd just create a stream without a stream buffer, e.g.:

std::istream in(0);
Read(in);

Note that the stream will initially have std::ios_base::badbit set and also get std::ios_base::failbit set upon an attempt to read a character. After clear()ing the std::ios_base::badbit will still be set, though.

To get std::ios_base::failbit set without also having std::ios_base::eofbit set you'll need to prevent it from seeing a non-whitespace character: the input operator for std::string by default start off skipping whitespace and then reads until it either reaches whitespace or EOF and it is successful if it could read at least one non-whitespace character. An approach to do that is to turn automatic skipping of whitespace off, e.g.:

std::istringstream in("test test");
Read(in >> std::noskipws);

BTW, note that there is no guarantee for the values of std::ios_base::eofbit, std::ios_base::failbit, or std::ios_base::badbit other than they can be used as bitmasks in some form.



Answered By - Dietmar Kühl
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, October 30, 2022

[FIXED] How to test EOF on io.Reader in Go?

 October 30, 2022     eof, file, go, io     No comments   

Issue

The Go's io.Reader documentation states that a Read() may return a non zero n value and an io.EOF at the same time. Unfortunately, the Read() method of a File doesn't do that.

When the EOF is reached and some bytes could still be read, the Read method of file returns non zero n and nil error. It is only when we try to read when already at the end of the file that we get back zero n and io.EOF as error.

I couldn't find a simple method to test if the EOF is reached without trying to read data from the file. If we perform a Read() with a buffer of 0 byte, we get back zero n and nil error although we are at the end of file.

To avoid this last read, the only solution I have found is to keep track myself of the number of bytes remaining to read in the file. Is there a simpler solution ?


Solution

You could create a new type, that keeps track of the number of bytes read so far. Then, at EOF check time, you could compare the expected number of bytes read with the actual number of bytes read. Here is a sample implementation. The eofReader keeps track of the number of bytes read and compares it to the file size, in case the underlying type is a file:

package main

// ... imports 

// eofReader can be checked for EOF, without a Read. 
type eofReader struct {
    r     io.Reader
    count uint64
}

// AtEOF returns true, if the number of bytes read equals the file size.
func (r *eofReader) AtEOF() (bool, error) {
    f, ok := r.r.(*os.File)
    if !ok {
        return false, nil
    }
    fi, err := f.Stat()
    if err != nil {
        return false, err
    }
    return r.Count() == uint64(fi.Size()), nil
}

// Read reads and counts.
func (r *eofReader) Read(buf []byte) (int, error) {
    n, err := r.r.Read(buf)
    atomic.AddUint64(&r.count, uint64(n))
    return n, err
}

// Count returns the count.
func (r *eofReader) Count() uint64 {
    return atomic.LoadUint64(&r.count)
}

You could use this type by wrapping any reader in an eofReader:

func main() {
    f, err := os.Open("main.go")
    if err != nil {
        log.Fatal(err)
    }

    r := &eofReader{r: f}
    log.Println(r.AtEOF())

    if _, err = ioutil.ReadAll(r); err != nil {
        log.Fatal(err)
    }

    log.Println(r.AtEOF())
}

// 2016/12/19 03:49:35 false <nil>
// 2016/12/19 03:49:35 true <nil>

Code as gist.



Answered By - miku
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to quit after run IO.read(:stdio, :all) in the Elixir iex?

 October 30, 2022     elixir, elixir-iex, eof, io     No comments   

Issue

I need test some input data flow, and use 'IO.read', but after entering data i can't exit from this mode, CTRL-Z/X/C/D doesn't help (it terminates the whole iex). So how correct EOF command for this mode? Thanks!


Solution

TL;DR: Use ^G followed by j, i [nn] and c [nn].


In both erl and iex shells you always might ^G to enter a “User switch command” mode. Type h for help there.

iex|1 ▶ IO.read :stdio, :all

^G
User switch command
  --> j
    1* {erlang,apply,[#Fun<Elixir.IEx.CLI.1.96155272>,[]]}
  --> i 1
  --> c 1
{:error, :interrupted}

iex|2 ▶

Sidenote: the correct EOF termination would be ^D in all the terminals. I honestly have no idea why it does not work as expected in erl/iex consoles.



Answered By - Aleksei Matiushkin
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to properly using EOF?

 October 30, 2022     c, eof, io     No comments   

Issue

I have question about EOF.

First of all, I am coding a simple program that is coping/printing the user's input.

However, the program copies the EOF also in the output.

For an example, my O.S is Window and my EOF works when I type (Enter -> cntrl + z -> Enter) in order. If I input "Hello" + Enter + EOF key combination, the output prints the weird letter('?') at the end of the copied user input.

enter image description here

How can I get rid of the '?' at the end of the output, and why is it happening?

#include <stdio.h>

void copy(char to[], char from[]);

main()
{
    int i;
    int c;

    char origin[10];
    char copied[10];

    for(i = 0; (c = getchar()) != EOF; ++i)
    {
        origin[i] = c;
    }

    copy(copied, origin);


    for(i = 0; i < 10; i++)
        putchar(copied[i]); 



}

void copy(char to[], char from[])
{
    int i;

    i = 0;
    while((to[i] = from[i]) != '\0')
        i++;
}

Solution

The problem is not related to EOF at all, there are multiple issues in your code leading to potential undefined behavior and unwanted side-effects:

  • The reading loop continues up to the end of file: if the input stream is longer than 10 bytes, the code will cause a buffer overrun, storing bytes beyond the end of the origin array. This is a first case of undefined behavior.
  • The local array origin is uninitialized, so its contents are indeterminate. You do not store a null terminator into it after the bytes read from stdin.
  • In the copy function, you rely on a null terminator to stop the copying loop, but since none was stored there, you access uninitialized contents after all bytes read from stdin have been copied. The null terminator test is combined with the assignment in while((to[i] = from[i]) != '\0'). Accessing uninitialized data has undefined behavior. Furthermore, you keep reading from origin until a null terminator is found, causing further undefined behavior if you end up reading beyond the end of the array, and even more so when writing beyond the end of the copied array.
  • The final loop outputs all 10 elements of the copied array.
  • Even if the array origin may by chance contain null bytes at the end, thus preventing undefined behavior in the copy function. The output loop would still output funny characters as you would not stop at the null terminator, but instead print it to stdout, and again have undefined behavior when you read uninitialized contents at the end of copied after that.
  • Also note that the prototype for main without arguments is int main(void). The syntax you used, without a return type, was common in the '70 and '80s but is now obsolete and should not be used anymore.

Here is a corrected version:

#include <stdio.h>

void copy(char to[], char from[]);

int main(void) {
    int i;
    int c;
    char origin[10];
    char copied[10];

    for (i = 0; i < 10 - 1 && (c = getchar()) != EOF; i++) {
        origin[i] = c;
    }
    origin[i] = '\0';

    copy(copied, origin);

    for (i = 0; copied[i] != '\0'; i++) {
        putchar(copied[i]);
    }

    return 0;
}

void copy(char to[], char from[]) {
    int i;

    i = 0;
    while ((to[i] = from[i]) != '\0')
        i++;
}


Answered By - chqrlie
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] why does ifstream read beyond eof? (even if no file is open) how to stop reading at eof?

 October 30, 2022     c++, eof, fstream, ifstream, io     No comments   

Issue

i was just testing some io safe checks with fstream and noticed i don't get any flags when seeking outside (i expected eof, but i realize flags are only set after io operations?) and when trying to read beyond the file size, i expected it to stop at eof, but it keeps on reading in from some unknown source. and lastly i noticed you don't even need to open a file. do i have to manually apply the math myself so it doesn't read past eof? and how/why/where is it reading past the file?

#include <iostream>
#include <fstream>

void checkErrors(std::ifstream& f){
    std::cout<<"FLAGS: ";
    if(f.good()) std::cout<<"good";
    if(f.rdstate() & f.badbit) std::cout<<"badbit ";
    if(f.rdstate() & f.eofbit) std::cout<<"eofbit ";
    if(f.rdstate() & f.failbit) std::cout<<"failbit ";
    std::cout<<std::endl;
}

int main(){
    std::ifstream file;
//  file.open("abc.txt"); // don't even have to open any file

    file.seekg(100, file.beg); // can seek outside file
    std::cout<<file.tellg()<<std::endl; // 100 (if open else) -1
    checkErrors(file); // FLAGS: good (if open else) failbit

    int size = 200;
    char* data = new char[size];

    file.read(data,size); // can read outside file
    checkErrors(file); // FLAGS: eofbit failbit (if open else) failbit

    for(int i=0; i<size; i++)std::cout<<data[i]; // PSModulePath=C:\Program Files\WindowsPowerShell\Modules;C:\Windows\...

}

Solution

why does ifstream read beyond eof?

I am sure it does not.
Are you asking why the bad() is not true after you move beyond the end?

(even if no file is open) how to stop reading at eof?

If you attempt to read beyond the end of a file then you will get an error. Moving beyond the end by itself is not enough. But an attempt to access the data after you are beyond the end should cause an error.

Well you see to have a bug is here:

file.read(data,size); // can read outside file
for(int i=0; i<size; i++)std::cout<<data[i]; // PSModulePath=C:\Program Files\WindowsPowerShell\Modules;C:\Windows\...

This should be written as:

if (file.read(data, size)) {
    // If you attempt to read and it works then you can print out
    // the data you read otherwise what is the point.

    // Also notice you can't gurantee that you got `size` bytes.
    // You should consult `gcount()` to get the number of characters read.

    for(int i = 0; i < file.gcount(); ++i) {
        std::cout << data[i];
    }
}


Answered By - Martin York
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, October 29, 2022

[FIXED] why does readLong method cause EOFException?

 October 29, 2022     binary, eof, io, java     No comments   

Issue

It throws eof exception in line 10 when I execute the following code. It seems that it cannot execute the readLong method. What should I do?

try (DataOutputStream dataOutputStream=new DataOutputStream(new BufferedOutputStream(new 
FileOutputStream("1.dat")));
         DataInputStream dataInputStream=new DataInputStream(new BufferedInputStream(new 
FileInputStream("C:\\Users\\Asus\\IdeaProjects\\Example" +
                 "\\1.dat")))){
        dataOutputStream.writeLong(123);
        dataOutputStream.writeChar('D');
        dataOutputStream.writeUTF("Hello!");

        System.out.println(dataInputStream.readLong());//exception occurse here
        System.out.println(dataInputStream.readChar());
        System.out.println(dataInputStream.readUTF());
    }catch (IOException e){
        e.printStackTrace();
    }

Solution

the problem you are reading the file before writing on it. when you read the file it was empty. also the data are not saved to the file until the stream is closed. so if you want to read the written values you should close the input stream and then read the file. also be careful that the output stream file path is different than the input stream

here an example:

  try ( DataOutputStream dataOutputStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("1.dat")))) {
        dataOutputStream.writeLong(123);
        dataOutputStream.writeChar('D');
        dataOutputStream.writeUTF("Hello!");
        dataOutputStream.close();
        DataInputStream dataInputStream = new DataInputStream(new BufferedInputStream(new FileInputStream("1.dat")));
        System.out.println(dataInputStream.readLong());
        System.out.println(dataInputStream.readChar());
        System.out.println(dataInputStream.readUTF());
    } catch (IOException e) {
        e.printStackTrace();
    }


Answered By - mss
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How would one generalise `clearerr()` under C++?…

 October 29, 2022     buffer, c++, eof, file-descriptor, io     No comments   

Issue

TL;DR

I am aware that if a program listens for EOF (e.g. ^D) as a sign to stop taking input, e.g. by relying on a conditional like while (std::cin) {...}, one needs to call cin.clear() before standard input can be read from again (readers who'd like to know more, see this table).

I recently learned that this is insufficient, and that the underlying C file descriptors, including stdin, need clearerr() to be run to forget EOF states.

Since clearerr() needs a C-style file descriptor, and C++ operates mainly with std::basic_streambufs and the like (e.g. cin), I want to generalise some code (see below) to run clearerr() on any streambuf's associated C-style file-descriptor, even if that may not be stdin.

EDITS (1&2):
I wonder if stdin is the only ever file-descriptor that behaves like this (needing clearerr() to run) ...?
If it isn't, then the following code should end the question of generalisation (idea pointed out by zkoza in their answer)

As zkoza pointed out in their comment below, stdin is the only file-descriptor that would, logically, ever need such treatment (i.e. clearerr()). Checking whether a given C++ stream is actually really attached to *std::cin.rdbuf() is all that is needed:

std::istream theStream /* some stream with some underlying streambuf */

if (theStream.rdbuf() == std::cin.rdbuf())
    clearerr(stdin);

Background

I'm writing a tool in C++ where I need to get multiple lines of user input, twice.

I know there are multiple ways of getting multiline input (e.g. waiting for double-newlines), but I want to use EOF as the user's signal that they're done — not unlike when you gpg -s or -e.

After much consultation (here, here, and on cppreference.com), I decided to use... (and I quote the third):

[the] idiomatic C++ input loops such as [...]

while(std::getline(stream, string)){...}

Since these rely on std::basic_ios::operator bool to do their job, I ensured that cin.rdstate() was cleared between the first and second user-input instructions (using cin.clear()).

The gist of my code is as follows:

std::istream& getlines (std::basic_istream<char> &theStream,
                        std::vector<std::string> &stack) {
    std::ios::iostate current_mask (theStream.exceptions());
    theStream.exceptions(std::ios::badbit);
    std::string &_temp (*new std::string);
    while (theStream) {
        if (std::getline(theStream, _temp))
            stack.push_back(_temp);   // I'd really like the input broken...
                                      // ... into a stack of `\n`-terminated...
                                      // ... strings each time
    }

    // If `eofbit` is set, clear it
    // ... since std::basic_istream::operator bool needs `goodbit`
    if (theStream.eof())
        theStream.clear(theStream.rdstate()
                        & (std::ios::failbit | std::ios::badbit));
                        // Here the logical AND with
                        // ... (failbit OR badbit) unsets eofbit
    
    // std::getline sets failbit if nothing was extracted
    if (theStream.fail() && !stack.size()) {
        throw std::ios::failure("No input recieved!");
    }
    else if (theStream.fail() && stack.size()) {
        theStream.clear(theStream.rdstate() & std::ios::badbit);
        clearerr(stdin); // 👈 the part which I want to generalise
    }
    
    delete &_temp;
    theStream.exceptions(current_mask);
    return theStream;
}

Solution

This does what you need:

#include <iostream>

int main()
{
    std::cin.sync_with_stdio(true);
    char c = '1', d = '1';
    std::cout << "Enter a char: \n";
    std::cin >> c;
    std::cout << (int)c << "\n";
    std::cout << std::cin.eof() << "\n";
    std::cin.clear();
    clearerr(stdin);
    std::cout << std::cin.eof() << "\n";

    std::cout << "Enter another char: \n";
    std::cin >> d;
    std::cout << (int)d << "\n";
    std::cout << std::cin.eof() << "\n";
}

It works because C++'s std::cin is tied, by default, with C's stdin (so, the first line is actually not needed). You have to modify your code to check if the stream is std::cin and if so, perform clearerr(stdin);

EDIT:

Actually, sync_with_stdio ensures only synchronization between the C and C++ interfaces, but internally they work on the same file descriptors and this may be why clearerr(stdin); works whether or not the interfaces are tied by sync_with_stdio

EDIT2: Does these answer your problem? Getting a FILE* from a std::fstream https://www.ginac.de/~kreckel/fileno/ ?



Answered By - zkoza
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, October 27, 2022

[FIXED] How to get the filename from the Javascript FileReader?

 October 27, 2022     filereader, io, javascript, jquery     No comments   

Issue

I'm using the Javascript FileReader to load an image in the browser:

e = e.originalEvent;
e.dataTransfer.dropEffect = 'copy';
this.documentFile = e.dataTransfer.files[0];

var reader = new FileReader();
reader.onloadend = function () {
    if (reader.result) {
        console.log(reader);
        $('#theImage').attr('src', reader.result);
    }
};
reader.readAsDataURL(this.documentFile);

This works fine. I now want to get the original filename of the image, but I've got no clue how and looking around the internet I can't find anything either?

Does anybody know how I can get the filename through the FileReader? All tips are welcome!


Solution

This is prob not the best solution, BUT it worked for me.

var reader = new FileReader();
reader.fileName = file.name // file came from a input file element. file = el.files[0];
reader.onload = function(readerEvt) {
    console.log(readerEvt.target.fileName);
};

Not the best answer, but a working one.



Answered By - Phreak Nation
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, October 22, 2022

[FIXED] What is the difference between epoll and multiple connect attempt?

 October 22, 2022     c++, io, networking, sockets, tcp     No comments   

Issue

Let's say i have a non blocking TCP client socket. I want to connect to a TCP server. I found that either of the following ways can be used to do so.

int num_of_retry=5;
for(int i=0;i<num_of_retry;i++){
   connect(SOCKET_FD,...);
   sleep(1000ms);
}

and this

connect(SOCKET_FD,...);
epoll_wait(...,5000ms)

What are the main difference in the above two approaches, performance and otherwise?


Solution

In this particular example, the main difference is that sleep() will not exit until the full interval has elapsed, whereas epoll() (and select(), too) will exit sooner if the pending connect operation finishes before the full interval has elapsed.

Otherwise, both examples are blocking the calling thread until something happens (which kind of defeats the purpose of using a non-blocking socket - except that this approach is the only way to implement a timeout with connect()).

Note that in either example, if you call connect() on a socket while it is already working on connecting, connect() will fail with an EALREADY error. If a connect operation times out, you should close() the socket and create a new socket before calling connect() again. And you should wait for epoll() (or select()) to tell you when the operation is finished, don't just call connect() in a loop until it reports something other than EALREADY.



Answered By - Remy Lebeau
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, September 26, 2022

[FIXED] How to get the code display proper rows and columns in .csv format

 September 26, 2022     binaries, bufferedwriter, csv, io, java     No comments   

Issue

I have the following code. The problem is that its displaying back to back in columns. Here is a picture from my excel file:
enter image description here

I want it to start over from next row once the record for single execution is filled from column to column.

Here is my code:

public class panel extends OrderSystem {

               final JTextField items;
               final JTextField number;
               final JTextField cost;
           final JTextField amount;




          public panel() {

              JFrame myFrame = new JFrame();    
                myFrame.setLayout( new FlowLayout() );

                myFrame.setTitle("GUI Demo - ISTE-121");
                myFrame.pack();
                myFrame.setLocation(600,300);
                myFrame.setSize(400,200);
                myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                myFrame.setVisible(true);

          JPanel order = new JPanel();
          order.setLayout(new GridLayout(5,5,2,2));

          myFrame.add(order, BorderLayout.CENTER);

          order.add(new JLabel("Item no:", SwingConstants.RIGHT));
          order.add(items = new JTextField(3));

          order.add(new JLabel("Number of:", SwingConstants.RIGHT));
          order.add(number = new JTextField(3));

          order.add(new JLabel("Cost", SwingConstants.RIGHT));
          order.add(cost = new JTextField(3));

          order.add(new JLabel("Amount owed:", SwingConstants.RIGHT));
          order.add(amount = new JTextField(10));
          amount.setEditable(false);


          JPanel buttons = new JPanel();
          buttons.setLayout(new GridLayout(1,1,2,2));

      myFrame.add(buttons ,BorderLayout.CENTER);

          JButton calculate;
          buttons.add(calculate=new JButton("Calculate"));

          calculate.addActionListener(new ActionListener() 
          {
            @Override
            public void actionPerformed(ActionEvent e) 
            {
                // TODO Auto-generated method stub
                double cost1 = new Double(cost.getText().trim()).doubleValue();
                double number1 = new Double(number.getText().trim()).doubleValue();

                double result =  cost1*number1;
                amount.setText(String.valueOf(result)); 

            }

          });

          JButton save;
          buttons.add(save = new JButton("Save"));

          save.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e) { 



                try{

                        // Assume default encoding.
                        FileWriter fw = new FileWriter("data.csv",true);
                        BufferedWriter bufferedWriter = new BufferedWriter(fw);



                        bufferedWriter.newLine();
                        bufferedWriter.write(',');

                        bufferedWriter.write("\"ItemCode:\""+"\""+ items.getText() +"\""+",");
                        bufferedWriter.write("\"ItemNumber:\""+"\""+number.getText()+"\""+",");
                        bufferedWriter.write("\"ItemCost:\""+"\""+cost.getText()+"\""+",");
                        bufferedWriter.write("\"AmountOwned:\""+"\""+amount.getText()+"\""+",");
                        bufferedWriter.newLine();

                        bufferedWriter.close();


                }  

                    catch(IOException ex) {
                        System.out.println(
                            "Error writing to file '"
                            +  "'");
                        // Or we could just do this:
                        // ex.printStackTrace();
                    }





            }}  
            );



          JButton clear;
          buttons.add(clear=new JButton("Clear"));

          clear.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                 items.setText(null);
                 number.setText(null);
                 cost.setText(null);
                 amount.setText(null);
            }});

          JButton exit;
          buttons.add(exit= new JButton("Exit"));

           exit.addActionListener(new ActionListener()
           {

        @Override
        public void actionPerformed(ActionEvent e) 
        {
            // TODO Auto-generated method stub
          System.exit(0);

        }


           });



           JPanel buttons2 = new JPanel();
              buttons2.setLayout(new GridLayout(1,1,2,2));

          myFrame.add(buttons2 ,BorderLayout.SOUTH);

              JButton load;
              buttons2.add(calculate=new JButton("Load"));

              calculate.addActionListener(new ActionListener() 
              {
                @Override
                public void actionPerformed(ActionEvent e) 
                {
                    // TODO Auto-generated method stub





                }

              });




                  JButton next;
                  buttons2.add(calculate=new JButton("Next>"));

                  calculate.addActionListener(new ActionListener() 
                  {
                    @Override
                    public void actionPerformed(ActionEvent e) 
                    {
                        // TODO Auto-generated method stub





                    }

                  });




                      JButton prev;
                      buttons2.add(calculate=new JButton("<Prev"));

                      calculate.addActionListener(new ActionListener() 
                      {
                        @Override
                        public void actionPerformed(ActionEvent e) 
                        {
                            // TODO Auto-generated method stub





                        }

                      });

    }

}


Solution

Android: How to write newline in CSV file?

Here is written that you can use write.print("\r\n") so use to "\r\n" to make a new line

instead of writing

bufferedWriter.newLine();

you write

bufferedWriter.write("\r\n");

or

bufferedWriter.write("\r");
bufferedWriter.newLine(); 

since bufferedWriter.newLine(); only writes "\n" into your file as far as i know. hope it will help you



Answered By - Gorock
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, September 18, 2022

[FIXED] How to capture prints in real time from function?

 September 18, 2022     io, printing, python, python-3.x, stringio     No comments   

Issue

I want to capture all the prints and do something like return them but keep running the function. I found this method but it only returns the prints when the code is finished.

f = io.StringIO()
with redirect_stdout(f):
    # my code

return f.getvalue()

Is there any method to capture every print in real-time?


Solution

You could write your own file-like object that processes lines of text as it sees them. In the simplest case you only need to supply a write method as shown below. The tricky part is knowing when a "print" call is done. print may call stdout.write several times to do a single print operation. In this example, I did processing whenever a newline is seen. This code does not return interim prints but does allow you to intercept the writes to stdout and process them before returning to the function that calls print.

from contextlib import redirect_stdout
import sys

real_stdout_for_test = sys.stdout

class WriteProcessor:

    def __init__(self):
        self.buf = ""

    def write(self, buf):
        # emit on each newline
        while buf:
            try:
                newline_index = buf.index("\n")
            except ValueError:
                # no newline, buffer for next call
                self.buf += buf
                break
            # get data to next newline and combine with any buffered data
            data = self.buf + buf[:newline_index + 1]
            self.buf = ""
            buf = buf[newline_index + 1:]
            # perform complex calculations... or just print with a note.
            real_stdout_for_test.write("fiddled with " + data)
            
with redirect_stdout(WriteProcessor()):
    print("hello there")
    print("a\nprint\nof\nmany\nlines")
    print("goodbye ", end="")
    print("for now")


Answered By - tdelaney
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, September 15, 2022

[FIXED] How to fill carriage return printed string with whitespaces until end of line?

 September 15, 2022     for-loop, io, printing, python-3.6     No comments   

Issue

I'm trying to do something that should (and perhaps is) quite simple, but I can't find a solution. I'm guessing it may be because I am not able to query the internet properly for this matter.

I am running a code that has a counter that prints an updated % of completion in a line using the carriage return character (\r) to update the same line each time.

The code iterates over a series of nations, for example Canada, USA, Argentina to name three.

When it prints the counter, it also prints the nation. Like this:

k=0
for nation in d.keys():
  k += 1
  num_items = len(d[nation])
  ...
  <do something>
  ...
  sys.stderr.write(f"Processed {k} out of {num_items} for {nation}\r")

Now the issue comes out when Argentina is processed first, then Canada, then USA. The printed strings are:

Processed 147 out of 147 for Argentina
Processed 762 out of 762 for Canadaina
Processed 241 out of 241 for USAadaina

How do I avoid the previous line being featured in the new one while still using the carriage return?


Solution

You can print clean line consisting of spaces and then print your new line, for example:

import random
from time import sleep

countries = ["Argentina", "USA", "Canada"]

for _ in range(10):
    # clear the line
    print(" " * 60, end="\r")

    # print new line
    print(f"Processed XXX for {random.choice(countries)}", end="\r")
    sleep(0.5)

print()


Answered By - Andrej Kesely
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, August 17, 2022

[FIXED] How to get the python interactive shell output of a python code in a variable?

 August 17, 2022     io, output, python, python-interactive     No comments   

Issue

Suppose I have

code = '2+3'

I want to run this code in python interactive shell and get the output string in a variable. So the result of the execution of code would be stored in another variable called output

In this case, the output variable would be '5'.

So is there any way to do this?

def run_code(string):
    # execute the string
    return output # the string that is given by python interactive shell

!!! note:

  exec returns None and eval doesn't do my job

Suppose code = "print('hi')" output should be 'hi'

Suppose code = 'hi' output should be

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'hi' is not defined 

Solution

if you really must run strings as python code, you COULD spawn another python process with the subprocess.Popen function, specify stdout, stderr, stdin each to subprocess.PIPE and use the .communicate() function to retrieve the output.

python takes a -c argument to specify you're giving it python code as the next argument to execute/interpret.

IE python -c "print(5+5)" will output 10 to stdout

IE

proc = subprocess.Popen(["python", "-c", code], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()
print(stdout.decode('utf-8'))


Answered By - JackofSpades
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, July 11, 2022

[FIXED] How to manage several Serial messages in processing

 July 11, 2022     arduino, io, messages, processing     No comments   

Issue

I am reading the UID of my RFID card and storing it in a variable called myUID.

After that I am authorizing to the card with the factory key and read block number 4 (which has been written to earlier) and store it in a string readBlock.

On the Arduino, I print out the variables onto the serial interface like so.

Serial.println(myUID);
Serial.println(readBlock);

On the client side, I use a Java program that reads in serial data. My program uses the Processing Library.

Serial mySerial;
PrintWriter output;

void setup() {
 output = createWriter( "data.txt" );
 mySerial = new Serial( this, Serial.list()[0], 9600 );
 mySerial.bufferUntil('\n');
}

void draw(){
  while (mySerial.available() > 0) {
  String inBuffer = mySerial.readString();   
  if (inBuffer != null)
    output.println(inBuffer); 
  }
}
void keyPressed() { // Press a key to save the data
  output.flush(); // Write the remaining data
  output.close(); // Finish the file
  exit(); // Stop the program
}

Now my data.txt is expected to look like

xxx xxx xxx xxx (uid of card)
00 00 00 00 00 00 00 00 ... (read block from card)

but looks like

237 63 58 1
07
37 37 95
 37 
97 98 50 54 37 5
4 55 102 55 52 
45 98

I have tried several things like readStringUntil('\n'); in the Processing Library but without success.


Solution

For everyone interested, I have fixed the problem myself with many hours of searching Google, so maybe this will help someone in the future:

I could fix it with this code:

import processing.serial.*;
int count = 0;
String input = "";
String fileName = dataPath("SET FILEPATH HERE");

Serial mySerial;

import java.io.*;

void setup() {
  mySerial = new Serial(this, Serial.list()[0], 9600);
  mySerial.bufferUntil('\n');

  File f = new File(fileName);
  if (f.exists()) {
    f.delete();
  }
}

void draw(){}

// listen to serial events happening
void serialEvent(Serial mySerial){
  input = mySerial.readStringUntil('\n'); 
  write(input, count);
  count++;
}

// function for writing the data to the file
void write(String inputString, int counter) {
  // should new data be appended or replace any old text in the file?  
  boolean append = false;

  // just for my purpose, because I have got two lines of serial which need to get written to the file 
  //(Line 1: UID of card, Line 2: Read block of card)  
  if(counter < 2){
    append = true;  
  }
  else{
    count = 0;
  }


  try {
    File file = new File("D:/xampp/htdocs/pizza/src/rfid/data.txt");

    if (!file.exists()) {
      file.createNewFile();
    }

    FileWriter fw = new FileWriter(file, append);
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter pw = new PrintWriter(bw);

    pw.write(inputString + '\n');
    pw.close();
  }
  catch(IOException ioe) {
    System.out.println("Exception ");
    ioe.printStackTrace();
  }
}


Answered By - TheEarthkin
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, May 13, 2022

[FIXED] How to change the use of Common Lisp `with-open-file` so that elements are appended inside a list in a file?

 May 13, 2022     append, common-lisp, file, format, io     No comments   

Issue

I am using Common Lisp (SBCL). Currently, I can write a file appending lists. In order to illustrate, let's first define some variables to make it easier to understand:

(defvar example-1 '((d-1 u-1) (i-1) (i-2)))
(defvar example-2 '((d-2 u-2) (i-1) (i-2)))

Now, in the REPL:

CL-USER> (with-open-file (str "/home/pedro/miscellaneous/misc/tests-output/stack-overflow.lisp"
                         :direction :output
                         :if-exists :append
                         :if-does-not-exist :create)
           (format str " ~S ~%" example-1))
    
CL-USER> (with-open-file (str "/home/pedro/miscellaneous/misc/tests-output/stack-overflow.lisp"
                         :direction :output
                         :if-exists :append
                         :if-does-not-exist :create)
           (format str " ~S ~%" example-2))

If I go to checkout the file "stack-overflow.lisp", I can see:

 ((D-1 U-1) (I-1) (I-2)) 
 ((D-2 U-2) (I-1) (I-2)) 

Ok. This is close to what I want.

However, I would like to have everything wrapped in a list:

(

 ((D-1 U-1) (I-1) (I-2)) 
 ((D-2 U-2) (I-1) (I-2)) 

)

Thus, every time something is "appended" to the file, it should be inside this list. I am changing this because it will make this file easier to read and work on. I will need to filter the elements added.

What do I need to change in with-open-file function to have this output?


Solution

Use a single call to WITH-OPEN-FILE and combine everything into a single list.

(with-open-file (str "/home/pedro/miscellaneous/misc/tests-output/stack-overflow.lisp"
                         :direction :output
                         :if-exists :overwrite
                         :if-does-not-exist :create)
  (pprint (list example-1 example-2) str))

If you want to append to the list every time you write, you need to read the list, append to the list, then overwrite the file with the updated list.

(defun append-to-list-in-file (filename new-item &aux contents) ;;;;
  (setq contents (list)) ;; default in case reading fails
  (ignore-errors
    (with-open-file (str filename :direction :input)
      (setq contents (read str))))
  (setq contents (nconc contents (list new-item)))
  (with-open-file (str filename :direction :output :if-exists :overwrite)
    (write contents :stream str)))


Answered By - Barmar
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing