Total Pageviews

2018/05/12

[snakeyaml] How to get rid of single quote in YAML when value is true / false?

Problem
The expected YAML is:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  intents:
  - greet
  - inform
  - others
  - question
  entities:
  - userid
  - is_account_locked
  - pass_company_check
  action_masking: true
  action_factory: remote
  actions:
  - utter_default
  - utter_greet
  - confirm:
      dependency:
        slots:
        - userid
  - unlock:
      dependency:
        slots:
        - userid
        - is_account_locked

Here has the 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
  package test.albert.snakeyaml;
  
  import java.util.Arrays;
  import java.util.HashMap;
  import java.util.List;
  import java.util.Map;
  
  import org.yaml.snakeyaml.DumperOptions;
  import org.yaml.snakeyaml.Yaml;
  import org.yaml.snakeyaml.constructor.Constructor;
  import org.yaml.snakeyaml.nodes.Tag;
  import org.yaml.snakeyaml.representer.Representer;
  
  import lombok.AllArgsConstructor;
  import lombok.Data;
  import lombok.extern.slf4j.Slf4j;
  
  @Slf4j
  public class SnakeYamlTest {
  
      public static void main(String[] args) {
          // Set DumperOptions options
          DumperOptions options = new DumperOptions();
          options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
          options.setPrettyFlow(true);
  
          // overwrite Representer
          Representer representer = new Representer();
          representer.addClassTag(ActionAttribute.class, Tag.MAP);
  
          // Create Yaml instance with Representer and DumperOptions
          Yaml yaml = new Yaml(new Constructor(), representer, options);
  
          // Prepare map data for YAML
          Map<String, Object> actionMap1 = new HashMap<>();
          actionMap1.put("confirm", new ActionAttribute(new Dependency(Arrays.asList("userid"))));
  
          Map<String, Object> actionMap2 = new HashMap<>();
          actionMap2.put("unlock", new ActionAttribute(new Dependency(Arrays.asList("userid", "is_account_locked"))));
  
          Map<String, Object> map = new HashMap<>();
          map.put("intents", Arrays.asList("greet", "inform", "others", "question"));
          map.put("entities", Arrays.asList("userid", "is_account_locked", "pass_company_check"));
          map.put("action_factory", "remote");
          map.put("actions", Arrays.asList("utter_default", "utter_greet", actionMap1, actionMap2));
          map.put("action_masking", "true");
  
          // Serialize a Java object into a YAML String
          String output = yaml.dump(map);
          log.info("\n" + output);
      }
  
      @Data
      @AllArgsConstructor
      private static class ActionAttribute {
          Dependency dependency;
      }
  
      @Data
      @AllArgsConstructor
      private static class Dependency {
          private List<String> slots;
      }
  }

But the action_masking value had been added single quote to its front and rear, how to remove single quote?
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  intents:
  - greet
  - inform
  - others
  - question
  entities:
  - userid
  - is_account_locked
  - pass_company_check
  action_masking: 'true'
  action_factory: remote
  actions:
  - utter_default
  - utter_greet
  - confirm:
      dependency:
        slots:
        - userid
  - unlock:
      dependency:
        slots:
        - userid
        - is_account_locked


How-To
According to snakeyaml source code, these values will regard as boolean value and add single quote from it front and rear



Therefore, you need to create a custom resolver to overwrite its value (remove true/false)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
  package test.albert.snakeyaml;
  
  import org.yaml.snakeyaml.nodes.Tag;
  import org.yaml.snakeyaml.resolver.Resolver;
  
  public class CustomResolver extends Resolver {
      protected void addImplicitResolvers() {
          addImplicitResolver(Tag.BOOL, BOOL, "yYnNoO");
      }
  }

