Month: October 2018

Understanding React Pure Components

Many people are confused by the difference between a Functional Component and a Pure Component. Most of them think that they are the same, but this is not true. When you use a React Pure Component, We need to import PureComponent from React:

    import React, { PureComponent } from 'react';

If your React component’s render method is “pure” (that means it renders the same result, given the same props and state), you can use this function to improve the performance of your application. A Pure Component performs a shallow comparison for the props and nextProps objects as well as the state and nextState objects. Pure components do not include the shouldComponentUpdate(nextProps, nextState) method, and if you try to add it, you’ll get a warning from React.

In this article, you’ll learn to create a basic example to understand how Pure Components works. To begin, you need to install the Chrome extension React Developer Tools to do a simple debug in your application. Download React Developer Tools from https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi.

Building your React application

First, create your React application using create-react-app. Once that is done, you can proceed to create your first React component.

Before you install create-react-app, remember that you need to download and install Node from www.nodejs.org. You can install it for Mac, Linux, and Windows.

Install create-react-app globally by typing this command in your Terminal:

  npm install -g create-react-app

Alternatively, you can use a shortcut:

  npm i -g create-react-app

Now build your first React application by following these steps:

  1. Create your React application with the following command:
create-react-app my-first-react-app
  1. Go to the new application with cd my-first-react-appand start it with npm start.
  2. The application should now be running at http://localhost:3000.
  3. Create a new file called js inside your src folder:
import React, { Component } from 'react';



class Home extends Component {

render() {

return <h1>I'm Home Component</h1>;

  }

}



export default Home;

File: src/Home.js

  1. You may have noticed that you are exporting your class component at the end of the file, but it’s fine to export it directly on the class declaration, like this:
import React, { Component } from 'react';

    export default class Home extends Component {

render() {

return<h1>I'm Home Component</h1>;

      }

    }

File: src/Home.js

  1. Now that you have created the first component, you need to render it. So, open the jsfile, import the Home component, and add it to the render method of the App component. If you are opening this file for the first time, you’ll probably see a code like this:
import React, { Component } from 'react';

import logo from './logo.svg';

import './App.css';

class App extends Component {

render() {

return (
 Welcome to React
);       
}     
}     
export default App;

To get started, edit src/App.js               and save to reload.

File: src/App.js

  1. Now change this code a bit. You need to import your Home component and then add it to the JSX. You also need to replace the <p> element with your component, like this:   
import React, { Component } from 'react';

import logo from './logo.svg';



// We import our Home component here...

import Home from './Home';

import './App.css';

class App extends Component {

render() {

return (

Welcome to React
{/* Here we add our Home component to be render it */}

);} } export default App;

File: src/components/App.js

  1. Now, create the Numbers component:
// Dependencies

import React, { Component } from 'react';
// Components
import Result from './Result';

// Styles

import './Numbers.css';



class Numbers extends Component {

state = {

numbers: '', // Here we will save the input value

results: [] // In this state we will save the results of the sums

};

handleNumberChange = e => {

const { target: { value } } = e;



// Converting the string value to array

// "12345" => ["1", "2", "3", "4", "5"]

const numbers = Array.from(value);

// Summing all numbers from the array

 // ["1", "2", "3", "4", "5"] => 15

const result = numbers.reduce((a, b) => Number(a) + Number(b), 0);



// Updating the local state

this.setState({

numbers: value,

results: [...this.state.results, result]

});
}

render() {
return (
  {/* Rendering the results array */}
              {this.state.results.map((result, i) => (                               ))}

)       }     }   export default Numbers;

File: src/components/Numbers/Numbers.js

  1. Then, create the Result component (as a Class Component):
import React, { Component } from 'react';



class Result extends Component {

render() {

return<li>{this.props.result}</li>;

      }

    }



 export default Result;

File: src/components/Numbers/Result.js

  1. Finally, create the styles:
.Numbers {

      padding: 30px;

    }

.Numbers input[type=number]::-webkit-inner-spin-button,

    .Numbers input[type=number]::-webkit-outer-spin-button {

      -webkit-appearance: none;

      margin: 0;

    }



 .Numbers input {

      width: 500px;

      height: 60px;

      font-size: 20px;

      outline: none;

      border: 1px solid #ccc;

      padding: 10px;

    }



.Numbers ul {

      margin: 0 auto;

      padding: 0;

      list-style: none;

      width: 522px;

    }



 .Numbers ul li {

      border-top: 1px solid #ccc;

      border-left: 1px solid #ccc;

      border-right: 1px solid #ccc;

      padding: 10px;

    }



.Numbers ul li:first-child {

      border-top: none;

    }



.Numbers ul li:last-child {

      border-bottom: 1px solid #ccc;

    }

File: src/components/Numbers/Numbers.css

How React Pure Component works…

If you run the application, you will see this:

  1. You have used an input with the number type, which means you’ll only accept numbers if you start writing numbers (1, then 2, then 3, and such). You will see the results of the sum on each row (0 + 1 = 1, 1 + 2 = 3, 3 + 3 = 6):

Now, inspect the application using React Developer Tools. You need to enable the Highlight Updates option:

After this, start writing multiple numbers in the input (quickly), and you will see all the renders that React is performing:

As you can see, React is doing a lot of renderings. When the highlights are red, it means the performance of that component is not good. Here’s when React Pure Components will help you. Migrate your Result component to be a Pure Component:

import React, { PureComponent } from 'react';



class Result extendsPureComponent {

render() {

return <li>{this.props.result}</li>;

      }

    }



   export default Result;

File: src/components/Numbers/Result.js

Now if you try to do the same with the numbers, see the difference:

With the Pure Component React, you do less renders in comparison to a Class Component. Probably, you may now think that if you use a Stateless component instead of a Pure Component, the result will be the same. Unfortunately, this won’t happen. If you want to verify this, change the Result component again and convert it into a Functional Component.:

