My Blog List

Thursday, December 12, 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: int minBins(int[] item)
(be sure your method is public)

Limits

    
Time limit (s): 2.000
Memory limit (MB): 64

Constraints

- item will contain between 1 and 50 elements, inclusive.
- Each element of item will be between 101 and 300, inclusive.

Examples

0)
    
{150, 150, 150, 150, 150}
Returns: 3
You have five items and each bin can hold at most two of them. You need at least three bins.
1)
    
{130, 140, 150, 160}
Returns: 2
For example, you can distribute the items in the following way:
  • Bin 1: 130, 150
  • Bin 2: 140, 160
2)
    
{101, 101, 101, 101, 101, 101, 101, 101, 101}
Returns: 5
3)
    
{101, 200, 101, 101, 101, 101, 200, 101, 200}
Returns: 6
4)
    
{123, 145, 167, 213, 245, 267, 289, 132, 154, 176, 198}
Returns: 8


and My Code is blow

public static int minBins2(int[] items){
  Arrays.sort(items);
 
  int sp = 0;
  int ep = Math.max(items.length -1, 0);
 
  int totalNum =0; 
  while(true){
   if(items[ep] > 199){
    totalNum ++;
    ep--;
   }else{
    break;
   }
  }
 
  while(ep >= sp){
   if(items[ep] + items[sp] <= 300){
    sp++;
   }
   ep--;
   totalNum++;
  }
 
  return totalNum;
 }


## Access Step ##

1. Sort Items
2. if items are bigger than 199 add totalNum
3. sum of first item and last item are bigger than 300
   last index -- and totalnum ++
.......

i think this is very easy

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:
  1. Find the smallest i such that the i-th character and the (i+1)-th character of the string are same.
  2. If there is no such i, end the process.
  3. 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

    
Class: ErasingCharacters
Method: simulate
Parameters: String
Returns: String
Method signature: String simulate(String s)
(be sure your method is public)

Limits

    
Time limit (s): 2.000
Memory limit (MB): 64

Constraints

- s will contain between 1 and 50 characters, inclusive.
- Each character in s will be a lowercase letter ('a'-'z').

Examples

0)
    
"cieeilll"
Returns: "cl"
This is the example from the statement.
1)
    
"topcoder"
Returns: "topcoder"
She won't erase any characters at all.
2)
    
"abcdefghijklmnopqrstuvwxyyxwvutsrqponmlkjihgfedcba"
Returns: ""
3)
    
"bacaabaccbaaccabbcabbacabcbba"
Returns: "bacbaca"
4)
    
"eel"
Returns: "l"


My Solution is Below

public static String simulate(String str){
  int start =0;
 
  while(str.length()-1 >start){
   char firstChar = str.charAt(start);
//   System.out.println(firstChar + " : fisrt");
   char nextChar = str.charAt(start+1);
//   System.out.println(nextChar +" : next");
   if(firstChar == nextChar){
    str = str.substring(0, start) + str.substring(start+2, str.length());
//    System.out.println("complete:" + str);
    if(start !=0){
     start--;
    }
   }else{
    start++;
   }
  }
 
//  System.out.println(str);
  return str;
 }


## Access Logic ##


my access is below but i don't think this is a good sample

because i just got 144point / 250 point

so other soultions are better than my solution

i attached other solution after my solution





cieeilll 
first point is c
first+1 point is i

c and i is differenct so first point will be 2

first point is i
first+1 point is e

c and i is differenct so first point will be 3

firtst point e
first+1 point is e

e and e is the same so cut before first point "ci" and cut after firstPoint +1 to end "ill"
and concat before string and after string

this will be ciill

first point changed first-1



Otheres are Below

public static String simulate(String s){
  for(int i=0; i<s.length()-1 i++){
    if(s.charAT(i) == s.charAT(i+1)){
     s= s.substring(0, i) + s.substring(i+2, s.length);
     i=-1;
     }
  }
}



sombody use StringBuffer.delete

and sombody use Stack

many different way i learend from topcoder --V

Sunday, December 1, 2013

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 ~



Wednesday, November 27, 2013

Bubble Sort

