How to Read Code Block After a Function Call

code block in curly braces after the function call

First of all, there are some issues with the code you posted. A better stripped-down version of the createStore() function would be:

function createStore(reducer) {
var listeners = [];

function subscribe(listener) {
listeners.push(listener);

return function unsubscribe() {
var index = listeners.indexOf(listener)
listeners.splice(index, 1)
};
}

return {subscribe};
}

Note that you were forgetting some semicolons and that (EDIT: the OP forgot nothing. Redux skips semicolons to conform to React Router ESLint) the subscribe() method wasn't returning function unsubscribe() but just unsubscribe().

Now, answering the question, this article is a nice lecture to illustrate the differences between Ruby and JavaScript on this topic.

Ruby methods are not functions or first-class citizens because they cannot be passed to other methods as arguments, returned by other methods, or assigned to variables. Ruby procs are first-class, similar to JavaScript’s first-class functions.

In JavaScript functions are truly first-class citizens. They can be passed a round as any other piece of data.

In our example, the createStore() function returns an object, containing the function/method subscribe(). It does so by returning the name of the function (subscribe). Likewise, subscribe() also returns a function, but this time the declaration of that function happens directly inside the return statement. Both are valid ways to pass a function.

When you instantiatecreateStore by a function call, you will obtain the returned object.

var myObject = createStore("foo");

The new object has the method subscribe(). If you call that method you will obtain the unsubscribe() function.

var myFunction = myObject.subscribe("bar");

Of course, you could do it in one line by:

var myFunction = createStore("foo").subscribe("bar");

Try it in the snippet below:

function createStore(reducer) {

var listeners = [];

function subscribe(listener) {

listeners.push(listener);

return function unsubscribe() {

var index = listeners.indexOf(listener)

listeners.splice(index, 1)

};

}

return {subscribe};

}

var myObject = createStore("foo");

console.log(myObject); // print an object with the subscribe method.

var myFunction = myObject.subscribe("bar");

console.log(myFunction); // print the unsubscribe function

console.log(createStore("foo").subscribe("bar"));

How to handle blocking read() call when reading from a socket?

What I fail to understand is why the program never gets to the final printf call, and rather sits there as if waiting for more from the server.

It is waitng for more from the server. read() will return zero when the peer disconnects, and not before.

C++ Function Call vs. New Blocks for Push/Popping on the Stack

Well, you could say that your first example could be seen as an inlined function. :P

But generally, function calls and opening a new scope have nothing to do with each other.

When you call a function, the return address and all arguments are pushed on the stacked and popped from it after the function returns.

When opening a new scope, you simple call the destructor of all objects within that scope at the end of it; it is by no means guaranteed that the actual space occupied by those variables is popped from the stack right away. It could, but the space could also simply be reused by other variables in the function, depending on the compilers / optimizers whims.

read() after select() blocking when reading from pipe from spawned process

[deleted the debugging statements which only clutter the view]

    if (FD_ISSET(out_fd, &rfds)) {
do
{
n = read(out_fd, &buf[0], buf.size());
if (n == -1) {
return result;
}
if (n>0)
result->append(buf.cbegin(), buf.cbegin()+n);
} while ( n > 0 );
}

Here you're not doing a single read(), but doing the read() in a loop until it returns an error or hits EOF. So code will loop until it will consume all data already written to the pipe, and then block until more data is written to it. select() returning a file as ready for reading only tells that there's some data available to be read from it, not that no read() will block until EOF.

And btw, select() makes no guarantees that even a single read() on a fd marked as ready for reading will not actually block.[1] The only way to be sure of that is to set the fd to non-blocking mode (eg. with fcntl(O_NONBLOCK)) and check for errno == EAGAIN in the error case.

Your code has many other problems (eg. double flushing of stdio buffers, failure to check for EINTR, etc).


[1] See the BUGS section of the Linux man page.

How to pass more one code block to a function in Ruby?

You can pass only one block at once but blocks are actually Proc instances and you can pass as many instances you wish as parameters.

def mymethod(proc1, proc2, &block)
proc1.call
yield if block_given?
proc2.call
end

mymethod(Proc.new {}, Proc.new {}) do
# ...
end

However, it rarely makes sense.

How to implement a timeout in read() function call?

select()
takes 5 parameters, first the highest file descriptor + 1, then a fd_set for read, one for write and one for exceptions. The last parameter is a struct timeval, used for timeout. It return -1 on error, 0 on timeout or the number of file descriptors in the sets that are set.

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/select.h>

int main(void)
{
fd_set set;
struct timeval timeout;
int rv;
char buff[100];
int len = 100;
int filedesc = open( "dev/ttyS0", O_RDWR );

FD_ZERO(&set); /* clear the set */
FD_SET(filedesc, &set); /* add our file descriptor to the set */

timeout.tv_sec = 0;
timeout.tv_usec = 10000;

rv = select(filedesc + 1, &set, NULL, NULL, &timeout);
if(rv == -1)
perror("select"); /* an error accured */
else if(rv == 0)
printf("timeout"); /* a timeout occured */
else
read( filedesc, buff, len ); /* there was data to read */
close(filedesc);
}

How to make program go back to the top of the code instead of closing

Python, like most modern programming languages, does not support "goto". Instead, you must use control functions. There are essentially two ways to do this.

1. Loops

An example of how you could do exactly what your SmallBasic example does is as follows:

while True :
print "Poo"

It's that simple.

2. Recursion

def the_func() :
print "Poo"
the_func()

the_func()

Note on Recursion: Only do this if you have a specific number of times you want to go back to the beginning (in which case add a case when the recursion should stop). It is a bad idea to do an infinite recursion like I define above, because you will eventually run out of memory!

Edited to Answer Question More Specifically

#Alan's Toolkit for conversions

invalid_input = True
def start() :
print ("Welcome to the converter toolkit made by Alan.")
op = input ("Please input what operation you wish to perform. 1 for Fahrenheit to Celsius, 2 for meters to centimetres and 3 for megabytes to gigabytes")
if op == "1":
#stuff
invalid_input = False # Set to False because input was valid

elif op == "2":
#stuff
invalid_input = False # Set to False because input was valid
elif op == "3": # you still have this as "if"; I would recommend keeping it as elif
#stuff
invalid_input = False # Set to False because input was valid
else:
print ("Sorry, that was an invalid command!")

while invalid_input: # this will loop until invalid_input is set to be False
start()


Related Topics



Leave a reply



Submit