명령 프롬프트에서 alert 메세지 띄우기

윈도우즈/OS 일반|2020. 5. 29. 16:08
반응형

명령 프롬프트를 통해 팝업과 같은 간단한 메세지 출력이 가능합니다.

아래 예제를 사용해 봅니다.


c:\> msg %username% 메세지를 띄우는 예제 입니다.




반응형

댓글()

batch 배치 파일을 exe 실행 파일로 변환하기 (윈도우즈 기본 기능 : iexpress.exe) - gui, cli 둘다 지원

윈도우즈/OS 일반|2020. 5. 29. 15:30
반응형

윈도우즈의 iexpress.exe 파일을 이용하면 배치 파일을 exe 실행 파일로 변환 시킬 수 있습니다.

파일을 찾아 더블클릭하여 GUI 환경에서 셋팅도 가능하며,

아래와 같이 convert.bat 파일을 만들어 cmd 화면에서 cli 명령으로 변환도 가능합니다.


본래는 패키지 만드는 도구이지만 이렇게 하나의 배치파일도 exe 파일로 변환이 가능합니다.

여기에서는 command line 에서 변환하는 방법을 안내 드립니다.


변환 도구를 아래와 같이 작성합니다.


1. 명령 프롬프트에서 사용시


convert.bat


;@echo off

; rem https://github.com/npocmaka/batch.scripts/edit/master/hybrids/iexpress/bat2exeIEXP.bat

;if "%~2" equ "" (

; echo usage: %~nx0 batFile.bat target.Exe

;)

;set "target.exe=%__cd__%%~2"

;set "batch_file=%~f1"

;set "bat_name=%~nx1"

;set "bat_dir=%~dp1"


;copy /y "%~f0" "%temp%\2exe.sed" >nul