Then create Yaml instance with this custom resolver
 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
  package test.albert.snakeyaml;
  
  import java.util.Arrays;
  import java.util.HashMap;
  import java.util.List;
  import java.util.Map;
  
  import org.yaml.snakeyaml.DumperOptions;
  import org.yaml.snakeyaml.Yaml;
  import org.yaml.snakeyaml.constructor.Constructor;
  import org.yaml.snakeyaml.nodes.Tag;
  import org.yaml.snakeyaml.representer.Representer;
  
  import lombok.AllArgsConstructor;
  import lombok.Data;
  import lombok.extern.slf4j.Slf4j;
  
  @Slf4j
  public class SnakeYamlTest {
  
      public static void main(String[] args) {
          // Set DumperOptions options
          DumperOptions options = new DumperOptions();
          options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
          options.setPrettyFlow(true);
  
          // overwrite Representer
          Representer representer = new Representer();
          representer.addClassTag(ActionAttribute.class, Tag.MAP);
  
          // Create Yaml instance with Representer, DumperOptions, CustomResolver
          Yaml yaml = new Yaml(new Constructor(), representer, options, new CustomResolver());
  
          // Prepare map data for YAML
          Map<String, Object> actionMap1 = new HashMap<>();
          actionMap1.put("confirm", new ActionAttribute(new Dependency(Arrays.asList("userid"))));
  
          Map<String, Object> actionMap2 = new HashMap<>();
          actionMap2.put("unlock", new ActionAttribute(new Dependency(Arrays.asList("userid", "is_account_locked"))));
  
          Map<String, Object> map = new HashMap<>();
          map.put("intents", Arrays.asList("greet", "inform", "others", "question"));
          map.put("entities", Arrays.asList("userid", "is_account_locked", "pass_company_check"));
          map.put("action_factory", "remote");
          map.put("actions", Arrays.asList("utter_default", "utter_greet", actionMap1, actionMap2));
          map.put("action_masking", "true");
  
          // Serialize a Java object into a YAML String
          String output = yaml.dump(map);
          log.info("\n" + output);
      }
  
      @Data
      @AllArgsConstructor
      private static class ActionAttribute {
          Dependency dependency;
      }
  
      @Data
      @AllArgsConstructor
      private static class Dependency {
          private List<String> slots;
      }
  }

2018/05/11

[Angular] How to add serial number in ng-grid

Problem
If I would like to add serial number in ng-grid, how to do it?
I would like to implement in client side instead of server side.

The column configuration in ng-grid is as bellows:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
  $scope.tab4.synonymCols  = [{
            field : 'value',
            displayName : 'value',
            cellClass : 'text-left',
            width : '25%'
        }, {
            field : 'synonyms',
            displayName : 'synonyms',
            cellClass : 'text-left',
            width : '70%'
        } ];


How-To
The updated column configuration in ng-grid is as bellows:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
       $scope.tab4.synonymCols  = [{
            field : 'seq',
            displayName : 'no',
            cellClass : 'text-left',
            width : '5%',
            cellTemplate: '<div class="ngCellText ng-scope col1 colt1" ng-class="col.colIndex()"><span ng-cell-text="">{{row.rowIndex + 1}}</span></div>'
        }, {
            field : 'value',
            displayName : 'value',
            cellClass : 'text-left',
            width : '25%'
        }, {
            field : 'synonyms',
            displayName : 'synonyms',
            cellClass : 'text-left',
            width : '70%'
        } ];





2018/05/10

[Java] How to compute variance and standard deviation via Java

Problem
Assume I have a List of double, I would like to compute its variance and standard deviation.

How to implement it with Java?

How-To
Here has sample code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
    public static void main(String[] args) {
        List<Double> data = Arrays.asList(0.51, 0.53, 0.49, 0.74, 0.55, 0.47, 0.59, 0.47, 0.45, 0.72);
        DoubleSummaryStatistics summaryStatistics = data.stream().mapToDouble(d -> d.doubleValue()).summaryStatistics();
        Double mean = summaryStatistics.getAverage();

        Double variance = 0d;
        for (Double num : data) {
            variance += Math.pow(num - mean, 2);
        }
        variance = variance / 10;
        Double standardDeviation = Math.sqrt(variance);

        DecimalFormat df = new DecimalFormat("0.000");

        log.info("variance = " + df.format(variance));
        log.info("standardDeviation = " + df.format(standardDeviation));
    }


