Java – Static Initialization Block

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.dw.lib.test;
 
public class StaticInitializationBlock {
 
	static  
    {  
        System.out.println("STATIC BLOCK");  
    } 
 
	public StaticInitializationBlock() {
		System.out.println("constructor");
	}
 
	public static void main(String[] args) {
 
		StaticInitializationBlock block = new StaticInitializationBlock();
 
		System.out.println("MAIN METHOD");
 
	}
 
}

output:
STATIC BLOCK
constructor
MAIN METHOD

log4j src – parse log4j.xml building DocumentBuilder

log4j uses DocumentBuilder to parse log4j.xml

here is example code which is same as log4j original source code.

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
 
package main;
 
import java.io.*;
import java.net.*;
 
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
 
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
 
public class DocumentBuilderEntry {
 
	public static void loop(Node node) {
	    // do something with the current node instead of System.out
	    System.out.println(node.getNodeName());
 
	    NodeList nodeList = node.getChildNodes();
	    for (int i = 0; i < nodeList.getLength(); i++) {
	        Node currentNode = nodeList.item(i);
	        if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
	            //calls this method for all the children which is Element
	        	loop(currentNode);
	        }
	    }
	}
 
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		URL url = DocumentBuilderEntry.class.getResource("log4j.xml");
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
		try {
			DocumentBuilder parser = factory.newDocumentBuilder();
			URLConnection uConn = url.openConnection();
 
			uConn.setUseCaches(false);
			InputStream stream = uConn.getInputStream();
			try {
			  InputSource src = new InputSource(stream);
			  src.setSystemId(url.toString());
			  Document doc = parser.parse(src);
			  loop(doc.getDocumentElement());
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
			  stream.close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
 
 
 
	}
 
}

influxdb – influxdb query for if/else case

influxdb didn’t support if/else in select statement.

mysql could support if/else/case statement, for example.

1
2
3
4
5
6
7
   SELECT
      CASE <field>
         WHEN 1 THEN 100
      ELSE
         0
   FROM TABLE
   WHERE [condition]

However, influxdb didn’t support if/else in select statement.
we have to use a function map for if/else

for example,

input set is (1, 2, 3, 4, 5, 6, 7)
output set is (100, 0, 0, 0, 0, 0, 0)

we design a function f(x) = 100*FLOOR(1/x)

so f(1) = 100, f(2) = 0, … , f(7) = 0;

it could match whole input set and output set

1
SELECT 100*FLOOR(1/FIELD) FROM 'measurement' WHERE <condition>

wordpress – wpdb init and generate all database schema

$wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST );

// very important, it will init all wpdb public/private attributes
// such as $wpdb->termmeta, without call this function , $wpdb->termmeta will be empty string.

wp_set_wpdb_vars();

