Swift tip

Programming/Swift 2017.05.27 10:48 Posted by 파란크리스마스

Optional

출처 : 옵셔널 (Optional)

//: Playground - noun: a place where people can play

import UIKit

var email: String?
print(email) // nil

nickname = "bluexmas"
print(nickname) // Optional("bluexmas")

var str = "Hello, playground"

var name:Optional<string> = "name"
var name2:String? = "name2"

var name4:ImplicitlyUnwrappedOptional<string> = "name4";
var name3:String! = "name3"

print() name2 값이 nil 아니면 name2값 출력, name2의 값이 nil 및 경우 ?? 뒤에 있는 값 출력

if name != nil {
    print(name!)
}

if val n = name {
    print(n)
}

if let n = name {
    print(n)
}

var text1:String = "abc"
Int(test1)  // nil


var test:String = "123"
print(Int(test)! + 10)

nil 전달 함수

	var lampOn:Bool? = false
	
	func lampOnOffRemove(isOn : Bool?) {
		if let onOff = isOn {
			self.lampOn = onOff
			self.lampImageView.image = UIImage(named : onOff ? "lamp-on.png" : "lamp-off.png")
		} else {
			self.lampOn = nil
			self.lampImageView.image = UIImage(named : "lamp-remove.png")
		}
	}

	@IBAction func lampOffClicked(_ sender: AnyObject) {
		if lampOn! { // <-- 컴파일시 느낌표(!) 있어야 컴파일이 되고, 값이 nil 인 경우 런타임시 오류 발생
			//
		} else {
			//
		}
	}

WebView HTML 문자열 로딩

	@IBAction func HTMLClicked(_ sender: AnyObject) {
		let htmlString = "

HTML String

String 변수를 이용한 웹페이지

애플 홈페이지로 이동

" webView.loadHTMLString(htmlString, baseURL: nil) }

WebView HTML 파일 로딩

	func loadPageWithUrlString(urlString : String) {
		if let url = URL(string : urlString) {
			webView.loadRequest(URLRequest(url: url))
		}
	}
		
	@IBAction func fileClicked(_ sender: AnyObject) {
		if let path = Bundle.main.path(forResource: "Sample", ofType : "html") {
			loadPageWithUrlString(urlString: path)
		}
	}

WebView Delegate

class ViewController: UIViewController, UIWebViewDelegate {

	@IBOutlet weak var webView: UIWebView!
	@IBOutlet weak var loadingIndicator: UIActivityIndicatorView!
	
	override func viewDidLoad() {
		super.viewDidLoad()
		// Do any additional setup after loading the view, typically from a nib.
		self.webView.delegate = self
	}
	
	public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool
	{
		guard let urlString = request.url?.absoluteString else {
			return true;
		}
		
		print(request.url?.absoluteString ?? "")
		
		if urlString.contains("daum.net") {
			return false;
		}
		
		return true;
	}
	
	public func webViewDidStartLoad(_ webView: UIWebView)
	{
		loadingIndicator.startAnimating()
	}
	
	public func webViewDidFinishLoad(_ webView: UIWebView)
	{
		loadingIndicator.stopAnimating()
	}
	
	public func webView(_ webView: UIWebView, didFailLoadWithError error: Error)
	{
		print(error.localizedDescription)
		loadingIndicator.stopAnimating()
	}

포커스 이동

		// 텍스트필드 컨트롤에 포커서를 줘서 키패드가 자동으로 올라오도록 함
		self.urlTextField.becomeFirstResponder()

Objective-C main 함수

출처 : The App Life Cycle

//
//  main.m
//  study2
//
//  Created by Mac on 2017. 5. 27..
//  Copyright © 2017년 Mac. All rights reserved.
//

#import <uikit uikit.h="">
#import "AppDelegate.h"

int main(int argc, char * argv[]) {
	@autoreleasepool {
	    return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
	}
}

UIImageView 확대

	@IBAction func OnBtnScaleClick(_ sender: UIButton) {
		imgLamp.frame.size.width *= 1.2
		imgLamp.frame.size.height *= 1.2
	}

형변환

	@IBAction func typeCast(_ sender: AnyObject) {
		if let tmpButton = sender as? UIButton {
			tmpButton.setTitle("확대2", for: .normal)
		}
	}

loadImage 함수 구현

	func loadImage(fileName : String, fileType : String) -> UIImage? {
		if let path = Bundle.main.path(forResource: fileName, ofType: fileType) {
			return UIImage(contentsOfFile : path)
		} else {
			return nil;
		}
	}

	@IBAction func OnRadio1Change(_ sender: UISwitch) {
		imgLamp.image = loadImage( fileName : sender.isOn ? "lamp_on.png" : "lamp_off.png", fileType : "png" )
	}

TextField Delegate

	public func textFieldShouldReturn(_ textField: UITextField) -> Bool // called when 'return' key pressed. return NO to ignore.
	{
		loadPageWithUrlString(urlString: urlTextField.text ?? "")
		
		// 포커스 해지
		view.endEditing(true)
		
		return true;
	}

배열추가, String format, 이미지 변경

	var flowerArray = [String]()

	override func viewDidLoad() {
		super.viewDidLoad()
		// Do any additional setup after loading the view, typically from a nib.
		
		for i in 1...6 {
			flowerArray.append( String(format : "%02d.png", i))
		}
	}

	@IBAction func onBtnNextClick(_ sender: UIButton) {
		if sender.currentTitle == "이전" {
			current_img_index -= 1
		} else {
			current_img_index += 1
		}
		
		if current_img_index >= flowerArray.count {
			current_img_index = 0
		}
		
		if current_img_index < 0 {
			current_img_index = flowerArray.count - 1
		}
		
		imgLamp.image = UIImage(named : flowerArray[current_img_index])
	}

Timer

		// 1초에 한번씩 호출
		Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: {
			(timer) -> Void in
//			NSLog("%G", #function)
			
			let dateFormatter = DateFormatter()
			dateFormatter.dateFormat = "yyyy M d HH:mm:ss"
			
			
			self.lblCurrentTime.text = "현재시간 : " + dateFormatter.string(from : Date())
		})

UIAlertController

	override func viewDidAppear(_ animated: Bool) {
		/*
		let messageBox = UIAlertView(title : "알림", message : "메시지", delegate : nil, cancelButtonTitle : "OK")
		messageBox.show()
		*/

		let messageBox = UIAlertController(title: "알림", message: "메시지", preferredStyle: .alert)
		messageBox.addAction(UIAlertAction(title : "OK", style : .default, handler : {
			(action) -> Void in
			print("OK 선택")
			
		}))
		
		messageBox.addTextField(configurationHandler: {
			(textfield) in
			textfield.backgroundColor = UIColor.yellow
		})
		
		present(messageBox, animated : true, completion : nil)
	}

picker

import UIKit

class ViewController: UIViewController,  UIPickerViewDataSource, UIPickerViewDelegate {
	
	@IBOutlet weak var imagePickerView: UIPickerView!
	@IBOutlet weak var selectedItemLable: UILabel!
	@IBOutlet weak var selectedImageView: UIImageView!
	
	var mArray = [String]()

	override func viewDidLoad() {
		super.viewDidLoad()
		// Do any additional setup after loading the view, typically from a nib.
		
		
		imagePickerView.dataSource = self
		imagePickerView.delegate = self
		
		for i in 1...6 {
			mArray.append(String(format: "%02d", i))
		}
	}

	override func didReceiveMemoryWarning() {
		super.didReceiveMemoryWarning()
		// Dispose of any resources that can be recreated.
	}
	
	
	// picker 열의 개수
	public func numberOfComponents(in pickerView: UIPickerView) -> Int {
		return 1
	}
	
	// picker 행의 개수
	public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
		
		return mArray.count;
	}
	
	/*
	func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
		
		return mArray[row]
	}*/
	
	// picker 행의 높이 설정
	public func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat
	{
		return 100;
	}
	
	// picker 행을 이미지로 표시
	public func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView
	{
		let imageView = UIImageView(frame:CGRect(x:0, y:0, width:100, height:100));
		imageView.image = UIImage(named : mArray[row])
		return imageView
	}
	
	// 선택이벤트
	public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
		selectedItemLable.text = "선택 = " + mArray[row]
		selectedImageView.image = UIImage(named : mArray[row])
	}
}

