python3 merge sort

 


import pdb


sorted = [0, 0, 0, 0, 0, 0, 0, 0] # cache for sorting


def merge(lst, m, middle, n):

    global sorted

    i = m

    j = middle + 1

    pos = m

    

    while i <= middle and j <= n:

        if lst[i] < lst[j]:

            sorted[pos] = lst[i]

            i+=1

        else:

            sorted[pos] = lst[j]

            j+=1


        pos+=1


    # insert part of remaining list

    if i > middle:

        for idx in range(pos, n+1):

            sorted[idx] = lst[j]

            j+=1

    else:

        for idx in range(pos, n+1):

            sorted[idx] = lst[i]

            i+=1

    

    # apply part of aligned list

    for idx in range(m, n+1):

        lst[idx] = sorted[idx]

        

    print("mergeSort({})".format(lst))


            

def mergeSort(lst, m, n):

     

    if m < n:

        middle = int((m+n)/2)

        mergeSort(lst, m, middle)

        mergeSort(lst, middle+1, n)

        merge(lst, m, middle, n)

    

if __name__ == '__main__':

    rawList = [3, 5, 2, 1, 8, 10, 11, 9]


    mergeSort(rawList, 0, len(rawList)-1)

    

    print(rawList)

    

error extraneous input '\n' expecting {'\', ':', '=', Space, IdentifierChar}

extraneous input '\n' expecting {'\', ':', '=', Space, IdentifierChar}


solution:

you just copy it and paste.

delete previous thing.

AnnotationConfigBeanDefinitionParser ERROR

"Caused by: java.lang.IllegalStateException: Context namespace element 'annotation-config' and its parser class [org.springframework.context.annotation.AnnotationConfigBeanDefinitionParser] are only available on JDK 1.5 and higher"

if you have seen this error from tomcat's catalina.out logfile,
it must be check where your JAVA_HOME in your tomcat's startup.sh

I am sure that this solution that maybe you will get to resolve the problem mostly.

package org.openqa.selenium does not exist

i wanna use selenium with maven with selenium's native library.

but eclipse didn't work.

it occured package org.openqa.selenium does not exist

but finally i could find out the solution.

i added just 'org.seleniumhq.selenium' dependency in pom.xml.

and i didn't need to selenium's native library.

compiled python No module named _sqlite3

if your python2.7 occured error and you compiled new python on linux,


you can fast resolve this error.

how to resolve its error below.

1) find _sqlite3.so file

$ find / -name _sqlite.so 2> /dev/null

2) copy _sqlite3.so file to your PYTHON_DYNAMIC_LIBRARY_PATH
 - my PYTHON_DYNAMIC_LIBRARY_PATH is /usr/local/lib/python2.7/lib-dynload

$ cp /usr/lib64/python2.7/lib-dynload/_sqlite3.so /usr/local/lib/python2.7/lib-dynload

3) then you can import sqlite3

sed delete line

You can delete line in text by sed on linux.

I will show you how to delete line by sed on linux.

Look at the text contents file below.
apple
banana
pineapple
melon
watermelon

I am going to delete what containing keyword line 'apple' like below result.
banana
melon
watermelon

you can use the following command.

sed '/apple/d' fruits.txt

python command timeout (Advanced)

python에서 command 실행시 타임아웃 설정 (Advanced)


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import subprocess as sp

class ExecuteFile:
    class TimeoutException(Exception):
        pass

    # timeout 커맨드실행
    @staticmethod
    def execute(cmd, errorKeyword=['error', 'fail', 'bad'], timeout=10):
        #pdb.set_trace()
        #popen = sp.Popen(cmd.split(), stderr=sp.STDOUT, stdout=sp.PIPE, env=os.environ)
        popen = sp.Popen(cmd, shell=True, stderr=sp.STDOUT, stdout=sp.PIPE, env=os.environ)

        # timeout 처리
        sTime = time.time()
        try:
            while True:
                if popen.poll() is not None:
                    break

                if time.time()-sTime > timeout:
                    raise ExecuteFile.TimeoutException

                time.sleep(0.1)

        except ExecuteFile.TimeoutException as e:
            popen.kill()

            return False, cmd, 'TimeoutException'

        # 에러 keyword 처리
        stdout = popen.stdout.read()

        for keyword in errorKeyword:
            if keyword in stdout:
                return False, cmd, stdout


        return True, cmd, 'SUCCESS'

mysql group by case ( GROUP BY 시 기타로 분류하는 방법 )

group by case 사용법

Group by 절을 사용시 키값이 되는 일부 분류를 기타로 넣고 싶은 경우가 있다.


위와 같은 데이터가 존재할때

단순 그룹핑을 하게 된다면 아래와 같을 것이다.





여기서 PYTHON과 C++ 이외에 분류키값들 ETC로 분류를 하고 싶다면 그때 group by case 절을 사용하여 아래와 같은 형태로 수행하면 된다.



how to install compiling python with ssl

ㅇ 아래 버전을 설치하였습니다.
- python2.7.15
- openssl1.0.2r


1. python설치 (ssl가능 세팅)
* 루트로 진행
1) python을 내려받고 압축을 푼다.