Sort Average Best Worst Space Stability Remarks
Bubble sort O(n^2) O(n^2) O(n^2) Constant Stable Always use a modified bubble sort
Modified Bubble sort O(n^2) O(n) O(n^2) Constant Stable Stops after reaching a sorted array
Selection Sort O(n^2) O(n^2) O(n^2) Constant Stable Even a perfectly sorted input requires scanning the entire array
Insertion Sort O(n^2) O(n) O(n^2) Constant Stable In the best case (already sorted), every insert requires constant time
Heap Sort O(n*log(n)) O(n*log(n)) O(n*log(n)) Constant Instable By using input array as storage for the heap, it is possible to achieve constant space
Merge Sort O(n*log(n)) O(n*log(n)) O(n*log(n)) Depends Stable On arrays, merge sort requires O(n) space; on linked lists, merge sort requires constant space
Quicksort O(n*log(n)) O(n*log(n)) O(n^2) Constant Stable Randomly 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>
#include <stdlib.h>
int main(int argc, char *argv[])
{
 int arr[] = {5, 1, 12, -5, 16, 2, 12, 14};

 int count;
 int i=0, j=0, k=0, temp;
 count = sizeof(arr)/sizeof(arr[0]);
 for(j; j<count -1; j++){
  for(i=0; i<count-1-j; i++){
   if(arr[i]> arr[i+1]){
    temp = arr[i];
    arr[i]= arr[i+1];
    arr[i+1]= temp;
   }
  }
 
  k=0;
  for(k=0; k<count; k++){
   printf("%d ", arr[k]);
  }
  printf("\n");
 }
 return 0;
}


result :

1 5 -5 12 2 12 14 16
1 -5 5 2 12 12 14 16
-5 1 2 5 12 12 14 16
-5 1 2 5 12 12 14 16
-5 1 2 5 12 12 14 16
-5 1 2 5 12 12 14 16
-5 1 2 5 12 12 14 16

Selection sort

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




Selection sort example


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;
}

Monday, November 11, 2013

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

</script>
</body>
</html>

Wednesday, November 6, 2013

make javascript Speed Up (2)

Asynchronous Transfer Mode getting script

function loadScript


this is sample

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

  script.src=url;
  document.getElementsByTagName("head")[0].appendChild(script);

 }

 function loadAllScript(){
  console.log('loadAllScript');
  loadScript("http://code.jquery.com/jquery-1.10.1.min.js", function(){
 
   loadScript("http://s1.daumcdn.net/cfs.tistory/v/130502110925/blog/plugins/A_ShareEntryWithSNS/script/shareEntryWithSNS.js", function(){
    alert();
   });
  });
 }
</script>
</body>
</html>

make javascript Speed Up (1)

Do you Think which sample is better between two samples

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



2. <html>
    <head>
   </head>
<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 sample is better than first
because after body is loaded javascript will run

Tuesday, November 5, 2013

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">
           <%
         extension.add("ap");extension.add("avi");extension.add("bmp");extension.add("doc");
         extension.add("docx");extension.add("exe");extension.add("gif");extension.add("gul");
               extension.add("htm");extension.add("html");extension.add("hwp");extension.add("jpg");
               extension.add("log");extension.add("mht");extension.add("mp3");extension.add("pdf");
               extension.add("png");extension.add("ppt");extension.add("pptx");extension.add("tif");
               extension.add("tiff");extension.add("txt");extension.add("vcf");extension.add("wav");
               extension.add("xls");extension.add("xlsx");extension.add("xml");extension.add("zip");
           %>
       </jsp:useBean>
       <c:choose>
        <c:when test="${fn:contains(extension, attach.contentType)}">
         <img src="/neo/img/neo/theme/fileIcon/file_${attach.contentType}.gif"/>${attach.name} ${attach.size }bytes</a>
        </c:when>
        <c:otherwise>
         <img src="/neo/img/neo/theme/fileIcon/file_unknown.gif"/>${attach.name} ${attach.size }bytes</a>
        </c:otherwise>
       </c:choose>

Monday, November 4, 2013

make Callback function and check if it is undefine in javascript

<!DOCTYPE html>

<html>
<script>
window.onload = hello;

function hello(){
test(function aaa(){
alert('callback success');
});

test();
}

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

callback();
}
}
</script>

</html>

Sunday, November 3, 2013

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 window method confirm() will return true. If the user clicks on the Cancel button confirm() returns false. You can use confirmation dialog box as follows:

<head>
<script type="text/javascript">
<!--
   var retVal = confirm("Do you want to continue ?");
   if( retVal == true ){
      alert("User wants to continue!");
   return true;
   }else{
      alert("User does not want to continue!");
   return false;
   }
//-->
</script>
</head>


Prompt Dialog Box:


The prompt dialog box is very useful when you want to pop-up a text box to get user input. Thus it enable you to interact with the user. The user needs to fill in the field and then click OK.

This dialog box is displayed using a method called prompt() which takes two parameters (i) A label which you want to display in the text box (ii) A default string to display in the text box.

This dialog box with two buttons: OK and Cancel. If the user clicks on OK button the window method prompt() will return entered value from the text box. If the user clicks on the Cancel button the window method prompt() returns null.

