구글링 해서 찾은 결과로는

대부분의 블로그에서 3번쨰 인자 값을 추가하라고 되어있다.


soup = BeautifulSoup(r.content, 'html.parser', from_encoding='utf-8')


허나 하나도 안된다. 

영어로 다시 검색해서 찾아보니..


검색 키워드 : python3 beautifulsoup encoding utf-8

찾았다..



#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
from requests import get

def test():
    url = 'http://xxxxxxxxxxxx'
    r = get(url)
    soup = BeautifulSoup(r.content.decode('euc-kr','replace'))
    print(soup)


replace, ignore를 사용하라는 네이버 블로그의 글이 

간접적으로 도움이 되었음.



반응형

설치하고 돌려 보면 에러 발생


ImportError: No module named 'jpype'


해결방안 - 직접 설치해서 해결함 (python3.5)


순서

1. https://pypi.python.org/pypi/JPype1

2. 최신 패키지 다운로드

3. 압축 풀고 

4. 해당 디렉토리로 이동

5. 설치 

   % python3.5 setup.py build 

   % python3.5 setup.py install


일단은 동작하는 것 같은데, 더 해보는 중.

반응형

그냥 한글을 인코딩해서 gmail 전송하면 한글이 전부 깨져버리는 문제가 발생

구글링해서 찾아보면 python2.x 코드가 있음


그래서 python3.5에서 만들어서 시험한 코드를 이곳에 기록함


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

def send_with_gmail(body):
    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText

    gmail_user = 'my_id'  # 실제 google 로그인할 때 쓰는 ID
    gmail_pw = 'my_pw'    # 실제 google 로그인할 때 쓰는 Password

    from_addr = 'sender@gmail.com'   # 보내는 사람 주소
    to_addr = 'iam.byungwoo@gmail.com'      # 받는 사람 주소

    msg=MIMEMultipart('alternative')
    msg['From'] = from_addr
    msg['To'] = to_addr
    msg['Subject'] = 'Send email with Gmail'     # 제목
    msg.attach(MIMEText(body, 'plain', 'utf-8')) # 내용 인코딩

    ########################
    # https://www.google.com/settings/security/lesssecureapps
    # Make sure less_secure_apps select 'use'
    ########################
    try:
        server = smtplib.SMTP("smtp.gmail.com", 587)
        server.ehlo()
        server.starttls()
        server.login(gmail_user, gmail_pw)
        server.sendmail(from_addr, to_addr, msg.as_string())
        server.quit()
        print('successfully sent the mail')
    except BaseException as e:
        print("failed to send mail", str(e))

if __name__ == '__main__':
    send_msg = '''
    multi
    L
    I
    N
    E
    '''
    send_with_gmail(send_msg)



반응형

reference : http://stackoverflow.com/questions/28400943/python-django-e-mail-form-example


기본 구조 이해에 도움이 많이 되서 저장해둠


A simple example could be:

urls.py

from django.conf.urls import patterns, url
from yourapp import views

urlpatterns = patterns(
    '',
    url(r'^email/$',
        views.email,
        name='email'
        ),
    url(r'^thanks/$',
        views.thanks,
        name='thanks'
        ),
)

forms.py

from django import forms

class ContactForm(forms.Form):

    from_email = forms.EmailField(required=True)
    subject = forms.CharField(required=True)
    message = forms.CharField(widget=forms.Textarea)

views.py

from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from yourapp.forms import ContactForm

def email(request):
    if request.method == 'GET':
        form = ContactForm()
    else:
        form = ContactForm(request.POST)
        if form.is_valid():
            subject = form.cleaned_data['subject']
            from_email = form.cleaned_data['from_email']
            message = form.cleaned_data['message']
            try:
                send_mail(subject, message, from_email, ['admin@example.com'])
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            return redirect('thanks')
    return render(request, "yourapp/email.html", {'form': form})

def thanks(request):
    return HttpResponse('Thank you for your message.')

email.html

<form method="post">
    {% csrf_token %}
    {{ form }}
    <div class="form-actions">
      <button type="submit">Send</button>
    </div>
