2019년 2월 21일 목요일

[Python] Shell Command


1. Shell Execute with subprocess.communicate()

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
import sys
import os
import time
import select
import copy
import subprocess
import threading
from threading import *

def ShellExecute(cmd, timeout=None):
    
    si = subprocess.STARTUPINFO()
    si.dwFlags |= subprocess.STARTF_USESHOWWINDOW #|subprocess.STARTF_USESTDHANDLES
    si.wShowWindow = subprocess.SW_HIDE
        
    process = subprocess.Popen(cmd
        , shell=True
        , stdin=subprocess.DEVNULL
        , stdout=subprocess.PIPE
        , stderr=subprocess.PIPE
        , startupinfo=si
        )

    outs, errs = process.communicate(timeout=timeout)
        
    return process.returncode, outs, errs


2. Shell Execute with read()

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
import sys
import os
import time
import select
import copy
import subprocess
import threading
from threading import *

def ShellExecuteRealTime(cmd, timeout=None):
    
    si = subprocess.STARTUPINFO()
    si.dwFlags |= subprocess.STARTF_USESHOWWINDOW #|subprocess.STARTF_USESTDHANDLES
    si.wShowWindow = subprocess.SW_HIDE
        
    process = subprocess.Popen(cmd
        , shell=True
        , stdin=subprocess.DEVNULL
        , stdout=subprocess.PIPE
        , stderr=subprocess.DEVNULL
        , startupinfo=si
        )

    outs = b''
    while True:
        char = process.stdout.read() # read(1), process.stderr.readline()
        if not char:
            break
        outs += char
        
    return process.returncode, outs


3. Shell Execute with Thread

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
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
import sys
import os
import time
import select
import copy
import subprocess
import threading
from threading import *

class ShellExecuteThread(object):
    
    def __init__(self, cmd, timeout=None):
        self.cmd = cmd
        self.thread = None
        self.process = None
        self.timeout = timeout
        self.stdouts = None
        self.stderrs = None
        self.running = None
        self.lock = threading.Lock()

    def run(self, timeout=None):
        if timeout is not None:
            self.timeout = timeout
        def target():
            self.running = True
            si = subprocess.STARTUPINFO()
            si.dwFlags |= subprocess.STARTF_USESHOWWINDOW # |subprocess.STARTF_USESTDHANDLES
            si.wShowWindow = subprocess.SW_HIDE
            self.process = subprocess.Popen(self.cmd
                    , shell=True 
                    , stdout=subprocess.PIPE
                    , stderr=subprocess.PIPE                    
                    , startupinfo=si
                    , bufsize=0
                    , universal_newlines=True 
                    , encoding='euc-kr'
                    , text=True
                )
            self.stdouts, self.stderrs = self.process.communicate(self.timeout)
            self.running = False

        self.thread = threading.Thread(target=target)
        self.thread.start()
        
    def runwait(self, timeout=None):
        self.run(timeout)
        self.thread.join(self.timeout)
        if self.thread.is_alive():
            self.process.terminate()
            self.thread.join()

        return self.process.returncode, self.stdouts, self.stderrs

    def run_stdouts(self):
        def target():
            self.running = True
            word = b''
            while True:
                char = self.process.stdout.read(1) #readline()
                if not char:
                    break
                if self.process.poll() is not None:
                    break;
                word += char
                if char.isspace():
                    self.lock.acquire()
                    self.stdouts += word
                    self.lock.release() 
                    word = b''
            if len(word) > 0:
                self.lock.acquire()
                self.stdouts += word
                self.lock.release() 
            self.running = False
            
        si = subprocess.STARTUPINFO()
        si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        si.wShowWindow = subprocess.SW_HIDE
        self.process = subprocess.Popen(self.cmd
                , shell=True 
                , stdout=subprocess.PIPE
                , startupinfo=si
            )

        self.stdouts = b'';
        self.thread = threading.Thread(target=target)
        self.thread.start()
        
    def get_stdouts(self):
        if self.running == True or len(self.stdouts) > 0 is None:
            self.lock.acquire()
            outs = self.stdouts  #copy.deepcopy(self.stdouts)
            self.stdouts = b'';
            self.lock.release()            
            return outs
        else:
            return None
    
    def get_returncode(self):
        if self.process is not None:
            return self.process.returncode
        return None
    


