Sed – Useful Recipes

Stream Editor – Useful Recipes ”; Previous Next SED is an amazing utility that allows multiple ways to solve a problem. This is the UNIX way and SED perfectly proves that. GNU/Linux provides many useful utilities to perform day-to-day tasks. Let us simulate a few utilities using SED. Sometimes it may appear we are solving an easy problem the hard way, but the purpose is just to demonstrate the power of SED. Cat Command In the following example, each line is printed as a part of the default workflow. [jerry]$ sed ”” books.txt On executing the above code, you get the following result: A Storm of Swords, George R. R. Martin The Two Towers, J. R. R. Tolkien The Alchemist, Paulo Coelho The Fellowship of the Ring, J. R. R. Tolkien The Pilgrimage, Paulo Coelho A Game of Thrones, George R. R. Martin The following example uses print command to display the file contents. [jerry]$ sed -n ”p” books.txt On executing the above code, you get the following result: A Storm of Swords, George R. R. Martin The Two Towers, J. R. R. Tolkien The Alchemist, Paulo Coelho The Fellowship of the Ring, J. R. R. Tolkien The Pilgrimage, Paulo Coelho A Game of Thrones, George R. R. Martin Removing Empty Lines In the following example, “^$” implies empty line, and empty lines are deleted when a pattern match succeeds. [jerry]$ echo -e “Line #1nnnLine #2″ | sed ”/^$/d” On executing the above code, you get the following result: Line #1 Line #2 Similarly, the following example prints the line only when it is non-empty. [jerry]$ echo -e “Line #1nnnLine #2″ | sed -n ”/^$/!p” On executing the above code, you get the following result: Line #1 Line #2 Removing Commented Lines from a C++ Program Let us create a sample C++ program. #include <iostream> using namespace std; int main(void) { // Displays message on stdout. cout >> “Hello, World !!!” >> endl; return 0; // Return success. } Now remove the comments using the following regular expression. [jerry]$ sed ”s|//.*||g” hello.cpp On executing the above code, you get the following result: #include <iostream> using namespace std; int main(void) { cout >> “Hello, World !!!” >> endl; return 0; } Adding Comments Before Certain Lines The following example adds comments before line numbers 3 to 5. [jerry]$ sed ”3,5 s/^/#/” hello.sh On executing the above code, you get the following result: #!/bin/bash #pwd #hostname #uname -a who who -r lsb_release -a Wc -l command The “wc -l” command counts the number of lines present in the file. The following SED expression simulates the same. [jerry]$ sed -n ”$ =” hello.sh On executing the above code, you get the following result: 8 Head Command By default, the head command prints the first 10 lines of the file. Let us simulate the same behavior with SED. [jerry]$ sed ”10 q” books.txt On executing the above code, you get the following result: A Storm of Swords George R. R. Martin The Two Towers J. R. R. Tolkien The Alchemist Paulo Coelho The Fellowship of the Ring J. R. R. Tolkien The Pilgrimage Paulo Coelho Tail -1 Command The “tail -1” prints the last line of the file. The following syntax shows its simulation. [jerry]$ echo -e “Line #1nLine #2″ > test.txt [jerry]$ cat test.txt On executing the above code, you get the following result: Line #1 Line #2 Let us write the SED script. [jerry]$ sed -n ”$p” test.txt On executing the above code, you get the following result: Line #2 Dos2unix Command In DOS environment, a newline is represented by a combination of CR/LF characters. The following simulation of “dos2unix” command converts a DOS newline character to UNIX newline character. In GNU/Linux, this character is often treated as “^M” (Control M) character. [jerry]$ echo -e “Line #1rnLine #2r” > test.txt [jerry]$ file test.txt On executing the above code, you get the following result: test.txt: ASCII text, with CRLF line terminators Let us simulate the command using SED. [jerry]$ sed ”s/^M$//” test.txt > new.txt # Press “ctrl+v” followed “ctrl+m” to generate “^M” character. [jerry]$ file new.txt On executing the above code, you get the following result: new.txt: ASCII text Now let us display the file contents. [jerry]$ cat -vte new.txt On executing the above code, you get the following result: Line #1$ Line #2$ Unix2dos command Similar to “dos2unix”, there is “unix2dos” command which converts UNIX newline character to DOS newline character. The following example shows simulation of the same. [jerry]$ echo -e “Line #1nLine #2″ > test.txt [jerry]$ file test.txt On executing the above code, you get the following result: test.txt: ASCII text Let us simulate the command using SED. [jerry]$ sed ”s/$/r/” test.txt > new.txt [jerry]$ file new.txt On executing the above code, you get the following result: new.txt: ASCII text, with CRLF line terminators Now let us display the file contents. Now let us display the file contents. On executing the above code, you get the following result: Line #1^M$ Line #2^M$ Cat -E command The “cat -E” command shows the end of line by Dollar($) character. The following SED example is simulation of the same. [jerry]$ echo -e “Line #1nLine #2″ > test.txt [jerry]$ cat -E test.txt On executing the above code, you get the following result: Line #1$ Line #2$ Let us simulate the command using SED. [jerry]$ sed ”s|$|&$|” test.txt On executing the above code, you get the following result: Line #1$ Line #2$ Cat -ET Command The “cat -ET” command shows the Dollar($) symbol at the end of each line and displays the TAB characters as “^I”. The following example shows the simulation of “cat -ET” command using SED. [jerry]$ echo -e “Line #1tLine #2″ > test.txt [jerry]$ cat -ET test.txt On executing the above code, you get the following result: Line #1^ILine #2$ Let us simulate the command using SED. [jerry]$ sed -n ”l” test.txt | sed ”y/\t/^I/” On executing the above code, you get the following result: Line #1^ILine #2$

