Babel Cli to translate html loop in jsx to React.createElement

step 1: create a project using following command line

npm init
npm install --save-dev babel-cli
npm install babel-plugin-transform-react-jsx

save following code into build.sh

./node_modules/.bin/babel --plugins transform-react-jsx index.jsx

step 2: create .babelrc

{
    "presets": ["es2015", "react"]
}

step 3: create index.jsx

import React from 'react';

const items = [
  { id: 1, name: 'Item 1' },
  { id: 2, name: 'Item 2' },
  { id: 3, name: 'Item 3' },
];

function MyComponent() {
  return (
    <div>
      <h1>Items List</h1>
      <ul>
        {items.map(item => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default MyComponent;

final step: run build.sh

'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var items = [{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }, { id: 3, name: 'Item 3' }];

function MyComponent() {
  return _react2.default.createElement(
    'div',
    null,
    _react2.default.createElement(
      'h1',
      null,
      'Items List'
    ),
    _react2.default.createElement(
      'ul',
      null,
      items.map(function (item) {
        return _react2.default.createElement(
          'li',
          { key: item.id },
          item.name
        );
      })
    )
  );
}

exports.default = MyComponent;

Summary

you could see that items.map(item => ()) has been translated into _react2.default.createElement(…items.map(function (item) {}… ).

Emacs – Use Etags to investigate Linux Kernel source code

Build TAGS file

Navigate Linux kernel source code folder to generate TAGS file.

find . -name “*.[chCH]” -print | etags –

Set Default TAGS file

Tags-table-list contains list of directories that contain TAGS file, All of Dir should contain TAGS file. Otherwise, search will stop at directory without TAGS file and print error message.

(setq tags-table-list '("~/.emacs.d" "/path/to/linux/kernel/src"))

Find Tag and Jump back

M-x find-tag         — jump to define

M-x xref-pop-mark-stack    — pop mark stack to jump back.

Linux Kernel may have different definition for one variable because of multiple Hardware architecture, we could jump all definition for one variable to find out right hardware architecture to view.

Java Stream – ParallelStream

Multiple All BigInteger in Array using Parallel Stream and reduce

package com.dw.thread;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

public class ParallelStreamTest {
    public static void main(String[] args) {
        List<BigInteger> integers = new ArrayList<>();
// fill data
        integers.add(new BigInteger("134123124325234234"));
        integers.add(new BigInteger("1341231243252"));
        integers.add(new BigInteger("134123124325234234"));
        integers.add(new BigInteger("134123124325234234"));
        integers.add(new BigInteger("134123124"));
        integers.add(new BigInteger("134123124"));
        integers.add(new BigInteger("134123124"));
        integers.add(new BigInteger("134123124"));
        integers.add(new BigInteger("134123124"));

        BigInteger result = integers.parallelStream()
                .reduce(BigInteger.ONE, (a, e) -> a.multiply(e));
        System.out.println(result);

    }
}

Java Thread – Calculate result = ( base1 ^ power1 ) + (base2 ^ power2)

Idea is to use two java threads, one thread calculates base1 ^ power1 using BigInteger and another thread calculates base2 ^ power2. Use thread.join() to wait for both thread to complete and sum result from both thread.

package com.dw.thread;

import java.math.BigInteger;

public class ComplexCalculation {

    public BigInteger calculateResult(BigInteger base1, BigInteger power1, BigInteger base2, BigInteger power2) throws InterruptedException {
        BigInteger result;
        /*
            Calculate result = ( base1 ^ power1 ) + (base2 ^ power2).
            Where each calculation in (..) is calculated on a different thread
        */

        PowerCalculatingThread thread1 = new PowerCalculatingThread(base1, power1);
        PowerCalculatingThread thread2 = new PowerCalculatingThread(base2, power2);

        thread1.start();
        thread2.start();

        thread1.join();   // important: wait thread to complete
        thread2.join();  
        result = thread1.getResult().add(thread2.getResult()); // add two result

        return result;
    }

    private static class PowerCalculatingThread extends Thread {
        private BigInteger result = BigInteger.ONE;
        private BigInteger base;
        private BigInteger power;

        public PowerCalculatingThread(BigInteger base, BigInteger power) {
            this.base = base;
            this.power = power;
        }

        @Override
        public void run() {
           /*
           Implement the calculation of result = base ^ power
           */
            for (BigInteger i = BigInteger.ZERO; i.compareTo(power) != 0; i = i.add(BigInteger.ONE)) {
                result = result.multiply(base);
            }
        }

        public BigInteger getResult() { return result; }
    }
    public static void main(String[] args) throws InterruptedException {
        ComplexCalculation c = new ComplexCalculation();
        BigInteger result = c.calculateResult(new BigInteger("123"), new BigInteger("10"), new BigInteger("456"), new BigInteger("20"));

        System.out.println(result);
    }
}

Java Stream – Map and FlatMap

Here is an example from book, it converts list of string into list of chars without duplicated. it is good example to show what different between map and flatmap. basically map will keep original structure of input element while flatmap won’t keep structure of input element.

Mockito – ByteBuddy Examples

ByteBuddy is key framework used in Mockito, it will auto generated subclass and override default methods. Following code will print out “Hello ByteBuddy!”.

import net.bytebuddy.ByteBuddy;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.matcher.ElementMatchers;

public class ByteBuddyEntry {
    public static void main(String[] args)
    {
        DynamicType.Unloaded unloadedType = new ByteBuddy()
                .subclass(Object.class)
                .method(ElementMatchers.isToString())
                .intercept(FixedValue.value("Hello ByteBuddy!"))
                .make();

        Class<?> dynamicType = unloadedType.load(ByteBuddyEntry.class
                        .getClassLoader())
                .getLoaded();

        try {
            System.out.println(dynamicType.newInstance().toString());
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

MySQL Core Src – Lex/Parse SQL Statement

SQL lex files:

sql/sql_lex.h、sql/lex_token.h、sql/lex.h、sql/lex_symbol.h

sql/gen_lex_token.cc、sql/sql_lex.cc

SQL grammar parser file:

sql/sql_yacc.yy、sql/sql_yacc.cc、sql/sql_yacc.h

SQL hint grammar parser file:

sql/sql_hints.yy、sql/sql_hints.yy.cc

mysql use bison (lex/yacc) to token sql statement and parse it, take sql_yacc.yy for example, it is main file contains all parse sql rules.

Docker – Setup git ssh server using docker

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
27
FROM ubuntu:18.04
 
ENV TZ=Australia/Sydney
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
 
RUN apt-get update
RUN apt-get install -y bash git python3 g++ curl vim openssh-server sudo
 
 
RUN addgroup --gid 9999 git && adduser --uid 9999 --gid 9999 --shell /usr/bin/git-shell git
RUN addgroup --gid 9000 xxx && adduser --uid 9000 --gid 9000 --shell /bin/bash xxx
 
RUN echo git:password | chpasswd
RUN echo xxx:password | chpasswd
 
RUN mkdir -p /home/git
RUN mkdir -p /home/xxx
 
RUN chown -Rh git:git /home/git
 
COPY sshd_config /etc/ssh/sshd_config
 
EXPOSE 22
 
ENTRYPOINT service ssh restart && bash
 
CMD ["/bin/bash"]

1863. Sum of All Subset XOR Totals

key idea is how to generate all subset of array.

take 3 elements of arrays for example,

[a, _, _] -> [1, 0, 0]
[_, b, _] -> [0, 1, 0]
[a, b, _] -> [1, 1, 0]
[_, _, c] -> [0, 0, 1]
[a, _, c] -> [1, 0, 1]
[_, b, c] -> [0, 1, 1]
[a, b, c] -> [1, 1, 1]

integer i is loop through 1 to Math.pow(2, nums.length) – 1, for each integer, we check how many 1 bit

i & 1, if it is 1, we get nums[index] out as elements for subarray.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 
class Solution {
    public int subsetXORSum(int[] nums) {
        int result = 0;
    	int x = (int)Math.pow(2, nums.length) - 1;
        for(int i=1;i<=x;i++) {
        	int p = i;
        	int r = 0;
        	for(int j=0;j<nums.length;j++) {
        		int t = p & 1;
        		p >>= 1;
 
        		if (t == 1) {
    				r ^= nums[j];
        		}
        	}
 
        	result += r;
        }
 
        return result;
    }
}