Ruby File Upload Size - ruby

I'm trying to test the size of an upload to validate its size. Outside of the upload algos, simply looking at the temp file is where I'm having the issue. I have a test file on my desktop named test1.png, which is 115 KB.
a = '/users/rich/desktop/test1.png'
s = File.open(a, 'wb')
r = File.size(a)
p r => 0
p s.size => 0
Not sure what I'm doing wrong here, but both resolve to 0. Not true.
How can I get the size of a file?

The problem is the 'w' flag, since it truncates existing file to zero length, so, since you open the file before getting its size, you get 0.
To get the size you could just use the path of the file without using File.open:
a = '/users/rich/desktop/test1.png'
File.size(a)
Or, if you need to create the File object, just use the 'r' flag:
a = '/users/rich/desktop/test1.png'
s = File.open(a, 'r')
Now you can either use File.size(a) or s.size to get the size of the file.

Related

Assign File.readlines[n] to variable

I'm reading a text file which has instructions on each line. I want to assign the text on each line to it's own variable. When I do this, the value returned is nil but when I output the value of readlines[n] it is correct.
e.g.
# Using the variable (incorrect result)
puts current_zone_size
>
e.g.
# Using readlines after variable assignment (incorrect result)
current_zone_size = instructions.readlines[0]
instructions.readlines[0]
>
e.g.
# Using readlines (correct result)
instructions.readlines[0]
> 8 10
This is my code:
instructions = File.open("operator-input.txt", "r")
current_zone_size = instructions.readlines[0]
rover_init_location_orientation = instructions.readlines[1]
rover_movements = instructions.readlines[2]
This is the text in the file being read:
8 10
1 2 E
MMLMRMMRRMML
Edit:
Is the file being closed? Is this the reason I can't assign values from File.readlines[n] to variables if I'm not doing the variable assignment from within a block?
Also, the file will only ever have three lines which is why I'm not using a loop to read the lines.
IO#readlines reads all the lines in the file. It should not come as a surprise that, in order to read all the lines in the file, it has to read the entire file.
So, where is the file pointer after you read the entire file? It is at the end of the file.
What happens if you call IO#readlines the second time, when the file pointer is still at the end of the file? It will start reading at the position of the file pointer, which means it will read an empty file.
Therefore, if you want to do it the way you are doing it, you need to reset the file pointer to the beginning of the file every time you call IO#readlines:
instructions = File.open('operator-input.txt', 'r')
current_zone_size = instructions.readlines[0]
instructions.pos = 0
rover_init_location_orientation = instructions.readlines[1]
instructions.pos = 0
rover_movements = instructions.readlines[2]
Note also that you are leaking resources: you never close the file, so it will only by closed at the earliest by Ruby when the instructions variable gets out of scope and the File instance gets garbage-collected, and at the latest by the OS automatically when your Ruby process exits, which may be a long time later. So, your code should rather be:
instructions = File.open('operator-input.txt', 'r')
current_zone_size = instructions.readlines[0]
instructions.pos = 0
rover_init_location_orientation = instructions.readlines[1]
instructions.pos = 0
rover_movements = instructions.readlines[2]
instructions.close
In general, it is much better to use the block form of File::open, which closes the file handle automatically for you at the end of the block, and also ensures that this happens even in the case of complex control flow, errors, or exceptions:
File.open('operator-input.txt', 'r') do |instructions|
current_zone_size = instructions.readlines[0]
instructions.pos = 0
rover_init_location_orientation = instructions.readlines[1]
instructions.pos = 0
rover_movements = instructions.readlines[2]
end
Note, however, that what you want to do is horribly inefficient: you read the entire file, then take the first line, throw the rest away. Then you read the entire file again, take the second line, throw the rest away. Then you read the entire file again, take the third line, throw the rest away.
It makes much more sense to read the entire file once and then take the lines you need. Something like this:
File.open('operator-input.txt', 'r') do |instructions|
current_zone_size, rover_init_location_orientation, rover_movements =
instructions.readlines
end
However, in the case where all you do is open the file, read all lines, then immediately close it again, you should rather use the IO::readlines method instead of IO#readlines, since it does all three things for you in one call:
current_zone_size, rover_init_location_orientation, rover_movements =
File.readlines('operator-input.txt')
I ended up reading all the lines at once, now I'm able to set each variable outside of a block. Like this:
instructions = File.readlines "operator-input.txt"
current_zone_size = instructions[0]
rover_init_location_orientation = instructions[1]
rover_movements = instructions[2]
e.g.
puts current_zone_size
> 8 10

Create a image file from binary data in Ruby

