2016年12月24日 星期六

永久修改 Ipython Nortebook 或 Jupter Notebook 的默認目錄

參考:
http://xuanchao1980.com/2016/05/12/jupyterDirectory/

步驟:
Ipython Notebook

1.打開命令行(初始化配置文件):
ipython profile create

這個命令,會初始化一份配置文件ipython_notebook_config.py,輸入後找到下面這行

# c.NotebookManager.notebook_dir = u'D:\\love\\cat'

如果没有,請找這行:

# c.NotebookApp.notebook_dir = u'Z:\\luv\\cat'

2.去掉註解&空格,修改路徑路徑為自己想要的

Jupyter Notebook

1.打開命令行(初始化配置文件):
jupyter notebook --generate-config
這個命令,會初始化一份配置文件.jupyter\jupyter_notebook_config.py
輸入後找到下面這行

# c.NotebookApp.notebook_dir = u'D:\\love\\you'


2.去掉註解&空格,修改路徑路徑為自己想要的

2016年12月20日 星期二

Word Cloud 文字雲 - jQCloud & WordCloud2

Sample Step:

1.Download word cloud jquery:
http://mistic100.github.io/jQCloud/#usage



2.Include package & jQuery CDN
- jqcloud.min.js- jqcloud.min.css
- jqcloud.min.js- jqcloud.min.js
- https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js

- 程式碼
<head>
 <meta charset="utf-8">
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
 <script src="jqcloud.min.js"></script>
 <link rel="stylesheet" href="jqcloud.min.css">
 <title>test</title>
</head>

3.設定『資料』 & 啟用文字雲
- 要記得給文字雲『範圍大小』,否則畫面上看不到
$('#keywords').jQCloud(words, {
  width: 500,
  height: 350
});

- 設定假資料
<script>
 $(function(){
  var words = [
    {text: "Lorem", weight: 13},
    {text: "Ipsum", weight: 10.5},
    {text: "Dolor", weight: 9.4},
    {text: "Sit", weight: 8},
    {text: "Amet", weight: 6.2},
    {text: "Consectetur", weight: 5},
    {text: "Adipiscing", weight: 5},
  ];

  <!-- $('#demo').jQCloud(words); -->
  
  $('#demo').jQCloud(words, {
    width: 600,
    height: 600
  });
 });
</script>

4.Result



5.Sample code
<!doctype html>
<html>
 <head>
  <meta charset="utf-8">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
  <script src="jqcloud.min.js"></script>
  <link rel="stylesheet" href="jqcloud.min.css">
  <title>test</title>
 </head>
 
 <script>
 $(function(){
  var words = [
    {text: "Lorem", weight: 13},
    {text: "Ipsum", weight: 10.5},
    {text: "Dolor", weight: 9.4},
    {text: "Sit", weight: 8},
    {text: "Amet", weight: 6.2},
    {text: "Consectetur", weight: 5},
    {text: "Adipiscing", weight: 5},
  ];

  <!-- $('#demo').jQCloud(words); -->
  
  $('#demo').jQCloud(words, {
    width: 600,
    height: 600
  });
 });

 </script>
 <body>
  <div id="demo" style="border:thin solid black">
  </div> 
 </body>

</html>

6.Advance Skill 
[自訂設定]
- delay: 50 (字體顯示的速度)
- steps : Number of "steps" to map the words on, depending on their weight (大約會有幾種字體大小,會與自設的color進行比對)
- colors: 自訂顏色
-from-to: 字體最大-最小(根據container的大小)
$('#wordCloud').jQCloud(words, {
    delay: 50,
    width: 500,
    height: 500,
    autoResize: true,
    steps : 50,
    //最凸顯
    colors: ["#CC0066", "#CC0066", "#009999", "#009999", "#FFCC33", "#FFCC33", "#0099CC", "#0099CC", "#FF6666","#FF6666",
        "#FF33CC", "#FF33CC", "#FF6600", "#FF6600", "#009966", "#009966", "#CC6633", "#CC6633", "#FF6666","#FF6666",
        "#555555", "#555555", "#555555", "#555555", "#555555", "#444444", "#444444", "#444444", "#444444","#444444",
        "#666633", "#666633", "#666633", "#666633", "#666699", "#666666", "#666666", "#666666", "#666666","#666666",
        "#333333", "#333333", "#333333", "#333333", "#333333", "#999999", "#999999", "#999999", "#999999","#999999"
    ],
    fontSize: {
        from: 0.08,
        to: 0.02
    }
});