이미지 비동기 로딩

       if let urlString = movieArray[indexPath.row].thumbnailUrl,
            let url = URL(string : urlString)
        {
            do {
                /*
                // 동기방식
                let imageData = try Data(contentsOf: url)
                cell.thumbnailImageView.image = UIImage(data : imageData)
                */
            } catch {
                
            }
            
            // 비동기방식
            let task = URLSession.shared.dataTask(with: url) {
                (data, response, error) -> Void in
                
                if let imageData = data {
                    DispatchQueue.main.async {
                        cell.thumbnailImageView.image = UIImage(data : imageData)
                    }
                }
            }
                
            task.resume()
        }
저작자 표시
신고

Raspberry PI -무선랜카드 AP모드로 사용하기

OS/Raspberry Pi 2017.05.22 23:31 Posted by 파란크리스마스

Raspberry PI -무선랜카드 AP모드로 사용하기

출처 : Using your new Raspberry Pi 3 as a WiFi access point with hostapd
라즈베리파이 활용강좌 : 라즈베리파이를 무선공유기(AP)로 활용하기 |
SETTING UP A RASPBERRY PI AS AN ACCESS POINT IN A STANDALONE NETWORK

최신으로 업데이트

$ sudo apt-get update;sudo apt-get upgrade -y

AP 관련 패키지 설치

$ sudo apt-get install hostapd bridge-utils iw
$ sudo apt-get install dnsmasq

wlan0 고정 아이피 설정

$ sudo vi /etc/dhcpcd.conf

아래 내용 하단에 추가

denyinterfaces wlan0

Network 설정 파일 백업하고 수정

$ sudo cp /etc/network/interfaces /etc/network/interfaces.bak
$ sudo vi /etc/network/interfaces

