Get readline input as an array - arrays

I'm doing a programming challenge right now but I'm struggling with getting the input right. There is no feedback on my output, only "error" which makes it really hard to debug for me. Here is the input:
4 2
1 4
2 9
4 7
5 8
and I want to collect it like this:
[4, 2, 1, 4, 2, 9, 4, 7, 5, 8];
The test environment tells me to work with the input like this:
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.on('line', (line) => {
var nums = line.split(' ');
/*Solve the test case and output the answer*/
});
How ever I must be getting the wrong array for my nums variable.I tried a bunch of approaches (splitting by /n and whitespaces, iterating with for loop and push... working with rl.close...) but as there is virtually no feedback on my input I am getting kind of desperate here. A simple interface which tells me my program output would help...
SOLUTION
var nums = [];
rl.on("line", line => {
let newLine = line.split(" ");
newLine.map(line => nums.push(line));
});
rl.on("close", function() {
console.log(nums)
});
It was possible for me to debug via the terminal once I got the input right.

The 'line' event would be emitted every time when rl read a new line, so you should just declare your nums outside of the callback function of the listener. Something like this:
...
var sums = [];
rl.on('line', (line) => {
let newNumbers = line.split(' '); // [4, 2]
sums.concat(newNumbers);
});
...
You may want to understand how event emitter and event listener work in JavaScript.
I think there is nothing for you even you register an 'error' event listener because everything is working as expected. And I believe there must be an event like 'end' or 'closed' which would be emitted after rl read all content of the input, and you can console.log your sums array there, I believe you can get your expected result.
You shouldn't handle the sums array right after the closing brackets, JavaScript is asynchronous, so those codes would be executed before all of the lines are read. If there is a method like rl.close you should call it in the situation like:
rl.on('line', (line) => {
...
if (line === undefined) { // or any terminal character which createInterface would return.
rl.close();
}
});
And I believe rl.close() will emit the event like what I said above , something like 'end' or 'closed', put the code to handle the final sums there.

A simple interface which tells me my program output would help...
You can run your nodejs application with nodejs! You can download and install it, and then in your terminal node yourjscodefile.js. When you console.log(variable); it will output in the terminal.

Related

How to use setInterval and setTimeout with React hooks

I want to loop through an array of strings
When a new string, from the array, is selected I want to print out a
substring of the selected string every 0.1 second
After the entire string is printed I want to pause and then select the
next string in the array
Repeat
eg ['one', 'two']
output:
o
on
one
// pause 1 second
t
tw
two
// pause 1 second
o
on
one
// pause 1 second
I have tried this but it only loops through once
useEffect(() => {
let i = 0
function increment() {
i++
console.log(i)
}
const incrementTimer = setInterval(increment, 100)
setInterval(() => {
clearInterval(incrementTimer)
}, 1000)
}, [])
I created a codesandbox link: https://codesandbox.io/s/recursing-bash-hkmqrc?file=/src/App.js
This is done by rxjs as you are dealing with time related actions. rxjs is the best tool. After you reload the page, it will start to log values as you expect in 1s.
Can you please let me know if the result is what you want? Thanks.

defining array in pug.js

I can't understand the difference. What is wrong here? Whenever I write it like this in pug—
-const users =[
{
"key":"Property",
"key":"Property",
}];
—it throws an error. And when I write it like this—
-
const users =[
{
"key":"Property",
"key":"Property",
}];
—it does not throw errors and gives the right result.
Please help me if you know the difference.
Unbuffered code in Pug must either all be on one line, or it must all be indented beneath a hyphen (-), with the hyphen on a line by itself.
// this is ok
- let users = ['foo', 'bar']
// this is also ok
-
let users = [
'foo',
'bar'
]
// this isn't ok
- let users = [
'foo',
'bar'
]
Placing content beside the hyphen signals to Pug that the code is all on one line, and it doesn't treat the next line as code, even if it's indented.

Can't add anything correctly to useState array?