2018/05/09

[Microsoft Excel] 如何運用 Excel 計算出變異數 (variance) 與標準差 (standard deviation)

Problem
假設我有十筆資料


How-To
可以利用 Excel 內建的 varp stdevp 計算出上述資料的變異數 (variance) 與標準差 (standard deviation)



2018/05/08

[Bootbox] How to set button focus in bootbox dialog

Problem
I am using Bootbox.js to create a custom dialog

The default behavior is focusing on the second button, i.e. EXCEL, how to I change its focus to the first button.

The code snippet is as bellows:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
  $scope.doExport = function() {
     bootbox.dialog({
     message: "請選擇要匯出 JSON 或 Excel",
         title: '匯出',
         buttons: {
            json: {
                label: 'JSON',
                callback: function() {
                    $scope.exportJson();
                }
            },
            excel: {
                label: 'Excel',
                callback: function() {
                    $scope.exportExcel();
                }
            }
         }
     });
  };


How-To
You can simply add btn-primay class to the first button, the code snippet is as following:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
   $scope.doExport = function() {
     bootbox.dialog({
         message: "請選擇要匯出 JSON 或 Excel",
         title: '匯出',
         buttons: {
             json: {
                 label: 'JSON',
                 className: 'btn-primary',
                 callback: function() {
                     $scope.exportJson();
                 }
             },
             excel: {
                 label: 'Excel',
                 callback: function() {
                     $scope.exportExcel();
                 }
             }
         }
     });
   };


Here has the updated dialog:



[Windows] Execute command every 10-sec in batch file

Problem
I would like to do two commands every 10 seconds via batch file in Windows:
 taskkill /IM test.exe /F
 del /F /Q C:\test\Bak\*.*


How to do it?


How-To
Here has the example:
:loop
 taskkill /IM test.exe /F
 del /F /Q C:\test\Bak\*.*
 timeout /t 10
 goto loop
 




2018/05/07

[Java] Use Apache Commons StringUtils.Replace Instead of String.replace

Quote
In general, the String.replace method works fine and is pretty efficient, especially if you’re using Java 9. But if your application requires a lot of replace operations and you haven’t updated to the newest Java version, it still makes sense to check for faster and more efficient alternatives.

Here has a simple experiments:

 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
package your.simple.java;

import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang.StringUtils;

public class StringReplacementTest {

    private String test = "test";
    private int count = 100000000;

    public static void main(String[] args) {
        new StringReplacementTest().test1();
        new StringReplacementTest().test2();
    }

    public void test1() {
        Date from = Calendar.getInstance().getTime();
        for (int i = 0; i < count; i++) {
            test.replace("test", "simple test");
        }

        Date to = Calendar.getInstance().getTime();
        long seconds = (to.getTime() - from.getTime()) / 1000;
        System.out.println("[test1] seconds = " + seconds);
    }

    public void test2() {
        Date from = Calendar.getInstance().getTime();
        for (int i = 0; i < count; i++) {
            StringUtils.replace(test, "test", "simple test");
        }

        Date to = Calendar.getInstance().getTime();
        long seconds = (to.getTime() - from.getTime()) / 1000;
        System.out.println("[test2] seconds = " + seconds);
    }

}


Execution result:
[test1] seconds = 56
[test2] seconds = 9


Reference
[1] https://dzone.com/articles/11-simple-java-performance-tuning-tips?edition=334833&utm_source=Daily%20Digest&utm_medium=email&utm_campaign=Daily%20Digest%202017-11-03

2018/05/06

[JavaScript] Utilize window.getSelection to get selected text

Problem
If I would like to get the selected text from a TextField via JavaScript, how to do it?

How-To

You can make good use of window.getSelection to fulfill this requirement.