// get all include user tables and blog tables
echo wp_get_db_schema(‘all’);

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
CREATE TABLE wp_users (
  ID BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  user_login VARCHAR(60) NOT NULL DEFAULT '',
  user_pass VARCHAR(255) NOT NULL DEFAULT '',
  user_nicename VARCHAR(50) NOT NULL DEFAULT '',
  user_email VARCHAR(100) NOT NULL DEFAULT '',
  user_url VARCHAR(100) NOT NULL DEFAULT '',
  user_registered datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  user_activation_key VARCHAR(255) NOT NULL DEFAULT '',
  user_status INT(11) NOT NULL DEFAULT '0',
  display_name VARCHAR(250) NOT NULL DEFAULT '',
  PRIMARY KEY  (ID),
  KEY user_login_key (user_login),
  KEY user_nicename (user_nicename),
  KEY user_email (user_email)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_520_ci;
CREATE TABLE wp_usermeta (
  umeta_id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  user_id BIGINT(20) UNSIGNED NOT NULL DEFAULT '0',
  meta_key VARCHAR(255) DEFAULT NULL,
  meta_value longtext,
  PRIMARY KEY  (umeta_id),
  KEY user_id (user_id),
  KEY meta_key (meta_key(191))
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_520_ci;
CREATE TABLE wp_termmeta (
  meta_id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  term_id BIGINT(20) UNSIGNED NOT NULL DEFAULT '0',
  meta_key VARCHAR(255) DEFAULT NULL,
  meta_value longtext,
  PRIMARY KEY  (meta_id),
  KEY term_id (term_id),
  KEY meta_key (meta_key(191))
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_520_ci;
CREATE TABLE wp_terms (
 term_id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
 name VARCHAR(200) NOT NULL DEFAULT '',
 slug VARCHAR(200) NOT NULL DEFAULT '',
 term_group BIGINT(10) NOT NULL DEFAULT 0,
 PRIMARY KEY  (term_id),
 KEY slug (slug(191)),
 KEY name (name(191))
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_520_ci;
CREATE TABLE wp_term_taxonomy (
 term_taxonomy_id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
 term_id BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
 taxonomy VARCHAR(32) NOT NULL DEFAULT '',
 description longtext NOT NULL,
 parent BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
 COUNT BIGINT(20) NOT NULL DEFAULT 0,
 PRIMARY KEY  (term_taxonomy_id),
 UNIQUE KEY term_id_taxonomy (term_id,taxonomy),
 KEY taxonomy (taxonomy)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_520_ci;
CREATE TABLE wp_term_relationships (
 object_id BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
 term_taxonomy_id BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
 term_order INT(11) NOT NULL DEFAULT 0,
 PRIMARY KEY  (object_id,term_taxonomy_id),
 KEY term_taxonomy_id (term_taxonomy_id)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_520_ci;
CREATE TABLE wp_commentmeta (
  meta_id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  comment_id BIGINT(20) UNSIGNED NOT NULL DEFAULT '0',
  meta_key VARCHAR(255) DEFAULT NULL,
  meta_value longtext,
  PRIMARY KEY  (meta_id),
  KEY comment_id (comment_id),
  KEY meta_key (meta_key(191))
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_520_ci;
CREATE TABLE wp_comments (
  comment_ID BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  comment_post_ID BIGINT(20) UNSIGNED NOT NULL DEFAULT '0',
  comment_author tinytext NOT NULL,
  comment_author_email VARCHAR(100) NOT NULL DEFAULT '',
  comment_author_url VARCHAR(200) NOT NULL DEFAULT '',
  comment_author_IP VARCHAR(100) NOT NULL DEFAULT '',
  comment_date datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  comment_date_gmt datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  comment_content text NOT NULL,
  comment_karma INT(11) NOT NULL DEFAULT '0',
  comment_approved VARCHAR(20) NOT NULL DEFAULT '1',
  comment_agent VARCHAR(255) NOT NULL DEFAULT '',
  comment_type VARCHAR(20) NOT NULL DEFAULT '',
  comment_parent BIGINT(20) UNSIGNED NOT NULL DEFAULT '0',
  user_id BIGINT(20) UNSIGNED NOT NULL DEFAULT '0',
  PRIMARY KEY  (comment_ID),
  KEY comment_post_ID (comment_post_ID),
  KEY comment_approved_date_gmt (comment_approved,comment_date_gmt),
  KEY comment_date_gmt (comment_date_gmt),
  KEY comment_parent (comment_parent),
  KEY comment_author_email (comment_author_email(10))
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_520_ci;
CREATE TABLE wp_links (
  link_id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  link_url VARCHAR(255) NOT NULL DEFAULT '',
  link_name VARCHAR(255) NOT NULL DEFAULT '',
  link_image VARCHAR(255) NOT NULL DEFAULT '',
  link_target VARCHAR(25) NOT NULL DEFAULT '',
  link_description VARCHAR(255) NOT NULL DEFAULT '',
  link_visible VARCHAR(20) NOT NULL DEFAULT 'Y',
  link_owner BIGINT(20) UNSIGNED NOT NULL DEFAULT '1',
  link_rating INT(11) NOT NULL DEFAULT '0',
  link_updated datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  link_rel VARCHAR(255) NOT NULL DEFAULT '',
  link_notes mediumtext NOT NULL,
  link_rss VARCHAR(255) NOT NULL DEFAULT '',
  PRIMARY KEY  (link_id),
  KEY link_visible (link_visible)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_520_ci;
CREATE TABLE wp_options (
  option_id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  option_name VARCHAR(191) NOT NULL DEFAULT '',
  option_value longtext NOT NULL,
  autoload VARCHAR(20) NOT NULL DEFAULT 'yes',
  PRIMARY KEY  (option_id),
  UNIQUE KEY option_name (option_name)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_520_ci;
CREATE TABLE wp_postmeta (
  meta_id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  post_id BIGINT(20) UNSIGNED NOT NULL DEFAULT '0',
  meta_key VARCHAR(255) DEFAULT NULL,
  meta_value longtext,
  PRIMARY KEY  (meta_id),
  KEY post_id (post_id),
  KEY meta_key (meta_key(191))
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_520_ci;
CREATE TABLE wp_posts (
  ID BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  post_author BIGINT(20) UNSIGNED NOT NULL DEFAULT '0',
  post_date datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  post_date_gmt datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  post_content longtext NOT NULL,
  post_title text NOT NULL,
  post_excerpt text NOT NULL,
  post_status VARCHAR(20) NOT NULL DEFAULT 'publish',
  comment_status VARCHAR(20) NOT NULL DEFAULT 'open',
  ping_status VARCHAR(20) NOT NULL DEFAULT 'open',
  post_password VARCHAR(255) NOT NULL DEFAULT '',
  post_name VARCHAR(200) NOT NULL DEFAULT '',
  to_ping text NOT NULL,
  pinged text NOT NULL,
  post_modified datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  post_modified_gmt datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  post_content_filtered longtext NOT NULL,
  post_parent BIGINT(20) UNSIGNED NOT NULL DEFAULT '0',
  guid VARCHAR(255) NOT NULL DEFAULT '',
  menu_order INT(11) NOT NULL DEFAULT '0',
  post_type VARCHAR(20) NOT NULL DEFAULT 'post',
  post_mime_type VARCHAR(100) NOT NULL DEFAULT '',
  comment_count BIGINT(20) NOT NULL DEFAULT '0',
  PRIMARY KEY  (ID),
  KEY post_name (post_name(191)),
  KEY type_status_date (post_type,post_status,post_date,ID),
  KEY post_parent (post_parent),
  KEY post_author (post_author)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_520_ci;

C++ – Initialize a two-dimensional vector in C++

1. init two-dimensional with 0 and resize

1
2
3
4
5
6
7
8
9
vector<vector<int>> c(n, vector<int>(m, 0));
 
resize:
// instantiate vector object of type std::vector<int>
std::vector<std::vector<int>> matrix;
 
// resize the vector to M elements of type std::vector<int>,
// each having size N and given default value
matrix.resize(M, std::vector<int>(N, default_value));

2. init with default value

1
2
3
4
5
6
vector<vector<int>> accounts
    {
        {1, 5},
        {7, 3},
        {3, 5}
    };

Spring – MultiValueMap and LinkedMultiValueMap

MultiValueMap is common object type in Spring Utils source code.

Here is an example of how to use it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
MultiValueMap<String, String> multiValueMaps = new LinkedMultiValueMap<String, String>();
multiValueMaps.add("Tom", "Book");
multiValueMaps.add("Tom", "Pen");
 
multiValueMaps.add("ABC", "Company");
multiValueMaps.add("ABC", "WebSite");
 
for(String key: multiValueMaps.keySet()) {
	List<String> value = multiValueMaps.get(key);
	System.out.print(key + "\t");
	for(String s: value) {
		System.out.print(s + "\t");
	}
	System.out.println();
}

Leetcode – 1553. Minimum Number of Days to Eat N Oranges

DP using hashMap

https://leetcode.com/problems/minimum-number-of-days-to-eat-n-oranges/

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import java.util.HashMap;
 
public class MinimumNumberofDaystoEatNOranges_5490 {
 
	HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
	public int minDays(int n) {
 
		hashMap.put(1, 1);
		hashMap.put(2, 2);
		hashMap.put(3, 2);
 
 
 
		return foo(n);
    }
 
	public int foo(int n) {		
		if(hashMap.containsKey(n))
			return hashMap.get(n);
 
		int a=Integer.MAX_VALUE,b=Integer.MAX_VALUE,c = Integer.MAX_VALUE;
 
		if(n%3 == 0 && n%2 == 0) {
			b = foo(n/3) + 1;
			a = foo(n/2) + 1;
		} 
		else if (n%3 == 0) {
 
			b = foo(n/3) + 1;
			c = foo(n - 1) + 1;
 
 
		}
		else if(n%2 == 0) {
			a = foo(n/2) + 1;
 
			c = foo(n - 1) + 1;
		}
		else {
			c = foo(n - 1) + 1;
		}
 
		int d = Math.min(Math.min(a,  b), c);
 
		hashMap.put(n, d);
		return d;
	}
 
	public static void main(String[] args) {
		MinimumNumberofDaystoEatNOranges_5490 s = new MinimumNumberofDaystoEatNOranges_5490();
		int n = 84806671;
 
		int result = s.minDays(n);
		System.out.println(result);
	}
}

GCC – Dump all Macro defined in GCC

$ gcc -E -dM – < /dev/null

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 
#define __SSP_STRONG__ 3
#define __DBL_MIN_EXP__ (-1021)
#define __UINT_LEAST16_MAX__ 0xffff
#define __ATOMIC_ACQUIRE 2
#define __FLT_MIN__ 1.17549435082228750797e-38F
#define __GCC_IEC_559_COMPLEX 2
#define __UINT_LEAST8_TYPE__ unsigned char
#define __SIZEOF_FLOAT80__ 16
#define __INTMAX_C(c) c ## L
#define __CHAR_BIT__ 8
#define __UINT8_MAX__ 0xff
#define __WINT_MAX__ 0xffffffffU
#define __ORDER_LITTLE_ENDIAN__ 1234
#define __SIZE_MAX__ 0xffffffffffffffffUL
#define __WCHAR_MAX__ 0x7fffffff
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 1
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 1
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 1
#define __DBL_DENORM_MIN__ ((double)4.94065645841246544177e-324L)
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 1
#define __GCC_ATOMIC_CHAR_LOCK_FREE 2
....

Java – long Value Mod Integer Value

Here is a java code for long % int (long mod int)

long v = 51;
long result = v%(10^9 + 7);

what is result value. it may looks to be surprised that result is 25.

result is supported to be 51.

here is right way to go.

long v = 51;
long result = v%100000007L
int finalResult = (int) result;

Idea here is very clear that we convert long%int to be long%long and convert result to be int.

linux 0.11 kernel – __NR_write and sys_write

Linux-0.11/include/linux/sys.h

1
2
3
4
fn_ptr sys_call_table[] = { sys_setup, sys_exit, sys_fork, sys_read,
sys_write, sys_open, sys_close, sys_waitpid, sys_creat, sys_link,
sys_unlink, sys_execve, sys_chdir, sys_time, sys_mknod, sys_chmod,
sys_chown, sys_break, sys_stat, sys_lseek, sys_getpid, sys_mount, ...}

Linux-0.11/include/unistd.h

1
2
3
4
5
6
7
#define __NR_setup	0	/* used only by init, to get system going */
#define __NR_exit	1
#define __NR_fork	2
#define __NR_read	3
#define __NR_write	4
#define __NR_open	5
#define __NR_close	6

Linux-0.11/lib/open.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
__asm__("int $0x80"
		:"=a" (res)
		:"0" (__NR_open),"b" (filename),"c" (flag),
		"d" (va_arg(arg,int)));
 
#define _syscall0(type,name) \
  type name(void) \
{ \
long __res; \
__asm__ volatile ("int $0x80" \
	: "=a" (__res) \
	: "0" (__NR_##name)); \
if (__res >= 0) \
	return (type) __res; \
errno = -__res; \
return -1; \
}
 
set_system_gate(0x80,&system_call);