페이지

2021년 5월 22일 토요일

VB.NET Sleep Delay 지연

Thread.Sleep 을 이용하여 간단히 지연시키는 코드


    Imports System.Threading

    Thread.Sleep(1000) 'milliseconds


Thread.Sleep 의 경우 UI 스레드에서 긴 시간 사용시 UI가 먹통될 수 있어 다음과 같은 코드를 사용할 수 있습니다.


    ' 지연되는 동안 cpu 점유율이 올라갑니다.

    Private sub Delay(milliseconds As Double)

        Dim delayTime As Date = Now.AddSeconds(milliseconds/1000)

        do until Now > delayTime

            Application.DoEvents()

        Loop

    End sub


    'cpu 점유율은 낮지만 시간지연이 좀 있습니다.

    Private sub Delay2(milliseconds As Double)

        Dim passed As Integer = 0

        For i  As Integer = 0 To milliseconds/10

            Thread.Sleep(10)

            Application.DoEvents()

        Next

    End sub


참고링크

2021년 5월 13일 목요일

JavaScript Audio File Play

var audioFile = new Audio('sound/sound1.wav');

audioFile.play()


참고링크

  • https://stackoverflow.com/questions/9419263/how-to-play-audio
  • https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement
  • https://www.w3schools.com/html/html5_audio.asp
  • https://howlerjs.com/
  • https://bskyvision.com/792


JavaScript 난수 생성하기 Math.random()

 Math.random()

0 이상 1 미만의 부동소숫점 값을 반환합니다.


두 값 사이의 난수 생성

function getRandomArbitrary(min, max) {
  return Math.random() * (max - min) + min;
}

두 값 사이의 정수 난수 생성 (최소값은 포함, 최대값은 제외)

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min; //최댓값은 제외, 최솟값은 포함
}

두 값 사이의 정수 난수 생성 (최소값 최대값 모두 포함)

function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min; //최댓값도 포함, 최솟값도 포함
}

출처

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Math/random


resharper unit tests system.badimageformatexception

 



단위 테스트 프로젝트와 테스트 대상 프로젝트의 구성이 다를 경우 발생할 수 있다고 합니다.

빌드 > 구성관리자 에서 두 프로젝트의 구성, 플랫폼 항목을 일치 시켜줍니다.




참고링크

https://stackoverflow.com/questions/32593358/system-badimageformatexception-while-using-nunit-and-resharper



2020년 10월 29일 목요일

카카오톡 링크 이미지 캐시 삭제

 카카오톡으로 링크를 보내면 해당 링크의 대표이미지가 나타나는데요.

링크에 해당하는 페이지를 수정해도 대표이미지는 변경되지 않는 경우가 있습니다.

이는 카카오쪽에 캐시가 되어있어서 그런데요.

그 캐시를 삭제하는 방법입니다.


다음 사이트에 접속합니다.

https://developers.kakao.com/

도구 메뉴를 클릭합니다.


초기화 도구 를 찾아서 바로가기 링크를 클릭합니다.



URL 란에 링크를 넣고 초기화 버튼을 클릭하면 캐시가 삭제되고

카카오톡으로 링크를 전송하면 다시 대표이미지가 생성됩니다.


2020년 10월 18일 일요일

OpenJDK 다운로드 링크

https://jdk.java.net/



 


압축 해제 후 JAVA_HOME 환경 변수 추가 후 사용


설치 파일이 필요하다면 다음 링크 이용

https://github.com/ojdkbuild/ojdkbuild


2020년 10월 6일 화요일

VB.NET DataGridView 의 Row 얻는 방법

Dim row As DataGridViewRow = dataGridView.Rows(0)

row.Height = 15

row.Visible = False 


참고

  • https://docs.microsoft.com/ko-kr/dotnet/api/system.windows.forms.datagridviewrow.height?view=netcore-3.1


2020년 1월 7일 화요일

jar 파일 압축 및 압축풀기


압축하기

    jar cvf filename.jar .