2) Modules/Setup.dist 를 편집
   2.1) SSL 로 찾기하면
         SSL=/usr/local/ssl 부터 총 4줄이 주석 처리되어 있음. 해제
         * python을 make했을때 ssl관련하여 컴파일 오류가 뜬다면 openssl경로를
           여기에 넣어 주어야 함.
           (허나 필자는 무식하게 Makefile을 변경하여 컴파일 완료하였음.)

3) $> ./configure (설정은 재량껏)
4) $> make
  4.1) 여기서 ssl관련하여 컴파일에러가 난다면 2.1)로 다시가서 설정하고
        다시 진행하는 방법과 지금 필자가 서술하는 방법이 있다. 후자를 서술하겠음.
  4.2) Makefile을 편집
       SSL=/usr/local/ssl 이란곳을 찾아 openssl경로로 바꾸어준다.
5) $> make install

2. openssl 설치
  1) openssl을 내려받고 압축을 푼다.
  2) $> Configure linux-x86_64 shared --prefix=/usr/local/openssl   (64비트 가정)
  3) $> make
  4) $> make install
  5) $> openssl version
     * 쉐어드 라이브러리 에러가 난다면 LD_LIBARY_PATH에
       openssl/lib 경로를 추가해준다.

[python] posix_ipc MessageQueue

posix_ipc MessageQueue sample


ㅇ source
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import posix_ipc as pi

# name 아규먼트는 posix에서 지정된 파일경로에 저장되며
# 경로는 명시하지 않는다. (경로를 명시하면 에러가 남.)
# mq저장경로는 virtual filesystem이므로 filesystem에 마운팅 시켜야 한다.
mq = pi.MessageQueue("/test.q", pi.O_CREAT|pi.O_RDWR)

mq.send("Hello world!!")

rst = mq.receive()

print rst

ㅇ It's way to mount posix message queue.
  1) login to root
  2) $ mkdir /dev/mqueue
  3) $ mount -t mqueue none /dev/mqueue

[logstash] 불필요한 정보, 메세지 필터링하기

logstash를 기동할때 쓰는 환경파일의 filter 섹션에 기술한다.

예)

filter {

  if "_grokparsefailure" in [tags] {
    drop {}
  }

}

vim 정규표현식 치환시 검색키워드 보존하는 방법

vim 정규표현식 치환시 검색키워드 보존하는 방법

1) 검색키워드를 보존하기 위해 capturing group 영역을 잡는다.
  -> 검색키워드에 \(와 \)를 문자열에 씌우면 캡쳐링 영역 생성

2) 치환에서 capturing group 정보를 가져온다.
  -> \1 를 사용하여 첫번째 capturing group을 가져온다.

예1)

아래 문자열에서 공백과 come사이에 문자열을 추가로 넣기.

    comes my home

- 치환 명령
:%s/^\([ ]\+\)/\1She /g

- 변환 후 문자열
    She comes my home


python function timeout decorator

it's function's timeout decorator on python



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from functools import wraps
import time
import signal
import errno

class TimeoutError(Exception):
    pass

def funcTimeout(timeout=30):
        def decorator(func):

                def handleFuncTimeout(signum, frame):
                        raise TimeoutError(os.strerror(errno.ETIME))

                @wraps(func)
                def wrapper(*args, **kwargs):
                        #print '[%d]wrapper START' % id
                        sTime = time.time()

                        signal.signal(signal.SIGALRM, handleFuncTimeout)
                        signal.alarm(timeout)

                        try:
                                result = func(*args, **kwargs)
                        finally:
                                signal.alarm(0)

                        #print '[%d]wrapper END(elapseTime=%d)' % (id, time.time()-sTime)

                        return result

                return wrapper

        return decorator


#DIRECTIONS
@funcTimeout(3)
def func():
    print 'func() start'
    time.sleep(5)
    print 'func() end'

func()

python threading.Thread생성시 function argument 사용 주의점

threading.Thread 생성시 function argument 사용할때

name을 구분해주지 않으면 같은 name이 재시도 되지 않는다.
(name을 구분해야 제대로 돌아간다는말)


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
// 1)  좋은 

def func():
  pass

for i in range(3):
  th = threading.Thread(func())
  th.start()


// 2) 좋은 

def func():
  pass

for i in range(3):
  thName = 't%d' % i
  th = threading.Thread(func(), name=thName)
  th.start()

convert (unicode <-> euc-kr)

python 2.x에 unicode는 언제봐도 항상 어려운거 같다.

example로 여기다가 남기겠음.

#-*- coding: utf-8 -*-

# utf-8 -> euckr
s1 = unicode('파이썬2.x 유니코드 정말 싫다!!', 'utf-8')
s2 = s1.encode('euc-kr')
print s2

# euckr -> utf-8
s3 = unicode(s2, 'euc-kr')
s4 = s1.encode('utf-8')
print s4

how to install django on cygwin

Cygwin is very restrictive when installs packages.

I needed to install django on cygwin.

I will introduce to install django on cygwin.

following is how to install django 1.8.7 with python 2.7 on cygwin 2.3.0 x86_64