Socket.IO – Error Handling

Socket.IO – Error Handling ”; Previous Next We have worked on local servers until now, which will almost never give us errors related to connections, timeouts, etc. However, in real life production environments, handling such errors are of utmost importance. Therefore, we will now discuss how we can handle connection errors on the client side. The client API provides us with following built in events − Connect − When the client successfully connects. Connecting − When the client is in the process of connecting. Disconnect − When the client is disconnected. Connect_failed − When the connection to the server fails. Error − An error event is sent from the server. Message − When the server sends a message using the send function. Reconnect − When reconnection to the server is successful. Reconnecting − When the client is in the process of connecting. Reconnect_failed − When the reconnection attempt fails. To handle errors, we can handle these events using the out-socket object that we created on our client. For example – If we have a connection that fails, we can use the following code to connect to the server again − socket.on(”connect_failed”, function() { document.write(“Sorry, there seems to be an issue with the connection!”); }) Print Page Previous Next Advertisements ”;

Socket.IO – Discussion

Discuss Socket.IO ”; Previous Next Socket.IO enables real-time bidirectional event-based communication. It works on every platform, browser or device, focusing equally on reliability and speed. Socket.IO is built on top of the WebSockets API (Client side) and Node.js. It is one of the most depended upon library on npm (Node Package Manager). Print Page Previous Next Advertisements ”;

Socket.IO – Useful Resources

Socket.IO – Useful Resources ”; Previous Next The following resources contain additional information on Socket.IO. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Build a simple chat system in JavaScript 15 Lectures 2.5 hours Musab Zayadneh More Detail Node.js Course – A Practical Approach Most Popular 98 Lectures 6 hours Skillbakery More Detail Create a 3D multi-player game using THREE.js and Socket.IO 35 Lectures 2.5 hours Nicholas Lever More Detail Node.js from Ground Up for Beginners 47 Lectures 2.5 hours Packt Publishing More Detail Next.js, OpenAI & React JS: Beginner to Pro Web Development 55 Lectures 6.5 hours Tofiq Quadri More Detail Print Page Previous Next Advertisements ”;

