## Posts

Showing posts from 2013

### TOPCORDER SRM598 DIV2 BinPackingEasy

Problem is

Problem Statement Fox Ciel has some items. The weight of the i-th (0-based) item is item[i]. She wants to put all items into bins.

The capacity of each bin is 300. She can put an arbitrary number of items into a single bin, but the total weight of items in a bin must be less than or equal to 300.

You are given the int[] item. It is known that the weight of each item is between 101 and 300, inclusive. Return the minimal number of bins required to store all items. Definition Class: BinPackingEasy Method: minBins Parameters: int[] Returns: int Method signature: …

### TOPCORDER SRM598 DIV1

The Question is

Problem Statement Fox Ciel received a string as a birthday present. However, the string was too long for her, so she decided to make it shorter by erasing some characters.

The erasing process will look as follows: Find the smallest i such that the i-th character and the (i+1)-th character of the string are same. If there is no such i, end the process. Remove the i-th and the (i+1)-th character of the string, and repeat from 1.

For example, if she receives "cieeilll", she will change the string as follows: "cieeilll" -> "ciilll" -> "clll" -> "cl". You are given a String s. Return the string she will get after she erases characters as described above. Definition���…

### Make small cafe DIY(Do it yourself)~

My name English Name is David Jung linving in korea. 2013/11/29 was just one year passed from meeting my girlFriend. so I wanted make her surprized and mad samll cafe for her i made it for about more than 20 hours.

complete ~ wow ~

### Bubble Sort

SortAverageBestWorstSpaceStabilityRemarksBubble sortO(n^2)O(n^2)O(n^2)ConstantStableAlways use a modified bubble sortModified Bubble sortO(n^2)O(n)O(n^2)ConstantStableStops after reaching a sorted arraySelection SortO(n^2)O(n^2)O(n^2)ConstantStableEven a perfectly sorted input requires scanning the entire arrayInsertion SortO(n^2)O(n)O(n^2)ConstantStableIn the best case (already sorted), every insert requires constant timeHeap SortO(n*log(n))O(n*log(n))O(n*log(n))ConstantInstableBy using input array as storage for the heap, it is possible to achieve constant spaceMerge SortO(n*log(n))O(n*log(n))O(n*log(n))DependsStableOn arrays, merge sort requires O(n) space; on linked lists, merge sort requires constant spaceQuicksortO(n*log(n))O(n*log(n))O(n^2)ConstantStableRandomly picking a pivot value (or shuffling the array prior to sorting) can help avoid worst case scenarios such as a perfectly sorted array.

this is bubble sort example

lets make it c language

#include <stdio.h>…

### Selection sort

Example. Sort {5, 1, 12, -5, 16, 2, 12, 14} using selection sort.

lets make it C language

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int arr[] = {5, 1, 12, -5, 16, 2, 12, 14};
int i=0;
int j=0;
int count=0;
int min=0;
int temp;

count = sizeof(arr)/sizeof(arr[0]);

for(i;i<count-1; i++){
min =i;
for(j=i+1;j<count; j++){
if(arr[min]>arr[j]){
min=j;
}
}
temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
i=0;
for(i=0; i<count; i++){
printf("%d ", arr[i]);
}
return 0;
}

this would be a good example

### This is basic concept of Memoization in Javascript

<!DOCTYPE>
<html>
<body>
<script>
<!--  Basic use -->
function square(num){
return num*num;
}

console.log(square(10));

function squareMemoization(num){
var result= '';
if(!squareMemoization.cache[num]){
console.log("computing value..");
result = num * num;
squareMemoization.cache[num]= result;
}

return squareMemoization.cache[num];

}

squareMemoization.cache = {};

console.log(squareMemoization(10)); //First time when we call this function. It calculates the value &amp; cache it.
console.log(squareMemoization(10)); // Second time onwards it return the result from cache.
console.log(squareMemoization(20)); // square function will calculate again if its a new value.

var a = ["a", "b", "c"];

console.log('a.slice(1,2)');
console.log(a.slice(1,2));
console.log('a.slice(1)');
console.log(a.slice(1));
console.log(a);

console.log('Array.prototype.slice.call(a, 1)');
console.log(Array.prototype.slice.call(a, 1));

</…

### make javascript Speed Up (2)