import React from 'react';



const Result = props => <li>{props.result}</li>;



 export default Result;

File: src/components/Numbers/Result.js

See what happens with the renders:

As you can see, the result is the same as the Class Component. This means that using a Stateless Component will not help you improve the performance of your application all the time. If you have components that you consider are pure, consider converting them into Pure components.

If you found this article interesting, you can explore Carlos Santana Roldan’s React Cookbook to be on the road to becoming a React expert. React Cookbook has over 66 hands-on recipes that cover UI development, animations, component architecture, routing, databases, testing, and debugging with React.

How to Use the jcmd Command for the JVM

This article will focus on the diagnostic command introduced with Java 9 as a command-line utility, jcmd. If the bin folder is on the path, you can invoke it by typing jcmd on the command line. Otherwise, you have to go to the bin directory or prepend the jcmd in your examples with the full or relative (to the location of your command line window) path to the bin folder.

If you open the bin folder of the Java installation, you can find quite a few command-line utilities there. These can be used to diagnose issues and monitor an application deployed with the Java Runtime Environment (JRE). They use different mechanisms to get the data they report. The mechanisms are specific to the Virtual Machine (VM) implementation, operating systems, and release. Typically, only a subset of these tools is applicable to a given issue.

If you do type it and there is no Java process currently running on the machine, you’ll get back only one line, as follows:

87863 jdk.jcmd/sun.tools.jcmd.JCmd

This shows that only one Java process is currently running (the jcmd utility itself) and it has the process identifier(PID) of 87863 (which will be different with each run).

JAVA Example

Now run a Java program, for example:

java -cp ./cookbook-1.0.jar

                   com.packt.cookbook.ch11_memory.Chapter11Memory

The output of jcmd will show (with different PIDs) the following:

87864 jdk.jcmd/sun.tools.jcmd.JCmd

87785 com.packt.cookbook.ch11_memory.Chapter11Memory

If entered without any options, the jcmd utility reports the PIDs of all the currently running Java processes. After getting the PID, you can then use jcmd to request data from the JVM that runs the process:

jcmd 88749 VM.version

Alternatively, you can avoid using PID (and calling jcmd without parameters) by referring to the process by the main class of the application:

jcmd Chapter11Memory VM.version

You can read the JVM documentation for more details about the jcmd utility and how to use it.

How to do it…

jcmd is a utility that allows you to issue commands to a specified Java process:

  1. Get the full list of the jcmdcommands available for a particular Java process by executing the following line:

     

jcmd PID/main-class-name help

Instead of PID/main-class, enter the process identifier or the main class name. The list is specific to JVM, so each listed command requests the data from the specific process.

  1. In JDK 8, the following jcmdcommands were available:
JFR.stop

JFR.start

JFR.dump

JFR.check

VM.native_memory

VM.check_commercial_features

VM.unlock_commercial_features

ManagementAgent.stop

ManagementAgent.start_local

ManagementAgent.start

GC.rotate_log

Thread.print

GC.class_stats

GC.class_histogram

GC.heap_dump

GC.run_finalization

GC.run

VM.uptime

VM.flags

VM.system_properties

VM.command_line

VM.version

JDK 9 introduced the following jcmd commands (JDK 18.3 and JDK 18.9 did not add any new commands):

  • queue: Prints the methods queued for compilation with either C1 or C2 (separate queues)
  • codelist: Prints n-methods (compiled) with full signature, address range, and state (alive, non-entrant, and zombie), and allows the selection of printing to stdout, a file, XML, or text printout
  • codecache: Prints the content of the code cache, where the JIT compiler stores the generated native code to improve performance
  • directives_add file: Adds compiler directives from a file to the top of the directives stack
  • directives_clear: Clears the compiler directives stack (leaves the default directives only)
  • directives_print: Prints all the directives on the compiler directives stack from top to bottom
  • directives_remove: Removes the top directive from the compiler directives stack
  • heap_info: Prints the current heap parameters and status
  • finalizer_info: Shows the status of the finalizer thread, which collects objects with a finalizer (that is, a finalize()method)
  • configure: Allows configuring the Java Flight Recorder
  • data_dump: Prints the Java Virtual Machine Tool Interface data dump
  • agent_load: Loads (attaches) the Java Virtual Machine Tool Interface agent
  • status: Prints the status of the remote JMX agent
  • print: Prints all the threads with stack traces
  • log [option]: Allows setting the JVM log configuration at runtime, after the JVM has started (the availability can be seen using VM.log list)
  • info: Prints the unified JVM info (version and configuration), a list of all threads and their state (without thread dump and heap dump), heap summary, JVM internal events (GC, JIT, safepoint, and so on), memory map with loaded native libraries, VM arguments and environment variables, and details of the operation system and hardware
  • dynlibs: Prints information about dynamic libraries
  • set_flag: Allows setting the JVM writable(also called manageable) flags
  • stringtableand VM.symboltable: Print all UTF-8 string constants
  • class_hierarchy [full-class-name]: Prints all the loaded classes or just a specified class hierarchy
  • classloader_stats: Prints information about the classloader
  • print_touched_methods: Prints all the methods that have been touched (have been read at least) at runtime

As you can see, these new commands belong to several groups, denoted by the prefix compiler, garbage collector (GC), Java Flight Recorder (JFR), Java Virtual Machine Tool Interface (JVMTI), Management Agent (related to remote JMX agent), thread, and VM.

How it works…

  1. To get help for the jcmdutility, run the following command:
jcmd -h

Here is the result of the command:

It tells you that the commands can also be read from the file specified after -f, and there is a PerfCounter.print command, which prints all the performance counters (statistics) of the process.

  1. Run the following command:
jcmd Chapter11Memory GC.heap_info

The output may look similar to this screenshot:

It shows the total heap size and how much of it was used, the size of a region in the young generation and how many regions are allocated, and the parameters of Metaspace and class space.

  1. The following command is very helpful in case you are looking for runaway threads or would like to know what else is going on behind the scenes:
jcmd Chapter11Memory Thread.print

Here is a fragment of the possible output:

  1. This command is probably used most often, as it produces a wealth of information about the hardware, the JVM process as a whole, and the current state of its components:
jcmd Chapter11Memory VM.info

It starts with a summary, as follows:

The general process description is as follows:

Then the details of the heap are shown (this is only a tiny fragment of it):

It then prints the compilation events, GC heap history, de-optimization events, internal exceptions, events, dynamic libraries, logging options, environment variables, VM arguments, and many parameters of the system running the process.

The jcmd commands give a deep insight into the JVM process, which helps to debug and tune the process for best performance and optimal resource usage.

If you found this article interesting, you can dive into Java 11 Cookbook – Second Edition to explore the new features added to Java 11 that will make your application modular, secure, and fast. Java 11 Cookbook – Second Edition offers a range of software development solutions with simple and straightforward Java 11 code examples to help you build a modern software system.

How to Develop a Real-Time Object Detection Project

Developing a real-time object detection project

You can develop a video object classification application using pre-trained YOLO models (that is, transfer learning), Deeplearning4j (DL4J), and OpenCV that can detect labels such as cars and trees inside a video frame. You can find the relevant code files for this tutorial at https://github.com/PacktPublishing/Java-Deep-Learning-Projects/tree/master/Chapter06. This application is also about extending an image detection problem to video detection. Time to get started!

Step 1 – Loading a pre-trained YOLO model

Since Alpha release 1.0.0, DL4J provides a Tiny YOLO model via ZOO. For this, you need to add a dependency to your Maven friendly pom.xml file:

<dependency>

  <groupId>org.deeplearning4j</groupId>

  <artifactId>deeplearning4j-zoo</artifactId>

  <version>${dl4j.version}</version>

</dependency>

Apart from this, if possible, make sure that you utilize the CUDA and cuDNN by adding the following dependencies:

<dependency>

  <groupId>org.nd4j</groupId>

  <artifactId>nd4j-cuda-9.0-platform</artifactId>

  <version>${nd4j.version}</version>

</dependency>

<dependency>

  <groupId>org.deeplearning4j</groupId>

  <artifactId>deeplearning4j-cuda-9.0</artifactId>

  <version>${dl4j.version}</version>

</dependency>