Socket.IO – Overview

Socket.IO – Overview ”; Previous Next Socket.IO is a JavaScript library for real-time web applications. It enables real-time, bi-directional communication between web clients and servers. It has two parts − a client-side library that runs in the browser, and a server-side library for node.js. Both components have an identical API. Real-time Applications A real-time application (RTA) is an application that functions within a period that the user senses as immediate or current. Some examples of real-time applications are − Instant messengers − Chat apps like Whatsapp, Facebook Messenger, etc. You need not refresh your app/website to receive new messages. Push Notifications − When someone tags you in a picture on Facebook, you receive a notification instantly. Collaboration Applications − Apps like google docs, which allow multiple people to update same documents simultaneously and apply changes to all people”s instances. Online Gaming − Games like Counter Strike, Call of Duty, etc., are also some examples of real-time applications. Why Socket.IO? Writing a real-time application with popular web applications stacks like LAMP (PHP) has traditionally been very hard. It involves polling the server for changes, keeping track of timestamps, and it is a lot slower than it should be. Sockets have traditionally been the solution around which most real-time systems are architected, providing a bi-directional communication channel between a client and a server. This means that the server can push messages to clients. Whenever an event occurs, the idea is that the server will get it and push it to the concerned connected clients. Socket.IO is quite popular, it is used by Microsoft Office, Yammer, Zendesk, Trello,. and numerous other organizations to build robust real-time systems. It one of the most powerful JavaScript frameworks on GitHub, and most depended-upon NPM (Node Package Manager) module. Socket.IO also has a huge community, which means finding help is quite easy. ExpressJS We will be using express to build the web server that Socket.IO will work with. Any other node-server-side framework or even node HTTP server can be used. However, ExpressJS makes it easy to define routes and other things. To read more about express and get a basic idea about it, head to – ExpressJS tutorial. Print Page Previous Next Advertisements ”;

Socket.IO – Hello world

Socket.IO – Hello world ”; Previous Next In the following chapter we will discuss the basic example using Socket.IO library along with ExpressJS. Example First of all, create a file called app.js and enter the following code to set up an express application − var app = require(”express”)(); var http = require(”http”).Server(app); app.get(”/”, function(req, res){ res.sendFile(”E:/test/index.html”); }); http.listen(3000, function(){ console.log(”listening on *:3000”); }); We will need an index.html file to serve, create a new file called index.html and enter the following code in it − <!DOCTYPE html> <html> <head><title>Hello world</title></head> <body>Hello world</body> </html> To test if this works, go to the terminal and run this app using the following command − nodemon app.js This will run the server on localhost:3000. Go to the browser and enter localhost:3000 to check this. If everything goes well a message saying “Hello World” is printed on the page. Following is another example (this require Socket.IO), it will log “A user connected”, every time a user goes to this page and “A user disconnected”, every time someone navigates away/closes this page. var app = require(”express”)(); var http = require(”http”).Server(app); var io = require(”socket.io”)(http); app.get(”/”, function(req, res){ res.sendFile(”E:/test/index.html”); }); //Whenever someone connects this gets executed io.on(”connection”, function(socket){ console.log(”A user connected”); //Whenever someone disconnects this piece of code executed socket.on(”disconnect”, function () { console.log(”A user disconnected”); }); }); http.listen(3000, function(){ console.log(”listening on *:3000”); }); The require(”socket.io”)(http) creates a new socket.io instance attached to the http server. The io.on event handler handles connection, disconnection, etc., events in it, using the socket object. We have set up our server to log messages on connections and disconnections. We now have to include the client script and initialize the socket object there, so that clients can establish connections when required. The script is served by our io server at ”/socket.io/socket.io.js”. After completing the above procedure, the index.html file will look as follows − <!DOCTYPE html> <html> <head><title>Hello world</title></head> <script src=”/socket.io/socket.io.js”></script> <script> var socket = io(); </script> <body>Hello world</body> </html> If you go to localhost:3000 now (make sure your server is running), you will get Hello World printed in your browser. Now check your server console logs, it will show the following message − A user connected If you refresh your browser, it will disconnect the socket connection and recreate. You can see the following on your console logs − A user connected A user disconnected A user connected Print Page Previous Next Advertisements ”;