[文字雲特殊效果(字體隨滑鼠移出移入改變)]
//文字雲特殊效果
$(document).on('mouseenter','.jqcloud-word',function(){
    var font_size = parseFloat($(this).css("font-size"));
    var newSize = font_size + 10;
    $(this).css("font-size",newSize + 'px');
}).on('mouseout','.jqcloud-word',function(){
    var font_size = parseFloat($(this).css("font-size"));
    var newSize = font_size - 10;
    $(this).css("font-size",newSize + 'px');
});

[使用者可調整"字體顏色"、文字雲型狀]

1.按下"更新"
2.刪掉文字雲
3.重建文字雲
//delete
wordCloud.jQCloud('destroy');
//update word cloud
wordCloud.jQCloud(words, {
    delay: 40,
    width: width,
    height: height,
    autoResize: true,
    steps : 50,
    colors: colorStyle,
    shape: shape,
    fontSize: {
        from: 0.08,
        to: 0.02
    }
});

4.sample code
//文字雲update
$('#updateButton').on('click', function() {
    var wordCloud = $('#wordCloud');
    var selectColorStyle = $('#colorStyle').val();
    var selectShape = $('#shape').val();
    var colorStyle;
    //custom color style
    if (selectColorStyle == '1') {
        colorStyle = ["#CC0066", "#CC0066", "#009999", "#009999", "#FFCC33", "#FFCC33", "#0099CC", "#0099CC", "#FF6666","#FF6666",
            "#FF33CC", "#FF33CC", "#FF6600", "#FF6600", "#009966", "#009966", "#CC6633", "#CC6633", "#FF6666","#FF6666",
            "#555555", "#555555", "#555555", "#555555", "#555555", "#444444", "#444444", "#444444", "#444444","#444444",
            "#666633", "#666633", "#666633", "#666633", "#666699", "#666666", "#666666", "#666666", "#666666","#666666",
            "#333333", "#333333", "#333333", "#333333", "#333333", "#999999", "#999999", "#999999", "#999999","#999999"
        ];
    } else if (selectColorStyle == '2') {
        colorStyle = ["#CC0066", "#CC0066", "#009999", "#009999", "#FFCC33", "#FFCC33", "#0099CC", "#0099CC", "#FF6666","#FF6666",
            "#FF33CC", "#FF33CC", "#FF6600", "#FF6600", "#009966", "#009966", "#CC6633", "#CC6633", "#FF6666","#FF6666",
            "#3399CC", "#3399CC", "#CC6600", "#CC6600", "#999999", "#444444", "#444444", "#444444", "#444444","#444444",
            "#666633", "#666633", "#666633", "#666633", "#666699", "#666666", "#666666", "#666666", "#666666","#666666",
            "#333333", "#333333", "#333333", "#333333", "#333333", "#999999", "#999999", "#999999", "#999999","#999999"
        ];
    } else if (selectColorStyle == '3') {
        colorStyle = ["#CC0066", "#CC0066", "#009999", "#009999", "#FFCC33", "#FFCC33", "#0099CC", "#0099CC", "#FF6666","#FF6666",
            "#FF33CC", "#FF33CC", "#FF6600", "#FF6600", "#009966", "#009966", "#CC6633", "#CC6633", "#FF6666","#FF6666",
            "#3399CC", "#3399CC", "#CC6600", "#CC6600", "#999999", "#999999", "#CCCC33", "#CCCC33", "#CCCC33","#CCCC33",
            "#FF9933", "#FF9933", "#CC9999", "#CC9999", "#666699", "#666699", "#FF9900", "#FF9900", "#0099CC","#0099CC",
            "#CCCC99", "#CCCC99", "#FF6666", "#FF6666", "#FFCC99", "#FFCC99", "#CC3399", "#CC3399", "#99CC33","#99CC33"
        ];
    }
    //custom shape
    var width;
    var height;
    var shape;
    if (selectShape == '1') {
        width = 550;
        height = 400;
        shape = 'elliptic';
    } else if (selectShape == '2') {
        width = 500;
        height = 500;
        shape = 'elliptic';
    } else {
        width = 550;
        height = 400;
        shape = 'rectangular';
    }
    //delete
    wordCloud.jQCloud('destroy');
    //update word cloud
    wordCloud.jQCloud(words, {
        delay: 40,
        width: width,
        height: height,
        autoResize: true,
        steps : 50,
        colors: colorStyle,
        shape: shape,
        fontSize: {
            from: 0.08,
            to: 0.02
        }
    });
});