# interfaces(5) file used by ifup(8) and ifdown(8)

# Please note that this file is written to be used with dhcpcd
# For static IP, consult /etc/dhcpcd.conf and 'man dhcpcd.conf'

# Include files from /etc/network/interfaces.d:
source-directory /etc/network/interfaces.d

auto lo
iface lo inet loopback

iface eth0 inet manual

allow-hotplug wlan0
iface wlan0 inet static
    address 192.168.0.1
    netmask 255.255.255.0
    network 192.168.1.0
    broadcast 192.168.0.255
#    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

allow-hotplug wlan1
iface wlan1 inet manual
    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

wlan 다시 시작

$ sudo service dhcpcd restart
$ sudo ifdown wlan0
$ sudo ifup wlan0

DHCP 서버 설정

$ sudo mv /etc/dnsmasq.conf /etc/dnsmasq.conf.orig
$ sudo vi /etc/dnsmasq.conf

interface=wlan0      # Use interface wlan0
listen-address=192.168.0.1 # Explicitly specify the address to listen on
bind-interfaces      # Bind to the interface to make sure we aren't sending things elsewhere
server=8.8.8.8       # Forward DNS requests to Google DNS
domain-needed        # Don't forward short names
bogus-priv           # Never forward addresses in the non-routed address spaces.
dhcp-range=192.168.0.2,192.168.0.20,255.255.255.0,24h # Assign IP addresses between 192.168.0.2 and 192.168.0.20 with a 24 hour lease time

hostapd.conf 파일 생성

$ sudo vi /etc/hostapd/hostapd.conf

# This is the name of the WiFi interface we configured above
interface=wlan0

# Use the nl80211 driver with the brcmfmac driver
driver=nl80211

# This is the name of the network
ssid=Pi3-AP

# Use the 2.4GHz band
hw_mode=g

# Use channel 6
channel=6

# Enable 802.11n
ieee80211n=1

# Enable WMM
wmm_enabled=1

# Enable 40MHz channels with 20ns guard interval
ht_capab=[HT40][SHORT-GI-20][DSSS_CCK-40]

# Accept all MAC addresses
macaddr_acl=0

# Use WPA authentication
auth_algs=1

# Require clients to know the network name
ignore_broadcast_ssid=0

# Use WPA2
wpa=2

# Use a pre-shared key
wpa_key_mgmt=WPA-PSK

# The network passphrase
wpa_passphrase=raspberry

# Use AES, instead of TKIP
rsn_pairwise=CCMP

default hostapd 파일 수정

$ sudo vi /etc/default/hostapd

DAEMON_CONF="/etc/hostapd/hostapd.conf"

서비스 다시 시작

$ sudo service hostapd start  
$ sudo service dnsmasq start
저작자 표시
신고

swift 기본문법

Programming/IOS 2017.05.20 12:56 Posted by 파란크리스마스

swift 기본문법

//: Playground - noun: a place where people can play

import UIKit

// var str:String ="Hello, playground"
var str = "Hello, playground"
str = "Hello, "

//
let myName = "bluexmas"

// char 타입
let lastName:Character = "류"

// int 타입
let age = 38

// boolean 타입
let isAult = true

print(isAult ? "성인" : "어린이")

// 범위연산자
for i in 1...5 {
    print(i)
}

// 자료형
print(Int.max)
print(Int8.max)
print(Int16.max)
print(UInt.max)

let num:Int8 = 10

let pi = 3.14159

// 자동 형변환 없음
//print(myName + age)
print(myName + String(age))

print("\(myName) 나이는 \(age)")

// 숫자형도 형변환이 없으면 더할수 없음
print(Double(num) + pi)

// 조건문
if str == "한글" {
    print("참")
} else if str == "play" {
    print("play도 아니다.")
} else {
    print("거짓")
}

if str != "최현택" && age == 38 {
    print("최현택은 아니지만 나이는 같다.")
}

// in line 
isAult ? print("성인") : print("청소년")


// switch
switch age {
case 0..<20:
    print("청소년")
case 20..<30:
    break // switch 를 빠져나감
case 30..<40:
    print("30대")
    fallthrough // break 와 다르게 이하  case 조건 실행
default:
    print("성인")
}

// 문자열 switch
switch lastName {
case "김", "이", "박":
    print("김이박")
default:
    print("test")
}

// 배열
let nameArray:[String] = ["추신수", "박찬호"]

var i = 1
var sum = 0
while i<=10 {
    sum += i
    i += 1
    print(sum)
}

구구단 출력

// 구구단
for i in 2...9 {
    print("\n \(i) 단\n")
    for j in 1...9 {
        print("\(i) * \(j) = \(i*j)")
    }
}

배열

// 배열
var arrray2:Array<string> = ["java", "c#", "delphi"]
var nameArray:[String] = ["java", "c#", "delphi"]

// 추가
nameArray.append("javascript")

// 삽입
nameArray.insert("sql", at: 2)

// 제거
nameArray.remove(at: 1)

print(nameArray)