Now, use the below code to load the pre-trained Tiny YOLO model as a Computation Graph. You can use the PASCAL Visual Object Classes (PASCAL VOC) dataset (see more at http://host.robots.ox.ac.uk/pascal/VOC/) to train the YOLO model.

private ComputationGraph model;

private TinyYoloModel() {

        try {

            model = (ComputationGraph) new TinyYOLO().initPretrained();

            createObjectLabels();

        } catch (IOException e) {

            throw new RuntimeException(e);

        }

    }

In the above code segment, the createObjectLabels() method refers to the labels from the PASCAL Visual Object Classes (PASCAL VOC) dataset. The signature of the method can be seen as follows:

private HashMap<Integer, String> labels; 

void createObjectLabels() {

        if (labels == null) {

            String label = "aeroplanen" + "bicyclen" + "birdn" + "boatn" + "bottlen" + "busn" + "carn" +

                    "catn" + "chairn" + "cown" + "diningtablen" + "dogn" + "horsen" + "motorbiken" +

                    "personn" + "pottedplantn" + "sheepn" + "sofan" + "trainn" + "tvmonitor";

            String[] split = label.split("\n");

            int i = 0;

            labels = new HashMap<>();

            for(String label1 : split) {

                labels.put(i++, label1);

            }

        }

    }

Now, create a Tiny YOLO model instance:

static final TinyYoloModel yolo = new TinyYoloModel();

    public static TinyYoloModel getPretrainedModel() {

        return yolo;

    }

Take a look at the model architecture and the number of hyper parameters in each layer:

TinyYoloModel model = TinyYoloModel.getPretrainedModel(); System.out.println(TinyYoloModel.getSummary());
Network summary and layer structure of a pre-trained Tiny YOLO model

Your Tiny YOLO model has around 1.6 million parameters across its 29-layer network. However, the original YOLO 2 model has more layers. You can look at the original YOLO 2 at https://github.com/yhcc/yolo2/blob/master/model_data/model.png.

Step 2 – Generating frames from video clips

To deal with real-time video, you can use video processing tools or frameworks such as JavaCV that can split a video into individual frames. Take the image height and width. For this, include the following dependency in the pom.xml file:

<dependency>

  <groupId>org.bytedeco</groupId>

  <artifactId>javacv-platform</artifactId>

  <version>1.4.1</version>

</dependency>

JavaCV uses wrappers from the JavaCPP presets of libraries commonly used by researchers in the field of computer vision (for example, OpenCV and FFmpeg). It provides utility classes to make their functionality easier to use on the Java platform, including Android.

For this project, there are two video clips (each 1 minute long) that should give you a glimpse into an autonomous driving car. This dataset has been downloaded from the following YouTube links:

After downloading them, they were renamed as follows:

  • SelfDrivingCar_Night.mp4
  • SelfDrivingCar_Day.mp4

When you play these clips, you’ll see how Germans drive their cars at 160 km/h or even faster. Now, parse the video (first use day 1) and see some properties to get an idea of video quality hardware requirements:

String videoPath = "data/SelfDrivingCar_Day.mp4";

FFmpegFrameGrabber frameGrabber = new FFmpegFrameGrabber(videoPath);

frameGrabber.start();

Frame frame;

double frameRate = frameGrabber.getFrameRate();

System.out.println("The inputted video clip has " + frameGrabber.getLengthInFrames() + " frames");

System.out.println("Frame rate " + framerate + "fps");
>>> 
 The inputted video clip has 1802 frames. The inputted video clip has frame rate of 29.97002997002997.

The inputted video clip has 1802 frames. The inputted video clip has frame rate of 29.97002997002997.

Now grab each frame and use Java2DFrameConverter to convert frames to JPEG images:

Java2DFrameConverter converter = new Java2DFrameConverter();

// grab the first frame

frameGrabber.setFrameNumber(1);

frame = frameGrabber.grab();

BufferedImage bufferedImage = converter.convert(frame);

System.out.println("First Frame" + ", Width: " + bufferedImage.getWidth() + ", Height: " + bufferedImage.getHeight());



// grab the second frame

frameGrabber.setFrameNumber(2);

frame = frameGrabber.grab();

bufferedImage = converter.convert(frame);

System.out.println("Second Frame" + ", Width: " + bufferedImage.getWidth() + ", Height: " + bufferedImage.getHeight());
>>> 

  First Frame: Width-640, Height-360 Second Frame: Width-640, Height-360

The above code will generate 1,802 JPEG images against an equal number of frames. Take a look at the generated images:

From video clip to video frame to image

Thus, the 1-minute long video clip has a fair number (that is, 1,800) of frames and is 30 frames per second. In short, this video clip has 720p video quality. So, you can understand that processing this video should require good hardware; in particular, having a GPU configured should help.

Step 3 – Feeding generated frames into the Tiny YOLO model

Now that you know some properties of the clip, start generating the frames to be passed to the Tiny YOLO pre-trained model. First, look at a less important but transparent approach:

private volatileMat[] v = new Mat[1];

private String windowName = "Object Detection from Video";

try {

    for(int i = 1; i < frameGrabber.getLengthInFrames();    

    i+ = (int)frameRate) {

                frameGrabber.setFrameNumber(i);

                frame = frameGrabber.grab();

                v[0] = new OpenCVFrameConverter.ToMat().convert(frame);

                model.markObjectWithBoundingBox(v[0], frame.imageWidth,

                                               frame.imageHeight, true, windowName);

                imshow(windowName, v[0]);



                char key = (char) waitKey(20);

                // Exit on escape:

                if (key == 27) {

                    destroyAllWindows();

                    break;

                }

            }

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            frameGrabber.stop();

        }

        frameGrabber.close();

In the above code, you send each frame to the model. Then, you use the Mat class to represent each frame in an n-dimensional, dense, numerical multi-channel (that is, RGB) array.

In other words, you split the video clip into multiple frames and pass into the Tiny YOLO model to process them one by one. This way, you applied a single neural network to the full image.

Step 4 – Real Object detection from image frames

Tiny YOLO extracts the features from each frame as an n-dimensional, dense, numerical multi-channel array. Then, each image is split into a smaller number of rectangles (boxes):

public void markObjectWithBoundingBox(Mat file, int imageWidth, int imageHeight, boolean newBoundingBOx,

String winName) throws Exception {

        // parameters matching the pretrained TinyYOLO model

int W = 416; // width of the video frame 

        int H = 416; // Height of the video frame

        int gW = 13; // Grid width

        int gH = 13; // Grid Height

        double dT = 0.5; // Detection threshold



Yolo2OutputLayer outputLayer = (Yolo2OutputLayer) model.getOutputLayer(0);

        if (newBoundingBOx) {

            INDArray indArray = prepareImage(file, W, H);

            INDArray results = model.outputSingle(indArray);

            predictedObjects = outputLayer.getPredictedObjects(results, dT);

            System.out.println("results = " + predictedObjects);

            markWithBoundingBox(file, gW, gH, imageWidth, imageHeight);

        } else {

            markWithBoundingBox(file, gW, gH, imageWidth, imageHeight);

        }

        imshow(winName, file);

    }

In the above code, the prepareImage() method takes video frames as images, parses them using the NativeImageLoader class, does the necessary preprocessing, and extracts image features that are further converted into a INDArray format, consumable by the model:

INDArray prepareImage(Mat file, int width, int height) throws IOException {

        NativeImageLoader loader = new NativeImageLoader(height, width, 3);

        ImagePreProcessingScaler imagePreProcessingScaler = new ImagePreProcessingScaler(0, 1);

        INDArray indArray = loader.asMatrix(file);

        imagePreProcessingScaler.transform(indArray);

        return indArray;

    }

Then, the markWithBoundingBox() method is used for non-max suppression in the case of more than one bounding box.

Step 5 – Non-max suppression in case of more than one bounding box

As YOLO predicts more than one bounding box per object, non-max suppression is implemented; it merges all detections that belong to the same object. Therefore, instead of using bxbybh, and bw, you can use the top-left and bottom-right points. gridWidth and gridHeight are the number of small boxes you split your image into. In this case, it is 13 x 13, where w and h are the original image frame dimensions:

void markObjectWithBoundingBox(Mat file, int gridWidth, int gridHeight, int w, int h, DetectedObject obj) { 

        double[] xy1 = obj.getTopLeftXY();

        double[] xy2 = obj.getBottomRightXY();

        int predictedClass = obj.getPredictedClass();

int x1 = (int) Math.round(w * xy1[0] / gridWidth);

        int y1 = (int) Math.round(h * xy1[1] / gridHeight);

        int x2 = (int) Math.round(w * xy2[0] / gridWidth);

        int y2 = (int) Math.round(h * xy2[1] / gridHeight);

        rectangle(file, new Point(x1, y1), new Point(x2, y2), Scalar.RED);

        putText(file, labels.get(predictedClass), new Point(x1 + 2, y2 - 2),

                                 FONT_HERSHEY_DUPLEX, 1, Scalar.GREEN);

    }

Finally, remove those objects that intersect with the max suppression, as follows:

static void removeObjectsIntersectingWithMax(ArrayList<DetectedObject> detectedObjects,

DetectedObject maxObjectDetect) {

        double[] bottomRightXY1 = maxObjectDetect.getBottomRightXY();

        double[] topLeftXY1 = maxObjectDetect.getTopLeftXY();

        List<DetectedObject> removeIntersectingObjects = new ArrayList<>();

for(DetectedObject detectedObject : detectedObjects) {

            double[] topLeftXY = detectedObject.getTopLeftXY();

            double[] bottomRightXY = detectedObject.getBottomRightXY();

            double iox1 = Math.max(topLeftXY[0], topLeftXY1[0]);

            double ioy1 = Math.max(topLeftXY[1], topLeftXY1[1]);



            double iox2 = Math.min(bottomRightXY[0], bottomRightXY1[0]);

            double ioy2 = Math.min(bottomRightXY[1], bottomRightXY1[1]);



            double inter_area = (ioy2 - ioy1) * (iox2 - iox1);



            double box1_area = (bottomRightXY1[1] - topLeftXY1[1]) * (bottomRightXY1[0] - topLeftXY1[0]);

            double box2_area = (bottomRightXY[1] - topLeftXY[1]) * (bottomRightXY[0] - topLeftXY[0]);



            double union_area = box1_area + box2_area - inter_area;

            double iou = inter_area / union_area; 



            if(iou > 0.5) {

                removeIntersectingObjects.add(detectedObject);

            }

        }

        detectedObjects.removeAll(removeIntersectingObjects);

    }

In the second block, you scaled each image into 416 x 416 x 3 (that is, W x H x 3 RGB channels). This scaled image is then passed to Tiny YOLO for predicting and marking the bounding boxes as follows:

Your Tiny YOLO model predicts the class of an object detected in a bounding box

Once the markObjectWithBoundingBox() method is executed, the following logs containing the predicted class, bxbybhbw, and confidence (that is, the detection threshold) will be generated and shown on the console:

 [4.6233e-11]], predictedClass=6),