Asynchronous Transfer Mode getting script

this is sample

<!DOCTYPE html>
<html>
<body>
<p>Hello</p>
<script>
var script = document.createElement("script");
script.type = "text/javascript";
callback();
}
};
}else{ //ELSE
callback();
};
}

script.src=url;

}

### make javascript Speed Up (1)

Do you Think which sample is better between two samples

1. <html>
<script type ="text/javascript" src="file1.js"></script>
<script type ="text/javascript" src="file2.js"></script>
<script type ="text/javascript" src="file3.js"></script>
<body>
...
</body>
<html>

2. <html>
<body>
...
//end of body
<script type ="text/javascript" src="file1.js"></script>
<script type ="text/javascript" src="file2.js"></script>
<script type ="text/javascript" src="file3.js"></script>
</body>
<html>

First is well-known pattern when we use javascript, and also we learn like 1 sample

but until scripts are fully loaded we will see white page

Second sa…

### how to compare string values using jstl fn

At first~!

in html we need to add Declare using jstl

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYE html>
<html>
....
</html>

this is really good i think

<jsp:useBean id="extension" class="java.util.HashSet" scope="request">
<%
…

### make Callback function and check if it is undefine in javascript

<!DOCTYPE html>

<html>
<script>

function hello(){
test(function aaa(){
});

test();
}

function test(callback){
if(typeof callback  != 'undefined'){

callback();
}
}
</script>

</html>

JavaScript supports three important types of dialog boxes. These dialog boxes can be used to raise and alert, or to get confirmation on any input or to have a kind of input from the users.

Here we will see each dialog box one by one:

An alert dialog box is mostly used to give a warning message to the users. Like if one input field requires to enter some text but user does not enter that field then as a part of validation you can use alert box to give warning message as follows:

Nonetheless, an alert box can still be used for friendlier messages. Alert box gives only one button "OK" to select and proceed.

Confirmation Dialog Box:
A confirmation dialog box is mostly used to take user's consent on any option. It displays a dialog box with two buttons: OK and Cancel.

If the user clicks on OK button the wi…

### Maven Using filter~ It is Awesome

When you use maven Filter is very good for user
We can easily control enviroment of the project

Let's use Porifle

Ex> pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mkyong.common</groupId>
<artifactId>SpringMVC</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>SpringMVC Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- Spring framework -->
<dependency>
<groupId>org.springframewo…

### Spring escapeXMl using StringEscapeUtils

escape xss from hacker

we have to  change value using  StringEscapeUtils.escapeXml(str)

this is apache library
import org.apache.commons.lang.StringEscapeUtils;

//handling xml special character & in Java String
String xmlWithSpecial = "Java & HTML"; //xml String with & as special characters
System.out.println("Original unescaped XML String: " + xmlWithSpecial);
System.out.println("Escaped XML String in Java: "
+  StringEscapeUtils.escapeXml(xmlWithSpecial));

//handling xml special character > in String on Java
xmlWithSpecial = "Java > HTML"; //xml String with & as special characters
System.out.println("Original unescaped XML String: " + xmlWithSpecial);
System.out.println("Escaped XML String : " + StringEscapeUtils.escapeXml(xmlWithSpecial));

//handling xml and html special character < in String
xmlWith…

### Spring 3 Scheduler

Basic Schduler in spring 3

<beans
xsi:schemaLocation="http://www.springframework.org/schema/beans
">

<bean id="schedulerService" class="com.operation.service.SchedulerService"
scope="singleton"/>