1) install cygwin
   recommending category packages are admin, Base, Database, Debug, Devel, Editors, Interpreters, Libs, Python, Math, Security, System, Util, Web

2) get the django source https://www.djangoproject.com/download/1.8.7/tarball/

3) extract Django-1.8.7.tar.gz

4) $ cd Django-1.8.7
    $ python setup.py build

5) $ python setup.py install

6) enjoy the django

Cannot find GMP version 4.1.3 or higher. centos6.7

gcc 버전을 높이기 위해 디펜던시가 걸린 패키지들을 인스톨하는 중

ppl 패키지에서 난관에 부딛혔다.

아래와 같은 메세지가 configure 메세지에서 뜨며 나를 괴롭혔다.

checking for the GMP library version 4.1.3 or above... no
configure: error: Cannot find GMP version 4.1.3 or higher.
GMP is the GNU Multi-Precision library:
see http://www.swox.com/gmp/ for more information.
When compiling the GMP library, do not forget to enable the C++ interface:
add --enable-cxx to the configuration options.

GMP버전은 이미 4.1.3을 넘었지만 똑같은 문구만 반복된다.

삽질과 구글링을 해본결과

configure 실행시 깔린곳의 library와 include를 옵션으로 지정하여 문제를 해결하였다.

[solution]
1. (gmp라이브러리는 --enable-cxx 옵션을 첨부하여 install한다. 이 부분도 솔루션에 포함되는지 않되는지는 확인해봐야 함)
2. $ ./configure --with-gmp-include=/usr/local/include/ --with-gmp-lib=/usr/local/lib


django error 'dict' object has no attribute 'META'

django 에러

symptom:
'dict' object has no attribute 'META'
Request Method:GET
Request URL:http://128.199.227.215:8000/tag/naver/
Django Version:1.8.4
Exception Type:AttributeError
Exception Value:
'dict' object has no attribute 'META'
Exception Location:/usr/local/lib/python2.7/site-packages/django/template/context_processors.py in debug, line 43
Python Executable:/usr/local/bin/python
Python Version:2.7.10
Python Path:
['/home/django/easy',
 '/usr/local/lib/python27.zip',
 '/usr/local/lib/python2.7',
 '/usr/local/lib/python2.7/plat-linux2',
 '/usr/local/lib/python2.7/lib-tk',
 '/usr/local/lib/python2.7/lib-old',
 '/usr/local/lib/python2.7/lib-dynload',
 '/usr/local/lib/python2.7/site-packages']

solution:
뷰쪽(views.py)에 RequestContext 아규먼트가 제대로 들어갔는지 확인한다.

parsing xml on python. unknown encoding

symptom:
SOAP 통신 서버 시뮬레이터에 xml 파서인 ElementTree에 fromString 메서드에서

"ExpatError: unknown encoding" 에러를 발생시켰다.

--------------------------------------------------------------------------------------
  File "/usr/local/lib/python2.6/SocketServer.py", line 322, in finish_request
  File "khubOiServerOri.py", line 320, in response
  File "/usr/local/lib/python2.6/xml/etree/ElementTree.py", line 1245, in feed
    method()
  File "khubOiServerOri.py", line 125, in do_POST
  File "khubOiServerOri.py", line 177, in recvHandler
  File "/usr/local/lib/python2.6/BaseHTTPServer.py", line 329, in handle
    self.handle_one_request()
    self._parser.Parse(data, 0)
  File "/usr/local/lib/python2.6/BaseHTTPServer.py", line 323, in handle_one_request
192.168.151.30 - - [19/Oct/2015 14:14:08] "POST / HTTP/1.1" 200 -
    self.RequestHandlerClass(request, client_address, self)
  File "/usr/local/lib/python2.6/SocketServer.py", line 617, in __init__
    reqDic = parseOi.parseOi(raw)
  File "/home/pis/SIM/lib/parseOi.py", line 37, in parseOi
    root = ET.fromstring(uRawData)
    method()
    rspData = self.response(paramDic)
ExpatError: unknown encoding: line 1, column 30
--------------------------------------------------------------------------------------

클라이언트는 euc-kr세팅으로 SOAP 통신을 하였고

서버 시뮬레이터에서는 UTF-8 세팅이 기본이였다.

모든것을 다 해보진 않았지만 ElementTree에서는 UTF-8이 기본세팅이기에

euc-kr 세팅으로는 파싱이 안되는걸로 추측하고 있다.

solution:
들어오는 스트링을 utf-8로 변환하고 xml header에 encoding을 utf-8로 세팅한다.
1) before
    root = ET.fromstring(rawData)

2) after
    uRawData = unicode(rawData, 'euc-kr').encode('utf-8')

    uRawData = uRawData.replace('euc-kr','utf-8')

    root = ET.fromstring(uRawData)

uwsgi invalid request block size

uwsgi 실행시 아래와 같은 에러가 난다면?
"invalid request block size: 21327 (max 4096)...skip"

solution:
사용하는 uwsgi.ini를 아래와 같이 수정한다.
module = django.core.wsgi:get_wsgi_application()