I'm new in React. I writed that code by following a tutorial.
I tried many ways but couldn't add new arrays correctly into useState array.
function TodoApp(){
const [liste, setListe] = useState( [] );
function listeyeEkle(e) {
console.log(e); // {yazi: "First", id: 0} It's great here, no problems.
setListe( [e, ...liste] ) // Console log in Picture 1
setListe( e ); // Console log in Picture 2
console.log(liste);
}
Picture 1
Picture 2
Something going wrong and it's adding a empty object into array??
Do you have any idea?
Thanks!
The way you wrote it, you are setting the correct array first:
setListe( [e, ...liste] )
Afterwards you are setting the state to the value of the inputs element:
setListe( e )
I think you should remove this line? Then it will work! But might not show up in console.log(liste), due to the async nature of setState()!

how many items can a array handle node.js

I am trying to put objects to array based on txt file that has around 500.000 lines or more
I am using require('readline') to handle it, but the processing "pause" for yourself when achieve line 470000(e.g) without errors, warnings, notices...
this is examplo of my code ( the original code fill the dataRow object then it "pauses" when achieve line 411000):
let myList = [];
let lineReader = require('readline').createInterface({
input: require('fs').createReadStream(filePath).pipe(iconv.decodeStream('latin1'))
});
lineReader.on('line', function (line) {
// here there are a lot more fields, but I have to cut off for this example
let dataRow = JSON.parse('{"Agencia_Cobranca":"","Aliquota_ICMS":""}');
myList.push(dataRow);
//this if is only to follow what is happen
if( myList.length %10000 == 0 || myList.length>420000) {
console.log(" myList executed: ",myList.length, ' - ', JSON.stringify( myList[myList.length-1] ).length, ' - ' ,new Date() );
}
}).on('close',function(){
console.log('finished');
process.exit(0);
});
I am using this command line to execute
node --max-old-space-size=8192 teste
Welll... this is the result, the screen just stay this way when achieve this line... never ends and without errors :(
Your stack/Ram is probably full and erroring out in a weird way. I would recommend if at all possible to make your program more memory efficient, do everything you need to do with a line as you read it and then discard it. Storing it all in memory is never going to be a solution.
In NodeJs (javascript too) maximum size of an array object is 2^32 -1. Just try to execute this in a nodejs application
console.log(new Array(4294967295))
try {
console.log(new Array(4294967296))
} catch(err){
console.log(err);
}
Consider using database if you work with that much data. Store it in a table then query the data you need to work with would be more efficient.

Value is not an array ref error

I have a list of checkboxes. I am trying to pass the list of selected checkboxes to a perl script. I am obtaining the list of checkboxes using the folliwng code :
function exec(){
var checkedValue = "";
var inputElements = document.getElementsByTagName('input');
for(var i=0; inputElements[i]; i++){
if(inputElements[i].className==="chk" &&
inputElements[i].checked){
checkedValue += inputElements[i].value;
if (inputElements[i+1])
checkedValue += ", ";
else
checkedValue += "";
}
}
I am then passing "checkedValue" to a perl script as follows :
self.location='/cgi-bin/ATMRunJob.pl?tcs='+checkedValue;
In the perl script, I read the array as follows :
our #testCasesToRun = $var->param("tcs");
This is then assigned to a hash as follows :
my $runSpec = {
TestCasesToRun => #testCasesToRun
};
However, I get the following error when I load the page in the browser :
Failed TestLimits() with error: [hash: k=TestCasesToRun, v=1,]:[array]:Value is not an array ref
In check against following TLS:
[
'hr',
{
'OptDefaults' => {
'JobRunningGroupName' => 'astbluetooth',
'RunMode' => 'Queue',
'CountTowardsReporting' => 1,
'JobOwnerGroupName' => 'astbluetooth',
'SelectSetupTeardown' => 1
},
'Optional' => {
'TestCasesToRun' => [
'ar',
undef,
undef,
[
'r',
1,
undef
]
],
I am new to perl as well as CGI scripting. How could I get around this error?
NOTE : All the code snippets have been shortened for brevity, but still portray the essence of the problem.
EDIT : What I want to do is this. The user selects a list of test cases from a checkboxed list that he wants to execute. I take the test case ids of all the selected test cases and pass it to a perl script. In the perl script, I just need to assign these selected testcase ids to the TestCasesToRun element in the runspec hash.
What would be the correct way to do that?
You are assigning an array as a hashkey value. That doesn't work; you need to assign an array ref:
my $runSpec = {
TestCasesToRun => \#testCasesToRun
};
Given that the code compiles, I have a feeling you just messed up your examples in the Q - please fix them to accurately reflect your code, even if they will be slightly less brief.
Your 'tcs' parameter is a single string (assigned via JS). Why are you then assigning results of param('tcs') to an array in the first place? Do you have a split somewhere in your code that you didn't include into the example?
Your dump contains an array reference within an array reference. You need to elaborate on what the expected structure of TestCasesToRun arrayref is, and show the code which processes it in the test runner.
As per your last comment:
Change your JavaScript code to join using simple comma: checkedValue += ",";
Change your Perl assignment to: our #testCasesToRun = split(/,/, $var->param("tcs"));

Resources