星期日, 8月 31, 2014

[AngularJS] NVD3基於D3繪圖的directive module


An AngularJS directive for NVD3 re-usable charting library (based on D3).
Easily customize your charts via JSON API.

NVD3讓你可以透過directive來實現D3的繪圖效果: D,使用Angular需要圖表呈現可以考慮



星期一, 8月 25, 2014

[WordPress] 改wordpress的相關手法筆記

本篇記錄一下簡單幫朋友建置wp的心得

修改siteurl

在資料表wp_options裡面有siteurl的欄位,修改後就能變更網站的固定網址


修改主標題選單

header.php的位置,每次升級themes前請小心header.php被更新後還原

content/themes/<你下載的佈景主題目錄>/header.php

判斷使用者有沒有登入的function


WooCommerce修改側欄選單的項目

外觀->小工具

從可用小工具拖拉WooCommerce到Sidebar即可

WooCommerce修改商品頁先顯示分類


WooCommerce->設定->Tab商品->Shop Page Display->改為顯示子類別



[AngularJS] ngprogress-lite 網頁讀取進度條

想要實作網頁的載入進度提示可以使用ngprogress-lite這個module

https://github.com/voronianski/ngprogress-lite

[AngularJS] 實作簡單的multipart uplaod

簡單記錄一下ng處理上傳的相關資源
Please note that solutions that use FormData(), such as the ones presented here in other answers, do not work correctly in older IE browsers.

The correct solution should use a backup strategy for that, such as using iFrames. There are already many angular JS modules to perform file uploading:

http://stackoverflow.com/questions/18571001/file-upload-using-angularjs
http://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs
https://egghead.io/lessons/angularjs-file-uploads

星期日, 8月 17, 2014

[Alfresco] 上傳大檔的相關問題筆記


先前處理alfresco上傳的議題
  1. Heap Size issue (Need to increase that) 
  2. JVM memory allocation 
  3. session time out (It will take more time to write the data on created content so need to make sure session timeout does not happens)

[jQuery plugin] 使用同一個驗證規則來驗證多個textobx欄位

今天有個畫面需求,需用驗證多個textbox (也可以動態產生),使用同一個規則。 一般來說jquery validator只會驗證一個元素(假設你有多個name故意一樣,也只有一個會被驗證)

以下這個StackoverFlow討論串有提供另一個解法:

http://stackoverflow.com/questions/15739390/validating-multiple-textbox-having-same-name-with-jquery-validator-validates-onl



星期五, 8月 15, 2014

[AngularJS] 自訂directive控制圖片找不到

如果遇到頁面的圖片載入失敗時,通常會load預設的圖片,避免有叉燒包的情況。
可以自建一個directive來處理此事件

以下是Stackoverflow的解法:
http://stackoverflow.com/questions/16310298/if-a-ngsrc-path-resolves-to-a-404-is-there-a-way-to-fallback-to-a-default


app.directive('errSrc', function() {
  return {
    link: function(scope, element, attrs) {

      scope.$watch(function() {
          return attrs['ngSrc'];
        }, function (value) {
          if (!value) {
            element.attr('src', attrs.errSrc);
          }
      });

      element.bind('error', function() {
        element.attr('src', attrs.errSrc);
      });
    }
  }
})

星期一, 8月 11, 2014

[NetBeans] NetBeans安裝不同的佈景主題

說明如何簡單的更換NetBeans的佈景主題:D
Themes are contained in a .zip archive.
  1. Open the Options window: Tools -> Options (see picture 1)
  2. Press the Import button (see picture 1)
  3. Press the Browse button and select the theme file (a .zip archive).
  4. Tick the checkbox to select all settings (just Fonts & Colors will be fine as well, those are the themes) (see picture 2)
  5. Press OK and accept the confirmation dialog
  6. After restarting, go to Options again and select the theme at Fonts & ColorsProfile (see picture 1)

Options dialog

[Angular] MVC MVVM MVP 說文解字

常見的 MVC MVVM MVP 框架說文解字
取自:
https://plus.google.com/+IgorMinar/posts/DRUAkZmXjNV

Igor Minar

公開分享 - 2012年7月19日


MVC vs MVVM vs MVP. What a controversial topic that many developers can spend hours and hours debating and arguing about.

For several years +AngularJS was closer to MVC (or rather one of its client-side variants), but over time and thanks to many refactorings and api improvements, it'snow closer to MVVM – the $scope object could be considered the ViewModel that is being decorated by a function that we call a Controller.

