Posts

Showing posts with the label How Tos

How to add Lombok to your project : Lombok Dependency is missing

Image
Lombok Dependency is missing How to add Lombok to your project

Android java: How to display phonetic symbol with correct fonts via WebView ?

Image
First, Download lingoes font file Android default fonts can not display phonetic symbol. lingoes.ttf can, please download it. Second, Put lingoes.ttf to assets/font Last, Add "lingoes" font-family in css files under assets @font-face { font-family: 'lingoes'; src:url('file:///android_asset/fonts/lingoes.ttf') format('truetype'); font-weight: normal; font-style: normal; } Use "lingoes" as font-family for the phonetic symbol content Android java : How to load html files in assets via WebView?

Android java : How to load html files in assets via WebView?

Image
The base url for html files under the assets of your app is "file:///android_asset/" WebView wv = new WebView(context); wv.getSettings().setJavaScriptEnabled(true); wv.loadUrl("file:///android_asset/coca/coca_00001_the.html");

Android java : How to copy/move file from assets to absolute path?

private void moveAssets(String assets_file_path, String absolutePath) throws IOException { File wwwFile = new File(absolutePath); if (wwwFile.exists()) return; InputStream is = activity.getAssets().open(assets_file_path); byte[] buffer = new byte[is.available()]; is.read(buffer); is.close(); wwwFile.createNewFile(); FileOutputStream os = new FileOutputStream(wwwFile); os.write(buffer); os.close(); }

Android java: How to orientation activity layout automatically ?

Add ~ android:screenOrientation="fullSensor" ~ to the activity AndroidManifest.xml activity android:name=".MainActivity" android:screenOrientation="fullSensor"

shell bash scripts : check process existed or not, if not existed then restart it

Put below scripts in your ~/.bash_profile or ~/.bashrc It will auto run "unison" process if not running yet when you open a new bash shell every time. Change the process name "unison" for your case. :) auto_unison() { u=`ps aux | grep unison | grep -v grep | wc -l` if [ $u -eq 0 ] then unison > /dev/null 2>&1 & fi } auto_unison

Android how to detect/register language/locale change listener/receiver

