Index

 - Primary키는 자동으로 인덱스로 생성된다.

 - 나머지 index는 생성해야 하는데,
     index는  Unique해도 되고 Unique하지 않아도 된다.

 

 

오라클 메모리 :

   PGA - 정령공간, 세션정보, 커서정보, 변수저장

   SGA - 공유풀, 데이터버퍼케쉬, ReDo Log버퍼

     -SGA조절 파라미터  : 10g부터는 자동조절 기능 제공.
            shared_pool_size        

db_cache_size
 log_buffer

 

Join ==========================Join===============

RDBMS에 일반적으로 많이 사용하는 NL(Nested Loop)조인 외에,

오라클에는 Hash Join이 존재한다.

 

((조인의 종류))

1. Sort Merge 조인  (양쪽을 sort해서 join한다..)

   - 잘 안쓰는 것 같은데.. 잘 못봤음

     (주로 Ordered 테이블에서 유리하지 않을까 예상 됨)

 

2. NL(Nested Loop)조인

  - 일반적인 조인.

   이너조인이 일반적이며, 아우터조인도 있음

 

3. 오라클 Hash Join

- (다른 RDMBS에도 있는지 좀 찾아봐야 하지만..)
  A. 작은 테이블(Build Input)을 읽어 Hash Area에 해시 테이블 생성한다.
    (해시 함수에서 리턴 받은 버킷 주소로 찾아가 해시 체인에 엔트리를 연결)
  B. 큰테이블 집합(Probe Input)을 읽어 해시 테이블을 탐색하면서 조인하는 방식이다.
    (해시 함수에서 리턴 받은 버킷 주소로 찾아가 해시 체인을 스캔하면서 데이터를 찾는다)

 

   기준테이블(작은 테이블:build Input)이 충분히 작은 경우에 Hash Join이 적합하다.


 

Posted by yongary
,

브라우저가 html5 video tag에서 mp4동영상을 재생할 때,

byte-range request를 이용하게 된다.


MPGE이 기본적으로 188-byte단위로 패킷을 구성하기 때문에 이러한 방식이 가능하다.


animated-GIF 의 경우에는 byte-range 로 스트리밍 받으면서

재생이 될까?  이 부분에 답은 아직 못 찾았지만


android 브라우저에서 충분히 빠른 것으로 봐서,

gif도 byte-range 전송이 되는 것으로 보인다.


==> 이 부분 확인을 위해서 tcpdump로 잡아보니,

1448 byte 짜리 패킷이 무수히 많이 서버->Client로 전송된다.


====tcpdump ==


14:42:32.699931 IP 192.168.0.67.http-alt > 192.168.0.101.42947: Flags [.], seq 7422086:7423534, ack 1030, win 244, options [nop,nop,TS val 5415908 ecr 6751675], length 1448

14:42:32.699940 IP 192.168.0.67.http-alt > 192.168.0.101.42947: Flags [.], seq 7423534:7424982, ack 1030, win 244, options [nop,nop,TS val 5415908 ecr 6751675], length 1448

14:42:32.699946 IP 192.168.0.67.http-alt > 192.168.0.101.42947: Flags [.], seq 7424982:7426430, ack 1030, win 244, options [nop,nop,TS val 5415908 ecr 6751675], length 1448



Posted by yongary
,

chrome - mobile mode

IT 2015. 9. 10. 08:44

In chrome - F12 is Debug mode



On left-top corner,  find and click 

toggle device mode icon off : toggle Device mode 



then you can resize your screen .  (default is small phone)

Initial start for device mode

Posted by yongary
,

android for Work

Mobile 2015. 9. 1. 18:53

 

android 4.0이후부터 지원되는 Android for Work는

개인모드와 기업모드 데이타를 완전히 분리하여 앱도 설치하고 모드가 관리된다.

(심지어는 앱스토어도 틀리다)

 

단 통화와 SMS는 개인모드의 앱을 이용하게 된다.

 

 

(Ref-Site:  내용)

Android for Work란 무엇인가요?

