<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jack Pan on Medium]]></title>
        <description><![CDATA[Stories by Jack Pan on Medium]]></description>
        <link>https://medium.com/@jackklpan?source=rss-47facfc2b4c6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*YwOFaevo7cbVIMbh.png</url>
            <title>Stories by Jack Pan on Medium</title>
            <link>https://medium.com/@jackklpan?source=rss-47facfc2b4c6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 14:39:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jackklpan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Flask-SQLAlchemy: one table has two 1-to-many relationships to another table]]></title>
            <link>https://medium.com/@jackklpan/flask-sqlalchemy-one-table-has-two-1-to-many-relationships-to-another-table-15c59e5e3931?source=rss-47facfc2b4c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/15c59e5e3931</guid>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[one-to-many]]></category>
            <category><![CDATA[flask-sqlalchemy]]></category>
            <dc:creator><![CDATA[Jack Pan]]></dc:creator>
            <pubDate>Fri, 28 Jul 2023 14:58:24 GMT</pubDate>
            <atom:updated>2023-07-28T14:58:24.073Z</atom:updated>
            <content:encoded><![CDATA[<p>For example:</p><pre>class Request(db.Model):<br>    id = db.Column(db.Integer, autoincrement=True, primary_key=True)<br>    title = db.Column(db.String)<br><br>    requester_id = db.Column(db.Integer, db.ForeignKey(&quot;user.id&quot;))<br>    approval_id = db.Column(db.Integer, db.ForeignKey(&quot;user.id&quot;))</pre><pre>class User(db.Model):<br>    id = db.Column(db.Integer, autoincrement=True, primary_key=True)<br>    name = db.Column(db.Text)<br><br>    requests = db.relationship(&quot;Request&quot;, foreign_keys=[Request.requester_id], backref=&quot;requester&quot;)<br>    approval_requests = db.relationship(&quot;Request&quot;, foreign_keys=[Request.approval_id], backref=&quot;approval_by&quot;)</pre><p>Should add foregin_keys in db.relationship function.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15c59e5e3931" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flask/Python Decorator Order]]></title>
            <link>https://medium.com/@jackklpan/flask-python-decorator-order-6fa57d0295a9?source=rss-47facfc2b4c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fa57d0295a9</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[decorators]]></category>
            <category><![CDATA[flask]]></category>
            <dc:creator><![CDATA[Jack Pan]]></dc:creator>
            <pubDate>Fri, 28 Jul 2023 14:53:52 GMT</pubDate>
            <atom:updated>2023-07-28T14:53:52.100Z</atom:updated>
            <content:encoded><![CDATA[<p>The order of decorators sometimes will affect the result.</p><p>For example, I want to check if a user is the admin or not. I have two decorators. One is login_required, and one is admin_required.</p><p>TL;DR, the order should be:</p><pre>@app.route(&quot;&quot;)<br>@login_required<br>@admin_required<br>def some_func_need_admin_permission():<br>  pass</pre><p>The login_required should be in front of admin_required.</p><p>The make sure the user is logged in and then we check if the user has admin permission.</p><p>You can check the example <a href="https://stackoverflow.com/questions/27342149/decorator-execution-order">here</a>.</p><pre>print(&quot;========== Definition ==========&quot;)<br>def decorator(extra):<br>    print(&quot; in decorator factory for %s &quot; % extra)<br>    extra = &quot; %s&quot; % extra<br>    def inner(func):<br>        print(&quot; defining decorator %s &quot; % extra)<br>        def wrapper(*args, **kwargs):<br>            print(&quot;before %s -- %s&quot; % (func.__name__, extra))<br>            func(*args, **kwargs)<br>            print(&quot;after %s -- %s&quot; % (func.__name__, extra))<br>        return wrapper<br>    return inner<br><br>@decorator(&#39;first&#39;)<br>@decorator(&#39;middle&#39;)<br>@decorator(&#39;last&#39;)<br>def hello():<br>    print(&#39;  Hello &#39;)<br><br>print(&quot;\n========== Execution ==========&quot;)<br>hello()</pre><pre>========== Definition ==========<br> in decorator factory for first <br> in decorator factory for middle <br> in decorator factory for last <br> defining decorator  last <br> defining decorator  middle <br> defining decorator  first <br><br>========== Execution ==========<br>before wrapper --  first<br>before wrapper --  middle<br>before hello --  last<br>  Hello <br>after hello --  last<br>after wrapper --  middle<br>after wrapper --  first</pre><ul><li>When the interpreter is evaluating the decorated method definition the decorators are evaluated from <strong><em>bottom → top</em></strong></li><li>When the interpreter calls the decorated method the decorators are called from <strong><em>top → bottom</em></strong></li></ul><p>So, the function:</p><pre>@login_required<br>@admin_required<br>def some_func_need_admin_permission():<br>  pass</pre><p>becomes login_required(admin_required(some_func_need_admin_permission)).</p><p>And we should be aware that the decorator returns the wrapper. Therefore, the call will be from top-&gt;bottom.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fa57d0295a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Run Puppeteer in Google Cloud Functions v2]]></title>
            <link>https://medium.com/@jackklpan/run-puppeteer-in-google-cloud-functions-v2-b18a353e609b?source=rss-47facfc2b4c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/b18a353e609b</guid>
            <category><![CDATA[google-cloud-functions]]></category>
            <category><![CDATA[puppeteer]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-crawler]]></category>
            <category><![CDATA[cloud-functions]]></category>
            <dc:creator><![CDATA[Jack Pan]]></dc:creator>
            <pubDate>Wed, 05 Apr 2023 13:22:52 GMT</pubDate>
            <atom:updated>2023-04-05T13:22:52.387Z</atom:updated>
            <content:encoded><![CDATA[<p>The latest version of Node.js in Google Cloud Function v2 is missing Chromium dependencies. Therefore, we cannot use the latest version. If you want to use latest version, try to use Google Cloud Run instead.</p><p>We should choose Node.js 16. Select the memory at least 1GB.</p><p>And create the following files:</p><h4>index.js</h4><pre>const functions = require(&#39;@google-cloud/functions-framework&#39;);<br>const puppeteer = require(&#39;puppeteer&#39;);<br><br>const PUPPETEER_OPTIONS = {<br>  headless: true,<br>};<br><br>functions.http(&#39;helloHttp&#39;, async (req, res) =&gt; {<br>  const browser = await puppeteer.launch(PUPPETEER_OPTIONS);<br>  const page = await browser.newPage();<br><br>  // your logic here<br><br>  res.send(`Hello ${req.query.name || req.body.name || &#39;World&#39;}!`);<br>});</pre><h4>package.json</h4><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;gcp-build&quot;: &quot;node node_modules/puppeteer/install.js&quot;<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;@google-cloud/functions-framework&quot;: &quot;^3.0.0&quot;,<br>    &quot;puppeteer&quot;: &quot;^19.8.0&quot;<br>  }<br>}</pre><h4>.puppeteerrc.cjs</h4><pre>const {join} = require(&#39;path&#39;);<br><br>/**<br> * @type {import(&quot;puppeteer&quot;).Configuration}<br> */<br>module.exports = {<br>  // Changes the cache location for Puppeteer.<br>  cacheDirectory: join(__dirname, &#39;.cache&#39;, &#39;puppeteer&#39;),<br>};</pre><p>Then it should work.</p><h3>Reference</h3><ul><li><a href="https://pptr.dev/troubleshooting#running-puppeteer-on-google-cloud-functions">Troubleshooting | Puppeteer (pptr.dev)</a></li><li><a href="https://pptr.dev/guides/configuration#changing-the-default-cache-directory">Configuration | Puppeteer (pptr.dev)</a></li><li><a href="https://hume.dev/articles/puppeteer-google-cloud-functions-v2/">How to use Puppeteer in Google Cloud Functions v2 | hume.dev</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b18a353e609b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setup formatting / linting for Python when committing]]></title>
            <link>https://medium.com/@jackklpan/setup-formatting-linting-for-python-when-committing-888ab40a1057?source=rss-47facfc2b4c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/888ab40a1057</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[linting]]></category>
            <category><![CDATA[pre-commit]]></category>
            <category><![CDATA[pep8]]></category>
            <category><![CDATA[formatting]]></category>
            <dc:creator><![CDATA[Jack Pan]]></dc:creator>
            <pubDate>Fri, 31 Dec 2021 09:48:36 GMT</pubDate>
            <atom:updated>2021-12-31T09:48:36.145Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we use Python package pre-commit to setup the git commit hook which will be triggered when we type the git commit -m &#39;xxx&#39; .</p><p>And use black+ isort to do the formatting. Use flake8 to do the linting.</p><p>First, please make sure you are in the folder which is under git controls. Or you can type git init to initialize the git settings.</p><p>Type the following commands.</p><pre>pip install pre-commit<br>touch .pre-commit-config.yaml<br>pre-commit install</pre><p>pre-commit install uses pre-commit package to setup the git hook. And it uses the file .pre-commit-config.yaml to know what hooks should be triggered when we type git commit -m &#39;xxx&#39; .</p><p>Let’s open an editor and modify the .pre-commit-config.yaml as the following content.</p><pre>repos:<br>- repo: <a href="https://github.com/psf/black">https://github.com/psf/black</a><br>  rev: 21.12b0<br>  hooks:<br>  - id: black<br>- repo: <a href="https://github.com/PyCQA/isort">https://github.com/PyCQA/isort</a><br>  rev: 5.10.1<br>  hooks:<br>  - id: isort<br>    args: [&quot;--profile&quot;, &quot;black&quot;]<br>- repo: <a href="https://gitlab.com/pycqa/flake8">https://gitlab.com/pycqa/flake8</a><br>  rev: 4.0.1<br>  hooks:<br>  - id: flake8<br>    args: [&quot;--max-line-length&quot;, &quot;88&quot;]</pre><p>You can change the rev in each repos to the latest one.</p><p>And all things are done. Now, whenever you commit, the black and isort will check and format you Python file and the flake8 will check your Python file format.</p><p>For example, a Python file test.py.</p><pre>import os</pre><pre>a = [1, 2,<br>3]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*UBscaDgM2khl-s8MZMnecw.png" /></figure><p>The file will be modified by black and show the error message about the unused import. So it become as the following.</p><pre>import os</pre><pre>a = [1, 2, 3]</pre><p>In order to pass the check by flake8 . Let’s remove the unused import.</p><pre>a = [1, 2, 3]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*WQHFcpIssg0OqsFGHKHHzw.png" /></figure><p>Passed the check and you successfully commit the file.</p><p>Through these settings, we can ensure our Python files have the good format and follow the PEP 8 coding style guide.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=888ab40a1057" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setup black, isort, flake8 in VSCode]]></title>
            <link>https://medium.com/@jackklpan/auto-format-and-lint-by-black-isort-flake8-in-vs-visual-studio-code-a62a3f5d940e?source=rss-47facfc2b4c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a62a3f5d940e</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pep8]]></category>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[visual-studio-code]]></category>
            <category><![CDATA[linter]]></category>
            <dc:creator><![CDATA[Jack Pan]]></dc:creator>
            <pubDate>Sat, 13 Nov 2021 08:19:59 GMT</pubDate>
            <atom:updated>2021-12-19T13:55:40.784Z</atom:updated>
            <content:encoded><![CDATA[<p>After you completed this article, the Python code will be auto formatting and linting whenever you save the file in VSCode.</p><h3>VSCode Python Extension</h3><p>Please make sure you have installed the python extension in the VSCode. You can install it through the UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bDvrIXFoa7-nMSpTdZrrfw.png" /></figure><p>Or type the “Ctrl + p” or “Cmd + p” (Based on you are using the Windows or MacOS). Paste the below line and hit enter to install.</p><pre>ext install ms-python.python</pre><h3>Black</h3><p>First, install the black into your Python environment by pip.</p><pre>pip install black</pre><p>Type the “Ctrl + ,” or “Cmd + ,” to open the settings page in the VSCode. (You can also find it through UI “Preferences -&gt; Settings”)</p><p>Search “format on save” and check the checkbox.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z7zZjirWpfIndN4fl8N00Q.png" /></figure><p>Search “python formatting provider” and select the “black”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cDBwz6KGXtXuyS68omHR6A.png" /></figure><p>Now, if you open the python file and save, it will be auto formatted by the black!</p><p>For example, if your file is like this before:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*xF4h5VOZ7ZpegdTKQ_9L-g.png" /></figure><p>After save, it will be like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*hL4MEhX5A90lHlyazyqhUA.png" /></figure><h3>isort</h3><p>Type “Ctrl + Shift + P” or “Cmd + Shift + P”. Search the “Preferences: Configure Language Specific Settings” and press enter. And search the “Python” and press enter. It will open the “settings.json”.</p><p>Please add the following settings:</p><pre>&quot;editor.codeActionsOnSave&quot;: {<br>    &quot;source.organizeImports&quot;: true<br>}</pre><p>Therefore, it may look like this:</p><pre>{<br>    &quot;python.formatting.provider&quot;: &quot;black&quot;,<br>    &quot;editor.formatOnSave&quot;: true,<br>    &quot;editor.codeActionsOnSave&quot;: {<br>        &quot;source.organizeImports&quot;: true<br>    }<br>}</pre><p>(VSCode already has the built-in function to use isort so that we don’t need to install it by pip)</p><p>Then isort will reorder your import order when you save the file. For example, if the file you have is like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*6PQSjsvYmmZYxo-v6-qYzw.png" /></figure><p>After save, it will be like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*6OWvN23HMM92F-UY8d4klQ.png" /></figure><h3>flake8</h3><p>First, install the flake8 into your Python environment by pip.</p><pre>pip install flake8</pre><p>Type “Ctrl + Shift + P” or “Cmd + Shift + P”. Search the “Python: Select Linter” and press enter. Select the “flake8”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*uxl_nQwPuhwc8J06Pf6DsQ.png" /></figure><p>Linting runs automatically when you save a file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*b2zp_LBdgWcu2avICo51ZQ.png" /></figure><h3>Reference</h3><ul><li><a href="https://marcobelo.medium.com/setting-up-python-black-on-visual-studio-code-5318eba4cd00">https://marcobelo.medium.com/setting-up-python-black-on-visual-studio-code-5318eba4cd00</a></li><li><a href="https://www.techiediaries.com/vscode-automatically-organize-python-imports/">https://www.techiediaries.com/vscode-automatically-organize-python-imports/</a></li><li><a href="https://code.visualstudio.com/docs/python/linting">https://code.visualstudio.com/docs/python/linting</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a62a3f5d940e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make Mac Terminal App Beautiful and Productive]]></title>
            <link>https://medium.com/@jackklpan/make-mac-terminal-app-beautiful-and-productive-213f24c0ef4f?source=rss-47facfc2b4c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/213f24c0ef4f</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[mac]]></category>
            <dc:creator><![CDATA[Jack Pan]]></dc:creator>
            <pubDate>Mon, 11 Oct 2021 04:21:01 GMT</pubDate>
            <atom:updated>2021-10-11T04:21:01.426Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lGZ4cswXnlvZ231cqJZWmw.png" /></figure><h3>Install Homebrew</h3><pre>/bin/bash -c &quot;$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)&quot;</pre><h3>Install Zsh</h3><pre><em># Install zsh</em><br>brew install zsh<br><em># Set zsh as your default shell</em><br>chsh -s /usr/local/bin/zsh</pre><h3>Install Terminal Profile</h3><ol><li>You can go to <a href="https://github.com/lysyi3m/osx-terminal-themes">osx-terminal-theme</a> and download your favorite theme. But, I use the theme from: <a href="https://github.com/sindresorhus/terminal-snazzy">https://github.com/sindresorhus/terminal-snazzy</a>.</li><li>Double click the downloaded “xxx.terminal” or right-click on the file and select Open with &gt; Terminal</li><li>Open Terminal &gt; Preferences &gt; Text and select the “xxx” theme and click on “Default” button</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*0ZbpPZmU2W_O4FSt4jqtdg.png" /></figure><h3>Install oh-my-zsh</h3><pre>sh -c &quot;$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)&quot;</pre><h3>Install Themes</h3><pre>brew tap homebrew/cask-fonts<br>brew install --cask font-fira-code</pre><p>Change your font settings in the Terminal to Fira Code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*KY0gikZUGnb1vWZJ-veaKQ.png" /></figure><pre>brew install starship<br>echo &#39;eval &quot;$(starship init zsh)&quot;&#39; &gt;&gt; ~/.zshrc</pre><h3>Install on-my-zsh plugins</h3><h4>autojump</h4><pre>brew install autojump</pre><p>Add the plugin to the list of plugins for oh-my-zsh to load (inside ~/.zshrc).</p><pre>plugins=( <br>    # other plugins...<br>    autojump<br>)</pre><h4>zsh-syntax-highlighting</h4><pre>git clone https://github.com/zsh-users/zsh-syntax-highlighting.git ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting</pre><p>Add the plugin to the list of plugins for oh-my-zsh to load (inside ~/.zshrc).</p><pre>plugins=( <br>    # other plugins...<br>    zsh-syntax-highlighting<br>)</pre><h4>zsh-autosuggestions</h4><pre>git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions</pre><p>Add the plugin to the list of plugins for oh-my-zsh to load (inside ~/.zshrc).</p><pre>plugins=( <br>    # other plugins...<br>    zsh-autosuggestions<br>)</pre><h3>Reference</h3><h4>English</h4><ul><li><a href="https://tonyxu.io/posts/2018/ultimate-way-to-beautify-mac-terminal-and-recommendations-for-plugins/">https://tonyxu.io/posts/2018/ultimate-way-to-beautify-mac-terminal-and-recommendations-for-plugins/</a></li><li><a href="https://opensource.com/article/20/8/iterm2-zsh">https://opensource.com/article/20/8/iterm2-zsh</a></li><li><a href="https://towardsdatascience.com/the-ultimate-guide-to-your-terminal-makeover-e11f9b87ac99">https://towardsdatascience.com/the-ultimate-guide-to-your-terminal-makeover-e11f9b87ac99</a></li><li><a href="https://starship.rs/faq/#what-is-the-configuration-used-in-the-demo-gif">https://starship.rs/faq/#what-is-the-configuration-used-in-the-demo-gif</a></li><li><a href="https://www.freecodecamp.org/news/jazz-up-your-bash-terminal-a-step-by-step-guide-with-pictures-80267554cb22/">https://www.freecodecamp.org/news/jazz-up-your-bash-terminal-a-step-by-step-guide-with-pictures-80267554cb22/</a></li></ul><h4>Chinese</h4><ul><li><a href="https://medium.com/@jinghua.shih/mac-setup-%E8%AE%93%E4%BD%A0%E7%9A%84%E9%96%8B%E7%99%BC%E9%80%9F%E5%BA%A6%E5%A4%A7%E8%BA%8D%E9%80%B2-cd07fa327aaf">https://medium.com/@jinghua.shih/mac-setup-%E8%AE%93%E4%BD%A0%E7%9A%84%E9%96%8B%E7%99%BC%E9%80%9F%E5%BA%A6%E5%A4%A7%E8%BA%8D%E9%80%B2-cd07fa327aaf</a></li><li><a href="https://medium.com/%E6%95%B8%E6%93%9A%E4%B8%8D%E6%AD%A2-not-only-data/macos-%E7%9A%84-terminal-%E5%A4%A7%E6%94%B9%E9%80%A0-iterms-oh-my-zsh-%E5%85%A8%E6%94%BB%E7%95%A5-77d5aae87b10">https://medium.com/%E6%95%B8%E6%93%9A%E4%B8%8D%E6%AD%A2-not-only-data/macos-%E7%9A%84-terminal-%E5%A4%A7%E6%94%B9%E9%80%A0-iterms-oh-my-zsh-%E5%85%A8%E6%94%BB%E7%95%A5-77d5aae87b10</a></li><li><a href="https://medium.com/statementdog-engineering/prettify-your-zsh-command-line-prompt-3ca2acc967f">https://medium.com/statementdog-engineering/prettify-your-zsh-command-line-prompt-3ca2acc967f</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=213f24c0ef4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s try OpenPAI]]></title>
            <link>https://blog.infuseai.io/lets-try-openpai-8b4c36c5a990?source=rss-47facfc2b4c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b4c36c5a990</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[platform]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Jack Pan]]></dc:creator>
            <pubDate>Wed, 26 Feb 2020 10:11:39 GMT</pubDate>
            <atom:updated>2020-02-27T06:51:57.032Z</atom:updated>
            <content:encoded><![CDATA[<p>OpenPAI 是微軟開源的平台，提供資源以及任務 ( Job ) 管理，並可以被安裝在 On-premises 或 Hybrid 或 Public Clouds 。</p><p>在開源說明中，主要提供給 AI 應用。因為目前在訓練 SOTA ( state-of-the-art ) 的模型時，大多需要花費大量的硬體資源以及時間，如何共享硬體資源及排程這些訓練任務就是 OpenPAI 主打的應用情境啦。</p><p>0.14 版的 OpenPAI 是建置一個 Hadoop 在 Kubernetes 之上來達成上述的管理功能。但在 Github Issue 中提到，將來會提供單純 Kubernetes 的環境 ( <a href="https://github.com/microsoft/pai/issues/3872">https://github.com/microsoft/pai/issues/3872</a> )。</p><p>接下來的文章將著重在以使用者的角度，如何運用此平台來送交訓練模型任務…等的相關介紹。</p><h3>網頁介面</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nOdqvLzdQAmWqNwY918GHA.png" /></figure><p>網頁介面提供 Command 欄位來填寫任務的相關指令，填寫在此欄位的指令最終會被 &amp;&amp; 合併成一行指令。</p><pre>apt update<br>apt install -y git<br>git clone https://github.com/tensorflow/models<br>cd models/research/slim<br>python download_and_convert_data.py --dataset_name=cifar10 --dataset_dir=/tmp/data<br>python train_image_classifier.py --dataset_name=cifar10 --dataset_dir=/tmp/data --max_number_of_steps=1000</pre><p>從官方的教學可以看到，透過這樣的形式，能夠先從 Github 拉程式下來，然後再跑需要的訓練模型任務。</p><p>接著在 Command 下方能夠客製化此任務需要的資源 ( CPU/GPU/Memory ) 和環境 ( Docker Image )。</p><p>訓練完的結果，需要一個地方來儲存，右邊的 Data 即是讓使用者可以設定儲存空間，來放置輸入或輸出資料的地方。需要注意的是，如果想要在不同的任務中共享資料，使用者要自己準備好如 NFS 這種可以被共享的儲存空間，才可再透過 OpenPAI 的工具設定上去。</p><p>所以這基本上就是很簡單但是符合一般使用的設定。</p><p>比較進階的是，使用者可以多加 Tabs ，並且在不同的 Tabs 寫不同的設定，但是彼此共享些環境變數，一次送出成一個任務，如此一來就能夠做 Distributed Training 的任務設定。</p><p>送出任務之後， OpenPAI 也提供相關必須的監控功能。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*njxhWOJEnLM5TmFgqG8vdg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YrbkBX5wzfG1laITYKYmsg.png" /></figure><p>如上兩圖所示，使用者能夠監控執行過程中的所有輸出和硬體使用狀態。</p><p>另外對於不熟悉共享資源的使用者，需要注意的是， OpenPAI 跟所有的資源及任務管理平台一樣，當使用者送出任務時，任務也許並不會馬上被執行，而是等到有合適的資源後，才會被執行。由資源管理平台來統一調度資源，才能夠達到所有硬體資源的利用最大化。</p><h3>VS Code</h3><p>由微軟所出的平台，跟自家 VS Code 的整合自然是必須的。這邊就借用官方 Github 裡的動圖來說明。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WEiqe51HMsPW5r0if4-uqg.gif" /></figure><p>前置作業，需要先下載 Extension 並且在 VS Code 中設置好 OpenPAI 平台的設定。</p><p>接下來將原本網頁介面的相關設定，寫成 YAML 檔後，就能夠用右鍵送出任務上去。</p><p>它在背後會自動幫使用者上傳本地端的程式到 OpenPAI 。因此使用者就能夠達到本地端寫程式，遠端跑程式的功能，讓需要大量資源的程式到遠端去跑，維持自己機器的順暢，也免除了只用自己的機器可能不夠力的困擾。</p><p>有時候如果需要 Debug ，它也提供先用本地端的 Docker 模擬跑在 OpenPAI 的環境，來協助使用者在本地端除錯 (當然使用上還是會有些限制，不能夠完全模擬遠端的平台環境)。</p><h3>Python SDK and CLI</h3><p>OpenPAI 也提供完整的 Python SDK 和 CLI 來讓使用者能夠透過程式進一步的控制送任務的行為。</p><p>比如使用者想要定時早上送一個任務，那就可以透過 Linux 內建的 Cron Tab 去呼叫 OpenPAI 的 CLI 來達成。</p><p>另外特別的是， SDK 和 CLI 還能夠送出跑 Notebook ( *.ipynb ) 的任務。它會將跑完的結果用 HTML 的方式顯示出來給使用者。或者是如果用 --interactive ，就能夠連上去當作一個 Jupyter Server 使用。</p><h3>總結</h3><p>OpenPAI 提供了一個算是完整的資源及任務管理平台，基本的功能都有。但是目前是建置 Hadoop 在 Kubernetes 之上，雖然可能是因為 Hadoop 任務管理的功能目前較完善，但 Hadoop 和 Kubernetes 的功能其實有重疊的地方，難免有些疊床架屋的感覺，因此期待能夠早日看到單純 Kubernetes 的版本。</p><p>另外對於一些進階的任務排程功能，似乎沒有相關的文件或實作，比如 Priority 、 Fair Sharing …等等，也期待這部分能夠有更多的細節。</p><p>這篇文章僅提供一些最初步的介紹，讓有興趣的人可以參考，在實際架設維運並使用的過程中，相信會遇到更多有趣的發現，也歡迎有使用過的人來分享！</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b4c36c5a990" width="1" height="1" alt=""><hr><p><a href="https://blog.infuseai.io/lets-try-openpai-8b4c36c5a990">Let’s try OpenPAI</a> was originally published in <a href="https://blog.infuseai.io/">InfuseAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Note]]></title>
            <link>https://medium.com/@jackklpan/docker-note-e343fa9fc108?source=rss-47facfc2b4c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e343fa9fc108</guid>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Jack Pan]]></dc:creator>
            <pubDate>Sat, 14 Apr 2018 15:46:33 GMT</pubDate>
            <atom:updated>2018-04-14T15:46:33.202Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build and Run</h3><p>Dockerfile</p><pre># Use an official Python runtime as a parent image<br>FROM python:2.7-slim</pre><pre># Set the working directory to /app<br>WORKDIR /app</pre><pre># Copy the current directory contents into the container at /app<br>ADD . /app</pre><pre># Install any needed packages specified in requirements.txt<br>RUN pip install --trusted-host pypi.python.org -r requirements.txt</pre><pre># Make port 80 available to the world outside this container<br>EXPOSE 80</pre><pre># Define environment variable<br>ENV NAME World</pre><pre># Run app.py when the container launches<br>CMD [&quot;python&quot;, &quot;app.py&quot;]</pre><p>And build using -t so it has a friendly name</p><pre>docker build -t friendlyhello .</pre><p>ls to list images</p><pre>$ docker image ls</pre><pre>REPOSITORY            TAG                 IMAGE ID<br>friendlyhello         latest              326387cea398</pre><p>mapping your machine’s port 4000 to the container’s published port 80 using -p</p><pre>docker run -p 4000:80 friendlyhello</pre><p>run the app in the background, in detached mode:</p><pre>docker run -d -p 4000:80 friendlyhello</pre><p>show and stop container</p><pre>docker container ls</pre><pre>docker container stop 1fa4ab2cf395</pre><h3>Share image</h3><p>The notation for associating a local image with a repository on a registry is <strong>username/repository:tag</strong>. The tag is optional, but recommended, since it is the mechanism that registries use to give Docker images a version. Give the repository and tag meaningful names for the context, such as get-started:part2. This puts the image in the <strong>get-started repository</strong> and <strong>tag it as part2</strong>.</p><pre>docker tag friendlyhello john/get-started:part2</pre><pre>$ docker image ls</pre><pre>REPOSITORY               TAG                 IMAGE ID       ...<br>friendlyhello            latest              d9e555c53008   ...<br>john/get-started         part2               d9e555c53008   ...</pre><p>So, it will create a new image which can be pushed to the registry later.</p><pre>docker push username/repository:tag</pre><p>And you can run it by</p><pre>docker run -p 4000:80 username/repository:tag</pre><p>If the image isn’t available locally on the machine, Docker pulls it from the repository.</p><h3>Cheatsheet</h3><pre>docker run -it</pre><p>run in interactive mode</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e343fa9fc108" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improving Deep Neural Networks Week 1]]></title>
            <link>https://medium.com/ml%C2%B2-notes/improving-deep-neural-networks-week-1-3e08958bdb04?source=rss-47facfc2b4c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e08958bdb04</guid>
            <dc:creator><![CDATA[Jack Pan]]></dc:creator>
            <pubDate>Mon, 15 Jan 2018 15:34:06 GMT</pubDate>
            <atom:updated>2018-01-15T15:34:06.118Z</atom:updated>
            <content:encoded><![CDATA[<p>深度學習層數、 Hidden Unit 數量、 Activation Function 、 Learning Rate 等需要決定的 Hyperparameters 通常會透過多次的測試來決定。</p><p>將資料切分成 Train / Dev / Test 三份，用 Train Set 訓練模型、 Dev Set 檢查不同 Hyperparameters 下模型的效果，並挑出表現最好的 Hyperparameters 、最後用 Test Set 得到無偏差的模型效果評估。</p><p>在傳統機器學習上，會用 60 / 20 / 20 的方式去切資料。但隨著資料量增大， Andrew 建議不用跟隨此原則， Dev / Test Set 皆各取一萬筆資料即可，其餘的皆用來訓練模型。</p><p>在切分資料的時候要注意，最好三份資料的分佈狀態皆是接近的，尤其是 Dev / Test Set ，因為這兩份會拿來評估模型的表現。</p><p>而若不想得到無偏差的模型效果評估，就可以不用切出 Test Set 。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*JCC4p2pgjmSg5O_Fc_AOFA.png" /></figure><p>透過 Train / Dev Set 來檢查模型是否有 High Bias 或 High Variance 。</p><p>假設已知模型最佳表現為 x ，則若在 Train Set 表現接近於 x ，是 Low Bias ，反之是 High Bias 。</p><p>若在 Dev Set 之表現接近於在 Train Set 之表現，是 Low Variance ，反之是 High Variance 。</p><p>建構深度學習網路時可以依照下面的步驟進行。首先將 Bias 降到足夠低，可以透過加大網路、增加訓練時間、改變神經網路的架構來達成。</p><p>當 Bias 夠低時，檢查 Variance 是否會高，若高的話，透過增加 Training Samples 、加上 Regularization 、改變神經網路的架構來降低。</p><p>調整過後再回頭檢視 Bias ，重複過程，直到 Bias 和 Variance 達到要求。</p><p>L2 Regularization ：所有的 w 平方後相加。<br>L1 Regularization ：所有的 w 絕對值相加。會使得 w 比較稀疏（較多 0 ）。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bzp5_Hl0sC2VU36CLyq10w.png" /></figure><p>上圖為加上 L2 Regularization 後做 Gradient Descent 的推導。</p><p>可以發現加上 L2 Regularization 後，每次更新 w 時，會多出一項 (- alpha*lambda/m)*w ，會使 w 每次都往 0 更靠近，因此又被稱作 Weight Decay 。</p><p>L2 Regularization 可以降低 Variance ，是因為它會使得 W 變小，使神經網路中，節點影響力下降，相對降低神經網路的複雜度。</p><p>另一種說法是，當使用 Tanh 當作 Activation Function 時，由於降低 W 會使進入 Tanh 的值變小較接近於零，其是在 Tanh 中接近於線性反應的區間，因此會讓神經網路的每個節點都變成幾近線性，降低複雜度。</p><ul><li>From HW: L2-regularization relies on the assumption that a model with small weights is simpler than a model with large weights. Thus, by penalizing the square values of the weights in the cost function you drive all the weights to smaller values. It becomes too costly for the cost to have large weights! This leads to a smoother model in which the output changes more slowly as the input changes.</li></ul><p>神經網路中另一種 Regularization 的方式為 Dropout 。設定每個節點在訓練時保留的機率，每次會刪掉不同的節點進行訓練。</p><p>而訓練完後，使用神經網路時，不需要刪掉任何節點。</p><p>現在最常用的 Dropout 方式為 Inverted Dropout ，它會依照刪除節點的機率，重新 Normalize 每層的 Activation Value 。如此可以確保，每次下一層拿到的輸入期望值都會是一樣的，不會降低。下圖中的 a3 /= keep-prob 即是在做這件事。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*qTmdswybPrqt01ab6naRuQ.png" /></figure><p>Dropout 因為每次都會隨機刪除掉一些節點，所以每個節點不會僅依靠前一層的少數節點，否則當這些節點被刪除時，就無法有正確輸出。因此會平均分佈權重在前一層的所有節點上，與 L2 Regularization 的效果類似。</p><ul><li>From HW: When you shut some neurons down, you actually modify your model. The idea behind drop-out is that at each iteration, you train a different model that uses only a subset of your neurons. With dropout, your neurons thus become less sensitive to the activation of one other specific neuron, because that other neuron might be shut down at any time.</li></ul><p>Dropout 只需用在訓練時。</p><p>Dropout 可以設定不同的機率在不同層上，通常會在參數比較多的層設定較大的機率。不過這樣的方式也會讓 Hyperparameters 增加，需要微調每個層設定的 Dropout 機率。折中的做法是，選取一些層做 Dropout ，另一些不做，而這些做 Dropout 的層皆使用相同的機率。</p><p>Dropout 一開始是使用於電腦視覺領域，因為相較於影像像素數量，訓練的資料都不太足夠，多會有 Overfitting 的問題。但不一定同樣適用於其他的領域。</p><p>Dropout 的缺點是，使用後 Cost Function 將不再能完整定義，因為每次會有隨機的節點被丟掉。所以在每次的訓練迴圈裡， Cost Function 不一定皆會遞減。若要檢查訓練過程是否有問題，最好將 Dropout 關掉比較容易檢查。</p><p>其他 Regularization 的方法：</p><p>Data Augmentation ，如將圖片的資料做旋轉、縮放等處理後，當作一個新的訓練資料。使模型適應更多樣化的資料。</p><p>Early Stop ，訓練模型時，若 Dev Set 的 Cost Function 開始上升，即停止。但 Andrew 並不推薦這樣的做法，因為 Early Stop 同時也使 Cost 沒有降到最低。他認為降低 Cost 、避免 Overfitting 兩件事，應該分開來處理，降低耦合性。</p><p>在訓練神經網路時，先將所有的輸入特徵皆 Normalize 成平均為零、變異數為一。這樣可以加快訓練速度。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*wzmnAiLp2vi48qgvOt5Mcw.png" /></figure><p>訓練深度神經網路的一個問題是， Gradient Vanishing / Exploding。當層數很多時，只要數值不接近於 1 ，經過多層的傳播，數值即會變很大或很小。</p><p>其中一個解決方式是，在一開始的時候對於 W 做好的初始化，讓 Activation Function 出來的數字能盡量接近 1 。當 Input 越多時， W 的初始化就要越小，如此才能使最後輸出的值較小。而不同的 Activation Function 也有不同的初始化方式。若用 Relu ，通常用 ：<br>np.random.randn(shape)*np.sqrt(2/n^(l-1)) 。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*sM-B1A6mKVcJ5J0JVBO54Q.png" /></figure><p>在檢查 Gradient 算的正不正確時，用 Double Side 的估計方式會比較準。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*bO1XjHeWH5STlPtFok-QmA.png" /></figure><p>同時 Andrew 也給我們準則，看怎麼樣的狀況是計算 Gradient 有問題。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*U5Rd6eLUDA6QGx2ZHOwXwQ.png" /><figcaption>d_theta_appro 代表用 Double Side 計算出來的 Gradient 。</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e08958bdb04" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ml%C2%B2-notes/improving-deep-neural-networks-week-1-3e08958bdb04">Improving Deep Neural Networks Week 1</a> was originally published in <a href="https://medium.com/ml%C2%B2-notes">ML² Notes</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neural Networks and Deep Learning Week 4]]></title>
            <link>https://medium.com/ml%C2%B2-notes/neural-networks-and-deep-learning-week-4-73fff2c7ac5d?source=rss-47facfc2b4c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/73fff2c7ac5d</guid>
            <dc:creator><![CDATA[Jack Pan]]></dc:creator>
            <pubDate>Mon, 08 Jan 2018 16:08:38 GMT</pubDate>
            <atom:updated>2018-01-08T16:08:38.791Z</atom:updated>
            <content:encoded><![CDATA[<h4>Deep Neural Network</h4><p>將上一週的兩層 Neural Network 繼續加入更多層，如：四層五層，即是深度神經網路。</p><p>在建置深度神經網路時，確認各個變數或參數的維度正確，可以降低 Bug 的發生率。</p><p>n^[l] 代表 l 層共有幾個節點。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*h49UtWLoyEvMCoe_Jg3piA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*PqUPUPCkxVjo9d82FKhPuw.png" /></figure><p>當層數加大時， Neural Network 越可以將低層的特徵，以有效率的方式結合，讓整個模型能夠學習複雜的問題。</p><p>以人臉辨識為例，低層次的部分，會學習到如線條邊緣等特徵，將這些特徵組合會形成單一眼睛、鼻子等輪廓，再將這些特徵組合，即可以合成一張臉。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*xL_RlcmHRzB34Di6Plscgw.png" /></figure><p>另一個例子是，若要學習 x1 XOR x2 XOR x3 … XOR xn 的函數。很明顯下圖左邊是更有效率的表示方式。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*XymfP487KzWL25EfAIaQXQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*K9BAP75vkQkqgzKIeV81iQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*My-qE6nEOzet_rO-CfCzyg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*LjdCKMQAUL7nQWauLXgb2Q.png" /></figure><p>Parameters： W 與 b 。</p><p>Hyperparameters： Neural Network 的層數、每層的節點數量、 Activation Function 、 Learning Rate ……等，需要人工設定的部分。</p><h4>Note on HW</h4><p>使用五層的神經網路，將先前辨識貓的模型準確度從 70% 提升到 80% 。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*ukvObzt_9OYgazHoLMlo-w.png" /></figure><p>但對於如上圖這些例子，仍是辨識錯誤的樣本。</p><p>作業中歸納幾個原因：<br>* 貓的身體位置比較不一樣<br>* 貓和背景顏色很像<br>* 不常見的貓顏色與品種<br>* 角度、亮度、貓在圖中很大或很小</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73fff2c7ac5d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ml%C2%B2-notes/neural-networks-and-deep-learning-week-4-73fff2c7ac5d">Neural Networks and Deep Learning Week 4</a> was originally published in <a href="https://medium.com/ml%C2%B2-notes">ML² Notes</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>