rabbitMQForMicroServices

Backend Decouple Stratergy

  1. A message queue provide an asynchronous communications protocol - You have the option to send a message from one service to another without having to know if another service is able to handle it immediately or not. Messages can wait until the responsible service is ready. A service publishing a message does not need know anything about the inner workings of the services that will process that message. This way of handling messages decouple the producer from the consumer.

A message queue will keep the processes in your application separated and independent of each other; this way of handling messages could create a system that is easy to maintain and easy to scale.

Source
https://stackoverflow.com/questions/45208766/microservices-why-use-rabbitmq

https://www.cloudamqp.com/blog/2017-09-25-breaking-down-a-monolithic-system-into-microservices.html
Here is a story explaining how Parkster (a digital parking service) are breaking down their system into multiple microservices by using RabbitMQ.

a story about the usage of RabbitMQ in an event-based microservices architecture to support 100 million users a month.
https://www.cloudamqp.com/blog/2019-01-18-softonic-userstory-rabbitmq-eventbased-communication.html

And finally a link to Kontena, about why they chose RabbitMQ for their microservice architecture: “Because we needed a stable, manageable and highly-available solution for messaging.”.
https://ghost.kontena.io/event-driven-microservices-with-rabbitmq-and-ruby/

practices to boost react performance

Practices to Boost React Performance

1. React under the hood?

React DOM wasn’t created with dynamic UI in mind. When the DOM needs to be updated, it has to go through a Reflow/Layout stage and the DOM nodes need to be repainted, which is slow. When you have an application with thousands of

s, there is a severe performance issue.

React uses a different strategy to update your DOM. The process is popularly known as Reconciliation. When your browser initially renders your application, React builds a tree of elements. Let’s imagine that this how React builds its tree.

But what when a component’s state changes, the render() method returns a different tree of React elements. React has to calculate the changes it has to make to the DOM, and it does so by creating a virtual DOM and then comparing that to the real DOM.

The good thing about virtual DOM is that it updates only the part of the DOM that needs to be updated. React uses a diffing algorithm that tries to minimize the number of operations to transform the tree. However, the diffing algorithm isn’t perfect. Let’s say that values of the nodes in yellow has changed, and needs to be updated.

However, the diffing algorithm isn’t perfect. If the updated props were passed in from the com React ends up updating entire subtree like this.

As you can see, React is unnecessarily rendering and diffing component subtrees. Instead, there are ways that you can re-render only the nodes that are directly affected by the props change and not the entire subtree.

When React wastes resources and CPU on rendering components that haven’t changed, we call it wasted renders. Wasted renders can throttle performance — but if we could streamline the diffing process further, we might be able to boost the speed significantly. The rest of the post will cover how to boost React performance.

Benchmark your Application to Improve Performance — Tools and Techniques

React used to have a tool called react-addon-perf that was recently retired and it isn’t available in the latest version of React. Instead, React recommends using the browTo create a performance profile for your application, follow the steps below:

Make sure that you’ve exported the JS with source-maps or that you’re in development mode.
Temporarily disable all React extensions, like React DevTools, because they can impact the results.
Set up the profiling tool. Open the Chrome developer tools and go to the performance tab. You can slow down the JavaScript execution so that the performance issues become more apparent.
Now, navigate to the page that you would like to profile and then press the red button that says “Record.” If you would like to create a performance trace of the initial render, you should choose the start profiling and reload button. Now, perform the desired action and stop the recording.
Chrome will return visualization of the performance data in vertical bands. Zoom in onto the User Timing band to see each component’s performance.
You can select individual components and the bottom up tab will give you insights into activities that take up most of the time.ser’s profiling tools to get the same result.

To create a performance profile for your application, follow the steps below:

Make sure that you’ve exported the JS with source-maps or that you’re in development mode.
Temporarily disable all React extensions, like React DevTools, because they can impact the results.
Set up the profiling tool. Open the Chrome developer tools and go to the performance tab. You can slow down the JavaScript execution so that the performance issues become more apparent.
Now, navigate to the page that you would like to profile and then press the red button that says “Record.” If you would like to create a performance trace of the initial render, you should choose the start profiling and reload button. Now, perform the desired action and stop the recording.
Chrome will return visualization of the performance data in vertical bands. Zoom in onto the User Timing band to see each component’s performance.
You can select individual components and the bottom up tab will give you insights into activities that take up most of the time.

