Cannot push to an array with Node EventEmitter .on method - arrays

Using readLine to read from a file I have:
fs = require 'fs'
readline = require 'readline'
stream = require 'stream'
instream = fs.createReadStream './test.txt'
outstream = new stream
outstream.readable = true
outstream.writable = true
rl = readline.createInterface({input: instream, output: outstream, terminal: false})
arr = []
rl.on 'line', (line) ->
arr.push line
console.log arr
I'm trying to push each line to an array, but the callback in rl.on doesn't seem to complete the push() method, but if I replace the push with console.log it will print every line of the file. I realise there are probably far better ways of achieving the same outcome, but this is an experiment that failed and I don't understand why.
Why is the .on callback not able to push the line to an array?

Related

Error: no method named `parse` found for enum `Result` in the current scope

I'm trying to read a txt file with numbers like 1234 823, I want to convert those into an u16 and .collect() them into a vec. It gives me this error: no method named "parse" found for enum "Result" in the current scope. So how can i fix this?
let file_in = fs::File::open("input.txt").unwrap();
let file_reader = BufReader::new(file_in);
let vec: Vec<u16> = file_reader.lines().map(|x| x.parse::<u16>().unwrap()).collect();
The lines returns an iterator which yield instances of io::Result<String>. So you can unwrap instance to get the contained Ok value.
let vec: Vec<u16> = file_reader
.lines()
.map(|x| x.unwrap().parse::<u16>().unwrap())
.collect();
But this will panic if any of the line is failed to parse(to u16). So you can use filter_map instead.
let vec: Vec<u16> = file_reader
.lines()
.filter_map(|x| x.unwrap().parse::<u16>().ok())
.collect();

Matlab, AppDesigner-Convert image on a good type and use it in "imread" function

