2018년 8월 14일 화요일

[C] 데이터타입 숫자 범위

[출처] http://mwultong.blogspot.com/2006/09/c-char-int-float-data-type-ranges.html

[정수형] 

▶ char, unsigned char          1 byte (8비트)
------------------------------------------------------
char 의 최소값: -128
char 의 최대값: 127

unsigned char 의 최소값: 0
unsigned char 의 최대값: 255 (0xff)



▶ short, unsigned short        2 bytes (16비트)
------------------------------------------------------
short 의 최소값: -32768
short 의 최대값: 32767

unsigned short 의 최소값: 0
unsigned short 의 최대값: 65535 (0xffff)


▶ wchar_t 또는 __wchar_t       2 bytes (16비트)
------------------------------------------------------
wchar_t 의 최소값: 0
wchar_t 의 최대값: 65535

※ wchar_t 는 유니코드 글자 1개를 저장합니다. "unsigned short"과 동일.



▶ int, unsigned int            4 bytes (32비트)
------------------------------------------------------
int 의 최소값: -2147483648
int 의 최대값: 2147483647

unsigned int의 최소값: 0
unsigned int의 최대값: 4294967295 (0xffffffff)



▶ long, unsigned long          4 bytes (32비트)
------------------------------------------------------
long 의 최소값: -2147483648L
long 의 최대값: 2147483647L

unsigned long 의 최소값: 0UL
unsigned long 의 최대값: 4294967295UL (0xffffffffUL)

※ 32비트OS에서의 long 은 int 와 동일



▶__int64 또는 long long        8 bytes (64비트)
------------------------------------------------------
__int64 의 최소값: -9223372036854775808i64
__int64 의 최대값: 9223372036854775807i64

unsigned __int64 의 최소값: 0ui64
unsigned __int64 의 최대값: 18446744073709551615ui64 (0xffffffffffffffffui64)


[실수형] 

▶ float                        4 bytes (32비트)
------------------------------------------------------
가장 작은 양수: 1.175494351e-38F
가장 큰 양수  : 3.402823466e+38F



▶ double                       8 bytes (64비트)
------------------------------------------------------
가장 작은 양수: 2.2250738585072014e-308
가장 큰 양수  : 1.7976931348623158e+308



▶ long double                  8 bytes (64비트)
------------------------------------------------------
double 과 같음.

[MFC] 파일입출력

[출처] http://phiru.tistory.com/138

// 읽기(바이너리로 읽기) 
// 쓰기(바이너리로 쓰기)

CFile rawData;              // 읽을 파일
CFile processData,            // 쓸 파일
CFileException proEx, rawEx;        // 예외

if(!rawData.Open(strFullPath, CFile::modeRead | CFile::typeBinary, &rawEx))  // 오류 체크
{
AfxMessageBox("rawData exception!");
rawData.Close();
return;
}

if(!processData.Open(strProData, CFile::modeCreate | CFile::modeWrite | CFile::typeBinary, &proEx))
{
AfxMessageBox("ProcessData exception!");
processData.Close();
return;
}

UINT nRet = 0;                                // 읽은 크기
char buffer[KD_BUFFER_SIZE];        // 읽을 버퍼 싸이즈

while(1)
{
ZeroMemory(buffer, sizeof(buffer));
nRet = rawData.Read(buffer, sizeof(buffer)); // 읽기
if(nRet == sizeof(buffer))                                               // 읽을 데이터가 남아있다(확률적으로 맞지)
{
processData.Write(buffer, sizeof(buffer));        // 사실 이거 만들때는 조건이 있어서 일케 분류했다.
}
else // 파일이 끝부분일 경우(안맞을 확률 1/버퍼 싸이즈)
{
processData.Write(buffer, sizeof(buffer));
break;
}
}

// 다 읽고 썼으니깐 핸들 닫자
processData.Close();
rawData.Close();

// 파일 잘 되었는지 친절히 폴더도 열어주자
ShellExecute(NULL, "open", dataDir, NULL, NULL, SW_SHOWNORMAL);

------------------------------------------------------------------------------------------
std::fstream rawData;                    // 읽고 쓸 파일.(여기에서는 덮어쓰기한다. 요고 디지게 찾았다)
std::fstream headerData;                // 읽을 파일(이걸 읽어서 rawData에 덮는 식으로 예제를 짰다)

rawData.open(cFileFullPath, std::ios::binary | std::ios::out | std::ios::in);        // Open할때 바이너리, 읽고 쓰기로.
if(!rawData.is_open())    // 잘 열렸는지 인. 아니면 오류 났다고 해주자
{
// 현재 fstream은 unicode가 안되어서?? 잘 모르겠지만 경로에 한글 있음 안된다.
MessageBox("File Open Error.(Don't use Korean title)", "Error", 0);
printf("error\n");
rawData.close();
return;
}

