Skip to main content

Posts

Move like a Ninja on Terminal Console

If you are in IT and do a lot of stuff on terminal, this is the post for you. In the following post, we will explore various key shortcuts to jump and edit on console. Note:- Short keys may behave differnt on differnt OS systems. These keys best work with Linux sytem, For mac OS you have to enable Option key as Meta key in case of Alt . I have never checked these on windows, Please share your experinece with windows in comments. ------------------------------------------------------------------ Edit Control Move forward one char: Ctrl + f Move backward one char: Ctrl + b Move forward one word: Alt + f Move backward one word: Alt + b Move to end: Ctrl + e #Like End Move to start: Ctrl + a #Like Home Jump toggle between current location and start: Ctrl + xx Delete forward one char: Ctrl + d #Like Delete Delete backward one char: Ctrl + h #Like Backspace Delete forward one word: Alt + d Delete backward one word: Ctrl + w Delete to end: Ctrl + k Delete to start: Ctrl + u Undo: Ct...

Get Create Table Query for all Tables in MySQL

 In a MySQL database whenever we need to generate the create table query for any existing table. We can use the below query. show create table test_table; If you need to generate create table query for all the tables then the above query will be cumbersome because you have to run it for every table. We can use mysqldump to generate create table query for all the tables in one go. Open your favorite terminal and execute the below command to check if you have the mysqldump on your system. If you don't have it, please install it first. Usually, it comes with mysql-client software but check the web for more help. mysqldump --version Now you have mysqldump ready, We can use the below command to generate the create table query for all the tables. mysqldump -h ${HOST} -u ${USER} -p -d --compact --column-statistics=0 ${DB_NAME}|egrep -v "(^SET|^/\*\!)" > tables.sql ${} represents the variable you can replace with your DB config. We have used -p So it will prompt for the passwo...

Volume Zero after Login or Unlock in Mac

After reaching office, as soon you opened your laptop it resumes the video/audio you left last night. Sometimes it can be embarrassing, So what we can do is write a script to set volume zero every time your laptop wakes up from login or unlock. The following script is for macOS only. The idea is the same for every OS, you just need to find the right hook and commands. First, we will install the software sleepwatcher which provides the hook for sleep and wakeup events in the OS. Open the terminal and execute the below command. brew install sleepwatcher brew services start sleepwatcher If everything executed correctly. The sleepwatcher has been installed and running in the background. Now we need to figure out how to execute the desired commands on sleep and wakeup events. If we execute below command ps -ef | grep 'sleepwatcher' you will see output something like this.   502   510     1   0 12:07PM ??        ...

Waiting Animation in Python Script

It is very often that we are writing some scripts and we need to put some sleep before executing the next step. During the sleep time of script Either you can use simple sleep and print a line or you can use little waiting animation during the sleep. Try running the below script, It will provide you some animation during sleeping time. The script is quite simple and self-explanatory. Feel free to modify and experiment with the script to get some kooler waiting animation. import time import sys import random ###################- Core Methods -################ def next_pos(i, fwd): if fwd: return i+1 else: return i-1; def nextchar_cursor(pattern): while True: for cursor in pattern: yield cursor #######- Simple spin and wait -##################### def spinner(speed, wt): cursor = nextchar_cursor("-/\\|") st = 1.0 / speed for i in range(wt): rs = "%3d" % (wt-i) for j in range(speed): ...

java.lang.IllegalArgumentException: Could not instantiate implementation: org.janusgraph.diskstorage.cassandra.thrift.CassandraThriftStoreManager