I use AppDesigner inMATLAB to show photos with changed RGB. But there is the problem with character of the photo.
When I switch on my own fuction "changeRGB", finally "choosenImage" has 20bytes, class "char" and size(1x10). OK!
There is no problem in using the "function OpenButtonValueChanged". OK!
There is the problem with "function UploadButtonPushed". OK!
ABOUT THE PROBLEM:
When I click button which callback is "function UploadButtonPushed" I get the error:
"Error using imread>parse_inputs (line 502)
The file name or URL argument must be a character
vector or string scalar."
"Error in imread (line 342)
[source, fmt_s, extraArgs, was_cached_fmt_used] =
parse_inputs(cached_fmt, varargin{:});"
WHY?
Because in the "function UploadButtonPushed" my choosenImage has 1977624bytes, class "uint8" and size(681x968x3). So it's too bug for "imread".
WHAT I TRIED:
When in "function OpenButtonValueChanged" I convert a photo, adding "char": (myimage = char(app.clickedImage)); the class of the photo is changing from uint8 to char but the size.
When I use "num2cell", the claas of the photo is changing on "cell" but size and number of bytes are the same- so big. And I get the Error: "Error using imread>parse_inputs (line 502) The file name or URL argument must be a character vector or string scalar."
In my own function "changeRGB" I used "imread(image)" and here is the problem with the size of the photo. Do you know how to get the correct one?
%my own properties in AppDesigner- to use them in different functions
properties (Access = public)
clickedImage;
addR = 1;
addG = 1;
addB = 1;
end
%first function in AppDeesigner
function OpenButtonValueChanged(app, event)
value = app.OpenButton.Value;
[file, howManyFiles] = chooseImagesFromComputer; %myown function
%I load 3 images which are showed as miniatures
myFile1 = imread(file{1});
imshow(myFile1, 'Parent', app.UIAxes1_1);
myFile2 = imread(file{2});
imshow(myFile2, 'Parent', app.UIAxes1_2);
myFile3 = imread(file{3});
imshow(myFile3, 'Parent', app.UIAxes1_3);
%take values of changed RGB from the slider
app.addR = app.SliderR.Value
app.addG = app.SliderG.Value
app.addB = app.SliderB.Value
%work only on one image to change its colors. app.clickedImage, app.addR, app.addG, app.addB are properties at the beginning of the code
app.clickedImage = file{1};
app.clickedImage = changeRGB(app.clickedImage,app.addR,app.addG,app.addB); %changeRGB- my own function- here is the problem. I add it bottom
imshow(app.clickedImage,'Parent',app.UIAxesMain);
end
%second function in AppDesigner
%here is the button to upload color of the photo
function UploadButtonPushed(app, event)
myimage = app.clickedImage;
myimage = changeRGB(myimage,app.addR,app.addG,app.addB);
imshow(myimage);
end
%here is my own function in matlab, not in AppDesigner, which makes problem:
function [changedImage] = changeRGB(choosenImage, addR, addG, addB)
whos
loadedImage = imread(choosenImage);
R = loadedImage(:,:,1); %extract one of the color channels
G = loadedImage(:,:,2);
B = loadedImage(:,:,3);
RBG = cat(3,R,G,B);
R_adj2 = R + addR;
G_adj2 = G + addG;
B_adj2 = B + addB;
changedImage = cat(3,R_adj2,G_adj2,B_adj2);
end
First, you make unnecessary operations in changeRGB
function [changedImage] = changeRGB(choosenImage, addR, addG, addB)
loadedImage = imread(choosenImage);
loadedImage = bsxfun(#sum, loadedImage, reshape([addR, addG, addB], [1 1 3]);
end
Then this function return an array (the modified image) so in UploadButtonPushed(app, event) when you run myimage = app.clickedImage;, you are passing the modified array instead of the image path, that you set here app.clickedImage = changeRGB(app.clickedImage,app.addR,app.addG,app.addB);
So you have to change the design of your variables, because app.clickedImage is saving either the image path, or the image itself. Consider having 2 different variables.
A good advice also is to use matlab debugger which is really good help to find the source of this kind of problems.

NodeJs Readline value put into array

I'm using NodeJS readline module to read from a text file. Its returning every line to the console however I want it to add the returned lines to an array. This is the code I got so far, but its not working. I thought the rd.on acted as a sortof for loop but it doesn't look like it. Any help would be appreciated!
function getinfomation2(){
var firstfile = [];
var secondfile = [];
var countvar = 0;
readline = require('readline');
var rd = readline.createInterface({
input: fs.createReadStream('../FixtureProfiles/CFIP1.json'),
output: process.stdout,
terminal: false
});
// Add fixture details from file to array to later be called
rd.on('line', function(line) {
// if fails console.log(line) returns line in console
firstfile(countvar) = line;
console.log(firstfile(countvar))
countvar = countvar +1;
});
}
firstfile(countvar) = line is incorrect.
Array access operators are [ and ] (see Array docs on MDN).
Also check out Array.push:
firstfile.push(line)

Swift 2 - How can I run a code after an asynchronous method?

I am using the following asynchronous method to get data from Firebase, ref is just my database url. It's working perfectly but I want to run the for loop after the data has been loaded. Because it's an asynchronies method, it starts to get the data from the database and immediately goes to the for loop. Anyway I can get it to wait till the data is downloaded then run the for loop? Please help! :-)
ref.observeSingleEventOfType(.Value, withBlock: { snapshot in
print(snapshot.value.objectForKey("Table")!)
s = snapshot.value.objectForKey("items:")! as! String
Str = s.componentsSeparatedByString(",")
})
for(var i = 0 ; i < Str.count ; i++){
print(Str[i])
}
Your code should probably look something like this:
ref.observeSingleEventOfType(.Value, withBlock: { snapshot in
print(snapshot.value.objectForKey("Table")!)
s = snapshot.value.objectForKey("items:")! as! String
Str = s.componentsSeparatedByString(",")
for part in Str {
print(part)
}
})
I also changed your loop to make it compatible with the next version of Swift.

File to Array in Lua

I was wondering how do I get a line into an array with lua in some sort of function
eg. FileToArray("C:/file.txt")?
I know I can use:
var = io.open("file")
Data = var:read()
But it only returns the 1st line, and no other lines.
Anyone know how to fix this or a different way? I'm new to lua and the file system stuff.
You can pass "*a" to read function, it should read the whole file:
local file = io.open("file-name", "r");
local data = file:read("*a")
And if you want to store each line in an array. Like Jane's solution you can use
io:lines () - which returns iterator function (each call gives you a new line)
local file = io.open("file-name", "r");
local arr = {}
for line in file:lines() do
table.insert (arr, line);
end
local file = io.open("c:\\file.txt")
local tbllines = {}
local i = 0
if file then
for line in file:lines() do
i = i + 1
tbllines[i] = line
end
file:close()
else
error('file not found')
end
See: http://lua-users.org/wiki/IoLibraryTutorial for more information.

Resources