// 대치
nameArray[0] = "자바"

// 출력
for i in 0...2 {
    print(nameArray[i])
}

// 배열의 Count
print("배열의 Count = \(nameArray.count)")

// 일부만 출력
print(nameArray[0...1])

// 전부 삭제
nameArray.removeAll()

Dictionary

// Dictionary
var capitalDic2:Dictionary<string, string=""> = ["한국" : "서울", "영국" : "런던", "미국" : "워싱턴"]
var capitalDic = ["한국" : "서울", "영국" : "런던", "미국" : "워싱턴"]
print(capitalDic["한국"])    // Optional("서울")

for capital in capitalDic.values {
    print(capital)
}

for (country, capital) in capitalDic {
    print("\(country)  국가의 수도는 \(capital)")
}

// 추가
capitalDic["중국"] = "배이징"
print(capitalDic)

// 삭제1
capitalDic.removeValue(forKey: "미국")
print(capitalDic)

// 삭제2
capitalDic["중국"] = nil
print(capitalDic)

// 전부삭제
capitalDic.removeAll()
print(capitalDic)

함수

// 함수
func printStr() {
    print(str)
}

func sum(lns : Int, rhs : Int) -> Int {
    return lns + rhs
}

print( sum(lns: 5, rhs: 3) )

튜플(Tuple)

// 튜플(Tuple)
func getMyInfo() -> (String, Int, String, String) {
    return ("블루", 10, "010-xxx-xxxx", "bluexmas@tistory.com")
}

let (name, age, phone, email) = getMyInfo()
print(name)
print(age)
print(phone)
print(email)

구조체

클래스와 다르게 구조체는 기본 자료형(int, boolean)처럼 대입시 별도의 메모리가 할당 되고, 클래스처럼 상속을 받을 수 없습니다.

// 구조체
struct UserInfo {
    var name : String
    var age : Int
    var email : String
    
    // swift 제고 초기화 함수
    init(name : String, age : Int, email : String) {
        self.name = name
        self.age = age
        self.email = email
    }
    
    func showInfo() {
        print("이름 : \(name), 나이 : \(age) 메일주소 : \(email)")
    }
}

var userInfo1 = UserInfo(name : "블루", age : 10, email : "bluexmas@tistyory.com")
var userInfo2 = UserInfo(name : "레드", age : 10, email : "bluexmas@tistyory.com")
userInfo1.showInfo()

var userArray:[UserInfo] = []
userArray.append(userInfo1)
userArray.append(userInfo2)

for info in userArray {
    info.showInfo()
}
저작자 표시
신고

java - mysql jdbc 연결

Programming/Java 2017.05.08 11:00 Posted by 파란크리스마스

출처 : 초보개발자 이야기. :: JAVA : JDBC를 사용하여 MySQL 과 연동하기 ...

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

public class MySQLJDBCTest {
	
	public static void main(String [] args) throws Exception {
		
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		
		try {
			Class.forName("org.gjt.mm.mysql.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://bluexmas.tistory.com:3306/test_db", "test", "test");
			System.out.println("connection = " + conn);
			
			// 
			stmt = conn.prepareStatement("SHOW DATABASES");
			rs = stmt.executeQuery();
			
			//
			ResultSetMetaData rsmd = rs.getMetaData();
			int cols = rsmd.getColumnCount();
			System.out.printf("The query fetched %d columns\n",cols);
			System.out.println("These columns are: ");
			for (int i=1;i<=cols;i++) {
				String colName = rsmd.getColumnName(i);
				String colType = rsmd.getColumnTypeName(i);
				System.out.println(colName+" of type "+colType);
			}
			
			//
			while (rs.next()) {
				String str = rs.getNString(1);
				System.out.println(str);
			}
		} catch (SQLException sqex) {
			System.out.println("SQLException: " + sqex.getMessage());
			System.out.println("SQLState: " + sqex.getSQLState());
		} finally {
			if (rs != null) try { rs.close(); } catch (SQLException e) { }
			if (stmt != null) try { stmt.close(); } catch (SQLException e) { }
			if (conn != null) try { conn.close(); } catch (SQLException e) { }
		}
	}

}
저작자 표시
신고

Maven - Spring 설정

Programming/Java 2017.05.05 19:55 Posted by 파란크리스마스

Maven - Spring 설정

Properties 추가

[Properties]항목에서 [Create]버튼을 선택해서 아래와 같이 입력하고 [OK]버튼을 선택

Name : org.springframework-version
Value : 4.1.7.RELEASE

Dependencies 추가

groupId : org.springframework
artifactId : spring-context
version : ${org.springframework-version}

저작자 표시
신고

Maven 설치

Programming/Java 2017.05.05 18:15 Posted by 파란크리스마스

Maven 설치

출처 : MAVEN 설치 및 Eclipse 연동하기 - FREESTROKES' Develog - Tistory

Maven 다운로드

Maven 다운로드 사이트에서 최신 Maven 파일(apache-maven-3.5.0-bin.zip)을 다운받아 적당한 폴더에 압축을 푼다. 

