JavaPythonTech blog contains various tools and skills for a developer. Java/Python Best Practices, Tools, Examples, Programming interview questions.

Raw-mode is unavailable courtesy of Hyper-V. (VERR_SUPDRV_NO_RAW_MODE_HYPER_V_ROOT)





This error usually occurs when hyperV is set to Auto which has to be disabled for you to use VM on Oracle VM VirtualBox.

Please follow the steps mentioned here to resolve the error.

Share:

Python Programming Questions


  • Print fibonacci  number using recursion.
def fib(x):
   
if x == 0 or x == 1:
       
return x
   
else:
       
return (fib(x-1) + fib(x-2))

for i in range(10):
   
print(fib(i))

  • Print the char and number of occurrences in a given input string.
input = "aaabbccbcc"

map = {}

for c in input:
    if(c in map):
        map[c] += 1
    else:
        map[c]=1print(map)

output = ""

for key,val in map.items():
    st = key+str(val)
    output += stprint(output)

More questions will be added soon!


Share:

How to calculate the sum of numbers in list asynchronously?


We will be using ExecutorService from Executor framework and Future interface to make asynchronous calls.
We will be using Streams from Java 8 to calculate the sum of integers in the list.

import java.util.List;
import
java.util.concurrent.Callable;
import
java.util.stream.Collectors;

public class
SumCalculator implements Callable {

    List
inputList;

    public
SumCalculator(List inputList){
       
this.inputList = inputList;
   
}

   
@Override
   
public Integer call() throws Exception {
       
return inputList.stream().collect(Collectors.summingInt(i->i));
   
}
}

Let’s split the list to 2 sublist and pass them to two different threads so that the sum is calculated asynchronously and returned.

We will use future.get() to get the result from each thread and combine to get the final total.

import java.util.ArrayList;

import java.util.List;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Future;

import java.util.stream.IntStream;



public class ListSumAsync {



    public static void main(String...args){

        ExecutorService executorService =

                Executors.newFixedThreadPool(2);



        List intList = new ArrayList<>();

        //Let us add 0 to 100 to a list

        IntStream.range(1, 11)

                .forEach(i -> intList.add(i));



        //Let's split the list to 2 lists and pass

        // it to two threads and combine the result

        SumCalculator calculator1 =

                new SumCalculator(intList.

                        subList(0,intList.size()/2));

        Future result1 =

                executorService.submit(calculator1);



        SumCalculator calculator2 =

                new SumCalculator(intList.subList(

                        (intList.size()/2),intList.size()));

        Future result2 =

                executorService.submit(calculator2);



        try {

            int total = result1.get().intValue()+

                    result2.get().intValue();

            System.out.println("Total sum: "+total);

        } catch (InterruptedException e) {

            e.printStackTrace();

        } catch (ExecutionException e) {

            e.printStackTrace();

        }

    }



}


Share:

How to combine result of two threads in java?


Let us consider a scenario where you want to make multiple service calls and combine the results at the end.

There are multiple ways how this can be achieved, we are going to see how we can do the same using Future and ExecutorService in java.

Let us first understand how and where Future class has to be used.

As per Javadoc a Future is “Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation. The result can only be retrieved using method get when the computation has completed, blocking if necessary until it is ready. Cancellation is performed by the cancel method. Additional methods are provided to determine if the task completed normally or was cancelled. Once a computation has completed, the computation cannot be cancelled. If you would like to use a Future for the sake of cancellability but not provide a usable result, you can declare types of the form Future and return null as a result of the underlying task.

Example use cases can be when you have to make a database call which will take more time and a REST web service call will also has to be called.

You can use Futures to make asynchronous calls so that both the operations can happen asynchronously.

The result of the async call can be retrieved by using the get() method.

Please note that the get() call will be a blocking call and hence has to be used after submitting the threads to the ExecutorService.

We will also be using Callable interface which is similar to Runnable interface but can return any object and also handle Exception.

