- $http 서비스를 이용해 json을 웹으로 가져오기.
| ||
| <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> |
전통적인 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)
}
}
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 임.
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에서도 안 됨.
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
마야의 달력 중에 260일이 1년인 Tzolkin 달력이 있다.
1년이 13달이고
1달 20일이라서 13*20 = 260일..
이 20일마다 기운이 다르다고 하는데

20일별 기운을 정리한 사이트:
<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
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>
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();
});
scala로 EOP (Expression Oriented Programming)을 하기에 좋다.
http://alvinalexander.com/scala/best-practice-think-expression-oriented-programming-eop