Word Cloud 2

1.下載:
https://timdream.org/wordcloud2.js/#red-chamber

2.Sample Code:
<!doctype html>
<html>
 <head>
  <meta charset="utf-8">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
  <script src="wordcloud2.js"></script>
  <title>test</title>
 </head>
 
 <script>
 $(function(){
  var words = [
   ["哈哈哈哈",60],
   ["Ipsum",19],
   ["Dolor",18],
   ["Sit",17],
   ["Amet",16],
   ["Consectetur",15],
   ["Adipiscing",14],
   ["dsfsf",13],
   ["Ipsdfsum",12],
   ["Dosdfsdflor",11],
   ["台灣",10],
   ["Ipsum",9],
   ["Dolor",8],
   ["Sit",7],
   ["Amet",6],
   ["Consectetur",5],
   ["Adipiscing",4],
   ["dsfsf",3],
   ["Ipsdfsum",2],
   ["Dosdfsdflor",1],
   ["台灣",25],
   ["Ipsum",24],
   ["Dolor",23],
   ["Sit",22],
   ["Amet",21],
  ];

  WordCloud($('#wordCloud')[0], {
            list: words,
            classes: 'wordCloud',
            wait: 30,
            gridSize: 10,
            weightFactor: 1.6,
            fontFamily: 'Hiragino Mincho Pro, serif',
            color: 'random-dark',
            backgroundColor: '#FFFFFF',
            rotateRatio: 0
        });
        //文字雲update
        $('#updateButton').on('click', function() {
            //custom shape
            var selectShape = $('#shape').val();
            var shape;
            if (selectShape == '1') {
                shape = 'circle';
            } else if (selectShape == '2') {
                shape = 'star';
            } else if (selectShape == '3') {
                shape = 'pentagon';
            } else if (selectShape == '4'){
                shape = 'diamond';
            } else if (selectShape == '5') {
                shape = 'triangle';
            }
            WordCloud($('#wordCloud')[0], {
                list: words,
                classes: 'wordCloud',
                wait: 30,
                shape: shape,
                gridSize: 10,
                weightFactor: 1.6,
                fontFamily: 'Hiragino Mincho Pro, serif',
                color: 'random-dark',
                backgroundColor: '#FFFFFF',
                rotateRatio: 0
            });
        });
        //文字雲特殊效果
        $(document).on('mouseenter','.wordCloud',function(){
            var font_size = parseFloat($(this).css("font-size"));
            var newSize = font_size + 10;
            $(this).css("font-size",newSize + 'px');
        }).on('mouseout','.wordCloud',function(){
            var font_size = parseFloat($(this).css("font-size"));
            var newSize = font_size - 10;
            $(this).css("font-size",newSize + 'px');
        });
  
  });
 
 </script>
 
 <body>
 <div style="border:thin solid red;align:center">
  <div id="wordCloud" style="width:500px;height:500px;border:thin solid black;margin:0 auto">
  </div>
 </div>  
 
 <select id="shape" class="pull-right" style="height: 27px;width: 100px;margin: 3px" type="select">
  <option value='1' selected="selected">雲朵</option>
  <option value='2' >星星</option>
  <option value='3'>五角大廈</option>
  <option value='4'>鑽石</option>
  <option value='5'>金字塔</option>
 </select>
 </body>
 <button class="" id="updateButton">Update</button>

</html>

2016年12月19日 星期一

Hibernate Criteria - DQL

Hibernate - Criteria

參考:
http://openhome.cc/Gossip/HibernateGossip/CriteriaBasic.html

範例:
1.add()
- org.hibernate.criterion.Criteria 實例代表著一個條件,您要使用org.hibernate.Criteria的add()方法加入這些條件實例,例如查詢” age”大於20且小於40的資料

- 使用add()時,預設是使用and來組合條件

- gt()大於 lt小於
Criteria criteria = session.createCriteria(User.class);
criteria.add(Restrictions.gt("age", new Integer(20)));
criteria.add(Restrictions.lt("age", new Integer(40)));
List users = criteria.list();

2.or()
- age等於(eq)20或(or)age為空(isNull)的條件
Criteria criteria = session.createCriteria(User.class);
criteria.add(Restrictions.or(
               Restrictions.eq("age", new Integer(20)),
               Restrictions.isNull("age")
           ));
List users = criteria.list();