현재디렉토리와 하위디렉토리의 모든 파일을 압축하여 filename.jar 로 만든다.

압축풀기

    jar xvf filename.jar

현재디렉토리에 filename.jar 파일의 압축을 푼다.
압축을 풀 디렉토리로 들어가서 작업한다.

2019년 12월 24일 화요일

python simple http server ( web server )

현재 디렉토리를 웹서버로 만들어주는 명령입니다.

커맨드창에서 다음 명령을 실행합니다.


python -m SimpleHTTPServer


포트를 지정할 수 있습니다.

python -m SimpleHTTPServer 9000


Serving HTTP on 0.0.0.0 port 9000 ...

과 같은 메시지가 나오면 작동하는 것입니다.



https://docs.python.org/2/library/simplehttpserver.html

2019년 8월 10일 토요일

python mysql mysqlclient MySQLdb

설치

pip install mysqlclient


모듈 로드

import MySQLdb


데이터베이스 연결

connection = MySQLdb.connect(
    user="username",
    passwd="password",
    host="localhost",
    db="dbname",
    charset="utf8"
)

커서 추출

cursor = connection.cursor()

업데이트 쿼리

# create table note ( title varchar(100), content text )
cursor.execute("insert into note(title, content) values(%s,%s)", ("a", "b"))
connection.commit()

조회 쿼리

sql = "select * from note where title=%s"
cursor.execute(sql, ('a',))

for row in cursor.fetchall():
    print(row)  # ('a', 'b')

Dict 커서로 변경

cursor = connection.cursor(MySQLdb.cursors.DictCursor)

cursor.execute(sql, ('a',))
for row in cursor.fetchall():
    print(row)  # {'title': 'a', 'content': 'b'}
    print(row['title'], row['content'])     # a b

연결 종료

connection.close()

2019년 4월 24일 수요일

(Roundcube) Mailbox doesn't exist: trash

(Roundcube) Mailbox doesn't exist: trash

지운 편지함이 없는 상태에서 메일을 지우면 위와 같이 에러가 발생합니다.

폴더 관리에서 Trash 폴더를 생성해주면 해결됩니다.



2019년 4월 23일 화요일

unable to allocate bitmaps for parallel garbage collection for the requested heap.


자바 메모리 할당 실패


>java -version
을 실행해도 아래와 같은 에러를 뿌리는 현상이 있었습니다.

unable to allocate 8192kb bitmaps for parallel garbage collection for the requested 262144KB heap.


여러 원인이 있을 수 있겠지만
저의 경우 시스템 메모리가 부족한 것이 원인이었고
가상 메모리를 사용하도록 변경하여 해결했습니다.
시스템 상태에 따라 적절하게 가상 메모리를 확보하면 해결할수 있을것 같습니다.


2016년 6월 22일 수요일

python django datetime timezone naive aware 정리

Python 3.5.1
Django 1.9.5
>>> from datetime import datetime
>>> # 현재시간을 확인해보겠습니다.
>>> now_naive = datetime.now()
>>> str(now_naive)
'2016-06-22 15:59:26.918742'
>>> # UTC 시간을 확인해보겠습니다.
>>> utcnow_naive = datetime.utcnow()
>>> str(utcnow_naive)
'2016-06-22 06:59:53.294294'
>>> # 두문자열을 보면 어떤게 어느지역 시간인지 분간할 수 없습니다.(naive datetime)

>>> # django 에서 제공하는 현재시간입니다.
>>> from django.utils import timezone
>>> timezone_now = timezone.now()
>>> str(timezone_now)
'2016-06-22 07:05:22.279485+00:00'
>>> # 위 문자열들과 비교해보면 뒤에 +00:00 이 붙어서 UTC 시간임을 알수 있습니다.(aware datetime)