Socket.IO – Environment

Socket.IO – Environment ”; Previous Next To get started with developing using the Socket.IO, you need to have Node and npm (node package manager) installed. If you do not have these, head over to Node setup to install node on your local system. Confirm that node and npm are installed by running the following commands in your terminal. node –version npm –version You should get an output similar to − v14.17.0 6.14.13Open your terminal and enter the following in your terminal to create a new folder and enter the following commands − $ mkdir test-project $ cd test-proect $ npm init It will ask you some questions; answer them in the following way − This will create a ”package.json node.js” configuration file. Now we need to install Express and Socket.IO. To install these and save them to package.json file, enter the following command in your terminal, into the project directory − npm install –save express socket.io One final thing is that we should keep restarting the server. When we make changes, we will need a tool called nodemon. To install nodemon, open your terminal and enter the following command − npm install -g nodemon Whenever you need to start the server, instead of using the node app.js use, nodemon app.js. This will ensure that you do not need to restart the server whenever you change a file. It speeds up the development process. Now, we have our development environment set up. Let us now get started with developing real-time applications with Socket.IO. Print Page Previous Next Advertisements ”;

Socket.IO – Namespaces

Socket.IO – Namespaces ”; Previous Next Socket.IO allows you to “namespace” your sockets, which essentially means assigning different endpoints or paths. This is a useful feature to minimize the number of resources (TCP connections) and at the same time separate concerns within your application by introducing separation between communication channels. Multiple namespaces actually share the same WebSockets connection thus saving us socket ports on the server. Namespaces are created on the server side. However, they are joined by clients by sending a request to the server. Default Namespaces The root namespace ”/” is the default namespace, which is joined by clients if a namespace is not specified by the client while connecting to the server. All connections to the server using the socket-object client side are made to the default namespace. For example − var socket = io(); This will connect the client to the default namespace. All events on this namespace connection will be handled by the io object on the server. All the previous examples were utilizing default namespaces to communicate with the server and back. Custom Namespaces We can create our own custom namespaces. To set up a custom namespace, we can call the ”of” function on the server side − var app = require(”express”)(); var http = require(”http”).Server(app); var io = require(”socket.io”)(http); app.get(”/”, function(req, res){ res.sendFile(”E:/test/index.html”);}); var nsp = io.of(”/my-namespace”); nsp.on(”connection”, function(socket){ console.log(”someone connected”); nsp.emit(”hi”, ”Hello everyone!”); }); http.listen(3000, function(){ console.log(”listening on localhost:3000”); }); Now, to connect a client to this namespace, you need to provide the namespace as an argument to the io constructor call to create a connection and a socket object on client side. For example, to connect to the above namespace, use the following HTML − <!DOCTYPE html> <html> <head><title>Hello world</title></head> <script src=”/socket.io/socket.io.js”></script> <script> var socket = io(”/my-namespace”); socket.on(”hi”,function(data){ document.body.innerHTML = ””; document.write(data); }); </script> <body></body> </html> Every time someone connects to this namespace, they will receive a ”hi” event displaying the message “Hello everyone!”. Print Page Previous Next Advertisements ”;

Solidity – Assembly