a library, known as why-did-you-update, that is an excellent tool for component analysis. It gives you a visualization of the props before and after and notifies you about components that shouldn’t have been rerendered.To install the tool, run

1
npm install --save why-did-you-update

Add this code into your index.js file.

1
2
3
4
5
6
import React from 'react';

if (process.env.NODE_ENV !== 'production') {
const {whyDidYouUpdate} = require('why-did-you-update');
whyDidYouUpdate(React);
}

2. Prevent Unnecessary Rendering

React re-renders a component when its props or state gets updated:default behaviors.

A. shouldComponentUpdate(). This lifecycle hook doesn’t get invoked during the initial render, but only on subsequent re-renders. shouldComponentUpdate() is triggered when the props have changed and it returns true by default.

If you’re sure that your component doesn’t need to re-render regardless of whether the props have updated or not, you can return false to skip the rendering process.

1
2
3
4
5
6
7
8
9
class ListItem extends Component {
shouldComponentUpdate(nextProps, nextState) {
return false
}

render() {
// Let the new props flow, I am not rendering again.
}
}

Alternatively, if you need to update only when certain props are updated, you can do something like this:

1
2
3
4
5
6
class ListItem extends Component {
shouldComponentUpdate(nextProps, nextState) {
return nextProps.isFavourite != this.props.isFavourite;
}
...
}

Pure Component

A React.PureComponent is pretty much like a normal Component but the key difference being, it handles the shouldComponentUpdate() method for you. When the props or the state update, PureComponent will do a shallow comparison on them and update the state.

So, what is shallow comparison? Here’s excerpt from an answer on StackOverflow:

1
Shallow compare does check for equality. When comparing scalar values (numbers, strings) it compares their values. When comparing objects, it does not compare their's attributes - only their references are compared (e.g. "do they point to same object?).

reference: immutable.js is coming!!! //topics involved here.

Personally, you should use PureComponent only if you have a clear understanding of how immutable data works and when to use forceUpdate() to update your component.

3. Debouncing input handlers

This concept is not specific to React, or any other front-end library. Debouncing has long been used in JavaScript to successfully run expensive tasks without hindering performance.

A debounce function can be used to delay certain events so that it doesn’t get fired up every millisecond. This helps you limit the number of API calls, DOM updates, and time consuming tasks. For instance, when you’re typing something into the search menu, there is a short delay before all of the suggestions pop up. The debounce function limits the calls to onChange event handler. In many cases, the API request is usually made after the user has stopped typing.

Let me focus more on the debouncing strategy for input handlers and DOM updates. Input handlers are a potential cause of performance issues. Let me explain how:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
export default class SearchBar extends React.Component {
constructor(props) {
super(props);
this.onChange = this.onChange.bind(this);
}
onChange(e) {
this.props.onChange(e.target.value);
}
render () {
return (
<label> Search </label>
<input onChange={this.onChange}/>
);
}
}

On every input change, we’re calling this.props.onChange(). What if there is a long-running sequence of actions inside that callback? That’s where debounce comes it handy. You can do something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import {debounce} from 'throttle-debounce';

export default class SearchBarWithDebounce extends React.Component {
constructor(props) {
super(props);
this.onChange = this.onChange.bind(this);
this.onChangeDebounce = debounce( 300,
value => this.props.onChange(value)
);
}
onChange(e) {
this.onChangeDebounce(e.target.value);
}
render () {
return (
<input onChange={this.onChange}/>
);
}
}

The DOM update happens after the user has finished typing, which is exactly what we need. If you’re curious about debouncing AJAX calls, you can do something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import {debounce} from 'throttle-debounce';

export default class Comp extends Component {
constructor(props) {
super(props);
this.callAPI = debounce(500, this.callAPI);
}
onChange(e) {
this.callAPI(e.target.value);
}
callAjax(value) {
console.log('value :: ', value);
// AJAX call here
}
render() {
return (
<div>
<input type="text" onKeyUp={this.onChange.bind(this)}/>
</div>
);
}
}

Optimize React for Production

A minified production build is faster and more optimized for heavy workloads, whereas a development build is meant to highlight errors and warnings in the console. Although these warnings help the developer debug errors, they can directly impact the performance of the application.

