프로그래밍 24

파이썬 "UnboundLocalError: local variable 'time' referenced before assignment"

파이썬에서 현재 timestamp를 얻기 위해 보통 import time을 하고 time.time() 함수를 호출한다. 그런데 UnboundLocalError: local variable 'time' referenced before assignment 라는 에러가 계속 발생했다. 수천번을 문제없이 썼던 간단한 코드라 황당해서 코드를 눈을 씻고 다시 살펴보았음. 알고보니 같은 함수에서 time이라는 이름으로 지역변수를 사용했고, 컴파일러는 time.time() 을 해석할 때 [지역변수: time].time()으로 받아들인 것. return이 있더라도 프로그램 흐름과 관계없이 컴파일 단계에서 지역변수로 인식하게 되는 것이다. global time을 넣어줘서 지역 변수 time이 아니라고 할 수 있긴 한데, ..

프로그래밍 2023.02.05

파이썬 datetime.utcnow()는 naive datetime 객체 반환

utcnow()를 썼다가 9시간 전 timestamp를 리턴하길래 찾아봄. https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow datetime — Basic date and time types — Python 3.10.5 documentation datetime — Basic date and time types Source code: Lib/datetime.py The datetime module supplies classes for manipulating dates and times. While date and time arithmetic is supported, the focus of the implementation is..

프로그래밍 2022.06.11

srand(...)와 rand() 난수 생성 시 주의 사항

돌아다니다가 눈에 띄이는 블로그 글(https://teus.me/834)을 하나 보게 되었다. Microsoft Visual C++에서 srand(...)와 rand()가 너무 심할 정도로 예측 가능한 패턴을 보인다는 것. 의사 난수 생성기(Pseudo Random Number Generator; PRNG)는 애초에 잘 사용하지 않지만 다시 한번 살펴보았다. #include #include #include #include #include #include int main() { while (true) { unsigned int seed = (unsigned int)time(NULL); srand(seed); int n1 = rand(); int n2 = rand(); printf("%d, %d, %d\n"..

프로그래밍 2022.05.22

[Rust] 숫자 맞추기 (guessing)

https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html 을 그대로 따라해보았다. 이번에는 cargo new 을 사용하여 프로젝트 디렉토리를 생성하였다. 02_guessing (디렉토리) src (디렉토리) main.rs target (디렉토리) // 실행 파일은 여기에 생성됨. (.gitignore에 포함) Cargo.toml Cargo.lock // 자동으로 package 정보들이 생성되는데 (.gitignore에 포함) Cargo.toml 에는 프로젝트에 관한 정보가 들어가게 된다. Cargo.toml [package] name = "guessing" version = "0.1.0" edition = "2021" [dependencies..

프로그래밍 2021.11.08

[Rust] 간단한 hello world 프로그램

Firefox나 Ethereum의 parity 클라이언트가 rust로 작성되었는데, 나름대로 언어의 장점(compile-time에서의 memory management)이 있는 것 같아 습득을 해보려고 한다. 튜토리얼 (https://www.rust-lang.org/learn) 페이지를 보면서 간략하게 남겨봄. 설치는 (https://forge.rust-lang.org/infra/other-installation-methods.html)에서 rustup-init.exe을 실행하면 된다. 패키지 관리는 cargo 라는 명령어가 있고, 컴파일은 rustc 를 사용한다고 한다. 프로젝트 폴더를 하나 만든 다음에 main.rs 파일을 만들었다. fn main(){ println!("hello world!"); }..

프로그래밍 2021.10.31

[Python] "nonlocal" 키워드

전역변수 (global variable)를 접근할 때 사용하는 global 키워드에 비하면 생소하지만 nonlocal 키워드라는 것도 있다. 함수 안에서 변수를 정의하면 지역변수 (local variable)를 선언하게 되는데 nonlocal이 붙으면 지역변수를 의미하는 것이 아니라 그 함수를 바깥에 있는 t를 의미한다고 한다. t = 0 # def foo1(): t = 1 # def foo2(): t = 2 # def foo3(): nonlocal t # t = 3 print("Q1:", t) foo3() print("Q2:", t) print("Q3:", t) foo2() print("Q4:", t) print("Q5:", t) foo1() print("Q6:", t) 우선 print 출력 순서는 Q..

프로그래밍 2021.10.19

윈도우용 RunCat의 CPU 사용량 표기 오류 고치기

RunCat은 iStat 같은 프로그램이다. CPU 사용량이 많아지면 고양이가 빨리 뛴다... 윈도우용은 https://github.com/Kyome22/RunCat_for_windows/ 에서 다운로드 받을 수 있는데, GitHub - Kyome22/RunCat_for_windows: A cute running cat animation on your windows taskbar. A cute running cat animation on your windows taskbar. - GitHub - Kyome22/RunCat_for_windows: A cute running cat animation on your windows taskbar. github.com 툴팁으로 표시되는 숫자와 작업 관리자에 있는 ..

프로그래밍 2021.08.21

[Python] 한글 자음 모음 재조합

한글 파일 이름의 초성, 중성, 종성이 분리되는 현상이다. 유니코드에서 NFC, NFKC, NFD, NFKD와 관련된 현상이다. 여러 운영체제 {Windows, Linux, Mac} x 다양한 압축 파일 {ZIP, RAR, TAR} x 클라우드 {Dropbox, OneDrive, Google Drive} 등을 사용하다 보면 흔하게 발생한다. 보통 구글에서 export 한 파일들이 저랬던 것으로 기억을 한다. '한'은 composed form이고, 'ㅎㅏㄴ'은 decomposed form이다. C는 composition, D는 decomposition을 의미한다. NFKC와 NFKD는 compatibility 어쩌고저쩌고 하던데 정확한 규칙은 찾아보지 않았다. 별의별 언어들, 표기 방식, 표기 방향, 각종..

프로그래밍 2020.07.14

[Python] 모듈 상대 경로 문제는 PYTHONPATH 환경 변수 사용

PYTHONPATH 환경 변수 설명 PYTHONPATH Augment the default search path for module files. The format is the same as the shell’s PATH: one or more directory pathnames separated by os.pathsep (e.g. colons on Unix or semicolons on Windows). Non-existent directories are silently ignored. In addition to normal directories, individual PYTHONPATH entries may refer to zipfiles containing pure Python modules (in ..

프로그래밍 2020.04.17

[Python] 시간이 오래 걸리는 함수 결과 파일에 저장하기 (cache)

a,b,c = get_cached_result("20200214-781199f1", lambda: sim_queue_length(sim_params)) 시간이 오래 걸리는 함수의 결과를 파일에 저장하기 위한 도움 함수(helper function)를 간단하게 만들어봤다. 참고로 메모리에 caching 할 때는 functools 모듈의 lru_cache 같은 것들을 쓰면 좋다. (https://docs.python.org/3/library/functools.html) 캐시 파일에 이미 실행 결과가 있으면 그대로 불러오고, 없으면 func를 실행한 다음, 캐시 파일에 쓴다. def get_cached_result(cache_name, func): cache_file = "{}.pickle".format(ca..

프로그래밍 2020.02.14