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()