You can use the Network tab in your Developer Tools to see what is actually slowing you down. React bundle size is usually the culprit, and you need to minify it before you push it for production. If you bootstrapped the application using create-react-app, you can get a production build by running npm run build.

When you run this, create-react-app will minify the code, obfuscate/uglify it (that happens as a result of minification) and generate source maps. The end user is able to load the scripts faster than the version that was not minified. The source maps generated are particularly handy if you decide to navigate around the code through the Developer console. The source maps are loaded on demand and you can delete it before actual deployment.

If you’re using webpack, you can build a production environment by running webpack -p. React also offers production-ready single files for React and ReactDOM.

1
2
3
4
5
<script 
src="https://unpkg.com/react@16/umd/react.production.min.js">
</script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js">
</script>

There are ways to reduce the bundle size even further, like using Preact, but you need to take that path only if the initial load time is noticeably slow.

Optimizing your application’s resource is another thing that you need to consider. This has nothing to do with React, but can indeed speed up your application. Resources such as images, icons and other media files can slow down the application if they are rendered uncompressed. The Network tab in the Developer Tools should give you insights into that too. If you’re using static resources, optimize and compress them before pushing them into the server. Use a CDN if your server and the potential users are not in close proximity. Here is a nice article written by David Lazic that covers optimizing the production build further. https://medium.com/netscape/webpack-3-react-production-build-tips-d20507dba99a

Micro-optimizations To Boost React Performance

Micro-optimizations are certain details that won’t have an immediate impact on your application, but will help you in the long run. There are many-micro optimizations around that you should know about. Some of these practices also help you improve the readability and maintainability of your codebase.

Functional components vs. Class components

Functional components are easier to write and read, and they are particularly useful for building the UI or the presentational layer. Class components, on the other hand, are ideal for building containers. The containers make API calls, dispatch actions to the store, and use the state to hold data. They then pass the data as props to the presentational components.

Until React v16 was released, both the functional components and the class components had the same code path. Although the functional components appeared to have fewer lines of code, they were neither optimized nor offered speed improvements because they were converted to Class components under the hood. However, the scenario has changed with the release of V6.

Here is an excerpt from the official docs:

1
Functional components in React 16 don't go through the same code path as class components, unlike in previous versions, where they were converted to classes and would have the same code path. Class components have additional checks required and overhead in creating the instances that simple functions don't have.

Bind Function Early

1
2
3
4
5
6
7
8
9
10
11
class Button extends React.Component {
handleClick() {
console.log('Yay!');
}

render() {
return (
<button onClick={this.handleClick.bind(this)}/>
);
}
}

Arrow functions inside the render method is bad too, unfortunately.

1
2
3
4
5
6
7
8
9
10
11
class Button extends React.Component {
handleClick() {
console.log('Yay');
}

render() {
return (
<button onClick={() => this.handleClick()}/>
);
}
}

The process of creating a new function is usually fast and won’t slow you down, to be honest. But if you’ve implemented shouldComponentUpdate() or if you’re using PureComponent base class, React sees new props on each render and the child components are re-rendered unnecessarily.

To fix this issue, you can bind functions early like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Button extends React.Component {
constructor(props) {
super(props);

this.handleClick = this.handleClick.bind(this);
}

handleClick() {
console.log('Yay!');
}

render() {
return (
<button onClick={this.handleClick}/>
);
}
}

Alternatively you can use something like class instance fields. However, it’s an experimental feature that has not yet made it to the standards. But you can use it in your project with the help of Babel.

Final Words

In this post, I’ve covered some of the popular and clever ways to boost React’s performance. On a general note, you don’t have to be concerned until you start seeing actual bottlenecks. I prefer to go with the “Don’t optimize unless you need to” approach. That’s why I’d recommend benchmarking components first and measuring whether they are actually slowing you down. Your browser’s developer tools will also give insights into other non-React factors that could be affecting your app. Use that as a starting point and that should help you get started.

leetcode465

Optimal Account Balancing, hard
Settling Multiple Debts Efficiently: An Invitation to Computing Science by T. Verhoeff, June 2003. http://www.mathmeth.com/tom/files/settling-debts.pdf
The question can be transferred to a 3-partition problem, which is NP-Complete.