환경설정

환경 변수 MAVEN_HOME 를 설정

Maven의 bin 폴더 Path에 추가

환경변수 path 항목에 구분자(;) 와 함께 추가 %MAVEN_HOME%\bin 추가

JDK 설치후 JAVA_HOME 설정

Maven 설치 확인

명령 프롬프트에서 mvn --version 실행

Eclipse Maven 설정

Maven 설정 변경 (옵션)

%MAVEN_HOME%\conf\settings.xml 파일을 C:\spring\maven 폴더에 복사

복사한 settings.xml 수정 - localRepository 주석을 제거하고 적당한 폴더 설정

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <!-- localRepository
   | The path to the local repository maven will use to store artifacts.
   |
   | Default: ${user.home}/.m2/repository
  -->
  <localRepository>C:/spring/maven/repository</localRepository>

eclipse - maven user settings

이클립스 프로젝트 Maven 연동

출처 : HunIT Blog :: Eclipse〃이클립스에 메이븐(Maven) 연동 및 환경설정


저작자 표시
신고

Swift 3.1

Programming/IOS 2017.04.26 09:34 Posted by 파란크리스마스

Swift 3.1

출처 : mozilla-mobile/firefox-ios
아이폰 Swift 개발 #6 Web Browser App - Machine Learning and ...
[iOS] WebKit API 알아보기. : 네이버 블로그

세로모드 고정

출처 : Swift 3 how to lock orientation - Stack Overflow

override var shouldAutorotate: Bool {
    return false
}

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return UIInterfaceOrientationMask.portrait
}

 override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
    return UIInterfaceOrientation.portrait
}

override func viewDidLoad() {
    super.viewDidLoad()
}

URL 주소의 이미지 가져오기

출처 : swift3 - Swift 3: Display Image from URL - Stack Overflow

                let url = URL(string: hostUrl + (share_url as! String))
                NSLog("url = \(url?.absoluteString)")

                var data = NSData(contentsOf: url as! URL)
                var image = UIImage(data : data as! Data)

문자열 내장 합수

출처 : How does String.Index work in Swift 3
Index of a substring in a string with Swift

JavaScript(Alert,Confirm,Prompt)

출처 : WKWebViewでJavaScript(Alert,Confirm,Prompt)の処理
WKWebView 사용 시 필수적으로 넣어줘야 하는Delegate 넷.

오류 해결 / This application is modifying the autolayout engine from a background thread, which can lead to engine corruption

출처 : This application is modifying the autolayout engine from a background thread, which can lead to engine corruption - Stack Overflow

    func alert(message : String) {
        let alertView = UIAlertController(title: "파란크리스마스", message: message, preferredStyle: .alert)
        alertView.addAction(UIAlertAction(title: "확인", style: .default, handler: { (alertAction) -> Void in
            //logUserIn()
        }))
        //alertView.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
        DispatchQueue.main.async {
            self.present(alertView, animated: true, completion: nil)
        }
    }

배포

출처 : 내가 만든 iOS앱을 앱스토어에 배포해보자 - xCode로 소스 업로드하기 ...

저작자 표시
신고
TAG

JsonConfig 사용

Programming/Java 2017.04.23 16:48 Posted by 파란크리스마스

JsonConfig 사용하기

출처 : 알팅스님의 개발 스토리 : Java Object(POJO) To JSON String

Mybatis XML

	<resultMap id="resultMapUserInfo" type="map">
		<result property="user_id" column="user_id" javaType="java.lang.String"/>
		<result property="email" column="email" javaType="java.lang.String"/>
		<result property="mobile" column="mobile" javaType="java.lang.String"/>
		<result property="name" column="name" javaType="java.lang.String"/>
		<result property="point" column="point" javaType="int"/>
		<result property="reg_date" column="reg_date" javaType="java.util.Date"/>
		<result property="service_start_date" column="service_start_date" javaType="java.util.Date"/>
		<result property="service_end_date" column="service_end_date" javaType="java.util.Date"/>
	</resultMap>

	<!-- listUser -->
	<select id="listUser" parameterType="map" resultMap="resultMapUserInfo">
		select a.*
		  FROM user_info a
		 WHERE a.delete_yn = 'N'
	</select>

Java

	JsonConfig jsonConfig = new JsonConfig();
	jsonConfig.registerJsonValueProcessor(java.util.Date.class, new JsonValueProcessor() {

		@Override
		public Object processArrayValue(Object value, JsonConfig jsonConfig) {
			
			java.util.Date[] dates = (java.util.Date[]) value;
			Long[] result = new Long[dates.length];
			for (int index = 0; index < dates.length; index++) {
				result[index] = dates[index].getTime();
			}
			return result;
		}

		@Override
		public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
			java.util.Date date = (java.util.Date) value;
			return date.getTime();
		}
	});
	
	List<Map<String, Object>> listUser = service.listUser(null);
	jsonObjet.put("listUser", JSONArray.fromObject(listUser, jsonConfig));
저작자 표시
신고

Ubuntu 디스크 mount 하기