3.like()
- 查詢"name"中名稱為"just"開頭的資料:
Criteria criteria = session.createCriteria(User.class);
criteria.add(Restrictions.like("name", "just%"));
List users = criteria.list();

4.in()
- 條件要放 『陣列 []
String[] queryArray = {"John", "Ian"}

criteria.add(Restrictions.in(columnName, queryArray)); // 使用criteria columnName要放『物件的名稱』not 欄位名稱

5.between()
- 要注意型態問題(ex. timestamp)
Criteria criteria = session.createCriteria(AuditTrail.class);
criteria.add(Restrictions.between("auditDate", sDate, eDate));

6.Restrictions的幾個常用限定查詢方法如下表所示:
方 法說 明
Restrictions.eq等於
Restrictions.allEq使用Map,使用key/value進行多個等於的比對
Restrictions.gt大於 >
Restrictions.ge大於等於 >=
Restrictions.lt小於 <
Restrictions.le小於等於 <=
Restrictions.between對應SQL的BETWEEN子句
Restrictions.like對應SQL的LIKE子句
Restrictions.in對應SQL的in子句
Restrictions.andand關係
Restrictions.oror關係
Restrictions.sqlRestrictionSQL限定查詢

2016年12月16日 星期五

Hibernate SQL - DML、DQL、JOIN 範例

SQL
參考:http://blog.csdn.net/vacblog/article/details/7769976

-Select
1.addEntity()
透過『addEntity()』將"table"與"實體類"關聯在一起
這樣可以融合SQL簡潔的語法與Hibernate的方便性

使用addEntity()的大前提
-查詢返回的是某個table的全部數據  
-該table有對應的映射實體

這時候才能透過addEntity()方法將查詢結果轉換成實體
Query query = session.createSQLQuery(
"SELECT * FROM user_account ua WHERE ua.account=:account AND ua.user_email=:emailAddress ")
.addEntity(UserAccountEntity.class) //結合entity的方式把資料傳回來,但使用時有前提
.setParameter("account", account)
.setParameter("emailAddress", emailAddress);
resultList = query.list();

2.使用別名的addEntity()
String sql = "select {myUser.*} from user_information myUser ORDER BY myUser.id";
SQLQuery query = session.createSQLQuery(sql);
query.addEntity("myUser", UserInformationEntity.class);

3.addScalar()
最基本的SQL查询就是取得一個物件的列表:
session.createSQLQuery("select * from person_inf").list();  
session.createSQLQuery("select id,name,age from person_inf").list();  

此時會返回一個Object陣列组成的List,陣列每個元素都是person_inf表的一個欄位值。Hibernate會使用ResultSetMetadata來判定返回的值的實際順序跟類型。
但是在JDBC中過多的使用ResultSetMetadata會降低程序的性能。為避免過多使用ResultSetMetadata或者指定更加明確的返回值類型,我們可以使用addScalar()方法提高效能
session.createSQLQuery("select * from person_inf")  
.addScalar("name",StandardBasicTypes.STRING)  
.addScalar("age",StandardBasicTypes.INT)  
.list();  

上述查询指定了:
-SQL查询欄位。
-要返回的欄位值和類型。
但是他仍然會返回Object陣列,但是此時不再使用ResultSetMetdata,而是明確的將\name和age按照String和int類型從resultset中取出。同時,也指明了就算query是使用*来查询的,可能獲得超過列出的這3個欄位,也僅僅會返回這3個欄位的值。