Let’s see an example with java multithreading using ExecutorService and Future.

The below ServiceExecutor class implements Callable interface.

Consider this as a class which is used to make some REST web service calls and will return the result of the service. We are just returning the name in this example.


import java.util.concurrent.Callable;

public class
ServiceExecutor implements Callable{

  
private String name;

   public
ServiceExecutor(String name){
     
this.name = name;
  
}

  
public String call() throws Exception {
     
//make service call and return the response
     
return this.name;
  
}

}

In the below FutureTask class we are using ExecutorService from the Executor framework.

We are initializing a pool with 2 threads and submitting it to the pool.

After submitting both the callable objects to the thread pool and once the execution completes, we are getting the result back using get() method and concatenating it using string builder to print it.

import java.util.concurrent.ExecutionException;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Future;



public class FutureTask {



   public static void main(String[] args) {

      ExecutorService executorService =

            Executors.newFixedThreadPool(2);



      //Thread 1

      ServiceExecutor executor1 =

            new ServiceExecutor("thread 1");

      Future firstResult =

            executorService.submit(executor1);



      //Thread 2

      ServiceExecutor executor2 =

            new ServiceExecutor("thread 2");

      Future secondResult =

            executorService.submit(executor2);



      StringBuilder sb = new StringBuilder();

      try {

         sb.append(firstResult.get()).append(" ")

               .append(secondResult.get());

      } catch (InterruptedException e) {

         e.printStackTrace();

      } catch (ExecutionException e) {

         e.printStackTrace();

      }

      System.out.println("Final output: "+sb.toString());

      //shut down the executor service

      executorService.shutdown();

   }



}


Share:

How to switch between Oralce VM VirtualBox and Docker on Windows 10


If you are wondering how to switch between Oracle VM VirtualBox and Docker on Windows 10, you can follow the below steps to find out how you achieve the same.

To start using Oracle VM VirtualBox:

  • Open the Command Prompt as Administrator. 
          Right Click on Command Prompt > More > Run as administrator
  • Execute “bcdedit” command

          If you observe the last line in the above snapshot, hypervisorlaunchtype is set to Auto.
  • For you to be able to use VirtualBox, hyper-V has to be disabled. To do this, execute the below command.
          bcdedit /set hypervisorlaunchtype off

  • Verify that hypervisorlaunchtype is set to off

  • Restart your PC/laptop for the changes to take effect.
  • You should be able to use VirtualBox after restart.



To start using Docker:

  • Open the Command Prompt as Administrator.
         Right Click on Command Prompt > More > Run as administrator
  • Execute “bcdedit” command

           If you observe the last line in the above snapshot, hypervisorlaunchtype is set to off.
  • For you to be able to use VirtualBox, hyper-V has to be enabled. To do this, execute the below command.
            bcdedit /set hypervisorlaunchtype auto

  • Verify that hypervisorlaunchtype is set to auto
  • Restart your PC/laptop for the changes to take effect.
  • You should be able to use Docker after restart.

Share:

Coming Soon!

Python programming examples.

Share:

How to resolve Git merge conflict from eclipse?


If you are a developer working on Git there are high chances that you have come across the merge conflict error while merging your changes to git repo.

Let's see how we can resolve git conflicts.

Consider the below example where there are 2 developers (developer1 and developer2) working on the same git branch (developer branch in this example).

Developer1 is working on the below project in his eclipse workspace.




Developer2 is working on the below project in his eclipse workspace. (See gitconflict2 next to the project name)


Let’s consider a situation where both developer1 and developer2 are changing the same line of code (line 6) from the file App.java

Developer2 changes the statement on line 6 to “Developer 2” from “Developer 1” and will commit his code to git.

Commit and Pushed.
If Developer1 tries to pull the latest from repo now, eclipse will throw the below error which indicates that there is a conflict.