OS/Linux 2017.04.19 14:03 Posted by 파란크리스마스

Ubuntu 디스크 mount 하기

출처 : Mint & Latte_. :: 리눅스에서 하드디스크 mount 하기

추가된 디스트 Volume 확인

$ sudo fdisk -l
 
Disk /dev/vda: 42.9 GB, 42949672960 bytes
16 heads, 63 sectors/track, 83220 cylinders, total 83886080 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x000648d6
 
   Device Boot      Start         End      Blocks   Id  System
/dev/vda1            2048     3905535     1951744   82  Linux swap / Solaris
/dev/vda2   *     3905536    83885759    39990112   83  Linux
 
Disk /dev/vdb: 214.7 GB, 214748364800 bytes
16 heads, 63 sectors/track, 416101 cylinders, total 419430400 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

Disk /dev/vdb doesn't contain a valid partition table

파일시스템 생성

$ sudo mkfs.ext4 /dev/vdb
mke2fs 1.42.9 (4-Feb-2014)
Filesystem label=
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
Stride=0 blocks, Stripe width=0 blocks
13107200 inodes, 52428800 blocks
2621440 blocks (5.00%) reserved for the super user
First data block=0
Maximum filesystem blocks=4294967296
1600 block groups
32768 blocks per group, 32768 fragments per group
8192 inodes per group
Superblock backups stored on blocks: 
        32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208, 
        4096000, 7962624, 11239424, 20480000, 23887872
 
Allocating group tables: done                            
Writing inode tables: done                            
Creating journal (32768 blocks): done
Writing superblocks and filesystem accounting information: done

mount 받을 디렉토리 생성

$ sudo mkdir /bluexmas_db

mount 하기

$ sudo mount /dev/vdb /bluexmas_db

mount 확인

$ df -h
Filesystem      Size  Used Avail Use% Mounted on
udev            2.0G   12K  2.0G   1% /dev
tmpfs           396M  364K  395M   1% /run
/dev/vda2        38G  1.6G   35G   5% /
none            4.0K     0  4.0K   0% /sys/fs/cgroup
none            5.0M     0  5.0M   0% /run/lock
none            2.0G     0  2.0G   0% /run/shm
none            100M     0  100M   0% /run/user
/dev/vdb        197G   60M  187G   1% /bluexmas_db

unmount 하기

$ sudo umount /bluexmas_db

unmount 확인

$ df -h
Filesystem      Size  Used Avail Use% Mounted on
udev            2.0G   12K  2.0G   1% /dev
tmpfs           396M  372K  395M   1% /run
/dev/vda2        38G  9.2G   27G  26% /
none            4.0K     0  4.0K   0% /sys/fs/cgroup
none            5.0M     0  5.0M   0% /run/lock
none            2.0G     0  2.0G   0% /run/shm
none            100M     0  100M   0% /run/user

자동 mount

출처 : Ubuntu 14.04에 새로운 하드디스크 추가 및 포맷후 자동 마운트 설정

UUID 확인

$ sudo blkid
/dev/vda1: UUID="4874a47d-f878-440c-95d0-297e6733abea" TYPE="swap" 
/dev/vda2: UUID="20c996fb-8c20-4e7f-958e-84b7581af70f" TYPE="ext4" 
/dev/vdb: UUID="6e0b7ac6-d17d-4829-839f-80662339cf6b" TYPE="ext4" 
저작자 표시
신고

Ubuntu 리눅스 서버에 MySQL 5.7.x 설치

Database 2017.04.18 13:01 Posted by 파란크리스마스

Ubuntu 리눅스 서버에 MySQL 5.7.x 설치

출처 : Ubuntu server에 mysql 5.5.x 설치하기 -pupustory@- - Tistory
[Linux/CentOS] Mysql을 컴파일해서 설치해보자 - AT BLOG

리눅스 정보 조회

출처 : 리눅스 종류 확인, 리눅스 버전 확인 - 제타위키

