Advantages of React Stateless Functional Components
Before reading this post, if you have not gone through what are functional components in Reactjs then kindly go throughthis post
In this post we will see what are the advantages of functional posts in React js. If you check your react js code, you will quickly figure out that many components do not actually need state, they do get data from parent as props and will render the information. In such a case why to introduce state and make it complicated? rather I would prefer calling a function which returns me a component. Isn’t it so simple ? React 14 introduced Functional Components, also called as stateless components and removed unnecessary complications. So let us explore what are the advantages of stateless components
Advantages of React Functional/Stateless Components: Ref
1. More focused on presentation
React is forcing us to write components which are used only for presentational purpose, these components are useful for dumb presentational purpose only, that focus on UI rather than behaviour. Technically speaking its normal tendency to go for stateful components, doing that way we are making our code easily hackable where every damn component keeps its own local state. Functional components allowing us to have pure components which just focus on presentation. where as the state is maintained by few higher level components.
2. Gain in Performance
Stateless components will bring performance gain since there is no state and lifecycle of a component. React doesn’t need to have unnecessary check and memory allocations which eventually brings performance boost.
3. Clean and Optimised Code
Stateless components reduce lot of code, almost 20% – 30% reduction in code and hence the code will become clean and optimised.
4. Easy to debug
Functional components are pure components and helps your to analyse your code quickly and you no need to put log if assert calls everywhere to debug.
React Native List View : Animate Rows While Scrolling Using FlatList
In my previous post I have written about how to use React Native FlatList and we have seen the issues we face with pagination also how to add a loading indicator in the footer of FlatList. You can first read about it Link In this post we will see how to animate the rows while scrolling a FlatList.
Animating Rows In React Native FlatList :
To achieve animation for FlatList Rows, you have to install an npm module react-native-animatable, which provides variety of smooth animations for List Rows.
Installation of npm module:
$ npm install react-native-animatable --save
To make a continuous animation do this
<Animatable.Text animation="slideInDown" iterationCount={5} direction="alternate">Up and down you go</Animatable.Text>
<Animatable.Text animation="pulse" easing="ease-out" iterationCount="infinite" style={{ textAlign: 'center' }}>❤</Animatable.Text>
To animate rows in FlatList Rows do this
import * as Animatable from 'react-native-animatable';
class FlatListRow extends Component {
render(){
return(
<Animatable.View animation='fadeInUp'>;
<TouchableWithoutFeedback>;
// here your row component
</TouchableWithoutFeedback>;
</Animatable.View>;
);
}
}
Variety of animations are supported in this React Native Animationlibrary
Note you have to pass your current location to land user on his current location, else any other location which is default location. and a callback for handling change in location.
ReactJS google map location change callback will be called by react-google-maps library when there is change in location, like user searched some location
Era of Artificial Intelligence : Facebook new algorithm to identify people
Amost five years ago face recognition was a trend your mobile applications use to set ur face as password for your smartphones, Windows OS introduced face recognition to unlock the system, Facebook used face recognition for tagging people in the group photos.
But Face recognition is now very old, technology is changing so fast that today’s technology will become out dated tomorrow. Every day something new coming to market, people are becoming more innovative than ever. Recognition ? what else can one do other than face and voice recognition ?
Identity of a person based on his unique characteristics
Every person will be having his own uniqueness in his characteristics, the way he dress, his hair style, his body shape, his standing posture what else ?. Identifying a person based on his characteristics can be achieved by properly analysing the data.
Facebook can recognise you in photos for tagging, even if you’re not looking
Facebook is experimenting on a new algorithm which can recognise a person based on his unique characteristics even though his face is not visible. Yann LeCun, head of artificial intelligence at Facebook, is leading a team of researchers. The team is analysing more than 40000 thousands photos from flickr and experimenting in the lab.
However there are certain privacy concerns raised by experts, but Facebook will surely find a way to keep things secured.
Facebook Shows how artificial intelligence improve Facebook to show you perfect posts
Facebook has set up three AI labs so far, the company is investing enough time and effort on AI which helps Facebook to server the content that matches the people’s interest. Facebook revealed backend recognition tech in F8 conference. CTO Mike Schroepfer described new systems for identifying the content and context of videos and sentences.
Facebook working on secretly working onLanguage Technology Groupand experimenting on recorded voices and converting it into text. It has been planned by Facebook to release the feature in Facebook messenger where it converts voice to text.
Facebook’s Video AI prototype
Facebook has developed video AI prototype that identify 485 types of sports but recognises tiny differences among games. See the video given below
AI can read sentences and determine things like who possesses what, or where is an object.
Check this experiment 🙂 AI recognises content from the Lord Of The Rings and able to answer question about the story.
Why AI Matters for Facebook ?
The one and only aim to understand the content, show the relevant content to the user. This is really very much required for Facebook like company because if some one else enter into the market with a new idea then people might start looking towards it. The only thing every one must focus on is never allow your user to think about something else.
Facebook, Google and Apple are really doing a great job in this aspect, Nokia once was a leading mobile phone manufacturers, but one product like iPhone killed Nokia. If you are an entrepreneur then you must learn a lesson out of it.
Regular Expressions : How Exactly they work internally ?
Regular expressions were playing major role in computers from several decades, they are not as simple as we think. They are need extensive computational power, a decade before regular expressions were a big headache for computer programmers and scientists because they were consuming lot of time to complete the task.
History behind Regular Expressions :
A neuroscientist who tried to understand how the human brain could produce complex patterns using simple cells that are bound together. In 1943, Warren McCulloch and Walter Pitts published “A logical calculus of the ideas immanent in nervous activity”. this paper had a great influence on computer science during that time. In 1956, mathematician Stephen Kleene developed this model one step further. In the paper“Representation of events in nerve nets and finite automata”he presents a simple algebra. The terms Regular Sets and Regular Expressions were born from then. As mentioned above, Kleene’s algebra had only two operations and one function. In 1968, the Unix pioneer Ken Thompson published the article“Regular Expression Search Algorithm”in Communications.
A Pattern in regular expression :
How to learn regular expressions ? How to understand regular expressions?. They look confusing to understand regular expression but regular expressions are an elegant way to do some string manipulations.
We have studied finite automata and the regular expressions all just works on this theory, but Most modern programming languages (Perl, Python, Ruby, Java (and JVM based languages), C#) do not use this approach rather they use recursive backtracking approach. But finite automata is really good to understand regular expressions with its state diagrams and not a bad idea to implement in this approach may be recursive backtracking is better. So do you need a help to understand regular expression? here it is…
Let us take one example, Validating an email address
Human’s can achieve anything, human mind is the greatest gift of god. If you run in hurry or if you run on a moving floor your mind will get confused and some times you fell down. If you are not practiced then you can’t even cross two three hurdles continuously, you will fell down. Have you ever wondered a robot can do this ? it is so difficult to program even a simplest automation or even a simplest robot which can just move by itself. Now we have everything ready made so you may say it is not so difficult, but Cheetha which can run and jump over the hurdles ? really challenging.
A MIT’s Cheetah Robotic TEAM
Deborah Ajilo, Negin Abdolrahim Poorheravi,John Patrick Mayo,Justin Cheung, Sangbae Kim, Shinsuk Park, Kathryn L. Evans, and Matt Angle. Will Bosworth, Joao Luiz Almeida Souza Ramos, Sehyuk Yim, Albert Wang, Meng Yee Chuah, and Hae Won Park.
Algorithm Behind MIT’s Cheetha robot :
The bounding algorithm which made this possible will program each of the robot’s legs to exert a certain amount of force in the split second during which it hits the ground, in order to maintain a given speed: In general, the faster the desired speed, the more force must be applied to propel the robot forward.
the cheetaha robot adopts the force as per the surface and hence it successfully passed the test in grassy area and treadmill.Robot can run 16 km/h, jump about 40 centimetres high, land safely and continue running for at least 15 minutes .
Technical Details of MIT’s Bounding Algorithm and Robotic Cheetah
It took more than 5 years to achieve this and Cheetah 2 contains the custom electric motor designed by Jeffrey Lang, the Vitesse Professor of Electrical Engineering at MIT and the amplifier designed by David Otten, a principal research engineer in MIT’s Research Laboratory of Electronics.
“bounding algorithm” calculates the varying amounts of force required to propel an animal forward or to jump over obstacles. Algorithm models the running mechanics of world-class sprinters like Olympian Usain Bolt: the faster the desired speed, the greater the force the legs exert.
This robotic cheetah carries out its movements with the help of battery powered electric motors which do not make much noise even. Though the US-military has been trying for several years to make a stealthy and fast robot, it hadn’t been successful until now so this DARPA funded research by the MIT researchers may just open a whole new vision regarding the making of a stealthier bot.
Android: ItemClickListner with CheckBox or RadioButton.
Lets take a scenario to understand the need of a listview which will have checkbox embedded in it.
Consider the flipkart mobile app, in that we want to compare 2 or more products, in order to do that I will go on selecting the items which I want to compare and then click on the compare button.
So we have multiple items in that and hence we cant use the android built in types for creating the list view. Hence we need to follow the below mentioned approach.
Create an activity, which contains 2 listviews, one listview for displaying all available mobiles and another listview for displaying selected mobiles.
Create an adapter for filling the mobile list for the above mentioned listviews.
The layout which will be used for creating row which will make ItemClickListner work is as follows,
These make the checkbox non clickable and eventually the event will be transferred to its parent i.e the row and hence the ItemClickListner will be invoked.
Have you ever wondered what happens in your computer when we see even a simple animation?
Your computer algorithm calculates every pixel and performs CPU intensive operation over each pixel. Ok what such operations it does ?. It calculates every pixel and performs Discrete Fourier Transformation on each pixel of the image. If your image is 512X512 = 2,62,144 pixels and the algorithms operates several frames per second, like 50 frames per second which depends upon the type of hardware/algorithm being used. It operates every pixel several times per second ( like every pixel 60 times per second ) now image for an image with size 512X512 = 2,62,144pixels and each pixel operated 60 times per second this gives you unbelievably huge number.
Assume that you operated only 1 second,
2,62,144 * 60 = 1,57,28,640 times and these many times it is not just a simple operation, they may apply Fourier transformation on each pixel.
Another important factor to note that the Image rotation, Image scaling or any graphics related operations the the matrix calculations will come into picture. The rotation matrix and the image matrix will be multiplied to get the resulting image
rotation matrix
An image matrix will be a huge one, like 512 x 512 x 3 for a given 512X512 image. the 3 in matrix indicates image is RGB coloured. It is not required to explain how matrix multiplications are CPU extensive, Theoretically, matrix-matrix multiplication uses O(N^3) operations on O(N^2) data.
Comparison of GPU Matrix Multiplication operation over CPU
Why GPU and Why not CPU.
GPU are specifically made for performing graphics operations like moving pixels and applying transforms. Since CPU will be doing many more tasks like file operations, audio, calculations etc it is better to separate out your animated objects and give it to a different GPU layer. Imagine in the screen of 1024X800, somewhere some 200X100 size portion is animating, rather than giving 1024X800 space and find 200×100 space and then operate , it is nice trick to create separate layer of 200×100 space and perform animation independently in that layer.
So the load on your CPU will be reduced and the performance of the system will be improved. The difference between CSS3 and jquery animations are , CSS3 utilises GPU but jquery doesn’t, there another javascript based latest framework available called GSAP which is 20x faster than query.
Comparison of jquery, CSS and GSAP Animation Performance :
How To Make You Web Site Faster : HTML , Javascript Tricks
The performance of your web application is highly important factor to get more user visits, experts have given many advices to improve the performance of a web application and few are listed below.
1. Meta refresh – Meta refresh is a method of instructing a web browser to automatically refresh the current web page or frame after a given time interval, using an HTMLmeta element with the http-equiv parameter set to “refresh” and a content parameter giving the time interval in seconds.
Avoid Meta refresh as much as possible. This will slow down your site.
2. @imports will synchronously load the style sheet, Avoiding @import will improve the performance of your site. Instead of @imports use LINK tag as follows
Use <link rel=’stylesheet’ href=’knowledge-cess-style.css’>
Than <style> @import url(‘knowledge-cess-style.css’); </style>
3. Avoid use of multiple framework – Some people use JQuery for some functionality and DOJO for some functionality . Loading of framework will take time and your app becomes heavy. Stick to one framework.
4. Placing scripts at the end
Most people will load all their scripts at the beginning of the page. Load scripts at the end, some times it is not possible, it gives an error if a function being used in the page. In that case make two js files and keep necessary stuff in one js and load it at the beginning.
5.Use ‘differ’ attribute to if some scripts must be loaded at the beginning.
<scriptsrc=“knowledge-cess.js”defer></script>
6. To construct dynamic pages it is better to use .innerHTML rather than always creating DOM elements dynamically.
7. Referencing more DOM elements using document.querySelectorAll()
var matches = document.querySelectorAll("div.note, div.alert"); Reference
8. Use Javascript timers carefully. Don't let timers run unnecessarily. 9. Javascript animation and Math
Time to play with Math now, animation is nothing but playing with frames, higher the frame rate smoother the animation and more frames means more processing. The time interval we set for an animation should depend on screen refresh rate.
Understand how Javascript Animation related to Screen refresh rate
Most screens have refresh rate of 60Hz, so 60 frames per second (60fps) is best frame rate. Javascript timer will be set in milliseconds. so considering 1000ms and 60FPS which will give 1000ms/60fps = 16.7ms. so it is best timer value, so set 16.7ms or 17ms for your javascript timer while playing with animations.
function setInterval(function(){
animate();
},17);
10. Performance factor for PNG and JPG – PNG will be of more size compared to jpg but jpg uses more complicated decoding algorithm compared to png.
Image format PnG vs JPG and performance The reason png size will be more is because png format will use lossless compression algorithm and jpg will use lossy compression algorithm. 11. Using requestAnimationFrame : Mozilla team proposed requestAnimationFrame method to over come from performance issues in javascript animations. Have a look into this Link There Many more performance tuning techniques.Now let us look into some best practices of javascript
Best Practices in Javascript
1. Use Shortcut notations
var cities = ["Bangalore","Delhi","Mysore"]
than
var cities = new Array();
cities[0]='Bangalore';
cities[1]='Delhi';
cities[2]='Mysore';
2. Keep related stuff together
Best Practice –
var settings = function(){
var userDefaults = {
categories: {"defaultCategory" : "xyz", "lastCategory":"pqr"},
modules : {}
}
function initUserDefaults(){ }
function clearUserDefaults(){}
} //End of settings
The above way is clean and better approach rather than separating all methods.
3. Do not use primitive types as objects
var name = "Ram"; //Best practice
var name = new String("Ram"); //Not recommended
4. Use === operator
Always use === operator for comparison, It always converts (to matching types) before comparison.
The === operator forces comparison of values and type:
100 == "100" //true which causes problem most of the times
100 === "100" //false Best Practice, strict type checking
5. Global Variables in Javascript
Global variables are not recommended, Avoiding global variables is best practice.
6. Using JSLint
Identify most common problems in your javascript code using JSLint tool
Check : how Animation in javascript works and how CSS3 is better than jQuery – link
Assume that you have multiple clients, each client has access to similar kind of data, so database architecture should remain same for every client.
An example for the same is , assume that you have developed an ERP product for a company, many companies will be having same requirement so the database will remain same.
Most of the developers will be under confusion, whether to go for single instance of database or multiple instance of database. Following are the two approaches and their pros and cons.
Approach 1 : Single instance database
Keeping single instance of database but providing client id for each client to keep track of data of each client.
Advantages :
1) Better resource utilization – If your database is hosted on cloud services, like Amazon then as you create more number of instances they will allocate resources accordingly and charges will be applied for each instance. Example – check pricing for db instance in amazon http://aws.amazon.com/rds/pricing/ http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.DBInstanceClass.html
2) Scalability – Scalability is more easy since single instance is maintained.
Problems :
1) Security issues – since every client’s data is in the same instance, developers should be wise enough to take care of showing data to appropriate users. Highest risk factor with single instance is security
2) Data loss – if the instance fails due to some problems related to one client, it affects to every other client, so routinely back of database is must be taken care. No compromise with data loss.
3) Performance issue – For a huge set of data performance of database might be low ( this matters for very huge data, not even for medium scale database )
This is called as Multitenancy – a principle in software architecture where a single instance of the software runs on a server, serving multiple tenants.
Approach 2 : Multiple instances database
with this approach all the problems of first approach will be solved but the only problem with this approach is scalability.