Android for Work는 기업용 모빌리티 운영(EMM) 플랫폼으로, 회사에서 이 플랫품을 통해 직원에게 안전하고 생산적이며 풍부한 모바일 환경을 제공할 수 있습니다. Android for Work에 솔루션을 구축하면 다음과 같은 이점이 있습니다.

  • 보안 및 데이터 분리—Android for Work가 배포된 기기는 하드웨어를 기반으로 하는 암호화 및 관리자 관리 정책을 통해 멀웨어를 차단하여 비즈니스 데이터를 안전하게 보호하고 개인정보를 비공개로 유지할 수 있습니다. 
  • 직원 소유 기기 및 회사용으로 프로비저닝된 기기 모두 지원—Android for Work 사용자는 하나의 Android 기기를 업무용 및 개인용으로 안전하게 사용할 수 있으며, 회사는 소유한 기기를 프로비저닝하거나 직원 소유 기기에 업무용 프로필을 구성할 수 있습니다. 
  • 원격 관리—관리자는 원격으로 모든 업무 관련 정책, 애플리케이션, 데이터를 제어하고 기기 소유자의 개인 데이터는 그대로 둔 채 기기를 초기화할 수 있습니다. 
  • 원활한 사용자 환경—Android for Work는 모든 기기에 일관된 환경을 제공하여 직관적이고 손쉬운 방법으로 업무용 앱과 개인용 앱 간에 전환할 수 있습니다. 비즈니스 앱은 런처 및 최근 앱 목록에 개인용 앱과 함께 표시되지만 비즈니스 앱 아이콘에 배지가 있기 때문에 손쉽게 구분이 가능합니다. 
  • 간단한 애플리케이션 배포—관리자는 Google Play에서 비즈니스 앱을 찾아 액세스를 허용하고 Android for Work 기기에 배포할 수 있습니다. 또한 Google Play를 사용하여 내부 애플리케이션 및 리소스를 배포할 수도 있습니다. Play for Work 도움말 센터를 참조하세요.
  • Divide Productivity Suite—Google Apps for Work를 사용하지 않는 사용자는 Android for Work용으로 특별히 설계된 안전한 생산성 앱 제품군을 대신 사용할 수 있습니다. 이 제품군에는 비즈니스 이메일, 캘린더, 주소록, 할일 목록, 다운로드 관리가 포함되어 있습니다.

Google은 Google Apps for Work 생산성 제품군에서 즉시 사용 가능한 Android for Work 솔루션을 제공합니다. 이 솔루션을 사용하면 Google Apps for Work 관리자가 관리 콘솔을 통해 EMM 기능에 액세스할 수 있으므로 현재의 기기 관리 기능을 확장할 수 있습니다.

또한 Google은 타사 EMM 공급자가 자체 Android for Work 솔루션을 구축하는 데 사용할 수 있는 인프라를 제공합니다. EMM 공급자는 휴대기기 관리(MDM), 모바일 애플리케이션 관리, 모바일 비용 관리 등의 고급 IT 솔루션을 제공합니다. Google Apps for Work를 사용하지 않는 회사는 Android for Work 배포 관리 도구를 제공하는 타사 EMM 공급자를 선택해야 합니다.

 

Posted by yongary
,

HTML5 Video tag + CSS

FRONT-END 2015. 8. 31. 09:23

<html>

<head>
<meta charset="utf-8" />
</head>

<head>

<script type="text/javascript">  //iphone&LGphone do not load automatically.
window.onload = function(){
  document.getElementById('video').load();
}
</script>

<style type="text/css">
#video{
  width : auto;
  margin : 0% 3%;  //상하 0%, 좌우 3%
  min-width: 94%;
  max-height: 100%;
  border : 3px solid white;
  border-radius : 10px;
}

#texts{
  font-size : 36px;
  margin : 5%;
}
</style>

</head>

 

<body>
<br/>

<video id="video" controls>   // Ref-Site:
  <source src="mpp_vod.mp4" type="video/mp4">
  Browser does not support HTML5 mp4.
</video>


<br/>
<br/>

<p id="texts">
Test용 동영상입니다.<br/><br/>
</p>

</body>
</html>

Posted by yongary
,

10 mistakes + Alpha

java core 2015. 8. 28. 15:27

Ref-Site:

 

1. 

array를 ArrayList로 전환시:

 

ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(arr));

 

(설명)

Collection인 java.util.ArrayList 는

java.util.Arrays.ArrayList와 다름.List list = Arrays.asList(anArray)  하면  static class인

   Arrays.ArrayList가 return됨: 쓰지 말것

 

 

2. array안에 value존재하는지 check시

Arrays.asList(arr).contains(targetValue);

 

3. List에서 element하나 삭제시.

Size()가 변하는 loop안이라면 Iterator를 사용하여 삭제하는 게 안전.

아니면 뒤에서부터 앞으로 Loop돌면서 삭제. (테스트 필요)

 

Iterator<String> iter = list.iterator();
while (iter.hasNext()) {  
     String s = iter.next(); //꼭 next먼저 호출.
     if (s.equals("a"))  iter.remove()//원래 remove는 가장최근 return()한 걸 삭제하는 이상한 함수임.
}

 

