전체 글 229

(React) useState 값 변경

1. 독립변수  선언const [value, setValue] = useState(0);새로운 값을 설정 setValue(3)}>click 기존 값을 변경 setValue(prev => prev + 1)}>click 2. 리스트 변수선언const [value, setValue] = React.useState(["a", "b", "c"]); 초기화  setValue([ ])}>click 값 추가 setValue(prev => [...prev, "d"])}>click 특정값 삭제 setValue(prev => prev.filter(item => item !== "a"))}>click 특정 인덱스 삭제 setValue(prev => prev.filter((item, index) => index !== 0))}..

(React) form data event 처리

아래와 같은 form 디자인이 있고 입력데이터를 보관하기 위해 오른쪽과 같이 useState 를 정의 할 수 있다.const [data, setData] = useState( {             address1: "",             address2: "",             zip: "",             city: "",             state: "",             country: "",  }); 이벤트 정의의 비효율 코드와 효율적인 코드 예비효율적 코드효율적 코드control의 이름을 onChange의 argument로 전달control 의 name 프로퍼티를 지정하고 event.target.name 으로 꺼내서 사용 const onChange = (key) ..

Thread vs ThreadPool vs ThreadPoolExecutor

ThreadThreadPool ThreadPoolExecutor생성쓰레드 수수동 Thread 1 = Task 1개파라미터로 지정가능디폴트=(논리CPU수 + 4)파라미터로 지정가능디폴트=(논리CPU수 + 4)최적의 용도적은 수로 동시에 실행이 필요한 경우모든 쓰레드가 동시에 실행되지는 않고 비어 있거나 I/O 등의 기다림이 있어 양보된 쓰레드에 실행되게 된다.같은 태스크 내용으로 파라미터만 달리하여 많은 수의 쓰레드를 실행하는 경우.모든 쓰레드가 동시에 실행되지는 않고 비어 있거나 I/O 등의 기다림이 있어 양보된 쓰레드에 실행되게 된다. 같은 태스크 내용으로 파라미터만 달리하여 많은 수의 쓰레드를 실행하는 경우.결과의 리턴불가능가능가능취소기능불가능불가능실행되기 전의 태스크에 한해가능※ ThreadPool..

data science/python 2024.05.11

(React) useCallback

function factory(a, b) {    return a + b; } const sumFunc1 = factory(); const sumFunc2 = factory();console.log(sumFunc1(1, 2)); // => 3 console.log(sumFunc2(1, 2)); // => 3console.log(sumFunc1 === sumFunc2); // => false console.log(sumFunc1 === sumFunc1); // => true같은 factory함수를 가르킨다고 해도 인스턴스 오브젝트는 서로 다르다. 또한 렌더링이 자주 반복되는 경우에도 이전 인스턴스와는 다른 sumFunc1과 sumFunc2 인스턴스가 생성된다. 그럼 언제 useCallback 필요할까?일단..

(React) map 에 의한 루프에서 표시가 되지 않는 문제

{  } 로 감싸여져 있는 경우 반드시 return 이 없는 경우 아무것도 표시되지 않는다.return (     { this.state.task.map((item,contentIndex) => {                   ( hello {item.event} {item.eventpara} ) })               }     ) 해결책 1) return 을 명시return (     { this.state.task.map((item,contentIndex) => {                 return ( hello {item.event} {item.eventpara} ) })              }    ) 해결책 2) { } 를 제거return (       { this...

(React) 무한 렌더링 원인과 방지

const [count, setCount] = useState(0);const handlecart= (item) => {          setCount(count+1);          setItem(item);}무한 렌더링을 유발하는 코드handlecart(item)}>cart 위의 코드는 handlecart 함수의 참조를 패스하는게 아니라 함수 자체를 호출하고 있다. 따라서 인위적으로 클릭하기 전에 인터프리터가 코드를 파스할 시에 함수를 실행하게 된다. 이로인해 함수내에서 스테이트는 업데이트되고 화면은 다시 렌더링하게 되서 무한 루프에 빠지게 된다.   따라서 해결책은 함수의 참조를 설정하는 것이다.() => handlecart(product)}>cart

threading / multiprocessing / asyncio

wikipedia에서 랜덤 100 페이지의 타이틀을 화일로 저장하는 샘플로서 multiprocessing과 async 를 이용하여 처리속도의 향상을 보여주고 있다.multiprcessing : 계산등의 CPU 의존적인 처리에 유리 async : 화일 I/O, 네트워크 I/O 등의 Blocking처리에 유리위의 둘을 이용하여 처리속도를 향상import asyncio                                         # Gives us async/await import concurrent.futures                        # Allows creating new processes import time from math import floor               ..

data science/python 2024.05.02

json

json.dumps vs json.jsonify return json.dumps({"language" : "python"}) return jsonify({"language" : "python"})자동으로 header 의 Content-Type  을 text/html; charset=utf-8 로 설정※ 수동으로 header 를 변경해 줘야 함.자동으로 header 의 Content-Type  을 application/json 로 설정 json.jsonify 와 함께 스테터스 코드로 함께 리턴 return jsonify({"language" : "python"}), 204 리턴하는 한글(비영어) 깨짐 해결 app.config["JSON_AS_ASCII"] = False frontend로부터의 json 데이..

image byte 데이터 <-> numpy string

인터넷 스트림으로 이미지를 전송할 경우 이미지 데이터는 string 형식으로 변환해야 한다.import numpy as np import base64 import sys def base64_encode_image(a):     # base64 encode the input NumPy array     return base64.b64encode(a).decode("utf-8") def base64_decode_image(a, dtype, shape):     # if this is Python 3, we need the extra step of encoding the     # serialized NumPy string as a byte object     if sys.version_info.major =..

data science/python 2024.04.29

Idioms 5개

1. 행동이 앞서다. 옛날 총소리로 출발신호를 알리기 전에 먼전 출발하는 것에 유래. Don't jump the gun! Wait for me! 앞서가지 말고 날 기다려! You jumped the gun. You should have waited for me. 너무 앞서 갔다구! 날 기다려야 했어. 2. 개운치 않게 잠에서 깨다. 찌푸둥 하다. 3. (면접, 첫인사, 미팅등) 좋은 인상을 주려 최상의 자신을 표현하다. 4. 어려운 상황이 닥쳤을때 최선을 다하다. 복싱에서 상대방의 펀치를 살짝 비켜 충격을 최소하는 것에 유래. 5. 여유를 가져라. 1960년대 골프선수의 자서전에서 유래. You need to stop and smell the roses. You're working too much.

youtube english 2024.04.16