You can use prompt dialog box as follows:

<head>
<script type="text/javascript">
<!--
   var retVal = prompt("Enter your name : ", "your name here");
   alert("You have entered : " +  retVal );
//-->
</script>
</head>

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.0 http://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.springframework</groupId>
   <artifactId>spring</artifactId>
   <version>2.5.6</version>
  </dependency>
  <!-- Spring MVC framework -->
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>2.5.6</version>
  </dependency>
  <!-- JSTL -->
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>jstl</artifactId>
   <version>1.1.2</version>
  </dependency>
  <dependency>
   <groupId>taglibs</groupId>
   <artifactId>standard</artifactId>
   <version>1.1.2</version>
  </dependency>
 </dependencies>
 <profiles>
  <profile>
   <id>dev</id>
   <activation>
    <activeByDefault>true</activeByDefault>
    <property>
     <name>env</name>
     <value>dev</value>
    </property>
   </activation>
   <properties>
    <appserver.home>dev</appserver.home>
   </properties>
  </profile>
  <profile>
   <id>real</id>
   <activation>
    <property>
     <name>env</name>
     <value>real</value>
    </property>
   </activation>
   <properties>
    <appserver.home>real</appserver.home>
   </properties>
  </profile>
 </profiles>
 <build>
  <filters>
   <filter>src/main/filter/${appserver.home}/spring-views.properties</filter>
  </filters>

  <resources>
   <resource>
    <directory>src/main/resources</directory>
    <filtering>true</filtering>
   </resource>
  </resources>
  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.3.2</version>
    <configuration>
     <source>1.6</source>
     <target>1.6</target>
    </configuration>
   </plugin>
  </plugins>
 </build>
</project>

project tree
src/main/filter/dev-spring-views.properties
                       /real-spring-views.properties
src/main/java
src/resources/spring-views.properties


command line
$ mvn clean package -P real


filters poperties will be injected into resources/spring-veiw.properties

if you want have sample

reply

Saturday, November 2, 2013

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
        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 html and xml special character " in 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 special character ' in String from 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));

Sunday, October 27, 2013

Spring 3 Scheduler

Basic Schduler in spring 3

<beans
 xmlns:task="http://www.springframework.org/schema/task"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/task  http://www.springframework.org/schema/task/spring-task-3.0.xsd
  ">


<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"
    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));
  System.out.println("gap is 5 second" + str);
 }
}


log gap is 5scond2013-06-28 02:06:44
log gap is 5scond2013-06-28 02:06:49

Wednesday, October 23, 2013

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"


Thursday, October 17, 2013

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;
 }

Monday, October 14, 2013

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';
}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.

Wednesday, October 9, 2013

DOMWindow.js this is kind of popup in html

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

Wednesday, September 11, 2013

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

Tuesday, September 10, 2013

Query time Count

you can fine result millisecond

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


[your Query here]


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

Sunday, September 8, 2013

Oracle backup exp


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

Tuesday, September 3, 2013

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~

Sunday, September 1, 2013

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 $>

Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/

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)
Time per request:       1.025 [ms] (mean, across all concurrent requests)
Transfer rate:          4784.80 [Kbytes/sec] received

 
Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        5    6   0.8      6       9
Processing:     8   14   8.3     11     124
Waiting:        7   14   8.3     11     123
Total:         13   20   8.6     17     131

 
Percentage of the requests served within a certain time (ms)
  50%     17
  66%     19
  75%     21
  80%     22
  90%     30
  95%     34
  98%     45
  99%     55
100%    131 (longest request)

Tuesday, August 27, 2013

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~!

Monday, August 26, 2013

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