4. Thread Example
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
45
46
47
48
49
50
51
52
53
import sys
import os
import time
import select
import copy
import subprocess
import threading
from threading import *

class WorkerThread(Thread):
    
    def __init__(self, cmd, timeout=None):
        Thread.__init__(self)
        self.cmd = cmd
        self.stoprequest = threading.Event()
        self.start()

    def run(self):
        import subprocess
        global threadLock
        global line
        
        si = subprocess.STARTUPINFO()
        si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        si.wShowWindow = subprocess.SW_HIDE

        process = subprocess.Popen(self.cmd
                , shell=False 
                , stdin=subprocess.DEVNULL
                , stdout=subprocess.PIPE
                , stderr=subprocess.PIPE
                , startupinfo=si
                )

        while not self.stoprequest.isSet():
            char = process.stdout.read(1) #process.stderr.readline()
            if not char:
                break
            if process.poll() is not None:
                break;
            if char != b'\r': # accept only b'\n'
                self.lock.acquire()
                self.stdouts += char
                self.lock.release()    

        errcode = process.returncode
        if errcode is not None:
            raise Exception('cmd %s failed, see above for details', cmd)
        process.terminate()

    def stop(self, timeout=None):
        self.stoprequest.set()
        super(WorkerThread, self).join(timeout)



[Python] File and Directory Operation


File Read, Write Example

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
def fileToString(file):
    f = codecs.open(file, "r", "utf-8")
    text = f.read()
    f.close()
    return text

def stringToFile(file,data):
    f = codecs.open(file, "w", "utf-8")
    f.write(data)
    f.close()

def fileToBinary(file):
    f = open(file, "rb")
    data = f.read()
    f.close()
    return data;
    
def binaryToFile(file,data):
    f = open(file, "wb")
    f.write(data)
    f.close()


File Read Line

f = open("C:/Bin/f.py", 'r')
while True:
    line = f.readline()
    if not line: break
    print(line)
f.close()

with open("C:/Bin/f.py", 'r') as f:
    line = f.readline()
    while line:
        print(line)
        line = f.readline()

f = open("C:/Bin/f.py", 'r')
lines = f.readlines()
for line in lines:
    print(line)
f.close()

with open("C:/Bin/f.py", 'r') as f:
    lines = f.readlines()
    for line in lines:
        print(line)

File Read Binary Data


def getint(f,n):
    v = 0
    l = list(f.read(n))
    for i in range(n):
        v <<= 8
        v |= ord(l[i])
    return v

def getdata(f,n):
    return list(f.read(n))

def pcap_header(f):
    magic = getint(f,4)
    major = getint(f,2)
    minor = getint(f,2)
    getdata(f,16)
    print( "%08x" % magic )
              
with open('C:/Bin/ecpri.pcap','rb') as f:
    if pcap_header(f):
        pass
    

File Search Operation

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import codecs
import os

def searchFile(dirname, recurse=False, extensions=None):
    list = []
    filenames = os.listdir(dirname)
    for filename in filenames:
        full_filename = os.path.join(dirname, filename)
        if os.path.isdir(full_filename) and recurse == True:
            list += searchFile(full_filename, recurse=recurse, extensions=extensions)
        if os.path.isfile(full_filename):
            ext = os.path.splitext(filename)[1]
            if extensions is None or ext in extensions:
                list.append(full_filename)
    return list


File Operation with os.walk

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import codecs
import os

def walkDir(dirname,extensions):
    list = []
    for (path, dirs, files) in os.walk(dirname):
        print( path, dirs, files )
        for filename in files:
            ext = os.path.splitext(filename)[-1]
            if ext in extensions:
                list.append(os.path.join(path, filename))
    return list