>>> # naive 시간들을 aware 로 변경해보겠습니다.
>>> now_aware_utc = timezone.make_aware(now_naive,timezone.utc)
>>> now_aware_localtime = timezone.make_aware(now_naive,timezone.get_current_timezone())
>>> str(now_aware_utc)
'2016-06-22 15:59:26.918742+00:00'
>>> str(now_aware_localtime)
'2016-06-22 15:59:26.918742+09:00'
>>> # 앞의 시간값은 같은데 뒤의 timezone 정보만 다릅니다. utc로 지정하면 +00:00 이 붙고, current_timezone 으로 지정하면 +09:00 이 붙습니다. 즉 timezone 정보가 추가됩니다.
>>> # 따라서 naive 상태의 시간이 utc인지 current_timezone인지 명확히 알고 변경해야 합니다.
>>> # datetime.now() 는 current_timezone 이므로 now_aware_localtime 이 정확한 변환값입니다.

>>> # datetime.utcnow() 는 UTC 이므로 UTC를 지정하여 변환해줘야합니다.
>>> utcnow_aware_utc = timezone.make_aware(utcnow_naive,timezone.utc)
>>> str(utcnow_aware_utc)
'2016-06-22 06:59:53.294294+00:00'


>>> # 어떤것들은 +00:00 이 붙어서 출력되므로 일괄적으로 +09:00 이 붙은상태의 localtime으로 출력해보겠습니다.
>>> str(timezone.localtime(utcnow_aware_utc))
'2016-06-22 15:59:53.294294+09:00'
>>> str(timezone.localtime(now_aware_localtime))
'2016-06-22 15:59:26.918742+09:00'
>>> str(timezone.localtime(timezone_now))
'2016-06-22 16:05:22.279485+09:00'

참고문서

https://docs.djangoproject.com/en/1.9/topics/i18n/timezones/

2016년 6월 8일 수요일

django DEBUG = False ALLOWED_HOSTS 설정

django 개발시 기본 설정은 다음과 같습니다.
DEBUG = True
ALLOWED_HOSTS = []
DEBUG = False
로 변경하면 아래와 같은 에러가 발생합니다.
CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False.

DEBUG = True 일때는 상관없지만 DEBUG = False 가 되면 접속가능한 호스트를
ALLOWED_HOSTS 에 추가해줘야 합니다.

ALLOWED_HOSTS = ['127.0.0.1'] 로 설정 후
http://localhost:8000/ 로 접속시
Bad Request (400)

http://127.0.0.1:8000/ 로 접속시
접속됨

ALLOWED_HOSTS = ['localhost'] 로 설정 후
http://localhost:8000/ 로 접속시
접속됨

ALLOWED_HOSTS = ['*']
로 하여 모든 곳으로 부터의 접속을 허용할 수도 있습니다.

DEBUG = False 로 하는 경우는 대부분 운영을 위한 경우이고
운영환경의 경우 아파치나 nginx 같은 웹서버를 경유하게 되므로
ALLOWED_HOSTS 에 서버의IP 만 적어 주는 것이 좋을것 같습니다.
그리고 웹서버에서 어떻게 요청을 전달하느냐에 따라 맞춰서 설정해 줘야 합니다.

django 에서 mysql 사용하기

데이터베이스 이름을 db1
유저명을 user1
유저암호를 user1_pw

데이터베이스 추가 및 유저 추가

create database db1;
grant all privileges on db1.* to 'user1'@'127.0.0.1' identified by 'user1_pw';

127.0.0.1 는 데이터베이스 서버와 django 서버가 다른서버에 있다면 django 서버의 IP 를 입력합니다.

mysqlclient 설치 - https://github.com/PyMySQL/mysqlclient-python

$ sudo apt-get install libmysqlclient-dev
$ pip install mysqlclient

데이터베이스 설정 변경 - project/settings.py

DATABASES 항목을 찾아서 다음과 같이 수정합니다.
DATABASES = {
    'default':{
        'ENGINE':'django.db.backends.mysql',
        'NAME':'db1',
        'USER':'user1',
        'PASSWORD':'user1_pw',
        'HOST':'mysqlhost.example.com',
        'PORT':'3306',
    }
}