If you are trying to get started with Janus Graph with Apache Cassandra. You may get the following error. Caused by: org.janusgraph.diskstorage.TemporaryBackendException: Temporary failure in storage backend at org.janusgraph.diskstorage.cassandra.thrift.CassandraThriftStoreManager.getCassandraPartitioner(CassandraThriftStoreManager.java:219) ~[janusgraph-cassandra-0.2.0.jar:na] at org.janusgraph.diskstorage.cassandra.thrift.CassandraThriftStoreManager.<init>(CassandraThriftStoreManager.java:198) ~[janusgraph-cassandra-0.2.0.jar:na] ... 48 common frames omitted Caused by: org.apache.thrift.transport.TTransportException: java.net.ConnectException: Connection refused (Connection refused) at org.apache.thrift.transport.TSocket.open(TSocket.java:187) ~[libthrift-0.9.2.jar:0.9.2] at org.apache.thrift.transport.TFramedTransport.open(TFramedTransport.java:81) ~[libthrift-0.9.2.jar:0.9.2] at org.janusgraph.diskstorage.cassandra.thrift.thriftpool.CTConnectionFactory.makeR...

HTTP2 Server Push in Apache2

Server Push is one of the most significant features in the HTTP/2 protocol. In this post, We will see a very simple demo of the Server Push feature using HTTP/2. Below is the list of tools and tech used in the demo. Ubuntu 16.04 Chrome 60.0.3112.101 Apache2 Some browsers require TLS 1.2 to support HTTP/2. So We need to configure https on Apache server. Try to open the URL https://localhost in your browser. If the above URL not responding, It means you need to configure HTTPS on your Apache server. Please refer to the digital ocean page. https://www.digitalocean.com/community/tutorials/how-to-create-a-ssl-certificate-on-apache-for-ubuntu-14-04 I hope the URL https://localhost is working now and We can proceed further. We will do it into 2 parts. Part-I: We will just enable the HTTP/2 protocol Part-II: We will configure server push feature Part-I: Enable HTTP/2 First, check the below points. Make sure you have the http2 module in your apache. Naviga...

Decorator Pattern : Real Life Example and Java Code Example

Decorator Pattern The Decorator Pattern provides a mechanism to dynamically attach the additional responsibilities to an object at runtime. Inheritance also provides the same but it is not flexible and does statically. We will see further in detail why Inheritance is not a good option as compared to Decorator Pattern. One important thing about the Decorator Pattern, It does not affect the core functionality just attach some additional. Real Life Example: Take the example of a bicycle store. When someone comes to buy a bicycle, The distributor shows the basic bicycle with core functionalities. After selecting the bicycle, He asks for the accessories you want to attach. Suppose there are accessories like carrier,stand-leg,front-light,front-box,bike-bell. The service man decorates your bicycle with accessories(additional functionalities without affecting the core functionality) as per your requirement. Java Code Example: We will try to implement the above real life exam...

Factory Pattern : Real Life Example and Java Code Example

Factory Pattern The Factory Pattern is actually a method(factory method) which is used to create objects on the basis of runtime requirements. Real Life Example: The factory method is same as the real world factory, It gives the same kind of object with different(based on the input) behavior. For example, There is a machine in a factory which takes wood and paints as input and gives a painted box as the final product. We can create different boxes by just changing the color of paint in the input. Java Code Example: Before going to codes, We need to see some key points about factory method implementation. We need an interface(Suppose A is an interface). Then We need various implementations of A (Suppose B, C, D are implementing A). Finally, We need a Factory class with a factory method. The factory method must have the return type of A. Find the below problem and its solution using the factory method. Suppose We need to build an application KNOW ABOUT ANIMALS. The a...

Singleton Pattern : Real Life Example and Java Code Example

Singleton Pattern The Singleton pattern uses to prevent the instantiation of an Object or creating a new one. It is used when We need only one instance in the whole application. The singleton is similar to global variables and we can find many debates over singleton vs global variables on the internet. We can choose between singleton and global variables based on the application context, But global variables violate the encapsulation policy of OOP concepts. Real Life Example: The DataSource is very good example of a singleton pattern. We initialize DataSourcet object by some parameters like host,port,user and password. Every time We need the DataSource, the values of the parameters remains same So We need exactly one instance of DataSource. Java Code Example: There is the various implementation of the singleton, based on the initialization like eager, lazy, static block and thread safe. Below implementation called Bill Pugh Singleton Implementation is simplest and also threa...