ListIterator의 경우에는 iter.set() 함수도 매우 쓸만하다. //이 역시, 가장 장최근 return()한 걸 치환.

 

4. 보통은 HashMap을 쓰자.  HashTable도 동일하지만 이건 synchronized가 걸려있어 조금 늦음.

Ref-Site: top 10 Q about Map

 

5. Default 생성자는 생성자가 없을경우에만 자동으로 compiler가 넣어 줌.

   => default생성자 없는 class를 상속받을 경우 super()가 필요한데 없으므로 컴파일 에러가 남.

 

6. Sort   Ref-Site:

   => Collections.sort( list, Comparator  ),  Arrays.sort( array, Comparator  ) 사용

 

        // 역순으로 정렬하기 위한 Comparator 객체 생성
        Comparator<String> reverseComparator = new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                return s2.compareTo(s1);
            }
        };
        
        /**참고 */
        따라서, Comparator 클래스를 구현할 때에는 compare() 메서드를 반드시 구현해야 합니다. compareTo() 메서드는 Comparable 인터페이스에서 정의되어 있는 메서드로, 객체를 자신과 비교하여 정렬 순서를 결정하는 메서드입니다. Comparable 인터페이스를 구현하면서 compareTo() 메서드를 구현해야 하며, Comparator 클래스를 구현할 때에는 compare() 메서드를 구현해야 합니다.

 

 

 

   => Set이나 Map의 경우에는 TreeSet, TreeMap 생성 후 add하면 자동 정렬 : complexity of O(logN)

REF-Site:

 - 필요시: 생성시에 Comparator 공급.

 - Sync필요시:  SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));

 

 

 

 

Posted by yongary
,

CentOS, jdk+tomcat 설치

Linux 2015. 8. 25. 13:36

 

 

1) JDK설치  Ref-Site

root로 로그인해서

#rpm -ivh jdk1.7_xx_xx.rpm  혹은

#rpm -ivh java-1.6.0-openjdk-1.6.0.0-1.45.1.11.1.el6.x86_64   (openJDK가 더 안전)

 

 

2) tomcat 설치  Ref-Site

 

오타: /lib/jsp-api.jar

Posted by yongary
,

JPA방식

Spring 2015. 8. 19. 23:35

REF-SITE 

 

Entity 어노테이션이 RDB테이블이 된다.


@Entity
public class Forum {
    @Id private Long id;
    @Column private String name;
    @Column private String description;
    @Column private Date createdAt;
 
// Omit Getters/Setters....
}


Posted by yongary
,

Frontend hacking

IT 2015. 8. 12. 23:56

SQL Injection

XSS (Cross Site Scripting) - javascirpt를 입력.  


==> 해결책: escapeHtml, escapeScirpt 등을 사용하거나, MVC framework을 사용. angular.js도 어느정도 막을 수 있을 듯.



그외,  

Command Injection

XXE(XML External Entity) 

등의 해킹법도 있음.

Posted by yongary
,

Collections

java core 2015. 8. 12. 17:53

(Sometiems ArrayList is better when no synchronize, Sometimes Vector is better because of Size doubling )

 

ArrayList : Resizable Array - fast because of index.  Add/Delete is Slow for data Copy. ==> 50% increase its array size

Vector : Similar to ArryList..  a little heavy because of synchronize processing. ==> doubles its array size

 

LinkedList: Fast for ADD/Delete.  But No Index so sequential search is slow.

 

HashSet, SortedSet,

HashMap

DelayQueue,  - - - |> BlockingQueue

Stack

 

several I/F like:

  Queue, - 보통  new LinkedList<T>();

  Deque, - 상동.    

  BlockingQueue : (waiting in some cases)

put은 queue가 꽉 차 있을 경우, take

는 queue가 비어있을 경우가 블로킹 조건이다. 

  TransferQueue

 

 

<class> 

  ConcurrentXX  Collections : thread-Safe

-ConcurrentHashMap : synchronize detail이 HashTable과 약간 다름.

   

  - SynchronousQueue: 초기 size가 0이고.. 다른Thread에서 빼려고 할때만 삽입이 가능한 놈이므로 peek도 안됨..

      

 

TreeMap -  red-black Tree 기반의 sorted NavigableMap

 

TreeSet   -  TreeMap기반.

 

PriorityQueue - Heap자료구조 기반..

PriorityQueue 클래스는 기본적으로 작은 값이 우선순위가 높은 것으로 취급합니다. 따라서, 1에서 100까지의 숫자를 PriorityQueue에 추가하면, 1이 가장 높은 우선순위를 갖게 되고, 100이 가장 낮은 우선순위를 갖게 됩니다. 따라서 poll() 메서드를 호출하면, 가장 높은 우선순위를 갖는 1이 먼저 반환됩니다.  => 체육복 코딩테스트에 사용 됨.

 

 