headerData.open(cHeaderPath, std::ios::binary | std::ios::in);     // 바이너리로 하고 읽기로.
if(!headerData.is_open())
{
MessageBox("File Open Error.(Don't use Korean title)", "Error", 0);
printf("error\n");
headerData.close();
return;
}

char buffer[KD_BUFFER_SIZE];
memset(buffer, 0, sizeof(buffer));
headerData.read(buffer, sizeof(buffer));        // 읽기
int size = strlen(buffer);                            // 읽은 사이즈 한번 보고
rawData.write(buffer, sizeof(buffer));            // 쓴다. 덮어서!
rawData.flush();                                    // 적용!!
rawData.close();                            // 닫어
headerData.close();                        // 요곳도 닫어

2018년 7월 23일 월요일

[python] 인터넷강의

경영학과 출신 교수님이 본인이 공부하고 계신 사이트를 소개해 주셨다.
들어보니 강의 스킬이 좋은 것 같다.
파이선 공부는 아래 사이트에서 하면 좋을 듯.

2018년 6월 16일 토요일

[공개강좌] 선형대수

살면서 정말 멋진 강의를 만나는 것은 행운이다.
나는 대학원때 그런 강의를 2번 석사를 마치고 사회에서 개발자로 일하고 있을 때 1번, 이렇게 3번 있었다.
다음 강의 또한 정말 멋지다.

MIT 공개강의 - 선형대수

by Professor Gilbert Strang.

[딥러닝] 캡슐네트워크

힌톤교수가 제안하여 더욱 주목을 받았던 신경망이었지만,
미루고 미루다 이제야 살펴보았다.
의미있다.
앞으로 많은 진전이 있을 것 같다.
Dynamic Routing과 Equivariance에 대한 Aurelien Geron의 설명력은 정말 대단하다.

2018년 5월 23일 수요일

[python] 문법10

--------------------------------------------------------------------------------
#
# 이벤트처리
#
--------------------------------------------------------------------------------
# 화면에 마우스클릭 위치까지 선그리기

import turtle

t = turtle.Turtle()

def drawit(x, y):
#t.penup()
t.goto(x, y)
t.write("click")

s = turtle.Screen()
s.onscreenclick(drawit) #onscreenclick( ) 여기 괄호 안에 들어가는 함수는 변수 2개를 갖도록 되어 있다.

turtle.done()

# 윈도우프로그래밍 = 이벤트처리 프로그래밍
# "스크린 윈도우"에서 "클릭" 이벤트에 대해 클릭위치에 click 출력하는 "처리"를 한 예제
# 터틀에서 하는 방법일 뿐.
# 보다 범용적인 방법 필요: Tk, Qt

--------------------------------------------------------------------------------
# 사건기반(event-driven) 프로그래밍 (~ 윈도우프로그래밍)
# 대표적인 사건: 마우스클릭, 키보드입력 ...
# 사건이 발생되는 토대: 윈도우

[윈도우에서 사건기반 프로그래밍]
- with Turtle in Python
- Win32 API in C
- MFC in C++
- C#, VB
- Java
- Qt in C++

[코딩요소]
- 윈도우생성
- 이벤트처리
- 메세지처리 반복(루프)

[기타]
- 부모윈도우 - 자식윈도우 관계 설정
--------------------------------------------------------------------------------
from tkinter import *

window = Tk()
button = Button(window, text="클릭")
button.pack() # 일단 그냥 하는 걸로

window.mainloop()

----------------------------------------
이벤트 처리 1:
- command; 버튼 클릭할 때 발생; 메뉴 아이템 클릭
----------------------------------------
from tkinter import *

def process():
print("안녕하세요?")

window = Tk()

button = Button(window, text="눌러봐", command=process)
#  버튼에서, command (클릭) 이벤트가 발생하면 process 함수를 호출해라

button.pack()

window.mainloop()

----------------------------------------
윈도우 크기 및 배치
----------------------------------------
from tkinter import *

def process():
print("안녕하세요?")

window = Tk()
window.title('my first window')
window.geometry("500x500")
window.resizable(0, 0)

button = Button(window, text="클릭", command=process)
btn.place(x=0, y=0, width=100, height=100)

# btn.destroy()

window.mainloop()

# 기타 배치관리자: pack; grid;
# 웹브라우저(부모 윈도우)같이 윈도우의 크기가 (확대/축소)변경되는 경우 pcak, grid가 유용할 수 있음
----------------------------------------
에딧 윈도우
----------------------------------------
from tkinter import *