Being able to categorize a framework and put it into one of the MV* buckets has some advantages. It can help developers get more comfortable with its apis by making it easier to create a mental model that represents the application that is being built with the framework. It can also help to establish terminology that is used by developers.

Having said, I'd rather see developers build kick-ass apps that are well-designed and follow separation of concerns, than see them waste time arguing about MV* nonsense. And for this reason, I hereby declare AngularJS to be MVW framework - Model-View-Whatever. Where Whatever stands for "whatever works for you".

Angular gives you a lot of flexibility to nicely separate presentation logic from business logic and presentation state. Please use it fuel your productivity and application maintainability rather than heated discussions about things that at the end of the day don't matter that much.




其他討論串:

星期五, 8月 08, 2014

[AngularJS] angular 執行順序

這篇文章回應了angular app執行順序:D 附執行範例。

http://stackoverflow.com/questions/20663076/angularjs-app-run-documentation

Here's the calling order:
  1. app.config()
  2. app.run()
  3. directive's compile functions (if they are found in the dom)
  4. app.controller()
  5. directive's link functions (again if found)
Here's a simple demo where you can watch each execute (and experiment if you'd like).
Run blocks - get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time.
Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the service have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.
One place you see run blocks used is for authentication
<div ng-app="myApp" ng-controller="myCtrl">
    <div test1 test2> </div>
</div>
var myApp = angular.module('myApp', []);
myApp.factory('aProvider', function() {
   console.log("factory");
});
 
myApp.directive("test1", function() {
    console.log("directive setup");
    return {
        compile: function() {console.log("directive compile");}
    }
});
 
myApp.directive("test2", function() {
    return {
        link: function() {console.log("directive link");}
    }
});
 
myApp.run(function() {
    console.log("app run");
});
 
myApp.config( function() {
    console.log("app config");
});
 
myApp.controller('myCtrl', function($scope) {
    console.log("app controller");
});

星期三, 7月 30, 2014

[Java] iterate map的範例集

今天為了某個需求用了MultivaluedMap,怎麼iterate找到了以下的參考範例。
請服用

http://www.sergiy.ca/how-to-iterate-over-a-map-in-java

[Alfresco] impersonate 登入用戶

alfresco提供以下方法讓你可以模仿別的用戶登入的授權。


//get current user
  String currentUser = AuthenticationUtil.getFullyAuthenticatedUser();
  String fakeUser = "IAMBIGD";
  LOGGER.debug("currentUser:" + currentUser);
  if (currentUser == null || !currentUser.equals(fakeUser)) {
            // AuthenticationUtil.setCurrentUser(username);
   //set impersonate 
   AuthenticationUtil.setFullyAuthenticatedUser(fakeUser);
  }

星期二, 7月 22, 2014

[AngularJS] 如何使用form validation驗證input=file

原生的ng並不支援file element的validation,可透過自已新增directive來達到這個功能。

directive

app.directive('validFile',function(){
  return {
    require:'ngModel',
    link:function(scope,el,attrs,ngModel){
      //change event is fired when file is selected
      el.bind('change',function(){
        scope.$apply(function(){
          ngModel.$setViewValue(el.val());
          ngModel.$render();
        });
      });
    }
  }
});

HTML


Input is valid: {{myForm.userUpload.$valid}} Selected file: {{filename}}

[AngularJS] 初學者的angular常用語法筆記

最近重回NG的懷抱,
從邊做專案的過程中,
記錄一些常用的手法。避免會忘記XD

ng-class

//設定某個物件被選擇
 ng-class="{true: 'table-row-selected', false: ''}[product.selected]"

Filter

//取得被選擇的使用者數量
  $scope.getSelectedUsers = function() {
   var selectedObjs = $filter("filter")($scope.userList, {
    selected: true
   })
   return selectedObjs;
  };

陣列反轉

//html 
ng-repeat="folder in parentFolders.slice().reverse()


改變url上面的參數

$location.path('/login');

轉頁

$window.open('http://www.yahoo.com.tw');

如果從已知的array移除指定的item

$scope.userList.splice($index, 1);//移除使用者清單內的某一用戶

事件處理$broadcast, $emit, $on


$broadcast:
發送事件的方法,向下分派事件到所有的子scope範圍。此外也可以由$rootScope發送事件,但要慎用。

$emit:
發送事件的方法,向上分派事件到scope階層範圍。

$on 接受事件的方法,發送端可帶入參數至接收端


將$http request加入common的header