Posted by yongary
,

ThreadLocal은 jdk1.2부터 있었다고 하는데, 그 동안 이런게 있는지 잘 몰랐다.

 

용도는 2가지인데

1. Thread별로 싱글턴 같은 global(local)변수를 생성/관리되므로, Thread별로 분리된 변수를 사용가능.

=> REF : per-thread Singleton.

 
    ==> synchronized없이도 Lock이 자동으로 방지 될 걸로 예상 됨..(이건 좀 토론이 필요함)

 

 

1.1. 하나의 Thread안에서 여러 class가 공용메모리 처럼 사용가능. (왜냐하면 Thread안에서 global이니깐)

 

관련사이트1 , 관련사이트2

 

 

 

 File f = File.createTempFile("aaa",".tmp")  도 유사한 성격으로 동시 접근을 피할 수 있다.

 write다한 후에 보통 f.setReadOnly();

==> 똑같은 파일명으로 만들어도 알아서 숫자가 붙는 방식임. 따라서 .deleteOnExit() 설정을 꼭 해주는 게 좋다.

Posted by yongary
,

EL과 JSTL

Spring 2015. 8. 7. 14:48

참고사이트:  http://egloos.zum.com/slog2/v/3581446   https://docs.oracle.com/javaee/6/tutorial/doc/bnahq.html 

 

 

EL (expression language) -> JSP2부터 기본 지원

JSTL (JavaServer Pages Standard Tag Library ) -> c tag를 가장 많이 사용.

 

앞부분에 taglib 디렉티브로 사용함을 표시한다.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  // c:tag사용.

 

<EL>

${param.name} => request.getParameter("name");
${member} => request.getAttribute("member");

 

${member.name} => Member m = (Member)request.getAttribute("member");
m.getName();
${list["0"]} => List list = (List)request.getAttribute("list");
list.get(0);

 <JSTL>

<c:forEach items="${list}" var="listItem" >

<td>${listItem.title}</td>

</c:forEach> 

 

Posted by yongary
,

javascript관련 질문들:

 

javascript에는 function statement와 function expression이 존재한다.

비슷하지만 약간의 차이가 난다.

 

<Function>

  - function expression: var x = function fname(){}   (fname is optional) 

 => 이걸로 싱글턴 만들수 있다. class만들고 싱클턴 만드는 거 보다 less expensive.

  - function statement:   function fname(){}

 

<기타>

  - javascript 에 {blocks}  는  scope을 가지지 않는다. 

 

<슈도 파라미터 2가지>

  - arguments : parameter와 밀접한 관계가 있으므로, read-only로 사용하는 게 좋다.

       일종의 array로 최근(ES5)에 .reduce 등이 소개되었다. 
         arguments.length

         arguments[i]

 

  - this : function 내에서 멤버변수를위한 public 키워드처럼 동작하기도 하며, (이건 아래2번)

1. reference to the object of invocation

2. allows to know the concerned Object

3. allows single function object to service many functions ?

4. key to prototype inheritance

 

Function.prototype.bind를 통해 this를 강제로 할당 할 수 있다.

 


<prototype이란>

All JavaScript objects inherit the properties and methods from their prototype.

Allows you to add properties and methods to an object 

we can inherit using prototype. and by overriding construct(). => prototype is copied.




<function관련 Form종류들>

  - New폼:      new functionObject() 

  - function폼: functionObject(arg) 이 경우, var that = this; 많이 사용. inner function이 outer를 접근하기 위해서..
                     (왜냐면 자체 this가 있기 때문)

  - method폼:  functionObject(arg).method()

  - apply폼:    apply()  form  ,   유사한것으로 call도 있는데, apply는 (this,array)  call은 (this, a,b,c : each object of array)가 전달된다.

 

 

this 참고사이트:  http://mobicon.tistory.com/189  

유투브:   15분-this,  30분-closure  (English)








Posted by yongary
,

hoisting, strict mode

javascript 2015. 8. 4. 19:19

javascript에서 hoisting이란 

 변수나 함수를 var 로 선언하기 전에도 사용할 수 있다는 의미이다.  참고사이트

(global함수의 경우는 어디서나 사용할 수 있으므로 hoisting이 아니다.)


참고사이트:영어

In JavaScript,  a variable can be used before it has been declared.


hoisting이 왜 중요한가?

==> 크드가 잘 돌아가더라도 hoisting이 동작한 것일 수 있기 때문에, hoisting을 알아두는 것이 각종버그를 방지할 수 있다.