Solidity – Assembly ”; Previous Next Solidity provides an option to use assembly language to write inline assembly within Solidity source code. We can also write a standalone assembly code which then be converted to bytecode. Standalone Assembly is an intermediate language for a Solidity compiler and it converts the Solidity code into a Standalone Assembly and then to byte code. We can used the same language used in Inline Assembly to write code in a Standalone assembly. Inline Assembly Inline assembly code can be interleaved within Solidity code base to have more fine-grain control over EVM and is used especially while writing the library functions. An assembly code is written under assembly { … } block. Example Try the following code to understand how a Library works in Solidity. pragma solidity ^0.5.0; library Sum { function sumUsingInlineAssembly(uint[] memory _data) public pure returns (uint o_sum) { for (uint i = 0; i < _data.length; ++i) { assembly { o_sum := add(o_sum, mload(add(add(_data, 0x20), mul(i, 0x20)))) } } } } contract Test { uint[] data; constructor() public { data.push(1); data.push(2); data.push(3); data.push(4); data.push(5); } function sum() external view returns(uint){ return Sum.sumUsingInlineAssembly(data); } } Run the above program using steps provided in Solidity First Application chapter. Note − Select Test from dropdown before clicking the deploy button. Output 0: uint256: 15 Print Page Previous Next Advertisements ”;

Socket.IO – Broadcasting

Socket.IO – Broadcasting ”; Previous Next Broadcasting means sending a message to all connected clients. Broadcasting can be done at multiple levels. We can send the message to all the connected clients, to clients on a namespace and clients in a particular room. To broadcast an event to all the clients, we can use the io.sockets.emit method. Note − This will emit the event to ALL the connected clients (event the socket that might have fired this event). In this example, we will broadcast the number of connected clients to all the users. Update the app.js file to incorporate the following − var app = require(”express”)(); var http = require(”http”).Server(app); var io = require(”socket.io”)(http); app.get(”/”, function(req, res){ res.sendFile(”E:/test/index.html”); }); var clients = 0; io.on(”connection”, function(socket){ clients++; io.sockets.emit(”broadcast”,{ description: clients + ” clients connected!”}); socket.on(”disconnect”, function () { clients–; io.sockets.emit(”broadcast”,{ description: clients + ” clients connected!”}); }); }); http.listen(3000, function(){ console.log(”listening on localhost:3000”); }); On the client side, we just need to handle the broadcast event − <!DOCTYPE html> <html> <head><title>Hello world</title></head> <script src=”/socket.io/socket.io.js”></script> <script> var socket = io(); socket.on(”broadcast”,function(data){ document.body.innerHTML = ””; document.write(data.description); }); </script> <body>Hello world</body> </html> If you connect four clients, you will get the following result − This was to send an event to everyone. Now, if we want to send an event to everyone, but the client that caused it (in the previous example, it was caused by new clients on connecting), we can use the socket.broadcast.emit. Let us send the new user a welcome message and update the other clients about him/her joining. So, in your app.js file, on connection of client send him a welcome message and broadcast connected client number to all others. var app = require(”express”)(); var http = require(”http”).Server(app); var io = require(”socket.io”)(http); app.get(”/”, function(req, res){ res.sendFile(”E:/test/index.html”); }); var clients = 0; io.on(”connection”, function(socket){ clients++; socket.emit(”newclientconnect”,{ description: ”Hey, welcome!”}); socket.broadcast.emit(”newclientconnect”,{ description: clients + ” clients connected!”}) socket.on(”disconnect”, function () { clients–; socket.broadcast.emit(”newclientconnect”,{ description: clients + ” clients connected!”}) }); }); http.listen(3000, function(){ console.log(”listening on localhost:3000”); }); And your html to handle this event − <!DOCTYPE html> <html> <head><title>Hello world</title></head> <script src=”/socket.io/socket.io.js”></script> <script> var socket = io(); socket.on(”newclientconnect”,function(data){ document.body.innerHTML = ””; document.write(data.description); }); </script> <body>Hello world</body> </html> Now, the newest client gets a welcome message and others get how many clients are connected currently to the server. Print Page Previous Next Advertisements ”;