recursion + backtracking, get the total transaction and then dfs and backtracing every trans.
Core code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int backtrack(Long[] debts, int pos, int count){
while(pos < debts.length && debts[pos] == 0) pos++;
if (pos >= debts.length) {
return count;
}
int res = Integer.MAX_VALUE;
for(int i = pos + 1; i < debts.length; i++){
if(debts[pos] * debts[i] < 0){
debts[i] += debts[pos];
res = Math.min(res, helper(debts, pos + 1, count + 1));
debts[i] = debts[i] - debts[pos];
}
}
return res;
}

edit distance modified version-bus station problem q

Edit Distance problem(leetcode)

problem: one dimension bus station, given a list of passangers: list = [0, 1,2, 4, 6, 7], they are all the passagers in One Dismension. And given a M as well, which means that the max time that the bus can stop, return in what stops for the car that makes the passager can pick up the bus in shortest distance.

logic: dp similar to min distance to multiple gas station.
we need to build stops to make the minimum distance.
解法: 求dp[i,j]表示前i个人(inclusive)和 j表示目前的公交站个数。
dp[i,j] = min(dp[k,j-1], min distance for people after k with one stop)

base: only one stop
optimal: median position

leetcode137Contest

  1. Last Stone Weight3
  2. Remove All Adjacent Duplicates In String4
  3. Longest String Chain6
  4. Last Stone Weight II

1. Last Stone Weight3

a collection of rocks with each one has positive weight. Each turn, we choose two heaviest rocks and smash them together.
logic:
sort them in increase order, and push back the last two elements, and smash and push the remain back to the vector.

solution:

1
2
3
4
5
6
7
8
9
10
11
12
public: 
int lastStoneWeight(vector<int>& a){
while(a.size()>1){
sort(a.begin(), a.end());
int n = a.size();
int x = a[n-1] - a[n-2];
a.pop_back();
a.pop_back();
a.push_back(x);
}
return a[0];
}

2. Remove All Adjacent Duplicates In String4

Given a String S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them.
Repeatly doing the removement until we no longer can. return the final string.

example: inputs: “abbaca”
outputs: “ca”
Solution Logic: using stack, check the top of the stack, if equal to current element, then pop it out.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public:
string removeDuplicates(string S){
vector<char> a;
for(auto& c: S){
if(a.size() && a.back()==c){
a.pop_back();
}else{
a.push_back(c);
}
}
string ret;
for(auto& it: a) ret += it;
return ret;
}

3. Longest String Chain6

Given a list of words, each word consists of English lowercase letters.
Let’s say word1 is a predecessor of word2 if and only if we can add exactly one letter anywhere in word1 to make it equal to word2. For example, “abc” is a predecessor of “abac”.
Return the longest possible length of a word chain with words chosen from the given list of words.
Example 1:

1
2
3
Input: ["a","b","ba","bca","bda","bdca"]
Output: 4
Explanation: one of the longest word chain is "a","ba","bda","bdca".

Solution:
Per inolving in state transfer: Dynamic programming is needed.
sort the word based on the length; then loop through all the possible string by missing one letter. if one string got seen before, we update the longest chain for current string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class solution{
//static attached to class
static bool compare(const string &s1, const string &s2){
return s1.length() < s2.length();
}
public:
int longestStrChain(vector<string>& words){
sort(words.begin(), words.end(), compare);
unordered_map<string,int> dp;
for(string w: words){
int max_idx = 0;
for(int i = 0; i < w.length(); i++){
string word = w.substr(0, i) + w.substr(i+1);
max_idx = max(max_idx, dp[word]+1);
}
dp[w] = max_index;
}
int result = 0;
for(auto m: dp){
result = max(result, m.second);
}
return result;
}
}

4. Last Stone Weight II

Follow up of the first one: not the biggest two stones anymore, but the smash strategy become:

1
2
3
4
5
Each turn, we choose any two rocks and smash them together.  
Suppose the stones have weights x and y with x <= y. The result of this smash is:

If x == y, both stones are totally destroyed;
If x != y, the stone of weight x is totally destroyed, and the stone of weight y has new weight y-x.

So, there are a lot of choices! ===> Knapsacks problem!

###Tips: Think in the way of real scenarios, and how you get it done first.
Then connect the logic with data structure and algorithm.

leetcode804