HTML code snippet:

       <div class="row">
           <div class="col-sm-offset-1 col-sm-10">
             <div class="form-group">
               <label for="operaName" class="control-label">連續劇</label>
               <input type="text" class="form-control input-lg" id="operaName" data-ng-model="operaName" 
                      data-ng-mouseup="showOperaSelectedText()" >
             </div>
             <div class="form-group">
              <label class="control-label">起訖</label>
              <span> {{operaNameFromIndex}} ~ {{operaNameToIndex}}</span>
             </div>
             <div class="form-group">
                 <label class="control-label">選擇文字</label>
                 <span> {{operaNameSelected}}</span>
             </div>
           </div>
       </div>


JavaScript code snippet:
     $scope.operaName = "又,吳海英";
     $scope.operaNameFromIndex = 0;
     $scope.operaNameToIndex = 0;
     $scope.operaNameSelected = '';
      
     $scope.showOperaSelectedText = function() {
     // if selected
     if (window.getSelection) {
          // get selected text
          $scope.operaNameSelected = window.getSelection().toString();
          // get from index
          $scope.operaNameFromIndex = $('#operaName').prop('selectionStart');
          // get end index
         $scope.operaNameToIndex = $('#operaName').prop('selectionEnd');
         }
     }


Screenshot:


2018/05/05

[Angular] How to show data via ng-repeat in horizontal ?

Problem
Assume I have an String array.
    $scope.names = ['朴道京', '吳海英', '李振尚', '朴秀京', '朴勳'];

I would like to show these names in HTML page via ng-repeat, here has the code snippet:

    <div class="row">
      <div class="col-sm-offset-1 col-sm-4">
         <div data-ng-repeat="name in names">
               <span>{{name}}</span>
         </div>
      </div>
    </div>

But it display in vertical way, how to display in horizontal way?


How-To
Use span instead of div, the updated code snippet are as bellows:
   <div class="row">
     <div class="col-sm-offset-1 col-sm-4">
        <span data-ng-repeat="name in names">
              <span>{{name}}</span>
        </span>
     </div>
   </div>

Here has the screenshot:




2018/05/04