;(echo()>>"%temp%\2exe.sed"

;(echo(AppLaunched=cmd.exe /c "%bat_name%")>>"%temp%\2exe.sed"

;(echo(TargetName=%target.exe%)>>"%temp%\2exe.sed"

;(echo(FILE0="%bat_name%")>>"%temp%\2exe.sed"

;(echo([SourceFiles])>>"%temp%\2exe.sed"

;(echo(SourceFiles0=%bat_dir%)>>"%temp%\2exe.sed"

;(echo([SourceFiles0])>>"%temp%\2exe.sed"

;(echo(%%FILE0%%=)>>"%temp%\2exe.sed"



;iexpress /n /q /m %temp%\2exe.sed


;del /q /f "%temp%\2exe.sed"

;exit /b 0


[Version]

Class=IEXPRESS

SEDVersion=3

[Options]

PackagePurpose=InstallApp

ShowInstallProgramWindow=0

HideExtractAnimation=1

UseLongFileName=1

InsideCompressed=0

CAB_FixedSize=0

CAB_ResvCodeSigning=0

RebootMode=N

InstallPrompt=%InstallPrompt%

DisplayLicense=%DisplayLicense%

FinishMessage=%FinishMessage%

TargetName=%TargetName%

FriendlyName=%FriendlyName%

AppLaunched=%AppLaunched%

PostInstallCmd=%PostInstallCmd%

AdminQuietInstCmd=%AdminQuietInstCmd%

UserQuietInstCmd=%UserQuietInstCmd%

SourceFiles=SourceFiles


[Strings]

InstallPrompt=

DisplayLicense=

FinishMessage=

FriendlyName=-

PostInstallCmd=<None>

AdminQuietInstCmd=

UserQuietInstCmd= 


그리고 변환이 필요한 bat 파일이 있다면 (예: run.bat) 아래 예시와 같이 명령을 수행하면 됩니다.


c:\> convert.bat run.bat run.exe



[출처] https://stackoverflow.com/questions/28174386/how-can-a-bat-file-be-converted-to-exe-without-third-party-tools



2. GUI 환경에서 사용시


순차적으로 실행 합니다.


시작 > 실행 > iexpress 입력 후 엔터


Create new Self Extraction Directive file.


Extract files and run an installation command


타이틀 이름 적기


No prompt


Do not display a license


Package file

> 압축할 파일을 찾기 (bat 파일)


Install Program to Launch

> exe 실행시 압축 해제 후 사용할 기본 명령어

> setup.bat 파일을 변환한다면 아래와 같이 입력

> cmd.exe /c "setup.bat"


Default (recommended)


No message


Package name and Options

> (exe 변환 파일 저장 위치) 찾아보기 누른 뒤 경로와 생성할 exe 파일명 지정


No restart


Save Self Extraction Directive (SED) file  (중요치않다)


Create package


끝.


* 참고로 파일명은 setup.bat > setup.exe 으로 했을때 잘 실행되지만

   이상하게 다른 이름을 사용하면 실행이 되지 않는다.

   (예: applypatch.bat > applypatch.exe)


* exe 로 실행시 %~dp0 이나 %~s0 의 기본 변수는 사용되지 못함에 주의

반응형

댓글()

input 으로 작성한 button 자동 클릭하기

반응형

눌러야 실행되는 것을 아래 script 를 추가함으로써 자동 실행 되도록 할 수 있습니다.



<input type="button" id="execute" value="실행" />



<script>

        window.onload = function() {

                document.getElementById('execute').click();

        }

</script>



반응형

댓글()

실시간 페이지 갱신 (ajax 이용)

반응형

index.html

<!DOCTYPE html>
<head>
<meta charset=UTF-8" />
<meta name="robots" content="noindex,nofollow"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no"/>
<meta http-equiv="X-UA Compatible" control="IE=edge,chrome=1" />
<link rel="stylesheet" type="text/css" href="css/table.css" />
<script type="text/javascript" src="//code.jquery.com/jquery.min.js"></script>

<!-- 자동 갱신 스크립트 include -->
<script>
var timerID;
$(document).ready(function() {
    $('#execute').on('click',function(e) {
        e.preventDefault();
        updateData();
    });
    $('#stop').on('click',function(e) {
        e.preventDefault();
        clearTimeout(timerID); // 타이머 중지
        $('#showtime').html('');
    });
});


function updateData() {
    $.ajax({
        url: "getserver.php",
        type: "post",
        cache : false,
        success: function(data) { // getserver.php 파일에서 echo 결과값이 data 임
            $('#showtime').html(data);
        }
    });
    timerID = setTimeout("updateData()", 1000); // 1초 단위로 갱신 처리
}
</script>
</head>

<body>
<p>time : <span id="
showtime"></span></p>
<input type="button" id="execute" value="실행" />
<input type="button" id="stop" value="중지" />
</body>
</html>

 

getserver.php

<?php
    $time = date("H:m:s");
    echo $time;
?>

 

작성 후 index.html 을 불러오면, '실행' 버튼을 눌렀을때 주기적으로 getserver.php 가 실행되어 빨간색 showtime 부분에  출력됩니다.

 

'실행' 버튼 누를 필요없이 자동으로 클릭한 효과를 얻으려면 아래와 같이 조치합니다.

1) input 두개의 type 을 hidden 으로 숨깁니다.

2) 아래 코드를 추가합니다.

<script>

        window.onload = function() {

                document.getElementById('execute').click();

        }

</script>

 

 

출처 : https://link2me.tistory.com/1139 [소소한 일상 및 업무TIP 다루기]

반응형

댓글()

php 에서 mongodb 데이터 읽기, 쓰기, 갱신, 삭제하기 (select, insert, update, delete)

프로그래밍/PHP|2020. 5. 20. 16:53
반응형

아래 코드는 PHP 7.2 에서 MongoDB 4.4.0 에서 확인 되었습니다.


참조 : http://zetcode.com/db/mongodbphp/

> MongoDB 설치에서 부터 PHP 연동을 위한 모듈 설치, 설정.

    그리고 데이터 입출력에 관한 간단한 소스가 예제로 잘 작성 되어 있습니다.



1. Insert


<?php


try {

    $mng = new MongoDB\Driver\Manager("mongodb://127.0.0.1:27017");

    $bulk = new MongoDB\Driver\BulkWrite;

    $doc = ['_id' => new MongoDB\BSON\ObjectID, 'Name' => "CDH", 'City' => "Seoul"];

    $bulk->insert($doc);

    $mng->executeBulkWrite('site.member', $bulk);


} catch (MongoDB\Driver\Exception\Exception $e) {

    $filename = basename(__FILE__);

    echo "The $filename script has experienced an error.\n";

    echo "It failed with the following exception:\n";

    echo "Exception:", $e->getMessage(), "\n";

    echo "In file:", $e->getFile(), "\n";

    echo "On line:", $e->getLine(), "\n";

}


?> 


* site 는 컬렉션 명, member 는 도큐멘트 명입니다.



2. Select


<?php


try {

    $mng = new MongoDB\Driver\Manager("mongodb://127.0.0.1:27017");

    $filter = [ 'Name' => 'CDH' ]; // 조건 (완전 일치)

    //$filter = [ 'Name' => array('$regex' => 'C') ]; // 조건 (포함)

    $query = new MongoDB\Driver\Query($filter);

    //$query = new MongoDB\Driver\Query([]); // 조건 없이 전체 조회


    $rows = $mng->executeQuery("site.member", $query);

    foreach ($rows as $row) { // 데이터가 있는대로 반복해서 가져온다.

            echo "이름은 $row->Name 이고, 도시는 $row->City 입니다.";

    }

} catch ......


?>


* 생략된 catch 부분은 Insert 예제와 동일

* 개수 제한 또는 정렬 필요시 filter 아래에 options 추가

$options = [

            'limit' => 50,

            'sort' => ['Date' => -1]

    ];

$query = new MongoDB\Driver\Query($filter, $options);



3. Update


<?php


try {

    $mng = new MongoDB\Driver\Manager("mongodb://127.0.0.1:27017");

    //$filter = [ 'Name' => "CDH", 'City' => "Seoul" ];

    $bulk = new MongoDB\Driver\BulkWrite;

    $bulk->update(

            ['Name' => "CDH", 'City' => "Seoul"], // 조건 (이렇게 직접 입력하거나 위의 $filter 활용)

            ['$set' => ['Name' => "JJE", 'City' => "Busan"]], // 변경값

            ['multi' => True] // 여러개 동시 수정할 경우

    );

    $mng->executeBulkWrite('site.member', $bulk);

} catch ......


?>


* 생략된 catch 부분은 Insert 예제와 동일



4. Delete


<?php


try {

    $mng = new MongoDB\Driver\Manager("mongodb://127.0.0.1:27017");

    $bulk = new MongoDB\Driver\BulkWrite;

    $bulk->delete(['Name' => "CDH"], ['City' => "Seoul"]); // 조건

    $mng->executeBulkWrite('site.member', $bulk);

} catch ......


?>


* 생략된 catch 부분은 Insert 예제와 동일


반응형

댓글()

파일 이벤트 모니터링 패키지 (incrontab)

리눅스/OS 일반|2020. 5. 19. 16:35
반응형

CentOS 8 에서 테스트 했습니다.

Ubuntu 20.04 에서는 데몬 시작시 incrond 대신 incron 을 사용합니다.

 

1. 설치

 

# yum -y install incron

또는

# cd /usr/local/src

# wget http://rpmfind.net/linux/epel/8/Everything/x86_64/Packages/i/incron-0.5.12-12.el8.x86_64.rpm

# rpm -ivh incron-0.5.12-12.el8.x86_64.rpm

 

 

2. 사용 방법

 

우선 incrond 를 실행 합니다.

 

# systemctl enable incrond

# systemctl start incrond

 

설정 방법은 crontab 과 유사 합니다.

 

아래와 같은 설정을 통해 원하는 작업을 실행 시킬 수 있으며,

설정값이 저장되면 crond 와 마찬가지로 incrond 데몬 재시작 없이도 적용이 됩니다.

 

# incrontab -e

 /data        IN_CLOSE_WRITE    /root/run.sh    

 

* 참고

Ubuntu 20.04 에서 아래와 같은 메세지가 출력된다면, 이는 incrontab 명령을 허용할 계정 리스트를 별도로 관리하고 있기 때문입니다.

# incrontab -e

user 'root' is not allowed to use incron

 
아래 파일을 열어 사용하고자 하는 계정을 추가해 줍니다

# vi /etc/incron.allow

 

root

 

* 위 설정 내용을 설명합니다.

/data 디렉토리 내의 파일 감시

파일 쓰기 작업을 끝낸 경우 (IN_CLOSE_WRITE )

/root/run.sh 파일을 실행합니다.

 

* 파일 이벤트 형태는 아래와 같이 다양합니다. (man page)

   > 괄호 안의 * 표시는 디렉토리와 파일에 모두 적용 됩니다.

       IN_ACCESS           File was accessed (read) (*)

       IN_ATTRIB           Metadata changed (permissions, timestamps, extended attributes, etc.) (*)

       IN_CLOSE_WRITE      File opened for writing was closed (*)

       IN_CLOSE_NOWRITE    File not opened for writing was closed (*)

       IN_CREATE           File/directory created in watched directory (*)

       IN_DELETE           File/directory deleted from watched directory (*)

       IN_DELETE_SELF           Watched file/directory was itself deleted

       IN_MODIFY           File was modified (*)

       IN_MOVE_SELF        Watched file/directory was itself moved

       IN_MOVED_FROM       File moved out of watched directory (*)

       IN_MOVED_TO         File moved into watched directory (*)

       IN_OPEN             File was opened (*)

 
* 설정 파일에 아래와 같은 와일드 카드를 사용하여 인자값을 전달 할 수 있습니다. (man page)
       $$   dollar sign
       $@   watched filesystem path (see above)
       $#   event-related file name
       $%   event flags (textually)
       $&   event flags (numerically)
 
* 사용예 (man page)
       /tmp IN_ALL_EVENTS abcd $@/$# $%
       /usr/bin IN_ACCESS,loopable=true abcd $#
       /home IN_CREATE /usr/local/bin/abcd $#
       /home IN_CREATE,dotdirs=true /usr/local/bin/abcd $#
       /home IN_CREATE,recursive=false /usr/local/bin/abcd $#
       /var/log 12 abcd $@/$#
 
 
* 참고
파일 수정 프로세스에 따라 IN_CLOSE_WRITE 가 빈번히 일어나는 경우가 있습니다.
(메일을 한통 받더라도 여러 이벤트가 발생됨)
이 경우 IN_ONESHOT 옵션을 추가하여 한번만 실행하도록 한 다음,
프로세스가 모든 처리를 완료하면 incrond 데몬을 재시작하여 다시 이벤트 감시 상태로 둘 수 있습니다.
 
 
반응형

댓글()

bash shell 에서 mongodb 읽고 쓰기

프로그래밍/BASH SHELL|2020. 5. 13. 16:37
반응형

1. 입력


# mongo -u packet -p 12345678 --host 127.0.0.1 --port 27017 --authenticationDatabase packet --eval 'db.logs.insert({"date" : "2020-05-05 11:22:33", "body" : "eee"})'

MongoDB shell version v3.4.24

connecting to: mongodb://127.0.0.1:27017/

MongoDB server version: 3.4.24

WriteResult({ "nInserted" : 1 })


[설명]

- packet : 계정

- 12345678 : 계정 비밀번호

- 127.0.0.1 : MongoDB 서버 IP

- 27017 : MongoDB Listening 포트

- logs : Collections (테이블 부분)

- { 부터 } 까지 : Documents (데이터 부분)



2. 조회


# mongo -u packet -p 12345678 --host 127.0.0.1 --port 27017 --authenticationDatabase packet --eval 'db.logs.find()'

{ "_id" : ObjectId("5ebb9ff124bd96fec20b5ff0"), "date" : "2020-05-05 11:22:33", "body" : "eee" }


반응형

댓글()

php 7.x 에서 mongodb 연결하기 (CentOS 8)

프로그래밍/PHP|2020. 5. 13. 15:21
반응형

DB 명 : packet

컬렉션명 : logs

Password : 12345678



# vi test.php


<?php

$manager = new MongoDB\Driver\Manager("mongodb://packet:12345678@localhost:27017/packet");


/*

  샘플 컬랙션을 아래와같이 정의하자.

  test {

    name : string,

    name2 : string,

    number : int

  }

*/


//첫번째 배열 값은 질의문이다. 질의할 대상은 도큐먼트이다.

//두번째 배열 값은 옵션이다. projection, skip, limit, sort 같은 것을 줄 수 있다.

$query = new MongoDB\Driver\Query(['date' => '2020-05-05 11:22:33', 'body' => 'aaa'], []);



$rows = $manager->executeQuery("packet.logs", $query);

foreach ($rows as $row) {

    $result1 = $row->name;     //name이라고 불리우는 것이 결과이다.

    $result2 = $row->name2;

}



$bulk = new MongoDB\Driver\BulkWrite;  //저장을 담당하는 객체

$document = [    //저장할 배열

        '_id' => new MongoDB\BSON\ObjectID,

        'name' => '텍스트',

        'number' => 1234,

        'date' => date(),

        'arrayStyle' =>  ['text' => '텍스트', 'num' => 5678]

];

$bulk->insert($document);  //객체에서의 함수 실행

$manager->executeBulkWrite('대상db.컬렉션이름', $bulk); //Manager객체에 내용 전달.

?>

 




반응형

댓글()

스크롤바 항상 출력 시키기

반응형

본문 길이가 길어서 화면을 벗어날 경우 스크롤바가 자동으로 생기는데,

이때 본문의 위치가 스크롤바로 인해 좌측으로 약간 밀리는 현상이 발생됩니다.


이를 방지하기 위해 스크롤바를 항상 출력 시키도록 합니다.

<head> 내에 아래 소스 코드를 첨부합니다.


<style>

<!--

html {overflow-y:scroll;}

-->

</style> 




반응형

댓글()

구글맵 마커 사이즈 조절하기

반응형

int height = 200;

int width = 200;

BitmapDrawable bitmapdraw=(BitmapDrawable)getResources().getDrawable(R.mipmap.marker);

Bitmap b=bitmapdraw.getBitmap();

Bitmap smallMarker = Bitmap.createScaledBitmap(b, width, height, false);


map.addMarker(new MarkerOptions()

                .position(POSITION)

                .title("Your title")

                .icon(BitmapDescriptorFactory.fromBitmap(smallMarker))

                );



[출처] https://stackoverflow.com/questions/14851641/change-marker-size-in-google-maps-api-v2 



반응형

댓글()

google map 에서 움직이는 마커 사용하기

반응형

[출처] https://exceptionshub.com/rotate-marker-and-move-animation-on-map-like-uber-android-2.html


아래 소스는 출력된 마커를 터치하면 목적지까지 부드럽게 마커가 이동하는 소스입니다.

(녹색 부분 제외하면 터치 없이 실행 됩니다)

어렵게 구했습니다.. ㅜ.ㅜ

목적에 맞게 수정해서 사용하면 됩니다.



1. onCreate 에서


SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

mapFragment.getMapAsync(this);



2. onMapReady 에서


@Override

    public void onMapReady(final GoogleMap googleMap) {


        mMap = googleMap;


        final LatLng SomePos = new LatLng(37.52487, 126.92723); // 시작 지점


        try {

            googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); // 지도 타입

            googleMap.setMyLocationEnabled(true); // 내 위치 표시

            googleMap.setTrafficEnabled(false); // 교통정보 레이어

            googleMap.setIndoorEnabled(false); // 실내 지도 여부. 향후 normal 지도 유형에서만 지원 예정

            googleMap.setBuildingsEnabled(true); // 건물 표시

            googleMap.getUiSettings().setZoomControlsEnabled(true); // 줌 컨트롤러 표시 (확대, 축소)

            googleMap.moveCamera(CameraUpdateFactory.newLatLng(SomePos));

            googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder()

                    .target(googleMap.getCameraPosition().target)

                    .zoom(17)

                    .bearing(30) // 지도를 돌려서 보기 (각도)

                    .tilt(45) // 지도를 눞여서 보기 (각도)

                    .build()));


            // 마커 이미지 및 사이즈 변경

            int height = 200;

            int width = 200;

            BitmapDrawable bitmapdraw = (BitmapDrawable)getResources().getDrawable(R.drawable.img_marker);

            Bitmap b = bitmapdraw.getBitmap();

            Bitmap smallMarker = Bitmap.createScaledBitmap(b, width, height, false);


            final Marker myMarker = googleMap.addMarker(new MarkerOptions()

                    .position(SomePos)

                    .icon(BitmapDescriptorFactory.fromBitmap(smallMarker))

                    .title("Hello world"));


            googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {

                @Override

                public boolean onMarkerClick(Marker arg0) {


                    final LatLng startPosition = myMarker.getPosition();

                    final LatLng finalPosition = new LatLng(37.62487, 127.02723); // 끝 지점

                    final Handler handler = new Handler();

                    final long start = SystemClock.uptimeMillis();

                    // AccelerateDecelerateInterpolator 는 마커 이동 유형 (움직이는 스타일)

                    //final Interpolator interpolator = new AccelerateDecelerateInterpolator();

                    final float durationInMs = 4000; // 이동 시간 (ms)


                    handler.post(new Runnable() {

                        long elapsed;

                        float t;


                        @Override

                        public void run() {

                            // Calculate progress using interpolator

                            elapsed = SystemClock.uptimeMillis() - start;

                            t = elapsed / durationInMs;


                            LatLng currentPosition = new LatLng(

                                    startPosition.latitude * (1 - t) + finalPosition.latitude * t,

                                    startPosition.longitude * (1 - t) + finalPosition.longitude * t);


                            myMarker.setPosition(currentPosition);


                            // Repeat till progress is complete.

                            if (t < 1) {

                                // Post again 16ms later.

                                handler.postDelayed(this, 16);

                            }

                        }

                    });

                    return true;

                }

            });


        } catch (Exception e) {

            e.printStackTrace();

        }


    } 



반응형

댓글()