/**
* @author jjhangu
*
*/
public class SchedulerService {
@Scheduled(fixedDelay = 5000)
public void doSomething() {
final long time = System.currentTimeMillis();
final SimpleDateFormat dayTime = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
final String str = dayTime.format(new Date(time));
Syst…

### Let me make replaceAll in Javascript

There is no replaceAll in javascript

if you use replace

ex) var orgStr = "welcome to my blog to have a fun";
orgStr = orgStr.replace('to', 'ha');
console.log(orgStr);
output = "welcome ha my blog to have a fun"

It mean only first String will be replaced but otheres not,

So this is good solution

var orgStr = "welcome to my blog to have a fun";
orgStr = orgStr.split('to').join('ha');
console.log(orgStr);
output = "welcome ha my blog ha have a fun"

### Javascript get Max Width of element in childnode

this function will return that the max width of element from tag element to inner element

var mainDiv = document.getElementById('mainDiv');
contentWidth = document.getElementById('contentScroller').offsetWidth;
var maxVal = getMax (mainDiv, contentWidth);

function getMax (tag, val){
if(typeof tag.offsetWidth != "undefined"){
if(val < tag.offsetWidth){
val = tag.offsetWidth;
}
}

if(tag.children.length>0){
var i=0;
for (i=0;i<tag.children.length;i++){
var childVal = getMax(tag.children[i], val);
if(val < childVal){
val = childVal;
}
}
}
return val;
}

### Search Tag in Iframe from out of Iframe

this is Just example

var frameHtml = document.getElementById("main_iframe").contentWindow.document.body.innerHTML;
}else{

}

};

<iframe src="" id="main_iframe" width="100%" height="100%" marginheight="0" marginwidth="0" frameborder="0" scrolling="no"></iframe>

### Call to Parent Function in Iframe

There are two ways call parent function in iframe

parent.functionName

or

window.top.functionName

This is only in my opinion, I would prefer to use  window.top.functionName.

because parent is not working well in sometime.

### DOMWindow.js this is kind of popup in html

you can try example from below site http://swip.codylindley.com/DOMWindowDemo.html#inlineContentExample7

setting Dabase

Setting Profile

### Query time Count

you can fine result millisecond

DECLARE @start_time DATETIME, @end_time DATETIME
SET @start_time = CURRENT_TIMESTAMP;

SET @end_time = CURRENT_TIMESTAMP
SELECT DATEDIFF(ms, @start_time, @end_time),DATEDIFF(ms, @start_time, @end_time)/1000;

### Oracle backup exp

exp system/oracle file=/backup/export/test05.dmp owner=(scott, hr)

### Oracle import dmp file

Step by Step

if not exist
1. create user {user_id} identified by {password}

2. GRANT CONNECT, DBA, RESOURCE TO {user_id};

\$ imp {user_id}/{password} file={filename}.dmp ignore=y full=y

wow very Easy~

### Apache Benchmark

[root@dev bin]# pwd
/usr/bin
[root@dev bin]# ab -n 500 -c 20 http://{testURL}
설명 : ab –n Request개수(500) –c 동시접속자 URL (API)

== 결과값 ==

This is ApacheBench, Version 2.3 <\$Revision: 655654 \$>
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 203.233.82.229 (be patient) Completed 100 requests Completed 200 requests Completed 300 requests Completed 400 requests Completed 500 requests Finished 500 requests
Server Software:        Apache/2.2.21 Server Hostname:        203.233.82.229 Server Port:            80
Document Path:          //account/view/terms Document Length:        4593 bytes
Concurrency Level:      20 (동시 접속자) Time taken for tests:   0.513 seconds (총 소요시간) Complete requests:      500 Failed requests:        0 Write errors:           0 Total transferred:      2511500 bytes HTML transferred:       2296500 bytes Requests per second:    975.44 [#/sec] (mean) Time per request:       20.504 [ms] (mean) Tim…

### Difference Between Connection Time out and Socket Time out~!!!

this is easy but easily fogettable

Connection Timeout is is the timeout in making the initial connection

Socket Timeout is the timeout on waiting to read data.

don't forget it~!

### oracle query trace

1. first of all need to find session id if you use any tool loke toad or sqldeveloper

SELECT * FROM v\$session

2. connect oracle by console

sqlplus '/as sysdba'
sessionid  , serial
execute sys.dbms_system.set_sql_trace_in_session(1151,29373,true);

find recently maed using
ls -ltr

tkprof filename.trc customname.txt explain=user/pw sys=no

ex)tkprof neosns_ora_7274.trc t1.txt explain=neo_sns/neo_sns_dba sys=no

execute sys.dbms_system.set_sql_trace_in_session(1151,29373,false);

### Making Secure Communication With RSA, DES [java]

Today I tried to write secure communication between client and server

i want to use ssl way

step by step I make example

and you just this process if you want secure communication

## Client ##
1. making publicKey and privateKey using RSA
2, making publicKey to Base64 String
3. give it(publicKey) to Server