</form>


반응형

참고: http://stackoverflow.com/questions/22489398/unsupported-major-minor-version-52-0


빌드는 1.8 JDK에서 해놓고 톰캣에 올려서 돌릴때는 1.7 JDK에서 돌린 경우 발생할 수도 있다고하는데
역시나.. ㅜ.ㅜ


OS: ubuntu 14.04

# update-alternatives --config java
대체 항목 java에 대해 (/usr/bin/java 제공) 3개 선택이 있습니다.

  선택       경로                                          우선순� 상태
------------------------------------------------------------
* 0            /usr/lib/jvm/java-8-oracle/jre/bin/java          1072      자동 모드
  1            /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java   1071      수동 모드
  2            /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java   1069      수동 모드
  3            /usr/lib/jvm/java-8-oracle/jre/bin/java          1072      수동 모드



# vi /etc/default/tomcat7

JAVA_HOME=/usr/lib/jvm/java-8-oracle


# service tomcat7 restart


 이제 정상 동작..


반응형

strace로 프로세스 상태를 체크하다가 보게 되었습니다.


FUTEX 란?

   출처 : http://www.hanbit.co.kr/preview/1492/sample_chap01.pdf

리눅스 커널 2.6에는 새로운 프로세스 간의 통신으로 FUTEX라는 것이 있습니다. 이것은 동일 머신 상의 복수 프로세스 간에 잠금(Lock) 처리를 합니다. 동일 페이지를 프로세스에 매핑하고, 그 위에 잠금 변수를 공유하게 함으로써 경합이 발생하지 않는 한 시스템 콜 개입 없이 잠금 처리를 할 수 있습니다. 많은 프로 세스나 스레드가 협조하여 동작하는 응용 프로그램에서는 매우 유용한 구조입니다.


FUTEX_WAIT ?

                           출처 : https://meenakshi02.wordpress.com/2011/02/02/strace-hanging-at-futex/

FUTEX_WAIT의 의미 

which simply means you are tracing the original parent thread, 

and it’s doing nothing but waiting for some other threads to finish.


[root@upi1 bin]# strace -p 24866
Process 24866 attached – interrupt to quit
futex(0xa280a0c, FUTEX_WAIT, 1, NULL



FUTEX_WAIT 과 FUTEX_WAIT_PRIVATE 차이 ?

출처: http://stackoverflow.com/questions/9983765/what-is-the-difference-between-futex-wait-and-futex-wait-private

This is an optimization done by linux/glibc to make futexes faster when they're not shared between processes. Glibc will use the _PRIVATE versions of each of the futex calls unless the PTHREAD_PROCESS_SHARED attribute is set on your mutex



데모 소스코드


#define _GNU_SOURCE

#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <linux/futex.h>
#include <sys/time.h>

#define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \
} while (0)

static int *futex1, *futex2, *iaddr;

static int futex(int *uaddr, int futex_op, int val,
        const struct timespec *timeout, int *uaddr2, int val3)
{
    return syscall(SYS_futex, uaddr, futex_op, val,
            timeout, uaddr, val3);
}

#define _GNU_SOURCE
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \
} while (0)

static int *futex1, *futex2, *iaddr;

static int futex(int *uaddr, int futex_op, int val,
        const struct timespec *timeout, int *uaddr2, int val3)
{
    return syscall(SYS_futex, uaddr, futex_op, val,
            timeout, uaddr, val3);
}

/* Acquire the futex pointed to by 'futexp': wait for its value to
   become 1, and then set the value to 0. */

static void fwait(int *futexp)
{
    int s;

    /* __sync_bool_compare_and_swap(ptr, oldval, newval) is a gcc
       built-in function.  It atomically performs the equivalent of:

       if (*ptr == oldval)
     *ptr = newval;

     It returns true if the test yielded true and *ptr was updated.
     The alternative here would be to employ the equivalent atomic
     machine-language instructions.  For further information, see
     the GCC Manual. */

    while (1) {

        /* Is the futex available? */

        if (__sync_bool_compare_and_swap(futexp, 1, 0))
            break;      /* Yes */

        /* Futex is not available; wait */

        s = futex(futexp, FUTEX_WAIT, 0, NULL, NULL, 0);
        if (s == -1 && errno != EAGAIN)
            errExit("futex-FUTEX_WAIT");
    }
}