데이터베이스에 적용 및 수퍼유저 생성

$ python manage.py migrate
$ python manage.py createsuperuser

django 에서 유저추가 방법

1. 수퍼유저를 만듭니다.

$ python manage.py createsuperuser

2. 각각의 유저를 만듭니다.

$ python manage.py shell
>>> from django.contrib.auth.models import User
>>> u = User(username='user1')
>>> u.set_password('1111')
>>> u.is_staff=True # admin 유저의 경우 True
>>> u.save()

참고로 django rest framework 에서
다음과 같은 IsAdminUser 권한을 설정하면
u.is_staff=True 로 되어있는 유저만 접속할 수 있습니다.

from rest_framework import viewsets
from rest_framework import permissions
class UserViewSet(viewsets.ModelViewSet):
  permission_classes = (permissions.IsAdminUser,)

2016년 6월 4일 토요일

Django Rest Framework 파일만 별도로 업로드 하는 기능 구현

Django Rest Framework Image Upload Download
에서 이어집니다.

functional_tests/tests_upload.py

  • 우선 기존테스트를 복사해서 test_upload_file 로 테스트를 하나 만듭니다.
  • title만 먼저 등록하고
  • /imageuploads/{pk}/upload 로 파일만 전송하도록 수정합니다.
  • 업로드한 파일을 지우고
  • 파일없이 요청하면 400 코드를 반환하게 합니다.

  def test_upload_file(self):
    # title 만 입력하여 추가한다.
    r = requests.post(self.live_server_url + '/imageuploads/',
        data={
            'title':'Test Image'
        }
    )
    self.assertEqual(201, r.status_code)  # created
    url = r.json()['url']
    # /imageuploads/{pk}/upload 로 파일을 전송한다.
    file = open('functional_tests/test_image.png','rb')
    files = [
        ('imagefile', ('test_image.png', file, 'image/png'))
    ]
    r = requests.post(url + 'upload/',
        files=files
    )
    file.close()
    self.assertEqual(200, r.status_code)
    self.assertEqual('upload success', r.json()['status'])
    # 업로드된 파일을 지운다.
    r = requests.get(url)
    imagefile = r.json()['imagefile']
    imagefilepath = imagefile.__str__().replace(url,'')
    imagefile_realpath = os.path.abspath(os.path.join(MEDIA_ROOT, imagefilepath))
    os.remove(imagefile_realpath)
    # 파일없이 요청하면 400 코드를 반환한다.
    r = requests.post(url + 'upload/')
    self.assertEqual(400, r.status_code)
    self.assertEqual('no file', r.json()['status'])

views.py

  • request.data 에서 첫번째 키 값을 찾고
  • 키 값이 있으면 저장해주고
  • 없으면 400 코드를 반환합니다.

from rest_framework.response import Response
from rest_framework import status
  @detail_route(methods=['post'])
  def upload(self, request, pk=None):
    key = None
    for k in request.data:
      key = k
      break
    if key:
      r = self.get_object()
      r.imagefile = request.data[key]
      r.save()
      return Response({'status': 'upload success'})
    else:
      return Response({'status': 'no file'}, status=status.HTTP_400_BAD_REQUEST)
전체 소스코드는 아래 링크를 확인하세요.
https://github.com/kyuhyung-park/djangorestframework_practice/tree/only_file_upload

2016년 6월 3일 금요일

Django Rest Framework Image Upload Download


Django Rest Framework Simple Start
에서 이어집니다.

업로드 테스트

command
(virtualenv) tutorial>pip install requests


functional_tests/test_image.png 준비

functional_tests/tests_upload.py
from django.test import LiveServerTestCase
import requests
class UploadTest(LiveServerTestCase):
    def test_upload(self):
        file = open('functional_tests/test_image.png','rb')
        files = [
            ('imagefile', ('test_image.png', file, 'image/png'))
        ]
        r = requests.post(self.live_server_url + '/imageuploads/',
            data={
                'title':'Test Image'
            },
            files=files
        )
        file.close()
        self.assertEqual(201, r.status_code)  # created