Wednesday, August 21, 2013

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;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.Formatter;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class RSACrypt {

public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidKeySpecException, NoSuchProviderException, IOException {
final KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
final KeyPair keyPair = generator.generateKeyPair();
final PublicKey publicKey = keyPair.getPublic();
final PrivateKey privateKey = keyPair.getPrivate();

/**
* 시나리오 1
*
* Client
* 1. make RSA keys (publicKey, priateKey)
* 2. give publicKey to Server
*
* Server
* 3. make Symmetric-key using publicKey given by client
* 4. give it to client
*
* Client and Server Communicate Using Symmetric-key using DES Algorithm
*
*/

// Client
// 1 making public and private key
final BASE64Encoder encoder = new BASE64Encoder();
final String pubKeyStr = encoder.encode(publicKey.getEncoded());
System.out.println("#######################################");
System.out.println("Client[publicKey] BASE64 ");
System.out.println("#######################################");
System.out.println(pubKeyStr);
System.out.println();
System.out.println();

final String priKeyStr = encoder.encode(privateKey.getEncoded());
System.out.println("#######################################");
System.out.println("Client[privateKey] BASE64 ");
System.out.println("#######################################");
System.out.println(priKeyStr);
System.out.println();
System.out.println();

// give it to public key to server

// Server
// 3. Get Public Key obejct

final BASE64Decoder decoder = new BASE64Decoder();
final byte[] sigBytes2 = decoder.decodeBuffer(pubKeyStr);

// PublicKey from client
final PublicKey publicServerKey = convertKeytoKeyObject(sigBytes2);

final String pubServerKeyStr = encoder.encode(publicServerKey.getEncoded());
System.out.println("#######################################");
System.out.println("Server [publicKey] BASE64 ");
System.out.println("#######################################");
System.out.println(pubServerKeyStr);
System.out.println();
System.out.println();

// 3. make Symmetric-key using publicKey given by client

final Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicServerKey);
final String symmetricKey = "0123456789ABCDEF";

System.out.println("#######################################");
System.out.println("Server [symmetricKey] ");
System.out.println("#######################################");
System.out.println(symmetricKey);
System.out.println();
System.out.println();

final byte[] b0 = cipher.doFinal(symmetricKey.getBytes());

// give symmetricKey to Client

// client decode
cipher.init(Cipher.DECRYPT_MODE, privateKey);
final byte[] b1 = cipher.doFinal(b0);

System.out.println("Client Finally Decode SymmetricKey : " + new String(b1));

// only one client and server will know symmetricKey
// and Server Client will Have Same symmetricKey and Communucating message using des
// algorithm with this symmetricKey
}

public static String bytesToHexString(byte[] bytes) {
final StringBuilder sb = new StringBuilder(bytes.length * 2);

final Formatter formatter = new Formatter(sb);
for (final byte b : bytes) {
formatter.format("%02x", b);
}

return sb.toString();
}

private static PublicKey convertKeytoKeyObject(byte[] publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
final X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKey);
final KeyFactory keyFact = KeyFactory.getInstance("RSA");
return keyFact.generatePublic(x509KeySpec);
}

}

Wednesday, August 7, 2013

SVN Merge

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

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

3. 다 완료하면 커밋치고

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

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

Sunday, July 28, 2013

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 stop
/etc/rc.d/init.d/mysqld restart
ㄴ) 서비스 등록
chkconfig — add mysqld
chkconfig –level 2345 mysqld on
chmod 755 /etc/rc.d/init.d/mysqld
ㄷ) 자동서비스 선택
[root@localhost test]# ntsysv
[*] mysqld
7. 패스워드 변경 및 등록
ㄱ) sql 에서 실행
mysql > update user set password = password(‘비밀번호’) where user = ‘사용자’;
mysql > flush privileges; (* 적용하기)
ㄴ) 명령어 실행
#mysqladmin -u 사용자 password 비밀번호
8. sql script 실행
#mysql -u 사용자 -p 비밀번호 mysql < 파일명.sql

Monday, July 22, 2013

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

Sunday, July 14, 2013

IIS ASP ERROR detail

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

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

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

짜잔 완성

Monday, July 8, 2013

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

about:blank in webpage

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

Thursday, July 4, 2013

autoCommit off in mssql 2008

if you you use this tool Microsoft SQL Server Management Studio

follow this step

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

important thing is open new Query Tap

Tuesday, July 2, 2013

sqlcmd in SQL SERVER

check if server pipe is available

if not check and restart

and

cmd

>sqlcmd -S DAVID-PC\SQLEXPRESS

Monday, July 1, 2013

APK download internal storage and install

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

            // 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.separator + APK_FILE_NAME);
//            output = new FileOutputStream(SDCardRoot + File.separator + APK_FILE_NAME);
            Log.d("need", "ApkDownload Location : " + path);

            byte data[] = new byte[1024];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                progressPercent =(int) (total * 100 / fileLength);
                publishProgress();
                output.write(data, 0, count);
            }

            output.flush();
            output.close();
            input.close();


2. Second Install
File fileLocation = new File(mActivity.getFilesDir(), ApkFileDownloadTask.APK_FILE_NAME);
         
Log.d("need", "apkFile isFile" + fileLocation.isFile());
Log.d("need", "apkFile getName" + fileLocation.getName());
Log.d("need", "apkFile getAbsolutePath" + fileLocation.getAbsolutePath());
Log.d("need", "apkFile getAbsolutePath" + fileLocation.length());
         
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(fileLocation), "application/vnd.android.package-archive");

startActivity(intent);