def onHello():
    msg = edt.get()
    edt2.insert(10, msg)

window = Tk()
window.title('my first window')
window.geometry("500x500")
window.resizable(0, 0)

btn = Button(window, text='hello', command=onHello)
btn.place(x=0, y=0, width=100, height=100)

edt = Entry(window, bg='white', fg='black')
edt.place(x=100, y=0, width=200, height=100)

edt2 = Entry(window, bg='white', fg='red')
edt2.place(x=100, y=100, width=200, height=100)

window.mainloop()

[참고자료]
http://effbot.org/tkinterbook/
https://www.tutorialspoint.com/python/tk_button.htm
https://www.python-course.eu/tkinter_layout_management.php

----------------------------------------
이벤트처리2

bind()
: 마우스 움직임 이벤트

printxy(event): event
----------------------------------------
from tkinter import *

def printxy(event):
    print(event.x, event.y)

window = Tk()
window.title("my")
window.geometry("500x500")
window.resizable(0, 0)

window.bind("", printxy)

window.mainloop()

[참고자료]
https://docstore.mik.ua/orelly/other/python/0596001886_pythonian-chp-16-sect-9.html

----------------------------------------
캔바스 - 그림 그리는 함수가 포함되어 있음
create_oval(x1, y1, x2, y2, fill="blue")

----------------------------------------
#
#   오른쪽 버튼 다운 이벤트
#   왼쪽버튼 누른 상태에서 마우스 이동 이벤트
  마우스 이동 이벤트
#

from tkinter import *

mycolor = "blue"

def paint(event):
    x1, y1 = ( event.x-5 ), ( event.y-5 )
    x2, y2 = ( event.x+5 ), ( event.y+5 )
    canvas.create_oval( x1, y1, x2, y2,  fill = mycolor)

def changeColor():
    global mycolor
    mycolor="red"

def toggleColor(event):
    global mycolor
    if (mycolor == "red"):
        mycolor="blue"
    else:
        mycolor="red"

window = Tk()
window.bind("", toggleColor)

canvas = Canvas(window)
canvas.pack()
canvas.bind("", paint)

button = Button(window, text="red", command=changeColor)
button.pack()

window.mainloop()

[참고자료]
http://www.python-course.eu/tkinter_layout_management.php
http://zetcode.com/gui/tkinter/layout/

--------------------------------------------------------------------------------
윈도우 생성 함수와 이벤트 처리 함수를 하나로 묶어 보자
--------------------------------------------------------------------------------
'''https://docs.python.org/3.5/library/tk.html'''

from tkinter import *

class MyButton(Button):
    def __init__(self, window):
        self.button = Button(window, text = "저를 클릭해주세요", command = self.Sum)
        self.button.pack()

    def Sum(self):
        sum = 0
        for i in range(1, 11):
            sum += i
        print("합계 : ", sum)

def main():
    window =Tk()
    a = MyButton(window)
    a.Sum()
    window.mainloop()

main()


#
# 부연설명
#

Tk() -> 뭔가를 만든다 ~ 생성
MyButton() -> 뭔가를 만든다 ~ 생성

이렇게 생성된 것들을 통칭해서 부르는 단어가 있으면 좋겠다 -> "객체; Object"

Tk() -> Tk 객체 생성
MyButton() -> MyButton 객체 생성

객체가 생성되면서 자동으로 호출되는 함수가 바로 __init__() 함수이다.

이와 같이 객체를 생성하려면, 미리 객체를 정의해 두어야 한다.

객체를 정의하는 방법은,

class 로 시작해서 위와 같이 몇 가지 규칙을 따라 작성해야 한다.

__init__() 함수가 반드시 있어야 한다.

class 내부에서 정의하는 함수들 사이에서 공동으로 사용하는 변수는 self.를 앞에 붙인다.

class 내부에서 정의하는 함수를 호출할 때도 self.를 앞에 붙인다.

class 내부에서 정의한 함수를 사용하려면 다음과 같은 형식을 취한다.

a.Sum()

미리 작성해 둔 class가 갖고 있는 함수나 변수를 유지하면서, 새롭게 함수나 변수를 추가해서 class를 정의하려면 위와 같이 객체이름 뒤 괄호안에 class이름을 넣는다.

class MyButton(Button)

그렇지 않은 경우, 다음과 같이 생략하면 된다.

class MyButton()

위 코드를 안보고 타이핑 가능해야 한다.

[참고자료]
http://zetcode.com/gui/tkinter/layout/
--------------------------------------------------------------------------------