<?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 Yen&#39;s Coding Journal on Medium]]></title>
        <description><![CDATA[Stories by Yen&#39;s Coding Journal on Medium]]></description>
        <link>https://medium.com/@Freeanser?source=rss-1e2900a787bb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QWKYybi6qxZ2CPeZN-s3Hg.jpeg</url>
            <title>Stories by Yen&amp;#39;s Coding Journal on Medium</title>
            <link>https://medium.com/@Freeanser?source=rss-1e2900a787bb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 02:25:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Freeanser/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[The data structure of Python deque]]></title>
            <link>https://medium.com/@Freeanser/the-data-structure-of-python-deque-31fa30402eb0?source=rss-1e2900a787bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/31fa30402eb0</guid>
            <category><![CDATA[deque]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Yen's Coding Journal]]></dc:creator>
            <pubDate>Tue, 26 Aug 2025 09:23:53 GMT</pubDate>
            <atom:updated>2025-08-26T09:23:53.370Z</atom:updated>
            <content:encoded><![CDATA[<h3>✅ Key points of Python deque</h3><h3>1. Structure</h3><ul><li>Made of many <strong>fixed-size blocks (small arrays) (</strong>block = 64 slots)</li><li>Blocks are connected with a <strong>doubly linked list</strong></li><li>Each block is a <strong>C array</strong> (continuous memory), so access inside the block is fast</li></ul><h3>2. Time complexity</h3><ul><li>append / appendleft / pop / popleft → <strong>O(1)</strong> (only moves head/tail block)</li><li>deque[i] → <strong>fast near the edges, slower in the middle</strong> (must walk through blocks)</li><li>Unlike list[i], which is true O(1) random access</li></ul><h3>🔹 Simple example (assume block size = 4)</h3><pre>from collections import deque<br>dq = deque()</pre><p>Insert some elements:</p><pre>dq.extend([&#39;A&#39;,&#39;B&#39;,&#39;C&#39;,&#39;D&#39;,&#39;E&#39;,&#39;F&#39;])</pre><p>Internal idea:</p><pre>Block1: [A, B, C, D]<br>Block2: [E, F, _, _]</pre><h3>Operation 1: dq.popleft()</h3><pre>Remove A<br>Block1: [_, B, C, D]<br>#           ^ head  <br>Block2: [E, F, _, _]<br>#              ^ tail</pre><p>👉 Just move the head pointer, no shifting needed → O(1)</p><h3>Operation 2: dq[5]</h3><pre>Index 5 # → the 5th element<br>5 // 4 = 1 # → in Block2<br>5 % 4 = 1 # → Block2[1] = F</pre><p>👉 Found F, but CPython must walk to Block2 → fast near edges, slower in the middle.</p><h3>✨ One-sentence summary</h3><ul><li>deque = <strong>blocks (small arrays) + doubly linked list</strong></li><li>Best for <strong>operations at both ends</strong> (O(1))</li><li>Not good for <strong>random indexing</strong> (middle elements are slower)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31fa30402eb0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I Chose PostgreSQL: Simple Pros and Cons]]></title>
            <link>https://medium.com/@Freeanser/why-i-chose-postgresql-simple-pros-and-cons-78460d015472?source=rss-1e2900a787bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/78460d015472</guid>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Yen's Coding Journal]]></dc:creator>
            <pubDate>Thu, 11 Jul 2024 09:36:52 GMT</pubDate>
            <atom:updated>2024-07-11T09:36:52.170Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Pros:</strong></h3><h4><strong>Open-Source and Free</strong>:</h4><ul><li>PostgreSQL is free to use, which means you don’t have to pay for a license. It’s also open-source, meaning you can see and modify the source code if needed.</li></ul><h4><strong>Powerful Features</strong>:</h4><ul><li>PostgreSQL supports advanced features like transactions, foreign keys, and subqueries, which help in managing complex databases efficiently.</li></ul><h4><strong>Reliability and Stability</strong>:</h4><ul><li>PostgreSQL is known for its stability and reliability. It handles large amounts of data well and is trusted by many big companies.</li></ul><h4><strong>Support for Various Data Types</strong>:</h4><ul><li>It supports a wide range of data types, including JSON, XML, and custom data types, making it versatile for different kinds of applications.</li></ul><h4><strong>Extensibility</strong>:</h4><ul><li>You can add new features to PostgreSQL by writing your own extensions or using existing ones. This makes it flexible and adaptable to specific needs.</li></ul><h4><strong>Strong Community Support</strong>:</h4><ul><li>There is a large community of users and developers who contribute to PostgreSQL. This means you can find a lot of resources, tutorials, and help online.</li></ul><h3><strong>Cons:</strong></h3><h4><strong>Complexity</strong>:</h4><ul><li>PostgreSQL can be more complex to set up and use compared to simpler databases like SQLite. It might take some time to learn all its features and capabilities.</li></ul><h4><strong>Performance Tuning</strong>:</h4><ul><li>To get the best performance out of PostgreSQL, you might need to spend some time tuning and optimizing it, which can be challenging for beginners.</li></ul><h4><strong>Resource Intensive</strong>:</h4><ul><li>PostgreSQL can require more system resources (like memory and CPU) compared to lighter databases, which might be a concern for very small projects or limited hardware.</li></ul><h3>Example</h3><p>Imagine PostgreSQL as a professional kitchen:</p><ul><li><strong>Pros</strong>: It has all the advanced tools (features) you need to cook any meal (manage any data). It’s reliable, you can add your own tools (extensions), and there are many chefs (community) ready to help.</li><li><strong>Cons</strong>: It might be harder to learn how to use all the tools, and you need to spend time to make sure everything works perfectly (performance tuning). It also needs more space and power (resources) than a smaller kitchen (lighter database).</li></ul><p>By using PostgreSQL, we get a powerful and flexible database system that can handle our needs well, even if it takes a bit more effort to learn and optimize.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78460d015472" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding PostgreSQL, pgAdmin4, psql, and Alembic]]></title>
            <link>https://medium.com/@Freeanser/understanding-postgresql-pgadmin4-psql-and-alembic-58d831d8e826?source=rss-1e2900a787bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/58d831d8e826</guid>
            <category><![CDATA[pgadmin-4]]></category>
            <category><![CDATA[alembic]]></category>
            <category><![CDATA[psql]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Yen's Coding Journal]]></dc:creator>
            <pubDate>Thu, 11 Jul 2024 09:34:29 GMT</pubDate>
            <atom:updated>2025-09-27T20:41:21.511Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>1. PostgreSQL:</strong> <br>PostgreSQL is a powerful, open-source relational database management system (RDBMS). It helps you store, retrieve, and manage data. Think of it as a big electronic filing cabinet where you can keep all your data organized.</p><p><strong>2. pgAdmin4:</strong> <br>pgAdmin4 is a graphical user interface (GUI) tool for managing PostgreSQL databases. It allows you to interact with your databases visually rather than through text commands. You can create, modify, and manage databases and tables using a user-friendly interface. Imagine it as a control panel for your filing cabinet.</p><p><strong>3. psql:</strong> <br>psql is a command-line tool for interacting with PostgreSQL databases. It allows you to run SQL commands directly in your terminal or command prompt. If pgAdmin4 is like a control panel, psql is like typing commands directly into a computer to organize your files.</p><p><strong>4. SQLAlchemy</strong>:<br> SQLAlchemy is a Python SQL toolkit and Object-Relational Mapping (ORM) library. It allows you to interact with your PostgreSQL database using Python objects instead of writing raw SQL queries. Imagine it as a translator that helps you talk to your filing cabinet (PostgreSQL) in a more Pythonic way, making your code cleaner and easier to maintain.</p><p><strong>5. Alembic:</strong> <br>Alembic is a lightweight database migration tool for SQLAlchemy, which is a Python SQL toolkit and Object-Relational Mapping (ORM) library. Alembic helps you manage changes to your database schema over time. It’s like a tool that helps you keep track of changes and updates in your filing system, ensuring everything stays in order.</p><h3>How They Work Together</h3><ul><li><strong>PostgreSQL</strong> is the database system where all your data is stored.</li><li><strong>pgAdmin4</strong> is the graphical tool that lets you manage your PostgreSQL databases using a visual interface.</li><li><strong>psql</strong> is the command-line tool that lets you manage PostgreSQL databases using text commands.</li><li><strong>SQLAlchemy</strong> lets you interact with PostgreSQL in your Python projects through ORM, simplifying database queries and schema definitions.</li><li><strong>Alembic</strong> helps you manage and apply changes to your PostgreSQL database schema when you update or modify your database structure using SQLAlchemy in your Python projects.</li></ul><h3>Example Workflow</h3><h4><strong>1. Create a Database</strong>:</h4><ul><li>Use <strong>PostgreSQL</strong> to create a new database.</li><li>You can do this visually using <strong>pgAdmin4</strong> or by typing commands using <strong>psql</strong>.</li></ul><h4>2. <strong>Interact with the Database</strong>:</h4><ul><li>In your Python project, use <strong>SQLAlchemy</strong> to define models (tables) and run queries without writing raw SQL.</li></ul><h4><strong>3. Manage Database Changes</strong>:</h4><ul><li>As your project evolves, you may need to change the structure of your database (e.g., add new tables or columns).</li><li>Use <strong>Alembic</strong> to create and apply these changes systematically, ensuring your database schema stays updated and consistent.</li></ul><p>[ Flask (Web App / API) ]<br> │<br> ▼<br>[ SQLAlchemy (ORM: Models ↔ Tables) ]<br> │<br> ▼<br>[ Alembic (Schema Migration: manage DB changes) ]<br> │<br> ▼<br>[ PostgreSQL (Database: stores all data) ]<br> │<br> ▼<br>- [ pgAdmin4 (GUI) ] Visual control <br>- [ psql (CLI) ] Text-based control</p><p>By using these tools together, you can efficiently manage your data and database structures, making your development process smoother and more organized.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58d831d8e826" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Do We Need to Create a Virtual Environment in Python Development?]]></title>
            <link>https://medium.com/@Freeanser/what-how-when-why-a-virtual-environment-in-python-d7c1fd6da977?source=rss-1e2900a787bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7c1fd6da977</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[virtual-environment]]></category>
            <category><![CDATA[venv]]></category>
            <dc:creator><![CDATA[Yen's Coding Journal]]></dc:creator>
            <pubDate>Thu, 11 Jul 2024 09:22:45 GMT</pubDate>
            <atom:updated>2024-07-11T09:29:46.340Z</atom:updated>
            <content:encoded><![CDATA[<p>Here are some useful videos to learn What, How, When, Why a Virtual Environment in Python:</p><p><a href="https://realpython.com/lessons/what-virtual-environments-are-good-for/">What Virtual Environments Are Good For</a><br><a href="https://www.youtube.com/watch?v=MfVOUSGbe60&amp;ab_channel=SamWestbyTech">What is a Virtual Environment in Python?</a> (Window version)</p><h3>Why Do We Need to Create a Virtual Environment in Python Development?</h3><p><strong>1. Isolate Dependencies:</strong> <br>Each Python project might need different versions of libraries or modules. Virtual environments help you create an isolated space for each project, preventing conflicts between projects that need different versions of the same libraries.</p><p><strong>Example</strong>: <br>Imagine you have different cooking recipes, and each recipe needs different spices. If you put all the spices in one big pot, your recipes will get mixed up. Similarly, different Python projects need different libraries, and mixing them can cause problems.</p><p><strong>2. Easy Management:</strong> <br>With virtual environments, you can easily manage and update the dependencies needed for your project without affecting other Python projects on your system.</p><p><strong>Example</strong>: <br>This is like having a separate bookshelf for each project. You can add or remove books (dependencies) as needed without affecting other bookshelves.</p><p><strong>3. Easy to Move:</strong> <br>When you need to run the same project on another machine or server, a virtual environment lets you easily copy the project environment without reconfiguring everything.</p><p><strong>Example</strong>: <br>It’s like packing up your kitchen (project environment) and taking it to another place without needing to buy all the spices (dependencies) again.</p><h3>Why We Must Activate the Virtual Environment in the Backend Folder</h3><p><strong>Reasons</strong>:</p><ol><li><strong>Consistency</strong>: <br>Activating the virtual environment in the backend folder ensures that every developer works in the same environment, avoiding version conflicts and compatibility issues.</li><li><strong>Prevent Dependency Problems</strong>: <br>Without a virtual environment, dependencies from different projects might interfere with each other, causing the project to not run properly.</li><li><strong>Security</strong>: <br>Virtual environments prevent unnecessary changes to the system-wide settings, reducing the risk of system crashes.</li></ol><p><strong>Simple Steps</strong>:</p><p>Enter the backend folder:</p><pre>cd backend</pre><p>Activate the virtual environment:</p><pre># For Unix or macOS<br>python3 -m venv project_name_env<br>source project_name_env/bin/activate<br><br># For Windows<br>python -m venv project_name_env<br>project_name_env\Scripts\activate  </pre><p>Install Dependencies:</p><pre>pip install -r requirements.txt</pre><p>Doing this ensures you and your partner are developing in the same environment, reducing issues when merging code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7c1fd6da977" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Install pgAdmin on Mac]]></title>
            <link>https://medium.com/@Freeanser/how-to-install-pgadmin-on-mac-6341e2b801c4?source=rss-1e2900a787bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/6341e2b801c4</guid>
            <category><![CDATA[pgadmin]]></category>
            <dc:creator><![CDATA[Yen's Coding Journal]]></dc:creator>
            <pubDate>Thu, 11 Jul 2024 08:38:45 GMT</pubDate>
            <atom:updated>2025-10-30T02:43:57.571Z</atom:updated>
            <content:encoded><![CDATA[<p>Check <a href="https://medium.com/@Freeanser/install-postgresql-and-pgadmin-on-mac-d13cf835d042">HERE</a> to learn <a href="https://medium.com/@Freeanser/install-postgresql-and-pgadmin-on-mac-d13cf835d042">How to Install PostgreSQL</a></p><p>Download pgAdmin <a href="https://www.pgadmin.org/download/">HERE</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*W7kGUGkRKSllwTtY.png" /></figure><p>To install pgAdmin, simply go to the pgAdmin website, choose your operating system, and select the latest version for installation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*B-cxYYgUtIK-SAbz.png" /></figure><p>Next, connect pgAdmin to your database. Open pgAdmin and you’ll see a ‘Postgre’ option, but that’s not the database you want to connect to. Let’s set up the connection to your database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*8bVrU0IX9UflO553.png" /></figure><p>Navigate to: Menu &gt; Object &gt; Server Set up the Server details. Usually, I set the Server to ‘local’ because it represents the local data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XmIUb-QImFFpF9i6ooRPGg.png" /></figure><p>Next, configure the Connection and save it.</p><ul><li><strong>Host name/address</strong>：localhost（or 127.0.0.1）</li><li><strong>Maintenance database</strong>: The database name we create.</li><li><strong>Username</strong>: The username name we create.</li></ul><p>What are the database and username?</p><p>Remember last time we<a href="https://medium.com/p/d13cf835d042/edit"> 7. Create a New User and Database</a>?</p><p>In the psql command line, We type the followings:<br> CREATE USER username WITH PASSWORD ‘password’;<br> CREATE DATABASE database;<br> GRANT ALL PRIVILEGES ON DATABASE database TO username;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*NUBLBMdOSIE1WcnWmmxQzw.png" /></figure><p>Afterward, you’ll see the new Server. Click on it, and you might be asked to enter a password. Input the correct password to access the Database of that Server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*Nw2IioZLM8ga2UYMfISwrQ.png" /></figure><p>You can visualize tables from here, but remember to refresh first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Kc_C-fpA7ZpwGxsL9TwNg.png" /></figure><p>After writing your code, you can use this to verify if you successfully connected to and operated the database. You can also manually add or delete data. Remember to save the change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BgjI_ZAA-uOsfFfd-qEHIg.png" /></figure><p>References:<br><a href="https://medium.com/@King610160/%E6%9C%AC%E5%9C%B0%E4%BD%BF%E7%94%A8postgre-sql-%E6%90%AD%E9%85%8D%E5%9C%96%E5%BD%A2%E5%8C%96%E4%BB%8B%E9%9D%A2pgadmin-729da4fd857b">HERE</a><br>GPT</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6341e2b801c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Install PostgreSQL on Mac]]></title>
            <link>https://medium.com/@Freeanser/install-postgresql-and-pgadmin-on-mac-d13cf835d042?source=rss-1e2900a787bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/d13cf835d042</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[pgadmin]]></category>
            <dc:creator><![CDATA[Yen's Coding Journal]]></dc:creator>
            <pubDate>Wed, 03 Jul 2024 07:19:18 GMT</pubDate>
            <atom:updated>2025-10-30T02:36:06.390Z</atom:updated>
            <content:encoded><![CDATA[<h3>Install PostgreSQL</h3><p>This is the common process to install and manage PostgreSQL on Mac using Homebrew. Below are detailed instructions for each step and some important notes:</p><h4>1. Install Homebrew (if not already installed)</h4><p>First, make sure Homebrew is installed on your system. It’s a package manager for Mac used to install and manage software packages. If not installed, visit the Homebrew website and follow the instructions to install it.</p><h4>2. Install Post<strong>greSQL</strong></h4><p>Install PostgreSQL using Homebrew:<br> brew install postgresql</p><p>This command installs the latest version of PostgreSQL unless you specify a specific version like postgresql@14.</p><h4>3. Start PostgreSQL Service</h4><p>If you want PostgreSQL to start automatically on startup:<br> brew services start postgresql</p><p>This adds PostgreSQL to system services, ensuring it starts automatically each time your computer starts.</p><h4>4. Manually Start PostgreSQL (non-automatic start scenario)</h4><p>If you prefer not to start PostgreSQL automatically, you can manually start it with this command:<br>/opt/homebrew/opt/postgresql@14/bin/postgres -D /opt/homebrew/var/postgresql@14</p><p>This command directly starts the PostgreSQL server without adding it to system services.</p><h4>5. Confirm Installation and Service Status</h4><p>You can check the status of all services managed by Homebrew with:<br> brew services list</p><p>This shows the status of the PostgreSQL service to confirm if it’s running.</p><h4>6. Connect to the Database Using psql</h4><blockquote><strong>Open a new terminal window</strong> and connect to PostgreSQL:<br><strong>Must</strong> <strong>Open a new terminal window</strong></blockquote><p>command+N to open a new terminal window</p><p>This logs you into PostgreSQL using the default postgresuser.</p><p>psql -d postgres</p><h4>7. Create New User and Database</h4><p>In the psql command linepostgres=#, you can create a new user and database and grant privileges:</p><p>postgres=#<br> CREATE USER username WITH PASSWORD ‘password’;<br> CREATE DATABASE database;<br> GRANT ALL PRIVILEGES ON DATABASE database TO username;<br> \q</p><p>Make sure to replace `username`, `password`, and `database` with your specific settings.</p><blockquote>Please note, remember the `username`, `password`, and `database`, we will use them several time later.<br>They are important!!!</blockquote><p>If you wanna create another database under the same user’s name:</p><p>postgres=#<br>CREATE DATABASE ride_sharing OWNER yen;<br>\q</p><p>Notes:</p><ul><li>In most cases, if your username and database name don’t contain special characters or reserved words, you don’t need to use quotes. Quotes are used to ensure PostgreSQL correctly interprets names with special characters (like uppercase letters, spaces, or reserved words).</li><li>`\q` is the command to quit psql, make sure to execute it after completing all SQL commands.</li></ul><p>These steps will guide you through installing, configuring, and basic usage of PostgreSQL.</p><p>Check <a href="https://medium.com/p/6341e2b801c4/edit">HERE</a> to learn <a href="https://medium.com/p/6341e2b801c4/edit">How to Install pgAdmin on Mac</a>.</p><p><strong>References:</strong><br><a href="https://medium.com/@King610160/%E6%9C%AC%E5%9C%B0%E4%BD%BF%E7%94%A8postgre-sql-%E6%90%AD%E9%85%8D%E5%9C%96%E5%BD%A2%E5%8C%96%E4%BB%8B%E9%9D%A2pgadmin-729da4fd857b">HERE</a><br>GPT</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d13cf835d042" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[US國際生non-resident 且沒有SSN 收到1099-INT]]></title>
            <link>https://medium.com/@Freeanser/%E5%9C%8B%E9%9A%9B%E7%94%9Fnon-resident-%E4%B8%94%E6%B2%92%E6%9C%89ssn-%E6%94%B6%E5%88%B01099-int-081b1088c95f?source=rss-1e2900a787bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/081b1088c95f</guid>
            <dc:creator><![CDATA[Yen's Coding Journal]]></dc:creator>
            <pubDate>Sat, 17 Feb 2024 00:12:45 GMT</pubDate>
            <atom:updated>2024-04-03T04:48:14.511Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>請記得「稅金規則每年都有可能更改」，所以如果有不確定的部分，可以請教 <a href="https://www.facebook.com/sprintaxcom">Sprintax FB 客服</a> 或者 聯繫 <a href="https://www.irs.gov/help/contact-your-local-irs-office">Local IRS Office</a></blockquote><pre>整篇文章的內容中，只要是有底線的文字，都有超連結可以點喔！</pre><p>非常感謝在過程中，遇到一起處理和討論的報稅小夥伴們（一起踩到系統bug小夥伴們XD)！</p><p>（！持續更新中，因為我正在等回報 ITIN 是否申請順利。）</p><h3>快速交待流程：</h3><ol><li>去 <a href="https://www.sprintax.com/?_gl=1%2Aal8uu%2A_ga%2AMTQwNDU5ODUwNi4xNzA3ODkyMjQ0%2A_ga_ZF8BY1VCRV%2AMTcwODA0OTY2MS4xMC4xLjE3MDgwNTA2NDAuMC4wLjA.">Sprintax</a> 填資料，自動生成 <a href="https://blog.sprintax.com/form-1040nr-explained/">1040-NR</a> 和 <a href="https://blog.sprintax.com/tax-form-8843-filing-instructions/">8843 form</a></li><li>自己填好 <a href="https://www.irs.gov/pub/irs-pdf/fw7.pdf">W-7</a> （<a href="https://www.youtube.com/watch?v=ddHHRWZz3no&amp;ab_channel=%E7%BE%8E%E5%9B%BD%E7%94%9F%E6%B4%BB%E6%94%BB%E7%95%A5">教學影片</a>）</li><li>打電話預約： 844–545–5640 (先用 4. 確認地點)</li><li><a href="https://apps.irs.gov/app/office-locator/">來這裡親自辦理</a>（記得輸入ZIP Code確認地點），帶上述三個稅表, 護照, I20, 以及所有美國發給自己的文件（例如駕照、1099-INT）</li><li>護照當場拿回來</li><li>等待 9–11 週，會收到信通知 ITIN 是否過關。接著再 6–8 週，會通知報稅是否過關。如果中間有任何未過關的部分，會在通知信上說明如何補件。</li></ol><h4>以下是概述型的資訊：</h4><ul><li><a href="https://dishtsai.com/study-us-tax-prep/">留學生繳稅概述</a></li><li><a href="https://blog.sprintax.com/f1-visa-tax-return-guide-international-students/">Tax return guide for international students</a></li><li><a href="https://www.nystartax.com/student-tax/">在美留学生报税</a></li></ul><h3>什麼是 1099-INT</h3><p><a href="https://www.kaizencpa.com/download/usa/Why%20I%20Receive%20the%20US%20Form%201099-INT(CHS).pdf">為何會收到1099-INT，以及每一格代表的意思</a></p><h4>如何避免收到 1099-INT</h4><ul><li>銀行開戶前 或者 在股市投資前，要請行員給你填 <a href="https://www.irs.gov/forms-pubs/about-form-w-8-ben">W-8 BEN</a></li><li>如果還是收到，應該就是遇到 <strong>銀行系統跟 IRS系統的 bug</strong>了。遇到了，就要開始報稅和申請退稅了～<br>(沒辦法，美國就一直裁掉軟體工程師啊～系統不好沒人修～)</li></ul><h4>是否真的要申報 1099-INT？</h4><p>如果你收到的 1099-INT ，請確認是否有withheld，例如：<br>Box 4 federal income tax withheld: $ 金額</p><p>並在「Step 3」填表格內容</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*ava3lChlxt98KGgvBc-LXw.png" /></figure><p>被稅和退稅前，要申請的資料：</p><ul><li>ITIN</li><li><a href="https://blog.sprintax.com/form-1040nr-explained/">1040-NR</a> (用Sprintax報稅就會生成 1040-NR )</li><li><a href="https://blog.sprintax.com/tax-form-8843-filing-instructions/">8843 form</a> (用Sprintax報稅就會生成 1040-NR )</li><li>可以自己申請所有表格，而不用使用 Sprintax: <a href="https://www.internationalstudent.com/tax/faqs/">此網址</a></li></ul><h3>沒有SSN，可申請ITIN:</h3><p><a href="https://blog.sprintax.com/how-get-itin-number-for-nonresident-alien-before-tax-season/">How can nonresident aliens get an ITIN before tax season?</a></p><p><a href="https://www.youtube.com/watch?v=ddHHRWZz3no&amp;ab_channel=%E7%BE%8E%E5%9B%BD%E7%94%9F%E6%B4%BB%E6%94%BB%E7%95%A5">教學影片</a></p><ol><li>報稅季(約2月到4月是報稅季節)<br>開始前 7 週就可以申請了（因為要 7 週才會處理完畢）</li><li>ITIN 跟 退稅單 (1040 NR) 一起申請：</li></ol><ul><li>填 <a href="https://www.irs.gov/pub/irs-pdf/fw7.pdf">W-7</a> （<a href="https://www.youtube.com/watch?v=ddHHRWZz3no&amp;ab_channel=%E7%BE%8E%E5%9B%BD%E7%94%9F%E6%B4%BB%E6%94%BB%E7%95%A5">教學影片</a>）</li><li>把護照拿去 <strong>大使館</strong> 或者<strong> IRS 辦公室 </strong>認證</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A_42aeW6gLzxRO26gwoyFA.png" /><figcaption>圖片來自<a href="https://blog.sprintax.com/how-get-itin-number-for-nonresident-alien-before-tax-season/">此網站</a></figcaption></figure><ul><li>把 W-7 &amp; 認證後的護照影本 &amp; 退稅單，一起寄到以下：<br><strong>Below is the address to mail your ITIN application to:<br></strong>Internal Revenue Service<br>Austin Service Center<br>ITIN Operation<br>P.O. Box 149342<br>Austin, TX 78714–9342</li><li>當然也可以請 Sprintax 幫你申請 ITIN，但是 Sprintax 還是會請你自己去認證護照。</li></ul><h3>開始退稅流程：打開Sprintax</h3><p>相關資訊連結：<br><a href="https://www.sprintax.com/?_gl=1%2Aal8uu%2A_ga%2AMTQwNDU5ODUwNi4xNzA3ODkyMjQ0%2A_ga_ZF8BY1VCRV%2AMTcwODA0OTY2MS4xMC4xLjE3MDgwNTA2NDAuMC4wLjA.">Sprintax連結</a><br><a href="https://www.facebook.com/sprintaxcom">Sprintax FB 客服</a><br><a href="https://www.youtube.com/watch?v=TbK8YeCE2js&amp;list=PL3mMKjXTjm7XXyUsaeWXd4dI1OYbYy8t6&amp;index=1&amp;ab_channel=Sprintax">Sprintax 的教學影片</a></p><h4>需要的資料：</h4><ul><li><a href="https://i94.cbp.dhs.gov/I94/#/home">I-94</a>: 為了確認你最早何時來美國（例如第一次來美國是五歲）</li><li>護照</li><li>I-20</li><li>1099-INT</li></ul><h3>“About You” 頁面</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g3fp5lJaDfX_ENPMAP3JYw.png" /></figure><h4>“Other Income” 頁面</h4><p>是否需要report tuition scholarship？</p><p>以下是 Sprintax 的回覆：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*h2WRJ4WF2O_L-JeDbowvRw.png" /></figure><p>補充說明 <a href="https://studentfinance.northeastern.edu/billing-payments/1098-t/">1098-T form</a>，超連結網址裡有提到：</p><p>The IRS does not require us to generate a 1098-T for the following:</p><ul><li>International and non-citizen students</li><li>細節請點進去 <a href="https://studentfinance.northeastern.edu/billing-payments/1098-t/">此網址</a>以及這個<a href="https://taxpanda.com/%E5%A5%96%E5%AD%A6%E9%87%91%E5%85%8D%E7%A8%8E/#%E5%A5%96%E5%AD%A6%E9%87%91%E5%85%8D%E7%A8%8E%E6%83%85%E5%86%B5%E4%B8%8B%EF%BC%8C%E5%AD%A6%E6%A0%A1%EF%BC%8C%E7%A8%8E%E5%8A%A1%E5%B1%80%EF%BC%8C%E5%92%8C%E4%BD%A0%E4%B9%8B%E9%97%B4%E7%9A%84%E5%85%B3%E7%B3%BB">網址</a></li></ul><h4>州稅</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BSjaYwpbjdqE0yLL7Ivd6Q.png" /></figure><h4>退稅銀行資訊</h4><p>routing number 怎麼填？</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vr0r4vNdPHh4jukjblhuyw.png" /></figure><h3>IRS 提供的資源</h3><p>志工服務</p><p><a href="https://irs.treasury.gov/freetaxprep/jsp/vita.jsp?zip=98109&amp;lat=47.6288591&amp;lng=-122.3456919&amp;radius=5">西雅圖志工服務</a></p><p><a href="https://www.irs.gov/help/contact-your-local-irs-office">Local IRS Office</a></p><p><a href="https://apps.irs.gov/app/office-locator/">可以來這裡親自辦理</a></p><h3>NEU 學生怎麼去 IRS</h3><ul><li>NEU — IRS：建議搭 577, 578，可以刷 Orca 卡。一下車就到 IRS 了。</li><li>IRS — 回家：我想搭 Link light rail -&gt; 沿著 2 nd Ave 到 Cherry 左轉後直走，到 3 rd Ave 後不要右轉！！！直接頭也不回地過馬路並進入 Pioneer Square Station。</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=081b1088c95f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[雲端運算（Cloud Computing）]]></title>
            <link>https://medium.com/@Freeanser/%E9%9B%B2%E7%AB%AF%E9%81%8B%E7%AE%97-cloud-computing-c5d66fdbbdf6?source=rss-1e2900a787bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5d66fdbbdf6</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Yen's Coding Journal]]></dc:creator>
            <pubDate>Wed, 31 Jan 2024 00:49:18 GMT</pubDate>
            <atom:updated>2024-01-31T01:22:21.396Z</atom:updated>
            <content:encoded><![CDATA[<ul><li>一種透過互聯網來提供各種計算資源（包括伺服器、儲存空間、資料庫、網路、軟體等）的模式。這些資源通常是由雲端服務提供商（例如Amazon Web Services、Microsoft Azure、Google Cloud等）在其資料中心中管理和維護的。</li><li>只要使用者能透過網路，由用戶端，登入遠端伺服器進行操作，就是雲端運算。</li></ul><h3>概述雲端運算：</h3><h4>定義雲運算：</h4><ul><li>雲運算是一種透過互聯網提供計算資源的模式，包括伺服器、儲存空間、資料庫、網路等，使用者可以隨時透過網路存取這些資源，而不需要擁有或管理實體硬體。</li></ul><h4>主要特點：</h4><p>提到雲運算的主要特點，如即時可用性、資源共享、按需取用、自動化管理、可伸縮性等。舉例說明這些特點如何使雲運算區別於傳統的資訊技術模型。</p><h4>服務模型：</h4><ul><li>雲運算的三種主要服務模型：IAAS（Infrastructure as a Service）、SAAS（Software as a Service）和PAAS（Platform as a Service）。</li></ul><h4>部署模型：</h4><ul><li>三種主要部署模型：公有雲、混合雲、私有雲。</li></ul><h4>實際應用與例子：</h4><ul><li>企業使用雲運算來擴展其應用程式、儲存和處理大數據，以及提高業務的靈活性和效率。</li><li>最新趨勢：雲運算領域的最新趨勢，如容器化、無伺服器計算、人工智慧在雲端的應用等。</li></ul><h4>個人經驗：</h4><blockquote>簡要介紹Heroku：</blockquote><ul><li>Heroku是一個PAAS（Platform as a Service）的雲平台，用於應用程式的開發、部署和運行。優勢：其易用性、快速部署和無需管理底層基礎設施的特點。</li></ul><blockquote>自動化構建和部署、簡單的環境變數管理：</blockquote><ul><li>Heroku 帳戶設定</li><li>Heroku CLI 設定</li><li>建立Heroku 專案</li><li>添加Heroku PostgreSQL作為資料庫</li><li>設定 Procfile</li><li>套用環境變數</li><li>部署到 Heroku (git push heroku main)</li><li>使用heroku open開啟應用程式：</li></ul><blockquote>自動化和集成：</blockquote><ul><li>是的，Heroku已經簡化應用程式的開發、部署和管理，讓使用者無需手動配置和管理這些方面的細節。以下是一些 Heroku 已經處理好的功能：</li><li>1. CI/CD 自動化：<br>Heroku Pipelines 提供了集成的 CI/CD 解決方案，無需額外配置。</li><li>2. Heroku Add-ons 集成：<br>Heroku Add-ons 提供了現成的擴展服務，使開發者能夠快速而輕鬆地使用各種第三方服務，例如資料庫、快取、監控工具等。</li><li>3. Heroku GitHub 集成：<br>開發者只需連接 Heroku 應用程式和 GitHub 存儲庫，就能夠實現代碼推送的自動部署。</li><li>4. Heroku 資源自動調整：<br> Heroku Autoscaling 允許開發者自動調整應用程式的 dyno 數量，以應對流量變化。</li></ul><blockquote>監控和調適：</blockquote><ul><li>談論在Heroku上如何進行應用程式的監控和調適，以確保高可用性和性能。</li></ul><blockquote>公有雲（Public Cloud）</blockquote><ul><li>Heroku是一種公有雲（Public Cloud）服務。在公有雲模型中，Heroku提供了由雲端服務提供商構建和管理的共享基礎設施，多個用戶可以透過互聯網存取和使用這些資源。使用者無需擁有或管理實體硬體，而是透過Heroku平台按需取用計算資源，使其成為一種具有高度可伸縮性和靈活性的雲端服務。</li></ul><blockquote>Google App Engine比較：</blockquote><ul><li>是流行的雲端平台</li></ul><h3>Heroku和Google App Engine（GAE）差異點：</h3><h4>運行環境：</h4><ul><li>Heroku： 支援多種語言和框架，提供更大的靈活性。使用者可以選擇自己的運行時環境。</li><li>Google App Engine： 主要支援特定的語言和框架，例如Python、Java、Go等。GAE強調開發者無需管理伺服器，而是依賴於平台的自動擴展能力。</li></ul><h4>部署模型：</h4><ul><li>都是公有雲(Public Cloud)</li></ul><h4>進行互動的命令行工具：</h4><ul><li>Heroku CLI（Command Line Interface），允許開發者通過終端機使用命令來管理和部署Heroku上的應用程式。Heroku CLI提供了各種命令，包括應用程式的創建、部署、管理附加元件、檢視日誌等，使開發者能夠在本地端更方便地與Heroku平台進行互動。</li><li>Google App Engine (GAE)，提供了 Google Cloud SDK，其中包括了 gcloud 命令行工具，這就是 GAE 的 CLI 工具。透過 Google Cloud SDK，開發者可以使用命令行來管理和操作 Google Cloud Platform 上的各種服務，包括 Google App Engine。gcloud 提供了一系列的命令，涵蓋了應用程式的部署、監控、設定、資源管理等功能。</li></ul><h4>擴展性：</h4><ul><li>Heroku： 允許用戶更靈活地擴展應用程式，但需要手動設置和管理。</li><li>Google App Engine： 具有自動擴展的能力，平台會根據需求自動調整伺服器實例數量，這使得擴展更加自動和無縫。</li></ul><h4>設定和管理：</h4><ul><li>Heroku： 提供更多自訂選項，開發者可以更精細地調整和配置應用程式。</li><li>Google App Engine： 強調無伺服器管理，開發者可以專注於應用程式的邏輯，而不需操心底層基礎設施的管理。</li></ul><h4>插件和擴展性：</h4><ul><li>Heroku： 具有豐富的插件生態系統，允許開發者擴展應用程式的功能。</li><li>Google App Engine： 提供許多內建服務，也支援外部服務的整合，但插件生態系統相對較少。</li></ul><h3>Heroku和Google App Engine（GAE）相似點：</h3><h4>雲端服務模型：</h4><ul><li>二者都是以Platform as a Service（PAAS）的形式提供，開發者可以專注於應用程式的開發，而不需操心底層基礎設施的管理。</li></ul><h4>自動擴展：</h4><ul><li>Heroku和Google App Engine都支援自動擴展，根據流量和需求調整伺服器實例的數量。</li></ul><h4>簡化部署流程：</h4><ul><li>兩者都致力於簡化應用程式的部署過程，減少開發者與底層基礎設施的互動，提高效率。</li></ul><h4>付費模型：</h4><ul><li>以使用量為基礎的付費模型，開發者根據實際使用的資源量支付相應的費用。</li></ul><h3>雲端運算的主要特點：</h3><h4>1. 即時可用性：</h4><p>基於雲端運算的方式，使用者無需建立自己的機房即可使用雲。使用者可以隨時隨地透過互聯網存取雲端資源，無需依賴特定的地理位置或設備。</p><h4>2. 資源共享：</h4><p>多個使用者可以同時共享同一組雲端資源，這些資源會根據需要動態分配和釋放，以提高效率和節省成本。</p><h4>3. 按需取用：</h4><p>使用者可以根據實際需求隨時擴展或縮減其使用的資源，並只需支付實際使用的量，而不必事先購買大量硬體。</p><h4>4. 自動化管理：</h4><p>雲端服務提供商負責管理和維護資源，包括硬體設備、網路設置、軟體更新等，使用者只需專注於應用程式和服務的開發、部署和管理。</p><h4>5. 可伸縮性：</h4><p>雲端資源可以根據使用者的需求動態擴展或縮小，確保系統在處理大量工作負載時仍能保持高效運作。</p><p>總的來說，雲端運算為使用者提供了更具靈活性、效率和成本效益的資源管理方式，使企業和個人能夠更輕鬆地運行應用程式、儲存和處理數據，並提高管理效率，而無需擔心硬體設備的維護和管理。</p><h3>類別：</h3><blockquote>IAAS、PAAS和SAAS</blockquote><h4>1.IAAS（Infrastructure as a Service）：</h4><ul><li>例子：<br>Amazon Web Services (AWS)、Microsoft Azure、Google Cloud Platform (GCP)</li><li>描述：<br>使用者可以在這些雲端平台上租用虛擬伺服器、儲存空間和網路資源。這允許用戶根據需要構建和管理自己的基礎設施，例如運行應用程式、虛擬機器、儲存區塊等。</li><li>具體例子：<br>在IAAS（Infrastructure as a Service）情況下，例如AWS，使用者需要自行管理和配置基礎設施，包括虛擬機器、網路、儲存等。這需要用戶更多的時間和精力來設置和調整不同的參數，以確保應用程式在雲端環境中正確運行。IAAS提供了更大的靈活性，但同時也需要更多的管理工作。</li></ul><h4>2. PAAS（Platform as a Service）：</h4><ul><li>例子：<br>Heroku、Google App Engine、Microsoft Azure App Service</li><li>描述：<br>這些平台提供了一個開發和運行應用程式的完整環境，包括開發工具、執行時環境和相關服務。開發者可以專注於應用程式的邏輯，而不必擔心底層的基礎設施。</li><li>具體例子：<br>在PAAS（Platform as a Service）的情況下，例如Heroku，使用者可以專注於應用程式的開發，而無需擔心底層的基礎設施。Heroku提供了一個完整的開發和部署平台，開發者只需按照Heroku的指示進行相應的操作，就能成功地部署應用程式，而不需要操心伺服器和網路設定等底層細節。</li></ul><h4>3. SAAS（Software as a Service）：</h4><ul><li>例子：<br>Microsoft 365、Google Workspace、Salesforce</li><li>描述：<br>這些是提供完整應用程式的服務，使用者可以透過網頁瀏覽器或應用程式存取，而不需擔心安裝、配置或維護應用程式的細節。例如，Microsoft 365提供了基於雲端的辦公軟體套件，包括Word、Excel、PowerPoint等。</li></ul><h3>部署模型：</h3><h4>公有雲（Public Cloud）：</h4><p>公有雲是由雲端服務提供商構建和管理的，多個客戶共享相同的基礎設施。這種模型的優勢在於成本共享和可伸縮性，但使用者無法掌握雲端基礎設施的具體位置和細節。</p><h4>混合雲（Hybrid Cloud）：</h4><p>混合雲結合了公有雲和私有雲的特點，使組織能夠在需要時擴展其資源，同時仍然保有一定程度的控制權。這允許敏感性較高的工作負載在私有雲中運行，而其他工作負載可以在公有雲中運行。</p><h4>私有雲（Private Cloud）：</h4><p>私有雲是由單一組織構建和管理的，僅供該組織內部使用。這種模型提供更高的安全性和控制權，但可能需要更多的資本投入和管理成本。</p><h3>部署模型：</h3><h4>1.公有雲（Public Cloud）：</h4><ul><li>例子：<br>Amazon Web Services (AWS), Microsoft Azure, Google Cloud Platform (GCP)</li><li>描述：<br>使用者可以透過這些公有雲服務提供商租用虛擬伺服器、儲存空間和其他資源，並與其他客戶共享相同的基礎設施。這提供了成本共享和可伸縮性的好處，但使用者無法直接掌握基礎設施的具體位置和細節。</li></ul><h4>2. 混合雲（Hybrid Cloud）：</h4><ul><li>例子：<br>Azure Hybrid Cloud, AWS Outposts</li><li>描述： <br>混合雲結合了公有雲和私有雲的特點，使組織能夠在需要時擴展其資源。例如，敏感性較高的工作負載可以在私有雲中運行，而其他工作負載可以在公有雲中運行。Microsoft Azure提供了混合雲解決方案，使組織能夠整合本地資源和雲端資源。</li></ul><h4>3. 私有雲（Private Cloud）：</h4><ul><li>例子：<br>VMware Cloud Foundation, OpenStack</li><li>描述：<br>私有雲是由組織內部構建和管理的，提供更高的安全性和控制權。組織可以在私有雲中運行特定應用程式或數據，並且有能力定制基礎設施，以滿足特定的安全性和合規性需求。但可能需要更多的資本投入和管理成本。 VMware提供了Cloud Foundation，而OpenStack則是一個開源的私有雲解決方案。</li><li>企業可以自行構建（Self-built）私有雲，也可以向專門的私有雲解決方案提供商購買現成的私有雲解決方案。 ex: Microsoft Azure Stack是微軟提供的一個私有雲解決方案。</li></ul><p>這些實例提供了不同的部署模型，使組織能夠根據需求和安全性要求做出適當的選擇。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5d66fdbbdf6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object-oriented programming (OOP)]]></title>
            <link>https://medium.com/@Freeanser/object-oriented-programming-oop-a009f29cd51f?source=rss-1e2900a787bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/a009f29cd51f</guid>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Yen's Coding Journal]]></dc:creator>
            <pubDate>Sun, 28 Jan 2024 08:18:35 GMT</pubDate>
            <atom:updated>2024-01-31T00:16:24.013Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Java 為主，JavaScript 為輔助說明。</em></blockquote><h3>物件導向編程（OOP）：</h3><ul><li>OOP 是一種程式設計範式，將程式中的相關數據和操作封裝到單個實體（物件）中</li><li>以物件(object)為中心設計</li><li>應用程式是「一群物件的互動」</li><li>物件會有不同的屬性和method，物件之間會有互動。</li></ul><h3>重要概念：</h3><p>物件導向設計是一種軟體設計方法，主要基於三個基本概念：封裝（Encapsulation）、繼承（Inheritance）、多型（Polymorphism）。</p><h3>封裝 Encapsulation</h3><p>封裝是指將類別的屬性（properties / attributes）和方法（methods）結合在一起，並將內部細節隱藏起來。這可以通過使用私有（private）屬性和方法，以及提供公開的方法來實現。</p><h4>優點：</h4><p>隱藏實現細節、提高代碼的可維護性。可以</p><p>通過 getter 和 setter 方法來訪問或修改私有屬性。</p><pre>public class Person {<br>    private String name;<br>    private int age;</pre><pre>    // Constructor<br>    public Person(String name, int age) {<br>        this.name = name;<br>        this.age = age;<br>    }</pre><pre>    // Public method to access private data<br>    public String getName() {<br>        return name;<br>    }</pre><pre>    public int getAge() {<br>        return age;<br>    }<br>}</pre><p>name 和 age 屬性是私有的，外部程式無法直接訪問，而透過 getName 和 getAge 方法提供了公開的介面（public interface）。</p><p>公開的介面。在物件導向設計中，封裝是一種設計原則，而在這裡描述的「介面」僅指類別對外暴露的公開方法。在物件導向設計中，封裝通常是透過設定存取權限和提供公開介面實現的。</p><h3>繼承 Inheritance</h3><p>繼承允許一個新的類別（子類別）繼承另一個類別（父類別）的屬性和方法。這促進了代碼的重用和擴展，同時建立了類別之間的層次結構。</p><p>這種繼承是靜態的，類別在定義時就確定了其繼承關係。子類別可以使用父類別的屬性和方法，並且還可以擴展或覆寫這些屬性和方法。</p><p>Java 中的繼承是透過 extends關鍵字實現的，如下所示：</p><pre>// 父類別<br>class Animal {<br> void eat() {<br> System.out.println(&quot;Animal is eating&quot;);<br> }<br>}<br>// 子類別繼承父類別<br>class Dog extends Animal {<br> void bark() {<br> System.out.println(&quot;Dog is barking&quot;);<br> }<br>}<br>public class InheritanceExample {<br> public static void main(String[] args) {<br> // 創建 Dog 實例<br> Dog myDog = new Dog();<br>// 調用父類別的方法<br> myDog.eat();<br>// 調用子類別的方法<br> myDog.bark();<br> }<br>}</pre><p>這裡的 Dog類別繼承自 Animal 類別，並且可以使用 Animal 類別中的 eat 方法。這是 Java 中基於類別的繼承概念。</p><p>再一個例子：</p><pre>// 建立一個名為 SmartPhone 的類別<br>class SmartPhone {<br>    // 定義 SmartPhone 的屬性<br>    String name;</pre><pre>    // SmartPhone 類別的建構函式<br>    public SmartPhone(String name) {<br>        this.name = name;<br>    }</pre><pre>    // 定義 SmartPhone 的方法<br>    public void displayInfo() {<br>        System.out.println(&quot;SmartPhone: &quot; + name);<br>    }<br>}</pre><pre>// 建立一個名為 AndroidPhone 的子類別，繼承自 SmartPhone<br>class AndroidPhone extends SmartPhone {</pre><pre>    // AndroidPhone 類別的建構函式<br>    public AndroidPhone(String name) {<br>        // 呼叫父類別的建構函式<br>        super(name);<br>    }</pre><pre>    // 這裡可以擴展 AndroidPhone 的特有方法<br>    public void runAndroidApp() {<br>        System.out.println(name + &quot; is running an Android app.&quot;);<br>    }<br>}<br></pre><pre>public class Main {<br>    public static void main(String[] args) {<br>        // 創建一個 AndroidPhone 的實例<br>        AndroidPhone alphaPhoneX = new AndroidPhone(&quot;AlphaPhoneX&quot;);<br>        // 調用 SmartPhone 的方法<br>        alphaPhoneX.displayInfo();<br>        // 調用 AndroidPhone 的方法<br>        alphaPhoneX.runAndroidApp();<br>    }<br>}</pre><h3>在 Java 中任何東西的 Class 都是繼承自 Object</h3><p>Object 類別是 Java 中的基礎類別，所有其他類別都直接或間接地繼承自它。</p><p>此符合 Java 的單一繼承模型，即每個類別只能有一個直接的父類別，而 Object 類別是這個繼承鏈的頂端。</p><p>因此，你可以說在 Java 中，任何 class 最終都是來繼承自 Object。這是 Java 物件導向設計中的基本概念。</p><h4>一個物件如何取得另一個物件的屬性與方法</h4><p>在 Java 中，基本型別（primitive types）如 int 或 char 是不屬於物件的，它們是直接存儲數值的。這些基本型別並沒有相對應的類別。例如，int 表示整數，而不是一個物件。</p><p>然而，String 是一個引用型別，是內建於 java.lang 包中的，它是 Java 中表示字串的類別。</p><p>String 是由 java.lang.String 類別定義的，並提供了許多字串相關的方法。當你宣告一個 String 變數時，實際上是在記憶體中創建一個對 String 物件的引用。你可以使用 name.getClass().getSimpleName() 來獲取字串 name 的類別名稱。</p><p>總結來說，基本型別和引用型別在 Java 中是有區別的，基本型別沒有相對應的類別，而引用型別有對應的類別，例如 String。</p><pre>// 建立一個字串物件作為例子<br>String name = &quot;AlphaPhoneX&quot;;<br>System.out.println(name); // &quot;AlphaPhoneX&quot;</pre><pre>// 使用 getClass() 方法獲取物件的 Class 對象<br>Class&lt;?&gt; classOfName = name.getClass();<br>System.out.println(classOfName); // class java.lang.String<br>// 使用 getSuperclass() 方法獲取類別的父類的 Class 對象<br>Class&lt;?&gt; superClassOfName = classOfName.getSuperclass();<br>System.out.println(superClassOfName); // class java.lang.Object<br>// Class&lt;?&gt; 是一個泛型類型，表示一個未知具體類型的 Class 對象<br>// 這裡的 &lt;?&gt; 是通配符，表示可以是任意類型。<br>// 透過繼承，字串 name 可以取用 String 和 Object 的定義好的方法<br>// 因此你可以使用 .toLowerCase(), .substring(), .length() 等字串方法：<br>System.out.println(name.toLowerCase()); // &quot;alphaphonex&quot;<br>System.out.println(name.substring(0, 5)); // &quot;Alpha&quot;<br>System.out.println(name.length()); // 12</pre><pre>// 在 Java 中，所有的類別都直接或間接地繼承自 Object 類別</pre><p>在 Java 中，使用 getClass() 以及 getSuperclass() 方法可以取得物件的類型和父類型。</p><p>在 Java 中，String`類別的父類別是 Object 類別。所有的類別在 Java 中都直接或間接地繼承自 Object 類別。因此，String 類別也繼承了 Object 類別的屬性和方法。</p><p>這就是 Java 中的「類別」和「繼承」，核心目的是「取得另一個物件的屬性與方法」，如此一來，你才能應用物件導向程式設計，把不同物件間共用的屬性與方法封裝到上層的 class 裡。</p><h3>多型 Polymorphism</h3><blockquote>多型（Polymorphism）和繼承（Inheritance）是物件導向程式設計中的兩個不同概念，但它們經常一起使用。</blockquote><p>多型允許使用相同的介面處理不同類型的物件，這提高了程式碼的可擴展性和可讀性。</p><ul><li>多型 涉及到 父類別 聲明一個方法（或介面定義一個方法），然後 子類別覆寫（override）這個方法以提供自己的實現。</li><li>如果兩個類別沒有繼承關係，即使它們有相同名稱的方法，這並不被視為多型性。</li></ul><pre>public class Animal {<br>    public void makeSound() {<br>        System.out.println(&quot;Animal makes a sound&quot;);<br>    }<br>}</pre><pre>public class Dog extends Animal {<br>    @Override<br>    public void makeSound() {<br>        System.out.println(&quot;Dog barks&quot;);<br>    }<br>}</pre><pre>public class Cat extends Animal {<br>    @Override<br>    public void makeSound() {<br>        System.out.println(&quot;Cat meows&quot;);<br>    }<br>}</pre><p>無論你處理一個 Animal 型別的變數，實際執行的方法取決於物件的實際型別：</p><pre>Animal myDog = new Dog();<br>Animal myCat = new Cat();</pre><pre>myDog.makeSound();  // 實際執行 Dog 的 makeSound()<br>myCat.makeSound();  // 實際執行 Cat 的 makeSound()</pre><p>因此，你可以使用相同的方法名稱 makeSound() 來處理不同類型的動物，並且根據實際的物件型別，呼叫對應的實現。</p><blockquote>使用相同的方法名字，是為了強調相同的介面或契約，而不是具體的實現。這樣的一致性有助於代碼的可讀性和可維護性。</blockquote><blockquote>當你在設計使用多型的系統時，你通常希望客戶端代碼（使用這些物件的代碼）能夠依賴於共同的介面，而不需要關心具體的實現。這樣，當你引入新的子類別時，客戶端代碼無需修改，因為它們只關心介面。</blockquote><blockquote>假設有一個簡單的場景，你需要處理不同類型的動物，並播放它們的聲音。如果每種動物都有一個不同名字的方法，那麼你在客戶端的代碼中將不得不處理每種動物的具體方法名字，這樣的代碼會變得冗長且難以維護。</blockquote><blockquote>使用相同的方法名稱（共同的介面）使得你能夠以通用的方式處理不同類型的物件，提高了代碼的可擴展性和靈活性。</blockquote><p>總結來說，繼承是建立類別之間的層次結構。多型強調的是對相同介面的使用，而不是對方法的修改。。它們通常一起使用。</p><h3>基礎概念：</h3><p>抽象化 Abstraction、類別與物件 Class and Object Instance、組合 Composition 或 聚合 Aggregation</p><h3>抽象化Abstraction</h3><p>「把真實世界的具體事情，轉化成程式世界裡面的抽象物件」的過程。</p><p>以「人」舉例：</p><ol><li>根據程式的需要，設計「人」的物件模型。</li><li>每一個「人」，都可以是獨立的物件。</li><li>重複宣告新物件，很浪費時間、程式碼也難以維護。</li><li>因此：<br>先統一為「人」物件建立一個抽象化的簡單模型，然後在程式中使用此模型來快速建立結構一致的「人」物件實例 (instance)。</li><li>先抽取出本質、設計共同的屬性和方法，形成「人」的概念。</li><li>根據應用程式的需求（也就是商業需求），將相關的本質，抽取成物件的 attribute 和 methods</li><li>情境：公司業務<br>attributes: <br>employee_id<br>name<br>sale<br>methods:<br>call<br>sale</li><li>情境：需要設計很多類型的手機<br>attributes:<br>name<br>price<br>features<br>methods:<br>showPhoneInfo</li></ol><h4>此為重複宣告新物件（實例 instance）的方法：</h4><p>以 JavaScript 舉例：</p><pre>let alphaPhoneX = {<br> name: ‘AlphaPhoneX’,<br> price: 14999,<br> features: [‘long battery life’, ‘AI camera’]<br> showPhoneInfo: function () {<br> console.log(`The price of ${this.name} is ${this.price}, which has the newest features such as ${this.features.join(‘, ‘)}.`)<br> }<br>}<br>let alphaPhoneY = {<br> name: &#39;AlphaPhoneY&#39;,<br> price: 18900,<br> features: [&#39;water proof&#39;, &#39;high screen resolution&#39;]<br> showPhoneInfo: function () {<br> console.log(`The price of ${this.name} is ${this.price}, which has the newest features such as ${this.features.join(&#39;, &#39;)}.`)<br> }<br>}<br>let alphaPhoneZ = {<br> name: &#39;AlphaPhoneZ&#39;,<br> price: 23900,<br> features: [&#39;IP47&#39;, &#39;high screen resolution&#39;, &#39;full display&#39;]<br> showPhoneInfo: function () {<br> console.log(`The price of ${this.name} is ${this.price}, which has the newest features such as ${this.features.join(&#39;, &#39;)}.`)<br> }<br>}</pre><blockquote>重複宣告新物件的方法，很浪費時間、程式碼也難以維護。</blockquote><h3>類別與物件 Class and Object Instance：</h3><p>物件導向設計的基本單位是類別（Class）和物件（Object）。類別是一種定義了屬性和行為的模板，而物件是類別的實例。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/0*zOMw8qmlATJFmqu6" /></figure><h4>類別 (class)：</h4><p>是 實例 上層的抽象來源</p><p>設定好共用的 attributes 和 methods之後，每一個從此class產生的instance，都能取得這些共用的 attributes 和 methods</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*k1yUlTgJnJpaS2Hc" /></figure><h4>實例 ( instance):</h4><p>這些真正存在的手機，是「實例」( instance)</p><h3>Constructor Function</h3><blockquote>是用來創造物件的函式：在 class 設定共同屬性，可以快速產生物件instance。<br>constructor ：「建構式」或「建構子」</blockquote><h4>定義 Constructor Function</h4><pre>public class SmartPhone {<br>    // 使用了 private 來封裝（Encapsulation）此 class 的 attributes<br>    // 所以這些屬性只能在 SmartPhone 這個類別的內部被訪問<br>    // 外部程式碼只能通過 public methods 進行訪問<br>    private String name;<br>    private int price;<br>    private String[] features;<br><br>// Constructor<br>    public SmartPhone(String name, int price, String[] features) {<br>        this.name = name;<br>        this.price = price;<br>        this.features = features;<br>    }<br>    // Method to show phone information<br>    public void showPhoneInfo() {<br>        System.out.println(&quot;The price of &quot; + name + &quot; is &quot; + price +<br>                &quot;, which has the newest features such as &quot; + String.join(&quot;, &quot;, features) + &quot;.&quot;);<br>    }<br>}</pre><ul><li>函式名稱使用大寫，以方便一看就知道這個函式是個 constructor。</li><li>不能用 return。使用 return 後，就不會建構新物件了。</li></ul><h4>new</h4><p>接著讓我們運用定義好的 SmartPhone class 來建立 new object (instance)，請在呼叫函式時加上 new：</p><pre>public class SmartPhoneUsage {<br><br>    // 前面有提到的代碼......<br><br>    public static void main(String[] args) {<br>        // 使用 &#39;new&#39; 關鍵字創建物件實例<br>        SmartPhone alphaPhoneX = new SmartPhone(&quot;alphaPhoneX&quot;, 14999, new String[]{&quot;long battery life&quot;, &quot;AI camera&quot;});<br>        SmartPhone alphaPhoneY = new SmartPhone(&quot;alphaPhoneY&quot;, 18900, new String[]{&quot;water proof&quot;, &quot;high screen resolution&quot;});<br>        SmartPhone alphaPhoneZ = new SmartPhone(&quot;alphaPhoneZ&quot;, 23900, new String[]{&quot;IP47&quot;, &quot;high screen resolution&quot;, &quot;full display&quot;});<br>        // 可以使用 alphaPhoneX、alphaPhoneY、alphaPhoneZ 物件進行相應的操作<br>    }<br>}</pre><p>由於建構式（constructor）中定義的類別（class）是代表通用手機的模板，而由建構式創建的物件（object）則是實際的、具體的手機實例，為了區分，我們通常會稱由建構式創建的物件為「實例（instance）」。</p><p>在這裡，alphaPhoneX, alphaPhoneY, alphaPhoneZ 都是由 SmartPhone 建立的 實例 (instance)<em> </em>。</p><h4>New 與 this</h4><h4>this</h4><p>在面向對象的程式語言中，this 是一個特殊的關鍵字，用來指代當前對象的實例。它在不同的語言中可能有一些微小的差異，但通常用於指代當前方法或建構子中正在被操作的物件。</p><h4>new</h4><p>在許多面向對象程式語言中用來創建新物件實例的關鍵字。當你使用 new 關鍵字時，它會觸發以下過程：</p><ol><li>創建一個空的物件： <br>new 關鍵字首先創建一個新的空物件。</li><li>將該物件的類型設定為新實例的類型： <br>該物件的 class 是由 new 後面的 class 來決定的。</li><li>將 this 設定為新創建的物件： <br>在建構子內部，this 關鍵字被設置為新創建的物件，這樣在建構子內部可以訪問到新物件的屬性。</li><li>返回新物件： <br>如果建構子內部沒有明確返回其他對象，則 new 運算符將返回新創建的物件。</li></ol><p>在 Java 中，這個過程與其他面向對象語言的過程相似。 你可以使用 new 來創建物件實例，並且建構子函數（例如上面的 SmartPhone）會在 new 調用時被呼叫。 這是一種標準的物件創建方法。</p><h4>舉例：</h4><pre>public class SmartPhone {<br>    private String name;<br>    private int price;<br>    private String[] features;<br><br>    // Constructor<br>    public SmartPhone(String name, int price, String[] features) {<br>        System.out.println(this);  // 在建構子中的 this 指向剛被創建的 SmartPhone 實例<br>        this.name = name;<br>        System.out.println(this);  // 在設置屬性 name 後，this 仍然指向相同的 SmartPhone 實例<br>        this.price = price;<br>        System.out.println(this);  // 在設置屬性 price 後，this 仍然指向相同的 SmartPhone 實例<br>        this.features = features;<br>        System.out.println(this);  // 在設置屬性 features 後，this 仍然指向相同的 SmartPhone 實例<br>        this.showPhoneInfo = new ShowPhoneInfo();  // 在建構子中新建一個 ShowPhoneInfo 實例，this 仍然指向相同的 SmartPhone 實例<br>        System.out.println(this);  // 在設置 showPhoneInfo 後，this 仍然指向相同的 SmartPhone 實例<br>    }<br><br>     // 其他方法和類別的定義...<br><br>    private class ShowPhoneInfo {<br>        // 一些用於顯示手機信息的實現<br>    }<br><br>    public static void main(String[] args) {<br>        SmartPhone alphaPhoneX = new SmartPhone(&quot;alphaPhoneX&quot;, 14999, new String[]{&quot;long battery life&quot;, &quot;AI camera&quot;});<br>        alphaPhoneX.showPhoneInfo();  // 調用 SmartPhone 實例的方法<br>    }<br>}</pre><h3>組合 Composition 或 聚合 Aggregation</h3><p>用來描述類別之間的關係：一個類別也可以是另外一個類別的屬性</p><h4>1. 組合（Composition）：</h4><ul><li>在組合中，一個類別的物件是另一個類別的部分。這表示如果父類別被刪除，所有的子類別也將被刪除。</li><li>例如，一個汽車類別可以包含引擎、輪胎、座椅等其他類別的物件。如果汽車被銷毀，所有的部分也應該被銷毀。</li></ul><pre>public class Car {<br> private Engine engine;<br> private Tire tire;<br> private Seat seat;<br>public Car(Engine engine, Tire tire, Seat seat) {<br> this.engine = engine;<br> this.tire = tire;<br> this.seat = seat;<br> }<br>}</pre><h4>2. 聚合（Aggregation）：</h4><ul><li>在聚合中，一個類別的物件可以包含另一個類別的物件，但它們之間的生命週期是獨立的。如果父類別被刪除，子類別仍然可以存在。</li><li>例如，一個學校類別可以包含多個班級類別的物件。如果學校被解散，班級仍然可以存在。</li></ul><pre><br>public class School {<br> private List&lt;Classroom&gt; classrooms;<br>public School(List&lt;Classroom&gt; classrooms) {<br> this.classrooms = classrooms;<br> }<br>}</pre><p>這些概念有助於設計具有良好結構和模組化的程式，同時明確了類別之間的關係和依賴性。</p><blockquote>待學：</blockquote><blockquote>abstract關鍵詞用法</blockquote><blockquote>在Java中，`interface` 是一個關鍵字，用來定義介面。它不是一種類別，而是一種特殊的型態，用於定義一組方法的規範，但沒有提供方法的實作。`interface` 定義了一個契約，要實現（implement）這個介面的類別必須提供介面中聲明的所有方法的具體實現。</blockquote><blockquote>在Java中，一個類別可以實現（implement）多個介面。不同於類別之間的繼承（extends），介面提供了一種實現多重繼承的方式。</blockquote><blockquote>`interface` 不是一個父類別，而是一種規範或契約，它定義了實現類別應該提供的方法，但不包含實際的屬性或方法實作。類別實現介面時使用 `implements` 關鍵字。</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a009f29cd51f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Favorite Movie List]]></title>
            <link>https://medium.com/@Freeanser/movie-favorite-list-7e42aeaefc42?source=rss-1e2900a787bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e42aeaefc42</guid>
            <category><![CDATA[flask-sqlalchemy]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[movie-api]]></category>
            <category><![CDATA[omdb]]></category>
            <dc:creator><![CDATA[Yen's Coding Journal]]></dc:creator>
            <pubDate>Tue, 12 Dec 2023 17:51:08 GMT</pubDate>
            <atom:updated>2023-12-12T19:28:55.854Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>a Python project</blockquote><p>I am excited to present the project I collaborated with my teammate. As movie enthusiasts, we shared the goal of creating a collection of our favorite films. Consequently, we decided to build a Favorite Movie List together.</p><p>However, as this is a team project, I will focus on providing details and explanations about the specific part I developed in this essay.</p><h3>Here’s the design diagram I drew by myself:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UNEU12tcNQ-LU6JzpiQ2Zw.jpeg" /></figure><p>This is a team project, and I will provide some details and explanations about the part I developed.</p><h3>Project Description (My Responsibility):</h3><p>Users can use this application to save their favorite movies to a “My Favorites” list, add movies, view their favorite movies, and remove movies from their favorites.</p><p>The application utilizes Flask as the web framework and SQLAlchemy to interact with a database.</p><h3>Setting up the environment：</h3><p>Enter the following commands in the terminal to build the environment：</p><pre>pipenv install flask flask-sqlalchemy</pre><pre>// Enter the Pipenv virtual environment to run commands,<br>// avoiding conflicts with commands affecting other projects.<br>pipenv shell</pre><pre>// Set the entry file<br>export FLASK_APP=flask-server.api <br><br>// Allow automatic application restarts when code changes occur<br>export FLASK_DEBUG=1</pre><pre>// Enter the Python interactive interpreter(for quick and convenient testing)<br>// In a general production environment, <br>// using a database migration tool like Flask-Migrate is a best practice.<br>python<br><br>// Import the Movie class from the models file in the api module.<br>from api.models import Movie<br>from api import db, create_app<br><br>// Create a Movie table if it doesn&#39;t exist.<br>db.create_all(app=create_app())<br>exit()</pre><p>For Testing:</p><pre>// Open the SQLite database file api/database.db<br>sqlite3 api/database.db<br><br>// View the tables in the current SQLite database.<br>.tables<br>// Query all data from the table named movies in SQLite.<br>select * from movies;</pre><h3>In __init__.py:</h3><p>The “__init__.py” file is typically used to turn a directory into a Python package. It handles initialization and configuration tasks, creates a Flask application instance (via the “create_app()” function), configures the application, and imports database objects.</p><pre>from flask import Flask<br>from flask_sqlalchemy import SQLAlchemy<br>from flask_cors import CORS<br><br>db = SQLAlchemy()<br>def create_app():<br><br>  # Build the application<br>  # The __name__ in Flask(name) is primarily used to determine the root directory of the Flask application and its default behavior when searching for templates and static files within Flask.<br>  app = Flask(__name__)<br><br>  # The purpose of CORS(app) is to enable Cross-Origin Resource Sharing on the backend,<br>  # allowing the frontend to send cross-origin requests to the backend, <br>  # thereby achieving cross-origin resource access<br>  # When developing frontend and backend on different servers <br>  # (e.g., using a JavaScript browser application), CORS(app) is needed.<br>  CORS(app)<br>  <br>  # This line configures the database URI for the SQLAlchemy extension in the Flask application. <br>  # The specified URI indicates the use of an SQLite database <br>  # with the filename `database.db`, and `sqlite:///` is the standard URI format for SQLite databases.<br>  app.config[‘SQLALCHEMY_DATABASE_URI’] = ‘sqlite:///database.db’<br>  <br>  # Initialize the database<br>  # Combining the initialization of the SQLAlchemy extension with the Flask application. <br>  # This is done by calling db.init_app(app), <br>  # where app is the Flask application instance.<br>  db.init_app(app)<br>  <br>  # Register the blueprint with the Flask application instance<br>  # This way, we can use the routes defined in the <br>  # `@main` blueprint within the Flask application.<br>  from .views import main<br>  app.register_blueprint(main)<br>  <br>  # Create the database tables<br>  with app.app_context():<br>  <br>  # Create database tables (if they do not exist).<br>  db.create_all()<br>  return app<br></pre><h3>In models.py:</h3><pre># from . =  from __init__.py<br>from . import db<br><br>class Movie(db.Model):<br><br>  # The name of this database table as &#39;movies&#39;.<br>   __tablename__ = &#39;movies&#39;<br><br>  # Defines a column named imdb_id with a data type of string <br>  # (maximum length of 20) <br>  # and marks it as a primary key.<br>  imdb_id = db.Column(db.String(20), primary_key=True)<br>  title = db.Column(db.String(255))<br>  year = db.Column(db.String(4))<br><br>  # Defines the constructor of the class<br>  def __init__(self, title, year, imdb_id):<br>    self.imdb_id = imdb_id<br>    self.title = title<br>    self.year = year</pre><h3>In Views.py:</h3><h4>Get Create-new-favorite-movie page and Create:</h4><pre>from flask import Blueprint, jsonify, request, render_template<br>import requests<br>from . import db<br>from .models import Movie<br>from . import omdb<br><br># Get the Create-new-favorite-movie page<br>@main.route(&#39;/movies/favorite/new&#39;, methods=[&#39;GET&#39;])<br>def get_create_page():<br>    return render_template(&#39;create_movie.html&#39;) <br><br># In the Create-new-favorite-movie page, create a new favorite movie<br>@main.route(&#39;/movies/favorite/new&#39;, methods=[&#39;POST&#39;])<br>def add_movie():<br>    if request.is_json:<br>        # If the request is in JSON format<br>        movie_data = request.get_json()<br><br>        # Create a new instance of the Movie class <br>        # and initialize its attributes with values from the JSON data.<br>        new_movie = Movie(<br>            imdb_id=movie_data.get(&#39;imdb_id&#39;),<br>            title=movie_data.get(&#39;title&#39;),<br>            year=movie_data.get(&#39;year&#39;),<br>        )<br><br>        #  Add the new_movie object to the database session.<br>        db.session.add(new_movie)<br><br>        # Commit the changes to the database, making the addition of the new movie permanent.<br>        db.session.commit()<br><br>        return &#39;Done&#39;, 201<br>    else:<br>        return jsonify({&#39;error&#39;: &#39;Invalid JSON data&#39;}), 400</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DGkG__2jKOdnTWxgsnArEg.png" /></figure><h4>Get Edit Page and Update:</h4><pre># Get the edit page of the specific movie<br>@main.route(&#39;/movies/favorite/&lt;imdb_id&gt;/edit&#39;, methods=[&#39;GET&#39;])<br>def get_edit_page(imdb_id):<br>    # Retrieve the movie from the database<br>    movie = Movie.query.get(imdb_id)<br><br>    # If the movie exists, return JSON data to the frontend<br>    if movie:<br>        return render_template(&#39;edit_movie.html&#39;, title=movie.title, year=movie.year, imdb_id=movie.imdb_id)<br>    else:<br>        return jsonify({&#39;error&#39;:&#39;Not found the movie.&#39;}), 404<br><br># In the specific movie edit page, update the movie<br>@main.route(&#39;/movies/favorite/&lt;imdb_id&gt;&#39;, methods=[&#39;PUT&#39;])<br>def update_movie(imdb_id):<br>    # Retrieve the movie from the database<br>    movie = Movie.query.get(imdb_id)<br><br> # If the movie exists, update the movie<br>    if movie:<br>        movie_data = request.get_json()<br>        movie.imdb_id = movie_data.get(&#39;imdb_id&#39;)<br>        movie.title = movie_data.get(&#39;title&#39;)<br>        movie.year = movie_data.get(&#39;year&#39;)<br>        db.session.commit()<br>        return &#39;Done&#39;, 201<br>    else:<br>        # If the movie doesn&#39;t exist, return a 404 error in JSON format<br>        return jsonify({&#39;error&#39;:&#39;Not found the movie.&#39;}), 404</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BMkF_I3GqQWvepIJ0cxPpw.png" /></figure><h4>Get details and Delete:</h4><pre># Get the detail of the specific movie<br>@main.route(&#39;/movies/favorite/&lt;imdb_id&gt;&#39;, methods=[&#39;GET&#39;])<br>def movie(imdb_id):<br>    # Retrieve the movie from the database<br>    movie = Movie.query.get(imdb_id)<br><br># If the movie exists, return its data<br>    if movie:<br>        # Return a JSON response containing details of the specific movie <br>        # to be used by the frontend.<br>        return jsonify({<br>            &#39;title&#39;: movie.title,<br>            &#39;year&#39;: movie.year,<br>            &#39;imdb_id&#39;: movie.imdb_id,<br>        })<br>    else:<br># If the movie does not exist, return a 404 error<br>        return jsonify({&#39;error&#39;:&#39;Not found the movie.&#39;}), 404<br>    <br><br># delete the specific movie<br>@main.route(&#39;/movies/favorite/&lt;imdb_id&gt;&#39;, methods=[&#39;DELETE&#39;])<br>def delete_movie(imdb_id):<br>    # Retrieve the movie from the database<br>    movie = Movie.query.get(imdb_id)<br><br>    # If the movie exists, delete the movie<br>    if movie:<br>        db.session.delete(movie)<br>        db.session.commit()<br>        return &#39;Done&#39;, 201<br>    else:<br>        # If the movie doesn&#39;t exist, return a 404 error in JSON format<br>        return jsonify({&#39;error&#39;:&#39;Not found the movie.&#39;}), 404@main.route(&#39;/movies/favorite/new&#39;, methods=[&#39;GET&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6I3bVDFarp1TKCDvbw5HjQ.png" /></figure><h3><strong>Challenges and Solutions of this project:</strong></h3><h4>(1) A member dropped out, and due to everyone’s busy schedules, the project faced a productivity crisis.</h4><p><strong>- Solution:</strong></p><p>Given my faster coding pace, I assumed the departing member’s tasks, wrote meeting records, and clarified responsibilities.</p><h4>(2) Because I made modifications to the .bash_profile while writing JavaScript, I couldn’t locate the Python path when working on this project.</h4><p><strong>- Solution:</strong></p><p>In the .bash_profile, I used the following command to reposition the Python3 path:</p><pre>`export PATH=$HOME/bin:/usr/local/bin/python3:/usr/bin:$PATH`.</pre><h4>(3) At the beginning of establishing this project, my teammate suggested using an anime API called Jikan. However, upon printing out the data, I found that the data structure of the Jikan database was very complex, and it included too many image files, making it difficult for me to work with.</h4><p><strong>- Solution:</strong></p><p>After discussing this dilemma with the team, we decided to split up and search for a movie API and determine the data structure of the retrieved data. Eventually, we found the omdb API!</p><h3>Future Expectations:</h3><p>I hope to implement user login, logout, and registration functionalities.</p><p>In the Python Flask framework, I can utilize extensions like Flask-Login and Flask-WTF to achieve user login, logout, and registration.</p><p>Additionally, I aim to establish a one-to-many relationship between the User table and the Favorite table.</p><p>I am looking forward to this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e42aeaefc42" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>