command
(virtualenv) tutorial>python manage.py test functional_tests

테스트 실행하면 업로드된 파일이 tutorial 폴더에 저장된것을 확인할 수 있습니다.

git tag upload_test

업로드시 파일 저장위치 변경

settings.py 에 다음을 추가합니다.
MEDIA_ROOT = os.path.abspath(os.path.join(BASE_DIR, '../uploadfiles'))

업로드 되는 파일이 프로젝트 루트 기준으로 /uploadfiles 가 됩니다.

models.py 에서 imagefile 에 upload_to 를 추가합니다. 
imagefile = models.FileField(upload_to='imagefile/%Y/%m/%d', null=True)

이 필드로 인해 업로드되는 파일은 /uploadfiles/imagefile/2016/06/02 형태가 됩니다.

functional_tests/tests_upload.py
from tutorial.settings import MEDIA_ROOT
import os
class UploadTest(LiveServerTestCase):
    def test_upload(self):
        # 기존 코드 이후에 추가
        imagefile = r.json()['imagefile']
        imagefilepath = imagefile.__str__().replace(self.live_server_url + '/imageuploads/','')
        imagefile_realpath = os.path.abspath(os.path.join(MEDIA_ROOT, imagefilepath))
        os.remove(imagefile_realpath)

업로드된 파일을 지우는 코드입니다.
파일이 없을 경우 os.remove(imagefile_realpath) 에서 에러가 발생합니다.

command
(virtualenv) tutorial>python manage.py test functional_tests
테스트를 돌려 확인해 봅니다.

git tag change_upload_path

다운로드 구현

serializers.py
class ImageUploadSerializer(serializers.HyperlinkedModelSerializer):
    imagefile_url = serializers.HyperlinkedIdentityField(view_name='imageupload-imagefile', read_only=True)
   
    class Meta:
        model = ImageUpload
        fields = ('url', 'pk', 'title', 'imagefile', 'imagefile_url')
views.py
from rest_framework.decorators import detail_route
from django.http import FileResponse
class ImageUploadViewSet(viewsets.ModelViewSet):
    queryset = ImageUpload.objects.all()
    serializer_class = ImageUploadSerializer
   
    @detail_route(methods=['get'])
    def imagefile(self, request, pk=None):
        r = self.get_object()
        # 확장자 추출
        ext = '*'
        if r.imagefile.path:
            ext = r.imagefile.path.split('.')[-1]
        content_type = 'image/' + ext
        # 다운로드용 Response 반환
        response = FileResponse(open(r.imagefile.path, 'rb'), content_type=content_type)
        return response
tests_upload.py
test_upload 메소드 명을 test_upload_download 로 바꿈.
아래 내용 추가
import shutil
import filecmp
        # 파일의 마지막 부분을 아래와 같이 수정
        # --------------------------------
        # 다운로드 경로를 알아내고 요청을 보낸다.
        imagefile_url = r.json()['imagefile_url']
        r = requests.get(imagefile_url, stream=True)
        # 다운로드한 파일을 저장한다.
        with open('functional_tests/download.png', 'wb') as out_file:
            shutil.copyfileobj(r.raw, out_file)
        # 업로드 한 파일과 다운로드 한 파일이 같은지 비교한다.
        self.assertTrue(filecmp.cmp('functional_tests/test_image.png', 'functional_tests/download.png'))
        # 다운로드한 파일을 삭제한다.
        os.remove('functional_tests/download.png')
        # --------------------------------
       
        # 업로드된 파일을 지운다.
        imagefilepath = imagefile.__str__().replace(self.live_server_url + '/imageuploads/','')
        imagefile_realpath = os.path.abspath(os.path.join(MEDIA_ROOT, imagefilepath))
        os.remove(imagefile_realpath)

git tag download

전체 소스코드는 아래 링크를 확인하세요.
https://github.com/kyuhyung-park/djangorestframework_practice/tree/download