strict mode : "use strict";  를 사용하면  hoisting을 방지할 수 있다. (꼭 선언 후 사용하는 모드)  w3schools_js



Posted by yongary
,

some JAVA keywords

java core 2015. 8. 2. 22:49

finalize(): GC calls when Instance is garbage collected. which has no reference.    참고사이트:


hashCode();  when making equals method of Object. we must consider this method().


final: (method or class) will not be inheritted.





Posted by yongary
,

(팁: 크롬으로 javascript 개발시 F12 키가 debug모드이다 :   메뉴엔 Ctrl-Shft-J)



JavaScript의 객체 상속도를 잘 나타낸 그림은 다음과 같다.  참고사이트:devbox


DOM구조에서 거의 모든 object들이 Node를 상속받아서 만들어 졌다고 보면된다.

그런데 개발시에는 node API를 쓰면 필요없는 tag등이 한번씩 나오는 경우가 있어서

위한 children() 함수를 더 많이 쓰게 된다. 


<많이 쓰는 코드>

    document.getElementById('aa').children  -> HTMLCollections 를 리턴함.

    

    (document.getElementByxxx부터 해서,  Element를 특히 많이 씀)

    document.getElementById('aa').children.item(i)  --> Element 리턴.

jquery의 경우는 : $('#aa')[0].childNodes[0].nodeValue;

  $($('h1').contents().get(0)).text(); //.get(0)=[0]

  $('h1').contents().each(function() {
          
if(this.nodeType == 3) { }


    removeChild(e) 

    appendChild(e)

    document.createElement('div')





Posted by yongary
,

UML & GoF pattern

IT 2015. 7. 29. 22:53

<UML>  Reference Site:


 Inheritance:       ㅡㅡㅡㅡㅡD        


 Interface:          - - - - - - D


 association(has):   A  ㅡㅡㅡㅡㅡ>     B               class A { member B}   

                                  Leg  <.>----->  필수.

           Flea <>------>



 dependency:             A  - - - - - >     B                 class A uses B temporary.




<Gof Pattern> Reference SIte

Creational Pattern:  Singleton, (Abstract)Factory, Builder, Prototype

Structral Pattern: Adapter, Decorator, Bridge, Proxy

Behavior Pattern: Command, Iterator, Visitor, Observer, Chain of Responsibility



Posted by yongary
,

OSGi for Java

java core 2015. 7. 29. 18:48

OSGI (Open Services Gateway Initiative)   REF-SITE:


- Originally targeted embedded devcies & home service GWs.

- Bundle based Fluent Life-Cycle framework.  (Bundle=jar+alpha)

   (life-cycle Layer can dynamically install/remove/start/stop bundles)

- JavaObject based SOA  


ex)  Eclipse Equinox PDE (Plug-in Development Environment)

     Apache Felix.  Reference-Site


Posted by yongary
,

참고사이트: Javascript 재입문


parseInt( "11", 2) = 3

NaN : Not a number    

Infinity : 무한대   1/0 = Infinity


1==true : true   (type이 오토케스팅 됨)

1===true: false  (===: type 강제변환 방지: type까지 비교함. )

 

var names;   //names == undefined임.

  이 때, !names == !undefined  //둘다 true임. 

 

setTimeout(func, 100) //0.1초 후 실행.

setInterval(func,100)  //0.1초씩 반복


for (var i in a)  //a[i]사용가능,   var a=["dog","cat","chicken"]

 

<주의>

var z = 0.1 + 0.2;  //z=0.300....4   모든 수가 64bit float이라 계산에 오류발생 가능.

javascript는 head나 body에 모두 사용가능하다.

==의 반대말은 !=  ( <>아님)

javascript는 당근 case Sensitive하다.

 

 

<JS object>

var person = {
    firstName: "John",
    lastName : "Doe",
    id       : 5566,
    fullName : function() {
       return this.firstName + " " + this.lastName;
    }
};  ==> prototype기반 function보단 사용용도가 약하지만, JSON은 큰 장점.

 

<array>

[1,2].concat([2,3]);  //Array.concat => [1,2,2,3]  혹은 arrA.concat(arrA)

[2,3,4].join()   // toString.. "2,3,4"

 

 

<기타>

navigator.userAgent;

navigator.appName ;  브라우저 name

window.btoa("abc") //=> base64 encoding.

 

<< My experience >>

new window['Pattern'+ i]()           //= new Pattern1 ~ new Pattern6

apply(obj, [a,b])  or   call(obj, a,b)   // 0bj->this, (a,b)   this chapter 참조.  

Posted by yongary
,





Curran의 20번 exam:

- $http 서비스를 이용해 json을 웹으로 가져오기.

<html ng-app="countryApp">

<head>

<meta charset="utf-8">
<title>Angular.js Example</title>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>
<script>
var countryApp = angular.module('countryApp', []);
countryApp.controller('CountryCtrl', function ($scope, $http){

$http.get('countries.json').success(function(data) {

$scope.countries = data;
});
});
</script>
</head>
<body ng-controller="CountryCtrl">
<table>
<tr>
<th>Country</th>
<th>Population</th>
</tr>
<tr ng-repeat="country in countries">
<td>{{country.name}}</td>
<td>{{country.population}}</td>
</tr>
</table>
</body>
</html>


Posted by yongary
,

전통적인 consumer/supplier 예제를 간단히 변형해서

2개의 은행에서 각자 고객 수자를 관리하다가

전체 고객의 합을 구하는 형태를 문제가 있게 OLD한 방법으로 일부러 작성해보면 다음과 같다.

 

 

///////////////////////////////////////////////////////////////

class Bank {
var numKid:Int = 0
var numAdult:Int = 0
var numAged:Int = 0

def addNum (k:Int,a:Int,g:Int) = {
numKid += k
numAdult += a
numAged += g
Main.totalKid += numKid //no need on FP
Main.totalAdult += numAdult
Main.totalAged += numAged
}

}

////global FOR: Bank Sum total : OLD ///////////////
var totalAll:Int = 0 //NO NEED on FP
var totalKid:Int = 0
var totalAdult:Int = 0
var totalAged:Int = 0

 

// main
def main(args:Array[String]) = {


//// Bank Sum total :OLD ///////////////
val actorBank1 = actor {
val bank1 = new Bank
while (true) {
bank1.addNum(0, 1, 0)
Thread.sleep(10)
}
}

val actorBank2 = actor {
val bank2 = new Bank
while (true) {
bank2.addNum(2, 2, 1)
Thread.sleep(10)
}
}

//WHEN WANT TO PRINT
while (true) {
//SUM
Main.totalAll = Main.totalKid + Main.totalAdult + Main.totalAged //SUM

//NO MATCH?
if( totalAll != (totalKid+totalAdult+totalAged))
println("total:" + totalAll + ", Kid:" + totalKid + ", Adult:" + totalAdult + ", Aged:" + totalAged)

Thread.sleep(20)
}

 

 

 

이게 돌다보면 totalALL합이 맞지 않는 경우가 자주발생하도록 한 코드인데..

FP 스타일로 바꿔보면 다음과 같다.

 

 

 

================================> FP Style 로 전환

 

 

1. 가능하면 tuple을 이용

2. 전체적인 합 같은 totalAll 같은 변수를 아예 없앤다.

(그 외에 좀 더 sum2Bank같은 함수를 sum리턴안하게 좀 하고 싶은데.. 연구 중.)

 


class Bank {
var numKAG = (0,0,0)

def addNum (k:Int,a:Int,g:Int):Unit = {
numKAG = (numKAG._1 + k, numKAG._2 + a, numKAG._3 + g)
}
}

def sum2Bank (b1:Tuple3[Int,Int,Int], b2:Tuple3[Int,Int,Int] ) = {
val sum = ( b1._1 + b2._1, b1._2 + b2._2, b1._3 + b2._3 )
sum
}

def main(args:Array[String]) = {

//// Bank Sum total :OLD ///////////////
val bank1 = new Bank
val bank2 = new Bank

val actorBank1 = actor {
while (true) {
bank1.addNum(0, 1, 0)
Thread.sleep(10)
}
}

val actorBank2 = actor {
while (true) {
bank2.addNum(2, 2, 1)
Thread.sleep(10)
}
}


//WHEN WANT TO PRINT
while (true) {
//SUM
val sum = sum2Bank(bank1.numKAG, bank2.numKAG)
val totalAll = sum._1 + sum._2 + sum._3

//Always MATCH cause there is no toalALL variable
if( totalAll != (sum._1 + sum._2 + sum._3))
println("total:" + totalAll + ", Kid:" + sum._1)


Thread.sleep(20)
}


}

 

 


 


Posted by yongary
,

scala 문법 요약

scala 2015. 7. 22. 18:22

참고사이트:

 

var (x,y,z) = (1,2,3)    //튜플 선언

(1 to 5).map( 2 * )     // Vector(2,4,6,8,10)임.   2 * _ 에서 마지막에 _은 생략 가능    

import java.util.Date    //java도 import 해서 사용가능

1 :: List(2,3)             // List(1,2,3) 과 동일  연결연산자cons

 

(1 to 5)         // Range(1, 2, 3, 4, 5)

(1 until 6)       // Range(1, 2, 3, 4, 5)

(1 to 10 by 2)  // Range(1, 3, 5, 7, 9)

 

_ > 4             // v => v > 4 와 같은 predicate 임.

 

 

Posted by yongary
,

java 7 nio2 + etc

java core 2015. 7. 20. 10:56

nio2  참고사이트:  copy, move, readAllLines, Files.walkFileTree(Path, FileVisitor<T> ),  WatchService,

 

기타7 문법 참고사이트

 

1. try-with-resource,  

File nFile=new File("abc.txt");
try ( InputStream in = new FileInputStream(nFile) ){



}catch (Exception e){



}

2. String in case, 

 case "abc":

 

 

 

그 외 될 뻔하다가 적용 안된 거.

     A.(multi) catch (|), 

    B. ?(return null when null).

     C.멀티Collection생성자, //ex: new ArrayList {"one", "two", "three"}; => 1.8에서도 안 됨.

Posted by yongary
,

java 8 오픈

java8~ 2015. 7. 20. 10:03

java 5와 java8은 major release이다.

java 5에서  generic, concurrent, annotation, JMX, enum, boxing/unboxing, static import  등의 기능이  update되었다면

 

 

java8에서의 핵심update는 FP 이다. 참고사이트

 

  

 

 

1. <java.uitl.function 에 추가된 함수형 인터페이스>

  • Function <T, R> - T를 입력으로 R을 출력으로 반환
  • Predicate <T> - T를 입력으로 boolean을 출력으로 반환
  • Consumer <T> - T를 입력으로 아무것도 반환하지 않는다
  • Supplier <T> - 입력을 취하지 않고 T를 반환
  • BinaryOperator <T> - 2 개의 T를 입력으로 하나의 T를 출력으로 반환 
    => c++의 unary operator override수준이 아니라서 별로 쓸일 없어 보이지만..
    minBy, maxBy는 사용하면 stream구문 없이 사용할 수 있어서 편할 듯 함.
    REF

 

 

2. <java.util.stream>

 - 배열,리스트,맵 등 Collection을 stream으로 다룰 수 있게 된다.

 

 

그리고

 -interface에 abstract method뿐 아니라 body추가.

 -OOM을 많이 유발하단 PermGen 이 사라짐. 

 - Date변환법이 좀 추가:   LocalDateTime Duration이 쓰기 좋겠네요.  REF-SITE

Posted by yongary
,

마야의 달력 중에 260일이 1년인 Tzolkin 달력이 있다.


1년이 13달이고

1달 20일이라서  13*20 = 260일..

이 20일마다 기운이 다르다고 하는데




 

 

20일별 기운을 정리한 사이트:  

http://mayan-calendar.com/ancient_birthdays.html 

Posted by yongary
,

Functional Programming How?

scala 2015. 7. 18. 11:27

<FP 기법>

1. carry Over  :  tail recursive 처럼 결과값을 계속 넘기는 방식. (carry Over: 그냥 영어임.)  

2. predicate : 함수는 f()로 표현. Boolean을 리턴하는 함수는 predicate 이라고 부름.
       (이것도 scala에선 그냥 영어임. java엔 Predicate존재) 

=> p()를 이용해  함수 input  param들을 필터처럼 거를 수 있음

 

 

<FP기법 예제 - 1.carryOver>


object Main{

  def total(list: List[Int]) = { //기존 sum함수
    var sum = 0
    for (i <- list) { sum += i }
    sum
  }

  def totalFP(list:List[Int]) = { //부분합을 계속 넘기면서 합을 해나가는 방식.  foldLeft함수가 첫번째 param으로 carryOver로 계속 받아 주면서 iterate를 제공.
    list.foldLeft(0) { (carryOver,v) => carryOver + v }
  }

  def main(args:Array[String]) = {
    println(totalFP(List(1,2,3,4,5)))
  }
}

 

 

<FP기법 예제 - 2.Predicate>

def totalFP(list:List[Int] , p:Int => Boolean) = {
list.foldLeft(0) { (carryOver,v) => if (p(v)) carryOver + v else carryOver }
}

def main(args:Array[String]) = {
println(totalFP(List(1,2,3,4,5),{ v => v % 2 == 0 })) //짝수인 2,4 만 적용되서 합이 6 이 나옴.
}

추가적으로 v => v > 4 같은 predicate은 _ > 4 로 표시 가능

 

 

그리고 아래 3가지들이 scala에서 좀 특별하다.

trait -  java의 Interface와 비슷하지만, class특성도 지님.

   <trait특성 >

     - extends 로도 with 로도 사용가능하다. 심지어는 구현body가 존재해도 된다.

     - with의 경우에는 여러가지 trait가 사용가능하며, with A, with B의 경우 B가 먼저 적용된다.

     - override abstract라는 키워드를 사용하여 기존 def를 추상화하여 사용할 수도 있다.

     - Class 가 아니고 인스턴스에도 사용가능 : with Friends

 

xml - xml이 1등급 고객임. "" 필요없음

actor - thread + 큐 : 수천개의 actor를 만들어도 된다


자세한 건 여기클릭: hillarious indian guy

 

 

Posted by yongary
,

특징

angular.js 2015. 7. 10. 10:50

참고사이트:

 

 

1. html tag에 ng-app 표시.

 

<html ng-app>  

 

 

2. script 소스 삽입

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js">
 </script>

 

여기에 있는 콜백이 html이 모두 로드된 후에, 브라우저로부터 호출되면

앵규러는 ng-app 지시어를 찾게 된다. 찾게되면 DOM의 최상위에 부트스트랩을 건다.

 

단계적으로 보면,

A.dependency injection을 위한 인젝터들이 생성되고

B. 인젝터는 root-scope를 생성하고

C. ng-app의 루토요소를 시작점으로 삼아 하위요소들을 컴파일한다.

 

 

 

3. ng 기본 문법 : 참고사이트Curran  (10번 exam)

<html ng-app> <head> <meta charset="utf-8">

<title>Angular.js Example</title>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>
<script>
function NameCtrl($scope){
$scope.firstName = 'John';
$scope.lastName = 'Smith';
}
</script>
</head>
<body ng-controller="NameCtrl">
First name:<input ng-model="firstName" type="text"/>
Last name:<input ng-model="lastName" type="text"/>
Hello {{firstName}} {{lastName}}
</body>
</html>


4. ng-repeat 예제 

<script>

functin phoneListControler($scope)

{

$scope.phones=[

{"name":"Gal5",

  "num":"010-2222-3333"

},

]

}

</script>

<body ng-controller="phonListController">

<div ng-repeat="phone in phones">

   <p >이름: {{phone.name}} </p>

</div>

Posted by yongary
,

Click:초보자안내사이트들

 

<설치방법:install>

1. node-xx.linux-x86.tar.gz 바이너리파일 다운로드   http://nodejs.org/download 

2. 압축풀고 README파일 참조. path와 lib path만 설정하면 될 듯한데.

# ln -s /usr/local/nodejs/v0.x.x/bin/node /usr/local/bin/node

 

 

 

<실행방법>

$> node httpSvr.js


<모듈 설치방법>

$ npm intall -g blabla   (-g 안하려면.. httpSvr.js가 있는 곳에서 실행해야 그 밑에 node_modules 폴더가 생기면서 설치됨)



==httpSvr.js=====

==> express모듈을 사용하면 웹서버가 더 쉬워짐:  참고사이트

var http = require('http');

var server = http.createServer(function (req, res) {
  res.writeHead(200, { 'Content-Type' : 'text/plain' });
  res.end('Hello World');
});

server.listen(8000);



===udpSvr.js===========================================================

var PORT = 33333;

var HOST = '127.0.0.1';


var dgram = require('dgram');

var server = dgram.createSocket('udp4');


server.on('listening', function () {

    var address = server.address();

    console.log('UDP Server listening on ' + address.address + ":" + address.port);

});


server.on('message', function (message, remote) {

    console.log('Svr Log:'+remote.address + ':' + remote.port +' - ' + message);


});


server.bind(PORT, HOST);





==udpClient.js==========================================

var PORT = 33333;

var HOST = '127.0.0.1';


var dgram = require('dgram');

var message = new Buffer('My KungFu is Good!');


var client = dgram.createSocket('udp4');

client.send(message, 0, message.length, PORT, HOST, function(err, bytes) {

    if (err) throw err;

    console.log('UDP message sent to ' + HOST +':'+ PORT);

    client.close();

});




==========packet분석 with cap===================


Posted by yongary
,

EOP

scala 2015. 6. 24. 08:59

scala로 EOP (Expression Oriented Programming)을 하기에 좋다.

 

 

http://alvinalexander.com/scala/best-practice-think-expression-oriented-programming-eop 

Posted by yongary
,

SPA를 위한 여러가지 framework들이 있지만, framework없이 간단한 library로만

js SPA를 구현하는 방법이 있다.

 

http://tutorialzine.com/2015/02/single-page-app-without-a-framework/ 

 

 

 handlebars.js 를 사용한다.

 

Posted by yongary
,