4. Join tables & 只傳回特定欄位值
Query query = session.createSQLQuery(
   "SELECT ua.f_service FROM user_account ua INNER JOIN service_account sa ON ua.f_service=sa.id
    WHERE sa.account=:serviceAccount AND ua.account=:account AND ua.user_email=:emailAddress ")
   
   .addScalar("f_service",StandardBasicTypes.INTEGER) 
   
   .setParameter("serviceAccount", serviceAccount)
   .setParameter("account", account)
   .setParameter("emailAddress", emailAddress);

resultList = query.list();

//get serviceId (createSQLQuery return Object[], but we only select f_service so only return an Object)

if (resultList.size() > 0) {
    Object aResult = resultList.get(0); //因為只有一個欄位值,所以傳回的並不是陣列,只是一個object
    serviceId = Integer.valueOf(String.valueOf(aResult));
}
下列語法也通用
Query query = session.createSQLQuery(
   "SELECT ua.f_service FROM user_account ua, service_account sa 
    WHERE ua.f_service=sa.id and sa.account=:serviceAccount AND ua.account=:account AND ua.user_email=:emailAddress ")
要是有『多個查詢值 select a,b,c......』會返回object[],使用下列方法接取
Object[] aResult = (Object[]) resultList.get(0);

5.透過addEntity、addScalar做join
http://blog.maxkit.com.tw/2014/03/hibernate-addentity-addscalar.html

2016年12月15日 星期四

Hibernate HQL - DML、DQL、JOIN 範例

HQL
-Select 
1.利用 ? 設定 sql 中的參數,搭配 query.setParameter("第幾個問號",變數);
Session session = BackendHibernateUtil.getSession();
List resultList = new LinkedList<>();
try {
     Query query = session.createQuery("FROM CtrlSourceAreaEntity WHERE source_type = ?");
     query.setParameter(0,sourceType);
     resultList = query.list();
} catch (HibernateException e) {
     log.error("XMLParserDAO @querySourceAreaId Fail:", e);
} finally {
     session.close();
}
return resultList;
2.利用 :Name 設定參數
"FROM CtrlSourceAreaEntity WHERE source_type = :sourceType"
 query.setParameter("sourceType",sourceType);

3.SQL Query In 設定參數
Query query = session.createQuery("FROM ScheduleDownloadEntity WHERE status in (:statusNames)  ORDER BY create_time ");
query.setParameterList("statusNames", statusList);
resultList = query.list();

-Update
1.executeUpdate()是執行DML的意思
 Query query = session.createQuery("UPDATE UserAccountEntity SET password = ? where f_service = ? AND account = ? AND user_email = ?");
 query.setParameter(0, userPasswordMD5);
 query.setParameter(1, serviceId);
 query.setParameter(2, account);
 query.setParameter(3, emailAddress);
 query.executeUpdate(); //這句是commit的意思

-Delete
1.executeUpdate() 是執行DML的意思

2.executeUpdate() 會傳回 int 影響的資料筆數
Query query = session.createQuery("DELETE EdititemEntity WHERE kind = ? AND post_time BETWEEN  ? AND ? ");
query.setParameter(0, taskNumber);
query.setParameter(1, startDate);
query.setParameter(2, endDate);
int resultCount = query.executeUpdate(); //可以取得DML影響的資料筆數

-Insert
1.將傳進來的 entity 實體 透過 session.save() 的方式把資料存進DB
public void insertData(EdititemEntity edititemEntity) {
Session session = Opv_lyHibernateUtil.getSession(); //Hibernate Session Connect
Transaction tx = session.beginTransaction(); //一組交易
try {
     session.save(edititemEntity); //將傳進來的Entity存進DB(透過Hibernate專屬方法)
     tx.commit(); //交易確認
} catch (HibernateException e) {
     tx.rollback(); //交易取消
     log.error("CategoryDAO @insertData Fail,newsId={},error={}", edititemEntity.getId(), e);
} finally {
     session.close();
}
}

HQL-Join

參考:
http://openhome.cc/Gossip/HibernateGossip/ManyToOne.html

多對一:
一個簡單的實體與實體間之關係為『多對一』的關係,例如『使用者』與『房間』的關係就是多對一的關係,多個使用者使用同一房間。

範例目標:

A:每個 user 有特定的 serviceId(f_service) ,多個user會對上同一個serviceId,希望透過HQL的方式,取得user時,順便取得service_account




1.實體設定(UserAccountEntity)

-在多對一的情況下,『多』的實體才需要特別設定,『一』的部份不用調整,因此我們只調整UserAccount
-UserAccountEntity.class
UserAccountEntity類別中有一serviceAccountEntity屬性,將參考至serviceAccountEntity實例,多個User實例可共同參考一個service實例











2.設定檔(UserAccountEntity.hbm.xml)
- class="絕對路徑""
- column="f_service" → userAccount的f_service(FK)會去參考到serviceAccount的id(PK),兩張table才會連結在一起
- cascade表示主控方(User)進行save-pdate、delete等 相關操作時,被控 方(Room)是否也一併進行相關操作,簡單的說,也就是您儲存或更新User實例時,被參考到的Room實例是否一併對資料庫發生儲存或操作,設定為 all,表示主控方任何操作,被控方也進行對應操作。

-把原先的fService先註解掉



-設定mana-to-one的參數















3.查詢結果
- 重要:INNER JOIN 是 userAccount實體中的serviceAccount屬性




- 結果
每個傳回的結果都帶有UserAccountEntity & ServiceAccountEntity