[閱讀筆記] The Little Book That Builds Wealth (4/7)

  1. 追求成長不一定都是好的。公司應該在自己擅長的領域賺錢與分享利潤給股東,不要將所賺得的利潤投入沒有護城河與未知的產業。Microsoft 有本錢這樣玩 (如成立Actimates 用來販售一系列的小孩玩具,又如成立 cable news chaneel 提供新聞服務等),但是大部分的公司並沒有這樣的本錢
  2. 有些產業競爭非常激烈,非常難以建立起獨特的競爭優勢;有些產業則相對沒這麼競爭 ,即便是普通的公司也可以維持穩固的資本回報。身為投資人,你應該選擇後者來投資
  3. Morningstar 將護城河分成兩類,公司擁有非常持久且強大的競爭優勢,稱為 wide moat;另外,公司所擁有的競爭優勢並非相當強大,則稱為 narrow moat
  4. 當成本是最重要的事情時,在此產業就很難挖掘出護城河。無論你是在挖掘金屬礦物、製造化學原料、生產鋼鐵等,這些都非常難以做出差異化,導致你的客戶只在乎誰最便宜
  5. 如何衡量企業的獲利能力呢?計算企業投入多少錢,以及獲得多少利潤,獲得的利潤越高,代表這個產品或服務就會好。即投入的資金轉換為獲利的效率
  6. 衡量資本回報率的幾個指標
    1. 資產回報率(ROA, Return On Assets)
      1. ROA 衡量的是每一塊錢的資產替公司產生多少收入
      2. ROA 的視角實際上是從資產負債表的左側去看,從資產的角度衡量回報,而並不關注資本結構。 資產收益率 = 凈利潤 / 總資產總額
    2. 凈資產回報率(ROE, Return On Equity):ROE的視角是從股東的角度看問題,單純從股權的角度衡量回報,而不考慮公司的資本結構及負債情況。凈資產收益率 = 稅後利潤 / 所有者權益。假定某公司年度稅後利潤為2億元,年度平均凈資產為15億元,則其本年度之凈資產收益率就是13.33%(即(2億元/15億元)*100%)。
    3. 投入資本回報率(ROIC, Return On Invested Capital)
      1. ROIC是從資本的角度看問題,綜合考慮股權與債權,衡量投資的效率。與ROIC對應的是平均資金成本(WACC)。如果ROIC小於WACC,就說明投入資本的回報小於平均資本成本,公司是在浪費資本。ROIC=息稅前收益(EBIT)*(1-稅率)/ 投入資本
      2. ROIC 計算相當複雜且不像 ROA、ROE這麼容易取得
  7. ROE 的缺點是,越會借錢的公司,ROE 就會越高,所以當你用 ROE 在分析企業的資本回報,記得留意公司的負債
  8. 有些產業在結構上就是比其他產業更賺錢,其一定較容易建立起護城河。你應該把錢投資在這種產業
  9. 有些產業就是比其他產業更容易建立起競爭優勢,人生本來就不公平
  10. 護城河是絕對的,不是相對的。結構上較具吸引力的產業的第四名的公司,與殺得你死我活的最佳的公司相較之下,前者一定擁有較寬廣的護城河
  11. 所謂的優秀企業,是指『更容易長期產生高資本報酬率的企業』
  12. 公司經營者的表現,沒有想你的這麼重要
  13. 企業的長期競爭優勢源自於結構化的企業特色,包含無形資產 (intangible assets)、轉換成本 (switching costs)、網絡效應 (network economics)、與成本優勢 (cost advantage),公司經營者對於這幾點的影響力微乎極危微
  14. 新創公司的投資人,應將分析比重主要放在新創公司所投入的事業,而非新創公司的管理團隊
  15. 公司的結構化特性 (structural characteristics) 對於企業的長期競爭優勢有巨大的影響,管理者的決策則鮮少造成影響
  16. 賽馬時,你該賭的是馬,而非騎師  (bet on the horse, not the jockey)
  17. 一個 CEO ,很難建立起不存在的競爭優勢,或是摧毀一開始就建立起來很強壯的競爭優勢
  18. 在沒有護城河、深陷紅海競爭的企業,為了克服更大的困難來獲得成功,的確需要優秀的管理者,才有機會獲得困難的競爭優勢,如 Starbucks、Dell、Nucor (紐克鋼鐵) 等。若是在擁有寬廣、強大的護城河的公司,CEO 的重要性就不是這麼高了
  19. 儘管說,好的 CEO 可以增加企業的價值,但是管理本身並無法建立可持續的競爭優勢
  20. 管理雖然重要,但是其重要性遠低於護城河
  21. 你該投資一家平庸的 CEO 但是擁有寬廣護城河的公司,而非投資一間由 superstar 所管理但是沒有護城河的公司。長期來說,前者可以提供較高的成功機率
  22. 尋找護城河流程
  1. 零售業與連鎖餐廳的客戶轉換成本(switching costs)非常低,所以在此產業中的企業必須建立起規模、擁有良好信譽的品牌或其他可以防禦的優勢,才能擁有護城河。若沒有護城河,現在的高資本報酬率(returns on capital),很快就會消失
  2. 檢視一家公司是否擁有經濟護城河,第一步是檢查產生資本回報的歷史紀錄。強勁的資本回報率代表公司可能擁有護城河,平庸或差勁的資本回報率代表公司缺乏競爭優勢
  3. 若一家企業擁有強勁的資本回報率,還需確認其是否有能力繼續維持這樣的績效表現。採用競爭優勢分析工具,如無形資產 (intangible assets)、轉換成本 (switching costs)、網絡效應 (network economics)、與成本優勢 (cost advantage),試著找出企業的護城河。若你無法找出維持優異的資本回報率的原因,這家公司可能不具備護城河