/* Release the futex pointed to by 'futexp': if the futex currently
   has the value 0, set its value to 1 and the wake any futex waiters,
   so that if the peer is blocked in fpost(), it can proceed. */

static void fpost(int *futexp)
{
    int s;

    /* __sync_bool_compare_and_swap() was described in comments above */

    if (__sync_bool_compare_and_swap(futexp, 0, 1)) {

        s = futex(futexp, FUTEX_WAKE, 1, NULL, NULL, 0);
        if (s  == -1)
            errExit("futex-FUTEX_WAKE");
    }
}

int main(int argc, char *argv[])
{
    pid_t childPid;
    int j, nloops;

    setbuf(stdout, NULL);

    nloops = (argc > 1) ? atoi(argv[1]) : 5;

    /* Create a shared anonymous mapping that will hold the futexes.
       Since the futexes are being shared between processes, we
       subsequently use the "shared" futex operations (i.e., not the
       ones suffixed "_PRIVATE") */

    iaddr = mmap(NULL, sizeof(int) * 2, PROT_READ | PROT_WRITE,
            MAP_ANONYMOUS | MAP_SHARED, -1, 0);
    if (iaddr == MAP_FAILED)
        errExit("mmap");

    futex1 = &iaddr[0];
    futex2 = &iaddr[1];

    *futex1 = 0;        /* State: unavailable */
    *futex2 = 1;        /* State: available */

    /* Create a child process that inherits the shared anonymous
       mapping */

    childPid = fork();
    if (childPid == -1)
        errExit("fork");

    if (childPid == 0) {        /* Child */
        for (j = 0; j < nloops; j++) {
            fwait(futex1);
            printf("Child  (%ld) %d\n", (long) getpid(), j);
            fpost(futex2);
        }

        exit(EXIT_SUCCESS);
    }

    /* Parent falls through to here */

    for (j = 0; j < nloops; j++) {
        fwait(futex2);
        printf("Parent (%ld) %d\n", (long) getpid(), j);
        fpost(futex1);
    }

    wait(NULL);

    exit(EXIT_SUCCESS);
}







반응형

MAC에서 brew install maven 으로 설치한 이후 

mvn 명령을 수행했더니 에러가 계속 발생.


org.codehaus.plexus.classworlds.launcher.launcher을(를) 찾거나 로드할 수 없습니다



원인은 ~/.bash_profile에 설정한 M2_HOME이 잘 못되었다.

brew로 설치한 것의 버전은 3.x.x이므로 M3_HOME으로 설정해야함.


export M3_HOME=/usr/local/Cellar/maven/3.3.9

export M3=$M3_HOME/bin


설정한 이후로 정상 동작함.

아무래도 환경변수 설정은 버전에 의존하지 않게 해야할 것 같다.

나중에 4.x.x 버전나오면 같은 오류 반복될지도 모르니..

반응형

'Language > JAVA' 카테고리의 다른 글

Unsupported major.minor version 52.0 Error in Java (ubuntu 14.04)  (346) 2016.07.18
컴파일 오류  (342) 2016.01.29
public static 의미  (329) 2016.01.29
[Intellij]com.google.common 패키지를 못 찾는 경우  (324) 2016.01.28

오류 메시지

unreported exception java.io.IOException; must be caught or declared to be thrown



참고: http://stackoverflow.com/questions/8707906/unreported-exception-java-io-ioexception-must-be-caught-or-declared-to-be-throw



함수 선언할 때 public void ReadBuffer(String buff) throws IOException {


throws를 추가한 경우에는 이를 호출하는 호출부에서 

try & catch로 에러를 받아줘야 함.

반응형

+ Recent posts