## Server ##
4. receive publicKey from client and decode Bas64String to byte[]
5. get object publicKey
6. making symmetric-key (Random 16 number)
7. encryting publickey symmetric-key and give it to client

.. and

you can make encrypted  message by using des or any with symmetric-key

The point is symmetric-key is exposed to only one client and one server

/**
*
* @description <br/>
*
* @create 2013. 8. 21.
* @author jjhangu
*/
package secure;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPa…

### SVN Merge

1. 먼저 원본 프로젝트에서 team->branch 생성하면 브랜치로 변경된다

2. switch 로 브랜치로 이동후 작업을 한다.

3. 다 완료하면 커밋치고

4. switch 로 원본 프로젝트 선택

5. 원본 프로젝트에서 merge 를 눌러서  머지 한다

### Mysql Install

1. yum 방식을 이용한 설치
[의존성 패키지]
mysql / mysql-server / mysql-connector-odbc / mysql-devel
yum -y install mysql mysql-server mysql-connector-odbc mysql-devel
-y 옵션은 [yes/no] 선택시 자동으로 yes를 처리하게해주는 옵션
2. 설정파일 복사
# cp /usr/share/mysql/my-huge.cnf /etc/my.cnf
설치되는 서버의 메모리용량에 따라 최적화된 설정파일을 복사해준다. 보통 2G이상의 메모리를 설치하므로 my-huge.cnf를 복사한다.
my-huge.cnf 1~2G
my-large.cnf 512M
my-medium.cnf 128M~ 256M
my-small.cnf 64M 이하
** UTF8 인코딩 셋을 사용하기 위한 설정파일 내용 변경
# vi /etc/my.cnf
[client]
default-character-set = utf8
[mysqld]
init_connect = SET collation_connection = utf8_general_ci
init_connect = SET NAMES utf8
default-character-set = utf8
character-set-server = utf8
collation-server = utf8_general_ci
[mysqldump]
default-character-set=utf8
[mysql]
default-character-set=utf8
3. DB파일 설치경로
/var/lib/mysql/mysql/ 경로아래에 DB파일이 위치한다.
4. 기본 mysql DB 인스톨 및 권한 변경
mysql_install_db && chown -R mysql:mysql /var/lib/mysql/
5. mysql 데몬 실행
ㄱ) 직접 실행
/etc/rc.d/init.d/mysqld start
/etc/rc.d/init.d/mysqld st…

### Linux How to see the log trying to access

This one is Access Log
1. cat /var/log/secure

This one is Success Access Log
2. last

### IIS ASP ERROR detail

1. IIS 설정 변경
IIS 관리자 ->  ASP 아이콘 더블클릭 -> 브라우져에 오류전송 : True
서버쪽 디버깅 사용 : False
클라이언트 디버깅 사용 : True

IIS 관리자 -> 오류페이지 더블클릭 -> 500 에러 오른쪽 마우스 클릭 -> 기능설정 편집
->자세한 오류 라디오 버튼 체크

2. WebBrowser 설정
도구 --> 인터넷 옵션 --> 고급
HTTP 오류 메세지 표시 체크 해제

짜잔 완성

### splice in javascript

<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to add elements to the array.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2,0,"Lemon","Kiwi");
var x=document.getElementById("demo");
x.innerHTML=fruits;
}
</script>
</body>
</html>

any way splice meaning is remove 0(count) from 2 line and add Lemon, Kiwi in array

I wanted to look for how i can show in blank page in website.

that is what i fount about:blank

this will show you nothing but white blank page

### autoCommit off in mssql 2008

if you you use this tool Microsoft SQL Server Management Studio

1. tool -> option -> query execute -> sql server -> ANSI -> SET Implicity_transactions check

important thing is open new Query Tap

### sqlcmd in SQL SERVER

check if server pipe is available

if not check and restart

and

cmd

>sqlcmd -S DAVID-PC\SQLEXPRESS

URL url = new URL(params[0]);
URLConnection connection = url.openConnection();
connection.setConnectTimeout(5000);
connection.connect();
// this will be useful so that you can show a typical 0-100% progress bar
int fileLength = connection.getContentLength();

File mkDir = mActivity.getDir("assets", Activity.MODE_WORLD_READABLE | Activity.MODE_WORLD_WRITEABLE);
String path = mkDir.getAbsolutePath();