How to Open a File in Vim Editor without Navigating through all the nested Directories

                      O ne day I was working on something and I needed to modify the configuration file on the server. So I had to navigate to all the way through nested directories and then finally edit the file. The requirement was quite frequent and every time I had to navigate to multiple directories. This post is about to simplify the above task. For example, We need to edit the following file. File path : /home/alex/Softwares/apache-tomcat-7.0.62/webapps/live-service/WEB-INF/classes/conf/database/database.conf We can do it by using the below command: alex:~$ vim /home/alex/Softwares/apache-tomcat-7.0.62/webapps/live-service/WEB-INF/classes/conf/database/database.conf If we count the nested directories, There are 10 directories We need to navigate through and It is cumbersome even we know the exact path of the file. We will try to do something which can reduce the effo...

Hibernate Template vs Entity Manager while Persisting a List of Entites

I did a test for comparison between  org.springframework.orm.hibernate3.HibernateTemplate and   javax.persistence.EntityManager . I am sharing the result of my analysis. use case : Persistence of a List of Entities. environment : Linux 64-bit, jdk_1.8 When I run the test I found that Entity Manager performing better when persisting large size of list. An image can tell better than thousands words. So find the below image to see the performance difference between the frameworks. Data Table: Graph Chart:

Best Way to use ArrayList in Java

                      I n the following post we are goning to discuss a little variation in use of ArrayList in java. We will see how we can improve the performance by just a small change. First of all run the below java code on your machine. import java.util.ArrayList; import java.util.List; public class Test{ public static void main(String... args) { int s = 10000000; String v = "PROGRAMMING"; long t1,t2; //Segment-1 t1 = System.currentTimeMillis(); List<String> l1 = new ArrayList<>(); for(int i=0; i<s; ++i){ l1.add(v); } t2 = System.currentTimeMillis(); System.out.println("Time for above segment-1 : "+(t2-t1)+" ms"); //Segment-2 t1 = System.currentTimeMillis(); List<String> l2 = new ArrayList<>(s); for(int i=0; i<s; ++i){ l2.add(v); } t2 = System.currentTimeMillis(); System.out.println("Time for abo...

About Software Design and Development

When we plan to design a software we need to focus certain things. Here are some important points we can go through. Functional Decomposition: Functional decomposition is natural way to deal with complexity. The challenges with this approach: to dealing with change and bugs originate with changes to code. Low cohesion, tight coupling Focus on function leads to a cascade of changes from which it is difficult to escape. The Problem of Requirements: Requirements always change. Requirements are incomplete. Requirements are usually wrong. Requirements (and users) are misleading. Requirements do not tell the whole story. Deal with Changes(Use Functional Decomposition): Shift responsbility from yourself to...

Builder Pattern : Java Code Example

Builder Pattern Builder Pattern is used when the increase of object constructor parameter combination leads to an exponential list of constructors. It is a solution to the telescoping constructor anti-pattern. Let's describe the pattern by using a sample requirement. Problem: We need to create a class for a Customer in a Bank and need following attributes in the Customer object. {Name, Father's Name, Date Of Birth, Mobile, Email, PAN, Permanent Address, Correspondence Address, Account, Branch} Constraint : Name,Date Of Birth,Account can not be null or empty There are 10 attributes in the objects So there will be total 2^10(1024) possible constructor and It is not practical to write all required constructors. One alternative could be to use Setter method but it will not work if any attribute has final modifier and would be difficult to fulfill the constraint that some attributes can not be null or empty. Now We will see how Builder Design Pattern helps to solve...

How to Create a Namespace in Aerospike Database

                      T his post is about creating a namespace in Aerospike. I could not find any concrete method to create a namespace like create database in MySQL and MongoDB. So I am suggesting a way to create a namespace in Aerospike Database. Step-1: Locate config file aerospike.conf and open it in your favorite editor and make sure you have permission to modify the file. In my system the path of file /etc/aerospike/aerospike.conf (Default in Ubuntu). Here the content of the file. # Aerospike database configuration file. service { user root group root paxos-single-replica-limit 1 # Number of nodes where the replica pidfile /var/run/aerospike/asd.pid service-threads 4 transaction-queues 4 transaction-threads-per-queue 4 proto-fd-max 15000 } logging { # Log file must be an absolute path. file /var/log/aerospike/aerospike.log { context any info } } net...

Books : Every Computer Science Student Should Read Before Leaving College

Awesome books for Computer Science students: =================================================================== ------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------------------ -------------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------------------    ------------------------------------------------------------------------------------------------------------------------  -----------------------------------------------------------------------------------------------------------...

com.mongodb.MongoCommandException: Command failed with error 18: 'Authentication failed.' on server

If you are trying to connect Mongo DB Server and it insanely throwing following error. com.mongodb.MongoTimeoutException : Timed out after 1000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=192.168.1.10:27010, type=UNKNOWN, state=CONNECTING, exception={ com.mongodb.MongoSecurityException: Exception authenticating MongoCredential {mechanism=null, userName='user123', source='admin', password=<hidden>, mechanismProperties={}}}, caused by {com.mongodb.MongoCommandException: Command failed with error 18 : 'Authentication failed.' on server 192.168.1.10:27010 . The full response is { "ok" : 0.0, "code" : 18, "errmsg" : "Authentication failed." }}}] If you start looking the error content First you encounter with Timeout Exception which may mislead you. It is basically an authentication error. I...