Logic:
Get the average of the array, then backtrack the subarray with the same average.
trick: be careful with sum * number % length; not only sum % length:
eg: 10 / 4 => 5/2, even sum % length !=0 , it still works!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class solution{
public boolean splitArraySameAverage(int[] A){
int len = A.length;
if(len==1) return false;
int s = 0;
for(int i: A){
s += i;
}
Arrays.sort(A);
for(int i = 1; i <= len/2; i++){
if((s * i % len == 0) & (backtracking(A, s * i /len, i, 0)) return true;
return false;
}
}
public boolean backtrack(int[] A, int target, int k, int start){
if(k==0) return target==0;
if(A[start] > target/k) return false;
for(int i = start; i < A.length - k + 1; i++){
if(i > start && A[i]==A[i-1]) continue;
if(backtrack(A, target - A[i], k -1, i + 1)) return true;
}
return false;
}
}

singleton_code_demo

SingleTon basic logic

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class SingleTonClass {
private static SingleTonClass obj = null;
private SingleTonClass(){
/*Private Constructor will prevent
* the instantiation of this class directly*/
}

public static SingleTonClass objectCreationMethod(){
/*This logic will ensure that no more than
* one object can be created at a time */
if(obj==null){
obj= new SingleTonClass();
}
return obj;
}
public void display(){
System.out.println("Singleton class Example");
}
public static void main(String args[]){
//Object cannot be created directly due to private constructor
//This way it is forced to create object via our method where
//we have logic for only one object creation
SingleTonClass myobject= SingleTonClass.objectCreationMethod();
myobject.display();
}
}

sass/scss

为什么使用SASS/SCSS?

易维护,更方便的定制
对于一个大型或者稍微有规模的UI来说,如果需要替换下整体风格,或者是某个字体的像素值,比如我们经常会遇到panel,window以及portal共用一个背景色,这个时候按照常规的方式,我们需要一个个定位到元素使用的class,然后逐个替换,SASS提供了变量的方式,你可以把某个样式作为一个变量,然后各个class引用这个变量即可,修改时,我们只需修改对应的变量。
对于编程人员的友好
对于一个没有前端基础的编程人员,写css样式是一件非常痛苦的事情,他们会感觉到各种约束,为什么我不能定一个变量来避免那些类似“变量”的重复书写?为什么我不能继承上个class的样式定义?。。。SASS/SCSS正是帮编程人员解开了这些疑惑,让css看起来更像是一门编程语言。
效率的提升
对于一个前端开发人员来说,我不熟悉编程,也不关注css是否具有的一些编程语言特性,但这不是你放弃他的理由,css3的发展,加之主流浏览器的兼容性不一,很多浏览器都有自己的兼容hack,很多时候我们需要针对不同的浏览器写一堆的hack,这种浪费时间的重复劳动就交给SASS处理去吧!

react component communication

https://blog.csdn.net/lizhipeng123321/article/details/80018003

总结
本文总结了 React 中组件的几种通信方式,分别是:

父组件向子组件通信:使用 props
子组件向父组件通信:使用 props 回调
跨级组件间通信:使用 context 对象
非嵌套组件间通信:使用事件订阅
事实上,在组件间进行通信时,这些通信方式都可以使用,区别只在于使用相应的通信方式的复杂程度和个人喜好,选择最合适的那一个。

比如,通过事件订阅模式通信不止可以应用在非嵌套组件间,还可以用于跨级组件间,非嵌套组件间通信也可以使用 context 等。关键是选择最合适的方式。

当然,自己实现组件间的通信还是太难以管理了,因此出现了很多状态管理工具,如 flux、redux 等,使用这些工具使得组件间的通信更容易追踪和管理。

react context api

react contect api state manage

When Should I Use Context?

I would recommend reaching for Context when you find yourself passing props down through three or more levels in your component tree. You might notice that you have renamed your props, making it challenging to determine the data’s origin. You might consider implementing context if a bunch of your components know about irrelevant data.

Rule of thumb: if you start to feel irritated by how long it takes to determine where data is coming from, introduce Context.

Do not hesitate to still use the other tools you have available, like prop drilling and redux. While Context can make it easier to pass props around in certain scenarios, it doesn’t give you access to some of the benefits redux offers, and it’s a more complicated abstraction than prop drilling.