During the same time Developer1 has also changed the same line 6 from “Developer 1” to “First Developer” and is trying to check-in the file to git.
Before doing that lets do Team > Synchronize Workspace

As you can see from the above snapshot, there is a conflict in App.java as there were changes committed to the repo which you do not have in your file.

Now, let’s see how we can resolve this conflict and merge our file.

There are several ways to resolve git conflicts and we are going to see one of those.
  • ·         Developer1 takes a backup of the file which he has changed.
  • ·         Right click on the project > Team > Reset

Select Remote Tracking and select the required branch (developer in this example)

          (Please note that Hard is selected in Reset type)
  • ·         Click on Reset.
  • ·         Now merge your changes from the backup file.

  • ·         Stage the changes, provide appropriate Commit message and click on Commit and Push.

         Changes will be successfully pushed to git repo.

Now if developer2 pulls the latest from repo, he gets the commit from developer1.

















Share:

Coming Soon!!

  • Steps to view SonarQube test coverage in IntelliJ Idea.
  • Steps to include Karma/Jasmine test coverage in Jenkins SonarQube.

Share:

Must have tools for developers in 2023

  1. IntelliJ IDEA : IntelliJ IDEA has lot of cool features which will help you greatly improve your productivity and write code faster.
  2. Cmder : Cmder is a software package created out of pure frustration over the absence of nice console emulators on Windows.
  3. MTPuTTY (Multi-Tabbed PuTTY): Multi-Tabbed PuTTY PuTTY is the most popular SSH client for Windows.
  4. Postman : Postman makes API development faster, easier, and better.
  5. Notepad++ :  Is a free source code editor which supports several programming languages running under the MS Windows environment.
  6. 7Zip : 7-Zip is a file archiver with a high compression ratio. You can use 7-Zip on any computer, including a computer in a commercial organization. 7Zip can be used to extract gz, tar files as well on windows.
  7. Docker for windows : Docker is a computer program that performs operating-system-level virtualization, also known as "containerization". 
  8. Microsoft OneNote : Helps you organize the data you need quickly. This tool can be used to store all the required text data which is typically stored in Sticky Notes or notepad. The main advantage of onenote is that you can store all the required data by classifying it into sections and pages which will help you in finding the data faster. Also this can be exported into PDF if you want to share it with someone else.
  9. Robo 3T : Robo 3T (formerly Robomongo) doesn't emulate the MongoDB shell, it embeds the same engine and environment, that is a part of mongo shell. This is a must have tool if you are using mongo db as the database. 



Share:

What is Project Lombok and why you should use it?

What is Project Lombok?



Project Lombok is a java library which can be included in your java project and you will never have to write/generate boring getter/setter/equals etc. methods in your java class.

Lombok can be easily integrated with your IDE like Eclipse or IntelliJ Idea. Once integrated you will be able to use the methods generated from Lombok directly in your classes without writing them explicitly.

Lombok will add the specified methods via annotation during build time so that the methods are part of your class file.

Using Lombok greatly reduces the lines of code which will in-turn increase the code quality and leads to easier maintenance.

Few of the most important annotations in Lombok are:

  1. @Getter/@Setter - Which will generate getter/setter methods.
  2. @ToString - Generates a toString method with the declared variables.
  3. @EqualsAndHashCode - Generates equals and hashCode method.
  4. @Data - Combination of @ToString, @Getter, @Setter, @EqualsAndHashCode and @RequiredArgsConstructor.
To use lombok in your maven project you just need to add the below dependency in your pom.xml

<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
<scope>provided</scope>
</dependency>
</dependencies>

How to integrate Project Lombok to your IDE?
Eclipse: 


IntelliJ Idea :


Share:

Announcements

Will be posting twice a week on latest java libraries/frameworks which a developer needs to know in 2019.
Also will add the common errors and resolutions for the same.

Please feel free to comment if you need anything specific.

Recent Posts

Popular Posts

Search This Blog

Blog Archive

Powered by Blogger.

Contributors

Pages