由於REST API很流行,大家都會定義呼叫時要帶入application/json,做法如下。
app.run(['$http', function($http) {

// The $http service will automatically add certain HTTP headers to all requests. These defaults can be fully configured by accessing the $httpProvider.defaults.headers configuration object, which currently contains this default configuration:

// $httpProvider.defaults.headers.common (headers that are common for all requests):
// Accept: application/json, text/plain, * / *
// $httpProvider.defaults.headers.post: (header defaults for POST requests)
// Content-Type: application/json
// $httpProvider.defaults.headers.put (header defaults for PUT requests)
// Content-Type: application/json


 $http.defaults.headers.common['Content-Type'] = 'application/json';
}])


$http GET content-type header無法正確送出的解決方法

[AngularJS] $http無法送出 content-type header

如何使用$watch監控JSON 物件

Call $watch with true as the third argument:
 
$scope.$watch('form', function(newVal, oldVal){
    console.log('changed');
}, true);

By default when comparing two complex objects in JavaScript, they will be checked for "reference" equality, which asks if the two objects refer to the same thing, rather than "value" equality, which checks if the values of all the properties of those objects are equal. Per the Angular documentation, the third parameter is for objectEquality: When objectEquality == true, inequality of the watchExpression is determined according to the angular.equals function. To save the value of the object for later comparison, the angular.copy function is used. This therefore means that watching complex objects will have adverse memory and performance implications.

星期日, 7月 20, 2014

[AngularJS] 使用angular ui-bootstrap 發生tooltip 404

今天開另一個專案載入UI-bootstrap使用tooltip時,發生找不到相關的樣版 *.tpls.html 可以透過$templateCache.removeAll();清除後就正常, 之後再把這個註解就沒問題了。
 app.run(['$templateCache',function($templateCache){
  $templateCache.removeAll();
 }]);

星期四, 7月 17, 2014

[Sublime Text] 寫網站的神級編輯器 筆記



剛好趁換新的Mac pro記錄一下安裝Sublime的過程,
目前已用了一年多了,細節大家看網路應該就一堆介紹啦,
所以不再多對它介紹了XD

使用版本:

Sublime Text 3

安裝第一個pluging "Page Control"


View->Show Console

將以下的install code貼到Console

import urllib.request,os,hashlib; h = '7183a2d3e96f11eeadd761d777e62404' + 'e330c659d4bb41d3bdf022e94cab3cd0'; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); urllib.request.install_opener( urllib.request.build_opener( urllib.request.ProxyHandler()) ); by = urllib.request.urlopen( 'http://sublime.wbond.net/' + pf.replace(' ', '%20')).read(); dh = hashlib.sha256(by).hexdigest(); print('Error validating download (got %s instead of %s), please try manual install' % (dh, h)) if dh != h else open(os.path.join( ipp, pf), 'wb' ).write(by)

星期三, 7月 16, 2014

[Java] 簡單的User authorization機制

常用到的使用者是否有正確的權限存取當前頁面的機制,Java可以透過Filter來達到。
可依個人需求再強化嚕。

This can be handled in a Filter and there are great explanation and example in StackOverflow Servlet-Filter wiki.
Adapting the code there for your problem (note the addition and usage of the needsAuthenticationmethod):
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig config)
        throws ServletException {
        // If you have any  in web.xml, then you could get them
        // here by config.getInitParameter("name") and assign it as field.
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession(false);

        String requestPath = httpServletRequest.getRequestURI();

        if (needsAuthentication(requestPath) ||
            session == null ||
            session.getAttribute("user") == null) { // change "user" for the session attribute you have defined

            response.sendRedirect(request.getContextPath() + "/login"); // No logged-in user found, so redirect to login page.
        } else {
            chain.doFilter(req, res); // Logged-in user found, so just continue request.
        }
    }

    @Override
    public void destroy() {
        // If you have assigned any expensive resources as field of
        // this Filter class, then you could clean/close them here.
    }

    //basic validation of pages that do not require authentication
    private boolean needsAuthentication(String url) {
        String[] validNonAuthenticationUrls =
            { "Login.jsp", "Register.jsp" };
        for(String validUrl : validNonAuthenticationUrls) {
            if (url.endsWith(validUrl)) {
                return false;
            }
        }
        return true;
    }
}
I would recommend to move all the pages that require authentication inside a folder like app and then change the web filter to
@WebFilter("/app/*")
In this way, you can remove the needsAuthentication method from the filter.

其他你感興趣的文章

Related Posts with Thumbnails