yeomko22 / til Goto Github PK
View Code? Open in Web Editor NEWToday I learned
Today I learned
Summarize ML course of Andrew ng.
$ export KAFKA_HEAP_OPTS="-Xmx400m -Xms400m"
$ dig algoexprt.io
; <<>> DiG 9.10.6 <<>> algoexpert.io
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 62516
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;algoexpert.io. IN A
;; ANSWER SECTION:
algoexpert.io. 3600 IN A 35.202.194.70
;; Query time: 61 msec
;; SERVER: 61.41.153.2#53(61.41.153.2)
;; WHEN: Wed Jun 23 16:41:00 KST 2021
;; MSG SIZE rcvd: 58
# 로컬 영역에서 TCP나 UDP 통신을 수신하기 위해 포트를 개방
$ nc -l 8021
# 로컬 컴퓨터의 8021 포트로 접속, TCP 통신을 수행
$ nc 127.0.0.1 8021
def merge(arr, l, m, r):
n1 = m - l + 1
n2 = r- m
# create temp arrays
L = [0] * (n1)
R = [0] * (n2)
# Copy data to temp arrays L[] and R[]
for i in range(0 , n1):
L[i] = arr[l + i]
for j in range(0 , n2):
R[j] = arr[m + 1 + j]
# Merge the temp arrays back into arr[l..r]
i = 0 # Initial index of first subarray
j = 0 # Initial index of second subarray
k = l # Initial index of merged subarray
while i < n1 and j < n2 :
if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
# Copy the remaining elements of L[], if there
# are any
while i < n1:
arr[k] = L[i]
i += 1
k += 1
# Copy the remaining elements of R[], if there
# are any
while j < n2:
arr[k] = R[j]
j += 1
k += 1
# l is for left index and r is right index of the
# sub-array of arr to be sorted
def mergeSort(arr,l,r):
if l < r:
# Same as (l+r)//2, but avoids overflow for
# large l and h
m = (l+(r-1))//2
# Sort first and second halves
mergeSort(arr, l, m)
mergeSort(arr, m+1, r)
merge(arr, l, m, r)
python에서 str은 불변 객체이다. 왜일까?
python은 원시 타입을 지원하는가? 그렇지 않다면 그 이유는?
python은 원시 타입을 지원하지 않는다. python에서 모든 자료형은 객체로 취급된다. 이는 언어 차원에서 강력한 기능을 제공해서 사용자의 편의성을 높이기 위한 조치이다.
python이 느린 이유를 아는대로 설명하라
먼저 인터프리터 언어이기 때문에 컴파일이 없다. 코드 한 줄씩 기계어로 번역하여 실행하다 보니 오버헤드가 발생한다. 다음으로 원시 타입을 지원하지 않는다. 때문에 연산을 많이 수행할 때 오버헤드가 발생한다. 마지막으로 GIL의 존재로 멀티 코어를 활용한 성능 향상을 구현하는데 한계가 있다.
GIL을 설명하라
python interpreter가 관리하는 일종의 mutex로 한번에 하나의 스레드가 코어를 점유하게끔 한다. 따라서 python 단에서 여러 쓰레드를 사용한다 하더라도 실제 하드웨어 코어는 하나만 사용하게 된다. 파이썬에서 멀티 코어를 활용하려면 멀티 프로세스를 사용해야 한다.
python에서 숫자는 int로만 처리된다. 다른 언어는 크기별로 다양한 타입을 지원하는데 어떻게 가능할까?
python에서의 int는 객체이다. 그리고 이는 무제한 자릿수 기능을 제공한다. int는 정수를 숫자의 배열로 간주한다. 즉, 자릿수 단위로 쪼개어 배열 형태로 표현한다. 이는 언어 차원에서 지원하는 강력한 기능이지만 그만큼 계산 성능과 메모리 사용량을 포기하는 조치이다.
list를 dictionary의 키 값으로 사용할 수 없는 이유를 설명하라
list는 mutable한 자료형이다. dictionary는 키 값을 hash 하는데 키 값이 변경 가능하면 안된다. 따라서 list는 키 값으로 사용이 불가하고, immutable한 tuple은 사용 가능하다.
list comprehension을 설명하라
list 문법을 사용해서 새로운 list를 정의하는 기법으로 가독성이 좋아 python에서 많이 사용된다. map이나 filter같은 함수형 문법의 사용보다 list comprehension을 사용하는게 더 pythonic하다고 권장된다.
generator를 설명하라
yeild를 사용하여 생성이 가능, 리턴값을 전달하고 반복의 위치를 기억, 다음번 호출 시엔 그 다음 시행을 한 뒤 값을 리턴해주어 메모리 efficient하게 반복을 구현할 수 있다. 딥 러닝에서 data loader를 만들 때 사용하기도 한다.
class TestIrisPredictions(unittest.TestCase):
def setUp(self):
# We prepare both pipelines for use in the tests
self.pipeline_v1 = SimplePipeline()
self.pipeline_v2 = PipelineWithDataEngineering()
self.pipeline_v1.run_pipeline()
self.pipeline_v2.run_pipeline()
# the benchmark is simply the same classification value for
# for every test entry
self.benchmark_predictions = [1.0] * len(self.pipeline_v1.y_test)
def test_accuracy_higher_than_benchmark(self):
# Given
benchmark_accuracy = accuracy_score(
y_true=self.pipeline_v1.y_test,
y_pred=self.benchmark_predictions)
predictions = self.pipeline_v1.predict(self.pipeline_v1.X_test)
# When
actual_accuracy = accuracy_score(
y_true=self.pipeline_v1.y_test,
y_pred=predictions)
# Then
print(f'model accuracy: {actual_accuracy}, benchmark accuracy: {benchmark_accuracy}')
self.assertTrue(actual_accuracy > benchmark_accuracy)
def test_accuracy_compared_to_previous_version(self):
# When
v1_accuracy = self.pipeline_v1.get_accuracy()
v2_accuracy = self.pipeline_v2.get_accuracy()
print(f'pipeline v1 accuracy: {v1_accuracy}')
print(f'pipeline v2 accuracy: {v2_accuracy}')
# Then
self.assertTrue(v2_accuracy >= v1_accuracy)
describeCluster(DescribeClusterOptions options)
listTopics(ListTopicsOptions options)
listConsumerGroups(ListConsumerGroupsOptions options)
createTopics(Collection<NewTopic> newTopics, CreateTopicsOptions options)
createPartitions(Map<String, NewPartitions> newPartitions, CreatePartitionsOptions options)
createAcls(Collection<AclBinding> acls, CreateAclsOptions options)
import typing as t
def add_two_integers(first: int, second: t.Optional[int] = None) -> int:
"""Sum two numbers."""
result = first
if second:
result = first + second
return result
class User(BaseModel):
id: int
name = 'John Doe'
signup_ts: Optional[datetime] = None
friends: List[int] = []
async def read_data(db):
pass
@types.coroutine
def process_data(db):
data = yield from read_data(db)
...
from aiohttp import web
async def hello(request):
await db.execute("SELECT * FROM tbl")
return web.Response(text="Hello, world")
app = web.Application()
app.add_routes([web.get('/', hello)])
web.run_app(app)
async def application(scope, receive, send):
event = await receive()
await send(
{"type": "websocket.send", ...}
)
async def app(scope, receive, send):
assert scope["type"] == "http"
await send({
"type": "http.response.start",
"status": 200,
"headers": [
(b"content-type", "text/plain"),
],
})
await send({
"type": "http.response.body",
"body": b"Hello, world!",
})
class PipelineWithConfig(SimplePipeline):
def __init__(self, config):
# Call the inherited SimplePipeline __init__ method first.
super().__init__()
# Pass in a config object which we use during the train method.
self.config = config
def train(self, algorithm=LogisticRegression):
# note that we instantiate the LogisticRegression classifier
# with params from the pipeline config
self.model = algorithm(solver=self.config.get('solver'),
multi_class=self.config.get('multi_class'))
self.model.fit(self.X_train, self.y_train)
class TestIrisConfig(unittest.TestCase):
def setUp(self):
# We prepare the pipeline for use in the tests
config = {'solver': 'lbfgs', 'multi_class': 'auto'}
self.pipeline = PipelineWithConfig(config=config)
self.pipeline.run_pipeline()
def test_pipeline_config(self):
# Given
# fetch model config using sklearn get_params()
# https://scikit-learn.org/stable/modules/generated/sklearn.base.BaseEstimator.html#sklearn.base.BaseEstimator.get_params
model_params = self.pipeline.model.get_params()
# Then
self.assertTrue(model_params['solver'] in ENABLED_MODEL_SOLVERS)
set ts=4
set sw=4
set et
set hls
set nu
syntax on
call plug#begin('~/.vim/plugged')
Plug 'davidhalter/jedi-vim'
let g:jedi#show_call_signatures=0 " 자세히 설명하는 창을 보여준다 1=활성화, 0=비>활성화
let g:jedi#popup_select_first="0" " 자동완성시 자동팝업 등장 x
let g:jedi#force_py_version=3 " 자동완성 3 = python3 , 2 = python2
Plug 'hynek/vim-python-pep8-indent' " python 자동 들여쓰기 Plugin
filetype plugin indent on " python 자동 들여쓰기 on
Plug 'nvie/vim-flake8' " python 문법 검사 plugin
let g:syntastic_python_checkers=['flake8'] " ↓ 실행시 현재줄 주석 해제필요
" let g:syntastic_python_flake8_args='--ignore=' " 무시하고자 하는 errorcode
Plug 'preservim/nerdtree'
call plug#end()
public class SimpleProducer {
private final static Logger logger = LoggerFactory.getLogger(SimpleProducer.class);
private final static String TOPIC_NAME = "test";
private final static String BOOTSTRAP_SERVERS = "my-kafka:9092";
public static void main(String[] args) {
Properties configs = new Properties();
configs.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, BOOTSTRAP_SERVERS);
configs.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
configs.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
KafkaProducer<String, String> producer = new KafkaProducer<>(configs);
String messageValue = "testMessage";
ProducerRecord<String, String> record = new ProducerRecord<>(TOPIC_NAME, messageValue);
producer.send(record);
producer.flush();
producer.close();
}
}
// key 설정 레코드
ProducerRecord<String, String> record = new ProducerRecord<>(TOPIC_NAME, "Pangyo", "23");
// partition 지정 레코드
ProducerRecord<String, String> record = new ProducerRecord<>(TOPIC_NAME, 0, "Pangyo", "23");
ProducerRecord<String, String> record = new ProducerRecord<>(TOPIC_NAME, messageValue);
RecordMetadata metadata = producer.send(record).get();
logger.info(metadata.toString());
데이터 처리량
메세지 키 사용 여부
브로커, 컨슈머 영향도
파티션 개수가 많아지면 1:1 매칭되는 컨슈머 개수가 늘어난다. 따라서 데이터 처리량 측정이 중요하다.
producer 데이터 전송량 < 컨슈머 처리량 x 파티션 개수
from typing import Optional
from fastapi import Depends, FastAPI
app = FastAPI()
async def common_parameters(q: Optional[str] = None, skip: int = 0, limit: int = 100):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
async def read_items(commons: dict = Depends(common_parameters)):
return commons
@app.get("/users/")
async def read_users(commons: dict = Depends(common_parameters())):
return commons
class FastAPI(Starlette):
...
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
$ ls hello.kafka-0/
00000000000000000000.index 00000000000000000000.log 00000000000000000000.timeindex leader-epoch-checkpoint
$ gunicorn --workers=2 mydjangoapp.wsgi
public class SimpleConsumer {
private final static Logger logger = LoggerFactory.getLogger(SimpleConsumer.class);
private final static String TOPIC_NAME = "test";
private final static String BOOTSTRAP_SERVERS = "my-kafka:9092";
private final static String GROUP_ID = "test-group";
public static void main(String[] args) {
Properties configs = new Properties();
configs.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, BOOTSTRAP_SERVERS);
configs.put(ConsumerConfig.GROUP_ID_CONFIG, GROUP_ID);
configs.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
configs.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(configs);
consumer.subscribe(Arrays.asList(TOPIC_NAME));
while (true) {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(1));
for (ConsumerRecord<String, String> record: records) {
logger.info("{}", record);
}
}
}
}
consumer.assign(Collections,singleton(new TopicPartition(TOPIC_NAME, PARTITION_NUMBER)));
try {
while (true) {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(1));
for (ConsumerRecord<String, String> record: records) {
logger.info("{}", record);
currentOffsets.put(new TopicPartition(record.topic(), record.partition()),
new OffsetAndMetadata(record.offset() + 1, null));
consumer.commitSync(currentOffsets);
}
}
} catch (WakeupException e) {
logger.warn("Wakeup consumer");
} finally {
consumer.close();
}
// shutdown hook 등록
Runtime.getRuntime().addShutdownHook(new ShutdownThread());
// wakeup 함수 호출하는 shutdown hook
static class ShutdownThread extends Thread {
public void run() {
logger.info("Shutdown hook");
consumer.wakeup();
}
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.