$ cat /etc/*-release | uniq
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=14.04
DISTRIB_CODENAME=trusty
DISTRIB_DESCRIPTION="Ubuntu 14.04.3 LTS"
NAME="Ubuntu"
VERSION="14.04.3 LTS, Trusty Tahr"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 14.04.3 LTS"
VERSION_ID="14.04"
HOME_URL="http://www.ubuntu.com/"
SUPPORT_URL="http://help.ubuntu.com/"
BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"

리눅스 비트 확인

출처 : 리눅스 32비트 64비트 확인 - 제타위키

$ getconf LONG_BIT
64

관련패키지 설치

$ sudo apt-get update
$ sudo apt-get install gcc g++ libncurses5-dev libxml2-dev openssl libssl-dev curl libcurl4-openssl-dev libjpeg-dev libpng-dev libfreetype6-dev libsasl2-dev autoconf libncurses5-dev

MySQL 계정 만들기

$ sudo groupadd mysql
$ sudo useradd -g mysql -s /bin/bash -m mysql

cmake 설치

$ sudo apt-get install cmake

cmake 수동 설치(option)

$ wget http://www.cmake.org/files/v2.8/cmake-2.8.4.tar.gz
$ tar xvf cmake-2.8.4.tar.gz 
$ cd cmake-2.8.4
$ ./bootstrap
$ make all
$ sudo make install

MySQL 소스 다운로드

$ wget https://dev.mysql.com/get/Downloads/MySQL-5.7/mysql-5.7.18.tar.gz

MySQL 소스 압축풀기

$ tar xvf mysql-5.7.18.tar.gz

MySQL 컴파일 및 설치

$ cd mysql-5.7.18
$ sudo cmake \
-DCMAKE_INSTALL_PREFIX=/usr/local/mysql \
-DMYSQL_DATADIR=/usr/local/mysql/data \
-DMYSQL_UNIX_ADDR=/usr/local/mysql/mysql.sock \
-DSYSCONFDIR=/etc \
-DMYSQL_TCP_PORT=3306 \
-DMYSQL_USER=mysql \
-DDEFAULT_CHARSET=utf8 \
-DDEFAULT_COLLATION=utf8_general_ci \
-DWITH_EXTRA_CHARSETS=all \
-DENABLED_LOCAL_INFILE=1 \
-DWITH_INNOBASE_STORAGE_ENGINE=1 \
-DWITH_ARCHIVE_STORAGE_ENGINE=1 \
-DWITH_BLACKHOLE_STORAGE_ENGINE=1 \
-DDOWNLOAD_BOOST=1 -DWITH_BOOST=/usr/local/mysql/boost
$ sudo make
$ sudo make install

MySQL 데이터베이스 초기화

$ cd /usr/local/mysql
$ sudo ./bin/mysql_install_db --user=mysql --datadir=/usr/local/mysql/data
2017-04-18 17:17:26 [WARNING] mysql_install_db is deprecated. Please consider switching to mysqld --initialize
2017-04-18 17:17:30 [WARNING] The bootstrap log isn't empty:
2017-04-18 17:17:30 [WARNING] 2017-04-18T08:17:27.284367Z 0 [Warning] --bootstrap is deprecated. Please consider using --initialize instead
2017-04-18T08:17:27.303996Z 0 [Warning] Changed limits: max_open_files: 1024 (requested 5000)
2017-04-18T08:17:27.304005Z 0 [Warning] Changed limits: table_open_cache: 431 (requested 2000)

MySQL 설치 디렉토리 mysql 계정으로 권한 수정

$ sudo chown -R mysql:mysql /usr/local/mysql

환경설정

$ vi /usr/local/mysql/my.cnf

[mysqld]
# port=3306
init_connect=SET collation_connection = utf8_general_ci
init_connect=SET NAMES utf8
character-set-server=utf8
collation-server=utf8_general_ci
# table_cache=1024
max_connections=2048
max_user_connections=500
max_connect_errors=10000
wait_timeout=300
query_cache_type = 1
query_cache_size = 128M
query_cache_limit = 5M
slow_query_log
long_query_time=3
max_allowed_packet=16M
sort_buffer_size = 2M
# skip-innodb
skip-name-resolve
sql_mode = STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

[mysql]
default-character-set=utf8

[client]
default-character-set=utf8

MySQL 서비스 등록

서비스 mysqld 파일 복사

$ sudo cp /usr/local/mysql/support-files/mysql.server /etc/init.d/mysqld

mysqld 수정

$ sudo vi /etc/init.d/mysqld

mysqld파일을 열어서 basedir에 mysql이 설치된 디렉토리와 데이터 디렉토리(datadir)를 설정한다.

basedir=/usr/local/mysql
datadir=/usr/local/mysql/data

mysqld 서비스 등록

$ sudo update-rc.d mysqld defaults
 Adding system startup for /etc/init.d/mysqld ...
   /etc/rc0.d/K20mysqld -> ../init.d/mysqld
   /etc/rc1.d/K20mysqld -> ../init.d/mysqld
   /etc/rc6.d/K20mysqld -> ../init.d/mysqld
   /etc/rc2.d/S20mysqld -> ../init.d/mysqld
   /etc/rc3.d/S20mysqld -> ../init.d/mysqld
   /etc/rc4.d/S20mysqld -> ../init.d/mysqld
   /etc/rc5.d/S20mysqld -> ../init.d/mysqld

mysqld 서비스 실행

$ sudo service mysqld start
Starting MySQL
. * 
$ sudo service mysqld status
 * MySQL running (29565)
$ sudo service mysqld stop
Shutting down MySQL
. * 

root 암호 초기화

$ sudo ./bin/mysqld_safe --skip-grant-tables &
[1] 31008
mysql@localhost:/usr/local/mysql$ 2017-04-18T09:21:34.035860Z mysqld_safe Logging to '/usr/local/mysql/data/localhost.err'.
2017-04-18T09:21:34.050764Z mysqld_safe Starting mysqld daemon with databases from /usr/local/mysql/data

mysql@localhost:/usr/local/mysql$ ./bin/mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.18-log Source distribution

Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> use mysql
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> update user set authentication_string = password('sql') where user = 'root';

Query OK, 1 row affected, 1 warning (0.02 sec)
Rows matched: 1  Changed: 1  Warnings: 1

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

mysql> quit
Bye

사용자 추가

mysql> create user 'user1'@'%' identified by 'userpw';
mysql> grant all privileges on *.* to 'user1'@'%';
mysql> flush privileges;
저작자 표시
신고

MySQL 레코드 자동 생성

Database 2017.04.16 19:04 Posted by 파란크리스마스

MySQL 레코드 자동 생성

출처 : MySQL Row Generator - Use The Index, Luke
[MySQL] 무작위 샘플 데이터 만들기

View 생성

CREATE OR REPLACE VIEW generator_16
AS SELECT 0 n UNION ALL SELECT 1  UNION ALL SELECT 2  UNION ALL 
   SELECT 3   UNION ALL SELECT 4  UNION ALL SELECT 5  UNION ALL
   SELECT 6   UNION ALL SELECT 7  UNION ALL SELECT 8  UNION ALL
   SELECT 9   UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL
   SELECT 12  UNION ALL SELECT 13 UNION ALL SELECT 14 UNION ALL 
   SELECT 15;

CREATE OR REPLACE VIEW generator_256
AS SELECT ( ( hi.n << 4 ) | lo.n ) AS n
     FROM generator_16 lo, generator_16 hi;

CREATE OR REPLACE VIEW generator_4k
AS SELECT ( ( hi.n << 8 ) | lo.n ) AS n
     FROM generator_256 lo, generator_16 hi;

CREATE OR REPLACE VIEW generator_64k
AS SELECT ( ( hi.n << 8 ) | lo.n ) AS n
     FROM generator_256 lo, generator_256 hi;

CREATE OR REPLACE VIEW generator_1m
AS SELECT ( ( hi.n << 16 ) | lo.n ) AS n
     FROM generator_64k lo, generator_16 hi;

0부터 30까지 레코드 만들기

select *
  from generator_256
 where n < 31;

해당 월의 마지막 날까지 레코드 생성

MySQL의 내장함수 current_date로 오늘날짜를 가져와서 날짜함수 LAST_DAY로 해당 월의 마지막 일을 얻어 오고, DATE_FORMAT 함수의 %d로 일수를 조회 한 후에 generator_256 뷰를 이용해서 일수만큼 레코드를 생성해서 INTERVAL 을 이용해서 마지막 일자에서 n 필드의 값으로 빼면서 해당 월의 일수 만큼 레코드를 생성한다.

SELECT LAST_DAY(current_date) - INTERVAL n DAY dt
  FROM generator_256
 WHERE n < DATE_FORMAT(LAST_DAY(current_date), '%d');

해당 월의 통계 데이터 생성

select a.dt, IFNULL(SUM(b.level_request), 0)
  from (  SELECT LAST_DAY(current_date) - INTERVAL n DAY dt
            FROM generator_256
           WHERE n < DATE_FORMAT(LAST_DAY(current_date), '%d')
       ) a LEFT OUTER JOIN group2 b
       ON a.dt = DATE(b.date_request)
 group by a.dt
 order by a.dt
저작자 표시
신고

JQuery UI - Datepicker

Programming/JavaScript, Sencha 2017.04.09 18:57 Posted by 파란크리스마스

JQuery UI - Datepicker

출처 : Datepicker | jQuery UI
JQuery UI datepicker 한국어 적용 - 제타위키

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="<c:url value="/resources/js/jquery-1.12.0.js"/>"></script>
<script type="text/javascript" src="<c:url value="/resources/js/jquery-ui.js"/>"></script>
<link rel="stylesheet" href="<c:url value="/resources/css/jquery-ui.css"/>">
<title>Insert title here</title>
<script>
// Datepicker 오늘 날짜 설정
function setDatepickerToday(datepicker) {
	var d = new Date();
	datepicker.datepicker("setDate", new Date(d.getFullYear(), d.getMonth(), d.getDate()) );
}

// 한글화 설정
$.datepicker.setDefaults({
	dateFormat: 'yy-mm-dd',
	prevText: '이전 달',
	nextText: '다음 달',
	monthNames: ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'],
	monthNamesShort: ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'],
	dayNames: ['일', '월', '화', '수', '목', '금', '토'],
	dayNamesShort: ['일', '월', '화', '수', '목', '금', '토'],
	dayNamesMin: ['일', '월', '화', '수', '목', '금', '토'],
	showMonthAfterYear: true,
	yearSuffix: '년'
});

$( function() {
	// datepicker 생성
	$( "#datepicker" ).datepicker({
		// 날짜를 선택했을 경우 이벤트 발생
		onSelect: function (dateText, inst) {
			alert('날짜선택 = ' + dateText);
		}
	});
	
	// 오늘 날짜 설정
	setDatepickerToday($( "#datepicker" ));
});
</script>
</head>
<body>
 
<p>날짜 : <input type="text" id="datepicker"></p>

</body>
</html>
저작자 표시
신고


 

티스토리 툴바