I am able to access the binary data of a file and store it in a varible like this
s = File.binread("sample_22122015_03.jpg")
bits = s.unpack("B*")[0]
where bits has data like this "101001001010100100......."
However, I want to do some changes and again write the binary data back to a new image, but I am unable to.
I am using
File.open('shipping_label_new.jpg', 'wb') do|f|
f.write(Base64.decode64(bits))
end
but it's not working and I see that the image is corrupt.
Try this code
s = File.binread("test_img.jpg")
bits = s.unpack("B*")
File.open('new_test_img.jpg', 'wb') do|f|
f.write(bits.pack("B*"))
end
The reverse of String.unpack is Array.pack:
:007 > bits = 'abc'.unpack("B*")
=> ["011000010110001001100011"]
:008 > bits.pack("B*")
=> "abc"

Import Multiple Images With Unknown Names

I need to import multiple images (10.000) in Matlab (2013b) from a subdirectory of the predefined directory of Matlab.
I don't know the exact names of the images.
I tried this:
file = dir('C:\Users\user\Documents\MATLAB\train');
NF = length(file);
for k = 1 : NF
img = imread(fullfile('C:\Users\user\Documents\MATLAB\train', file(k).name));
end
But it throws this error though I ran it with the Admin privileges:
Error using imread (line 347)
Can't open file "C:\Users\user\Documents\MATLAB\train\." for reading;
you may not have read permission.
The "dir" command returns the virtual directory elements "." (self directory) and ".." parent, as your error message shows.
A simple fix is to use a more specific dir call, based on your image types, perhaps:
file = dir('C:\Users\user\Documents\MATLAB\train\*.jpg');
Check the output of dir. The first two "files" are . and .., which is similar to the behaviour of the windows dir command.
file = dir('C:\Users\user\Documents\MATLAB\train');
NF = length(file);
for k = 3 : NF
img = imread(fullfile('C:\Users\user\Documents\MATLAB\train', file(k).name));
end
In R2013b you would have to do
file = dir('C:\Users\user\Documents\MATLAB\train\*.jpg');
If you have R2014b with the Computer Vision System Toolbox then you can use imageSet:
images = imageSet('C:\Users\user\Documents\MATLAB\train\');
This will create an object containing paths to all image files in the train directory, regardless of format. Then you can read the i-th image like this:
im = read(images, i);

'File path' use causing program exit in Python 3

I have downloaded a set of html files and saved the file paths which I saved them to in a .txt file. It has each path on a new line. I wanted to look at the first file in the list and then itterate through the whole list, opening the files and extracting data before going on to the next file.
My code works fine with a single path put in directly (for the first file) as:
path = r'C:\path\to\file.html'
and works if I itterate through the text file using:
file_list_fp = r'C:\path\to\file_with_pathlist.txt'
with open(file_list_fp, 'r') as file_list:
for filepath in file_list:
pathend = filepath.find('\n')
path = file[:pathend]
q = open(path, 'r').read()
but it fails when I try getting a single path using either:
with open(file_list_fp, 'r') as file_list:
path_n = file_list.readline()
end = path_n.find('\n')
path_bad1 = path_n[:end]
or:
with open(file_list_fp, 'r') as file_list:
path_bad2 = file_list.readline().split('\n')[0]
With these two my code exits just after that point. I can't figure out why. Any pointers very welcome. (I'm using Python 3.3.1 on windows.)

Cannot open file for output (Matlab)

I am having a problem in matlab and the problem is described as follows:
When i try to read an image ( I have several images) and write them to a specific folder, the matlab triggers an error saying
Error using ==> imwrite at 394
Can't open file "\Temp\\inim735282.4716703009300000.jpg" for writing.
You may not have write permission.
May I know why this is happening?
this is the code where the problem occurs
mkdir('.\Temp');
temp_name = sprintf('%.16f',now);
corner_file = ['\Temp\corners', temp_name,'.in'];
image_file = ['\Temp\inim', temp_name,'.jpg'];
out_file = ['\Temp\out', temp_name,'.desc'];
out_imname = ['\Temp\out', temp_name,'.desc.jpg'];
I tried to change it by omitting
mkdir('.\Temp');
moreoever, i direct the path in the folder to the folder by doing this
binary_path = 'C:\Users\cool\Documents\MATLAB\Experment\experiments\bag_of_words\Temp';
to read and and write in and out of the folder.
Can someone please help me figure out this problem?
Thank you guys
Open MatLAB with admin privileges.
A few suggestions:
To generate a temporary output name use the command tempname.
temp_name = tempname();
To concatenate paths and file names use fullfile.
conrner_file = fullfile( '\', 'Temp', 'corners', [temp_name, '.in'] );
You should be careful not to mix '\Temp' and '.\Temp': as the first is an absolute path, while the second is a relative path to cwd.
EDIT:
How about:
temp_name = tempname(); % temp name + folder name in TEMP
corner_file = [ temp_name,'.in'];
image_file = [ temp_name,'.jpg'];
out_file = [temp_name,'.desc'];
out_imname = [temp_name,'.desc.jpg'];
Is it working now?

Resources