2019년 2월 13일 수요일

[python] wxPython Examples


1. wxFormBuilder





Generaged Code:

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# -*- coding: utf-8 -*-

###########################################################################
## Python code generated with wxFormBuilder (version Oct 26 2018)
## http://www.wxformbuilder.org/
##
## PLEASE DO *NOT* EDIT THIS FILE!
###########################################################################

import wx
import wx.xrc

wx.ID_MenuExit = 1000

###########################################################################
## Class wxForm
###########################################################################

class wxForm ( wx.Frame ):

 def __init__( self, parent ):
  wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = u"wxForm", pos = wx.DefaultPosition, size = wx.Size( 500,300 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )

  self.SetSizeHints( wx.DefaultSize, wx.DefaultSize )

  self.m_menubar1 = wx.MenuBar( 0 )
  self.m_menuFile = wx.Menu()
  self.m_menuItemExit = wx.MenuItem( self.m_menuFile, wx.ID_MenuExit, u"Exit", wx.EmptyString, wx.ITEM_NORMAL )
  self.m_menuItemExit.SetBitmap( wx.Bitmap( u"icon/exit.png", wx.BITMAP_TYPE_ANY ) )
  self.m_menuFile.Append( self.m_menuItemExit )

  self.m_menubar1.Append( self.m_menuFile, u"File" )

  self.SetMenuBar( self.m_menubar1 )

  self.m_statusBar1 = self.CreateStatusBar( 1, wx.STB_SIZEGRIP, wx.ID_ANY )
  self.m_toolBar1 = self.CreateToolBar( wx.TB_DEFAULT_STYLE|wx.TB_FLAT|wx.TB_HORIZONTAL|wx.TB_TEXT, wx.ID_ANY )
  self.m_toolExit = self.m_toolBar1.AddLabelTool( wx.ID_ANY, u"Exit", wx.Bitmap( u"icon/exit.png", wx.BITMAP_TYPE_ANY ), wx.NullBitmap, wx.ITEM_NORMAL, wx.EmptyString, wx.EmptyString, None )

  self.m_toolBar1.Realize()

  bSizer1 = wx.BoxSizer( wx.VERTICAL )

  self.m_splitter1 = wx.SplitterWindow( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.SP_3D|wx.SP_BORDER )
  self.m_splitter1.SetSashSize( 6 )
  self.m_splitter1.Bind( wx.EVT_IDLE, self.m_splitter1OnIdle )

  self.m_panel1 = wx.Panel( self.m_splitter1, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
  self.m_panel1.SetMinSize( wx.Size( 120,-1 ) )

  bSizer3 = wx.BoxSizer( wx.VERTICAL )

  m_comboBox1Choices = [ u"Combo 1", u"Combo 2", u"Combo 3" ]
  self.m_comboBox1 = wx.ComboBox( self.m_panel1, wx.ID_ANY, u"Combo 1", wx.DefaultPosition, wx.DefaultSize, m_comboBox1Choices, 0 )
  bSizer3.Add( self.m_comboBox1, 0, wx.ALL|wx.EXPAND, 5 )

  self.m_buttonClear = wx.Button( self.m_panel1, wx.ID_ANY, u"Clear", wx.DefaultPosition, wx.DefaultSize, 0 )
  bSizer3.Add( self.m_buttonClear, 0, wx.ALL|wx.EXPAND, 1 )

  self.m_buttonCopy = wx.Button( self.m_panel1, wx.ID_ANY, u"Copy", wx.DefaultPosition, wx.DefaultSize, 0 )
  bSizer3.Add( self.m_buttonCopy, 0, wx.ALL|wx.EXPAND, 1 )

  self.m_buttonPaste = wx.Button( self.m_panel1, wx.ID_ANY, u"Paste", wx.DefaultPosition, wx.DefaultSize, 0 )
  bSizer3.Add( self.m_buttonPaste, 0, wx.ALL|wx.EXPAND, 1 )


  self.m_panel1.SetSizer( bSizer3 )
  self.m_panel1.Layout()
  bSizer3.Fit( self.m_panel1 )
  self.m_panel2 = wx.Panel( self.m_splitter1, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
  self.m_panel2.SetMinSize( wx.Size( 200,-1 ) )

  bSizer4 = wx.BoxSizer( wx.VERTICAL )

  self.m_textCtrl1 = wx.TextCtrl( self.m_panel2, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, wx.TE_MULTILINE )
  bSizer4.Add( self.m_textCtrl1, 1, wx.ALL|wx.EXPAND, 5 )


  self.m_panel2.SetSizer( bSizer4 )
  self.m_panel2.Layout()
  bSizer4.Fit( self.m_panel2 )
  self.m_splitter1.SplitVertically( self.m_panel1, self.m_panel2, 120 )
  bSizer1.Add( self.m_splitter1, 1, wx.EXPAND|wx.TOP, 1 )


  self.SetSizer( bSizer1 )
  self.Layout()

  self.Centre( wx.BOTH )

 def __del__( self ):
  pass

 def m_splitter1OnIdle( self, event ):
  self.m_splitter1.SetSashPosition( 120 )
  self.m_splitter1.Unbind( wx.EVT_IDLE )



2. Event Handler


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
 def OnFileExit(self, event):
  self.Close(True)
  
 def OnClose(self, event):
  dlg = wx.MessageDialog(self, 
          "Do you really want to close this application?",
          "Confirm Exit", wx.OK|wx.CANCEL|wx.ICON_QUESTION)
  result = dlg.ShowModal()
  dlg.Destroy()
  if result == wx.ID_OK:
   self.Destroy()

 def OnClear(self, event):
  self.m_textCtrl1.Clear()
   
 def OnCopy(self, event):
  if wx.TheClipboard.Open():
   wx.TheClipboard.SetData(wx.TextDataObject(self.m_textCtrl1.GetValue()))
   wx.TheClipboard.Close()
   
 def OnPaste(self, event):
  text_data = wx.TextDataObject()
  if wx.TheClipboard.Open():
   success = wx.TheClipboard.GetData(text_data)
   wx.TheClipboard.Close()
  if success:
   self.m_textCtrl1.SetValue(text_data.GetText())
   


3. Main Loop and Event Registration


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
if __name__ == '__main__':
 app = wx.PySimpleApp()
 frame = wxForm(None)
 frame.SetIcon(wx.Icon("icon/icon.ico", wx.BITMAP_TYPE_ANY))
 frame.Bind(wx.EVT_CLOSE, frame.OnClose)
 frame.Bind(wx.EVT_MENU, frame.OnFileExit, frame.m_menuItemExit)
 frame.Bind(wx.EVT_TOOL, frame.OnFileExit, frame.m_toolExit )
 frame.Bind(wx.EVT_BUTTON, frame.OnClear, frame.m_buttonClear )
 frame.Bind(wx.EVT_BUTTON, frame.OnCopy, frame.m_buttonCopy )
 frame.Bind(wx.EVT_BUTTON, frame.OnPaste, frame.m_buttonPaste )
 frame.SetStatusText("Ready")
 frame.Show() 
 app.MainLoop()




2019년 2월 1일 금요일

[Markdown] Markdown Syntax


Reference : https://www.markdownguide.org/basic-syntax/

Headings

# heading 1
## heading 2
### heading 3
#### heading 4
##### heading 5
###### heading 6

Heading level 1
===============

Heading level 2
---------------

Emphasis

*Emphasis* _Emphasis_ (Italic)
**String** __String__ (Bold)
*__BoldItalic__*
**_BoldItalic_**

List

1. 1) Numbered List
* + - Bullet List

Blockquotes

> Block Quote Level 1
>> Block Quote Level 2

Code

`Code Span`
```
Code Block
```

Table

Left  | Center | Right
:---  | :---:  | ---:
d1 | d2 | d3

Line

--- ___ Horizontal Rule

Link

[Link](http://url.com "Title")

[Reference Link][ID]
[ID]: http://url.com "Reference Definition"

![Image][./image.jpg "Title"]

Paragraphs

To create paragraphs, use a blank line to separate one or more lines of text. You should not indent paragraphs with spaces or tabs.

Line Breaks

To create a line break, end a line with two or more spaces, and then type return.

Escape

CharacterName
\backslash
`tick mark
*asterisk
_underscore
{}curly braces
[]brackets
()parentheses
#pound sign
+plus sign
-minus sign (hyphen)
.dot
!exclamation mark

[Markdown] How to embed PlantUML


1. Process File


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
public static int processFile(File inFile, File outDir, String outFilePrefix, FileFormat outFormat) 
        throws IOException, InterruptedException {

    final Option option = new Option(); 
    if (inFile.exists() == false) {
            throw new IllegalArgumentException();
    }
    FileSystem.getInstance().setCurrentDir(inFile.getAbsoluteFile().getParentFile());
    BlockUmlBuilder builder = new BlockUmlBuilder(
            new ArrayList<String>(), //option.getConfig(),  
            "UTF-8", //option.getCharset(), 
            createEmpty(), //option.getDefaultDefines(file), 
            new InputStreamReader(new FileInputStream(inFile), "UTF-8"),
            inFile.getAbsoluteFile().getParentFile(), 
            inFile.getName());      

    //final List<GeneratedImage> result = new ArrayList<>();
    int count = 0;
    for (BlockUml blockUml : builder.getBlockUmls()) {    
        final Diagram system;
        try {
            system = blockUml.getDiagram();
            final List<FileImageData> exportDiagrams = PSystemUtils.exportDiagrams(system, 
                SuggestedFile.fromOutputFile(new File(outDir, outFilePrefix  + count) , outFormat, 0),
                new FileFormatOption(outFormat),
                false);
            if (exportDiagrams.size() > 1) {
                    exportDiagrams.size();
            }    
            count++;
        } catch (Throwable t) {
            return 0;
        }
    }     
    return count;
}



[Markdown] Mermaid Examples


1. Mermaid Flowchart (1)

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="script/mermaid.css" />
<script src="script/mermaid.min.js"></script>
</head>
<body>
<div class="mermaid">
graph TD
A[Christmas] -->|Get money| B(Go shopping)
B --> C{Let me think}
C -->|One| D[Laptop]
C ==>|Two| E["iPhone #9829;"]
D --- E
C -.->|Three| F[fa:fa-car Car]
F -. Loop .-> B
</div>
</body>
</html>


Output:



2. Mermaid Flowchart (1)


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/mermaid/7.0.0/mermaid.css" rel="stylesheet"/>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mermaid/7.0.0/mermaid.js"></script>
</head>
<body>
    <div class="mermaid">
        graph LR
            A-->B
            B-->C
            C-->A
            D-->C
    </div>
</body>
</html>


Output:





[Markdown] Vega-Lite Examples


1. Vega-Lite Bar Chart Example (1)

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<!DOCTYPE html>
<html>
  <head>
    <title>Vega-Lite Bar Chart</title>
    <meta charset="utf-8" />

    <script src="https://cdn.jsdelivr.net/npm/vega@4.4.0/build/vega.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vega-lite@3.0.0-rc12/build/vega-lite.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vega-embed@3.29.1/build/vega-embed.js"></script>

    <style media="screen">
      /* Add space between Vega-Embed links  */
      .vega-actions a {
        margin-right: 5px;
      }
    </style>
  </head>
  <body>
    <h1>Template for Embedding Vega-Lite Visualization</h1>
    <!-- Container for the visualization -->
    <div id="vis"></div>

    <script>
      // Assign the specification to a local variable vlSpec.
      var vlSpec = {
        $schema: 'https://vega.github.io/schema/vega-lite/v3.json',
        data: {
          values: [
            {a: 'C', b: 2},
            {a: 'C', b: 7},
            {a: 'C', b: 4},
            {a: 'D', b: 1},
            {a: 'D', b: 2},
            {a: 'D', b: 6},
            {a: 'E', b: 8},
            {a: 'E', b: 4},
            {a: 'E', b: 7}
          ]
        },
        mark: 'bar',
        encoding: {
          y: {field: 'a', type: 'nominal'},
          x: {
            aggregate: 'average',
            field: 'b',
            type: 'quantitative',
            axis: {
              title: 'Average of b'
            }
          }
        }
      };

      // Embed the visualization in the container with id `vis`
      vegaEmbed('#vis', vlSpec);
    </script>
  </body>
</html>


Output:



2. Vega-Lite Bar Chart Example (2)


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
45
46
47
48
49
50
51
52
53
54
55
56
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <script src="script/vega.js"></script>
  <script src="script/vega-lite.js"></script>
  <script src="script/vega-embed.js"></script>
  <style media="screen">
      /* Add space between Vega-Embed links  */
      .vega-actions a {
        margin-right: 5px;
      }
  </style>
  <script>
    function readSingleFile(e) {
    var file = e.target.files[0];
    if (!file) {
      return;
    }
    var reader = new FileReader();
    reader.onload = function(e) {
      var contents = e.target.result;
      displayContents(contents);
    };
      reader.readAsText(file);
    }
  </script>
</head>

<body>  
  <div id="vis"></div>
  
  <script>
  var spec = //readSingleFile("vega_demo_2.json");
  {
  "$schema": "https://vega.github.io/schema/vega-lite/v3.json",
  "description": "A simple bar chart with embedded data.",
  "width": 360,
  "data": {
    "values": [
      {"a": "A","b": 28}, {"a": "B","b": 55}, {"a": "C","b": 43},
      {"a": "D","b": 91}, {"a": "E","b": 81}, {"a": "F","b": 53},
      {"a": "G","b": 19}, {"a": "H","b": 87}, {"a": "I","b": 52}
    ]
  },
  "mark": "bar",
  "encoding": {
    "x": {"field": "a", "type": "ordinal"},
    "y": {"field": "b", "type": "quantitative"},
    "tooltip": {"field": "b", "type": "quantitative"}
  }
  };
  vegaEmbed('#vis', spec)
  </script>
</body>
</html>

Output:



3. Vega-Lite Line Chart Example 


1
"mark": "line",

Output:


4. Vega-Lite Area Chart Example 


1
"mark": "area",

Output:







2018년 12월 24일 월요일

[Utility] ImageMagick Examples


1. Make Android Icon

C:\> andicon.bat  
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
mkdir %1
mkdir %1\drawable-mdpi
mkdir %1\drawable-hdpi
mkdir %1\drawable-xhdpi
mkdir %1\drawable-xxhdpi
mkdir %1\drawable-xxxhdpi
convert.exe %1.png -resize 48x48   %1\drawable-mdpi\%1.png
convert.exe %1.png -resize 72x72   %1\drawable-hdpi\%1.png
convert.exe %1.png -resize 96x96   %1\drawable-xhdpi\%1.png
convert.exe %1.png -resize 144x144 %1\drawable-xxhdpi\%1.png
convert.exe %1.png -resize 192x192 %1\drawable-xxxhdpi\%1.png


2. Make Font Image

- English Character

1
convert -size 768x128 xc:white -font Ravie -pointsize %1 -stroke black -strokewidth 8 -annotate +25+100 %2 -blur 0x8 -fill white   -stroke none   -annotate +25+100 %2 %2.png


- Korean Character
1
2
3
set font=malgunbd.ttf

convert -size 512x300 xc:white -font %font% -pointsize %1 -stroke black -strokewidth 8 -annotate +4+200 %2 -blur 0x8 -fill white -stroke none -annotate +4+200 %2 %2.png