The easy way is to register a BroadcastReceiver for Intent.ACTION_LOCALE_CHANGED . Example: change your ViewModel data when language/locale changed. public class QASViewModel extends ViewModel { @SuppressLint ( "StaticFieldLeak" ) private final FragmentActivity activity ; public QASViewModel ( @NonNull FragmentActivity activity ) { this . activity = activity ; setLangReceiver (); } private void setLangReceiver () { final QASViewModel qasViewModel = this ; final BroadcastReceiver langReceiver = new BroadcastReceiver () { @Override public void onReceive ( Context context , Intent intent ) { // do action when language change } }; activity . getApplicationContext (). registerReceiver ( langReceiver , new IntentFilter ( Intent . ACTION_LOCALE_CHANGED )); } }

Android ViewModel with ArgsConstructor via Custom ViewModelFactory

Android ViewModel is very useful. However ViewModel has no args constructor by default. Typical usage of ViewModel looks like: public class UserModel extends ViewModel { } final UserModel viewModel = ViewModelProviders . of ( this ). get ( UserModel . class ); Let's look the definition of ViewModelProviders.of method. /** * Creates a {@link ViewModelProvider}, which retains ViewModels while a scope of given Activity * is alive. More detailed explanation is in {@link ViewModel}. * * It uses the given {@link Factory} to instantiate new ViewModels. * * @param activity an activity, in whose scope ViewModels should be retained * @param factory a {@code Factory} to instantiate new ViewModels * @return a ViewModelProvider instance */ @NonNull @MainThread public static ViewModelProvider of ( @NonNull FragmentActivity activity , @Nullable Factory factory ) { Have you found it? We can pas

How to convert UTC Date Time String to Java object and compare it ?

Use java.time.Instant ; import java.time.Instant; Instant instantStart = Instant.parse("20200229T12:00:00Z"); Instant instantEnd = Instant.parse("20200329T12:00:00Z"); Instant instantNow = Instant.now(); return instantNow.isAfter(instantStart) && instantNow.isBefore(instantEnd);

How to convert json array to java Object

Use com.amazonaws.util.json.Jackson import com.amazonaws.util.json.Jackson; import java.util.ArrayList; import lombok.Data; @Data class DeviceList { private ArrayList<String> devices; } DeviceList deviceList = Jackson.fromJsonString( "{\"devices\":[\"Mobile\", \"Desktop\"]}", DeviceList.class);

Java Spring Bean constructor how to get call stack, backtrace

Easy wasy to print Java call stack or backtrace: Implement a function and throw an Exception. Call the function in the place you want to know its backtrace or callstack And Catch the Exception then Call Exception.getStackTrace class MyService { public static void f() throws Exception { throw new Exception(); } void forTest() { try { f(); } catch (Exception e) { e.printStackTrace(); } } } Via this solution, we can get Bean constructor call stack easily. [tomcat:launchProperties] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [tomcat:launchProperties] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) [tomcat:launchProperties] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [tomcat:launchProperties] at java.lang.reflect.Method.invoke(Method.java:498) [tomcat:launchProperties] at org.sprin

How to use @Mock @InjectMocks

class MyService { private UserDao userDao; } import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.runners.MockitoJUnitRunner; public class MyServiceTest { @InjectMocks private MyService myService; @Mock private UserDao userDao; @Before public void setUp() { myService = new MyService(); } } Cannot mock/spy class java.lang.String Mockito cannot mock/spy following: - final classes - anonymous classes - primitive types org.mockito.exceptions.base.MockitoException: Cannot mock/spy class java.lang.String Mockito cannot mock/spy following: - final classes - anonymous classes - primitive types at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl$1.withBefores(JUnit45AndHigherRunnerImpl.java:27) at org.mockito.internal.runners.JUnit45AndHigher

How to increase terminal window buffer in IntelliJ

Image
Command + Shift + A or Ctrl + Shift + A Type registry, click "Registry..." Increase the "terminal.buffer.max.lines.count" to 100000 or any number you want, the default is 1000.

make vim like source insight, a effective c/c++ ide

Image
IDE setup latest vim git clone https://github.com/vim/vim.git cd vim/src ./configure --enable-cscope --enable-terminal make sudo make install https://www.vim.org/git.php use universal ctags git clone https://github.com/universal-ctags/ctags.git cd ctags ./autogen.sh ./configure make sudo make instahttps://www.tamacom.com/global/global-6.6.3.tar.gzll setup gnu tags wget https://www.tamacom.com/global/global-6.6.3.tar.gz tar -xvf global-6.6.3.tar.gz cd global-6.6.3 sh reconf.sh sudo apt install ncurses-dev ./configure --with-universal-ctags=/usr/local/bin/ctags make sudo make install https://www.tamacom.com/global/global-6.6.3.tar.gz http://www.gnu.org/software/global/download.html install gtags as vim plugin cp gtags.vim ~/.vim/plugin/ cp gtags-cscope.vim ~/.vim/plugin/ config gtags as cscope in ~/.vimrc " gtags configure " To use the default key/mouse mapping: let GtagsCscope_Auto_Map = 1 " To ignore letter case when searching: let GtagsCscope_Ignore_Cas

nginx : set up http/https conf for your server(Ghost)

Let me use cluster.errong.win as a example. All you need to do is replace the server name and port. All reqest to cluster.errong.win will be proxyed by http://127.0.0.1:6666 http conf server { listen 80; listen [::]:80; server_name cluster.errong.win; root /home/errong_leng/www/cluster/system/nginx-root; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $http_host; proxy_pass http://127.0.0.1:6666; } location ~ /.well-known { allow all; } client_max_body_size 50m; } enable http server to nginx ln -sf /home/errong_leng/www/cluster/system/files/cluster.errong.win.conf /etc/nginx/sites-available/cluster.errong.win.conf ln -sf /etc/nginx/sites-available/cluster.errong.win.conf /etc/nginx/sites-enabled/cluster.errong.win.conf Use Let's Encrypt Le

react-native : navigate/load url via WebView

Image
No Image, No Truth use WebView component in reactnative. var { ...., WebView, } = React; initial state give a default url getInitialState: function() { return { url: '', // or default url }; }, render with state url <WebView ....your styles, properties url={this.state.url} /> Navigate/load codes load() { this.setState({url:'http://google.com'}); } Full Sample Codes import React, { Component } from 'react'; import { Button, Modal, Image, Keyboard, NativeModules, Platform, StyleSheet, Text, TextInput, TouchableOpacity, View, WebView, } from 'react-native'; const { WeChat } = NativeModules; const SHARE_TO_WXTIMELINE = 0; const SHARE_TO_WXSESSION = 1; const webview = "webview"; const HOME_URL = " https://errong.win "; export default class App extends Component<{}> { componentWillMount () { this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', () => {this.k

react-native : Modal example, share to WeChat

Image
Refer https://facebook.github.io/react-native/docs/modal.html No Image, No Truth Full Codes import React, { Component } from 'react'; import { Button, Modal, Image, Keyboard, NativeModules, Platform, StyleSheet, Text, TextInput, TouchableOpacity, View, WebView, } from 'react-native'; const { WeChat } = NativeModules; const SHARE_TO_WXTIMELINE = 0; const SHARE_TO_WXSESSION = 1; const webview = "webview"; const HOME_URL = "https://errong.win"; export default class App extends Component<{}> { componentWillMount () { this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', () => {this.keyboardDidHide()}); } componentWillUnmount () { this.keyboardDidHideListener.remove(); } keyboardDidHide () { console.log( this.urlText ); if (this.urlText != null) { this.setState({url:this.urlText}); } } constructor(props) { super(props);

react-native : How to create Image Button

Image
Solution Use TouchableOpacity , Image and Styles . Key codes import React, { Component } from 'react'; import { Image, StyleSheet, TouchableOpacity, } from 'react-native'; <TouchableOpacity style={styles.sharebutton} onPress={() => {this.onShare(SHARE_TO_WXTIMELINE)}} > <Image source={require('./res/img/wxtimeline.png')} /> </TouchableOpacity> No Image, No Truth See Full sample codes Share to WeXin via Modal

react-native : Native Modules, name prefix "RCT"works for android too

I tried to export wechat sdk as a native module. I copied some codes here: public class WeChatModule extends ReactContextBaseJavaModule implements IWXAPIEventHandler {  private String appId;  public WeChatModule(ReactApplicationContext context) {  super(context);  }  @Override public String getName() {  return "RCTWeChat";  }  } I used "RCTWeChat" as the module name, I did not know the "RCT" prefix meanings. ReactContextBaseJavaModule requires that a method called getName is implemented. The purpose of this method is to return the string name of the NativeModule which represents this class in JavaScript. Then I encountered error in my react-native JS codes. import {NativeModules} from 'react-native'; const { RCTWeChat } = NativeModules; WeChat or NativeModules.RCTWeChat always undefined. Cause RCT is a prefix used in react native, it will be removed when exported to JS. React Native uses RCT as a prefix. In

react-native run-android : No connected devices!

Image
What went wrong: Execution failed for task ':app:installDebug'. com.android.builder.testing.api.DeviceException: No connected devices! Cause ADB driver is not ready Solution Install correct driver