DetectedObject(exampleNumber=0,

centerX=3.5445247292518616, centerY=7.621537864208221,

width=2.2568163871765137, height=1.9423424005508423,

confidence=0.7954192161560059,

classPredictions=[[ 1.5034e-7], [ 3.3064e-9]...

Step 6 – Wrapping up everything and running the application

Up to this point, you know the overall workflow of your approach. You can now wrap up everything and see whether it really works. However, before this, take a look at the functionalities of different Java classes:

  • java: This shows how to grab frames from the video clip and save each frame as a JPEG image. Besides, it also shows some exploratory properties of the video clip.
  • java: This instantiates the Tiny YOLO model and generates the label. It also creates and marks the object with the bounding box. Nonetheless, it shows how to handle non-max suppression for more than one bounding box per object.
  • java: This main class continuously grabs the frames and feeds them to the Tiny YOLO model (until the user presses the Esckey). Then, it predicts the corresponding class of each object successfully detected inside the normal or overlapped bounding boxes with non-max suppression (if required).

In short, first, you create and instantiate the Tiny YOLO model. Then, you grab the frames and treat each frame as a separate JPEG image. Next, you pass all the images to the model and the model does its trick as outlined previously. The whole workflow can now be depicted with some Java code as follows:

// ObjectDetectorFromVideo.java

public class ObjectDetectorFromVideo{

    privatevolatile Mat[] v = new Mat[1];

    private String windowName;



    public static void main(String[] args) throws java.lang.Exception {

        String videoPath = "data/SelfDrivingCar_Day.mp4";

        TinyYoloModel model = TinyYoloModel.getPretrainedModel();

        

        System.out.println(TinyYoloModel.getSummary());

        new ObjectDetectionFromVideo().startRealTimeVideoDetection(videoPath, model);

    }



    public void startRealTimeVideoDetection(String videoFileName, TinyYoloModel model)

throwsjava.lang.Exception {

        windowName = "Object Detection from Video";

        FFmpegFrameGrabber frameGrabber = new FFmpegFrameGrabber(videoFileName);

        frameGrabber.start();



        Frame frame;

        double frameRate = frameGrabber.getFrameRate();

        System.out.println("The inputted video clip has " + frameGrabber.getLengthInFrames() + " frames");

        System.out.println("The inputted video clip has frame rate of " + frameRate);



        try {

            for(int i = 1; i < frameGrabber.getLengthInFrames(); i+ = (int)frameRate) {

                frameGrabber.setFrameNumber(i);

                frame = frameGrabber.grab();

                v[0] = new OpenCVFrameConverter.ToMat().convert(frame);

                model.markObjectWithBoundingBox(v[0], frame.imageWidth, frame.imageHeight,

                                                true, windowName);

                imshow(windowName, v[0]);



                char key = (char) waitKey(20);

                // Exit on escape:

                if(key == 27) {

                    destroyAllWindows();

                    break;

                }

            }

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            frameGrabber.stop();

        }

        frameGrabber.close();

    }

}

Once the preceding class is executed, the application should load the pre-trained model and the UI should be loaded, showing each object being classified:

Your Tiny YOLO model can predict multiple cars simultaneously from a video clip (day)

Now, to see the effectiveness of your model even in night mode, perform a second experiment on the night dataset. To do this, just change one line in the main() method, as follows:

String videoPath = "data/SelfDrivingCar_Night.mp4";

Once the preceding class is executed using this clip, the application should load the pre-trained model and the UI should be loaded, showing each object being classified:

Your Tiny YOLO model can predict multiple cars simultaneously from a video clip (night)

Furthermore, to see the real-time output, execute the given screen recording clips showing the output of the application.

If you found this interesting, you can explore Md. Rezaul Karim’s Java Deep Learning Projects to build and deploy powerful neural network models using the latest Java deep learning libraries. Java Deep Learning Projects starts with an overview of deep learning concepts and then delves into advanced projects.

Using Modules in Node.js

Node.js is an event-driven, server-side JavaScript environment. Node.js runs JS using the V8 engine developed by Google for use in their Chrome web browser. Leveraging V8 allows Node.js to provide a server-side runtime environment that compiles and executes JS at lightning speeds.

The Module System

This article covers the Node’s module system and the different categories of the Node.js modules.

Application Modularization

Like most programming languages, Node.js uses modules as a way of organizing code. The module system allows you to organize your code, hide information, and only expose the public interface of a component using module.exports.

Node.js uses the CommonJS specification for its module system:

  • Each file is its own module, for instance, in the following example, jsand math.js are both modules
  • Each file has access to the current module definition using the modulevariable
  • The export of the current module is determined by the module.exportsvariable
  • To import a module, use the globally available requirefunction

Take a look at a simple example:

// math.js file

function add(a, b)

{

  return a + b;

}

…

…

module.exports =

{

  add,

  mul,

  div,

};

// index.js file

const math = require('./math');

console.log(math.add(30, 20)); // 50

To call other functions such as mul and div, use object destructuring as an alternative when requiring the module, for example, const { add } = require(‘./math’);. The code files for the section The Module System are placed at Code/Lesson-1/b-module-system.

Module Categories

You can place Node.js modules into three categories:

  • Built-in (native) modules: These are modules that come with Node.js itself; you don’t have to install them separately.
  • Third-party modules: These are modules that are often installed from a package repository. npm is a commonly used package repository, but you can still host packages on GitHub, your own private server, and so on.
  • Local modules: These are modules that you have created within your application, like the example given previously.

Built-In Modules

These are modules that can be used straight away without any further installation. All you need to do is to require them. There are quite a lot of them, but here are a few that you are likely to come across when building web applications:

  • assert: Provides a set of assertion tests to be used during unit testing
  • buffer: To handle binary data
  • child_process: To run a child process
  • crypto: To handle OpenSSL cryptographic functions
  • dns: To do DNS lookups and name resolution functions
  • events: To handle events
  • fs: To handle the filesystem
  • httpor https: For creating HTTP(s) servers
  • stream: To handle streaming data
  • util: To access utility functions like deprecate (for marking functions as deprecated), format (for string formatting), inspect (for object debugging), and so on

For example, the following code reads the content of the lesson-1/temp/sample.txt file using the in-built fs module:

const fs = require('fs');

let file = `${__dirname}/temp/sample.txt`;

fs.readFile(file, 'utf8', (err, data) =>

{

  if (err) throw err;

  console.log(data);

});

npm – Third-Party Module Registry

Node Package Manager (npm) is the package manager for JavaScript and the world’s largest software registry, enabling developers to discover packages of reusable code. To install an npm package, you only need to run the npm install <package-name> command within your project directory.

Here’s a simple example. If you want to use a package (library) like request in your project, you can run the following command on your Terminal, within your project directory:

npm install request

To use it in your code, you should require it, like any other module:

const request = require('request');

request('http://www.example.com', (error, response, body) =>

{

  if (error) console.log('error:', error); // Print the error if one occurred

  else console.log('body:', body); // Print the HTML for the site.

});

More details about npm can be found at https://docs.npmjs.com/. When you run the npm install <module-name> command on your project for the first time, the node_modules folder gets created at the root of your project.

Scanning for node_modules

It’s worth noting how Node.js goes about resolving a particular required module. For example, if a /home/tony/projects/foo.js file has a require call require(‘bar’), Node.js scans the filesystem for node_modules in the following order. The first bar.js that is found is returned as follows:

  • /home/tony/projects/node_modules/bar.js
  • /home/tony/node_modules/bar.js
  • /home/node_module/bar.js
  • /node_modules/bar.js

Node.js looks for node_moduels/bar in the current folder followed by every parent folder until it reaches the root of the filesystem tree for the current file. Note that the module foo/index.js can be required as foo, without specifying an index and will be picked by default.

Handy npm Commands

Now dive a little deeper into npm, by looking at some of the handy npm commands that you will often need:

  • npm init: Initializes a Node.js project. This should be run at the root of your project and will create a respective jsonfile. This file usually has the following parts (keys):
  • name: Name of the project.
  • version: Version of the project.
  • description: Project description.
  • main: The entry-point to your project, the main file.
  • scripts: This will be a list of other keys whose values will be the scripts to be run, for example, test, dev-server. Therefore, to run this script, you will only need to type commands such as npm run dev-server, npm run test, and so on.
  • dependencies: List of third-party packages and their versions used by the project. Whenever you do npm install <package-name> –save, this list is automatically updated.
  • devDependencies: List of third-party packages that are not required for production, but only during development. This will usually include packages that help to automate your development workflow, for example, task runners like gulp.js. This list is automatically updated whenever you do npm install <package-name> –save-dev.
  • npm install: This will install all the packages, as specified in the jsonfile.
  • npm install <package-name> <options>:
  • The –saveoption installs the package and saves the details in the json file.
  • The –save-devoption installs the package and saves the details in the json, under devDependencies.
  • The –globaloption installs the package globally in the whole system, not only in the current system. Due to permissions, this might require running the command with administrator rights, for example, sudo npm install <package-name> –global.
  • npm install <package-name>@<version>, installs a specific version of a package. Usually, if a version is not specified, the latest version will be installed.
  • npm list: Lists the packages that have been installed for the project, reading from what is installed in node_modules.
  • npm uninstall <package-name>: Removes an installed package.
  • npm outdated: Lists installed packages that are outdated, that is, newer versions have been released.

Local Modules

You have already looked at how local modules are loaded from the previous example that had math.js and index.js.

Since JavaScript Object Notation (JSON) is such an important part of the web, Node.js has fully embraced it as a data format, even locally. You can load a JSON object from the local filesystem the same way you load a JavaScript module. During the module loading sequence, whenever a file.js is not found, Node.js looks for a file.json.

See the example files in lesson-1/b-module-system/1-basics/load-json.js:

const config = require('./config/sample');

console.log(config.foo); // bar

Here, you will notice that once required, the JSON file is transformed into a JavaScript object implicitly. Other languages will have you read the file and perhaps use a different mechanism to convert the content into a data structure such as a map, a dictionary, and so on.

For local files, the extension is optional, but should there be a conflict, it might be necessary to specify the extension. If you have both a sample.js and a sample.json file in the same folder, the .js file will be picked by default; it would be prudent to specify the extension, for example const config = require(‘./config/sample.json’).

When you run npm install, without specifying the module to install, npm will install the list of packages specified (under dependencies and devDependencies in the package.json file in your project). If package.json does not exist, it will give an error indicating that no such file has been found.

Activity: Running Basic Node.js Code

Open the IDE and the Terminal to implement this solution and learn how to write a basic Node.js file and run it. Write a very basic mathematical library with handy mathematical functions using the following steps:

  1. Create your project directory (folder), where all the code for this will be kept. Inside this directory, create another directory named lesson-1, and inside it, create another directory called activity-a. All this can be done using the following command:
mkdir -p beginning-nodejs/lesson-1/activity-a
  1. Inside activity-a, create a file using the touch maths.js
  2. Inside this file, create the following functions:
  • add: This takes any two numbers and returns the sum of both, for example, add(2, 5)returns 7
  • sum: Unlike add, sum takes any number of numbers and returns their sum, for example, sum(10, 5, 6)returns 21
  1. After these functions, write the following code to act as tests for your code:
console.log(add(10, 6)); // 16

console.log(sum(10, 5, 6)); // 21
  1. Now, on the Terminal, change directory to lesson-1.
  2. To run the code, run the following command:
node activity-a/math.js

The 16 and 21 values should be printed out on the Terminal.

Activity: Using a Third-Party Package

This activity will build upon the, Running Basic Node.js activity. If the argument is a single array, sum up the numbers, and if it’s more than one array, first combine the arrays into one before summing up. Use the concat() function from lodash, which is a third-party package that you need to install.

Now create a new function, sumArray, which can sum up numbers from one or more arrays using the following steps:

  1. Inside Lesson-1, create another folder called activity-b.
  2. On the Terminal, change directory to activity-band run the following command:
npm init
  1. This will take you to an interactive prompt; just press Enter all the way, leaving the answers as suggested defaults. The aim here is to get a json file, which will help organize your installed packages.
  2. Since you’ll be using lodash, install it. Run the following command:
npm install lodash--save

Notice that you’re adding the –save option on your command so that the package installed can be tracked in package.json. When you open the package.json file created in step 3, you will see an added dependencies key with the details.

  1. Create a jsfile in the activity-b directory and copy the math.js code from ActivityRunning Basic Node.js into this file.
  2. Now, add the sumArrayfunction right after the sum
  3. Start with requiring lodash, which you installed in step 4 since you’re going to use it in the sumArrayfunction:
const _ = require('lodash');
  1. The sumArrayfunction should call the sum function to reuse your code. Use the spread operator on the array. See the following code:
function sumArray()

{

  let arr = arguments[0];

  if (arguments.length > 1)

  {

    arr = _.concat(...arguments);

  }

  // reusing the sum function

  // using the spread operator (...) since

  // sum takes an argument of numbers

  return sum(...arr);

}
  1. At the end of the file, export the three functions, add, sum, and sumArraywith exports.
  2. In the same activity-bfolder, create a file, js.
  3. In jsfile, require ./math.js and go ahead to use sumArray:
// testing

console.log(math.sumArray([10, 5, 6])); // 21

console.log(math.sumArray([10, 5], [5, 6], [1, 3])) // 30
  1. Run the following code on the Terminal:
node index.js

You should see 21 and 30 printed out.

If you found this article interesting, you can explore Anthony Nandaa’s Beginning API Development with Node.js to learn everything you need to get up and running with cutting-edge API development using JavaScript and Node.js. Beginning API Development with Node.js begins with the basics of Node.js in the context of backend development and quickly leads you through the creation of an example client that pairs up with a fully authenticated API implementation.

How to Work with the Latest JS features in React

Working with the latest javascript features in React

React is mainly written with modern JavaScript (ES6, ES7, and ES8). If you want to take advantage of React, there are some modern JS features that you should master to get the best results for your React applications.

In this article, you’ll learn the essential JS features so that you are ready to start working on your first React application.

How to do it

In this section, you’ll see how to use the most important JS features in React:

  • let and const: The new way to declare variables in JavaScript is using let or const. You can use let to declare variables that can change their value but in a block scope. The difference between let and var is that let is a block scoped variable that cannot be global, and with var, you can declare a global variable, for example:
var name = 'Carlos Santana';

let age = 30;



console.log(window.name); // Carlos Santana

console.log(window.age);  // undefined
  • The best way to understand block scope is by declaring a forloop with var and let. First, use var and see its behavior:
for (var i = 1 ; i <= 10; i++) {

console.log(i); // 1, 2, 3, 4... 10

    }



console.log(i); // Will print the last value of i: 10
  • If you write the same code with let, this will be the result:
for (let i = 1 ; i <= 10; i++) {

console.log(i); // 1, 2, 3, 4... 10

    }



console.log(i); // Uncaught ReferenceError: i is not defined

  • With const, you can declare constants, which means that the value can’t be changed (except for arrays and objects):
const pi = 3.1416;

pi = 5; // Uncaught TypeError: Assignment to constant variable.
  • If you declare an array with const, you can manipulate the array elements (add, remove, or modify elements):
constcryptoCurrencies = ['BTC', 'ETH', 'XRP'];



// Adding ERT: ['BTC', 'ETH', 'XRP', 'ERT'];

cryptoCurrencies.push('ERT');



    // Will remove the first element: ['ETH', 'XRP', 'ERT'];

cryptoCurrencies.shift();



// Modifying an element

cryptoCurrencies[1] = 'LTC'; // ['ETH', 'LTC', 'ERT'];
  • Also, using objects, you can add, remove, or modify the nodes:
const person = {

name: 'Carlos Santana',

age: 30,

email: 'carlos@milkzoft.com'

    };



// Adding a new node...

person.website = 'https://www.codejobs.com';



// Removing a node...

deleteperson.email;



// Updating a node...

person.age = 29;
  • Spread operator:The spread operator (…) splits an iterable object into individual values. In React, it can be used to push values into another array, for example when you want to add a new item to a to-do list utilizing setState:
this.setState({

items: [

...this.state.items, // Here we are spreading the current items

        {

task: 'My new task', // This will be a new task in our Todo list.

        }

      ]

    });
  • Also, the Spread operator can be used in React to spread attributes (props) in JSX:
render() {

const props = {};



      props.name = 'Carlos Santana';

props.age = 30;

props.email = 'carlos@milkzoft.com';



return<Person{...props}/>;

    }
  • Rest parameter:The rest parameter is also represented by …. The last parameter in a function prefixed with … is called the rest parameter. The rest parameter is an array that will contain the rest of the parameters of a function when the number of arguments exceeds the number of named parameters:
functionsetNumbers(param1, param2, ...args) {

// param1 = 1

 // param2 = 2

// args = [3, 4, 5, 6];

console.log(param1, param2, ...args); // Log: 1, 2, 3, 4, 5, 6

    }



setNumbers(1, 2, 3, 4, 5, 6);
  • Destructuring: The destructuring assignment javascript feature is the most used feature in React. It is an expression that allows you to assign the values or properties of an iterable object to variables. Generally, with this, you can convert your component props into variables (or constants):   
// Imagine we are on our <Person> component and we are

    // receiving the props (in this.props): name, age and email.

render() {

      // Our props are:

      // { name: 'Carlos Santana', age: 30, email:

'carlos@milkzoft.com' }

console.log(this.props);

const{ name, age, email } = this.props;



      // Now we can use the nodes as constants...

console.log(name, age, email);



return (

<ul>

<li>Name: {name}</li>

<li>Age: {age}</li>

<li>Email: {email}</li>

</ul>

      );

}



// Also the destructuring can be used on function parameters

const Person = ({ name, age, email }) => (

<ul>

<li>Name: {name}</li>

<li>Age: {age}</li>

<li>Email: {email}</li>

</ul>

    );
  • Arrow functions: In Javascript ES6 provides a new way to create functions using the => These functions are called arrow functions. This new method has a shorter syntax, and the arrow functions are anonymous functions. In React, arrow functions are used as a way to bind the this object in your methods instead of binding it in the constructor:
    class Person extends Component {

showProps = () => {

        console.log(this.props); // { name, age, email... }

      }

render() {

return (       
// Consoling props: 
{this.showProps()}
);       }     }
  • Template literals: The template literal is a new way to create a string using backticks (` `) instead of single quotes (‘ ‘)   or double quotes (” “). React uses template literals to concatenate class names or render a string using a ternary operator:
render() {

const { theme } = this.props;



return (
<div>Some content here...</div>
);     }
  • Map: The map()method returns a new array with the results of calling a provided function on each element in the calling array. Map use is widespread in React and mainly used to render multiple elements inside a React component.For example, it can be used to render a list of tasks:
render() {

const tasks = [

{ task: 'Task 1' },

{ task: 'Task 2' },

{ task: 'Task 3' }

      ];



return (

<ul>

          {tasks.map((item, key) =><likey={key}>{item.task}</li>}

</ul>

      );

    }
  • assign(): The Object.assign()method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object. This method is used mainly with Redux to create immutable objects and return a new state to the reducers:
export default functioncoinsReducer(state = initialState, action) {

switch (action.type) {

caseFETCH_COINS_SUCCESS: {

const { payload: coins } = action;



returnObject.assign({}, state, {

coins

          });

        }



default:

return state;

      }

    };
  • Classes: JavaScript classes, introduced in ES6, are mainly a new syntax for the existing prototype-based inheritance. Classes are functions and are not hoisted. React uses classes to create class Components:
import React, { Component } from 'react';



class Home extends Component {

render() {

return<h1>I'm Home Component</h1>;

      }

    }



export default Home;
  • Static methods: Static methods are not called on instances of the class. Instead, they’re called on the class itself. These are often utility functions, such as functions to create or clone objects. In React, they can be used to define the PropTypes in a component:
import React, { Component } from 'react';

import PropTypes from 'prop-types';

import logo from '../../images/logo.svg';



class Header extends Component {

staticpropTypes = {

title: PropTypes.string.isRequired,

url: PropTypes.string

      };



render() {

const {

title = 'Welcome to React',

url = 'http://localhost:3000'

        } = this.props;



return (

<header className="App-header">

<a href={url}>

<imgsrc={logo}className="App-logo"alt="logo"/>

</a>

<h1 className="App-title">{title}</h1>

</header>

        );

      }

    }



export default Header;
  • Promises:The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Use promises in React to handle requests using axios or fetch; also, you can use Promises to implement server-side rendering.
  • async/await: The async function declaration defines an asynchronous function, which returns an AsyncFunction This can also be used to perform a server request, for example, using axios:
Index.getInitialProps = async () => {

consturl = 'https://api.coinmarketcap.com/v1/ticker/';

const res = awaitaxios.get(url);



return {

coins: res.data

      };

    };

If you found this article interesting, you can explore React Cookbook, which covers UI development, animations, component architecture, routing, databases, testing, and debugging with React. React Cookbook will save you from a lot of trial and error and developmental headaches, and you’ll be on the road to becoming a React expert.