WARN AEROSPIKE_ERR_CLIENT Socket write error: 111

If you are just typing aql on terminal and following error throwing while your aerospike server has been started successfully. WARN AEROSPIKE_ERR_CLIENT Socket write error: 111 It may happen because you had connected some other server before, Now you are trying to connect to your localhost or different server. To remove the above error just type full command: aql -h 127.0.0.1 -p 3000                           ( put server ip in case of other server rather than localhost) instead of jus aql.

com.aerospike.client.AerospikeException$Serialize: Error Code -1:

If you are trying to save a  whole simple java object into Aerospike database and your are getting the following annoying errors. com.aerospike.client.AerospikeException$Serialize: Error Code -1: java.io.NotSerializableException: com.sangnak-science. Person at com.aerospike.client.Value$BlobValue.estimateSize(Value.java:977) at com.aerospike.client.command.Command.estimateOperationSize(Command.java:767) at com.aerospike.client.command.Command.setWrite(Command.java:76) at com.aerospike.client.command.WriteCommand.writeBuffer(WriteCommand.java:56) at com.aerospike.client.command.SyncCommand.execute(SyncCommand.java:47) at com.aerospike.client.AerospikeClient.put(AerospikeClient.java:339) at com.yatra.Aerospike.main(Aerospike.java:57) Caused by: java.io.NotSerializableException: com.yatra.Person at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348) at com.aerospike.cli...

Java Code Example For Aerospike Simple Operations [Read, Write, Delete]

                      I n the following post we will see sample java code to perform simple operation (read, write and delete Records) from Aerospike Database System. The code are self explanatory, follow the comments in code for better understanding. You only need a jar for java client which you can download from aerospike official website. Main Class import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.aerospike.client.AerospikeClient; import com.aerospike.client.AerospikeException; import com.aerospike.client.Bin; import com.aerospike.client.Host; import com.aerospike.client.Key; import com.aerospike.client.Record; import com.aerospike.client.Value; import com.aerospike.client.policy.ClientPolicy; import com.aerospike.client.policy.WritePolicy; public class Aerospike { public static void main(String... args){ ...