Skip to main content


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: …


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++){
  temp = arr[i];
  arr[i] = arr[min];
  arr[min] = temp;
 for(i=0; i<count; i++){
  printf("%d ", arr[i]);
 return 0;

Html Youtube Link

this would be a good example

This is basic concept of Memoization in Javascript

<!--  Basic use -->
function square(num){
return num*num;


function squareMemoization(num){
var result= '';
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(', 1)');
console.log(, 1));


make javascript Speed Up (2)

Asynchronous Transfer Mode getting script

function loadScript

this is sample

<!DOCTYPE html>
 window.onload = loadAllScript;
 function loadScript(url, callback){
  var script = document.createElement("script");
  script.type = "text/javascript";
  if(script.readState){ //IE
   script.onreadystatechange =function(){
    if(script.readState =="loaded" || script.readyState =="complete"){
     script.onreadstatechage= null;
  }else{ //ELSE



 function loadAllScript(){
  loadScript("", function(){


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>

2. <html>
//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>

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="" %>
<%@ taglib prefix="fn" uri="" %>
<!DOCTYE html>

this is really good i think

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

basic javascript 3type alert

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:

Alert Dialog Box:
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:

<head> <script type="text/javascript"> <!-- alert("Warning Message"); //--> </script> </head>
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="" xmlns:xsi=""
 <name>SpringMVC Maven Webapp</name>
  <!-- Spring framework -->

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

Spring 3 Scheduler

Basic Schduler in spring 3


<task:scheduler id="Scheduler" pool-size="10" />
 <task:executor id="TaskExecutor" pool-size="10"/>
 <task:annotation-driven executor="TaskExecutor" scheduler="Scheduler"/>

 <bean id="schedulerService" class="com.operation.service.SchedulerService"

 * @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));

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');
     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');
     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;

   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

document.getElementById('main_iframe').onload = function(){

var frameHtml = document.getElementById("main_iframe").contentWindow.document.body.innerHTML;
if(frameHtml.indexOf("loginForm") != -1){
location.href = '/neo/m4/home/login.mvc';



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

Install Openfire with Mssql

GO to openfire Website Download openfire for Windows OS Select Language Select Your DB Server
setting Dabase

Setting Profile

setting Admin Account
Finally You can login  asdf

Query time Count

you can fine result millisecond

DECLARE @start_time DATETIME, @end_time DATETIME

[your Query here]

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

Apache Benchmark

[root@dev bin]# pwd
[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 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd,
Licensed to The Apache Software Foundation,

Benchmarking (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: 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…

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

 * (c)Copyright 2010-2010, BaruSoft Co., Ltd. All rights reserved <br/>
 * @description <br/>
 * @create 2013. 8. 21.
 * @author jjhangu
package secure;


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
default-character-set = utf8
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
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…


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

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

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

짜잔 완성

splice in javascript

<!DOCTYPE html>
<p id="demo">Click the button to add elements to the array.</p>
<button onclick="myFunction()">Try it</button>
function myFunction()
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x=document.getElementById("demo");

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

APK download internal storage and install

1. First Download
            URL url = new URL(params[0]);
            URLConnection connection = url.openConnection();
            // 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();
            Log.d("need", "ApkDownload Location : " + path);

            // download the file
            input = new BufferedInputStream(url.openStream());
            output = mActivity.openFileOutput(APK_FILE_NAME,
              Activity.MODE_WORLD_READABLE | Activity.MODE_WORLD_WRITEABLE);
//            output = new FileOutputStream(mActivity.getFilesDir().getAbsoluteFile() + File.…