🔍 搜尋結果:oop

🔍 搜尋結果:oop

30 多個應用程式創意以及完整的源程式碼

這是科技進步的令人興奮的時刻。 作為開發人員,我們所有人都需要從事可以產生收入或幫助建立我們聲譽的副業專案。 今天,我們將介紹 10 個令人興奮的專案,並發現使用每個專案建立的 3-4 個流行應用程式。總共有 30 多個專案,提供程式碼存取供您學習。 這些將讓您編碼一段時間,所以讓我們開始吧! ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4fhpnyrvncqsbultjfk9.gif) --- 1. [CopilotKit](https://github.com/CopilotKit/CopilotKit) - 在數小時內為您的產品提供 AI Copilot。 ------------------------------------------------------------------------------------ ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/769q31e3wi56efcmkx1s.png) 將 AI 功能整合到 React 中是很困難的,這就是 Copilot 的用武之地。一個簡單快速的解決方案,可將可投入生產的 Copilot 整合到任何產品中! 您可以使用兩個 React 元件將關鍵 AI 功能整合到 React 應用程式中。它們還提供內建(完全可自訂)Copilot 原生 UX 元件,例如`<CopilotKit />` 、 `<CopilotPopup />` 、 `<CopilotSidebar />` 、 `<CopilotTextarea />` 。 開始使用以下 npm 指令。 ``` npm i @copilotkit/react-core @copilotkit/react-ui ``` Copilot Portal 是 CopilotKit 提供的元件之一,CopilotKit 是一個應用程式內人工智慧聊天機器人,可查看目前應用狀態並在應用程式內採取操作。它透過插件與應用程式前端和後端以及第三方服務進行通訊。 這就是整合聊天機器人的方法。 `CopilotKit`必須包裝與 CopilotKit 互動的所有元件。建議您也開始使用`CopilotSidebar` (您可以稍後切換到不同的 UI 提供者)。 ``` "use client"; import { CopilotKit } from "@copilotkit/react-core"; import { CopilotSidebar } from "@copilotkit/react-ui"; import "@copilotkit/react-ui/styles.css"; export default function RootLayout({children}) { return ( <CopilotKit url="/path_to_copilotkit_endpoint/see_below"> <CopilotSidebar> {children} </CopilotSidebar> </CopilotKit> ); } ``` 您可以使用此[快速入門指南](https://docs.copilotkit.ai/getting-started/quickstart-backend)設定 Copilot 後端端點。 之後,您可以讓 Copilot 採取行動。您可以閱讀如何提供[外部上下文](https://docs.copilotkit.ai/getting-started/quickstart-chatbot#provide-context)。您可以使用`useMakeCopilotReadable`和`useMakeCopilotDocumentReadable`反應掛鉤來執行此操作。 ``` "use client"; import { useMakeCopilotActionable } from '@copilotkit/react-core'; // Let the copilot take action on behalf of the user. useMakeCopilotActionable( { name: "setEmployeesAsSelected", // no spaces allowed in the function name description: "Set the given employees as 'selected'", argumentAnnotations: [ { name: "employeeIds", type: "array", items: { type: "string" } description: "The IDs of employees to set as selected", required: true } ], implementation: async (employeeIds) => setEmployeesAsSelected(employeeIds), }, [] ); ``` 您可以閱讀[文件](https://docs.copilotkit.ai/getting-started/quickstart-textarea)並查看[演示影片](https://github.com/CopilotKit/CopilotKit?tab=readme-ov-file#demo)。 您可以輕鬆整合 Vercel AI SDK、OpenAI API、Langchain 和其他 LLM 供應商。您可以按照本[指南](https://docs.copilotkit.ai/getting-started/quickstart-chatbot)將聊天機器人整合到您的應用程式中。 基本概念是在幾分鐘內建立可用於基於 LLM 的應用程式的 AI 聊天機器人。 用例是巨大的,作為開發人員,我們絕對應該在下一個專案中嘗試使用 CopilotKit。 CopilotKit 在 GitHub 上擁有超過 4,200 個星星,發布了 200 多個版本,這意味著它們正在不斷改進。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p8i6roafbjxvds26fl35.gif) {% cta https://github.com/CopilotKit/CopilotKit %} Star CopilotKit ⭐️ {% endcta %} --- ### 🎯 使用 CopilotKit 建立的熱門應用程式。 我們可以使用 CopilotKit 建立許多創新應用程式,所以讓我們探索一些脫穎而出的應用程式! ### ✅ [人工智慧驅動的部落格平台](https://dev.to/copilotkit/how-to-build-an-ai-powered-blogging-platform-nextjs-langchain-supabase-1hdp)。 ![部落格平台](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b89eub6whw7kxzbyw1dl.png) 您可以閱讀本文,使用`Next.js` 、 `Langchain` 、 `Supabase`和`CopilotKit`來建立這個令人驚嘆的應用程式。 LangChain &amp; Tavily 用於網路搜尋人工智慧代理,Supabase 用於儲存和檢索部落格平台文章資料,而 CopilotKit 用於將人工智慧整合到應用程式中。 您可以檢查[GitHub 儲存庫](https://github.com/TheGreatBonnie/aipoweredblog)。 ### ✅ [文字到 Powerpoint 應用程式](https://dev.to/copilotkit/how-to-build-ai-powered-powerpoint-app-nextjs-openai-copilotkit-ji2)。 您可以閱讀本文,使用`Next.js` 、 `OpenAI`和`CopilotKit`建立 Text to Powerpoint 應用程式。 您可以檢查[GitHub 儲存庫](https://github.com/TheGreatBonnie/aipoweredpresentation)。 ### ✅ [V0.dev 複製](https://dev.to/copilotkit/i-created-a-v0-clone-with-nextjs-gpt4-copilotkit-3cmb)。 ![v0](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pyutbegrv571lp3i6081.png) 如果您不熟悉,Vercel 的 V0 是一款人工智慧驅動的工具,可讓您根據提示產生 UI,以及許多其他有用的功能。 您可以使用`Next.js` 、 `GPT4`和`CopilotKit`建立 V0 的克隆。這篇文章名列前 7 名,總的來說,這是一個值得加入到您的作品集中的偉大專案。 您可以檢查[GitHub 儲存庫](https://github.com/Tabintel/v0-copilot-next)。 ### ✅[與您的履歷聊天](https://dev.to/copilotkit/how-to-build-the-with-nextjs-openai-1mhb)。 您可以閱讀本文,使用`Next.js` 、 `OpenAI`和`CopilotKit`來建立這個很棒的工具。 您不僅可以使用 ChatGPT 產生履歷,還可以將其匯出為 PDF,甚至可以透過與其對話來進一步改進它。多酷啊,對吧:) 您可以檢查[GitHub 儲存庫](https://github.com/TheGreatBonnie/AIPoweredResumeBuilder)。 --- 2. [Appwrite](https://github.com/appwrite/appwrite) - 減少後端的麻煩。 -------------------------------------------------------------- ![應用程式寫入](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8x568uz21seyygw6b72z.png) ![帶有 appwrite 的 sdk 列表](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cp7k8qnamsluto7eifpl.png) Appwrite 的開源平台可讓您將身份驗證、資料庫、函數和儲存體新增至您的產品中,並建立任何規模的任何應用程式、擁有您的資料並使用您喜歡的編碼語言和工具。 類似的選項是supabase,但儘管它們有相似之處,但它們在幾個方面有很大不同。 Restack 非常漂亮地涵蓋了[Appwrite 與 Supabase](https://www.restack.io/docs/supabase-knowledge-supabase-vs-appwrite) 。一探究竟! 他們有很好的貢獻指南,甚至不厭其煩地詳細解釋架構。 開始使用以下 npm 指令。 ``` npm install appwrite ``` 您可以像這樣建立一個登入元件。 ``` "use client"; import { useState } from "react"; import { account, ID } from "./appwrite"; const LoginPage = () => { const [loggedInUser, setLoggedInUser] = useState(null); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [name, setName] = useState(""); const login = async (email, password) => { const session = await account.createEmailSession(email, password); setLoggedInUser(await account.get()); }; const register = async () => { await account.create(ID.unique(), email, password, name); login(email, password); }; const logout = async () => { await account.deleteSession("current"); setLoggedInUser(null); }; if (loggedInUser) { return ( <div> <p>Logged in as {loggedInUser.name}</p> <button type="button" onClick={logout}> Logout </button> </div> ); } return ( <div> <p>Not logged in</p> <form> <input type="email" placeholder="Email" value={email} onChange={(e) => setEmail(e.target.value)} /> <input type="password" placeholder="Password" value={password} onChange={(e) => setPassword(e.target.value)} /> <input type="text" placeholder="Name" value={name} onChange={(e) => setName(e.target.value)} /> <button type="button" onClick={() => login(email, password)}> Login </button> <button type="button" onClick={register}> Register </button> </form> </div> ); }; export default LoginPage; ``` 您可以閱讀[文件](https://appwrite.io/docs)。 Appwrite 可以非常輕鬆地建立具有開箱即用的擴充功能的可擴展後端應用程式。 Appwrite 最近推出的「Init」發布了一些令人興奮的功能。對於我們可以用 init 做什麼,我並沒有達到 100% 的標準,所以請發表評論讓我們了解更多資訊。 它有一些很酷的功能,對於將我們的應用程式提升到一個新的水平非常有用。好奇心超載:D ![熱](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yflpzhvz7h0shs0dsrp8.png) 我很高興它可以連接到 Twilio、Vonage 和 Mailgun。更多選擇意味著更好的產品。 Appwrite 在 GitHub 上擁有 40k+ Stars,並且發布了`v1.5`版本。 {% cta https://github.com/appwrite/appwrite %} Star Appwrite ⭐️ {% endcta %} ### 🎯 使用 Appwrite 建立的熱門應用程式。 Appwrite 非常受歡迎,尤其是因為它的易用性。這些是一些很酷的專案,您可以從中獲得靈感。 ### ✅ [FoodMagic](https://github.com/Sameerkash/FoodMagic) - 擴增實境食品應用程式。 ![食物魔法](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/verpfy365uzrdyhopgdu.png) FoodMagic 是使用擴增實境和令人驚嘆的使用者介面的獨特食品配送服務。 它是使用`Appwrite`和 Flutter 建立的。 涉及 Appwrite 函數、資料庫、儲存和更多概念,因此您可以使用它學到很多東西。 您可以檢查[GitHub 儲存庫](https://github.com/TheGreatBonnie/aipoweredpresentation)。 ### ✅[回購評級員](https://github.com/EddieHubCommunity/RepoRater)。 此專案可讓您從開發者體驗 (DX) 的角度對 GitHub 儲存庫進行評分。 它是使用`Appwrite` 、 `Headless UI (React)` 、 `Next.js`和`Tailwind CSS`建立的。 您可以檢查[GitHub 儲存庫](https://github.com/TheGreatBonnie/aipoweredpresentation)並查看[即時執行情況](https://repo-rater.eddiehub.io/)。 ### ✅ [Twitter 克隆](https://www.youtube.com/watch?v=njLEDvoDjtk)- FreeCodeCamp (YouTube)。 它具有各種功能,例如使用電子郵件和密碼註冊和登入、發送文字、圖像和連結、辨識和儲存主題標籤、顯示推文、喜歡推文、轉發、評論/回應、關注用戶、搜尋用戶、顯示追蹤者、追蹤和最近的推文、編輯用戶個人資料、顯示帶有特定主題標籤的推文以及名為「Twitter Blue」的高級功能。 講師還實現了一個通知選項卡,當有人回覆您、追蹤您、喜歡您的推文或轉發時,該選項卡將顯示通知。在本教程結束時,您將擁有一個功能齊全的 Twitter 克隆,您可以對其進行進一步自訂和改進。意味著一切:) 他使用過`Flutter` 、 `Appwrite`和`Riverpod` ,並且教學超過 9 個小時,所以這是一個很長的教學。 ### ✅ [Dart 線上編譯器](https://github.com/aadarshadhakalg/Dart-Playground) ![飛鏢編譯器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pfazlnc0j33nrlybsngr.png) 一個應用程式,用戶可以編寫和執行小型 dart 程序,而無需在系統中安裝 dart SDK。該應用程式使用 Appwrite 函數來執行 dart 程式碼。 它是使用`Appwrite`和`Flutter`建構的。 這使用了 Appwrite Auth、函數和資料庫來進行工作。 您可以檢查[GitHub 儲存庫](https://github.com/aadarshadhakalg/Dart-Playground)。 --- 3.[重新發送](https://github.com/resend)- 為開發人員提供的電子郵件 API。 ------------------------------------------------------ ![重發](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x3auhh3hbxjmmzehe5v0.png) 您可以使用 React 建立和傳送電子郵件。 2023 年最受炒作的產品之一。 他們提供了大量的 SDK 選項,因此您不必從您首選的技術堆疊進行切換。 ![開發工具包](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1e8qmaxzk00t7etu4f0z.png) Resend 非常值得信賴,許多公司(例如 Payload 和 Dub)都使用它。您可以看到[客戶](https://resend.com/customers)清單。 開始使用以下 npm 指令。 ``` npm install @react-email/components -E ``` 這是將其與 next.js 專案整合的方法。 ``` import { EmailTemplate } from '@/components/email-template'; import { Resend } from 'resend'; const resend = new Resend(process.env.RESEND_API_KEY); export async function POST() { const { data, error } = await resend.emails.send({ from: '[email protected]', to: '[email protected]', subject: 'Hello world', react: EmailTemplate({ firstName: 'John' }), }); if (error) { return Response.json({ error }); } return Response.json(data); } ``` 您可以閱讀[文件](https://resend.com/docs/introduction)。 ![重發](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rer9ym187e4i9l11afkg.png) 如果您是教學人員,我推薦 YouTube 上的這個[播放清單系列](https://www.youtube.com/playlist?list=PL8HkCX2C5h0VVXsgSXtj2KXpoPATnMFeF),它涵蓋了大部分內容並且易於理解。 基本理念是一個簡單、優雅的介面,使您能夠在幾分鐘內開始發送電子郵件。它可以透過適用於您最喜歡的程式語言的 SDK 直接融入您的程式碼中。 出於顯而易見的原因,React email 在 GitHub 上擁有最高的星數(12k+),並且超過 5000 名開發人員在他們的應用程式中使用它。 {% cta https://github.com/resend %} 星標重新發送 ⭐️ {% endcta %} ### 🎯 使用重新發送發送電子郵件的熱門應用程式。 讓我們看看一些使用重新發送來發送電子郵件的應用程式。 ### ✅ [gitroom](https://github.com/gitroomhq/gitroom) 。 提前安排所有社群媒體貼文和文章。您也可以與其他團隊成員合作交換或購買貼文。 它是使用`NX (Monorepo)` 、 `NextJS (React)` 、 `NestJS` 、 `Prisma (Default to PostgreSQL)` 、 `Redis`和`Resend`建構的。 您可以檢查[GitHub 儲存庫](https://github.com/gitroomhq/gitroom)和[網站](https://gitroom.com/)。 Gitroom 在 GitHub 上有 3k+ Stars。 ### ✅[任何郵件](https://github.com/anymail/django-anymail)。 Anymail 可讓您使用您選擇的交易電子郵件服務提供者 (ESP) 在 Django 中傳送和接收電子郵件。 您可以檢查[GitHub 儲存庫](https://github.com/anymail/django-anymail)和[網站](https://anymail.dev/en/stable/)。他們在 GitHub 上有超過 1,500 個 Stars,並且正在發布 v10 版本。 ### ✅[徽章](https://github.com/projectx-codehagen/Badget)。 ![徽章](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xmfd2wzpfj0c0qmxkt22.png) Badget 旨在透過使用者友善的介面和強大的後端來簡化財務管理。 它是使用`Next.js 14` 、 `Turborepo` 、 `Drizzle ORM` 、 `Planetscale` 、 `Clerk` 、 `Resend` 、 `React Email` 、 `Shadcn/ui`和`Stripe`建置的。 您可以檢查[GitHub 儲存庫](https://github.com/projectx-codehagen/Badget)。 這個專案很快就會在 GitHub 上達到 2k Stars。 --- 4. [Shadcn UI](https://ui.shadcn.com/docs) - 您可以將其複製並貼上到應用程式中的元件。 ----------------------------------------------------------------- ![shadcn使用者介面](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0xhp1p50dd3b51weao3b.png) 這個開源專案無需介紹。 由於其簡單性、自訂選項和靈活性,它一推出就受到了熱烈歡迎。 然而,我確實同意它並不像看起來那麼簡單,特別是如果您不熟悉它的語法和結構。 開始使用以下命令(Next.js 應用程式)。 ``` npx shadcn-ui@latest init ``` 其餘的將自動完成,您可以匯入[元件](https://ui.shadcn.com/docs/components/accordion)並相應地使用它們。 您可以根據您使用的框架閱讀[文件](https://ui.shadcn.com/docs)和[安裝指南](https://ui.shadcn.com/docs/installation)。 Shadcn UI 在 GitHub 上擁有超過 55,000 顆星,並被超過 3,000 名開發者使用。 {% cta https://ui.shadcn.com/docs %} Star Shadcn UI ⭐️ {% endcta %} ### 🎯 使用 Shadcn UI 建立的熱門應用程式。 我不會介紹非常簡單的專案,所以不用擔心。 ### ✅ [10000+ shadcn/ui 主題](https://github.com/jln13x/ui.jln.dev/)。 ![10000+ 主題](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ywbrkhizpjqogtrk7svm.png) 有了這個,您可以探索、保存、產生新主題,甚至對隨機主題進行投票。您可以使用的好專案之一。 使用者介面也很糟糕。 它是使用很多套件建構的,例如`react-query` 、 `Framer` 、 `Zod` ,當然還有`shadcn ui` 。 您可以查看[GitHub 儲存庫](https://github.com/jln13x/ui.jln.dev/)和[現場演示](https://ui.jln.dev/)。 它在 GitHub 上有 600 多個 Star。 ### ✅[開啟 v0](https://github.com/raidendotai/openv0) 。 ![開放v0](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rubuowp2oerrexy9adp1.png) 我正在報道 v0.dev 但意識到它不是開源的。 我不會放棄這個想法。 Openv0 是另一個使用 AI 產生 UI 元件的專案。元件產生是一個多通道管道 - 每個通道都是一個完全獨立的插件。 它支援 React、Next.js 和 Svelte 等前端框架。使用 Flowbite、NextUI 和 Shadcn 建置。 檢查[GitHub 儲存庫](https://github.com/raidendotai/openv0)並閱讀[安裝指南](https://github.com/raidendotai/openv0?tab=readme-ov-file#install)。 您也可以在[Replit](https://replit.com/@n-raidenai/openv0-react)上執行它。它在 GitHub 上有 3k+ Stars。 很多專案都使用Shadcn,請自行探索。 --- 5. [Buildship](https://buildship.com/) - 低程式碼視覺化後端建構器。 ------------------------------------------------------ ![建造船](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rzlrynz5xephv4t9layd.png) 對於您正在使用無程式碼應用程式建構器(FlutterFlow、Webflow、Framer、Adalo、Bubble、BravoStudio...)或前端框架(Next.js、React、Vue...)建立的應用程式,您需要一個後端來支援可擴展的 API、安全工作流程、自動化等。 BuildShip 為您提供了一種完全視覺化的方式,可以在易於使用的完全託管體驗中可擴展地建立這些後端任務。 這意味著您無需在雲端平台上爭論或部署事物或執行 DevOps。只需立即建造和發貨 🚀 他們甚至與 TypeSense 合作並且發展得非常快! ![建造船](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6oc3rc713mjg9cwqj7d4.png) 我嘗試過Buildship,它很強大。 {% cta https://github.com/rowyio/buildship %} 明星建造 ⭐️ {% endcta %} ### 🎯 使用 Buildship 建立的熱門應用程式。 大多數資源都是影片,但值得一看。 YouTube 官方頻道上有很多教程,但以下是一些有趣的教程。 ### ✅[使用低程式碼和 AI 建立旅遊 WebApp](https://www.youtube.com/watch?v=Pj08uTOzNPQ) 。 ![旅行應用程式](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8c179msfljpnesbrf4vi.png) 它是使用`Buildship`和`Locofy`建構的。 Locofy.ai 用於從設計到應用程式前端的過渡,而 BuildShip.com 用於應用程式的後端。 它還計算實時距離和旅程成本。他們使用 Figma 來源進行設計。 ### ✅ [Telegram 上的人工智慧助理](https://www.youtube.com/watch?v=Pz1t1KCnrbs)。 您可以使用 OpenAI Assistant 和 BuildShip 建立智慧型 Telegram 機器人,而無需編碼。這將幫助您與資料聊天。看起來很令人興奮,對吧:) ### ✅ [AI YouTube 時間戳產生器](https://www.youtube.com/watch?v=7DkLUY6kfTg)。 ![時間戳生成器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b2wv0s9mz9wpuez4egee.png) 相信我,使用本教程您會學到很多東西。您可以查看開發人員上[未發布的有關自訂提示的帖子](https://dev.to/jamesmurdza/building-a-fcg-temp-slug-4578922?preview=4210cdff8fea25a8cd4d81363155c451b20e6484504a41fa0f0d992a272c21a3a707c0cb6ddac2f740234c032a02af5ce442841ad4033efc46424c84)。 您可以檢查[前端程式碼](https://github.com/jamesmurdza/timestamp-generator-app/)。 --- 6. [Taipy](https://github.com/Avaiga/taipy) - 將資料和人工智慧演算法整合到生產就緒的 Web 應用程式中。 ---------------------------------------------------------------------------- ![打字](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/deak7rre409rzv5j5viv.png) Taipy 是一個開源 Python 庫,可用於輕鬆的端到端應用程式開發,具有假設分析、智慧管道執行、內建調度和部署工具。 我相信你們大多數人都不明白 Taipy 用於為基於 Python 的應用程式建立 GUI 介面並改進資料流管理。 因此,您可以繪製資料集的圖表,並使用類似 GUI 的滑桿來提供使用其他實用功能來處理資料的選項。 雖然 Streamlit 是一種流行的工具,但在處理大型資料集時,其效能可能會顯著下降,這使得它在生產級使用上不切實際。 另一方面,Taipy 在不犧牲性能的情況下提供了簡單性和易用性。透過嘗試 Taipy,您將親身體驗其用戶友好的介面和高效的資料處理。 在底層,Taipy 利用各種函式庫來簡化開發並增強功能。 ![圖書館](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n9xts3nof4uapr7dakrl.png) 開始使用以下命令。 ``` pip install taipy ``` 他們還使用分散式運算提高了效能,但最好的部分是 Taipy,它的所有依賴項現在都與 Python 3.12 完全相容,因此您可以在使用 Taipy 進行專案的同時使用最新的工具和程式庫。 您可以閱讀[文件](https://docs.taipy.io/en/latest/)。 另一個有用的事情是,Taipy 團隊提供了一個名為[Taipy Studio](https://docs.taipy.io/en/latest/manuals/studio/)的 VSCode 擴充功能來加速 Taipy 應用程式的建置。 ![太皮工作室](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kc1umm5hcxes0ydbuspb.png) 如果您想閱讀部落格來了解程式碼庫結構,您可以閱讀 HuggingFace[的使用 Taipy 在 Python 中為您的 LLM 建立 Web 介面](https://huggingface.co/blog/Alex1337/create-a-web-interface-for-your-llm-in-python)。 Taipy 在 GitHub 上有 8k+ Stars,並且處於`v3`版本,因此它們正在不斷改進。 {% cta https://github.com/Avaiga/taipy %} Star Taipy ⭐️ {% endcta %} ### 🎯 使用 Taipy 建立的熱門應用程式。 嘗試新技術通常很困難,但 Taipy 提供了 10 多個演示教程,其中包含程式碼和適當的文件供您遵循。我們將看到開發人員建構的其他一些專案。 ### ✅[錢包方面](https://github.com/Ujj1225/from_Taipy-walletWISE)。 ![錢包明智](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vva4tu9dxrz9fgaiavlb.png) WalletWise 就像是我們財務的友善幫手,幫助我們追蹤收入和支出。它使用 Gemini 進行交易,使用 Taipy 來了解支出。 對使用者的收入和支出進行分析,以數學方式顯示,並顯示 7 個做出更好、更明智的財務決策的提示。 它還具有視覺化工具,您可以在其中查看不同的標題,以了解有關您的支出的更多資訊。 就創造力而言,這是下面提到的所有內容中最好的。 ### ✅[人口普查](https://github.com/SusheelThapa/from_taipy_census)。 透過由 Taipy 提供支持的「人口普查」專案,將資料編織到動態視覺化中,揭開 2021 年尼泊爾的住房和人口故事。 這有很多選擇,所以如果您想用更少的錢學到更多,這是最好的選擇! ### ✅[太皮象棋](https://github.com/KorieDrakeChaney/taipy-chess)。 ![棋](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xasxqldf7z1q5ie3r4nn.png) 所有應用程式中我最喜歡的一個,因為我喜歡國際象棋。哈哈! 這是一個基於20,000盤棋的國際象棋視覺化工具。您可以查看所有比賽、他們參加的開局、對手、表現最好的開局以及最成功的開局。您可以查看資料的熱圖和圖表。 您還可以查看[Olympic Medals Taipy 應用程式](https://github.com/enarroied/Olympic-Medals-Taipy-App),該應用程式提供了一個儀表板,其中包含有關奧運獎牌、 [Covid 儀表板](https://covid-dashboard.taipy.cloud/Country)和[資料視覺化的](https://production-planning.taipy.cloud/Data-Visualization)訊息。 --- 7. [xyflow](https://github.com/xyflow/xyflow) - 使用 React 建立基於節點的 UI。 -------------------------------------------------------------------- ![XY流](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yevpzvqpt3u6ahkqdrsl.png) XYFlow 是一個強大的開源程式庫,用於使用 React 或 Svelte 建立基於節點的 UI。它是一個單一的倉庫,提供[React Flow](https://reactflow.dev)和[Svelte Flow](https://svelteflow.dev) 。讓我們更多地了解可以使用 React flow 做什麼。 ![反應流](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8mzezlna4v4bx75z3omr.png) 您可以觀看此影片,在 60 秒內了解 React Flow。 {% 嵌入 https://www.youtube.com/watch?v=aUBWE41a900 %} 有些功能在專業模式下可用,但免費層中的功能足以形成一個非常互動的流程。 React 流程以 TypeScript 編寫並使用 Cypress 進行測試。 開始使用以下 npm 指令。 ``` npm install reactflow ``` 以下介紹如何建立兩個節點( `Hello`和`World` ,並透過邊連接。節點具有預先定義的初始位置以防止重疊,並且我們還應用樣式來確保有足夠的空間來渲染圖形。 ``` import ReactFlow, { Controls, Background } from 'reactflow'; import 'reactflow/dist/style.css'; const edges = [{ id: '1-2', source: '1', target: '2' }]; const nodes = [ { id: '1', data: { label: 'Hello' }, position: { x: 0, y: 0 }, type: 'input', }, { id: '2', data: { label: 'World' }, position: { x: 100, y: 100 }, }, ]; function Flow() { return ( <div style={{ height: '100%' }}> <ReactFlow nodes={nodes} edges={edges}> <Background /> <Controls /> </ReactFlow> </div> ); } export default Flow; ``` 這就是它的樣子。您還可以新增標籤、更改類型並使其具有互動性。 ![你好世界](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xzerdd3ng0vtnz5rbgau.png) 您可以在 React Flow 的 API 參考中查看[完整的選項清單](https://reactflow.dev/api-reference/react-flow)以及元件、鉤子和實用程式。 最好的部分是您還可以加入[自訂節點](https://reactflow.dev/learn/customization/custom-nodes)。在您的自訂節點中,您可以渲染您想要的一切。您可以定義多個來源和目標句柄並呈現表單輸入或圖表。您可以查看此[codesandbox](https://codesandbox.io/p/sandbox/pensive-field-z4kv3w?file=%2FApp.js&utm_medium=sandpack)作為範例。 您可以閱讀[文件](https://reactflow.dev/learn)並查看 Create React App、Next.js 和 Remix 的[範例 React Flow 應用程式](https://github.com/xyflow/react-flow-example-apps)。 React Flow 附帶了幾個額外的[插件](https://reactflow.dev/learn/concepts/plugin-components)元件,可以幫助您使用 Background、Minimap、Controls、Panel、NodeToolbar 和 NodeResizer 元件製作更高級的應用程式。 例如,您可能已經注意到許多網站的背景中有圓點,增強了美觀性。要實現此模式,您可以簡單地使用 React Flow 中的後台元件。 ``` import { Background } from 'reactflow'; <Background color="#ccc" variant={'dots'} /> // this will be under React Flow component. Just an example. ``` ![背景元件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/en2tl17ef31nydaycw18.png) 如果您正在尋找一篇快速文章,我建議您查看 Webkid 的[React Flow - A Library for Rendering Interactive Graphs](https://webkid.io/blog/react-flow-node-based-graph-library/) 。 React Flow 由 Webkid 開發和維護。 它在 GitHub 上有超過 19k 顆星星,並且在`v11.10.4`上顯示它們正在不斷改進,npm 套件每週下載量超過 40 萬次。您可以輕鬆使用的最佳專案之一。 ![統計資料](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o99csz9epqmai3ixt859.png) {% cta https://github.com/xyflow/xyflow %} 星 xyflow ⭐️ {% endcta %} ### 🎯 使用 React Flow 建立的熱門應用程式。 很多公司都使用 React flow,例如 Zapier 和 Stripe。夠可信,可以使用。我不會介紹使用 Svelte Flow 製作的應用程式,因為 React 更受歡迎。 ### ✅[條紋文件](https://docs.stripe.com/payments/checkout/how-checkout-works#lifecycle)。 ![條紋](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/crma9z46y0u2m5p3z9wa.png) Stripe 使用它,特別是在展示結帳的工作原理時。 您可以閱讀[完整的文件](https://stripe.com/docs)。 ### ✅[著色蛙](https://shaderfrog.com/2/editor/cln84z4950000pan66v5fcunv)。 ![著色蛙](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4ri9aw9vynoiflkbvclq.png) 我選擇這個是因為這個專案很酷。 ### ✅ [類型](https://www.typeform.com/help/a/use-the-logic-map-to-add-logic-to-your-forms-5514792640916/)。 ![打字機](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/48gc4m8ewm4j65luuavs.png) Typeform 使用它來展示如何使用邏輯圖為表單新增邏輯。 您也可以發現它被用於[FlowwiseAI](https://flowiseai.com/)和[Doubleloop](https://app.doubleloop.app/strategy/2236/map) 。想讓您知道,Supabase 是 GitHub 上 XYflow 的贊助商之一。 --- 8. [Pieces](https://github.com/pieces-app) - 您的工作流程副駕駛。 ------------------------------------------------------- ![件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qf2qgqtpv78fxw5guqm5.png) Pieces 是一款支援人工智慧的生產力工具,旨在透過智慧程式碼片段管理、情境化副駕駛互動和主動呈現有用材料來幫助開發人員管理混亂的工作流程。 它最大限度地減少了上下文切換、簡化了工作流程並提升了整體開發體驗,同時透過完全離線的 AI 方法維護了工作的隱私和安全性。太棒了:D ![整合](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f2ro3rcwnqp4qrmv5e8s.png) 它與您最喜歡的工具無縫集成,以簡化、理解和提升您的編碼流程。 它具有比表面上看到的更令人興奮的功能。 - 它可以透過閃電般快速的搜尋體驗找到您需要的材料,讓您根據您的喜好透過自然語言、程式碼、標籤和其他語義進行查詢。可以放心地說“您的個人離線谷歌”。 - Pieces 使用 OCR 和 Edge-ML 升級螢幕截圖,以提取程式碼並修復無效字元。因此,您可以獲得極其準確的程式碼提取和深度元資料豐富。 您可以查看 Pieces 可用[功能的完整清單](https://pieces.app/features)。 您可以閱讀[文件](https://docs.pieces.app/)並存取[網站](https://pieces.app/)。 他們為 Pieces OS 用戶端提供了一系列 SDK 選項,包括[TypeScript](https://github.com/pieces-app/pieces-os-client-sdk-for-typescript) 、 [Kotlin](https://github.com/pieces-app/pieces-os-client-sdk-for-kotlin) 、 [Python](https://github.com/pieces-app/pieces-os-client-sdk-for-python)和[Dart](https://github.com/pieces-app/pieces-os-client-sdk-for-dart) 。 {% cta https://github.com/pieces-app/ %} 星星碎片 ⭐️ {% endcta %} ### 🎯 用 Pieces 建置的熱門應用程式。 由於它更像是一個工具,因此不會有那麼多專案,但開發人員仍然使用它來建立很棒的專案。 ### ✅[辦公桌夥伴](https://github.com/ayothekingg/deskbuddy)。 一個社區專案,可透過分析和 Copilot Conversation 幫助您了解、評估和改善您的編碼習慣。 使用的主要語言是 TypeScript。 您可以檢查[GitHub 儲存庫](https://github.com/ayothekingg/deskbuddy)。 ### ✅ [CLI 代理](https://github.com/pieces-app/cli-agent)。 一個全面的命令列介面 (CLI) 工具,旨在與 Pieces OS 無縫互動。它提供了一系列功能,例如資產管理、應用程式互動以及與各種 Pieces OS 功能的整合。 使用的主要語言是Python。 您可以檢查[GitHub 儲存庫](https://github.com/pieces-app/cli-agent)。 ### ✅ [Streamlit 和碎片](https://github.com/pieces-app/pieces-copilot-streamlit-example)。 Pieces Copilot Streamlit Bot 是一款使用 Streamlit 建立的互動式聊天機器人應用程式,旨在為用戶提供無縫介面來即時提問和接收答案。 使用的主要語言是Python。 您可以檢查[GitHub 儲存庫](https://github.com/pieces-app/pieces-copilot-streamlit-example)。 --- 9. [Typesense](https://github.com/typesense/typesense) - 快速、容錯、記憶體中模糊搜尋引擎。 -------------------------------------------------------------------------- ![類型感](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4uc2r5owew7bkeckc81n.png) Typesense 是一款開源、容錯的搜尋引擎,針對即時(通常低於 50 毫秒)的即輸入即搜尋體驗和開發人員工作效率進行了最佳化。 如果您聽說過 ElasticSearch 或 Algolia,那麼考慮 Typesense 的一個好方法是,它是 Algolia 的開源替代品,解決了一些關鍵問題,並且是 ElasticSearch 的更易於使用、包含電池的替代品。 您可以在[Algolia vs ElasticSearch vs Meilsearch vs Typesense](https://typesense.org/typesense-vs-algolia-vs-elasticsearch-vs-meilisearch/)中對它們進行比較。 它是一個快速、容錯、內存中模糊搜尋引擎,用於建置令人愉快的搜尋體驗 ![特徵](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dj1dov237eyg662vqw6y.png) 您可以使用此指令安裝 Typesense 的 python 用戶端。 ``` pip install typesense ``` 根據文件,在這些情況下不應使用 Typesense。 A。 Typesense 不應用作主資料存儲,它存儲資料的唯一副本。 b. Typesense 通常不太適合搜尋應用程式日誌。 您可以閱讀[文件](https://typesense.org/docs/)和[安裝指南](https://github.com/typesense/typesense?tab=readme-ov-file#install)。 ![類型感](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bwf0c9jgjrju1xtrwfqv.png) 我建議您閱讀快速入門[指南](https://typesense.org/docs/guide/#quick-start),該指南將逐步指導您如何安裝和建立搜尋 UI。他們還提供了高達 28M 的資料集的明確[基準測試](https://typesense.org/docs/overview/benchmarks.html#typesense-benchmarks),以便您可以檢查將獲得的效能。 如果您更喜歡教程,那麼我建議您觀看這個[YouTube 影片](https://www.youtube.com/watch?v=kwtHOkf7Jdg)。您將獲得 Typesense 的概述,作者將向您展示端到端演示。 TypeSense 在 GitHub 上有 17k+ Stars,而且版本為 26,這真是太瘋狂了。它是使用 C++ 建構的。 {% cta https://github.com/typesense/typesense?tab=readme-ov-file %} 明星 Typesense ⭐️ {% endcta %} ### 🎯 使用 Typesense 建立的熱門應用程式。 一些使用 Typesense 的現場演示和應用程式。 ### ✅ 現場示範。 他們還提供現場演示,展示 Typesense 在大型資料集上的實際應用,例如: - [從 Linux 核心搜尋 1M Git 提交訊息](linux-commits-search.typesense.org)- [GitHub Repo](https://github.com/typesense/showcase-linux-commits-search) - [從 MusicBrainz 搜尋 3200 萬首歌曲資料集](songs-search.typesense.org)- [GitHub Repo](https://github.com/typesense/showcase-songs-search) - [具有預先輸入功能的拼字檢查器,包含 333K 英文單字](spellcheck.typesense.org)- [GitHub Repo](https://github.com/typesense/showcase-spellcheck) - [從 OpenLibrary 搜尋 28M 圖書資料集](books-search.typesense.org)- [GitHub Repo](https://github.com/typesense/showcase-books-search) - [GeoSearch / 瀏覽體驗](airbnb-geosearch.typesense.org)- [GitHub Repo](https://github.com/typesense/showcase-airbnb-geosearch) - [電子商務瀏覽與搜尋體驗](https://ecommerce-store.typesense.org/)- [GitHub Repo](https://github.com/typesense/showcase-ecommerce-store) - [搜尋 2M 烹飪食譜](https://recipe-search.typesense.org/)- [GitHub Repo](https://github.com/typesense/showcase-recipe-search) 其他一些公司使用 Typesense 雲端來完成整個工作。 ![類型感知雲](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0kn37bf908emr04ahilo.png) 這些公司包括 Codecademy、Logitech、Buildship、n8n 和 Storipress CMS。 --- 10. [Payload](https://github.com/payloadcms/payload) - 建立未來網路的最快方式。 ------------------------------------------------------------------- ![有效負載](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h79j0zte5eo7n32639jy.png) 建立現代後端 + 管理 UI 的最佳方式。 Payload 沒有黑魔法,全是 TypeScript,並且完全開源,它既是一個應用程式框架,也是一個無頭 CMS。我全心全意欽佩的少數專案之一。 他們的網站擁有最乾淨的使用者介面之一,我看過 1000 多個網站,其中包括非常瘋狂的網站。快去看看吧! ![有效負載客戶](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6ep8brjas1iaptifw97e.png) 您可以觀看這段 YouTube 影片,其中 James(聯合創始人)談論了 Payload CMS 簡介以及它如何縮小 Headless CMS 和應用程式框架之間的差距。 {% 嵌入 https://www.youtube.com/watch?v=In\_lFhzmbME %} 簡而言之,Payload 是一個無頭 CMS 和應用程式框架。它旨在為您的開發過程提供巨大的推動力,但重要的是,當您的應用程式變得更加複雜時,請不要妨礙您。 開始使用以下命令。 ``` npx create-payload-app@latest ``` 您可以閱讀 Payload 與普通 CMS 不同的完整[功能清單](https://github.com/payloadcms/payload?tab=readme-ov-file#-features)。 如果您是 next.js 的粉絲,我建議您閱讀[The Ultimate Guide To Use Next.js with Payload](https://payloadcms.com/blog/the-ultimate-guide-to-using-nextjs-with-payload) 。 您可以閱讀[文件](https://payloadcms.com/docs)和[安裝指南](https://payloadcms.com/docs/getting-started/installation)。 v3 beta 版本的有效負載也變得很困難,所以請密切注意。 Payload 在 GitHub 上擁有 19k+ Stars,並被 8k+ 開發者使用。 {% cta https://github.com/payloadcms/payload %} 明星有效負載 ⭐️ {% endcta %} ### 🎯 使用 Payload 的熱門應用程式 + 模板。 我們將看到可協助您將 Payload 用於特定用例的範本和應用程式。 ### ✅[混音和有效負載](https://github.com/payloadcms/remix-server) 帶有 Remix 和 Payload 的單聲道儲存庫範本。 這可以幫助您設定 Payload CMS 與 Remix 一起進行內容管理,從而將每個應用程式分為其套件(包括 Express 伺服器應用程式)。 ### ✅ [Astro 和有效負載](https://github.com/mooxl/astroad) 這是 Astro 和 Payloadcms 的預先配置設置,旨在讓您輕鬆開始建立網站。借助 Astroad,您將擁有一個可以使用 Docker 在本地執行的完整開發環境。此設定簡化了將網站部署到生產環境之前的測試和開發。 ### ✅[電子商務範本](https://github.com/payloadcms/payload/tree/main/templates/ecommerce)。 他們還提供了一個電子商務模板,可幫助您更專注於業務策略而不是技術。您的 API 是您自己的,您的資料也屬於您。您無需依賴第三方服務,這些服務可能會在每月費用之外向您收取 API 超額費用,並可能限制您對資料庫的存取。經營線上商店的成本永遠不會超過伺服器的成本(加上支付處理費)。 開始做一些我們不喜歡的事情總是感覺很奇怪,因此您可以閱讀[如何使用使用此範本的 Next.js 建立電子商務網站](https://payloadcms.com/blog/how-to-build-an-e-commerce-site-with-nextjs)。 使用 Payload 的一些流行公司包括[Speechify](https://speechify.com/) 、 [Bizee](https://bizee.com/)等。 閱讀以下案例研究。他們將告訴您 Payload 的功能以及它如何奠定堅實的基礎。 ### ✅[快速犁](https://miquikplow.com/) ![快犁](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j4k2rlwzf1u3vnfe1yxr.png) Quikplow 是一個創新的隨選服務平台,通常被稱為「掃雪機的 Uber」。 Quikplow 為其應用程式開發和部署功能齊全的後端的速度不僅是無與倫比的,而且幾乎是聞所未聞的。整個應用程式涵蓋身份驗證、基於位置的搜尋、電子商務功能等,開發時間不到 120 天。 前所未有的速度歸功於 Payload 的身份驗證、CRUD 操作和管理面板生成功能,為 Quikplow 節省了寶貴的開發時間和預算資源。 ### ✅[紙三角形](https://www.papertriangles.com/) ![紙三角形](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/73t78tva710qj5owgos1.png) Paper Triangles 需要在線展示,以反映其著名的沉浸式體驗,但發現自己受到過時且緩慢的內容管理系統的限制。 與他們的代理商合作夥伴 Old Friends 合作,面臨的挑戰是建立一個能夠反映他們尖端工作的網站 - 需要自動播放影片、動態動畫、整合式相機庫等,而不犧牲內容更新的速度或便利性。 有效負載成為完美的選擇。它的開源特性以及 TypeScript 和 React 的強大基礎使其成為開發高度客製化的互動式前端的理想選擇。 對於像 Old Friends 這樣的代理商來說,Payload 是向 Paper Triangles 這樣的客戶兌現承諾的最佳選擇。 「Payload 為我們的客戶提供了易於使用的介面,並為我們提供了執行客製化設計所需的開發自由度,」Old Friends 的設計工程師 James Clements 說。 ### ✅[比茲](https://bizee.com/) ![比西](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1mai4bkcu4vdi3138gqm.png) 他們需要在短短三個月內遷移和檢修 2,500 個頁面,同時重新建立新的 CMS 平台,並在全面品牌重塑下實施全面的網站重新設計。 為了兌現對 Bizee 的承諾,Ritters(代理商)依靠 Payload 乾淨的、TypeScript 驅動的架構,事實證明該架構具有變革性,簡化了設計整合並確保了無錯誤、可維護的程式碼。這加速了內容遷移並保留了 SEO 和用戶體驗。 它甚至促進了從設計到開發的過程,幫助 Riotters 將 Figma 概念轉化為實際實施。 至關重要的是,Payload 與 Next.js 的天然協同作用促進了開發人員、設計師、UX 專業人員、QA 團隊和行銷人員之間的跨職能協作。 有許多公司決定使用 Payload,這是他們做出的最佳決定之一。不管怎樣,去探索你能用它做什麼。 --- 哇! 這花了我很長很長的時間來寫。我希望你喜歡它。 我得到它! 建立良好的長期副專案可能很困難,但即使是一個簡單的用例也可以帶來顯著的成果。誰知道?從長遠來看,您甚至可能會獲得對您有幫助的直接機會。 我試圖涵蓋每個專案製作的最好和最有用的應用程式。 不管怎樣,請讓我們知道您的想法以及您計劃在未來建立任何可擴展的副專案嗎? 祝你有美好的一天!直到下一次。 請在 Twitter 上關注我,我將非常感激。 |如果你喜歡這類東西, 請關注我以了解更多:) | [![用戶名 Anmol_Codes 的 Twitter 個人資料](https://img.shields.io/badge/Twitter-d5d5d5?style=for-the-badge&logo=x&logoColor=0A0209)](https://twitter.com/Anmol_Codes) [![用戶名 Anmol-Baranwal 的 GitHub 個人資料](https://img.shields.io/badge/github-181717?style=for-the-badge&logo=github&logoColor=white)](https://github.com/Anmol-Baranwal) [![用戶名 Anmol-Baranwal 的 LinkedIn 個人資料](https://img.shields.io/badge/LinkedIn-0A66C2?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/Anmol-Baranwal/) | |------------|----------| 請關注 CopilotKit 以了解更多此類內容。 {% 嵌入 https://dev.to/copilotkit %} --- 原文出處:https://dev.to/copilotkit/30-app-ideas-with-complete-source-code-5f76

面試時必須了解的 10 個系統設計概念

*揭露:這篇文章包含附屬連結;如果您透過本文中提供的不同連結購買產品或服務,我可能會獲得補償。* [![面試時必須了解的 10 個系統設計概念](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kfxdldzd09fwws7nve36.png)](https://bit.ly/3cNF0vw) image\_credit -[指數](https://bit.ly/3cNF0vw) 您好,作為開發人員,充分理解基本系統設計概念對於開發可擴展、可靠和高效能的軟體系統至關重要。 [**系統設計**](https://medium.com/javarevisited/7-system-design-problems-to-crack-software-engineering-interviews-in-2023-13a518467c3e)涉及設計軟體系統的體系結構和元件,以滿足特定要求並實現所需的性能特徵。 隨著技術的快速進步和軟體應用的複雜性不斷增加,掌握系統設計概念對於程式設計師建立高效且有效的系統至關重要。 在上幾篇文章中,我回答了流行的系統設計問題,例如[API 網關與負載平衡器](https://dev.to/somadevtoo/difference-between-api-gateway-and-load-balancer-in-system-design-54dd)以及[水平與垂直擴展](https://dev.to/somadevtoo/horizontal-scaling-vs-vertical-scaling-in-system-design-3n09),今天,我們將看看每個程式設計師都應該學習的 10 個關鍵系統設計概念。 這些概念為設計能夠處理大規模資料、容納並髮用戶並提供最佳效能的軟體系統奠定了堅實的基礎。 無論您是初學者還是經驗豐富的開發人員,了解這些系統設計概念都將使您能夠建立強大且可擴展的軟體系統,以滿足現代應用程式的需求。那麼,讓我們深入探討這些基本的系統設計原則吧! 順便說一句,如果您正在準備系統設計面試並想深入學習系統設計,那麼您還可以查看[**ByteByteGo**](https://bit.ly/3P3eqMN) 、 [**Design Guru**](https://bit.ly/3pMiO8g) 、 [**Exponent**](https://bit.ly/3cNF0vw) 、 [**Educative**](https://bit.ly/3Mnh6UR)和[**Udemy**](https://bit.ly/3vFNPid)等網站,它們有許多很棒的系統設計課程 以下是每個程式設計師都應該考慮學習的 10 個重要的系統設計概念: 1. **可擴展性** 2. **可用性** 3. **可靠性** 4. **容錯能力** 5. **快取策略** 6. **負載平衡** 7. **安全** 8. **可擴展的資料管理** 9. **設計模式** 10. **效能最佳化** 理解和應用這些系統設計概念可以幫助程式設計師和開發人員建立強大的、可擴展的、高效能的軟體系統,以滿足現代應用程式和使用者的需求。 現在,讓我們深入研究它們中的每一個並了解它們是什麼以及如何在您的應用程式中實現它們。 ### 1. 可擴展性 可擴展性是指系統或應用程式處理不斷增加的工作負載或使用者而不顯著降低效能或功能的能力。 它是系統設計中的一個重要概念,因為它允許系統成長並適應不斷變化的需求,**例如增加的資料量、使用者流量或處理需求,**而不會遇到效能瓶頸或限制。 在現代運算環境中,系統需要處理大量且不斷成長的資料和用戶,可擴展性至關重要。例如,流行的網站、行動應用程式和基於雲端的服務需要能夠同時處理數百萬甚至數十億個請求,而分散式資料庫和大資料平台需要擴展以處理 PB 或 EB 的資料。 對於需要適應尖峰負載的系統來說,可擴展性也很重要,例如假期期間的線上購物或因病毒事件導致的用戶活動突然激增。 > 可擴展性主要有兩種:**垂直可擴展性和水平可擴展性**。垂直可擴展性涉及向單一伺服器或節點加入更多資源(例如 CPU、記憶體或儲存)以處理增加的工作負載。另一方面,水平可擴展性涉及向系統加入更多伺服器或節點以分配工作負載並處理增加的需求。 水平可擴展性通常透過[負載平衡](https://medium.com/javarevisited/difference-between-api-gateway-and-load-balancer-in-microservices-8c8b552a024)、 [分片](https://medium.com/javarevisited/what-is-database-sharding-scaling-your-data-horizontally-1dc12b33193f)、分區和分散式處理等技術來實現。 實現可擴展性需要仔細的系統設計、架構和實作。它涉及設計能夠有效處理不斷增加的工作負載、有效利用資源、最大限度地減少依賴性以及跨多個節點或伺服器分佈處理的系統。 > 快取、非同步處理、平行處理和分散式資料庫等技術通常用於提高可擴展性。測試和效能監控對於確保系統在擴展時繼續保持良好效能也至關重要。 可擴展性是建立強大的高效能係統的重要考慮因素,這些系統可以處理成長並適應隨時間變化的需求。它使系統能夠滿足不斷增長的需求,提供無縫的用戶體驗,並支援業務成長,而不會遇到效能限製或停機。 這是來自[**ByteByteGo**](https://bit.ly/3P3eqMN)的一個很好的圖表,這是準備系統設計面試的好地方,它顯示了[*垂直擴展和水平擴展之間的區別*](https://medium.com/javarevisited/difference-between-horizontal-scalability-vs-vertical-scalability-67455efc91c) [![水平縮放與垂直縮放](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xd4vz64i6vywjpopepku.png)](https://bit.ly/3P3eqMN) --- ### 2. 可用性 可用性是指軟體系統即使在發生故障或中斷時也能保持運作並可供使用者存取的能力。 高可用性是許多系統的關鍵要求,特別是那些任務關鍵型或時間敏感型系統,例如線上服務、電子商務網站、金融系統和通訊網路。 此類系統的停機可能會導致重大的財務損失、聲譽受損和客戶不滿。因此,保證高可用性是系統設計時重點考慮的問題。 可用性通常**使用正常運作時間(衡量系統運作時間的百分比)和停機時間(衡量系統不可用的時間)等指標**來量化。 實現**高可用性涉及設計具有冗餘、容錯和故障轉移機制的系統**,以最大限度地降低因硬體故障、軟體故障或其他意外事件而導致停機的風險。 > 在系統設計中,採用了各種技術和策略來提高可用性,例如負載平衡、叢集、複製、備份和復原、監控和主動維護。 實施這些措施是為了最大限度地減少單點故障、檢測故障並從故障中恢復,並確保系統即使在發生故障或中斷時也能保持運作。 透過設計具有高可用性的系統,工程師可以確保系統可以長時間存取和執行,從而提高客戶滿意度、減少停機時間並提高業務連續性。 [![系統設計中的高可用性](https://miro.medium.com/v2/resize:fit:546/0*SnLVBPu0JGx4N9F7.gif)](https://www.linkedin.com/pulse/top-20-system-design-interview-questions-answers-soma-sharma-g0pqc/) --- ### 3、可靠性 可靠性是指**軟體系統在交付預期結果時的一致性和可靠性**。建立具有可靠元件、錯誤處理機制和備份/復原策略的系統對於確保系統按預期運作並產生準確的結果至關重要。 可靠性是系統設計的關鍵因素,因為它直接影響系統的整體性能和品質。可靠的系統應始終按預期執行,不會出現意外故障、錯誤或中斷。 **關鍵任務應用通常需要高可靠性,**因為系統故障可能會造成嚴重後果,例如在航空、醫療保健、金融和其他安全關鍵領域。 可靠性通常使用各種指標來量化,例如**平均故障間隔時間 (MTBF)** (測量故障之間的平均持續時間)和故障率 (FR)(測量一段時間內故障發生的速率)。 > 可靠性可以透過各種技術和策略來實現,例如冗餘、錯誤檢測和糾正、容錯和穩健設計。 在系統設計中,要實現高可靠性需要仔細考慮各種因素,包括元件品質、系統架構、錯誤處理、容錯機制、監控和維護策略。 透過**設計高可靠性的系統**,工程師可以確保系統始終如一地按預期執行,從而提高客戶滿意度、減少停機時間並提高系統效能和可用性。 --- ### 4. 容錯性 容錯是指系統或元件在故障或故障(例如硬體故障、軟體錯誤或其他不可預見的問題)時繼續正常運作的能力。 容錯系統旨在檢測、隔離故障並從故障中恢復,而不會完全故障或停機。 容錯是系統設計中的重要概念,特別是在分散式系統或需要在具有挑戰性的環境中可靠運作的系統中。 它涉及實現冗餘、錯誤檢測、錯誤糾正和錯誤恢復機制,以確保即使某些元件或子系統發生故障,系統也能繼續運作。 > 有多種技術和策略可以實現容錯,例如**複製**,即在不同位置維護相同資料或服務的多個副本,以便在一個發生故障時,其他副本可以接管;檢查點,定期保存系統狀態,以便在發生故障時,系統可以恢復到先前已知的良好狀態;優雅降級,即係統在故障時可以繼續執行,但功能會減少。 容錯對於確保系統的高可用性、可靠性和彈性至關重要,特別是在系統故障可能造成嚴重後果的關鍵任務應用程式中。 透過在系統設計中納入容錯機制,工程師可以建立強大且可靠的系統,即使在遇到意外故障時也可以繼續運作並提供預期結果。 [![系統設計中的容錯](https://miro.medium.com/v2/resize:fit:609/0*AKUPawvM6q1K8utM.jpg)](https://bit.ly/3P3eqMN) --- ### 5. 快取策略 快取策略是一種用於優化系統效能的技術,它透過將經常存取的資料或結果儲存在稱為快取的臨時儲存位置中,以便可以快速檢索資料,而無需重新計算或從原始來源取得。 系統設計中常用的快取策略有以下幾種: 1. **完全緩存** 在此策略中,整個資料集或結果都會快取在快取中,提供對所有資料或結果的快速存取。當資料或結果相對較小且可以輕鬆儲存在記憶體或本地快取中時,此策略非常有用。 2. **部分快取** 在此策略中,通常基於使用模式或頻繁存取的資料,僅快取資料或結果的子集。當資料或結果規模很大,或並非所有資料或結果都被頻繁存取,並且快取整個資料集不可行時,此策略很有用。 3. \*\*基於時間的到期時間 在此策略中,資料或結果被快取特定的時間,之後快取被認為是陳舊的,並且資料或結果從原始來源獲取並在快取中更新。當資料或結果相對穩定且不經常變化時,此策略很有用。 4. **LRU(最近最少使用)或 LFU(最不常使用)替換策略** 在這些策略中,最近最少使用或最不頻繁使用的資料或結果被從快取中逐出,以為新資料或結果騰出空間。當快取的儲存容量有限且需要驅逐不常存取的資料以容納新資料時,這些策略非常有用。 5. **直寫式或後寫式緩存** 在這些策略中,資料或結果在更新或插入時寫入快取和原始來源(直寫)或僅寫入快取(後寫)。當系統需要保持快取和原始來源之間的一致性或原始來源無法直接更新時,這些策略就非常有用。 6. **分散式快取** 在此策略中,快取分佈在多個節點或伺服器上,通常使用分散式快取框架或技術。當系統跨多個節點或伺服器分佈或擴展並且需要保持分散式快取的一致性和效能時,此策略就非常有用。 7. **自訂快取** 可以根據系統或應用程式的特定要求和特徵來實施自訂快取策略。這些策略可能涉及上述策略或其他自訂方法的組合,以滿足系統的獨特需求。 選擇*合適的快取策略取決於資料或結果的大小、存取頻率、資料或結果的易變性、儲存容量、一致性要求以及系統的效能目標等多種因素*。仔細考慮和實施快取策略可以顯著提高系統效能、降低資源利用率、提高可擴展性並增強使用者體驗。 [![系統設計的快取策略](https://miro.medium.com/v2/resize:fit:609/0*vm4O76NLJuhVu68G)](https://bit.ly/3P3eqMN) --- ### **6.負載平衡** 負載平衡是分散式系統或網路中使用的技術,用於在多個伺服器或資源之間均勻分配傳入的網路流量或工作負載,確保沒有任何單一伺服器或資源因過多的流量或工作負載而不堪負荷。 負載平衡的目的是優化資源利用率,最大化系統可用性,提高系統整體效能和可靠性。在微服務架構中, [*負載平衡和 API 閘道*](https://medium.com/javarevisited/difference-between-api-gateway-and-load-balancer-in-microservices-8c8b552a024)通常指的是相同的,但事實並非如此,API 閘道可以做更多的事情,如[本文](https://medium.com/javarevisited/what-is-api-gateway-pattern-in-microservices-architecture-what-problem-does-it-solve-ebf75ae84698)所述。 負載平衡可以透過各種演算法或方法來實現,例如: 1. **循環:**傳入請求以輪流方式依序分發到每個伺服器或資源,確保所有伺服器或資源之間的流量平均分配 2. **最少連線:**傳入請求分發到活動連線數最少的伺服器或資源,確保負載最少的伺服器或資源接收新請求。 3. **來源 IP 關聯性:**來自相同客戶端 IP 位址的傳入請求將導向至相同伺服器或資源,確保來自特定用戶端的請求始終由相同伺服器或資源處理。 4. **加權循環:**傳入請求根據分配給每個伺服器或資源的預定義權重進行分配,從而允許根據伺服器或資源容量或功能採用不同的流量分配比率。 5. **自適應負載平衡:**負載平衡演算法根據伺服器或資源健康、效能或其他指標的即時監控,動態調整流量分配,確保最佳的資源利用率和系統效能。 負載平衡可以使用基於硬體的負載平衡器、基於軟體的負載平衡器或基於雲端的負載平衡服務來實現。 它在具有高流量負載或資源密集型工作負載的分散式系統或網路中發揮著至關重要的作用,可以實現資源的高效利用,增強系統的可用性和可靠性,並提供無縫的用戶體驗。 這裡還有一個來自[DesignGuru.io](https://bit.ly/3pMiO8g)的漂亮圖表,這是一個學習面試準備系統設計的優秀網站,它強調了負載平衡器和 API 閘道之間的區別: [![負載平衡器和API網關之間的區別](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bi0uzsaryydef7es0dmv.jpg)](https://bit.ly/3pMiO8g) --- ### **7. 安全** 系統設計中的安全性是指考慮和實施保護系統免受潛在安全威脅、漏洞或攻擊的措施。 它涉及設計和實施具有內建安全功能和實踐的系統,以防止未經授權的存取、資料外洩、資料外洩、惡意軟體攻擊和其他安全風險。 系統設計中的安全性通常涉及以下原則: 1. **身份驗證:**確保使用者或實體經過驗證並根據其身分和憑證被授予適當的存取權限。 2. **授權**:實施存取控制和權限,限制使用者或實體存取未經授權的資源或執行未經授權的操作。 3. **加密**:透過使用加密技術來保護敏感資料,以防止未經授權的存取或資料外洩。 4. **稽核和日誌記錄**:實施機制來追蹤和記錄系統活動和事件,以用於監視、稽核和取證目的。 5. **輸入驗證:**驗證和清理所有輸入資料,以防止常見的安全漏洞,例如 SQL 注入、跨站腳本 (XSS) 和跨站請求偽造 (CSRF) 攻擊。 6. **修補程式和更新**:使用最新的安全性修補程式和更新使系統保持最新狀態,以解決已知的安全漏洞。 7. **深度防禦**:實施多層安全控制,例如防火牆、入侵偵測系統和防毒軟體,以提供針對安全威脅的多層防禦。 8. **最小權限原則**:將使用者或實體的存取權限限製到執行其任務所需的最低限度,減少安全漏洞或攻擊的潛在影響。 9. **安全通訊**:使用安全通訊協定(例如 HTTPS 或 SSL/TLS)來保護傳輸中的資料免於攔截或竊聽。 系統設計中的安全性對於保護資料和資源的完整性、機密性和可用性以及確保系統的整體安全狀況至關重要。應考慮並納入系統的設計、開發和部署階段,以減輕潛在的安全風險並防範安全威脅。 --- ### **8. 可擴展的資料管理** 可擴展的資料管理是指系統或應用程式有效處理不斷增長的資料量而不會出現效能下降或功能遺失的能力。 它涉及設計和實施資料管理實務和技術,這些實務和技術可以處理不斷增加的資料量、使用者負載和處理要求,同時保持可接受的效能和可靠性水準。 可擴展的資料管理通常涉及以下原則: 1. **資料分區:**將大型資料集分割成更小的、可管理的區塊或分區,以將資料分佈在多個儲存或處理資源上。這有助於減少單一資源的負載,並允許並行處理和提高效能。 2. **分散式資料庫系統:**使用分散式資料庫或資料儲存解決方案,可以將資料分佈在多個節點或伺服器上,從而實現水平擴展並提高效能。 3. **資料複製**:跨多個節點或伺服器複製資料,以確保資料可用性和容錯性。這可能涉及資料鏡像、資料分片或資料快取等技術,以提高效能和可靠性。 4. **快取和記憶體中資料儲存:快取**經常存取的資料或將資料儲存在記憶體中,以便更快地檢索和處理,減少對昂貴的磁碟 I/O 操作的需求並提高效能。 5. **索引和查詢最佳化**:使用高效的索引和查詢最佳化技術來加速資料檢索和處理操作,尤其是在大型資料集中。 6. **資料壓縮:**實施資料壓縮技術以減少儲存佔用空間並提高資料傳輸效率,特別是對於大型資料集。 7. **資料歸檔和清除**:實施資料歸檔和清除實踐以刪除或歸檔舊的或不經常存取的資料,減少儲存和處理開銷並提高效能。 8. **可擴展的資料處理框架:**使用可擴展的資料處理框架,例如 Apache Hadoop、Apache Spark 或 Apache Flink,可以分散式並行方式處理大規模資料處理和分析任務。 9. **雲端的資料管理**:利用雲端的資料管理服務,例如 Amazon S3、Amazon RDS 或 Google Bigtable,提供可擴充和託管的資料儲存和處理功能。 10. **監控和可擴展性測試**:定期監控系統效能並進行可擴展性測試,以辨識和解決效能瓶頸、資源限製或其他可擴展性挑戰,並確保資料管理實踐能夠有效處理不斷增長的資料量和負載。 簡而言之,可擴展的資料管理對於需要處理大量資料、使用者負載和處理要求的現代應用程式和系統至關重要。 它使系統能夠成長並適應不斷變化的需求,而無需犧牲效能或可靠性,從而確保資料管理實踐能夠有效地處理不斷增加的資料量和負載。 --- ### **9. 設計模式** 系統設計中的[設計模式](https://medium.com/javarevisited/top-10-microservice-design-patterns-for-experienced-developers-f4f5f782810e)是指用於解決軟體系統開發過程中遇到的常見設計挑戰或問題的可重複使用解決方案或最佳實踐。 [設計模式](https://medium.com/javarevisited/21-software-design-pattern-interview-questions-and-answers-b7d1774b5dd2)是被廣泛接受和經過驗證的設計和架構軟體系統的方法,它們為設計高效、可維護和可擴展的系統提供了一組明確的指南。 系統設計中的設計模式可分為多種類型,包括: 1. **建立模式:**這些模式專注於物件建立機制,並提供以靈活且可重複使用的方式建立物件的方法。建立模式的範例包括 Singleton、Factory Method、Abstract Factory、Builder 和 Prototype 模式。 2. **結構模式:**這些模式著重於類別和物件的組織以形成更大的結構或系統。結構模式的範例包括適配器、橋、複合、裝飾器和外觀模式。 3. **行為模式:**這些模式著重於系統內物件或元件之間的互動和通訊。行為模式的範例包括觀察者、策略、命令、迭代器和模板方法模式。 4. **架構模式:**這些模式為設計系統的整體架構提供了高階指南和策略。架構模式的範例包括模型-視圖-控制器 (MVC)、模型-視圖-視圖模型 (MVVM)、分層架構、微服務和事件驅動架構模式。 設計模式在系統設計中非常重要,因為它們提供了經過驗證的標準化方法來解決常見的設計挑戰、提高程式碼品質並確保軟體系統的可維護性和可擴展性。 它們促進程式碼的可重複使用性、關注點分離和功能封裝,從而更容易管理複雜的系統並使其適應不斷變化的需求。 透過使用設計模式,開發人員可以利用現有知識和最佳實踐來設計強大而高效的系統,以滿足使用者和利害關係人的需求。 在過去的幾篇文章中,我還討論了常見的微服務設計模式,如[**事件來源**](https://medium.com/javarevisited/what-is-event-sourcing-design-pattern-in-microservices-architecture-how-does-it-work-b38c996d445a)**、** [**CQRS**](https://medium.com/javarevisited/what-is-cqrs-command-and-query-responsibility-segregation-pattern-7b1b38514edd) \*\*、SAGA\*\*、 [**每個微服務的資料庫**](https://medium.com/javarevisited/what-is-database-per-microservices-pattern-what-problem-does-it-solve-60b8c5478825)**、** [**API 閘道**](https://medium.com/javarevisited/difference-between-api-gateway-and-load-balancer-in-microservices-8c8b552a024)、 [**斷路器**](https://medium.com/javarevisited/what-is-circuit-breaker-design-pattern-in-microservices-java-spring-cloud-netflix-hystrix-example-f285929d7f68),並分享了[*設計微服務的最佳實踐*](https://medium.com/javarevisited/10-microservices-design-principles-every-developer-should-know-44f2f69e960f),您也可以查看這些文章以了解有關微服務通訊的更多訊息,包括同步和非同步通訊。 --- ### 10. 性能 雖然我們已經知道效能意味著什麼,但還記得速度慢的筆記型電腦嗎?在系統設計中,效能是指軟體系統處理資料和交付結果的速度、反應能力和效率。 透過高效的演算法、快取、索引和其他技術來優化系統效能對於建立能夠處理大規模資料處理並提供最佳回應時間的系統至關重要。 系統設計中的效能是指軟體系統或應用程式有效率且有效地執行其預期功能或任務,同時滿足效能要求和期望的能力。它涵蓋了系統的回應時間、吞吐量、資源利用率、可擴展性和效率等各個方面。 效能是系統設計中的關鍵因素,因為它直接影響使用者體驗、系統可靠性和整體系統效率。效能不佳的系統可能會導致反應時間慢、吞吐量低、資源利用率高以及系統資源使用效率低下,導致系統效能下降和使用者不滿意。 系統設計人員在設計過程中需要考慮各種與效能相關的因素,例如選擇適當的演算法和資料結構、最佳化程式碼、最大限度地減少不必要的開銷、有效管理系統資源以及確保正確的系統配置和調優。 效能測試和分析技術還可用於辨識和解決效能瓶頸並優化系統效能。 優化系統設計中的效能需要在功能、複雜性和資源利用率之間進行仔細的平衡。它涉及做出明智的設計決策、使用最佳實踐以及持續監控和優化系統性能,以確保系統滿足其性能要求並提供流暢高效的用戶體驗。 ### 結論 這就是面試的基本系統設計概念。理解和掌握這些關鍵的系統設計概念對於程式設計師建立健壯、可擴展且高效的軟體系統至關重要。 這些概念,包括容錯、可靠性、可用性、快取策略、負載平衡、安全性、可擴展資料管理、設計模式和效能,在確保軟體系統滿足其預期目標、最佳執行並提供卓越的效能方面發揮著關鍵作用。 透過對這些系統設計概念的深入理解,您可以做出明智的設計決策,選擇適當的技術和技巧,並優化系統效能。 它還允許您設計具有彈性、可擴展、安全和高效的系統,能夠應對現代軟體開發的挑戰並滿足最終用戶的期望。 順便說一句,如果您正在*準備系統設計面試*並想要深入學習系統設計,那麼您還可以查看[**ByteByteGo**](https://bit.ly/3P3eqMN) 、 [**DesignGuru**](https://bit.ly/3pMiO8g) 、 [**Exponent**](https://bit.ly/3cNF0vw) 、 [**Educative**](https://bit.ly/3Mnh6UR)和[**Udemy**](https://bit.ly/3vFNPid)等網站,它們有許多很棒的系統設計課程,如果您需要免費的系統設計課程您也可以查看下面的文章。 --- 原文出處:https://dev.to/somadevtoo/10-must-know-system-design-concepts-for-interviews-2fii

如何亂下 git 讓自己被公司開除

這是比利。 ----- ![帶著微笑和紅色領帶的簡筆畫](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zi8n22y9i5j499h2bvx7.png) 他是一位為重要公司工作的實習開發人員。 對公司來說不幸的是,今天比利醒來並選擇了*暴力。* 這是因為他覺得學習Git非常麻煩、枯燥、很費解。 分支、提交、簽出、HEAD、功能、暫存,天啊! 這對他來說實在太多了。 但隨後比利想到了一個絕對是最好、最壞的主意。 > 「如果我學習 git 時先學會什麼不該做,然後又去做,那會怎麼樣!” 這將完成三件事: 1. 他會透過給自己一些通常被禁止的有趣的小挑戰來學習 git 最常用的工具。 2. 如果他知道什麼**不該**做,那麼他以後就可以專注於他**應該**做的事情。 3. 這樣的學習滿足了他混亂的邪惡傾向。 對比利來說,這聽起來越來越像是個好主意。這肯定會讓他成為一個更好的開發人員。 但只有一個問題...... ### Git 是開發人員用來管理軟體原始碼的版本控制系統。 每當某人更改、新增甚至刪除某些內容時,Git 都會記錄誰做了什麼。 如果你想在你工作的公司擁有的儲存庫中做一些非常糟糕的事情,那麼總是有人可以追溯到你。 那肯定會讓你被解僱。 這就是比利偷了特倫特電腦的原因。 ![簡筆人物比利舉著一台逼真的筆記型電腦,上面寫著“特倫特的電腦(被盜)”](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4dgqmz1otq6yqcqj3vsf.png) 特倫特是個大笨蛋,他去洗手間時打開了電腦,而且沒有採取任何保護措施。 在上個月的聚會後,他還沒有事先詢問就吃了最後一片披薩。 透過 Trent 的計算機,Billy 現在可以存取相同的儲存庫,但需要使用 Trent 的登入憑證。 所以現在 Billy 可以透過先學習他不應該做的所有事情來學習 Git,例如: 1.使用--force將程式碼推送到別人的分支 ----------------------- 假設目前的 git 生態系如下所示: ![主分支和同事功能分支的 Git 圖。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d6jhhy9i977la225uatn.png) Billy 目前正在查看另一位同事分支的早期版本。 如果兩個人在同一個分支上簽出,但其中一個人開始將變更推送到遠端,則可能會發生這種情況。 這意味著比利在分支上落後了。如果他想取得目前所在分支的最新更改,他會在終端機中寫入`git pull` 有趣的事實: Git pull 其實是另外 2 個 git 指令的組合。 - `git fetch origin` (取得遠端的最新變更而不檢查或合併它) - `git merge origin/<branch name>` (這*會將*本機變更合併至遠端。由於通常您不會合併本機文件,因此 git 會執行所謂的「快轉」操作,最終您會得到最新的變更) 比利想知道如果他嘗試推動這個人的分支會發生什麼,即使他落後於最新的變化。 通常,如果他嘗試`git push`某些程式碼,該嘗試將會失敗並出現錯誤 - 要求他首先提取最新的更改。 (這是 git 內建的安全網,以避免工作遺失。除非先拉,否則無法推!) 但如果比利執行`git push --force`指令,就可以避免這種情況。 `git push --force`對於開發人員來說通常是一個大問題。這是一個強制覆蓋 git 歷史記錄並讓您推送本地更改的命令,儘管它可能會刪除同一分支上其他人的工作。 比利以前從未使用過它,是一個好奇的男孩,所以他做了任何好奇的人都會做的事情。 1. 他建立了一個新文件,其中包含特殊文字: `echo "Trent was here" > Trent.txt` 2. 他對分行做出了非常重要的改變 `git add Trent.txt` `git commit -m "Trent committed this"` 這使得 git 看起來像這樣: ![Git 流程圖顯示了他的同事的更改如何消失以及 Billy 的新程式碼如何覆蓋它](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3wzzbao8zv2mbs9ciuqy.png) 3. 他透過強制將新變更推送到分支來結束 `git push --force` 幾秒鐘後... *噗!* Billy 非常重要的更改現在已在 Git 中! 同時,他同事的所有工作完全消失了! 天啊,那真是太有趣了。比利想知道他還要等多久才能讓那位同事注意到。 他想知道是否有什麼事情是他能做的最糟糕的事情。也許……他可以在生產中做類似的事情? 比利腦中的一個燈泡突然熄滅了!如果他做了: 2.生產分支上的硬重置 ----------- `Git reset`是一個命令,類似於 Billy 對他的同事所做的那樣,撤消在分支中建立的對先前提交的更改。 與他之前學到的`git push --force`指令不同,沒有什麼可以推送的。它只是透過(通常)取消提交在某個提交之前完成的所有事情來重寫 git 歷史記錄。 git reset 指令有 3 種模式。 1. `git reset --soft`將 HEAD(Head 是您目前簽出的提交)移回指定的提交,同時也撤銷所做的所有變更。所有這些變更都會返回暫存狀態,並允許您再次提交。 2. `git reset --mixed`與`git reset --soft`作用相同,但會保留您所做的所有變更。這也是 git reset 指令的預設模式。因此,如果您編寫`git reset` ,則與執行`git reset --mixed`相同。 3. `git reset --hard`是惡魔般的。它不會撤消更改並將其保留在暫存/未暫存狀態...它只是丟棄它們。 *噗* 當您硬重置到舊提交時,所有這些更改都會消失。 因此,如果 Billy 說…硬重置到**6 個月前**的提交,哦,我不知道,這對公司來說將是非常糟糕的。 比利微笑著打開終端機。 記住 git 生態系統是什麼樣子的: ![Git 分支顯示 6 個月前的提交和最新的提交](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4xwvqa9275q5f4f9oa1p.png) 比利高興地開始說: 1. 在終端`git checkout main`中輸入,將他定位到該分支的最新提交。 2. 使用 git 視覺化工具從主分支尋找 6 個月前的提交。 3. 最後輸入`git reset --hard <commit hash>`刪除主分支中過去 6 個月的所有變更。 幾秒鐘後... *噗!* 比利成功地讓一些公司高層非常非常生氣! 但等一下... 比利能夠做到這一點很奇怪,不是嗎?畢竟... ### 權限通常在儲存庫中設置,以便任何人都無法直接推送到生產分支。 這可以防止意外推送或重寫直接影響網站的 git 歷史記錄。 這就是為什麼存在所謂的「拉取請求」(或 PR)的原因。 ### 拉取請求是將一組變更從一個分支合併到另一個分支的提議。 通常,其他精通技術的開發人員首先必須接受您的更改,然後您才能合併。 但如果從未設定這些權限會發生什麼事? 好吧,似乎像比利這樣的人可以在一秒鐘內抹掉每個人過去兩個季度的努力。 他計算出,在他對生產產生主要影響之前,他可能還有 10 分鐘……不,15 分鐘。 所以比利必須快速行動。在一個名叫特倫特的人陷入麻煩之前,他可能還有時間去做另一件混亂的邪惡事情。 該怎麼辦... 哦,比利知道!他應該: 3. 揭露專案秘密並將其推向生產! ----------------- Billy 可以透過修改 .gitignore 檔案輕鬆完成此操作。 ### .gitignore 是位於專案目錄中的一種特殊類型的檔案。顧名思義,它指定 Git 應忽略哪些檔案並避免讓您暫存。 當您有一些不想先上傳到儲存庫的特定檔案時,這非常有用。 您*通常*希望避免上傳的檔案之一是 .env 檔案。 ### .env 檔案往往在專案中用於保存您將在整個解決方案中使用的環境變數。 它們具有鍵/值對以及您*確實*不想上傳的資訊。 API 金鑰、資料庫 URI、AUTH 金鑰等。 但比利不喜歡保守秘密。 他是他故事中的英雄,必須讓人知道! 因此,如果我們假設 .gitignore 檔案如下所示: ``` # Javascript node_modules node_modules/ # API keys .env ``` 那麼比利要做的就是: 1. 找到 .gitignore 文件 2. 使用他最喜歡的 IDE 或終端文字編輯器從檔案中刪除 .env 行並儲存。 (這使得文件現在看起來像這樣) ``` # Javascript node_modules node_modules/ # API keys are gone from ignore oops ``` 3. 將現在更改的 .gitignore 檔案新增到暫存中。 Billy 透過在終端機中輸入`git add .gitignore`來完成此操作 4. 等一下!不要忘記 - 由於 Git 現在不會忽略 .env 文件,Billy 也必須加入它! `git add .env`也被輸入到終端機中。 5. 是時候做出承諾了!比利用這一行做到了這一點: ``` `git commit -m "FREEEEEEDOOOOOMMM!!!! #TrentWasHere"` ``` 6. 最後一步!是時候推送到主分支了。再次,由於某種原因,沒有任何權限設定可以阻止比利,他可以在終端機中寫入`git push --force` 。 幾秒鐘後... *噗!* 「自由、平等、博愛」比利高興地低聲說!就在他把特倫特的電腦留在了它所屬的地方。 這也是一件好事,因為他剛剛聽到遠處房間裡傳來廁所沖水的聲音。 比利跑回他的辦公桌,在任何人注意到之前及時趕到。 *唷* 看來特倫特終於從衛浴休息回來,坐在辦公桌前。 但就在他打開筆記型電腦之前,特倫特的電話響了。 *戒指戒指,戒指戒指* 比利滿懷期待地等待著,看到特倫特慢慢地拿起電話。 “你好?” “特倫特。辦公室。現在。” 比利可以在 5 個辦公桌外聽到特倫特電話裡的喊叫聲。 “哇,老闆發生什麼事了?” … “我沒有做任何事——” … 「你們生產出了什麼事嗎? … “我正在路上” 崔恩特迅速跑向辦公室,可能是為了他一生中的尖叫聲。 比利坐下來,放鬆下來,終於可以說: 「今天我是一個更好的開發人員」。 ![簡筆畫比利微笑著](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7627w4yj05yxqwiomyty.png) --- 這是我寫過的最愚蠢的文章。 ------------- 如果您喜歡我的幽默感,那麼我想您一定會喜歡我的電子報「Exceptional Frontend」——網路上最有趣的前端電子報。 它適合任何想要一份以前端為中心、試圖與其他人不同的時事通訊的開發人員。我們專注於使其獨一無二,最重要的是—有趣! 同時也幫助開發人員在他們所做的事情上變得出色。 [您可以在這裡註冊。](https://exceptional-frontend.aweb.page/p/b56d0522-222b-468d-85b2-d69c15afac1c) --- 原文出處:https://dev.to/mauroaccorinti/how-to-get-somebody-fired-using-git-31if

建立你的第一個 npm 包

這個週末我開始開發我的第一個 npm 包。我不敢相信我編寫程式碼已經有多久了,我從來沒有費心去建立自己的 npm 包,但我們來了。我使用 Gridsome 和 markdown 建立了我的最新網站,您可以[在此處](https://www.danvega.me/blog/hello-gridsome)閱讀所有相關內容。在 Markdown 文件中,我想要一個簡單的方法來插入 Twitter 狀態並嵌入推文。 我將在以後的部落格文章中告訴您有關 Gridsome 插件的更多訊息,但現在,我想向您展示如何建立您的第一個 npm 包。我在做這件事的過程中學到了一些東西,我想與你們分享。 先決條件 ---- 我假設你至少知道什麼是 Node 和 npm,並且之前寫過 JavaScript。如果您對其中任何一個都不了解,並希望我寫一些有關這些入門的內容,請告訴我。 在我們深入並開始編寫一些程式碼之前,您需要一些東西。 - [Visual Studio Code](https://code.visualstudio.com/)或您最喜歡的編輯器 - [節點和 NPM](https://nodejs.org/en/) - [NPM帳戶](https://www.npmjs.com/) 建立你的 npm 包 ---------- 您要做的第一件事是建立一個新資料夾來保存您的 npm 套件。對於此範例,我將建立一個名為**wrap-with-poo**的新目錄。是的,你沒看錯。 進入該資料夾並輸入以下內容: ``` npm init ``` 這會問你一堆問題,然後建立一個 package.json。如果您還不知道某些問題的答案,請不要擔心,您可以稍後再回來回答。 ``` This utility will walk you through creating a package.json file. It only covers the most common items and tries to guess sensible defaults. See `npm help json` for definitive documentation on these fields and exactly what they do. Use `npm install <pkg>` afterward to install a package and save it as a dependency in the package.json file. Press ^C at any time to quit. package name: (wrap-with-poop) version: (0.1.0) 0.1.0 description: This package will take any string you give it and wrap it with the poop emjoi entry point: (index.js) test command: git repository: keywords: node,npm author: Dan Vega license: (ISC) MIT About to write to /Users/vega/dev/npm/wrap-with-poop/package.json: { "name": "wrap-with-poop", "version": "0.1.0", "description": "This package will take any string you give it and wrap it with the poop emjoi", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [ "node", "npm" ], "author": "Dan Vega", "license": "MIT" } Is this OK? (yes) yes ``` 寫你的插件 ----- 接下來在 Visual Studio Code 中開啟專案並建立 index.js。您建立此文件的原因是您在 package.json 中說過這是您的入口點。在你的index.js中加入以下程式碼: ``` module.exports = (str) => { return `💩${str}💩`; } ``` module.exports 物件允許我們組織一些相關的程式碼,然後將其公開為模組。這意味著當我們完成後,我們可以將此模組匯入到另一個應用程式中。在本例中,我們指派一個箭頭函數,這表示我們公開一個函數,該函數接受一個名為 str 的參數,並傳回用 poo 表情符號包裹的字串。這就是您需要對這個專案做的全部事情。這是一個非常簡單的包,但它將有助於完成一些事情。 npm 本機開發 -------- 現在您已經準備好了我們的包,您需要在另一個專案中測試它。在現實世界中,您應該針對它編寫一些單元測試,但我想將其保存到另一篇文章和截圖中。 接下來,建立一個名為「wrap-with-poo-testing」的新目錄(在套件外部)。您將再次需要執行 npm init 但這次您可以加入 -y 參數來跳過所有問題,這次它們不太重要。 ``` npm init -y Wrote to /Users/vega/dev/npm/wrap-with-poo/package.json: { "name": "wrap-with-poop", "version": "0.1.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" } ``` ### NPM安裝 在此專案中建立一個名為 app.js 的新檔案。這是您將使用新的wrap-with-poo 套件的地方。通常,您可以透過執行以下命令來安裝所需的 npm 軟體包。 ``` npm install wrap-with-poo ``` 問題是你還沒有發布你的新插件,所以它不在 npm 中。您需要一種在開發時在本地引用該套件的方法。您可以使用套件的絕對路徑來執行 npm install。 ``` npm install /Users/vega/dev/npm/wrap-with-poo ``` 這會將您的 package.json 更新為如下所示 ``` { "name": "npm", "version": "0.1.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "wrap-with-poo": "file:../wrap-with-poo" } } ``` 如果您需要測試套件中的[安裝前/安裝後掛鉤,](https://docs.npmjs.com/misc/scripts)那麼您將需要使用此方法。如果您不關心本地開發 NPM 專案的最佳方法是使用[npm link](https://docs.npmjs.com/cli/link.html) 。 ### NPM連結 npm link 是一個允許您在專案和依賴項之間建立符號連結的過程。首先,您需要進入目錄wrapper-with-poo並執行以下命令。 ``` npm link ``` 這將獲取您的套件並在 npm 全域資料夾中建立符號連結。 **/Users/vega/.nvm/versions/node/v10.15.0/lib/node\_modules/wrap-with-poo -> /Users/vega/dev/npm/wrap-with-poo** 這意味著您的專案只需一個簡單的步驟即可在任何專案中使用。您需要做的下一件事是進入專案 wrap-with-poo-testing 並執行以下命令。 ``` npm link wrap-with-poo ``` 這將輸出以下內容: \_\_/Users/vega/dev/npm/wrap-with-poo-testing/node\_modules/wrap-with-poo -> /Users/vega/.nvm/versions/node/v10.15.0/lib /node\_modules/wra p-with-poo -> /Users/vega/dev/npm/wrap-with-poo\_\_ 這就是全部內容,無需安裝依賴項。您已準備好開始編寫一些程式碼來使用新插件。打開 app.js 並新增以下程式碼。 ``` const poo = require('wrap-with-poo'); const boring = 'This is a boring string'; const fun = poo(boring); console.log(fun); ``` 並從集成終端執行以下命令 ``` node app.js ``` 你會得到以下輸出 ``` 💩This is a boring string💩 ``` 發布原始碼 ----- 現在我們知道我們的專案正在發揮作用,是時候將其公開供所有人使用了。如果您還沒有這樣做,我會將您的專案加入到 Github 或您喜歡的任何原始程式碼託管位置。 ``` git init git add . git commit -m "Initial commit" git remote add origin https://github.com/cfaddict/wrap-with-poo.git git push -u origin master ``` 現在它位於 Github 上,返回並在 package.json 中加入一個條目,以便每個人都知道在哪裡可以使用主頁鍵找到原始程式碼。 ``` { "name": "wrap-with-poo", "version": "0.1.0", "description": "This package will wrap any string you give it with the poop emoji", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [ "node", "npm", "poop" ], "author": "Dan Vega", "license": "MIT", "homepage": "https://github.com/cfaddict/wrap-with-poo" } ``` 發布 NPM 包 -------- 現在是時候將我們的專案發佈到 npm 以便任何人都可以使用它了。如果這是您第一次發布包,請在wrap-with-poo 目錄中開啟終端,然後鍵入以下命令。 ``` npm adduser ``` 這將要求您提供 npm 帳戶訊息,例如使用者名稱、密碼和電子郵件。 ``` vega wrap-with-poo (master) $ npm adduser Username: therealdanvega Password: Email: (this IS public) [email protected] Logged in as therealdanvega on https://registry.npmjs.org/. ``` 現在您已準備好發布,但您需要記住一些事情。首先,每個 npm 套件必須有一個唯一的名稱。我會前往[npm](https://www.npmjs.com/)并快速搜尋你的包。我已經發布了套件wrapper-with-poo,所以你的套件需要一個新的唯一名稱。 接下來您需要知道的是您的版本號碼很重要。我從 0.0.1 開始,然後從那裡開始工作。發布特定版本後,您將無法再次發布相同版本。將許多功能建置到一個版本中然後發布是一個好主意。如果你跑 ``` npm version ``` 它會告訴您目前的版本是什麼。 ``` { 'wrap-with-poo': '0.1.0', npm: '6.7.0', ares: '1.15.0', cldr: '33.1', http_parser: '2.8.0', icu: '62.1', modules: '64', napi: '3', nghttp2: '1.34.0', node: '10.15.0', openssl: '1.1.0j', tz: '2018e', unicode: '11.0', uv: '1.23.2', v8: '6.8.275.32-node.45', zlib: '1.2.11' } ``` 如果一切看起來都不錯,您可以透過執行來發布您的新專案 ``` npm publish ``` 這可能需要幾秒鐘,但如果一切順利,你的包包現在應該[在 npm 上](https://www.npmjs.com/settings/therealdanvega/packages)。 恭喜你發布了你的第一個 npm 包!!! 現在您可以進入任何已有 package.json 的專案並輸入以下內容 ``` npm install wrap-with-poo ``` 就像我們在上面的測試範例中所做的那樣使用它。 文件 -- 我知道有些人說你應該從一開始就建立文件,但我並不總是確定我的程式碼最終會是什麼樣子,所以我通常會等待。在專案的根目錄中建立 README.md 並加入有關專案的一些資訊。 - 你的 npm 包是做什麼的? - 你為什麼創造它。 - 你如何安裝它? - 有任何配置選項嗎? 結論 -- 正如我在本文開頭所說,我不敢相信我這個週末發布了我的第一個 npm 包。直到現在我才真正需要這樣做,但我真的很高興知道它是多麼容易。如果這是您的第一個 npm 軟體包,請在您的軟體包上線後給我留下一些評論或推文! 快樂編碼! 和 *本文首先發佈在我的部落格:https://www.danvega.dev/blog 如果您覺得這篇文章有趣,請考慮[訂閱我的電子報](https://www.danvega.dev/signup/)或在[Twitter](http://twitter.com/therealdanvega)上關注我。* --- 原文出處:https://dev.to/therealdanvega/creating-your-first-npm-package-2ehf

50 多個核心 Java 面試問題及程式設計師答案

--- 標題:針對程式設計師的 50 多個核心 Java 面試問題及其答案 發表:真實 描述:核心 Java 面試常見問題及其答案,幫助初學者和初級開發人員獲得第一份 Java 開發工作。 標籤: java、程式設計、職業 封面圖:https://thepracticaldev.s3.amazonaws.com/i/k63545lbbjmh582tiosr.png --- *揭露:這篇文章包含附屬連結;如果您透過本文中提供的不同連結購買產品或服務,我可能會獲得補償。* Java程式設計師大家好!在過去的幾年裡,我一直在分享許多[Java 面試問題](http://javarevisited.blogspot.sg/2015/10/133-java-interview-questions-answers-from-last-5-years.html)、答案和單獨討論。我的許多讀者要求我將他們聚集在一起,以便他們可以在同一個地方進行面試準備。 這篇文章就是這個結果。 本文包含**50 多個 Java 面試問題和答案**,涵蓋所有重要主題,如核心 Java 基礎知識、 [Java 集合框架](https://javarevisited.blogspot.com/2011/11/collection-interview-questions-answers.html)、 [Java 多執行緒和並發](https://javarevisited.blogspot.com/2014/07/top-50-java-multithreading-interview-questions-answers.html)、 [Java IO](https://javarevisited.blogspot.com/2014/08/socket-programming-networking-interview-questions-answers-Java.html) 、 [JDBC](https://javarevisited.blogspot.com/2012/12/top-10-jdbc-interview-questions-answers.html) 、 [JVM 內部原理](http://www.java67.com/2016/08/10-jvm-options-for-java-production-application.html)、 [編碼問題](http://www.java67.com/2018/06/data-structure-and-algorithm-interview-questions-programmers.html)、 [物件導向程式設計](http://www.java67.com/2015/12/top-30-oops-concept-interview-questions-answers-java.html)等。 這些問題是從我做過的各種 Java 訪談中挑選出來的,我的朋友、讀者和其他人根據自己的經驗分享了一些問題。它們絕不是非常困難。您可能已經在電話或面對面的面試中見過它們。 這些問題對於複習重要的 Java 主題(例如核心 Java 概念、多執行緒、lambda、流和集合)也非常有用。 我還分享了一些*用於進一步學習和提高的有用資源*,例如 Udemy 上的[**完整 Java 大師**](https://click.linksynergy.com/fs-bin/click?id=JVFxdTr9V80&subid=0&offerid=323058.1&type=10&tmpid=14538&RD_PARM1=https%3A%2F%2Fwww.udemy.com%2Fjava-the-complete-java-developer-course%2F)課程,您可以加入課程來提高和填補 Java 技能方面的空白。 我還寫過有關 Java 面試準備的書籍,例如[《Grokking the Java Interview》](https://gumroad.com/l/QqjGH)和[《Grokking the Spring Boot Interviews》](https://gumroad.com/l/hrUXKY) ,其中我為 Java 開發人員分享了很多問題。 如果你今年正在準備 Java 面試,你也可以**[在 Gumroad 上取得我的 Java + Spring Interview + SQL Bundle](https://javinpaul.gumroad.com/l/sowpfg)** ,使用程式碼**Friends20**還可獲得 20% 的折扣 [![Java 和 Spring 面試書籍](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xj0hpl0w5lyvdrnwlsoe.png)](https://javinpaul.gumroad.com/l/sowpfg) 那我們還在等什麼?以下是針對初學者和經驗豐富的 Java 開發人員的面試中最常見的一些 Java 問題的清單。 2 至 3 年經驗豐富的程式設計師的 50 個 Java 面試問題 --------------------------------- 因此,為了不浪費您的時間,這裡列出了一些針對初學者程式設計師的常見[核心 Java 面試問題](http://www.java67.com/2018/03/top-50-core-java-interview-questions.html)。此清單主要針對初學者和經驗不足的開發人員,例如具有 2 到 3 年 Java 經驗的人。 1) **Java如何實現平台無關性?** ([回答](http://www.java67.com/2012/08/how-java-achieves-platform-independence.html)) 提示:字節碼和Java虛擬機 答案 - Java 透過產生字節碼然後在 Java 虛擬機器上執行來實現平台獨立性,該虛擬機將這些字節碼轉換為依賴計劃的機器程式碼。由於不同平台的 JVM 不同,我的意思是,對於 Windows,您有單獨的 JRE(其中包括 JVM),對於 Linux,您將有單獨的 JRE。由於 Java 程式碼不會編譯為本機機器碼,而是編譯為字節碼,這使得它們獨立於平台。 2) **Java中的**`**ClassLoader**`**是什麼**? ([回答](http://javarevisited.blogspot.sg/2012/12/how-classloader-works-in-java.html#axzz59AWpr6cb)) 提示:JVM 的一部分,用於載入類別的字節碼。你可以自己寫。 答:在Java中,程式碼被封裝在類別中,因為Java是物件導向的程式設計。你的程式是在類別中寫的,為了執行它們,JVM 會載入這些包含你的程式碼的類別。負責載入類別的 JVM 元件稱為類別載入器。它們是存在的三個主要類別載入器:引導類別載入器、擴充類別載入器和應用程式類別載入器。 這是一個很好的圖表,顯示了每個 Java 類別載入器的功能: [![Java 中的類別載入器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g2brxfmzd67dv2k7rwmv.PNG)](https://javarevisited.blogspot.com/2021/05/java-classloader-interview.html) 3)**寫一個Java程式來檢查一個數字是偶數還是奇數?** ([回答](http://javarevisited.blogspot.sg/2013/04/how-to-check-if-number-is-even-or-odd.htm)) 提示:您可以使用位元運算符,例如位元與,記住,二進位格式中偶數末尾為 0,奇數末尾為 1。 4) **Java中**`**ArrayList**`**和**`**HashSet**`**的差別**? ([回答](http://www.java67.com/2012/07/difference-between-arraylist-hashset-in-java.html)) 提示: `List`和`Set`之間的所有差異都適用於此,例如排序、重複、隨機搜尋等。請參閱 Richard Warburton 的[**《Java 基礎知識:集合》**](https://pluralsight.pxf.io/c/1193463/424552/7490?u=https%3A%2F%2Fwww.pluralsight.com%2Fcourses%2Fjava-fundamentals-collections)以了解有關Java 中的ArrayList、HashSet 和其他重要集合的更多資訊。 [![](https://miro.medium.com/max/875/1*hd861fcwDe86tY-1Y0VNRQ.png)](https://pluralsight.pxf.io/c/1193463/424552/7490?u=https%3A%2F%2Fwww.pluralsight.com%2Fcourses%2Fjava-fundamentals-collections) 5)**什麼是單例中的雙重檢查鎖定?** ([回答](http://www.java67.com/2016/04/why-double-checked-locking-was-broken-before-java5.html)) 提示:兩次檢查實例是否已初始化,第一次不加鎖,第二次加鎖。 **6)如何在Java中建立線程安全的Singleton? (** [**回答**](http://javarevisited.blogspot.sg/2012/12/how-to-create-thread-safe-singleton-in-java-example.html)**)** 提示:有很多方法,例如使用 Enum 或使用雙重檢查鎖定模式或使用巢狀靜態類別。 **7) Java中Serialized和Externalized的差別? (** [**回答**](http://www.java67.com/2012/10/difference-between-serializable-vs-externalizable-interface.html)**)** 提示:Externalized 讓您可以更好地控制序列化過程。 **8) Java中何時使用瞬態變數? (**[**回答**](http://www.java67.com/2012/08/what-is-transient-variable-in-java.html)**)** 提示:當您想要在實作 Serialized 介面的類別中使變數不可序列化時。換句話說,您可以將其用於不想保存其值的變數。請參閱[**完整的 Java MasterClass**](https://click.linksynergy.com/fs-bin/click?id=JVFxdTr9V80&subid=0&offerid=323058.1&type=10&tmpid=14538&RD_PARM1=https%3A%2F%2Fwww.udemy.com%2Fjava-the-complete-java-developer-course%2F)以了解 Java 中的瞬態變數。 **9) Java中transient變數和volatile變數的差別? (** [**回答**](http://www.java67.com/2012/11/difference-between-transient-vs-volatile-modifier-variable-java.html)**)** 提示:完全不同,一個用於序列化上下文,另一個用於並發。 **10) Java中什麼時候使用易失性變數? (**[**回答**](http://www.java67.com/2012/08/what-is-volatile-variable-in-java-when.html)**)** 提示:當你需要指示JVM一個變數可以被多個執行緒修改並提示JVM不緩存其值。 **11)我們可以重寫Java中的私有方法嗎? (** [**回答**](http://www.java67.com/2013/08/can-we-override-private-method-in-java-inner-class.html)**)** 提示:不,因為它在子類別中不可見,這是在 Java 中重寫方法的主要要求。 12) **Java中**`**Hashtable**`**和**`**HashMap**`**的差別**? **(** [**回答**](http://javarevisited.blogspot.sg/2010/10/difference-between-hashmap-and.html#axzz53B6SD769)\*\*) \*\*提示:有幾個但最重要的是`Hashtable` ,它是同步的,而`HashMap`不是。與`HashMap`相比,它也是遺留的且緩慢的。 13) **Java中**`**List**`**和**`**Set**`**的差別**? **(** [**回答**](http://javarevisited.blogspot.sg/2012/04/difference-between-list-and-set-in-java.html#axzz53n9YK0Mb)**)** 提示: `List`是有序的並且允許重複。 `Set`是無序的,不允許有重複的元素。 14) **Java中**`**ArrayList**`**和**`**Vector**`**的區別**([**答案**](http://www.java67.com/2012/09/arraylist-vs-vector-in-java-interview.html)**)** 提示:很多,但最重要的是, `ArrayList`是非同步的,速度很快,而`Vector`是同步的,速度很慢。它也是像`Hashtable`這樣的遺留類別。 **15)** **Java 中**`**Hashtable**`**和**`**ConcurrentHashMap**`的差異? **(** [**回答**](http://javarevisited.blogspot.sg/2011/04/difference-between-concurrenthashmap.html#axzz4qw7RoNvw)**)** 提示:更具可擴展性。請參閱 Richard Warburton 的[**《Java 基礎知識:集合》**](https://pluralsight.pxf.io/c/1193463/424552/7490?u=https%3A%2F%2Fwww.pluralsight.com%2Fcourses%2Fjava-fundamentals-collections)以了解更多資訊。 16) `**ConcurrentHashMap**`**如何實現可擴充性? (** [**回答**](http://javarevisited.blogspot.sg/2017/08/top-10-java-concurrenthashmap-interview.html#axzz50U9xyqbo)**)** 提示:透過將映射分為段並僅在寫入操作期間鎖定。 **17) 您將重寫哪兩個方法來將**`**Object**`**用作**`**HashMap**`**中的**`**Key**` **? (** [**回答**](http://www.java67.com/2013/06/how-get-method-of-hashmap-or-hashtable-works-internally.html)**)** 提示:等於和哈希碼 **18) Java中wait和sleep的差別? (**[**回答**](http://www.java67.com/2012/08/what-are-difference-between-wait-and.html)**)** \\ 提示: `wait()`方法釋放鎖定或監視器,而 sleep 則不會。 19\) **Java中**`**notify**`**和**`**notifyAll**`**的差別**? **(** [**回答**](http://www.java67.com/2013/03/difference-between-wait-vs-notify-vs-notifyAll-java-thread.html)**)** 提示: `notify`通知一個隨機執行緒正在等待該鎖,而`notifyAll`通知所有等待監視器的執行緒。如果你確定只有一個執行緒在等待,那麼使用`notify` ,否則`notifyAll`會更好。請參閱 Java Champion Heinz Kabutz 的[**線程基礎迷你課程,**](https://javaspecialists.teachable.com/p/threading-essentials/?product_id=539197&coupon_code=SLACK100?affcode=92815_johrd7r8)以了解有關線程基礎知識的更多資訊。 20\) 為什麼要**在 Java 中重寫 hashcode 以及**`**equals()**` ? **(** [**回答**](http://javarevisited.blogspot.sg/2015/01/why-override-equals-hashcode-or-tostring-java.html#axzz55oDxm8vv)**)** 提示:遵守 equals 和 hashcode 約定,如果您打算將物件儲存到集合類別(例如`HashMap`或`ArrayList`中,則需要遵守這一點。 21) `**HashMap**`**的負載因子是什麼意思? (**[**回答**](http://www.java67.com/2017/08/top-10-java-hashmap-interview-questions.html)**)** 提示:觸發`HashMap`調整大小的閾值一般為 0.75,這表示如果 HashMap 已滿 75%,則`HashMap`會自行調整大小。 **22)** **Java 中**`**ArrayList**`**和**`**LinkedList**`之間的差異? **(** [**回答**](http://www.java67.com/2012/12/difference-between-arraylist-vs-LinkedList-java.html)**)** 提示:與陣列和鍊錶相同,其中一個允許隨機搜尋,而另一種則不允許。在鍊錶上插入和刪除很容易,但在陣列上搜尋很容易。請參閱[**《Java 基礎知識:集合》**](https://pluralsight.pxf.io/c/1193463/424552/7490?u=https%3A%2F%2Fwww.pluralsight.com%2Fcourses%2Fjava-fundamentals-collections) **(** Richard Warburton 在 Pluralsight 上的課程),以了解更多關於 Java 中基本集合資料結構的資訊。 **23)** **Java 中**`**CountDownLatch**`**和**`**CyclicBarrier**`之間的差異? **(** [**回答**](http://www.java67.com/2012/08/difference-between-countdownlatch-and-cyclicbarrier-java.html)**)** 提示:屏障被打破後,您可以重複使用`CyclicBarrier` ,但計數為零後,您無法重複使用`CountDownLatch` 。 24)**在 Java 中什麼時候使用**`**Runnable**`**和**`**Thread**` ? **(** [**回答**](http://www.java67.com/2016/01/7-differences-between-extends-thread-vs-implements-Runnable-java.html)**)** 提示:總是 **25) Java 中 Enum 類型安全的意義是什麼? (** [**回答**](http://www.java67.com/2014/04/what-java-developer-should-know-about-Enumeration-type-in-Java.html)**)** 提示:這表示您不能將不同 Enum 類型的實例指派給 Enum 變數。例如,如果您有一個像`DayOfWeek` day 這樣的變數,那麼您無法從`DayOfMonth`枚舉中為其指派值。 **26) Java 中整數的自動裝箱如何運作? (** [**回答**](http://javarevisited.blogspot.sg/2012/07/auto-boxing-and-unboxing-in-java-be.html#axzz59AWpr6cb)**)** 提示:透過使用Java中的`valueOf()`方法。 **27)** **Java 中**`**PATH**`**和**`**Classpath**`之間的差異? **(** [**回答**](http://www.java67.com/2012/08/what-is-path-and-classpath-in-java-difference.html)**)** 提示:作業系統使用`PATH` ,而JVM 使用`Classpath`來定位Java 二進位文件,例如JAR 檔案或Class 檔案。請參閱[**Java 基礎知識:核心平台**](https://pluralsight.pxf.io/c/1193463/424552/7490?u=https%3A%2F%2Fwww.pluralsight.com%2Fcourses%2Fjava-fundamentals-core-platform),以了解有關`PATH` 、 `Classpath`和其他 Java 環境變數的更多資訊。 [![](https://miro.medium.com/max/478/1*PBuMgGmVXwBguv-SPw7YJw.jpeg)](https://pluralsight.pxf.io/c/1193463/424552/7490?u=https%3A%2F%2Fwww.pluralsight.com%2Fcourses%2Fjava-fundamentals-core-platform) **28) Java中方法重載和重寫的差別? (** [**回答**](http://www.java67.com/2015/08/top-10-method-overloading-overriding-interview-questions-answers-java.html)**)** 提示:重寫發生在子類別中,而重載發生在同一個類別中。此外,覆蓋是執行時活動,而重載是在編譯時解決的。 **29) 如何防止 Java 中的類別被子類化? (**[**回答**](http://www.java67.com/2017/06/10-points-about-final-modifier-in-java.html)**)** \\ 提示:只需將其建構函數設為私有即可 **30) 你如何限制你的類別被你的客戶使用? (** [**回答**](http://javarevisited.blogspot.sg/2016/01/why-jpa-entity-or-hibernate-persistence-should-not-be-final-in-java.html)**)** \\ 提示:使建構子私有或從建構子拋出異常 **31)** **Java 中**`**StringBuilder**`**和**`**StringBuffer**`之間的差異? **(**[**回答**](http://www.java67.com/2016/10/5-difference-between-stringbuffer.html)**)** 提示: `StringBuilder`不同步,而`StringBuffer`同步。 **32) Java 中多態性與繼承的差別? (** [**回答**](http://www.java67.com/2014/04/difference-between-polymorphism-and-Inheritance-java-oops.html)**)** 提示:繼承允許程式碼重複使用並建構類別之間的關係,這是多態性所需要的,多態性提供動態行為。請參閱\[**物件導向的 Java 程式設計:資料結構及超越專業化**\]( https://coursera.pxf.io/c/3294490/1164545/14726?u=https%3A%2F%2Fwww.coursera.org%2Fspecializations%2Fjava-object-orientation)在Coursera 上,了解有關OOP 功能的更多資訊。適合初學者的最深入的課程之一。 \[![](https://thepracticaldev.s3.amazonaws.com/i/vuohxotp8qeh638lzjpr.png) \]( https://coursera.pxf.io/c/3294490/1164545/14726?u=https%3A%2F%2Fwww.coursera.org%2Fspecializations%2Fjava-物件導向) 順便說一句,如果您發現 Coursera 課程很有用,因為它們是由世界各地的知名公司和大學建立的,我建議您加入[**Coursera Plus**](https://coursera.pxf.io/c/3294490/1164545/14726?u=https%3A%2F%2Fwww.coursera.org%2Fcourseraplus) ,這是Coursera 的訂閱計劃,可以讓您無限制地存取他們最受歡迎的課程、專業、專業憑證和指導專案。它的費用約為 399 美元/年,但它完全物有所值,因為您可以獲得無限的憑證。 **33)我們可以在Java中重寫靜態方法嗎? (**[**回答**](http://www.java67.com/2012/08/can-we-override-static-method-in-java.html)**)** \\ 提示:否,因為重寫在執行時間解析,而靜態方法呼叫在編譯時解析。 **34) 我們可以存取Java中的私有方法嗎? (**[**回答**](http://www.java67.com/2012/08/can-we-override-private-method-in-java.html)**)** \\ 提示:可以,在同一個班級內,但不能在班級外 **35) Java中介面和抽象類別的區別? (** [**回答**](http://www.java67.com/2017/08/difference-between-abstract-class-and-interface-in-java8.html)**)** 提示:從[Java 8](https://dzone.com/articles/5-courses-to-crack-java-certification-ocajp-1z0-80)開始,差異變得模糊。然而,一個Java類別仍然可以實作多個接口,但只能擴展一個類別。 **36) Java 中 DOM 和 SAX 解析器的差別? (**[**回答**](http://www.java67.com/2012/09/dom-vs-sax-parser-in-java-xml-parsing.html)**)** \\ 提示:DOM 將整個 XML 檔案載入到記憶體中,而 SAX 則不會。它是一個基於事件的解析器,可用於解析大文件,但 DOM 速度很快,對於小文件應該是首選。 **37) Java 中 throw 和 throws 關鍵字的差異? (**[**回答**](http://www.java67.com/2012/10/difference-between-throw-vs-throws-in.html)**)** \\ 提示: throws 聲明方法在發生錯誤時可以拋出什麼異常,但 throw 關鍵字實際上會拋出異常。請參閱[**Java 基礎知識:異常處理**](https://pluralsight.pxf.io/c/1193463/424552/7490?u=https%3A%2F%2Fwww.pluralsight.com%2Fcourses%2Fjava-fundamentals-exception-handling)以了解有關 Java 中異常處理的更多資訊。 [![](https://miro.medium.com/max/875/1*O5DEoN9mOy3D0HxFKWwfKQ.png)](https://pluralsight.pxf.io/c/1193463/424552/7490?u=https%3A%2F%2Fwww.pluralsight.com%2Fcourses%2Fjava-fundamentals-exception-handling) **38) Java 中的故障安全迭代器和故障快速迭代器的差異? (** [**回答**](http://www.java67.com/2015/06/what-is-fail-safe-and-fail-fast-iterator-in-java.html)**)** 提示:故障安全性不會拋出`ConcurrentModificationException` ,而`fail-fast`則在迭代時檢測到底層集合的外部變更時拋出 ConcurrentModificationException。 **39) Java 中迭代器和枚舉的差別? (** [**回答**](http://javarevisited.blogspot.sg/2010/10/what-is-difference-between-enumeration.html#axzz59AWpr6cb)**)** 提示:迭代器還使您能夠在迭代時刪除元素,而枚舉不允許這樣做。 **40)** **Java 中的**`**IdentityHashMap**`是什麼? **(** [**回答**](http://www.java67.com/2016/09/difference-between-identityhashmap-weakhashmap-enummap-in-java.html)**)** 提示:一個`Map` ,它使用`==`相等運算子來檢查相等性,而不是`equals()`方法。 **41)** **Java 中的**`**String**`池是什麼? **(** [**回答**](http://javarevisited.blogspot.sg/2016/07/difference-in-string-pool-between-java6-java7.html#axzz4pGGwsyna)**)** 提示: `String`文字池。請記住,它已從 JDK 7 中的永久代空間移至堆疊。 **42)** Java 中`**Serializable**`**類別可以包含不可序列化欄位嗎? (** [**回答**](http://javarevisited.blogspot.sg/2016/09/how-to-serialize-object-in-java-serialization-example.html)\*\*) \*\*提示:是的,但您需要將其設定為靜態或瞬態。 **43) Java 中 this 和 super 的差別? (**[**回答**](http://www.java67.com/2013/06/difference-between-this-and-super-keyword-java.html)**)** 提示:this 指的是目前實例,而 super 指的是超類別的實例。 **44)** **Java 中**`**Comparator**`**和**`**Comparable**`之間的差異? **(** [**回答**](http://www.java67.com/2013/08/difference-between-comparator-and-comparable-in-java-interface-sorting.html)**)** \\ 提示: `Comparator`定義自訂排序,而`Comparable`定義物件的自然順序,例如`String`字母順序。請參閱[**完整的 Java 大師課程**](https://click.linksynergy.com/fs-bin/click?id=JVFxdTr9V80&subid=0&offerid=323058.1&type=10&tmpid=14538&RD_PARM1=https%3A%2F%2Fwww.udemy.com%2Fjava-the-complete-java-developer-course%2F)以了解有關 Java 排序的更多資訊。 [![](https://miro.medium.com/max/875/1*MTR8OytpiIMidLndBnsJ5g.png)](https://click.linksynergy.com/fs-bin/click?id=JVFxdTr9V80&subid=0&offerid=323058.1&type=10&tmpid=14538&RD_PARM1=https%3A%2F%2Fwww.udemy.com%2Fjava-the-complete-java-developer-course%2F) **45)** **Java 中**`**java.util.Date**`**和**`**java.sql.Date**`之間的差異? **(**[**回答**](http://javarevisited.blogspot.sg/2012/04/difference-between-javautildate-and.html)**)** 提示:前者包含日期和時間,後者僅包含日期部分。 46)為什麼**Java中的**`**Object**`類別**中宣告了wait和notify方法**? **(**[**回答**](http://javarevisited.blogspot.sg/2012/02/why-wait-notify-and-notifyall-is.html)**)** 提示:因為它們需要僅對物件可用的鎖。 **47)為什麼Java不支援多重繼承? (** [**回答**](http://javarevisited.blogspot.sg/2011/07/why-multiple-inheritances-are-not.html)**)** 提示:它不支持,因為 C++ 的體驗不好,但對於 Java 8,它在某種意義上是支援的 --- 現在 Java 中不支援`Type`的多重繼承。 **48) Java 中檢查異常和非檢查異常的差異? (** [**回答**](http://javarevisited.blogspot.sg/2011/12/checked-vs-unchecked-exception-in-java.html)**)** 提示:如果是選取的,則必須使用 catch 區塊處理異常,而如果是未選取的,則由您決定;編譯不會打擾你。 **49) Java 中錯誤和異常的區別? (**[**回答**](http://www.java67.com/2012/12/difference-between-error-vs-exception.html)**)** 提示:我厭倦了打字,請檢查答案 **50) Java 中的競爭條件和死鎖的差異? (** [**回答**](http://javarevisited.blogspot.sg/2012/02/what-is-race-condition-in.html#axzz59AbkWuk9)**)** 提示:這兩種錯誤都是並發應用程式中發生的錯誤,一種是由於執行緒調度而發生的,另一種是由於編碼不良而發生的。請參閱[Java 中的多執行緒和平行計算](https://click.linksynergy.com/fs-bin/click?id=JVFxdTr9V80&subid=0&offerid=323058.1&type=10&tmpid=14538&RD_PARM1=https%3A%2F%2Fwww.udemy.com%2Fmultithreading-and-parallel-computing-in-java%2F),以了解有關死鎖、競爭條件和其他多執行緒問題的更多資訊。 其他資源 --- - [Java 面試指南:200+ 面試題目及答案](https://click.linksynergy.com/fs-bin/click?id=JVFxdTr9V80&subid=0&offerid=323058.1&type=10&tmpid=14538&RD_PARM1=https%3A%2F%2Fwww.udemy.com%2Fjava-interview-questions-and-answers%2F) - [Spring框架面談指南---200+問答](https://click.linksynergy.com/fs-bin/click?id=JVFxdTr9V80&subid=0&offerid=323058.1&type=10&tmpid=14538&RD_PARM1=https%3A%2F%2Fwww.udemy.com%2Fspring-interview-questions-and-answers%2F) - [準備工作面試 作者:John Sonmez](https://pluralsight.pxf.io/c/1193463/424552/7490?u=https%3A%2F%2Fwww.pluralsight.com%2Fcourses%2Fdeveloper-job-interviews) - [Markham 曝光的 Java 程式設計面試](http://www.amazon.com/Java-Programming-Interviews-Exposed-Markham/dp/1118722868?tag=javamysqlanta-20) - [破解編碼面試 --- 189 個問題和答案](http://www.amazon.com/Cracking-Coding-Interview-6th-Edition/dp/0984782850/?tag=javamysqlanta-20) - [求職面試的資料結構與演算法分析](https://click.linksynergy.com/fs-bin/click?id=JVFxdTr9V80&subid=0&offerid=323058.1&type=10&tmpid=14538&RD_PARM1=https%3A%2F%2Fwww.udemy.com%2Fdata-structure-and-algorithms-analysis%2F) - [過去 5 年 130 多道 Java 面試題](http://javarevisited.blogspot.sg/2015/10/133-java-interview-questions-answers-from-last-5-years.html) - [Grokking the Java Interview - 免費範例 PDF](https://javinpaul.gumroad.com/l/HMOAv) - [深入了解 Spring Boot 面試 - 免費 PDF 範本](https://javinpaul.gumroad.com/l/grokking-springboot-interview-sample) ### 結束語 謝謝,您已經讀到了文章的結尾...祝您程式設計面試順利!這當然不會很容易,但這些問題肯定會對您有所幫助。它還會鼓勵您了解更多。 如果您喜歡這篇文章,請與您的朋友和同事分享,並且不要忘記在 Twitter 上關注[javinpaul](https://twitter.com/javinpaul) ! > **PS ---**如果您需要一些免費資源來學習 Java,您可以查看[**我最喜歡的免費 Java 課程**](https://medium.com/javarevisited/10-free-courses-to-learn-java-in-2019-22d1f33a3915)清單來開始您的準備。 &gt; > **PSS ---**我沒有提供圖片中分享的面試問題的答案“程式碼中建立了多少個 String 物件?”你能猜出並解釋一下嗎? 而且,如果你今年正在準備 Java 面試,你還可以**[在 Gumroad 上取得我的 Java + Spring Interview + SQL Bundle](https://javinpaul.gumroad.com/l/sowpfg)** ,使用程式碼**friends20**也可以獲得 20% 的折扣 --- 原文出處:https://dev.to/javinpaul/50-core-java-interview-questions-with-answers-for-programmers-3bc

JavaScript 的 25 個不明顯的特性

通常,作為開發人員,我們會編寫類似類型的程式碼,陷入雖然舒適但有時感覺很平凡的模式。 然而,JavaScript 的世界是廣闊的,充滿了高級功能,當發現和使用這些功能時,可以將我們的開發工作變得更加令人興奮和充實。 在本指南中,我們將揭曉 25 個高級 JavaScript 功能,這些功能不僅能揭示這些隱藏的瑰寶,還能將您對 JavaScript 的掌握提升到前所未有的水平。 讓我們一起踏上這段發現之旅,將 JavaScript 的高級功能整合到我們的編碼庫中,以建立更有效率、更優雅、更強大的應用程式。是時候為我們的開發任務注入新的樂趣和創造力了。 1 — 迴圈和區塊語句的標籤 -------------- JavaScript 允許標記迴圈和區塊語句,從而可以使用`break`和`continue`進行精確控制。 ``` outerLoop: for (let i = 0; i < 5; i++) { innerLoop: for (let j = 0; j < 5; j++) { if (i === 2 && j === 2) break outerLoop; console.log(`i=${i}, j=${j}`); } } ``` 2 - 逗號運算符 --------- 逗號運算子允許按序列計算多個表達式,並傳回最後一個表達式的結果。 ``` let a = (1, 2, 3); // a = 3 ``` 3 — 字串格式化以外的標記範本文字 ------------------ 除了建立字串之外,標記範本還可用於 DSL(域特定語言)、清理使用者輸入或本地化。 ``` function htmlEscape(strings, ...values) { // Example implementation } ``` 4 — 區塊內的函數聲明 ------------ 儘管不推薦,但 JavaScript 允許在區塊內聲明函數,這可能會導致非嚴格模式下的不同行為。 ``` if (true) { function test() { return "Yes"; } } else { function test() { return "No"; } } test(); // Behavior varies depending on the environment ``` 5 — 無效運算符 --------- `void`運算子計算任何表達式,然後傳回未定義的值,這對於 JavaScript 的超連結很有用。 ``` void (0); // returns undefined ``` 6 — 用於快速數學的位元運算符 ---------------- 位運算符,例如`|`和`&` ,可以更快地執行一些數學運算,但會犧牲可讀性。 ``` let floor = 5.95 | 0; // Fast way to do Math.floor(5.95) ``` 7 — with 處理物件的語句 ---------------- `with`語句擴展了區塊的作用域鏈,讓您可以編寫更短的程式碼。但是,出於可讀性和效能方面的考慮,不建議這樣做。 ``` with(document.getElementById("myDiv").style) { background = "black"; color = "white"; } ``` [![Christian Heilmann 的 JavaScript 開發技能分享課程](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h758ymfla96s5md0vyf3.png)](https://skillshare.eqcm.net/QyLx6z) 與 Christian Heilmann 一起提高您的 JavaScript 技能 - 從今天開始編寫更乾淨、更快、更好的程式碼! 8 — 自動分號插入 (ASI) ---------------- JavaScript 嘗試修復缺少的分號,但依賴它可能會導致意外結果。 ``` let x = 1 let y = 2 [x, y] = [y, x] // Without proper semicolons, this could fail ``` 9 — 在屬性檢查操作員中 ------------- 檢查物件是否具有屬性,而無需直接存取其值。 ``` "toString" in {}; // true ``` 10——instanceof 與 typeof ----------------------- `instanceof`檢查原型鏈,而`typeof`傳回一個字串,指示未計算的操作數的類型。 ``` function Person() {} let person = new Person(); console.log(person instanceof Person); // true console.log(typeof person); // "object" ``` 11 — ES6 中的區塊級函數 ---------------- [ES6](https://www.webdevstory.com/mastering-es6-for-react/)允許函數具有區塊作用域,類似`let`和`const` 。 ``` { function test() { return "block scoped"; } } console.log(typeof test); // "function" in non-strict mode, "undefined" in strict mode ``` 12 — 偵錯器語句 ---------- 使用`debugger`語句暫停執行並開啟偵錯器。 ``` function problematicFunction() { debugger; // Execution pauses here if the developer tools are open } ``` **13 —**用於動態程式碼執行的`eval()` -------------------------- `eval`將字串作為 JavaScript 程式碼執行,但會帶來重大的安全性和效能影響。 ``` eval("let a = 1; console.log(a);"); // 1 ``` [![InMotion Hosting 促銷虛擬主機計劃](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vevir51wi5coo4gtq3db.png)](https://partners.inmotionhosting.com/k0EPWv) 利用 InMotion Hosting 的一系列計劃(從共享伺服器到 VPS 以及專用伺服器)為您的專案找到合適的託管解決方案。 **14 — 非標準**`__proto__`屬性 ------------------------- 雖然`__proto__`被廣泛支持用於設定物件的原型,但它是非標準的。請改用`Object.getPrototypeOf()`和`Object.setPrototypeOf()` 。 ``` let obj = {}; obj.__proto__ = Array.prototype; // Not recommended ``` 15 — document.write() 用於直接文件編輯 ------------------------------ `document.write()`直接寫入 HTML 文件,但使用它可能會產生負面影響,特別是同步載入外部腳本。 ``` document.write("<h1>Hello World!</h1>"); ``` 16 — 鍊式分配 --------- JavaScript 允許鍊式賦值,它可以在一個語句中將單一值指派給多個變數。 ``` let a, b, c; a = b = c = 5; // Sets all three variables to the value of 5 ``` 17 — 屬性存在的 in 運算符 ----------------- `in`運算子檢查屬性是否存在於物件中,而不存取屬性值。 ``` const car = { make: 'Toyota', model: 'Corolla' }; console.log('make' in car); // true ``` 18 — 物件屬性簡寫 ----------- 為物件指派屬性時,如果屬性名稱與變數名稱相同,則可以使用簡寫。 ``` const name = 'Alice'; const age = 25; const person = { name, age }; ``` 19 — 預設參數值和解構組合 --------------- 您可以將預設參數值與函數參數中的解構結合起來,以獲得更具可讀性和更靈活的函數定義。 ``` function createPerson({ name = 'Anonymous', age = 0 } = {}) { console.log(`Name: ${name}, Age: ${age}`); } createPerson({ name: 'Alice' }); // Name: Alice, Age: 0 createPerson(); // Name: Anonymous, Age: 0 ``` **20 — 使用**`Array.fill()`初始化陣列 ------------------------------ 使用`fill()`方法使用特定值快速初始化陣列。 ``` const initialArray = new Array(5).fill(0); // Creates an array [0, 0, 0, 0, 0] ``` [![符合人體工學的工作空間設置,辦公桌上放置一台筆記型電腦,由 LED 檯燈照明,35.4 英寸的亮度為 500 勒克斯,周圍擺滿了書籍和辦公用品。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ly6b54e50pprze3p6lc9.jpg)](https://amzn.to/3VhQFae) 利用可調式 LED 照明優化您的工作空間,提高工作效率和舒適度,為專注的工作會議創造理想的環境。 **21 —** `Array.includes()`用於存在檢查 --------------------------------- 使用`includes()`方法可以輕鬆檢查陣列中是否存在元素,這比使用`indexOf()`更具可讀性。 ``` const fruits = ['apple', 'banana', 'mango']; console.log(fruits.includes('banana')); // true ``` 22 — 解構別名 --------- `destructuring`物件時,可以使用別名將屬性指派給具有不同名稱的變數。 ``` const obj = { x: 1, y: 2 }; const { x: newX, y: newY } = obj; console.log(newX); // 1 ``` 23 — 預設值的空合併運算符 --------------- 使用`??`僅在處理`null`或`undefined`時提供預設值,而不是其他`falsy`值,例如 ``` const count = 0; console.log(count ?? 10); // 0, because count is not null or undefined ``` 24 — 動態函數名稱 ----------- 使用物件字面量中的計算屬性名稱建立具有動態名稱的函數。 ``` const dynamicName = 'func'; const obj = { [dynamicName]() { return 'Dynamic Function Name!'; } }; console.log(obj.func()); // "Dynamic Function Name!" ``` 25 — 私有類別字段 ----------- 使用 hash `#`前綴定義類別中的私有字段,該字段無法從類別外部存取。 ``` class Counter { #count = 0; increment() { this.#count++; } getCount() { return this.#count; } } ``` 簡單總結 --- 當我們結束 25 個 JavaScript 高階功能的探索時,JavaScript 的函式庫既龐大又強大。 我們深入研究的每個功能都為解決編碼挑戰開闢了新途徑,類似於在我們的工具包中加入創新工具。 這不僅增強了我們創造性、有效率地制定解決方案的能力,而且還強調了 JavaScript 的動態多功能性。 這些進階功能凸顯了持續學習在 Web 開發領域的關鍵角色。 接受這些細微差別並將它們整合到我們的日常編碼實踐中,使我們能夠提高我們的技能並為[網路技術的發展](https://www.simplilearn.com/what-is-web-1-0-web-2-0-and-web-3-0-with-their-difference-article)做出貢獻。 請記住,[掌握 JavaScript 的](https://www.webdevstory.com/javascript-essential-terms/)道路是一個持續的旅程,每一行程式碼都提供了發現非凡事物的機會。 讓我們不斷突破 JavaScript 所能實現的極限,保持好奇心並對未來的無限可能性保持開放。 ***支持我們的技術見解*** [![請我喝杯咖啡](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lsm9uucbnw7x9iw0loxr.png)](https://www.buymeacoffee.com/mmainulhasan) [![透過 PayPal 按鈕捐贈](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ipnhbim2ba56kt32zhn3.png)](https://www.paypal.com/donate/?hosted_button_id=GDUQRAJZM3UR8) 注意:此頁面上的某些連結可能是附屬連結。如果您透過這些連結進行購買,我可能會賺取少量佣金,而您無需支付額外費用。感謝您的支持! --- 原文出處:https://dev.to/mmainulhasan/25-unnoticeable-features-of-javascript-15l1

讓我們將函數式程式設計引入 OOP 程式碼庫

時間越長,我就越成為函數式程式設計的愛好者。即使當我在 OOP 程式碼庫中工作時,我也會嘗試應用旨在簡化程式碼並更輕鬆地預測結果的小概念。身為 Ruby 專家,我也喜歡使用功能程式碼編寫單元測試是多麼簡單。 本文的目的是分享我對函數式程式設計概念的看法,並提出一種可以在已編寫的 OOP 程式碼中使用函數式概念的方法。希望我們能夠停止爭論哪種範式更好,並開始編寫好的想法,每次都能產生更好的程式碼! 目錄 -- - [一開始,有函數式編程](#in-the-beginning-there-was-functional-programming) - [進入OOP,這個範式是什麼?](#entering-oop-what-is-this-paradigm) - [什麼是類別以及我們如何以不同的方式思考它](#what-is-a-class-and-how-can-we-think-about-it-differently) - [變異還是不變異:什麼是不變性](#to-mutate-or-not-to-mutate-what-is-immutability) - [床下的怪物:有什麼副作用](#the-monster-under-the-bed-what-are-side-effects) - [隔離一切:什麼是純函數](#isolate-everything-what-are-pure-functions) - [使用函數式模式而不需要完整的 haskell](#using-functional-patterns-without-going-full-haskell) - [結論](#conclusion) 一開始,有函數式編程 ---------- ![功能性](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hpg7b5lx6czu67jv9e07.png) 函數式程式設計範式於 1958 年隨著第一個 Lisp 語言的出現而出現(美好的時光)。它的根源可以追溯到 Alonzo Church 的 lambda 演算。函數式程式設計的核心原則圍繞著最小化對程式碼庫中狀態的依賴。 與允許狀態但強調封裝的物件導向程式設計 (OOP) 不同,函數式程式設計師努力優先編寫無狀態元件。這種方法鼓勵建立獨立於外部狀態變數的程式碼。 此外,即使引入了狀態,在編寫狀態時也必須考慮不變性、函數的純度,甚至避免副作用。隨著本文的深入,所有這些概念都將進一步介紹。 進入OOP,這個範式是什麼? -------------- ![打開](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/em6b2ejnoml80awxyrhw.png) OOP,或更廣為人知的名稱為“物件導向程式設計”,是一種可以追溯到 1967 年的範式。其最偉大的代表是 Simula、Smalltalk 和 Java。背後的思想過程是透過強制封裝實踐來將這些狀態以及修改它們的任何行為分組到公共「實體」或「物件」下,從而減少「全局」狀態的數量。 事實上,「物件導向程式設計」這個名字多年來一直被廣泛討論。 OOP 的建立者之一 Alan Key 實際上希望更多地關注該範例的訊息傳遞方面。這意味著我們應該強調封裝並允許物件之間進行狀態和行為的通訊。也許在不同的宇宙中,我們可以擁有「面向訊息的程式」。然而,OOP 這個名字已經經久不衰,而我們就在這裡! 我不知道你怎麼想,但是這個考慮範式的另一個可能名稱的簡單過程讓我的思維變得瘋狂,重新思考了一些概念,並實際上簡化了我建置軟體的方式。 什麼是類別以及我們如何以不同的方式思考它 -------------------- ![什麼是類](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/70x9cp26qi2cvx13dm3q.png) 我想每個人都聽過那個經典的講座,其中我們學到了“動物”類,其中包括“狗”類,對嗎?你可能聽過同樣的話(至少我聽過)。 > 類別是現實世界中實體的藍圖,描述其特徵和操作。 雖然不正確,但我想建議稍微改變一下單字的用法,以幫助澄清封裝,以便更好地理解,就像它對我所做的那樣。讓我們考慮以下新引文: > 類別是一種封裝狀態和在該狀態上操作的行為的方法。 這個簡單的字的改變確實讓我的思想改變了。我不再嘗試將類別視為現實世界的實體,而是開始簡單地將其視為將具有相似上下文的狀態分組在一起並公開對這些狀態進行操作的函數的另一種方式。我希望這個小小的改變也能幫助你回顧自己的概念! 以這種方式抽象化這個概念的重要性是,在從具有不同結構(例如模組)的語言中讀取程式碼時變得熟練。我們可以觀察到這段 OOP 程式碼是用 typescript 寫的: ``` class Github { private _url: string; privale _repo: string; private _username: string; constructor(url: string, repo: string, username: string) { this._repo = repo this._username = username this._url = url } public createRepo(name: string): void { // TODO: do stuff here using the provided state in _url, _repo and _username } } ``` 與此 Elixir 程式碼完全等效,即使 Elixir 程式碼使用“模組”而不是“類別”: ``` defmodule Github do @url "" @repo "" @username "" defstruct url: @url, repo: @repo, username: @username def new(url, repo, username) do %Github{url: url, repo: repo, username: username} end def create_repo(%Github{repo: repo, username: username}, name) do # TODO: do stuff here using the provided state in url, repo, and username end end ``` 接下來我們將研究一些功能概念並進一步討論這些範例的合併,讓我們開始吧! 變異還是不變異:什麼是不變性 -------------- ![不變性](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4fotff1cbifqi2c5ubtb.png) 現在我們正在達到第一個真正的功能概念,而且是一個非常重要的概念,我可以補充一下(一切都在這裡計劃)!為了正確理解不變性,讓我們回顧一下在程式設計中處理值的方式: 通常,我們將值綁定到變數,以便稍後可以對它們進行操作,對嗎?就像簡單的事情 ``` # Bounding values to variables name = 'Cherry' age = 23 # Operating on it and bounding to another variable year_born = Time.now.year - age # Printing it puts "#{name} has #{age} years old and was born at #{year_born}" ``` 對於這些變數,透過更新其值來更改原始變數是很常見的,但這裡缺少的是:修改變數是一種**破壞性**操作。 但為什麼?好吧,讓我們想像一下多個操作(函數或程式碼區塊)在不同時刻和頻率修改相同變數。在這種情況下,我們會產生很多問題,例如: - **1. 無法對操作重新排序或根本無法更改它們:**當我們有如此多的依賴程式碼時,甚至很難對程式碼進行重新排序或更改,因為所有內容都綁定到特定的更改順序。 - **2. 理解程式碼在做什麼的心理負擔:**雖然這是個人觀點,但我認為這是一個廣受認可的觀點。高度可變的程式碼很容易變得混亂且難以理解資料流,需要除錯器等工具來逐步完成轉換。 - **3. 測試時的困難:**模擬函數轉換的特定狀態確實很困難,這將逐漸擴展您的單元測試,直到它們不再是單元。 不變性可以定義為避免更改(或變異)程式內任何變數的做法。儘管根據語言的不同,我們可能需要做出讓步並改變一些控制變數,但這裡要學到的總體教訓是: > 我們應該不惜一切代價避免改變沒有定義範圍的變數。 透過這句話,我的意思是可以在函數內建立作用域變數並在那裡對其進行變異。然而,一旦您將這個可變變數傳遞給另一個函數,您就會增加改變相同變數的目標數量,並且您將慢慢失去控制。這正是我們想要避免的情況! 床底下的怪物:有什麼副作用 ------------- ![副作用](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yb1osy6ziacyc2l12h6v.png) 每當有人提出這個話題來討論時,這個話題就會引起很大的熱度。我可能不會涵蓋這個主題的每一個細微差別,但我一定會向您解釋它們是什麼以及我如何在我自己的軟體中管理副作用,好嗎? 那麼,副作用就是透過呼叫協定(HTTP、WebSocket、GraphQL 等)甚至操作 stdin/stdout 與外部資源(或「外部世界」)互動的每一次計算。是的,我知道,即使是我們無害的`print`也會在這裡受到指責。 😔 但與變異性不同的是,我們不應該盡可能避免使用它,而應該將其隔離在單獨處理副作用的特定函數中。這樣,我們將程式碼分為「不執行任何副作用的函數」和「執行副作用的函數」。但為什麼要擔心這種分離呢? 每次我們觸發對「外部世界」的任何操作時,我們都會失去對這個特定計算部分可能發生的情況的控制(例如在執行 HTTP 呼叫時,伺服器可能會關閉或可能根本不存在)。其他問題包括測試困難和程式碼可預測性降低。 由於我們無法編寫沒有副作用的任何現實世界軟體,因此一般建議是將其聚集成小函數,透過對錯誤的適當抽象來單獨處理它。這樣,就可以只測試我們 100% 控制的函數,並模擬所有執行副作用的函數。 例如,請考慮以下執行 HTTP 請求的函數以及轉換從該請求傳回的資料的小函數。 ``` require 'faraday' module MyServiceModule # This function perform side effects def perform_http_request conn = Faraday.new(url: "fakeapi.com") begin response = conn.get {ok: true, data: response.body} rescue => e {ok: false, error: e} end end # These functions doens't perform any side effects def upcase_name(name) return '' unless name.is_a?(String) name.upcase end def retrieve_born_year(age) return 0 unless age.is_a?(Integer) Time.now.year - age end end ``` > 看到我怎麼說「錯誤周圍的抽象」了嗎?這正是上面的程式碼範例中實現的,而不是讓異常在我們針對雜湊抽象的程式碼中冒泡。 在使用「副作用」和「無副作用」之間的明確定義來定義這些函數之後,很容易預測程式碼中會發生什麼,也更容易測試,如下所示: ``` require 'minitest/autorun' class TestingStuff < Minitest::Test def test_upcase_name assert_equal MyServiceModule.upcase_name "cherry", "CHERRY" assert_equal MyServiceModule.upcase_name "kalane", "KALANE" assert_equal MyServiceModule.upcase_name "Thales", "THALES" end def test_retrieve_born_year Time.stub :now, Time.new(2024, 3, 5) do assert_equal MyServiceModule.retrieve_born_year 23, 2001 assert_equal MyServiceModule.retrieve_born_year 20, 2004 assert_equal MyServiceModule.retrieve_born_year 14, 2010 end end end ``` 這個策略真的很棒,因為您甚至不需要在測試時擔心副作用部分,只需為實際執行某些操作的程式碼轉換部分編寫斷言,您最終會得到更好的測試,真正驗證重要的內容您的程式碼庫的一部分!整齊吧? 隔離一切:什麼是純函數 ----------- ![純函數](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bgnpfyig36sssuio9qpy.png) 現在是時候總結到目前為止所獲得的所有知識了。在前面的範例中,我們觀察到程式碼分為「副作用」和「無副作用」。我們還看到了這些功能如何更容易測試,並且我們的主要轉換業務邏輯應該保持隔離。您想知道這些函數叫什麼嗎?它們是**純函數**! 讓我們檢查純函數的正確形式定義並逐步探索這個概念。 > 純函數是尊重不變性、不執行任何副作用並且在給定相同參數的情況下傳回相同輸出的函數。 基本上,純函數遵循我們之前提到的所有原則,而且它們總是為相同的參數產生相同的返回。讓我們來看看之前的函數。 ``` def upcase_name(name) return '' unless name.is_a?(String) name.upcase end upcase_name('cherry') # => Will be *always* CHERRY ``` 使用純函數,我們可以輕鬆定義多個斷言,因為我們不受任何需要大量模擬的上下文的約束。我們只需用靜態值傳遞所需的參數,就這樣! 由於純函數非常小且可組合,因此它們的數量增加得非常快。為了解決這個問題,像 Elixir 這樣的函數式語言提供了像管道這樣的組合運算符,這使得按順序執行多個純函數變得非常容易。 ``` "cherry " |> trim |> upcase # => "CHERRY" ``` > 管道運算子源自 Bash 等函數。您可以在這裡閱讀更多相關資訊:\[ <https://dev.to/cherryramatis/linux-filters-how-to-streamline-text-like-a-boss-2dp4#what-is-a-pipeline> \] 使用函數式模式而不需要完整的 haskell ---------------------- ![都是功能啊](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/42ndx4tuvrs35q2woepg.png) 我一直害怕學習函數範式,因為社群透過使用現成的句子和大概念讓每個試圖學習一些小技巧的人變得非常複雜。在掌握了許多函數式語言並嘗試盡可能多地學習之後,我的目標是簡化這些概念,最重要的是,提倡在 OOP 程式碼中使用函數式概念。 應用純函數(或純方法,如果您願意)、不變性和副作用分離可以使您的 OOP 程式碼看起來更乾淨和解耦。你不需要知道什麼是 monad 或如何在 Haskell 中手動編寫編譯器;您可以使用簡單而有效的函數概念來堅持使用 Ruby on Rails! 我希望透過這篇小文章(以及本系列中的文章),無論您選擇哪種語言和框架,您都可以透過可組合性和簡單性來改進您的程式碼庫。 結論 -- 這篇文章是我嘗試使函數範式的知識民主化(在我的能力和專業知識範圍內)。需要強調的是,我不是函數式專家,本文針對的是了解 OOP 並對函數式程式設計感興趣的初學者。我希望它有用,並且我願意提供任何需要的幫助。願原力與你同在🍒 --- 原文出處:https://dev.to/cherryramatis/ending-the-war-or-continuing-it-lets-bring-functional-programming-to-oop-codebases-3mhd

100 多個專案創意

**編輯**:大家好!在對本文做出驚人反應後,我建立了一個名為「每週專案俱樂部」的專案。每週您的收件匣都會收到需要解決的問題。你可以努力解決問題,並且你將得到整個俱樂部的幫助,讓你走上正軌。了解更多並[在這裡](https://weeklyproject.club)註冊! 有一天我注意到一個模式。我注意到很多人都在努力 學習編程,但他們心中沒有特定的目標。我已經討論過如何了解您想要學習程式設計的原因可以幫助您選擇要學習的語言[!](https://pickaframework.com/articles/why/) ,以及如何實際做出決定([在這裡!](https://pickaframework.com/feature_fishing/) )但是專案有什麼幫助呢? 當我指導程式設計師時,我發現有一個專案可以幫助排除其他一些幹擾,例如想知道你是否使用了正確的語言。透過專注於一個特定的目標,你就不用那麼費力去擔心*這*是否正是你應該使用的語言。結果是你建立了一些簡潔的東西,並且一路上你學到了一些東西! 2隻鳥,1塊石頭。 這就是為什麼我為初學者程式設計師策劃了這個專案清單。許多人列出了大量的專案來學習編程,但很少按照難度進行組織。我瀏覽了幾個流行的程式設計專案想法清單。如果您想查看完整列表,可以在頁面底部找到來源。 我將其分為教程和想法。教程包含資源連結,而想法只是專案的一般描述。我還列出了我最喜歡的初學者清單。 看看,看看是否有什麼啟發你! 教學 == 我的最愛 ---- - [透過 30 個教學在 30 天內建立 30 個東西](https://javascript30.com) - [在 30 分鐘內建立一個簡單的搜尋機器人](https://medium.freecodecamp.org/how-to-build-a-simple-search-bot-in-30-minutes-eb56fcedcdb1) - [使用 Xamarin 和 Visual Studio 建立 iOS 照片庫應用程式](https://www.raywenderlich.com/134049/building-ios-apps-with-xamarin-and-visual-studio) - [建立 Android 手電筒應用程式](https://www.youtube.com/watch?v=dhWL4DC7Krs)(影片) - [製作聊天應用程式](https://medium.freecodecamp.org/how-to-build-a-chat-application-using-react-redux-redux-saga-and-web-sockets-47423e4bc21a) - [使用 React Native 建立 ToDo 應用程式](https://blog.hasura.io/tutorial-fullstack-react-native-with-graphql-and-authentication-18183d13373a) 簡單的 --- - [使用 C# 和 Xamarin 建立空白應用程式(正在進行中)](https://www.intertech.com/Blog/xamarin-tutorial-part-1-create-a-blank-app/) - [使用 Xamarin 和 Visual Studio 建立 iOS 照片庫應用程式](https://www.raywenderlich.com/134049/building-ios-apps-with-xamarin-and-visual-studio) - [建立加載畫面](https://medium.freecodecamp.org/how-to-build-a-delightful-loading-screen-in-5-minutes-847991da509f) - [使用 JS 建立 HTML 計算器](https://medium.freecodecamp.org/how-to-build-an-html-calculator-app-from-scratch-using-javascript-4454b8714b98) - [建立 React Native Todo 應用程式](https://egghead.io/courses/build-a-react-native-todo-application) - 使用 Node.js 編寫 Twitter 機器人 ``` - [Part 1](https://codeburst.io/build-a-simple-twitter-bot-with-node-js-in-just-38-lines-of-code-ed92db9eb078) ``` ``` - [Part 2](https://codeburst.io/build-a-simple-twitter-bot-with-node-js-part-2-do-more-2ef1e039715d) ``` - [建立一個簡單的 RESTFUL Web 應用程式](https://closebrace.com/tutorials/2017-03-02/creating-a-simple-restful-web-app-with-nodejs-express-and-mongodb) - [在 30 分鐘內建立一個簡單的搜尋機器人](https://medium.freecodecamp.org/how-to-build-a-simple-search-bot-in-30-minutes-eb56fcedcdb1) - [建立一個工作抓取 Web 應用程式](https://medium.freecodecamp.org/how-i-built-a-job-scraping-web-app-using-node-js-and-indreed-7fbba124bbdc) - [使用 Python 挖掘 Twitter 資料](https://marcobonzanini.com/2015/03/02/mining-twitter-data-with-python-part-1/) - [使用 Scrapy 和 MongoDB 抓取網站](https://realpython.com/blog/python/web-scraping-with-scrapy-and-mongodb/) - [如何使用 Python 和 Selenium WebDriver 進行抓取](http://www.byperth.com/2018/04/25/guide-web-scraping-101-what-you-need-to-know-and-how-to-scrape-with-python-selenium-webdriver/) - [我應該使用 BeautifulSoup 觀看哪部電影](https://medium.com/@nishantsahoo.in/which-movie-should-i-watch-5c83a3c0f5b1) - [使用 Flask 建立微博](https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world) - 在 Django 中建立部落格 Web 應用程式 ``` - [Part I : Introduction](https://tutorial.djangogirls.org/en/) ``` ``` - [Part II : Extension To Add More Features](https://legacy.gitbook.com/book/djangogirls/django-girls-tutorial-extensions/details) ``` - [選擇您自己的冒險演示](https://www.twilio.com/blog/2015/03/choose-your-own-adventures-presentations-wizard-mode-part-1-of-3.html) - [使用 Flask 和 RethinkDB 建立待辦事項列表](https://realpython.com/blog/python/rethink-flask-a-simple-todo-list-powered-by-flask-and-rethinkdb/) 中等的 --- - [透過建立簡單的 RPG 遊戲來學習 C#](http://scottlilly.com/learn-c-by-building-a-simple-rpg-index/) - [用 C# 創作 Rogue-like 遊戲](https://roguesharp.wordpress.com/) - [使用 Clojure 建構 Twitter 機器人](http://howistart.org/posts/clojure/1/index.html) - [建立拼字檢查器](https://bernhardwenzel.com/articles/clojure-spellchecker/) - [使用 Java 建立簡單的 HTTP 伺服器](http://javarevisited.blogspot.com/2015/06/how-to-create-http-server-in-java-serversocket-example.html) - [建立 Android 手電筒應用程式](https://www.youtube.com/watch?v=dhWL4DC7Krs)(影片) - [建立具有使用者身份驗證的 Spring Boot 應用程式](https://scotch.io/tutorials/build-a-spring-boot-app-with-user-authentication) - [透過 30 個教學在 30 天內建立 30 個東西](https://javascript30.com) - [使用純 JS 建立應用程式](https://medium.com/codingthesmartway-com-blog/pure-javascript-building-a-real-world-application-from-scratch-5213591cfcd6) - [建立無伺服器 React.js 應用程式](http://serverless-stack.com/) - [建立 Trello 克隆](http://codeloveandboards.com/blog/2016/01/04/trello-tribute-with-phoenix-and-react-pt-1/) - [使用 React、Node、MongoDB 和 SocketIO 建立角色投票應用程式](http://sahatyalkabov.com/create-a-character-voting-app-using-react-nodejs-mongodb-and-socketio/) - [React 教學:克隆 Yelp](https://www.fullstackreact.com/articles/react-tutorial-cloning-yelp/) - [使用 React.js 和 Node.js 建立簡單的中型克隆](https://codeburst.io/build-simple-medium-com-on-node-js-and-react-js-a278c5192f47) - [在 JS 中整合 MailChimp](https://medium.freecodecamp.org/how-to-integrate-mailchimp-in-a-javascript-web-app-2a889fb43f6f) - [使用 React Native 建立 ToDo 應用程式](https://blog.hasura.io/tutorial-fullstack-react-native-with-graphql-and-authentication-18183d13373a) - [製作聊天應用程式](https://medium.freecodecamp.org/how-to-build-a-chat-application-using-react-redux-redux-saga-and-web-sockets-47423e4bc21a) - [使用 React Native 建立新聞應用程式](https://medium.freecodecamp.org/create-a-news-app-using-react-native-ced249263627) - [學習 React 的 Webpack](https://medium.freecodecamp.org/learn-webpack-for-react-a36d4cac5060) - [建立您自己的 React 樣板](https://medium.freecodecamp.org/how-to-build-your-own-react-boilerplate-2f8cbbeb9b3f) - [基本 React+Redux 入門教學](https://hackernoon.com/a-basic-react-redux-introductory-tutorial-adcc681eeb5e) - [建立一個預約安排程序](https://hackernoon.com/build-an-appointment-scheduler-using-react-twilio-and-cosmic-js-95377f6d1040) - 使用 Angular 2+ 建立具有離線功能的 Hacker News 用戶端 ``` - [Part 1](https://houssein.me/angular2-hacker-news) ``` ``` - [Part 2](https://houssein.me/progressive-angular-applications) ``` - 帶有 Angular 5 的 ToDo 應用程式 ``` - [Introduction to Angular](http://www.discoversdk.com/blog/intro-to-angular-and-the-evolution-of-the-web) ``` ``` - [Part 1](http://www.discoversdk.com/blog/angular-5-to-do-list-app-part-1) ``` - 帶有 Angular 5 的 ToDo 應用程式 ``` - [Introduction to Angular](http://www.discoversdk.com/blog/intro-to-angular-and-the-evolution-of-the-web) ``` ``` - [Part 1](http://www.discoversdk.com/blog/angular-5-to-do-list-app-part-1) ``` 難的 -- - [建構一個解釋器](http://www.craftinginterpreters.com/)(第 14 章是用 C 寫的) - [用 C 語言寫一個 Shell](https://brennan.io/2015/01/16/write-a-shell-in-c/) - [編寫 FUSE 文件系統](https://www.cs.nmsu.edu/~pfeiffer/fuse-tutorial/) - [建立您自己的文字編輯器](http://viewsourcecode.org/snaptoken/kilo/) - [建立自己的 Lisp](http://www.buildyourownlisp.com/) - [建構 CoreWiki](https://www.youtube.com/playlist?list=PLVMqA0_8O85yC78I4Xj7z48ES48IQBa7p)這是一個 Wiki 風格的內容管理系統,完全用 C# 使用 ASP.NET Core 和 Razor Pages 編寫。您可以[在這裡](https://github.com/csharpfritz/CoreWiki)找到原始程式碼。 - [建構 JIRA 與 Clojure 和 Atlassian Connect 的集成](https://hackernoon.com/building-a-jira-integration-with-clojure-atlassian-connect-506ebd112807) - [建構一個解釋器](http://www.craftinginterpreters.com/)(第 4-13 章是用 Java 寫的) - [使用 Mocha、React、Redux 和 Immutable 透過測試優先開發來建立全端電影投票應用程式](https://teropa.info/blog/2015/09/10/full-stack-redux-tutorial.html) - [使用 React 和 Node 建立 Twitter Stream](https://scotch.io/tutorials/build-a-real-time-twitter-stream-with-node-and-react-js) - 使用 Webtask.io 建立無伺服器 MERN Story 應用程式 ``` - [Part 1](https://scotch.io/tutorials/build-a-serverless-mern-story-app-with-webtask-io-zero-to-deploy-1) ``` ``` - [Part 2](https://scotch.io/tutorials/build-a-serverless-mern-story-app-with-webtask-io-zero-to-deploy-2) ``` - [使用 React + Parcel 建立 Chrome 擴充功能](https://medium.freecodecamp.org/building-chrome-extensions-in-react-parcel-79d0240dd58f) ``` [Testing React App With Pupepeteer and Jest](https://blog.bitsrc.io/testing-your-react-app-with-puppeteer-and-jest-c72b3dfcde59) ``` - [用 React 編寫生命遊戲](https://medium.freecodecamp.org/create-gameoflife-with-react-in-one-hour-8e686a410174) - [建立帶有情感分析的聊天應用程式](https://codeburst.io/build-a-chat-app-with-sentiment-analysis-using-next-js-c43ebf3ea643) - [建立全端 Web 應用程式設置](https://hackernoon.com/full-stack-web-application-using-react-node-js-express-and-webpack-97dbd5b9d708) - 建立隨機報價機 ``` - [Part 1](https://www.youtube.com/watch?v=3QngsWA9IEE) ``` ``` - [Part 2](https://www.youtube.com/watch?v=XnoTmO06OYo) ``` ``` - [Part 3](https://www.youtube.com/watch?v=us51Jne67_I) ``` ``` - [Part 4](https://www.youtube.com/watch?v=iZx7hqHb5MU) ``` ``` - [Part 5](https://www.youtube.com/watch?v=lpba9vBqXl0) ``` ``` - [Part 6](https://www.youtube.com/watch?v=Jvp8j6zrFHE) ``` ``` - [Part 7](https://www.youtube.com/watch?v=M_hFfrN8_PQ) ``` - 使用 Angular 6 建立美麗的現實世界應用程式: ``` - [Part I](https://medium.com/@hamedbaatour/build-a-real-world-beautiful-web-app-with-angular-6-a-to-z-ultimate-guide-2018-part-i-e121dd1d55e) ``` - [使用 BootStrap 4 和 Angular 6 建立響應式佈局](https://medium.com/@tomastrajan/how-to-build-responsive-layouts-with-bootstrap-4-and-angular-6-cfbb108d797b) - [使用 Django 和測試驅動開發建立待辦事項列表](http://www.obeythetestinggoat.com/) - [使用 Python 建立 RESTful 微服務](http://www.skybert.net/python/developing-a-restful-micro-service-in-python/) - [使用 Docker、Flask 和 React 的微服務](https://testdriven.io/) - [使用 Flask 建立簡單的 Web 應用程式](https://pythonspot.com/flask-web-app-with-python/) - [使用 Flask 建立 RESTful API – TDD 方式](https://scotch.io/tutorials/build-a-restful-api-with-flask-the-tdd-way) - [在 20 分鐘內建立 Django API](https://codeburst.io/create-a-django-api-in-under-20-minutes-2a082a60f6f3) 想法 == 簡單的 --- ### 99 瓶 - 建立一個程序,列印歌曲“牆上的 99 瓶啤酒”的每一行。 - 不要使用所有數字的列表,也不要手動輸入所有數字。請改用內建函數。 - 除了短語“取下一個”之外,您不得直接在歌詞中輸入任何數字/數字名稱。 - 請記住,當您還剩下 1 瓶時,「瓶子」一詞將變為單數。 ### 魔術8球 - 模擬神奇的 8 球。 - 允許使用者輸入他們的問題。 - 顯示正在進行的訊息(即“思考”)。 - 建立 20 個回應,並顯示隨機回應。 - 允許用戶提出另一個問題或退出。 - 獎金: ``` - Add a gui. ``` ``` - It must have a box for users to enter the question. ``` ``` - It must have at least 4 buttons: ``` ``` - ask ``` ``` - clear (the text box) ``` ``` - play again ``` ``` - quit (this must close the window) ``` ### 石頭剪刀布遊戲 - 建立一個石頭剪刀布遊戲。 - 讓玩家選擇石頭、剪刀或布。 - 讓計算機選擇它的移動方式。 - 比較選擇並決定誰獲勝。 - 列印結果。 - 子目標: ``` - Give the player the option to play again. ``` ``` - Keep a record of the score (e.g. Player: 3 / Computer: 6). ``` ### 倒數時鐘 - 建立一個程序,允許使用者選擇時間和日期,然後以給定的時間間隔(例如每秒)列印一條訊息,告訴使用者距離所選時間還有多長時間。 - 子目標: ``` - If the selected time has already passed, have the program tell the user to start over. ``` ``` - If your program asks for the year, month, day, hour, etc. separately, allow the user to be able to type in either the month name or its number. ``` ``` - TIP: Making use of built in modules such as time and datetime can change this project from a nightmare into a much simpler task. ``` 中等的 --- ### 番茄計時器 建立一個番茄計時器。 番茄計時器是一種時間管理方法。該技術使用計時器將工作分解為多個時間間隔,通常長度為 25 分鐘,中間間隔短暫的休息。這些間隔被命名為“pomodoros”,是意大利語單字“pomodoro”(番茄)的英文複數形式,以西里洛在大學時使用的番茄形狀的廚房計時器命名。 原始技巧有六個步驟: 決定要完成的任務。 設定番茄計時器(傳統上為 25 分鐘)。 完成任務。 當計時器響起時結束工作並在一張紙上畫上複選標記。 如果您的複選標記少於四個,請短暫休息(3-5 分鐘),然後轉到步驟 2。 四個番茄鐘後,休息較長時間(15-30 分鐘),將複選標記計數重設為零,然後轉到步驟 1。 要了解有關番茄計時器的更多訊息[,請單擊此處](https://en.wikipedia.org/wiki/Pomodoro_Technique) ### 谷歌案例 - 這是一個可以讓你玩英文句子的遊戲。 - 使用者將以任何格式輸入一個句子。(大寫或小寫或兩者的混合) - 程式必須將給定的句子轉換為Google大小寫。什麼是Google大小寫句子風格?\[know\_about\_it\_here:\](這是一種寫作風格,我們將所有小寫字母替換為大寫字母,留下所有單字的首字母)。 - 子目標: ``` - Program must then convert the given sentence in camel case.To know more about camel case ``` ``` [click_here](https://en.wikipedia.org/wiki/Camel_case) ``` ``` - Sentence can be entered with any number of spaces. ``` ### 擲骰子模擬器 - 允許使用者輸入骰子的面數以及應擲骰子的次數。 - 您的程式應該模擬擲骰子並追蹤每個數字出現的次數(這不必顯示)。 - 最後,列印出每個數字出現的次數。 - 子目標: ``` - Adjust your program so that if the user does not type in a number when they need to, the program will keep prompting them to type in a real number until they do so. ``` ``` - Put the program into a loop so that the user can continue to simulate dice rolls without having to restart the entire program. ``` ``` - In addition to printing out how many times each side appeared, also print out the percentage it appeared. If you can, round the percentage to 4 digits total OR two decimal places. ``` - 獎金: ``` - You are about to play a board game, but you realize you don't have any dice. Fortunately you have this program. ``` ``` - 1. Create a program that opens a new window and draws 2 six-sided dice ``` ``` - 2. Allow the user to quit, or roll again ``` ``` - Allow the user to select the number of dice to be drawn on screen(1-4) 2. Add up the total of the dice and display it ``` ### 計算並修復綠雞蛋和火腿 你們有些人可能還記得蘇博士的故事「綠雞蛋和火腿」。對於那些不記得或從未聽說過的人,[這](http://pastebin.com/XMY48CnN)是這個故事。然而,我給你的故事有一個問題——每次使用「我」這個詞時,它都是小寫的。 由於此問題,您的工作是執行以下操作: - 將我給您的故事複製到常規文字檔案中。 - 建立一個程式來通讀故事並在任何時候將字母 i 變為大寫。 (當它也用在 sam-I-am 的名字中時,請務必更改它。) - 讓你的程式建立一個新文件,並讓它正確地寫出故事。 - 印出有多少錯誤被修正。 - 完成後,您應該已經糾正了[這麼多](https://i.imgur.com/GRkj3yz.jpg)錯誤。 難的 -- ### 隨機維基百科文章 如果您曾造訪維基百科,您可能已經注意到螢幕左側有一個指向隨機文章的連結。雖然看到您被帶到哪篇文章可能很有趣,但有時看到文章的名稱會很好,這樣您就可以在聽起來很無聊時跳過它。幸運的是,維基百科有一個 API,允許我們這樣做[點擊這裡](https://en.wikipedia.org/w/api.php?action=query&list=random&rnnamespace=0&rnlimit=10&format=json)。 然而,有一個困境。由於維基百科擁有有關世界各地主題的文章,其中一些文章的標題中包含特殊字元。例如,關於西班牙畫家[埃拉斯托·科爾特斯·華雷斯 (Erasto Cortés Juárez)](https://en.wikipedia.org/wiki/Erasto_Cort%C3%A9s_Ju%C3%A1rez)的文章中就有 é 和 á。如果您查看這篇特定文章的[API](https://en.wikipedia.org/w/api.php?action=query&prop=info&pageids=39608394&inprop=url&format=json) ,您將看到標題是“Erasto Cort\\u00e9s Ju\\u00e1rez”,並且 \\u00e9 和 \\u00e1 正在替換前面提到的兩個字母。 (有關這是什麼的訊息,請首先查看文件中[本頁](https://docs.python.org/2/howto/unicode.html)的前半部分)。為了讓你的程式正常運作,你必須以某種方式處理這個問題。 - 建立一個程序,從官方維基百科 API 中提取標題,然後一一詢問用戶是否願意閱讀該文章。 - 例子: ``` - If the first title is Reddit, then the program should ask something along the lines of "Would you like to read about Reddit?" If the user says yes, then the program should open up the article for the user to read. ``` ``` - HINT: Click [here](https://en.wikipedia.org/wiki?curid=39608394) to see how the article's ID can be used to access the actual article. ``` - 子目標: ``` - As mentioned before, do something about the possibility of unicode appearing in the title. ``` ``` - Whether you want your program to simply filter out these articles or you want to actually turn the codes into readable characters, that's up to you. ``` ``` - Make the program pause once the user has selected an article to read, and allow him or her to continue browsing different article titles once finished reading. ``` ``` - Allow the user to simply press ENTER to be asked about a new article. ``` ### 天氣如何? 如果您想了解 API 的基礎知識,請查看 iamapizza 的[這篇](http://www.reddit.com/r/explainlikeimfive/comments/qowts/eli5_what_is_api/c3z9kok)文章。 - 建立一個程序,從 OpenWeatherMap.org 提取資料並列印有關當前天氣的訊息,例如您居住的地方的最高氣溫、最低氣溫和雨量。 - 子目標: ``` - Print out data for the next 5-7 days so you have a 5 day/week long forecast. ``` ``` - Print the data to another file that you can open up and view at, instead of viewing the information in the command line. ``` ``` - If you know html, write a file that you can print information to so that your project is more interesting. ``` - 尖端: ``` - APIs that are in Json are essentially lists and dictionaries. Remember that to reference something in a list, you must refer to it by what number element it is in the list, and to reference a key in a dictionary, you must refer to it by its name. ``` ``` - Don't like Celsius? Add &units=imperial to the end of the URL of the API to receive your data in Fahrenheit. ``` ### 來源 - https://github.com/tuvtran/project-based-learning - https://github.com/jorgegonzalez/beginner-projects - https://github.com/MunGell/awesome-for-beginners/blob/master/README.md - https://github.com/sarahbohr/AbsoluteBeginnerProjects --- 你怎麼認為?您喜歡透過特定專案進行學習還是不喜歡透過特定專案進行學習? --- 原文出處:https://dev.to/samborick/100-project-ideas-oda

我正在建立一個全端應用程式:以下是我將要使用的庫......

您可以使用無數的框架和函式庫來改進您的全端應用程式。 我們將介紹令人興奮的概念,例如應用程式內通知、使用 React 製作影片、從為開發人員提供的電子郵件 API 到在瀏覽器中建立互動式音樂。 那我們就開始吧。 (不要忘記為這些庫加註星標以表示您的支持)。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qqoipyuoxgb83swyoo4a.gif) https://github.com/CopilotKit/CopilotKit --- 1. [CopilotKit](https://github.com/CopilotKit/CopilotKit) - 在數小時內為您的產品提供 AI Copilot。 ------------------------------------------------------------------------------------ ![副駕駛套件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nzuxjfog2ldam3csrl62.png) 您可以使用兩個 React 元件將關鍵 AI 功能整合到 React 應用程式中。它們還提供內建(完全可自訂)Copilot 原生 UX 元件,例如`<CopilotKit />` 、 `<CopilotPopup />` 、 `<CopilotSidebar />` 、 `<CopilotTextarea />` 。 開始使用以下 npm 指令。 ``` npm i @copilotkit/react-core @copilotkit/react-ui @copilotkit/react-textarea ``` 這是整合 CopilotTextArea 的方法。 ``` import { CopilotTextarea } from "@copilotkit/react-textarea"; import { useState } from "react"; export function SomeReactComponent() { const [text, setText] = useState(""); return ( <> <CopilotTextarea className="px-4 py-4" value={text} onValueChange={(value: string) => setText(value)} placeholder="What are your plans for your vacation?" autosuggestionsConfig={{ textareaPurpose: "Travel notes from the user's previous vacations. Likely written in a colloquial style, but adjust as needed.", chatApiConfigs: { suggestionsApiConfig: { forwardedParams: { max_tokens: 20, stop: [".", "?", "!"], }, }, }, }} /> </> ); } ``` 您可以閱讀[文件](https://docs.copilotkit.ai/getting-started/quickstart-textarea)。 基本概念是在幾分鐘內建立可用於基於 LLM 的全端應用程式的 AI 聊天機器人。 https://github.com/CopilotKit/CopilotKit --- 2. [Storybook](https://github.com/storybookjs/storybook) - UI 開發、測試和文件變得簡單。 --------------------------------------------------------------------------- ![故事書](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/78rfum1ydisn51qhb408.png) Storybook 是一個用於獨立建立 UI 元件和頁面的前端工作坊。它有助於 UI 開發、測試和文件編制。 他們在 GitHub 上有超過 57,000 次提交、81,000 多個 star 和 1300 多個版本。 這是您為專案建立簡單元件的方法。 ``` import type { Meta, StoryObj } from '@storybook/react'; import { YourComponent } from './YourComponent'; //👇 This default export determines where your story goes in the story list const meta: Meta<typeof YourComponent> = { component: YourComponent, }; export default meta; type Story = StoryObj<typeof YourComponent>; export const FirstStory: Story = { args: { //👇 The args you need here will depend on your component }, }; ``` 您可以閱讀[文件](https://storybook.js.org/docs/get-started/setup)。 如今,UI 除錯起來很痛苦,因為它們與業務邏輯、互動狀態和應用程式上下文糾纏在一起。 Storybook 提供了一個獨立的 iframe 來渲染元件,而不會受到應用程式業務邏輯和上下文的干擾。這可以幫助您將開發重點放在元件的每個變體上,甚至是難以觸及的邊緣情況。 https://github.com/storybookjs/storybook --- 3. [Appwrite](https://github.com/appwrite/appwrite) - 您的後端減少麻煩。 --------------------------------------------------------------- ![應用程式寫入](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8x568uz21seyygw6b72z.png) ![帶有 appwrite 的 sdk 列表](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cp7k8qnamsluto7eifpl.png) Appwrite 的開源平台可讓您將身份驗證、資料庫、函數和儲存體新增至您的產品中,並建立任何規模的任何應用程式、擁有您的資料並使用您喜歡的編碼語言和工具。 他們有很好的貢獻指南,甚至不厭其煩地詳細解釋架構。 開始使用以下 npm 指令。 ``` npm install appwrite ``` 您可以像這樣建立一個登入元件。 ``` "use client"; import { useState } from "react"; import { account, ID } from "./appwrite"; const LoginPage = () => { const [loggedInUser, setLoggedInUser] = useState(null); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [name, setName] = useState(""); const login = async (email, password) => { const session = await account.createEmailSession(email, password); setLoggedInUser(await account.get()); }; const register = async () => { await account.create(ID.unique(), email, password, name); login(email, password); }; const logout = async () => { await account.deleteSession("current"); setLoggedInUser(null); }; if (loggedInUser) { return ( <div> <p>Logged in as {loggedInUser.name}</p> <button type="button" onClick={logout}> Logout </button> </div> ); } return ( <div> <p>Not logged in</p> <form> <input type="email" placeholder="Email" value={email} onChange={(e) => setEmail(e.target.value)} /> <input type="password" placeholder="Password" value={password} onChange={(e) => setPassword(e.target.value)} /> <input type="text" placeholder="Name" value={name} onChange={(e) => setName(e.target.value)} /> <button type="button" onClick={() => login(email, password)}> Login </button> <button type="button" onClick={register}> Register </button> </form> </div> ); }; export default LoginPage; ``` 您可以閱讀[文件](https://appwrite.io/docs)。 Appwrite 可以非常輕鬆地建立具有開箱即用的擴充功能的可擴展後端應用程式。 https://github.com/appwrite/appwrite --- 4. [Wasp](https://github.com/wasp-lang/wasp) - 用於 React、node.js 和 prisma 的類似 Rails 的框架。 --------------------------------------------------------------------------------------- ![黃蜂](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fi2mwazueoc3ezjx8a9q.png) 使用 React 和 Node.js 開發全端 Web 應用程式的最快方法。這不是一個想法,而是一種建立瘋狂快速全端應用程式的不同方法。 這是將其整合到元件中的方法。 ``` import getRecipes from "@wasp/queries/getRecipes"; import { useQuery } from "@wasp/queries"; import type { User } from "@wasp/entities"; export function HomePage({ user }: { user: User }) { // Due to full-stack type safety, `recipes` will be of type `Recipe[]` here. const { data: recipes, isLoading } = useQuery(getRecipes); // Calling our query here! if (isLoading) { return <div>Loading...</div>; } return ( <div> <h1>Recipes</h1> <ul> {recipes ? recipes.map((recipe) => ( <li key={recipe.id}> <div>{recipe.title}</div> <div>{recipe.description}</div> </li> )) : 'No recipes defined yet!'} </ul> </div> ); } ``` 您可以閱讀[文件](https://wasp-lang.dev/docs)。 https://github.com/wasp-lang/wasp --- 5. [Novu](https://github.com/novuhq/novu) - 將應用程式內通知新增至您的應用程式! -------------------------------------------------------------- ![再次](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/716b7biilet4auudjlcu.png) Novu 提供開源通知基礎架構和功能齊全的嵌入式通知中心。 這就是如何使用`React`建立 novu 元件以用於應用程式內通知。 ``` import { NovuProvider, PopoverNotificationCenter, NotificationBell, } from "@novu/notification-center"; function App() { return ( <> <NovuProvider subscriberId={process.env.REACT_APP_SUB_ID} applicationIdentifier={process.env.REACT_APP_APP_ID} > <PopoverNotificationCenter> {({ unseenCount }) => <NotificationBell unseenCount={unseenCount} />} </PopoverNotificationCenter> </NovuProvider> </> ); } export default App; ``` 您可以閱讀[文件](https://docs.novu.co/getting-started/introduction)。 https://github.com/novuhq/novu --- 6. [Remotion](https://github.com/remotion-dev/remotion) - 使用 React 以程式設計方式製作影片。 ------------------------------------------------------------------------------- ![遠端](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wmnrxhsc7b9mm5oagflm.png) 使用 React 建立真正的 MP4 影片,使用伺服器端渲染和參數化擴展影片製作。 開始使用以下 npm 指令。 ``` npm init video ``` 它為您提供了一個幀號和一個空白畫布,您可以在其中使用 React 渲染任何您想要的內容。 這是一個範例 React 元件,它將當前幀渲染為文字。 ``` import { AbsoluteFill, useCurrentFrame } from "remotion";   export const MyComposition = () => { const frame = useCurrentFrame();   return ( <AbsoluteFill style={{ justifyContent: "center", alignItems: "center", fontSize: 100, backgroundColor: "white", }} > The current frame is {frame}. </AbsoluteFill> ); }; ``` 您可以閱讀[文件](https://www.remotion.dev/docs/)。 過去兩年,remotion 團隊因製作 GitHub Wrapped 而聞名。 https://github.com/remotion-dev/remotion --- [7.NocoDB](https://github.com/nocodb/nocodb) - Airtable 的替代品。 ------------------------------------------------------------- ![諾科資料庫](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iw3tchfgyzehye5c39xq.png) Airtable 的免費開源替代品是 NocoDB。它可以使用任何 MySQL、PostgreSQL、SQL Server、SQLite 或 MariaDB 資料庫製作智慧型電子表格。 其主要目標是讓強大的計算工具得到更廣泛的使用。 開始使用以下 npx 指令。 ``` npx create-nocodb-app ``` 您可以閱讀[文件](https://docs.nocodb.com/)。 NocoDB 的建立是為了為世界各地的數位企業提供強大的開源和無程式碼資料庫介面。 您可以非常快速地將airtable資料匯入NocoDB。 https://github.com/nocodb/nocodb --- 8.[新穎](https://github.com/steven-tey/novel)- 所見即所得編輯器,具有人工智慧自動完成功能。 ------------------------------------------------------------------- ![小說](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uo34vd9twpxcpbpzgchi.png) 它使用`Next.js` 、 `Vercel AI SDK` 、 `Tiptap`作為文字編輯器。 開始使用以下 npm 指令。 ``` npm i novel ``` 您可以這樣使用它。有多種選項可用於改進您的應用程式。 ``` import { Editor } from "novel"; export default function App() { return <Editor />; } ``` https://github.com/steven-tey/novel --- 9. [Blitz](https://github.com/blitz-js/blitz) - 缺少 NextJS 的全端工具包。 ----------------------------------------------------------------- ![閃電戰](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vz6ineg1o7xyv7pwbuqn.png) Blitz 繼承了 Next.js 的不足,為全球應用程式的交付和擴展提供了經過實戰考驗的函式庫和約定。 開始使用以下 npm 指令。 ``` npm install -g blitz ``` 這就是您如何使用 Blitz 建立新頁面。 ``` const NewProjectPage: BlitzPage = () => { const router = useRouter() const [createProjectMutation] = useMutation(createProject) return ( <div> <h1>Create New Project</h1> <ProjectForm submitText="Create Project" schema={CreateProject} onSubmit={async (values) => { // This is equivalent to calling the server function directly const project = await createProjectMutation(values) // Notice the 'Routes' object Blitz provides for routing router.push(Routes.ProjectsPage({ projectId: project.id })) }} /> </div> ); }; NewProjectPage.authenticate = true NewProjectPage.getLayout = (page) => <Layout>{page}</Layout> export default NewProjectPage ``` 您可以閱讀[文件](https://blitzjs.com/docs/get-started)。 它使建築物改善了數倍。 ![閃電戰](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cc4mb5wdksjv1ybx71co.png) https://github.com/blitz-js/blitz --- 10. [Supabase](https://github.com/supabase/supabase) - 開源 Firebase 替代品。 ----------------------------------------------------------------------- ![蘇帕貝斯](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ksfygjhrzhmsg9cnvobs.png) 我們大多數人都已經預料到 SUPABASE 會出現在這裡,因為它實在是太棒了。 開始使用以下 npm 指令 (Next.js)。 ``` npx create-next-app -e with-supabase ``` 這是使用 supabase 建立用戶的方法。 ``` import { createClient } from '@supabase/supabase-js' // Initialize const supabaseUrl = 'https://chat-room.supabase.co' const supabaseKey = 'public-anon-key' const supabase = createClient(supabaseUrl, supabaseKey) // Create a new user const { user, error } = await supabase.auth.signUp({ email: '[email protected]', password: 'example-password', }) ``` 您可以閱讀[文件](https://supabase.com/docs)。 您可以使用身份驗證、即時、邊緣功能、儲存等功能建立一個速度極快的應用程式。 Supabase 涵蓋了這一切! 他們還提供了一些入門套件,例如 AI 聊天機器人和 Stripe 訂閱。 https://github.com/supabase/supabase --- [11.Refine](https://github.com/refinedev/refine) - 企業開源重組工具。 ------------------------------------------------------------ ![精煉](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qx0kd6t2jzdtf90k5ke3.png) 建立具有無與倫比的靈活性的管理面板、儀表板和 B2B 應用程式 您可以在一分鐘內使用單一 CLI 命令進行設定。 它具有適用於 15 多個後端服務的連接器,包括 Hasura、Appwrite 等。 開始使用以下 npm 指令。 ``` npm create refine-app@latest ``` 這就是使用 Refine 新增登入資訊的簡單方法。 ``` import { useLogin } from "@refinedev/core"; const { login } = useLogin(); ``` 您可以閱讀[文件](https://refine.dev/docs/)。 https://github.com/refinedev/refine --- 12. [Zenstack](https://github.com/zenstackhq/zenstack) - 資料庫到 API 和 UI 只需幾分鐘。 ----------------------------------------------------------------------------- ![禪斯塔克](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3b6n2ea3jeeva6uujoex.png) TypeScript 工具包,透過強大的存取控制層增強 Prisma ORM,並釋放其全端開發的全部功能。 開始使用以下 npx 指令。 ``` npx zenstack@latest init ``` 這是透過伺服器適配器建立 RESTful API 的方法。 ``` // pages/api/model/[...path].ts import { requestHandler } from '@zenstackhq/next'; import { enhance } from '@zenstackhq/runtime'; import { getSessionUser } from '@lib/auth'; import { prisma } from '@lib/db'; // Mount Prisma-style APIs: "/api/model/post/findMany", "/api/model/post/create", etc. // Can be configured to provide standard RESTful APIs (using JSON:API) instead. export default requestHandler({ getPrisma: (req, res) => enhance(prisma, { user: getSessionUser(req, res) }), }); ``` 您可以閱讀[文件](https://zenstack.dev/docs/welcome)。 https://github.com/zenstackhq/zenstack --- 13. [Buildship](https://github.com/rowyio/buildship) - 低程式碼視覺化後端建構器。 -------------------------------------------------------------------- ![建造船](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rzlrynz5xephv4t9layd.png) 對於您正在使用無程式碼應用程式建構器(FlutterFlow、Webflow、Framer、Adalo、Bubble、BravoStudio...)或前端框架(Next.js、React、Vue...)建立的應用程式,您需要一個後端來支援可擴展的 API、安全工作流程、自動化等。BuildShip 為您提供了一種完全視覺化的方式,可以在易於使用的完全託管體驗中可擴展地建立這些後端任務。 這意味著您不需要在雲端平台上爭論或部署東西、執行 DevOps 等。只需立即建置和交付 🚀 https://github.com/rowyio/buildship --- 14. [Taipy](https://github.com/Avaiga/taipy) - 將資料和人工智慧演算法整合到生產就緒的 Web 應用程式中。 ----------------------------------------------------------------------------- ![打字](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ohv3johuz92lsaux52oq.png) Taipy 是一個開源 Python 庫,用於輕鬆的端到端應用程式開發, 具有假設分析、智慧管道執行、內建調度和部署工具。 開始使用以下命令。 ``` pip install taipy ``` 這是一個典型的Python函數,也是過濾器場景中使用的唯一任務。 ``` def filter_genre(initial_dataset: pd.DataFrame, selected_genre): filtered_dataset = initial_dataset[initial_dataset['genres'].str.contains(selected_genre)] filtered_data = filtered_dataset.nlargest(7, 'Popularity %') return filtered_data ``` 您可以閱讀[文件](https://docs.taipy.io/en/latest/)。 他們還有很多可供您建立的[演示應用程式教學](https://docs.taipy.io/en/latest/knowledge_base/demos/)。 https://github.com/Avaiga/taipy --- 15. [LocalForage](https://github.com/localForage/localForage) - 改進了離線儲存。 ------------------------------------------------------------------------ ![當地飼料](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4hlrka5pybvmgmo2djel.png) LocalForage 是一個 JavaScript 函式庫,它透過使用非同步資料儲存和簡單的、類似 localStorage 的 API 來改善 Web 應用程式的離線體驗。它允許開發人員儲存多種類型的資料而不僅僅是字串。 開始使用以下 npm 指令。 ``` npm install localforage ``` 只需包含 JS 檔案並開始使用 localForage。 ``` <script src="localforage.js"></script> ``` 您可以閱讀[文件](https://localforage.github.io/localForage/#installation)。 https://github.com/localForage/localForage --- 16. [Zod](https://github.com/colinhacks/zod) - 使用靜態類型推斷的 TypeScript-first 模式驗證。 ------------------------------------------------------------------------------- ![佐德](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1s6zvmqr0lv93vsrhofs.png) Zod 的目標是透過最大限度地減少重複的類型聲明來對開發人員友好。使用 Zod,您聲明一次驗證器,Zod 將自動推斷靜態 TypeScript 類型。將更簡單的類型組合成複雜的資料結構很容易。 開始使用以下 npm 指令。 ``` npm install zod ``` 這是您在建立字串架構時自訂一些常見錯誤訊息的方法。 ``` const name = z.string({ required_error: "Name is required", invalid_type_error: "Name must be a string", }); ``` 您可以閱讀[文件](https://zod.dev/)。 它適用於 Node.js 和所有現代瀏覽器 https://github.com/colinhacks/zod --- 17.[多普勒](https://github.com/DopplerHQ)- 管理你的秘密。 ----------------------------------------------- ![多普勒](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gycxnuiiwsvibryrytlc.png) 您可以透過在具有開發、暫存和生產環境的專案中組織機密來消除機密蔓延。 開始使用以下指令 (MacOS)。 ``` $ brew install dopplerhq/cli/doppler $ doppler --version ``` 這是安裝 Doppler CLI[的 GitHub Actions 工作流程](https://github.com/DopplerHQ/cli-action)。 您可以閱讀[文件](https://docs.doppler.com/docs/start)。 ``` name: Example action on: [push] jobs: my-job: runs-on: ubuntu-latest steps: - name: Install CLI uses: dopplerhq/cli-action@v3 - name: Do something with the CLI run: doppler secrets --only-names env: DOPPLER_TOKEN: ${{ secrets.DOPPLER_TOKEN }} ``` https://github.com/DopplerHQ --- 18. [FastAPI](https://github.com/tiangolo/fastapi) - 高效能、易於學習、快速編碼、可用於生產。 ------------------------------------------------------------------------- ![快速API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h2awncoia6255ycl95lk.png) FastAPI 是一個現代、快速(高效能)的 Web 框架,用於基於標準 Python 類型提示使用 Python 3.8+ 建立 API。 開始使用以下命令。 ``` $ pip install fastapi ``` 這是您開始使用 FastAPI 的方式。 ``` from typing import Union from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"Hello": "World"} @app.get("/items/{item_id}") def read_item(item_id: int, q: Union[str, None] = None): return {"item_id": item_id, "q": q} ``` 您的編輯器將自動完成屬性並了解它們的類型,這是使用 FastAPI 的最佳功能之一。 您可以閱讀[文件](https://fastapi.tiangolo.com/)。 https://github.com/tiangolo/fastapi --- 19. [Flowise](https://github.com/FlowiseAI/Flowise) - 拖放 UI 來建立您的客製化 LLM 流程。 ---------------------------------------------------------------------------- ![流動](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ct732wv07pvwx0nmavp5.png) Flowise 是一款開源 UI 視覺化工具,用於建立客製化的 LLM 編排流程和 AI 代理程式。 開始使用以下 npm 指令。 ``` npm install -g flowise npx flowise start OR npx flowise start --FLOWISE_USERNAME=user --FLOWISE_PASSWORD=1234 ``` 這就是整合 API 的方式。 ``` import requests url = "/api/v1/prediction/:id" def query(payload): response = requests.post( url, json = payload ) return response.json() output = query({ question: "hello!" )} ``` 您可以閱讀[文件](https://docs.flowiseai.com/)。 https://github.com/FlowiseAI/Flowise --- 20. [Scrapy](https://github.com/scrapy/scrapy) - Python 的快速進階網頁爬行和抓取框架.. ------------------------------------------------------------------------ ![鬥志旺盛](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k1b2y1hzdsphw43b6v7b.png) Scrapy 是一個快速的高級網路爬行和網頁抓取框架,用於爬行網站並從頁面中提取結構化資料。它可用於多種用途,從資料探勘到監控和自動化測試。 開始使用以下命令。 ``` pip install scrapy ``` 建造並執行您的網路蜘蛛。 ``` pip install scrapy cat > myspider.py <<EOF import scrapy class BlogSpider(scrapy.Spider): name = 'blogspider' start_urls = ['https://www.zyte.com/blog/'] def parse(self, response): for title in response.css('.oxy-post-title'): yield {'title': title.css('::text').get()} for next_page in response.css('a.next'): yield response.follow(next_page, self.parse) EOF scrapy runspider myspider.py ``` 您可以閱讀[文件](https://scrapy.org/doc/)。 它擁有大約 50k+ 的星星,因此對於網頁抓取來說具有巨大的可信度。 https://github.com/scrapy/scrapy --- 21. [Tone](https://github.com/Tonejs/Tone.js) - 在瀏覽器中製作互動式音樂。 ------------------------------------------------------------- ![音調.js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fokxsoblaohgs4tx75g3.png) 開始使用以下 npm 指令。 ``` npm install tone ``` 這是您開始使用 Tone.js 的方法 ``` // To import Tone.js: import * as Tone from 'tone' //create a synth and connect it to the main output (your speakers) const synth = new Tone.Synth().toDestination(); //play a middle 'C' for the duration of an 8th note synth.triggerAttackRelease("C4", "8n"); ``` 您可以閱讀[文件](https://github.com/Tonejs/Tone.js?tab=readme-ov-file#installation)。 https://github.com/Tonejs/Tone.js --- 22. [Spacetime](https://github.com/spencermountain/spacetime) - 輕量級 javascript 時區庫。 ----------------------------------------------------------------------------------- ![時空](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/abfyfuzt4nw4h7b8usab.png) 您可以計算遠端時區的時間;支持夏令時、閏年和半球。按季度、季節、月份、週來定位時間.. 開始使用以下 npm 指令。 ``` npm install spacetime ``` 您可以這樣使用它。 ``` <script src="https://unpkg.com/spacetime"></script> <script> var d = spacetime('March 1 2012', 'America/New_York') //set the time d = d.time('4:20pm') d = d.goto('America/Los_Angeles') d.time() //'1:20pm' </script> ``` https://github.com/spencermountain/spacetime --- 23. [Mermaid](https://github.com/mermaid-js/mermaid) - 從類似 markdown 的文字產生圖表。 ---------------------------------------------------------------------------- ![美人魚](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ggubn86xv7fznxol6fw7.png) 您可以使用 Markdown with Mermaid 等文字產生流程圖或序列圖等圖表。 這就是建立圖表的方法。 ``` sequenceDiagram Alice->>John: Hello John, how are you? loop Healthcheck John->>John: Fight against hypochondria end Note right of John: Rational thoughts! John-->>Alice: Great! John->>Bob: How about you? Bob-->>John: Jolly good! ``` 它將做出如下圖。 ![圖表](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bbuo2ey5q2x3sjwywizg.png) 您可以閱讀[VS Code](https://docs.mermaidchart.com/plugins/visual-studio-code)的[文件](https://mermaid.js.org/intro/getting-started.html)和外掛程式。 請參閱[即時編輯器](https://mermaid.live/edit#pako:eNpVkE1PwzAMhv9KlvM-2AZj62EIxJd24ADXXLzEbaKlcUkdUDX1v5MONomcnNevXz32UWoyKAvZ4mfCoPHRQRWhVuHeO42T7XZHNhTiFb0nMdRjYelbQETRUbpTwRM1uQ2erbaoDyqI_AbnZfjZVZYFVOBCy8J2DWlLwUQHKmAwKrwRo4gnF5Xid-gd2FEAL9hSyp12pMIpNcee2ArxEhH4LG-3D7TPoAPcnhL_4WVxcgHZkfedqIjMSI5ljbEGZ_LyxwFaSbZYo5JFLg3Eg5Iq9NkHiemjC1oWHBOOZWoM8PlQ_8Un45iiLErwbRY9gcH8PUrumuHKlWs5J2oKpasGPUWfZcvctMVsNrSnlWOb9lNN9ax1xkJk-7VZzVaL1RoWS1zdLuFmuTR6P9-sy8X1vDS3V_MFyL7vfwD_bJ1W)中的範例。 https://github.com/mermaid-js/mermaid --- 24.[公共 API](https://github.com/public-apis/public-apis) - 20 多個類別的 1400 多個 API。 ------------------------------------------------------------------------------- ![公共API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sjapk9rwlzdl6bcyqdnl.png) 我們主要使用外部 API 來建立應用程式,在這裡您可以找到所有 API 的清單。網站連結在最後。 它在 GitHub 上擁有大約 279k+ 顆星。 ![公共API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rld5i88smezo1naawz7a.png) 從儲存庫取得網站連結非常困難。所以,我把它貼在這裡。 網址 - [Collective-api.vercel.app/](https://collective-api.vercel.app/) https://github.com/public-apis/public-apis --- 25. [Framer Motion](https://github.com/framer/motion) - 像魔法一樣的動畫。 ----------------------------------------------------------------- ![成幀器運動](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hn4ecqkrhs8f4729bzps.png) 可用的最強大的動畫庫之一。 Framer 使用簡單的聲明性語法意味著您編寫的程式碼更少。更少的程式碼意味著您的程式碼庫更易於閱讀和維護。 您可以建立事件和手勢,並且使用 Framer 的社區很大,這意味著良好的支援。 開始使用以下 npm 指令。 ``` npm install framer-motion ``` 您可以這樣使用它。 ``` import { motion } from "framer-motion" <motion.div whileHover={{ scale: 1.2 }} whileTap={{ scale: 1.1 }} drag="x" dragConstraints={{ left: -100, right: 100 }} /> ``` 您可以閱讀[文件](https://www.framer.com/motion/introduction/)。 https://github.com/framer/motion --- 26.[順便說一句](https://github.com/btw-so/btw)- 在幾分鐘內建立您的個人部落格。 ---------------------------------------------------------- ![順便提一句](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gnne3lrfpolotmxkdz2m.png) 順便說一句,您可以註冊並使用,而無需安裝任何東西。您也可以使用開源版本自行託管。 ![順便提一句](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2rli7hpoccqwpvba29b4.png) 使用順便說一句建立的[範例部落格](https://www.siddg.com/about)。 https://github.com/btw-so/btw --- 27. [Formbricks](https://github.com/formbricks/formbricks) - 開源調查平台。 -------------------------------------------------------------------- ![成型磚](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tp6ggyom33vdifd3m1vt.png) Formbricks 提供免費、開源的測量平台。透過精美的應用程式內、網站、連結和電子郵件調查收集用戶旅程中每個點的回饋。在 Formbricks 之上建置或利用預先建置的資料分析功能。 開始使用以下 npm 指令。 ``` npm install @formbricks/js ``` 這就是您開始使用 formbricks 的方法。 ``` import formbricks from "@formbricks/js"; if (typeof window !== "undefined") { formbricks.init({ environmentId: "claV2as2kKAqF28fJ8", apiHost: "https://app.formbricks.com", }); } ``` 您可以閱讀[文件](https://formbricks.com/docs/getting-started/quickstart-in-app-survey)。 https://github.com/formbricks/formbricks --- 28. [Stripe](https://github.com/stripe) - 支付基礎設施。 ------------------------------------------------- ![條紋](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/79yvcgsi4744cmryh15j.png) 數以百萬計的各種規模的公司在線上和親自使用 Stripe 來接受付款、發送付款、自動化財務流程並最終增加收入。 開始使用以下 npm 指令 (React.js)。 ``` npm install @stripe/react-stripe-js @stripe/stripe-js ``` 這就是使用鉤子的方法。 ``` import React, {useState} from 'react'; import ReactDOM from 'react-dom'; import {loadStripe} from '@stripe/stripe-js'; import { PaymentElement, Elements, useStripe, useElements, } from '@stripe/react-stripe-js'; const CheckoutForm = () => { const stripe = useStripe(); const elements = useElements(); const [errorMessage, setErrorMessage] = useState(null); const handleSubmit = async (event) => { event.preventDefault(); if (elements == null) { return; } // Trigger form validation and wallet collection const {error: submitError} = await elements.submit(); if (submitError) { // Show error to your customer setErrorMessage(submitError.message); return; } // Create the PaymentIntent and obtain clientSecret from your server endpoint const res = await fetch('/create-intent', { method: 'POST', }); const {client_secret: clientSecret} = await res.json(); const {error} = await stripe.confirmPayment({ //`Elements` instance that was used to create the Payment Element elements, clientSecret, confirmParams: { return_url: 'https://example.com/order/123/complete', }, }); if (error) { // This point will only be reached if there is an immediate error when // confirming the payment. Show error to your customer (for example, payment // details incomplete) setErrorMessage(error.message); } else { // Your customer will be redirected to your `return_url`. For some payment // methods like iDEAL, your customer will be redirected to an intermediate // site first to authorize the payment, then redirected to the `return_url`. } }; return ( <form onSubmit={handleSubmit}> <PaymentElement /> <button type="submit" disabled={!stripe || !elements}> Pay </button> {/* Show error message to your customers */} {errorMessage && <div>{errorMessage}</div>} </form> ); }; const stripePromise = loadStripe('pk_test_6pRNASCoBOKtIshFeQd4XMUh'); const options = { mode: 'payment', amount: 1099, currency: 'usd', // Fully customizable with appearance API. appearance: { /*...*/ }, }; const App = () => ( <Elements stripe={stripePromise} options={options}> <CheckoutForm /> </Elements> ); ReactDOM.render(<App />, document.body); ``` 您可以閱讀[文件](https://github.com/stripe/react-stripe-js?tab=readme-ov-file#minimal-example)。 您幾乎可以整合任何東西。它有一個巨大的選項清單。 ![整合](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/67f3pb2i8xolt635rp2p.png) https://github.com/stripe --- 29. [Upscayl](https://github.com/upscayl/upscayl) - 開源 AI 影像升級器。 ---------------------------------------------------------------- ![高級](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2c1837rev5jb260ro2sd.png) 適用於 Linux、MacOS 和 Windows 的免費開源 AI Image Upscaler 採用 Linux 優先概念建構。 它可能與全端無關,但它對於升級圖像很有用。 ![高級](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a4qq1wm3wey3vihn9al4.png) 透過最先進的人工智慧,Upscayl 可以幫助您將低解析度影像變成高解析度。清脆又鋒利! https://github.com/upscayl/upscayl --- 30.[重新發送](https://github.com/resend)- 為開發人員提供的電子郵件 API。 ------------------------------------------------------- ![重發](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x3auhh3hbxjmmzehe5v0.png) 您可以使用 React 建立和傳送電子郵件。 2023 年最受炒作的產品之一。 開始使用以下 npm 指令。 ``` npm install @react-email/components -E ``` 這是將其與 next.js 專案整合的方法。 ``` import { EmailTemplate } from '@/components/email-template'; import { Resend } from 'resend'; const resend = new Resend(process.env.RESEND_API_KEY); export async function POST() { const { data, error } = await resend.emails.send({ from: '[email protected]', to: '[email protected]', subject: 'Hello world', react: EmailTemplate({ firstName: 'John' }), }); if (error) { return Response.json({ error }); } return Response.json(data); } ``` 您可以閱讀[文件](https://resend.com/docs/introduction)。 ![重發](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rer9ym187e4i9l11afkg.png) 基本概念是一個簡單、優雅的介面,讓您可以在幾分鐘內開始發送電子郵件。它可以透過適用於您最喜歡的程式語言的 SDK 直接融入您的程式碼中。 https://github.com/resend --- 哇!如此長的專案清單。 我知道您有更多想法,分享它們,讓我們一起建造:D 如今建立全端應用程式並不難,但每個應用程式都可以透過有效地使用優秀的開源專案來解決任何問題來增加這一獨特因素。 例如,您可以建立一些提供通知或建立 UI 流來抓取資料的東西。 我希望其中一些內容對您的開發之旅有用。他們擁有一流的開發人員經驗;你可以依賴他們。 由於您將要建造東西,因此您可以在這裡找到一些[瘋狂的想法](https://github.com/florinpop17/app-ideas)。 祝你有美好的一天!直到下一次。 --- 原文出處:https://dev.to/copilotkit/im-building-a-full-stack-app-here-are-the-libraries-im-going-to-use-51nk

軟體工程師面試學習指南

[本·羅戈揚](https://www.linkedin.com/in/benjaminrogojan/) 軟體工程面試與其他技術面試一樣,需要充分的準備。有許多主題需要涵蓋,以確保您準備好應對有關演算法、資料結構、設計、最佳化以及不斷增長的主題的連續問題。 因此,我在最後一輪面試中建立了一個清單,涵蓋了許多熱門話題。 為了幫助您追蹤進度,我們針對下面列出的相同問題編制了一份全面的清單; [該列表可以在這裡找到](https://docs.google.com/spreadsheets/d/19hSRrL4l3gRiJ5ucH9q4iwFo2QHgic9gGMNUrcn1mm0/edit?usp=sharing)。 ### **聆聽經典熱身** 1. [fizzbuzz](https://www.hackerrank.com/challenges/fizzbuzz/problem) 2. [子陣列和等於 K](https://leetcode.com/problems/subarray-sum-equals-k/) 3. [陣列:左旋轉](https://www.hackerrank.com/challenges/ctci-array-left-rotation/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=arrays) 4. [字串:製作字謎詞](https://www.hackerrank.com/challenges/ctci-making-anagrams/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=strings) 5. [第 N 次斐波那契數](https://www.algoexpert.io/questions/Nth%20Fibonacci) 你怎麼做的?花點時間對這些經典作品進行評價。我們在面試過程中的某個時刻被問到了其中大部分問題,而且通常是在早期就被問到的淘汰式問題。它們通常與演算法和資料結構關係不大,但仍然需要對循環和陣列有很好的理解(是的,陣列是一種資料結構)。 ### **演算法和資料結構** #### **預習問題** 在觀看有關資料結構和演算法的影片內容之前,請考慮嘗試以下這些問題。看看你能否回答他們。這將幫助您知道要關注什麼。 1. [985. 查詢後偶數之和](https://leetcode.com/problems/sum-of-even-numbers-after-queries/) 2. [657. 機器人回歸原點](https://leetcode.com/problems/robot-return-to-origin/) 3. [961. 2N 陣列中的 N 重複元素](https://leetcode.com/problems/n-repeated-element-in-size-2n-array/) 4. [110.平衡二元樹](https://leetcode.com/problems/balanced-binary-tree/) 5. [3. 最長無重複字元的子字串](https://leetcode.com/problems/longest-substring-without-repeating-characters/) 6. [19. 從清單結尾刪除第 N 個節點](https://leetcode.com/problems/remove-nth-node-from-end-of-list/) 7. [23. 合併 k 個排序列表](https://leetcode.com/problems/merge-k-sorted-lists/) 8. [31. 下一個排列](https://leetcode.com/problems/next-permutation/) ### 演算法和資料結構影片 #### 資料結構 ![](https://cdn-images-1.medium.com/max/1600/1*Dyu63sMUVL-gYEZISOE2BQ.jpeg) 1. [資料結構與演算法 #1 --- 什麼是資料結構?](https://www.youtube.com/watch?v=bum_19loj9A) --- 影片 2. [多調光](https://archive.org/details/0102WhatYouShouldKnow/02_05-multidimensionalArrays.mp4)--- 影片 3. [動態陣列](https://www.coursera.org/learn/data-structures/lecture/EwbnV/dynamic-arrays)[ ](https://archive.org/details/0102WhatYouShouldKnow/03_01-resizableArrays.mp4)--- 影片 4. [調整陣列大小](https://archive.org/details/0102WhatYouShouldKnow/03_01-resizableArrays.mp4)--- 影片 5. [資料結構:鍊錶](https://youtu.be/njTh_OwMljA)--- 影片 6. [核心鍊錶與陣列](https://www.coursera.org/learn/data-structures-optimizing-performance/lecture/rjBs9/core-linked-lists-vs-arrays)--- 影片 7. [指針到指針](https://www.eskimo.com/~scs/cclass/int/sx8.html)[ ](https://archive.org/details/0102WhatYouShouldKnow/03_01-resizableArrays.mp4)--- 影片 8. [資料結構:樹](https://youtu.be/oSWTXtMglKE)[ ](https://archive.org/details/0102WhatYouShouldKnow/03_01-resizableArrays.mp4)--- 影片 9. [資料結構:堆](https://youtu.be/t0Cq6tVNRBA)[ ](https://archive.org/details/0102WhatYouShouldKnow/03_01-resizableArrays.mp4)--- 影片 10. [資料結構:哈希表](https://youtu.be/shs0KM3wKv8)[ ](https://archive.org/details/0102WhatYouShouldKnow/03_01-resizableArrays.mp4)--- 影片 11. [電話簿問題](https://www.coursera.org/learn/data-structures/lecture/NYZZP/phone-book-problem)---影片 12. [資料結構:堆疊和佇列](https://youtu.be/wjI1WNcIntg)[ ](https://archive.org/details/0102WhatYouShouldKnow/03_01-resizableArrays.mp4)--- 影片 13. [使用堆疊後進先出](https://archive.org/details/0102WhatYouShouldKnow/05_01-usingStacksForLast-inFirst-out.mp4)--- 影片 14. [資料結構:計算機科學速成課程#14](https://youtu.be/DuDz6B4cqVc)[ ](https://archive.org/details/0102WhatYouShouldKnow/03_01-resizableArrays.mp4)--- 影片 15. [資料結構:嘗試](https://www.youtube.com/watch?v=zIjfhVPRZCg)[ ](https://archive.org/details/0102WhatYouShouldKnow/03_01-resizableArrays.mp4)--- 影片 #### 演算法 ![](https://cdn-images-1.medium.com/max/1600/1*bPpvELo9_QqQsDz7CSbwXQ.gif) 1. [演算法:圖搜尋、DFS 和 BFS](https://www.youtube.com/watch?v=zaBhtODEL0w&list=PLX6IKgS15Ue02WDPRCmYKuZicQHit9kFt)[ ](https://archive.org/details/0102WhatYouShouldKnow/03_01-resizableArrays.mp4)--- 影片 2. [BFS(廣度優先搜尋)和DFS(深度優先搜尋)](https://www.youtube.com/watch?v=uWL6FJhq5fM) --- 影片 3. [演算法:二分查找](https://youtu.be/P3YID7liBug)---影片 4. [二元搜尋樹回顧](https://www.youtube.com/watch?v=x6At0nzX92o&index=1&list=PLA5Lqm4uh9Bbq-E0ZnqTIa8LRaL77ica6)--- 影片 5. [用於面試的 Python 演算法](https://www.youtube.com/watch?v=p65AHm9MX80)[ ](https://archive.org/details/0102WhatYouShouldKnow/03_01-resizableArrays.mp4)--- 影片 6. [演算法:遞歸](https://youtu.be/KEEKn7Me-ms)---影片 7. [演算法:冒泡排序](https://youtu.be/6Gv8vg0kcHc)--- 影片 8. [演算法:歸併排序](https://youtu.be/KF2j-9iSf4Q)--- 影片 9. [演算法:快速排序](https://youtu.be/SLauY6PpjW4)---影片 ### **大 O 表示法** 1. [大 O 表示法與時間複雜度簡介(資料結構與演算法 #7)](https://www.youtube.com/watch?v=D6xkbGLQesk) --- 影片 2. [哈佛 CS50 --- 漸近符號](https://www.youtube.com/watch?v=iOq5kSKqeR4)--- 影片 3. [演算法複雜度分析的簡單介紹](http://discrete.gr/complexity/)--- Post 4. [備忘錄](http://bigocheatsheet.com/)--- 帖子 ### **動態規劃** 1. [動態規劃(像程式設計師一樣思考)---影片](https://www.youtube.com/watch?v=iv_yHjmkv4I) 2. [演算法:記憶化與動態規劃 --- 影片](https://www.youtube.com/watch?v=P8Xa2BitN3I&t=13s) 3. 6 [.006:動態規劃 I:斐波那契、最短路徑 --- 影片](https://www.youtube.com/watch?v=OQ5jsbhAv_M&t=7s) 4. [6.006:動態規劃 II:文字對齊、二十一點 --- 影片](https://www.youtube.com/watch?v=ENyox7kNKeY&t=4s) 5. [動態規劃 --- 帖子](https://www.topcoder.com/community/competitive-programming/tutorials/dynamic-programming-from-novice-to-advanced/) ### **字串操作** 1. [編碼面試問答:最長的連續字元](https://www.youtube.com/watch?v=qRNB8CV3_LU)--- 影片 2. [Sedgewick --- 子字串搜尋](https://www.coursera.org/learn/algorithms-part2/home/week/4)--- 影片 #### 面試問題演練 1. [谷歌編碼面試 --- 普世價值樹問題](https://www.youtube.com/watch?v=7HgsS8bRvjo)--- 影片 2. [Google 編碼面試問題和答案 #1:第一個重複出現的字元](https://www.youtube.com/watch?v=GJdiM-muYqc)--- 影片 3. [在二元搜尋樹中找到最小和最大元素](https://www.youtube.com/watch?v=Ut90klNN264&index=30&list=PL2_aWCzGMAwI3W_JlcBbtYTwiQSsOTa6P)--- 影片 4. [求二元樹的高度](https://www.youtube.com/watch?v=_pnqMz5nrRs&list=PL2_aWCzGMAwI3W_JlcBbtYTwiQSsOTa6P&index=31)--- 影片 5. [檢查二元樹是否為二元搜尋樹](https://www.youtube.com/watch?v=yEwSGhSsT0U&index=35&list=PL2_aWCzGMAwI3W_JlcBbtYTwiQSsOTa6P)--- 影片 6. [什麼是尾遞歸?為什麼這麼糟?](https://www.quora.com/What-is-tail-recursion-Why-is-it-so-bad) --- 影片 ### **學後問題** 現在您已經學習了一些,並觀看了一些影片,讓我們嘗試更多問題! 1. [越大越好](https://www.hackerrank.com/challenges/bigger-is-greater/problem) 2. [6.之字折線轉換](https://leetcode.com/problems/zigzag-conversion/) 3. [7. 反轉整數](https://leetcode.com/problems/reverse-integer/) 4. [40. 組合和 II](https://leetcode.com/problems/combination-sum-ii/) 5. [43. 字串相乘](https://leetcode.com/problems/multiply-strings/) 6. [拉里的陣列](https://www.hackerrank.com/challenges/larrys-array/problem) 7. [短回文](https://www.hackerrank.com/challenges/short-palindrome/problem) 8. [65. 有效號碼](https://leetcode.com/problems/valid-number/) 9. [越大越好](https://www.hackerrank.com/challenges/bigger-is-greater/problem) 10. [完整計數排序](https://www.hackerrank.com/challenges/countingsort4/problem) 11. [莉莉的家庭作業](https://www.hackerrank.com/challenges/lilys-homework/problem) 12. [普通孩子](https://www.hackerrank.com/challenges/common-child/problem) 13. [459. 重複子字串模式](https://leetcode.com/problems/repeated-substring-pattern/) 14. [27. 刪除元素](https://leetcode.com/problems/remove-element/) 15. [450. 刪除 BST 中的節點](https://leetcode.com/problems/delete-node-in-a-bst/) 16. [659. 將陣列分割成連續的子序列](https://leetcode.com/problems/split-array-into-consecutive-subsequences/) 17. [最大值有界的子陣列數](https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum) 18. [組合和 IV](https://leetcode.com/problems/combination-sum-iv) 19. [買賣股票的最佳時機(有冷卻時間)](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown) 20. [最長重複字元替換](https://leetcode.com/problems/longest-repeating-character-replacement) 21. [成對交換節點](https://leetcode.com/problems/swap-nodes-in-pairs) 22. [二元樹右側視圖](https://leetcode.com/problems/binary-tree-right-side-view) 23. [展平嵌套列表迭代器](https://leetcode.com/problems/flatten-nested-list-iterator) 24. [二元樹層次順序遍歷](https://leetcode.com/problems/binary-tree-level-order-traversal) 25. [二元搜尋樹迭代器](https://leetcode.com/problems/binary-search-tree-iterator) 26. [對鏈最大長度](https://leetcode.com/problems/maximum-length-of-pair-chain) 27. [將鍊錶拆分為多個部分](https://leetcode.com/problems/split-linked-list-in-parts) ### **操作性程式設計問題** 有些公司不會問你演算法問題。相反,他們可能會更專注於實施和營運問題。這些通常更小眾,涉及實際問題,例如循環資料和執行某種任務。這些類型的問題通常不需要太多練習,因為更多的是了解陣列和 HashMap 等基本概念並追蹤您對它們所做的事情。 1. [袋鼠問題](https://www.hackerrank.com/challenges/kangaroo/problem) 2. [打破記錄](https://www.hackerrank.com/challenges/breaking-best-and-worst-records/problem) 3. [查找字串](https://www.hackerrank.com/challenges/find-a-string/problem)[迭代器](https://www.hackerrank.com/challenges/itertools-permutations/problem) 4. [不知道!](https://www.hackerrank.com/challenges/no-idea/problem) 5. [程式設計師的日子](https://www.hackerrank.com/challenges/day-of-the-programmer/problem) 6. [排行榜](https://www.hackerrank.com/challenges/climbing-the-leaderboard/problem) 7. [詞序](https://www.hackerrank.com/challenges/word-order/problem) 8. [夏洛克和方塊](https://www.hackerrank.com/challenges/sherlock-and-squares/problem) 9. [均衡陣列](https://www.hackerrank.com/challenges/equality-in-a-array/problem) 10. [蘋果和橘子](https://www.hackerrank.com/challenges/apple-and-orange/problem) 11. [更多操作風格問題](https://www.hackerrank.com/domains/python) ### **系統設計影片** 系統設計問題是至關重要的問題,表明您不僅僅是一名編碼員。身為工程師,您需要能夠思考大局。某些服務屬於哪裡,您需要什麼樣的伺服器,您將如何管理流量等等。所有這些想法都表明您能夠設計軟體,而不僅僅是編寫人們告訴您編寫的程式碼。 1. [停車場系統](https://youtu.be/DSGsa0pu8-k)---影片 2. [什麼是應用程式](https://www.youtube.com/watch?v=vvhC64hQZMk)--- 影片 3. [優步設計](https://youtu.be/umWABit-wbk)---影片 4. [Instagram](https://www.youtube.com/watch?v=QmX2NPkJTKg) --- 影片 5. [Tinder 服務](https://www.youtube.com/watch?v=xQnIN9bW0og)--- 影片 ### **作業系統** 作業系統問題比較少見,但是對執行緒、調度、記憶體等概念有紮實的理解是有好處的,即使只是基本的理解。當被問到進程和線程有什麼區別而不知道答案時,這是非常尷尬的。 1. [常見作業系統面試問題](https://www.geeksforgeeks.org/commonly-asked-operating-systems-interview-questions-set-1/) 2. [什麼是翻譯後備緩衝區?](https://www.geeksforgeeks.org/operating-system-translation-lookaside-buffer-tlb/) 3. [為什麼循環法可以避免優先反轉問題?](https://leetcode.com/discuss/interview-question/operating-system/220604/Why-does-Round-Robin-avoid-the-Priority-Inversion-Problem) 4. [中斷與系統呼叫---檔案系統中的「inode」是什麼?](https://leetcode.com/discuss/interview-question/operating-system/124838/Interrupt-Vs-System-Call) 5. [作業系統面試題目及答案 --- 第一部分](https://www.youtube.com/watch?v=b18X4uOKjHs) 6. [什麼是內核 --- Gary 解釋](https://www.youtube.com/watch?v=mycVSMyShk8) 7. [循環演算法教程(CPU調度)](https://www.youtube.com/watch?v=aWlQYllBZDs) 8. [LRU 快取的魔力(Google 開發 100 天)](https://www.youtube.com/watch?v=R5ON3iwx78M) --- 影片 9. [MIT 6.004 L15:記憶體層次結構](https://www.youtube.com/watch?v=vjYF_fAZI5E&list=PLrRW1w6CGAcXbMtDFj205vALOGmiRc82-&index=24)--- 影片 10. [中斷](https://www.youtube.com/watch?v=uFKi2-J-6II&list=PLCiOXwirraUCBE9i_ukL8_Kfg6XNv7Se8&index=3)---影片 11. [調度](https://www.youtube.com/watch?v=-Gu5mYdKbu4&index=4&list=PLCiOXwirraUCBE9i_ukL8_Kfg6XNv7Se8)---影片 ### **執行緒數** ![](https://cdn-images-1.medium.com/max/1600/1*uSHd3KSxg363C1frMv2KwQ.png) 1. [用戶級線程與內核級線程](https://leetcode.com/discuss/interview-question/operating-system/124631/User-Level-thread-Vs-Kernel-Level-thread) 2. [行程和線程簡介](https://www.youtube.com/watch?v=exbKr6fnoUw)--- 影片 3. [進程和線程之間的區別 --- 佐治亞理工學院 --- 高級操作系統](https://www.youtube.com/watch?v=O3EyzlZxx3g&t=11s)--- 影片 4. [分叉和多線程之間的區別](https://leetcode.com/discuss/interview-question/operating-system/125024/Difference-between-forking-and-multithreading) ### **物件導向** ![](https://cdn-images-1.medium.com/max/1600/1*8LHiDwWhrU4iegYiNnKX_A.png) 與作業系統類似,並不是每次面試都會問你有關物件導向程式設計的問題,但你永遠不知道。您需要確保記住計算機 162 課程中的基礎知識。 1. [Java 程式設計教學 --- 49 --- 繼承](https://www.youtube.com/watch?v=9JpNY-XAseg)--- 影片 2. [Java 程式設計教學 --- 55 --- 多態性簡介](https://www.youtube.com/watch?v=0xw06loTm1k)--- 影片 3. [Java 程式設計教學 --- 58 --- 抽象類別與具體類別](https://www.youtube.com/watch?v=TyPNvt6Zg8c)--- 影片 4. [Java 程式設計教學 --- 57 --- 重寫規則](https://www.youtube.com/watch?v=zN9pKULyoj4&t=3s)--- 影片 5. [Java 程式設計教學 --- 59 --- 保存物件的類](https://www.youtube.com/watch?v=slY5Ag7IjM0) 6. [物件導向程式設計](https://www.youtube.com/watch?v=lbXsrHGhBAU)---影片 ### **設計模式** 如果您像我們一樣,我們不會被教導所有各種設計模式。因此,最好了解它們的工作原理以及使用它們的原因。一些面試問題可以很簡單,例如“為什麼要使用工廠類?” 1. [工廠設計模式](https://www.youtube.com/watch?v=ub0DXaeV6hA)---影片 2. [觀察者設計模式](https://youtu.be/wiQdrH2YpT4)---影片 3. [適配器設計模式](https://www.youtube.com/watch?v=qG286LQM6BU&list=PLF206E906175C7E07&index=13)---影片 4. [立面設計模式](https://www.youtube.com/watch?v=B1Y8fcYrz5o&list=PLF206E906175C7E07&index=14)---影片 5. [責任鏈設計模式](https://www.youtube.com/watch?v=jDX6x8qmjbA&list=PLF206E906175C7E07&index=22)---影片 6. [解譯器設計模式](https://www.youtube.com/watch?v=6CVymSJQuJE&list=PLF206E906175C7E07&index=23)---影片 7. [單例設計模式教學](https://www.youtube.com/watch?v=NZaXM67fxbs&list=PLF206E906175C7E07&index=7)--- 影片 8. [第 6 章(第 1 部分)--- 模式(影片)](https://youtu.be/LAP2A80Ajrg?list=PLJ9pm_Rc9HesnkwKlal_buSIHA-jTZMpO&t=3344) --- 影片 9. [Head First 設計模式](https://www.amazon.com/Head-First-Design-Patterns-Freeman/dp/0596007124)--- 影片 ### SQL 這是最後一節。你們中的許多人可能不會被問到那麼多 SQL 問題。不過,我始終認為放在後口袋是件好事。 #### SQL --- 問題 1. [262. 行程和用戶](https://leetcode.com/problems/trips-and-users/) 2. [601. 體育場人流量](https://leetcode.com/problems/human-traffic-of-stadium/) 3. [185. 部門前三薪資](https://leetcode.com/problems/department-top-three-salaries/) 4. [626.交換席位](https://leetcode.com/problems/exchange-seats/) 5. [駭客排名報告](https://www.hackerrank.com/challenges/the-report/problem) 6. [177.第N最高薪水](https://leetcode.com/problems/nth-highest-salary/) 7. [對稱對](https://www.hackerrank.com/challenges/symmetric-pairs/problem) 8. [職業](https://www.hackerrank.com/challenges/placements/problem)[安置](https://www.hackerrank.com/challenges/occupations/problem) 9. [奧利凡德的庫存](https://www.hackerrank.com/challenges/harry-potter-and-wands/problem) #### SQL --- 影片 1. [IQ15:6 個 SQL 查詢面試問題](https://www.youtube.com/watch?v=uAWWhEA57bE)--- 影片 2. [了解 ROW\_NUMBER 和分析函數](https://www.youtube.com/watch?v=QFj-hZi8MKk)--- 影片 3. [分析函數的高級實現](https://www.youtube.com/watch?v=G3kYPzLWtpo&t=4s)--- 影片 4. [分析函數的高級實現第 2 部分](https://www.youtube.com/watch?v=XecU6Ieyu-4&t=54s)--- 影片 5. [聰明的貓頭鷹 SQL 影片](https://www.youtube.com/watch?v=2-1XQHAgDsM&list=PL6EDEB03D20332309)--- 影片 #### SQL 後問題 1. [二元樹節點](https://www.hackerrank.com/challenges/binary-search-tree-1/problem) 2. [氣象觀測站 18](https://www.hackerrank.com/challenges/weather-observation-station-18/problem) 3. [挑戰](https://www.hackerrank.com/challenges/challenges/problem)[列印素數](https://www.hackerrank.com/challenges/print-prime-numbers/problem) 4. [595.大國](https://leetcode.com/problems/big-countries/) 5. [626.交換席位](https://leetcode.com/problems/exchange-seats/) 6. [SQL 面試問題:3 個技術篩選練習(針對資料分析師)](https://data36.com/sql-interview-questions-tech-screening-data-analysts/) 面試可能會很困難,因為你會覺得自己沒有任何進展。擁有本學習指南將幫助您追蹤您的進度並讓您更好地了解自己的表現! 祝你好運! 另外,如果您想閱讀/觀看更多精彩的貼文或影片: [在 SaturnCloud 上使用 Jupyter Notebook 連接到大查詢第 2 部分](https://www.youtube.com/watch?v=O1cBN5gJtdw&t=15s) [身為資料科學家你應該閱讀的三本書](https://www.coriers.com/three-books-you-must-read-if-you-want-a-career-as-a-data-scientist/) [Hadoop 與關聯式資料庫](http://www.acheronanalytics.com/acheron-blog/hadoop-vs-relational-databases) [算法如何變得不道德和有偏見](http://www.acheronanalytics.com/acheron-blog/how-do-machines-learn-bias-data-science) [如何改善資料驅動策略](http://www.acheronanalytics.com/acheron-blog/how-to-improve-your-data-driven-strategy) [如何開發穩健演算法](https://medium.com/better-programming/how-to-develop-a-robust-algorithm-c38e08f32201) [資料科學家必須具備的 4 項技能](https://www.theseattledataguy.com/4-skills-data-scientist-must-have/) [SQL 最佳實踐 - 設計 ETL 影片](http://www.acheronanalytics.com/acheron-blog/sql-best-practices-designing-an-etl-video) --- 原文出處:https://dev.to/seattledataguy/the-interview-study-guide-for-software-engineers-764

為初學者到專家提供的 101 個 Bash 指令和提示

> **2019 年 9 月 25 日更新:**感謝[ラナ・kuaru](https://twitter.com/rana_kualu)的辛勤工作,本文現已提供日文版。請點擊下面的連結查看他們的工作。如果您知道本文被翻譯成其他語言,請告訴我,我會將其發佈在這裡。 [🇯🇵 閱讀日語](https://qiita.com/rana_kualu/items/7b62898d373901466f5c) > **2019 年 7 月 8 日更新:**我最近發現大約兩年前發佈在法語留言板上的[這篇非常相似的文章](https://bookmarks.ecyseo.net/?EAWvDw)。如果您有興趣學習一些 shell 命令——並且您*會說 français* ,那麼它是對我下面的文章的一個很好的補充。 直到大約一年前,我幾乎只在 macOS 和 Ubuntu 作業系統中工作。在這兩個作業系統上, `bash`是我的預設 shell。在過去的六、七年裡,我對`bash`工作原理有了大致的了解,並想為那些剛入門的人概述一些更常見/有用的命令。如果您認為您了解有關`bash`所有訊息,請無論如何看看下面的內容 - 我已經提供了一些提示和您可能忘記的標誌的提醒,這可以讓您的工作更輕鬆一些。 下面的命令或多或少以敘述風格排列,因此如果您剛開始使用`bash` ,您可以從頭到尾完成操作。事情到最後通常會變得不那麼常見並且變得更加困難。 <a name="toc"></a> 目錄 -- - [基礎](#the-basics) ``` - [First Commands, Navigating the Filesystem](#first-commands) ``` ``` - [`pwd / ls / cd`](#pwd-ls-cd) ``` ``` - [`; / && / &`](#semicolon-andand-and) ``` ``` - [Getting Help](#getting-help) ``` ``` - [`-h`](#minus-h) ``` ``` - [`man`](#man) ``` ``` - [Viewing and Editing Files](#viewing-and-editing-files) ``` ``` - [`head / tail / cat / less`](#head-tail-cat-less) ``` ``` - [`nano / nedit`](#nano-nedit) ``` ``` - [Creating and Deleting Files and Directories](#creating-and-deleting-files) ``` ``` - [`touch`](#touch) ``` ``` - [`mkdir / rm / rmdir`](#mkdir-rm-rmdir) ``` ``` - [Moving and Copying Files, Making Links, Command History](#moving-and-copying-files) ``` ``` - [`mv / cp / ln`](#mv-cp-ln) ``` ``` - [Command History](#command-history) ``` ``` - [Directory Trees, Disk Usage, and Processes](#directory-trees-disk-usage-processes) ``` ``` - [`mkdir –p / tree`](#mkdir--p-tree) ``` ``` - [`df / du / ps`](#df-du-ps) ``` ``` - [Miscellaneous](#basic-misc) ``` ``` - [`passwd / logout / exit`](#passwd-logout-exit) ``` ``` - [`clear / *`](#clear-glob) ``` - [中間的](#intermediate) ``` - [Disk, Memory, and Processor Usage](#disk-memory-processor) ``` ``` - [`ncdu`](#ncdu) ``` ``` - [`top / htop`](#top-htop) ``` ``` - [REPLs and Software Versions](#REPLs-software-versions) ``` ``` - [REPLs](#REPLs) ``` ``` - [`-version / --version / -v`](#version) ``` ``` - [Environment Variables and Aliases](#env-vars-aliases) ``` ``` - [Environment Variables](#env-vars) ``` ``` - [Aliases](#aliases) ``` ``` - [Basic `bash` Scripting](#basic-bash-scripting) ``` ``` - [`bash` Scripts](#bash-scripts) ``` ``` - [Custom Prompt and `ls`](#custom-prompt-ls) ``` ``` - [Config Files](#config-files) ``` ``` - [Config Files / `.bashrc`](#config-bashrc) ``` ``` - [Types of Shells](#types-of-shells) ``` ``` - [Finding Things](#finding-things) ``` ``` - [`whereis / which / whatis`](#whereis-which-whatis) ``` ``` - [`locate / find`](#locate-find) ``` ``` - [Downloading Things](#downloading-things) ``` ``` - [`ping / wget / curl`](#ping-wget-curl) ``` ``` - [`apt / gunzip / tar / gzip`](#apt-gunzip-tar-gzip) ``` ``` - [Redirecting Input and Output](#redirecting-io) ``` ``` - [`| / > / < / echo / printf`](#pipe-gt-lt-echo-printf) ``` ``` - [`0 / 1 / 2 / tee`](#std-tee) ``` - [先進的](#advanced) ``` - [Superuser](#superuser) ``` ``` - [`sudo / su`](#sudo-su) ``` ``` - [`!!`](#click-click) ``` ``` - [File Permissions](#file-permissions) ``` ``` - [File Permissions](#file-permissions-sub) ``` ``` - [`chmod / chown`](#chmod-chown) ``` ``` - [User and Group Management](#users-groups) ``` ``` - [Users](#users) ``` ``` - [Groups](#groups) ``` ``` - [Text Processing](#text-processing) ``` ``` - [`uniq / sort / diff / cmp`](#uniq-sort-diff-cmp) ``` ``` - [`cut / sed`](#cut-sed) ``` ``` - [Pattern Matching](#pattern-matching) ``` ``` - [`grep`](#grep) ``` ``` - [`awk`](#awk) ``` ``` - [Copying Files Over `ssh`](#ssh) ``` ``` - [`ssh / scp`](#ssh-scp) ``` ``` - [`rsync`](#rsync) ``` ``` - [Long-Running Processes](#long-running-processes) ``` ``` - [`yes / nohup / ps / kill`](#yes-nohup-ps-kill) ``` ``` - [`cron / crontab / >>`](#cron) ``` ``` - [Miscellaneous](#advanced-misc) ``` ``` - [`pushd / popd`](#pushd-popd) ``` ``` - [`xdg-open`](#xdg-open) ``` ``` - [`xargs`](#xargs) ``` - [獎勵:有趣但大多無用的東西](#bonus) ``` - [`w / write / wall / lynx`](#w-write-wall-lynx) ``` ``` - [`nautilus / date / cal / bc`](#nautilus-date-cal-bc) ``` --- <a name="the-basics"></a> 基礎 == <a name="first-commands"></a> 第一個指令,瀏覽檔案系統 ------------ 現代檔案系統具有目錄(資料夾)樹,其中目錄要么是*根目錄*(沒有父目錄),要么是*子目錄*(包含在單一其他目錄中,我們稱之為“父目錄”)。向後遍歷檔案樹(從子目錄到父目錄)將始終到達根目錄。有些檔案系統有多個根目錄(如 Windows 的磁碟機: `C:\` 、 `A:\`等),但 Unix 和類別 Unix 系統只有一個名為`\`的根目錄。 <a name="pwd-ls-cd"></a> ### `pwd / ls / cd` [\[ 返回目錄 \]](#toc) 在檔案系統中工作時,使用者始終*在*某個目錄中工作,我們稱之為當前目錄或*工作目錄*。使用`pwd`列印使用者的工作目錄: ``` [ andrew@pc01 ~ ]$ pwd /home/andrew ``` 使用`ls`列出該目錄的內容(檔案和/或子目錄等): ``` [ andrew@pc01 ~ ]$ ls Git TEST jdoc test test.file ``` > **獎金:** > > 使用`ls -a`顯示隱藏(“點”)文件 > > 使用`ls -l`顯示文件詳細訊息 > > 組合多個標誌,如`ls -l -a` > > 有時您可以連結諸如`ls -la`之類的標誌,而不是`ls -l -a` 使用`cd`更改到不同的目錄(更改目錄): ``` [ andrew@pc01 ~ ]$ cd TEST/ [ andrew@pc01 TEST ]$ pwd /home/andrew/TEST [ andrew@pc01 TEST ]$ cd A [ andrew@pc01 A ]$ pwd /home/andrew/TEST/A ``` `cd ..`是「 `cd`到父目錄」的簡寫: ``` [ andrew@pc01 A ]$ cd .. [ andrew@pc01 TEST ]$ pwd /home/andrew/TEST ``` `cd ~`或只是`cd`是「 `cd`到我的主目錄」的簡寫(通常`/home/username`或類似的東西): ``` [ andrew@pc01 TEST ]$ cd [ andrew@pc01 ~ ]$ pwd /home/andrew ``` > **獎金:** > > `cd ~user`表示「 `cd`到`user`的主目錄 > > 您可以使用`cd ../..`等跳轉多個目錄等級。 > > 使用`cd -`返回到最近的目錄 > > `.`是「此目錄」的簡寫,因此`cd .`不會做太多事情 <a name="semicolon-andand-and"></a> ### `; / && / &` [\[ 返回目錄 \]](#toc) 我們在命令列中輸入的內容稱為*命令*,它們總是執行儲存在電腦上某處的一些機器碼。有時這個機器碼是一個內建的Linux命令,有時它是一個應用程式,有時它是你自己寫的一些程式碼。有時,我們會想依序執行一個指令。為此,我們可以使用`;` (分號): ``` [ andrew@pc01 ~ ]$ ls; pwd Git TEST jdoc test test.file /home/andrew ``` 上面的分號表示我首先 ( `ls` ) 列出工作目錄的內容,然後 ( `pwd` ) 列印其位置。連結命令的另一個有用工具是`&&` 。使用`&&`時,如果左側命令失敗,則右側命令將不會執行。 `;`和`&&`都可以在同一行中多次使用: ``` # whoops! I made a typo here! [ andrew@pc01 ~ ]$ cd /Giit/Parser && pwd && ls && cd -bash: cd: /Giit/Parser: No such file or directory # the first command passes now, so the following commands are run [ andrew@pc01 ~ ]$ cd Git/Parser/ && pwd && ls && cd /home/andrew/Git/Parser README.md doc.sh pom.xml resource run.sh shell.sh source src target ``` ....但是與`;` ,即使第一個命令失敗,第二個命令也會執行: ``` # pwd and ls still run, even though the cd command failed [ andrew@pc01 ~ ]$ cd /Giit/Parser ; pwd ; ls -bash: cd: /Giit/Parser: No such file or directory /home/andrew Git TEST jdoc test test.file ``` `&`看起來與`&&`類似,但實際上實現了完全不同的功能。通常,當您執行長時間執行的命令時,命令列將等待該命令完成,然後才允許您輸入另一個命令。在命令後面加上`&`可以防止這種情況發生,並允許您在舊命令仍在執行時執行新命令: ``` [ andrew@pc01 ~ ]$ cd Git/Parser && mvn package & cd [1] 9263 ``` > **額外的好處:**當我們在命令後使用`&`來「隱藏」它時,我們說該作業(或「進程」;這些術語或多或少可以互換)是「後台的」。若要查看目前正在執行的背景作業,請使用`jobs`指令: > ````bash \[ andrew@pc01 ~ \]$ 職位 \[1\]+ 執行 cd Git/Parser/ && mvn package & ``` <a name="getting-help"></a> ## Getting Help <a name="minus-h"></a> ### `-h` [[ Back to Table of Contents ]](#toc) Type `-h` or `--help` after almost any command to bring up a help menu for that command: ``` \[ andrew@pc01 ~ \]$ du --help 用法:你\[選項\]...\[檔案\]... 或: du \[選項\]... --files0-from=F 對目錄遞歸地總結文件集的磁碟使用情況。 長期權的強制性參數對於短期權也是強制性的。 -0, --null 以 NUL 結束每個輸出行,而不是換行符 -a, --all 計算所有檔案的寫入計數,而不僅僅是目錄 ``` --apparent-size print apparent sizes, rather than disk usage; although ``` ``` the apparent size is usually smaller, it may be ``` ``` larger due to holes in ('sparse') files, internal ``` ``` fragmentation, indirect blocks, and the like ``` -B, --block-size=SIZE 在列印前按 SIZE 縮放大小;例如, ``` '-BM' prints sizes in units of 1,048,576 bytes; ``` ``` see SIZE format below ``` … ``` <a name="man"></a> ### `man` [[ Back to Table of Contents ]](#toc) Type `man` before almost any command to bring up a manual for that command (quit `man` with `q`): ``` LS(1) 使用者指令 LS(1) 姓名 ``` ls - list directory contents ``` 概要 ``` ls [OPTION]... [FILE]... ``` 描述 ``` List information about the FILEs (the current directory by default). ``` ``` Sort entries alphabetically if none of -cftuvSUX nor --sort is speci- ``` ``` fied. ``` ``` Mandatory arguments to long options are mandatory for short options ``` ``` too. ``` … ``` <a name="viewing-and-editing-files"></a> ## Viewing and Editing Files <a name="head-tail-cat-less"></a> ### `head / tail / cat / less` [[ Back to Table of Contents ]](#toc) `head` outputs the first few lines of a file. The `-n` flag specifies the number of lines to show (the default is 10): ``` 列印前三行 ===== \[ andrew@pc01 ~ \]$ 頭 -n 3 c 這 文件 有 ``` `tail` outputs the last few lines of a file. You can get the last `n` lines (like above), or you can get the end of the file beginning from the `N`-th line with `tail -n +N`: ``` 從第 4 行開始列印文件末尾 ============== \[ andrew@pc01 ~ \]$ tail -n +4 c 確切地 六 線 ``` `cat` concatenates a list of files and sends them to the standard output stream (usually the terminal). `cat` can be used with just a single file, or multiple files, and is often used to quickly view them. (**Be warned**: if you use `cat` in this way, you may be accused of a [_Useless Use of Cat_ (UUOC)](http://bit.ly/2SPHE4V), but it's not that big of a deal, so don't worry too much about it.) ``` \[ andrew@pc01 ~ \]$ 貓 a 歸檔一個 \[ andrew@pc01 ~ \]$ 貓 ab 歸檔一個 文件b ``` `less` is another tool for quickly viewing a file -- it opens up a `vim`-like read-only window. (Yes, there is a command called `more`, but `less` -- unintuitively -- offers a superset of the functionality of `more` and is recommended over it.) Learn more (or less?) about [less](http://man7.org/linux/man-pages/man1/less.1.html) and [more](http://man7.org/linux/man-pages/man1/more.1.html) at their `man` pages. <a name="nano-nedit"></a> ### `nano / nedit` [[ Back to Table of Contents ]](#toc) `nano` is a minimalistic command-line text editor. It's a great editor for beginners or people who don't want to learn a million shortcuts. It was more than sufficient for me for the first few years of my coding career (I'm only now starting to look into more powerful editors, mainly because defining your own syntax highlighting in `nano` can be a bit of a pain.) `nedit` is a small graphical editor, it opens up an X Window and allows point-and-click editing, drag-and-drop, syntax highlighting and more. I use `nedit` sometimes when I want to make small changes to a script and re-run it over and over. Other common CLI (command-line interface) / GUI (graphical user interface) editors include `emacs`, `vi`, `vim`, `gedit`, Notepad++, Atom, and lots more. Some cool ones that I've played around with (and can endorse) include Micro, Light Table, and VS Code. All modern editors offer basic conveniences like search and replace, syntax highlighting, and so on. `vi(m)` and `emacs` have more features than `nano` and `nedit`, but they have a much steeper learning curve. Try a few different editors out and find one that works for you! <a name="creating-and-deleting-files"></a> ## Creating and Deleting Files and Directories <a name="touch"></a> ### `touch` [[ Back to Table of Contents ]](#toc) `touch` was created to modify file timestamps, but it can also be used to quickly create an empty file. You can create a new file by opening it with a text editor, like `nano`: ``` \[ andrew@pc01 前 \]$ ls \[ andrew@pc01 ex \]$ 奈米 a ``` _...editing file..._ ``` \[ andrew@pc01 前 \]$ ls A ``` ...or by simply using `touch`: ``` \[ andrew@pc01 ex \]$ touch b && ls ab ``` > **Bonus**: > > Background a process with \^z (Ctrl+z) > > ```bash > [ andrew@pc01 ex ]$ nano a > ``` > > _...editing file, then hit \^z..._ > > ```bash > Use fg to return to nano > > [1]+ Stopped nano a > [ andrew@pc01 ex ]$ fg > ``` > > _...editing file again..._ --- > **Double Bonus:** > > Kill the current (foreground) process by pressing \^c (Ctrl+c) while it’s running > > Kill a background process with `kill %N` where `N` is the job index shown by the `jobs` command <a name="mkdir-rm-rmdir"></a> ### `mkdir / rm / rmdir` [[ Back to Table of Contents ]](#toc) `mkdir` is used to create new, empty directories: ``` \[ andrew@pc01 ex \]$ ls && mkdir c && ls ab ABC ``` You can remove any file with `rm` -- but be careful, this is non-recoverable! ``` \[ andrew@pc01 ex \]$ rm a && ls 西元前 ``` You can add an _"are you sure?"_ prompt with the `-i` flag: ``` \[ andrew@pc01 前 \]$ rm -ib rm:刪除常規空文件“b”? y ``` Remove an empty directory with `rmdir`. If you `ls -a` in an empty directory, you should only see a reference to the directory itself (`.`) and a reference to its parent directory (`..`): ``` \[ andrew@pc01 ex \]$ rmdir c && ls -a 。 .. ``` `rmdir` removes empty directories only: ``` \[ andrew@pc01 ex \]$ cd .. && ls 測試/ \*.txt 0.txt 1.txt a a.txt bc \[ andrew@pc01 ~ \]$ rmdir 測試/ rmdir:無法刪除“test/”:目錄不為空 ``` ...but you can remove a directory -- and all of its contents -- with `rm -rf` (`-r` = recursive, `-f` = force): ``` \[ andrew@pc01 ~ \]$ rm –rf 測試 ``` <a name="moving-and-copying-files"></a> ## Moving and Copying Files, Making Links, Command History <a name="mv-cp-ln"></a> ### `mv / cp / ln` [[ Back to Table of Contents ]](#toc) `mv` moves / renames a file. You can `mv` a file to a new directory and keep the same file name or `mv` a file to a "new file" (rename it): ``` \[ andrew@pc01 ex \]$ ls && mv ae && ls A B C D BCDE ``` `cp` copies a file: ``` \[ andrew@pc01 ex \]$ cp e e2 && ls BCDE E2 ``` `ln` creates a hard link to a file: ``` ln 的第一個參數是 TARGET,第二個參數是 NEW LINK ================================= \[ andrew@pc01 ex \]$ ln bf && ls bcde e2 f ``` `ln -s` creates a soft link to a file: ``` \[ andrew@pc01 ex \]$ ln -sbg && ls BCDE E2 FG ``` Hard links reference the same actual bytes in memory which contain a file, while soft links refer to the original file name, which itself points to those bytes. [You can read more about soft vs. hard links here.](http://bit.ly/2D0W8cN) <a name="command-history"></a> ### Command History [[ Back to Table of Contents ]](#toc) `bash` has two big features to help you complete and re-run commands, the first is _tab completion_. Simply type the first part of a command, hit the \<tab\> key, and let the terminal guess what you're trying to do: ``` \[ andrew@pc01 目錄 \]$ ls 另一個長檔名 這是一個長檔名 一個新檔名 \[ andrew@pc01 目錄 \]$ ls t ``` _...hit the TAB key after typing `ls t` and the command is completed..._ ``` \[ andrew@pc01 dir \]$ ls 這是檔名 這是長檔名 ``` You may have to hit \<TAB\> multiple times if there's an ambiguity: ``` \[ andrew@pc01 目錄 \]$ ls a \[ andrew@pc01 目錄 \]$ ls an 一個新檔名另一個長檔名 ``` `bash` keeps a short history of the commands you've typed previously and lets you search through those commands by typing \^r (Ctrl+r): ``` \[ andrew@pc01 目錄 \] ``` _...hit \^r (Ctrl+r) to search the command history..._ ``` (反向搜尋)``: ``` _...type 'anew' and the last command containing this is found..._ ``` (reverse-i-search)`anew': 觸碰新檔名 ``` <a name="directory-trees-disk-usage-processes"></a> ## Directory Trees, Disk Usage, and Processes <a name="mkdir--p-tree"></a> ### `mkdir –p / tree` [[ Back to Table of Contents ]](#toc) `mkdir`, by default, only makes a single directory. This means that if, for instance, directory `d/e` doesn't exist, then `d/e/f` can't be made with `mkdir` by itself: ``` \[ andrew@pc01 ex \]$ ls && mkdir d/e/f ABC mkdir:無法建立目錄「d/e/f」:沒有這樣的檔案或目錄 ``` But if we pass the `-p` flag to `mkdir`, it will make all directories in the path if they don't already exist: ``` \[ andrew@pc01 ex \]$ mkdir -pd/e/f && ls A B C D ``` `tree` can help you better visualise a directory's structure by printing a nicely-formatted directory tree. By default, it prints the entire tree structure (beginning with the specified directory), but you can restrict it to a certain number of levels with the `-L` flag: ``` \[ andrew@pc01 前 \]$ 樹 -L 2 。 |-- 一個 |-- b |-- c `--d ``` `--e ``` 3個目錄,2個文件 ``` You can hide empty directories in `tree`'s output with `--prune`. Note that this also removes "recursively empty" directories, or directories which aren't empty _per se_, but which contain only other empty directories, or other recursively empty directories: ``` \[ andrew@pc01 ex \]$ 樹 --prune 。 |-- 一個 `--b ``` <a name="df-du-ps"></a> ### `df / du / ps` [[ Back to Table of Contents ]](#toc) `df` is used to show how much space is taken up by files for the disks or your system (hard drives, etc.). ``` \[ andrew@pc01 前 \]$ df -h 已使用的檔案系統大小 可用 使用% 安裝於 udev 126G 0 126G 0% /dev tmpfs 26G 2.0G 24G 8% /執行 /dev/mapper/ubuntu--vg-root 1.6T 1.3T 252G 84% / … ``` In the above command, `-h` doesn't mean "help", but "human-readable". Some commands use this convention to display file / disk sizes with `K` for kilobytes, `G` for gigabytes, and so on, instead of writing out a gigantic integer number of bytes. `du` shows file space usage for a particular directory and its subdirectories. If you want to know how much space is free on a given hard drive, use `df`; if you want to know how much space a directory is taking up, use `du`: ``` \[ andrew@pc01 ex \]$ 你 4 ./d/e/f 8./d/e 12 ./天 4./c 20 . ``` `du` takes a `--max-depth=N` flag, which only shows directories `N` levels down (or fewer) from the specified directory: ``` \[ andrew@pc01 ex \]$ du -h --max-深度=1 12K./天 4.0K./c 20K。 ``` `ps` shows all of the user's currently-running processes (aka. jobs): ``` \[ andrew@pc01 前 \]$ ps PID TTY 時間 CMD 16642 分/15 00:00:00 ps 25409 點/15 00:00:00 重擊 ``` <a name="basic-misc"></a> ## Miscellaneous <a name="passwd-logout-exit"></a> ### `passwd / logout / exit` [[ Back to Table of Contents ]](#toc) Change your account password with `passwd`. It will ask for your current password for verification, then ask you to enter the new password twice, so you don't make any typos: ``` \[ andrew@pc01 目錄 \]$ 密碼 更改安德魯的密碼。 (目前)UNIX 密碼: 輸入新的 UNIX 密碼: 重新輸入新的 UNIX 密碼: passwd:密碼更新成功 ``` `logout` exits a shell you’ve logged in to (where you have a user account): ``` \[ andrew@pc01 目錄 \]$ 註銷 ────────────────────────────────────────────────── ── ────────────────────────────── 會話已停止 ``` - Press <return> to exit tab ``` ``` - Press R to restart session ``` ``` - Press S to save terminal output to file ``` ``` `exit` exits any kind of shell: ``` \[ andrew@pc01 ~ \]$ 退出 登出 ────────────────────────────────────────────────── ── ────────────────────────────── 會話已停止 ``` - Press <return> to exit tab ``` ``` - Press R to restart session ``` ``` - Press S to save terminal output to file ``` ``` <a name="clear-glob"></a> ### `clear / *` [[ Back to Table of Contents ]](#toc) Run `clear` to move the current terminal line to the top of the screen. This command just adds blank lines below the current prompt line. It's good for clearing your workspace. Use the glob (`*`, aka. Kleene Star, aka. wildcard) when looking for files. Notice the difference between the following two commands: ``` \[ andrew@pc01 ~ \]$ ls Git/Parser/source/ PArrayUtils.java PFile.java PSQLFile.java PWatchman.java PDateTimeUtils.java PFixedWidthFile.java PStringUtils.java PXSVFile.java PDelimitedFile.java PNode.java PTextFile.java Parser.java \[ andrew@pc01 ~ \]$ ls Git/Parser/source/PD\* Git/Parser/source/PDateTimeUtils.java Git/Parser/source/PDelimitedFile.java ``` The glob can be used multiple times in a command and matches zero or more characers: ``` \[ andrew@pc01 ~ \]$ ls Git/Parser/source/P *D* m\* Git/Parser/source/PDateTimeUtils.java Git/Parser/source/PDelimitedFile.java ``` <a name="intermediate"></a> # Intermediate <a name="disk-memory-processor"></a> ## Disk, Memory, and Processor Usage <a name="ncdu"></a> ### `ncdu` [[ Back to Table of Contents ]](#toc) `ncdu` (NCurses Disk Usage) provides a navigable overview of file space usage, like an improved `du`. It opens a read-only `vim`-like window (press `q` to quit): ``` \[ andrew@pc01 ~ \]$ ncdu ncdu 1.11 ~ 使用箭頭鍵導航,按 ?求助 \--- /home/安德魯 ------------------------------------------- ------------------ 148.2 MiB \[##########\] /.m2 91.5 MiB \[######\] /.sbt 79.8 MiB \[######\] /.cache 64.9 MiB \[####\] /.ivy2 40.6 MiB \[##\] /.sdkman 30.2 MiB \[##\] /.local 27.4 MiB \[#\] /.mozilla 24.4 MiB \[#\] /.nanobackups 10.2 MiB \[ \] .confout3.txt ``` 8.4 MiB [ ] /.config ``` ``` 5.9 MiB [ ] /.nbi ``` ``` 5.8 MiB [ ] /.oh-my-zsh ``` ``` 4.3 MiB [ ] /Git ``` ``` 3.7 MiB [ ] /.myshell ``` ``` 1.7 MiB [ ] /jdoc ``` ``` 1.5 MiB [ ] .confout2.txt ``` ``` 1.5 MiB [ ] /.netbeans ``` ``` 1.1 MiB [ ] /.jenv ``` 564.0 KiB \[ \] /.rstudio-desktop 磁碟使用總量:552.7 MiB 表觀大小:523.6 MiB 專案:14618 ``` <a name="top-htop"></a> ### `top / htop` [[ Back to Table of Contents ]](#toc) `top` displays all currently-running processes and their owners, memory usage, and more. `htop` is an improved, interactive `top`. (Note: you can pass the `-u username` flag to restrict the displayed processes to only those owner by `username`.) ``` \[ andrew@pc01 ~ \]$ htop 1 \[ 0.0%\] 9 \[ 0.0%\] 17 \[ 0.0%\] 25 \[ 0.0%\] 2 \[ 0.0%\] 10 \[ 0.0%\] 18 \[ 0.0%\] 26 \[ 0.0%\] 3 \[ 0.0%\] 11 \[ 0.0%\] 19 \[ 0.0%\] 27 \[ 0.0%\] 4 \[ 0.0%\] 12 \[ 0.0%\] 20 \[ 0.0%\] 28 \[ 0.0%\] 5 \[ 0.0%\] 13 \[ 0.0%\] 21 \[| 1.3%\] 29 \[ 0.0%\] 6 \[ 0.0%\] 14 \[ 0.0%\] 22 \[ 0.0%\] 30 \[| 0.6%\] 7 \[ 0.0%\] 15 \[ 0.0%\] 23 \[ 0.0%\] 31 \[ 0.0%\] 8 \[ 0.0%\] 16 \[ 0.0%\] 24 \[ 0.0%\] 32 \[ 0.0%\] Mem\[|||||||||||||||||||1.42G/252G\] 任務:188、366 個; 1 執行 交換電壓\[| 2.47G/256G\]平均負載:0.00 0.00 0.00 ``` Uptime: 432 days(!), 00:03:55 ``` PID USER PRI NI VIRT RES SHR S CPU% MEM% TIME+ 指令 9389 安德魯 20 0 23344 3848 2848 R 1.3 0.0 0:00.10 htop 10103 根 20 0 3216M 17896 2444 S 0.7 0.0 5h48:56 /usr/bin/dockerd ``` 1 root 20 0 181M 4604 2972 S 0.0 0.0 15:29.66 /lib/systemd/syst ``` 533 根 20 0 44676 6908 6716 S 0.0 0.0 11:19.77 /lib/systemd/syst 546 根 20 0 244M 0 0 S 0.0 0.0 0:01.39 /sbin/lvmetad -f 1526 根 20 0 329M 2252 1916 S 0.0 0.0 0:00.00 /usr/sbin/ModemMa 1544 根 20 0 329M 2252 1916 S 0.0 0.0 0:00.06 /usr/sbin/ModemMa F1Help F2Setup F3SearchF4FilterF5Tree F6SortByF7Nice -F8Nice +F9Kill F10Quit ``` <a name="REPLs-software-versions"></a> ## REPLs and Software Versions <a name="REPLs"></a> ### REPLs [[ Back to Table of Contents ]](#toc) A **REPL** is a Read-Evaluate-Print Loop, similar to the command line, but usually used for particular programming languages. You can open the Python REPL with the `python` command (and quit with the `quit()` function): ``` \[ andrew@pc01 ~ \]$ python Python 3.5.2(默認,2018 年 11 月 12 日,13:43:14)... > > > 辭職() ``` Open the R REPL with the `R` command (and quit with the `q()` function): ``` \[ andrew@pc01 ~ \]$ R R版3.5.2(2018-12-20)--「蛋殼冰屋」... > q() 儲存工作區影像? \[是/否/c\]: 否 ``` Open the Scala REPL with the `scala` command (and quit with the `:quit` command): ``` \[ andrew@pc01 ~ \]$ scala 歡迎使用 Scala 2.11.12 ... 斯卡拉>:退出 ``` Open the Java REPL with the `jshell` command (and quit with the `/exit` command): ``` \[ andrew@pc01 ~ \]$ jshell |歡迎使用 JShell——版本 11.0.1 ... jshell> /退出 ``` Alternatively, you can exit any of these REPLs with \^d (Ctrl+d). \^d is the EOF (end of file) marker on Unix and signifies the end of input. <a name="version"></a> ### `-version / --version / -v` [[ Back to Table of Contents ]](#toc) Most commands and programs have a `-version` or `--version` flag which gives the software version of that command or program. Most applications make this information easily available: ``` \[ andrew@pc01 ~ \]$ ls --version ls (GNU coreutils) 8.25 ... \[ andrew@pc01 ~ \]$ ncdu -版本 NCDU 1.11 \[ andrew@pc01 ~ \]$ python --version Python 3.5.2 ``` ...but some are less intuitive: ``` \[ andrew@pc01 ~ \]$ sbt scalaVersion … \[資訊\]2.12.4 ``` Note that some programs use `-v` as a version flag, while others use `-v` to mean "verbose", which will run the application while printing lots of diagnostic or debugging information: ``` SCP(1) BSD 通用指令手冊 SCP(1) 姓名 ``` scp -- secure copy (remote file copy program) ``` … -v 詳細模式。導致 scp 和 ssh(1) 列印偵錯訊息 ``` about their progress. This is helpful in debugging connection, ``` ``` authentication, and configuration problems. ``` … ``` <a name="env-vars-aliases"></a> ## Environment Variables and Aliases <a name="env-vars"></a> ### Environment Variables [[ Back to Table of Contents ]](#toc) **Environment variables** (sometimes shortened to "env vars") are persistent variables that can be created and used within your `bash` shell. They are defined with an equals sign (`=`) and used with a dollar sign (`$`). You can see all currently-defined env vars with `printenv`: ``` \[ andrew@pc01 ~ \]$ printenv SPARK\_HOME=/usr/local/spark 術語=xterm … ``` Set a new environment variable with an `=` sign (don't put any spaces before or after the `=`, though!): ``` \[ andrew@pc01 ~ \]$ myvar=你好 ``` Print a specific env var to the terminal with `echo` and a preceding `$` sign: ``` \[ andrew@pc01 ~ \]$ echo $myvar 你好 ``` Environment variables which contain spaces or other whitespace should be surrounded by quotes (`"..."`). Note that reassigning a value to an env var overwrites it without warning: ``` \[ andrew@pc01 ~ \]$ myvar="你好,世界!" && 回顯 $myvar 你好世界! ``` Env vars can also be defined using the `export` command. When defined this way, they will also be available to sub-processes (commands called from this shell): ``` \[ andrew@pc01 ~ \]$ export myvar="另一" && echo $myvar 另一個 ``` You can unset an environment variable by leaving the right-hand side of the `=` blank or by using the `unset` command: ``` \[ andrew@pc01 ~ \]$ 取消設定 mynewvar \[ andrew@pc01 ~ \]$ echo $mynewvar ``` <a name="aliases"></a> ### Aliases [[ Back to Table of Contents ]](#toc) **Aliases** are similar to environment variables but are usually used in a different way -- to replace long commands with shorter ones: ``` \[ andrew@pc01 apidocs \]$ ls -l -a -h -t 總計 220K drwxr-xr-x 5 安德魯 安德魯 4.0K 12 月 21 日 12:37 。 -rw-r--r-- 1 安德魯 安德魯 9.9K 十二月 21 12:37 help-doc.html -rw-r--r-- 1 安德魯 安德魯 4.5K 12 月 21 日 12:37 script.js … \[ andrew@pc01 apidocs \]$ 別名 lc="ls -l -a -h -t" \[ andrew@pc01 apidocs \]$ lc 總計 220K drwxr-xr-x 5 安德魯 安德魯 4.0K 12 月 21 日 12:37 。 -rw-r--r-- 1 安德魯 安德魯 9.9K 十二月 21 12:37 help-doc.html -rw-r--r-- 1 安德魯 安德魯 4.5K 12 月 21 日 12:37 script.js … ``` You can remove an alias with `unalias`: ``` \[ andrew@pc01 apidocs \]$ unalias lc \[ andrew@pc01 apidocs \]$ lc 目前未安裝程式“lc”。 … ``` > **Bonus:** > > [Read about the subtle differences between environment variables and aliases here.](http://bit.ly/2TDG8Tx) > > [Some programs, like **git**, allow you to define aliases specifically for that software.](http://bit.ly/2TG8X1A) <a name="basic-bash-scripting"></a> ## Basic `bash` Scripting <a name="bash-scripts"></a> ### `bash` Scripts [[ Back to Table of Contents ]](#toc) `bash` scripts (usually ending in `.sh`) allow you to automate complicated processes, packaging them into reusable functions. A `bash` script can contain any number of normal shell commands: ``` \[ andrew@pc01 ~ \]$ echo "ls && touch file && ls" > ex.sh ``` A shell script can be executed with the `source` command or the `sh` command: ``` \[ andrew@pc01 ~ \]$ 源 ex.sh 桌面 Git TEST c ex.sh 專案測試 桌面 Git TEST c ex.sh 檔案專案測試 ``` Shell scripts can be made executable with the `chmod` command (more on this later): ``` \[ andrew@pc01 ~ \]$ echo "ls && touch file2 && ls" > ex2.sh \[ andrew@pc01 ~ \]$ chmod +x ex2.sh ``` An executable shell script can be run by preceding it with `./`: ``` \[ andrew@pc01 ~ \]$ ./ex2.sh 桌面 Git TEST c ex.sh ex2.sh 檔案專案測試 桌面 Git TEST c ex.sh ex2.sh 檔案 file2 專案測試 ``` Long lines of code can be split by ending a command with `\`: ``` \[ andrew@pc01 ~ \]$ echo "for i in {1..3}; do echo \\ > \\"歡迎\\$i次\\";完成” > ex3.sh ``` Bash scripts can contain loops, functions, and more! ``` \[ andrew@pc01 ~ \]$ 源 ex3.sh 歡迎1次 歡迎2次 歡迎3次 ``` <a name="custom-prompt-ls"></a> ### Custom Prompt and `ls` [[ Back to Table of Contents ]](#toc) Bash scripting can make your life a whole lot easier and more colourful. [Check out this great bash scripting cheat sheet.](https://devhints.io/bash) `$PS1` (Prompt String 1) is the environment variable that defines your main shell prompt ([learn about the other prompts here](http://bit.ly/2SPgsmT)): ``` \[ andrew@pc01 ~ \]$ printf "%q" $PS1 $'\\n\\\[\\E\[1m\\\]\\\[\\E\[30m\\\]\\A'$'\\\[\\E\[37m\\\]|\\\[\\E\[36m\\\]\\u\\\[\\E\[37m \\\]@\\\[\\E\[34m\\\]\\h'$'\\\[\\E\[32m\\\]\\W\\\[\\E\[37m\\\]|'$'\\\[\\E(B\\E\[m\\\] ' ``` You can change your default prompt with the `export` command: ``` \[ andrew@pc01 ~ \]$ export PS1="\\n此處指令> " 此處指令> echo $PS1 \\n此處指令> ``` ...[you can add colours, too!](http://bit.ly/2TMbEit): ``` 此處指令> export PS1="\\e\[1;31m\\n程式碼: \\e\[39m" (這應該是紅色的,但在 Markdown 中可能不會這樣顯示) =============================== 程式碼:回顯$PS1 \\e\[1;31m\\n程式碼: \\e\[39m ``` You can also change the colours shown by `ls` by editing the `$LS_COLORS` environment variable: ``` (同樣,這些顏色可能不會出現在 Markdown 中) =========================== 程式碼:ls 桌面 Git TEST c ex.sh ex2.sh ex3.sh 檔案 file2 專案測試 程式碼:匯出 LS\_COLORS='di=31:fi=0:ln=96:or=31:mi=31:ex=92' 程式碼:ls 桌面 Git TEST c ex.sh ex2.sh ex3.sh 檔案 file2 專案測試 ``` <a name="config-files"></a> ## Config Files <a name="config-bashrc"></a> ### Config Files / `.bashrc` [[ Back to Table of Contents ]](#toc) If you tried the commands in the last section and logged out and back in, you may have noticed that your changes disappeared. _config_ (configuration) files let you maintain settings for your shell or for a particular program every time you log in (or run that program). The main configuration file for a `bash` shell is the `~/.bashrc` file. Aliases, environment variables, and functions added to `~/.bashrc` will be available every time you log in. Commands in `~/.bashrc` will be run every time you log in. If you edit your `~/.bashrc` file, you can reload it without logging out by using the `source` command: ``` \[ andrew@pc01 ~ \]$ nano ~/.bashrc ``` _...add the line `echo “~/.bashrc loaded!”` to the top of the file_... ``` \[ andrew@pc01 ~ \]$ 源 ~/.bashrc ~/.bashrc 已載入! ``` _...log out and log back in..._ ``` 最後登入:2019 年 1 月 11 日星期五 10:29:07 從 111.11.11.111 ~/.bashrc 已加載! \[ 安德魯@pc01 ~ \] ``` <a name="types-of-shells"></a> ### Types of Shells [[ Back to Table of Contents ]](#toc) _Login_ shells are shells you log in to (where you have a username). _Interactive_ shells are shells which accept commands. Shells can be login and interactive, non-login and non-interactive, or any other combination. In addition to `~/.bashrc`, there are a few other scripts which are `sourced` by the shell automatically when you log in or log out. These are: - `/etc/profile` - `~/.bash_profile` - `~/.bash_login` - `~/.profile` - `~/.bash_logout` - `/etc/bash.bash_logout` Which of these scripts are sourced, and the order in which they're sourced, depend on the type of shell opened. See [the bash man page](https://linux.die.net/man/1/bash) and [these](http://bit.ly/2TGCwA8) Stack Overflow [posts](http://bit.ly/2TFHFsf) for more information. Note that `bash` scripts can `source` other scripts. For instance, in your `~/.bashrc`, you could include the line: ``` 來源~/.bashrc\_addl ``` ...which would also `source` that `.bashrc_addl` script. This file can contain its own aliases, functions, environment variables, and so on. It could, in turn, `source` other scripts, as well. (Be careful to avoid infinite loops of script-sourcing!) It may be helpful to split commands into different shell scripts based on functionality or machine type (Ubuntu vs. Red Hat vs. macOS), for example: - `~/.bash_ubuntu` -- configuration specific to Ubuntu-based machines - `~/.bashrc_styles` -- aesthetic settings, like `PS1` and `LS_COLORS` - `~/.bash_java` -- configuration specific to the Java language I try to keep separate `bash` files for aesthetic configurations and OS- or machine-specific code, and then I have one big `bash` file containing shortcuts, etc. that I use on every machine and every OS. Note that there are also _different shells_. `bash` is just one kind of shell (the "Bourne Again Shell"). Other common ones include `zsh`, `csh`, `fish`, and more. Play around with different shells and find one that's right for you, but be aware that this tutorial contains `bash` shell commands only and not everything listed here (maybe none of it) will be applicable to shells other than `bash`. <a name="finding-things"></a> ## Finding Things <a name="whereis-which-whatis"></a> ### `whereis / which / whatis` [[ Back to Table of Contents ]](#toc) `whereis` searches for "possibly useful" files related to a particular command. It will attempt to return the location of the binary (executable machine code), source (code source files), and `man` page for that command: ``` \[ andrew@pc01 ~ \]$ whereis ls ls: /bin/ls /usr/share/man/man1/ls.1.gz ``` `which` will only return the location of the binary (the command itself): ``` \[ andrew@pc01 ~ \]$ 其中 ls /bin/ls ``` `whatis` prints out the one-line description of a command from its `man` page: ``` \[ andrew@pc01 ~ \]$ 什麼是哪裡是哪個什麼是 whereis (1) - 尋找指令的二進位、原始檔和手冊頁文件 which (1) - 定位指令 Whatis (1) - 顯示一行手冊頁描述 ``` `which` is useful for finding the "original version" of a command which may be hidden by an alias: ``` \[ andrew@pc01 ~ \]$ 別名 ls="ls -l" “original” ls 已被上面定義的別名“隱藏” =========================== \[ andrew@pc01 ~ \]$ ls 總計 36 drwxr-xr-x 2 安德魯 andrew 4096 Jan 9 14:47 桌面 drwxr-xr-x 4 安德魯 安德魯 4096 十二月 6 10:43 Git … 但我們仍然可以使用返回的位置來呼叫「原始」ls ======================= \[ andrew@pc01 ~ \]$ /bin/ls 桌面 Git TEST c ex.sh ex2.sh ex3.sh 檔案 file2 專案測試 ``` <a name="locate-find"></a> ### `locate / find` [[ Back to Table of Contents ]](#toc) `locate` finds a file anywhere on the system by referring to a semi-regularly-updated cached list of files: ``` \[ andrew@pc01 ~ \]$ 找到 README.md /home/andrew/.config/micro/plugins/gotham-colors/README.md /home/andrew/.jenv/README.md /home/andrew/.myshell/README.md … ``` Because it's just searching a list, `locate` is usually faster than the alternative, `find`. `find` iterates through the file system to find the file you're looking for. Because it's actually looking at the files which _currently_ exist on the system, though, it will always return an up-to-date list of files, which is not necessarily true with `locate`. ``` \[ andrew@pc01 ~ \]$ find ~/ -iname "README.md" /home/andrew/.jenv/README.md /home/andrew/.config/micro/plugins/gotham-colors/README.md /home/andrew/.oh-my-zsh/plugins/ant/README.md … ``` `find` was written for the very first version of Unix in 1971, and is therefore much more widely available than `locate`, which was added to GNU in 1994. `find` has many more features than `locate`, and can search by file age, size, ownership, type, timestamp, permissions, depth within the file system; `find` can search using regular expressions, execute commands on files it finds, and more. When you need a fast (but possibly outdated) list of files, or you’re not sure what directory a particular file is in, use `locate`. When you need an accurate file list, maybe based on something other than the files’ names, and you need to do something with those files, use `find`. <a name="downloading-things"></a> ## Downloading Things <a name="ping-wget-curl"></a> ### `ping / wget / curl` [[ Back to Table of Contents ]](#toc) `ping` attempts to open a line of communication with a network host. Mainly, it's used to check whether or not your Internet connection is down: ``` \[ andrew@pc01 ~ \]$ ping google.com PING google.com (74.125.193.100) 56(84) 位元組資料。 使用 32 位元組資料 Ping 74.125.193.100: 來自 74.125.193.100 的回覆:位元組=32 時間<1ms TTL=64 … ``` `wget` is used to easily download a file from the Internet: ``` \[ andrew@pc01 ~ \]$ wget \\ > http://releases.ubuntu.com/18.10/ubuntu-18.10-desktop-amd64.iso ``` `curl` can be used just like `wget` (don’t forget the `--output` flag): ``` \[ andrew@pc01 ~ \]$ 捲曲 \\ > http://releases.ubuntu.com/18.10/ubuntu-18.10-desktop-amd64.iso \\ > \--輸出ubuntu.iso ``` `curl` and `wget` have their own strengths and weaknesses. `curl` supports many more protocols and is more widely available than `wget`; `curl` can also send data, while `wget` can only receive data. `wget` can download files recursively, while `curl` cannot. In general, I use `wget` when I need to download things from the Internet. I don’t often need to send data using `curl`, but it’s good to be aware of it for the rare occasion that you do. <a name="apt-gunzip-tar-gzip"></a> ### `apt / gunzip / tar / gzip` [[ Back to Table of Contents ]](#toc) Debian-descended Linux distributions have a fantastic package management tool called `apt`. It can be used to install, upgrade, or delete software on your machine. To search `apt` for a particular piece of software, use `apt search`, and install it with `apt install`: ``` \[ andrew@pc01 ~ \]$ apt 搜尋漂白位 ...bleachbit/bionic、bionic 2.0-2 全部 從系統中刪除不需要的文件 您需要“sudo”來安裝軟體 ============== \[ andrew@pc01 ~ \]$ sudo apt installbleachbit ``` Linux software often comes packaged in `.tar.gz` ("tarball") files: ``` \[ andrew@pc01 ~ \]$ wget \\ > https://github.com/atom/atom/releases/download/v1.35.0-beta0/atom-amd64.tar.gz ``` ...these types of files can be unzipped with `gunzip`: ``` \[ andrew@pc01 ~ \]$gunzipatom-amd64.tar.gz && ls 原子 amd64.tar ``` A `.tar.gz` file will be `gunzip`-ped to a `.tar` file, which can be extracted to a directory of files using `tar -xf` (`-x` for "extract", `-f` to specify the file to "untar"): ``` \[ andrew@pc01 ~ \]$ tar -xfatom-amd64.tar && mv \\ 原子-beta-1.35.0-beta0-amd64 原子 && ls 原子atom-amd64.tar ``` To go in the reverse direction, you can create (`-c`) a tar file from a directory and zip it (or unzip it, as appropriate) with `-z`: ``` \[ andrew@pc01 ~ \]$ tar -zcf 壓縮.tar.gz 原子 && ls 原子atom-amd64.tar壓縮.tar.gz ``` `.tar` files can also be zipped with `gzip`: ``` \[ andrew@pc01 ~ \]$ gzipatom-amd64.tar && ls 原子 原子-amd64.tar.gz 壓縮.tar.gz ``` <a name="redirecting-io"></a> ## Redirecting Input and Output <a name="pipe-gt-lt-echo-printf"></a> ### `| / > / < / echo / printf` [[ Back to Table of Contents ]](#toc) By default, shell commands read their input from the standard input stream (aka. stdin or 0) and write to the standard output stream (aka. stdout or 1), unless there’s an error, which is written to the standard error stream (aka. stderr or 2). `echo` writes text to stdout by default, which in most cases will simply print it to the terminal: ``` \[ andrew@pc01 ~ \]$ 回顯“你好” 你好 ``` The pipe operator, `|`, redirects the output of the first command to the input of the second command: ``` 'wc'(字數)傳回檔案中的行數、字數、位元組數 ======================== \[ andrew@pc01 ~ \]$ echo "範例文件" |廁所 ``` 1 2 17 ``` ``` `>` redirects output from stdout to a particular location ``` \[ andrew@pc01 ~ \]$ echo "test" > 文件 && 頭文件 測試 ``` `printf` is an improved `echo`, allowing formatting and escape sequences: ``` \[ andrew@pc01 ~ \]$ printf "1\\n3\\n2" 1 3 2 ``` `<` gets input from a particular location, rather than stdin: ``` 'sort' 依字母/數字順序對檔案的行進行排序 ======================== \[ andrew@pc01 ~ \]$ sort <(printf "1\\n3\\n2") 1 2 3 ``` Rather than a [UUOC](#viewing-and-editing-files), the recommended way to send the contents of a file to a command is to use `<`. Note that this causes data to "flow" right-to-left on the command line, rather than (the perhaps more natural, for English-speakers) left-to-right: ``` \[ andrew@pc01 ~ \]$ printf "1\\n3\\n2" > 文件 && 排序 < 文件 1 2 3 ``` <a name="std-tee"></a> ### `0 / 1 / 2 / tee` [[ Back to Table of Contents ]](#toc) 0, 1, and 2 are the standard input, output, and error streams, respectively. Input and output streams can be redirected with the `|`, `>`, and `<` operators mentioned previously, but stdin, stdout, and stderr can also be manipulated directly using their numeric identifiers: Write to stdout or stderr with `>&1` or `>&2`: ``` \[ andrew@pc01 ~ \]$ 貓測試 回顯“標準輸出”>&1 回顯“標準錯誤”>&2 ``` By default, stdout and stderr both print output to the terminal: ``` \[ andrew@pc01 ~ \]$ ./測試 標準錯誤 標準輸出 ``` Redirect stdout to `/dev/null` (only print output sent to stderr): ``` \[ andrew@pc01 ~ \]$ ./test 1>/dev/null 標準錯誤 ``` Redirect stderr to `/dev/null` (only print output sent to stdout): ``` \[ andrew@pc01 ~ \]$ ./test 2>/dev/null 標準輸出 ``` Redirect all output to `/dev/null` (print nothing): ``` \[ andrew@pc01 ~ \]$ ./test &>/dev/null ``` Send output to stdout and any number of additional locations with `tee`: ``` \[ andrew@pc01 ~ \]$ ls && echo "測試" | tee 文件1 文件2 文件3 && ls 文件0 測試 文件0 文件1 文件2 文件3 ``` <a name="advanced"></a> # Advanced <a name="superuser"></a> ## Superuser <a name="sudo-su"></a> ### `sudo / su` [[ Back to Table of Contents ]](#toc) You can check what your username is with `whoami`: ``` \[ andrew@pc01 abc \]$ whoami 安德魯 ``` ...and run a command as another user with `sudo -u username` (you will need that user's password): ``` \[ andrew@pc01 abc \]$ sudo -u 測試觸摸 def && ls -l 總計 0 -rw-r--r-- 1 次測試 0 Jan 11 20:05 def ``` If `–u` is not provided, the default user is the superuser (usually called "root"), with unlimited permissions: ``` \[ andrew@pc01 abc \]$ sudo touch ghi && ls -l 總計 0 -rw-r--r-- 1 次測試 0 Jan 11 20:05 def -rw-r--r-- 1 root root 0 Jan 11 20:14 ghi ``` Use `su` to become another user temporarily (and `exit` to switch back): ``` \[ andrew@pc01 abc \]$ su 測試 密碼: test@pc01:/home/andrew/abc$ whoami 測試 test@pc01:/home/andrew/abc$ 退出 出口 \[ andrew@pc01 abc \]$ whoami 安德魯 ``` [Learn more about the differences between `sudo` and `su` here.](http://bit.ly/2SKQH77) <a name="click-click"></a> ### `!!` [[ Back to Table of Contents ]](#toc) The superuser (usually "root") is the only person who can install software, create users, and so on. Sometimes it's easy to forget that, and you may get an error: ``` \[ andrew@pc01 ~ \]$ apt 安裝 ruby E:無法開啟鎖定檔案 /var/lib/dpkg/lock-frontend - 開啟(13:權限被拒絕) E: 無法取得 dpkg 前端鎖定 (/var/lib/dpkg/lock-frontend),您是 root 嗎? ``` You could retype the command and add `sudo` at the front of it (run it as the superuser): ``` \[ andrew@pc01 ~ \]$ sudo apt install ruby 正在閱讀包裝清單... ``` Or, you could use the `!!` shortcut, which retains the previous command: ``` \[ andrew@pc01 ~ \]$ apt 安裝 ruby E:無法開啟鎖定檔案 /var/lib/dpkg/lock-frontend - 開啟(13:權限被拒絕) E: 無法取得 dpkg 前端鎖定 (/var/lib/dpkg/lock-frontend),您是 root 嗎? \[ andrew@pc01 ~ \]$ sudo !! sudo apt 安裝 ruby 正在閱讀包裝清單... ``` By default, running a command with `sudo` (and correctly entering the password) allows the user to run superuser commands for the next 15 minutes. Once those 15 minutes are up, the user will again be prompted to enter the superuser password if they try to run a restricted command. <a name="file-permissions"></a> ## File Permissions <a name="file-permissions-sub"></a> ### File Permissions [[ Back to Table of Contents ]](#toc) Files may be able to be read (`r`), written to (`w`), and/or executed (`x`) by different users or groups of users, or not at all. File permissions can be seen with the `ls -l` command and are represented by 10 characters: ``` \[ andrew@pc01 ~ \]$ ls -lh 總計 8 drwxr-xr-x 4 安德魯 安德魯 4.0K 1 月 4 日 19:37 品嚐 -rwxr-xr-x 1 安德魯 安德魯 40 Jan 11 16:16 測試 -rw-r--r-- 1 安德魯 安德魯 0 一月 11 16:34 tist ``` The first character of each line represents the type of file, (`d` = directory, `l` = link, `-` = regular file, and so on); then there are three groups of three characters which represent the permissions held by the user (u) who owns the file, the permissions held by the group (g) which owns the file, and the permissions held any other (o) users. (The number which follows this string of characters is the number of links in the file system to that file (4 or 1 above).) `r` means that person / those people have read permission, `w` is write permission, `x` is execute permission. If a directory is “executable”, that means it can be opened and its contents can be listed. These three permissions are often represented with a single three-digit number, where, if `x` is enabled, the number is incremented by 1, if `w` is enabled, the number is incremented by 2, and if `r` is enabled, the number is incremented by 4. Note that these are equivalent to binary digits (`r-x` -> `101` -> `5`, for example). So the above three files have permissions of 755, 755, and 644, respectively. The next two strings in each list are the name of the owner (`andrew`, in this case) and the group of the owner (also `andrew`, in this case). Then comes the size of the file, its most recent modification time, and its name. The `–h` flag makes the output human readable (i.e. printing `4.0K` instead of `4096` bytes). <a name="chmod-chown"></a> ### `chmod / chown` [[ Back to Table of Contents ]](#toc) File permissions can be modified with `chmod` by setting the access bits: ``` \[ andrew@pc01 ~ \]$ chmod 777 測試 && chmod 000 tit && ls -lh 總計 8.0K drwxr-xr-x 4 安德魯 安德魯 4.0K 1 月 4 日 19:37 品嚐 -rwxrwxrwx 1 安德魯 安德魯 40 Jan 11 16:16 測試 \---------- 1 安德魯 安德魯 0 一月 11 16:34 tist ``` ...or by adding (`+`) or removing (`-`) `r`, `w`, and `x` permissions with flags: ``` \[ andrew@pc01 ~ \]$ chmod +rwx Tist && chmod -w 測試 && ls -lh chmod:測試:新權限是 r-xrwxrwx,而不是 r-xr-xr-x 總計 8.0K drwxr-xr-x 4 安德魯 安德魯 4.0K 1 月 4 日 19:37 品嚐 -r-xrwxrwx 1 安德魯 安德魯 40 Jan 11 16:16 測試 -rwxr-xr-x 1 安德魯 安德魯 0 一月 11 16:34 tist ``` The user who owns a file can be changed with `chown`: ``` \[ andrew@pc01 ~ \]$ sudo chown 碼頭測試 ``` The group which owns a file can be changed with `chgrp`: ``` \[ andrew@pc01 ~ \]$ sudo chgrp hadoop tit && ls -lh 總計 8.0K drwxr-xr-x 4 安德魯 安德魯 4.0K 1 月 4 日 19:37 品嚐 \-----w--w- 1 瑪麗娜·安德魯 2011 年 1 月 40 日 16:16 測試 -rwxr-xr-x 1 安德魯 hadoop 0 一月 11 16:34 tist ``` <a name="users-groups"></a> ## User and Group Management <a name="users"></a> ### Users [[ Back to Table of Contents ]](#toc) `users` shows all users currently logged in. Note that a user can be logged in multiple times if -- for instance -- they're connected via multiple `ssh` sessions. ``` \[ andrew@pc01 ~ \]$ 用戶 安德魯·科林·科林·科林·科林·科林·克里希納·克里希納 ``` To see all users (even those not logged in), check `/etc/passwd`. (**WARNING**: do not modify this file! You can corrupt your user accounts and make it impossible to log in to your system.) ``` \[ andrew@pc01 ~ \]$ alias au="cut -d: -f1 /etc/passwd \\ > |排序| uniq”&& au \_易於 一個廣告 安德魯... ``` Add a user with `useradd`: ``` \[ andrew@pc01 ~ \]$ sudo useradd aardvark && au \_易於 土豚 一個廣告... ``` Delete a user with `userdel`: ``` \[ andrew@pc01 ~ \]$ sudo userdel aardvark && au \_易於 一個廣告 安德魯... ``` [Change a user’s default shell, username, password, or group membership with `usermod`.](http://bit.ly/2D4upIg) <a name="groups"></a> ### Groups [[ Back to Table of Contents ]](#toc) `groups` shows all of the groups of which the current user is a member: ``` \[ andrew@pc01 ~ \]$ 組 andrew adm cdrom sudo dial plugdev lpadmin sambashare hadoop ``` To see all groups on the system, check `/etc/group`. (**DO NOT MODIFY** this file unless you know what you are doing.) ``` \[ andrew@pc01 ~ \]$ alias ag=“cut -d: -f1 /etc/group \\ > |排序”&& ag 管理員 一個廣告 安德魯... ``` Add a group with `groupadd`: ``` \[ andrew@pc01 ~ \]$ sudo groupadd aardvark && ag 土豚 管理員 一個廣告... ``` Delete a group with `groupdel`: ``` \[ andrew@pc01 ~ \]$ sudo groupdel aardvark && ag 管理員 一個廣告 安德魯... ``` [Change a group’s name, ID number, or password with `groupmod`.](https://linux.die.net/man/8/groupmod) <a name="text-processing"></a> ## Text Processing <a name="uniq-sort-diff-cmp"></a> ### `uniq / sort / diff / cmp` [[ Back to Table of Contents ]](#toc) `uniq` can print unique lines (default) or repeated lines: ``` \[ andrew@pc01 man \]$ printf "1\\n2\\n2" > a && \\ > printf "1\\n3\\n2" > b \[ andrew@pc01 人 \]$ uniq a 1 2 ``` `sort` will sort lines alphabetically / numerically: ``` \[ andrew@pc01 man \]$ 排序 b 1 2 3 ``` `diff` will report which lines differ between two files: ``` \[ andrew@pc01 人 \]$ diff ab 2c2 < 2 --- > 3 ``` `cmp` reports which bytes differ between two files: ``` \[andrew@pc01 人\]$ cmp ab ab 不同:字元 3,第 2 行 ``` <a name="cut-sed"></a> ### `cut / sed` [[ Back to Table of Contents ]](#toc) `cut` is usually used to cut a line into sections on some delimiter (good for CSV processing). `-d` specifies the delimiter and `-f` specifies the field index to print (starting with 1 for the first field): ``` \[ andrew@pc01 人 \]$ printf "137.99.234.23" > c \[ andrew@pc01 man \]$ cut -d'.' c-f1 137 ``` `sed` is commonly used to replace a string with another string in a file: ``` \[ andrew@pc01 man \]$ echo "舊" | sed s/舊/新/ 新的 ``` ...but `sed` is an extremely powerful utility, and cannot be properly summarised here. It’s actually Turing-complete, so it can do anything that any other programming language can do. `sed` can find and replace based on regular expressions, selectively print lines of a file which match or contain a certain pattern, edit text files in-place and non-interactively, and much more. A few good tutorials on `sed` include: - [https://www.tutorialspoint.com/sed/](https://www.tutorialspoint.com/sed/) - [http://www.grymoire.com/Unix/Sed.html](http://www.grymoire.com/Unix/Sed.html) - [https://www.computerhope.com/unix/used.htm](https://www.computerhope.com/unix/used.htm) <a name="pattern-matching"></a> ## Pattern Matching <a name="grep"></a> ### `grep` [[ Back to Table of Contents ]](#toc) The name `grep` comes from `g`/`re`/`p` (search `g`lobally for a `r`egular `e`xpression and `p`rint it); it’s used for finding text in files. `grep` is used to find lines of a file which match some pattern: ``` \[ andrew@pc01 ~ \]$ grep -e " *.fi.* " /etc/profile /etc/profile:Bourne shell 的系統範圍 .profile 檔案 (sh(1)) =================================================== ``` # The file bash.bashrc already sets the default PS1. ``` ``` fi ``` ``` fi ``` … ``` ...or contain some word: ``` \[ andrew@pc01 ~ \]$ grep "andrew" /etc/passwd 安德魯:x:1000:1000:安德魯,,,:/home/andrew:/bin/bash ``` `grep` is usually the go-to choice for simply finding matching lines in a file, if you’re planning on allowing some other program to handle those lines (or if you just want to view them). `grep` allows for (`-E`) use of extended regular expressions, (`-F`) matching any one of multiple strings at once, and (`-r`) recursively searching files within a directory. These flags used to be implemented as separate commands (`egrep`, `fgrep`, and `rgrep`, respectively), but those commands are now deprecated. > **Bonus**: [see the origins of the names of a few famous `bash` commands](https://kb.iu.edu/d/abnd) <a name="awk"></a> ### `awk` [[ Back to Table of Contents ]](#toc) `awk` is a pattern-matching language built around reading and manipulating delimited data files, like CSV files. As a rule of thumb, `grep` is good for finding strings and patterns in files, `sed` is good for one-to-one replacement of strings in files, and `awk` is good for extracting strings and patterns from files and analysing them. As an example of what `awk` can do, here’s a file containing two columns of data: ``` \[ andrew@pc01 ~ \]$ printf "A 10\\nB 20\\nC 60" > 文件 ``` Loop over the lines, add the number to sum, increment count, print the average: ``` \[ andrew@pc01 ~ \]$ awk 'BEGIN {sum=0;計數=0; OFS=“”} {sum+=$2; count++} END {print "平均值:", sum/count}' 文件 平均:30 ``` `sed` and `awk` are both Turing-complete languages. There have been multiple books written about each of them. They can be extremely useful with pattern matching and text processing. I really don’t have enough space here to do either of them justice. Go read more about them! > **Bonus**: [learn about some of the differences between `sed`, `grep`, and `awk`](http://bit.ly/2AI3IaN) <a name="ssh"></a> ## Copying Files Over `ssh` <a name="ssh-scp"></a> ### `ssh / scp` [[ Back to Table of Contents ]](#toc) `ssh` is how Unix-based machines connect to each other over a network: ``` \[ andrew@pc01 ~ \]$ ssh –p安德魯@137.xxx.xxx.89 上次登入:2019 年 1 月 11 日星期五 12:30:52,來自 137.xxx.xxx.199 ``` Notice that my prompt has changed as I’m now on a different machine: ``` \[ andrew@pc02 ~ \]$ 退出 登出 與 137.xxx.xxx.89 的連線已關閉。 ``` Create a file on machine 1: ``` \[ andrew@pc01 ~ \]$ echo "你好" > 你好 ``` Copy it to machine 2 using `scp` (secure copy; note that `scp` uses `–P` for a port #, `ssh` uses `–p`) ``` \[ andrew@pc01 ~ \]$ scp –P你好安德魯@137.xxx.xxx.89:~ 你好 100% 0 0.0KB/秒 00:00 ``` `ssh` into machine 2: ``` \[ andrew@pc02 ~ \]$ ssh –p安德魯@137.xxx.xxx.89 上次登入:2019 年 1 月 11 日星期五 22:47:37,來自 137.xxx.xxx.79 ``` The file’s there! ``` \[ andrew@pc02 ~ \]$ ls 你好多xargs \[ andrew@pc02 ~ \]$ 貓你好 你好 ``` <a name="rsync"></a> ### `rsync` [[ Back to Table of Contents ]](#toc) `rsync` is a file-copying tool which minimises the amount of data copied by looking for deltas (changes) between files. Suppose we have two directories: `d`, with one file, and `s`, with two files: ``` \[ andrew@pc01 d \]$ ls && ls ../s f0 f0 f1 ``` Sync the directories (copying only missing data) with `rsync`: ``` \[ andrew@pc01 d \]$ rsync -off ../s/\* . 正在發送增量文件列表... ``` `d` now contains all files that `s` contains: ``` \[ andrew@pc01 d \]$ ls f0 f1 ``` `rsync` can be performed over `ssh` as well: ``` \[ andrew@pc02 r \]$ ls \[ andrew@pc02 r \]$ rsync -avz -e "ssh -p “ [email protected]:~/s/\* 。 接收增量檔案列表 f0 f1 發送 62 位元組 接收 150 位元組 141.33 位元組/秒 總大小為 0 加速率為 0.00 \[ andrew@pc02 r \]$ ls f0 f1 ``` <a name="long-running-processes"></a> ## Long-Running Processes <a name="yes-nohup-ps-kill"></a> ### `yes / nohup / ps / kill` [[ Back to Table of Contents ]](#toc) Sometimes, `ssh` connections can disconnect due to network or hardware problems. Any processes initialized through that connection will be “hung up” and terminate. Running a command with `nohup` insures that the command will not be hung up if the shell is closed or if the network connection fails. Run `yes` (continually outputs "y" until it’s killed) with `nohup`: ``` \[ andrew@pc01 ~ \]$ nohup 是 & \[1\]13173 ``` `ps` shows a list of the current user’s processes (note PID number 13173): ``` \[ andrew@pc01 ~ \]$ ps | sed -n '/是/p' 13173 分/10 00:00:12 是 ``` _...log out and log back into this shell..._ The process has disappeared from `ps`! ``` \[ andrew@pc01 ~ \]$ ps | sed -n '/是/p' ``` But it still appears in `top` and `htop` output: ``` \[ andrew@pc01 ~ \]$ 頂部 -bn 1 | sed -n '/是/p' 13173 安德魯 20 0 4372 704 636 D 25.0 0.0 0:35.99 是 ``` Kill this process with `-9` followed by its process ID (PID) number: ``` \[ andrew@pc01 ~ \]$ 殺死 -9 13173 ``` It no longer appears in `top`, because it’s been killed: ``` \[ andrew@pc01 ~ \]$ 頂部 -bn 1 | sed -n '/是/p' ``` <a name="cron"></a> ### `cron / crontab / >>` [[ Back to Table of Contents ]](#toc) `cron` provides an easy way of automating regular, scheduled tasks. You can edit your `cron` jobs with `crontab –e` (opens a text editor). Append the line: ``` - - - - - 日期 >> ~/datefile.txt ``` This will run the `date` command every minute, appending (with the `>>` operator) the output to a file: ``` \[ andrew@pc02 ~ \]$ head ~/datefile.txt 2019 年 1 月 12 日星期六 14:37:01 GMT 2019 年 1 月 12 日星期六

S.O.L.I.D:提升編碼技能的 5 個黃金法則

在軟體開發領域,這個以其多樣化和強烈持有觀點而聞名的領域,很少有實踐能夠像 SOLID 原則那樣達成共識,作為成為更好的軟體工程師的保證途徑。 Robert C. Martin 在 2000 年代初期正式製定的 5 條黃金法則極大地影響了軟體開發產業,並為更好的程式碼品質和決策過程製定了新標準,至今仍具有相關性。 ![堅實的原則](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l2mdlic5qf7f0ws36owf.jpg) SOLID 原則是專門為支援 OOP(物件導向程式設計)範例而設計的。因此,本文是為希望提高開發技能並編寫更優雅、可維護和可擴展程式碼的 OOP 開發人員而設計的。 這裡使用的語言是 TypeScript,遵循常見的跨語言 OOP 概念。需要基本的 OOP 知識。 --- 1. S = 單一職責原則(SRP) ------------------ 單一職責原則 (SRP) 是五個 SOLID 原則之一,它規定每個類別應該只有一個職責,以保持有意義的關注點分離。 此模式是一種稱為「上帝物件」的常見反模式的解決方案,「上帝物件」只是指承擔太多職責的類別或物件,使其難以理解、測試和維護。 遵循 SRP 規則有助於使程式碼元件可重複使用、鬆散耦合且易於理解。讓我們探討這項原則,展示 SRP 違規情況和解決方案。 ### 全域宣告 ``` enum Color { BLUE = 'blue', GREEN = 'green', RED = 'red' } enum Size { SMALL = 'small', MEDIUM = 'medium', LARGE = 'large' } class Product { private _name: string; private _color: Color; private _size: Size; constructor (name: string, color: Color, size: Size) { this._name = name; this._color = color; this._size = size; } public get name(): string { return this._name; } public get color(): Color { return this._color; } public get size(): Size { return this._size; } } ``` ### 違反 在下面的程式碼中, `ProductManager`類別負責**products 的建立和存儲**,違反了單一職責原則。 ``` class ProductManager { private _products: Product[] = []; createProduct (name: string, color: Color, size: Size): Product { return new Product(name, color, size); } storeProduct (product: Product): void { this._products.push(product); } getProducts (): Product[] { return this._products; } } const productManager: ProductManager = new ProductManager(); const product: Product = productManager.createProduct('Product 1', Color.BLUE, Size.LARGE); productManager.storeProduct(product); const allProducts: Product[] = productManager.getProducts(); ``` ### 解決 將產品建立和儲存的處理分離到兩個不同的類別可以減少`ProductManager`類別的職責數量。這種方法進一步模組化了程式碼並使其更易於維護。 ``` class ProductManager { createProduct (name: string, color: Color, size: Size): Product { return new Product(name, color, size); } } class ProductStorage { private _products: Product[] = []; storeProduct (product: Product): void { this._products.push(product); } getProducts (): Product[] { return this._products; } } ``` #### 用法: ``` const productManager: ProductManager = new ProductManager(); const productStorage: ProductStorage = new ProductStorage(); const product: Product = productManager.createProduct("Product 1", Color.BLUE, Size.LARGE); productStorage.storeProduct(product); const allProducts: Product[] = productStorage.getProducts(); ``` --- 2. O = 開閉原理 (OCP) ----------------- > “軟體實體應該對擴展開放,但對修改關閉” 開閉原則 (OCP) 是*「寫一次,寫得夠好以便可擴展,然後就忘記它」。* 這項原則的重要性取決於這樣一個事實:模組可能會根據新的需求不時發生變化。如果在模組編寫、測試並上傳到生產環境後出現新需求,則修改此模組通常是不好的做法,尤其是當其他模組依賴它時。為了防止這種情況,我們可以使用開閉原則。 ### 全域宣告 ``` enum Color { BLUE = 'blue', GREEN = 'green', RED = 'red' } enum Size { SMALL = 'small', MEDIUM = 'medium', LARGE = 'large' } class Product { private _name: string; private _color: Color; private _size: Size; constructor (name: string, color: Color, size: Size) { this._name = name; this._color = color; this._size = size; } public get name(): string { return this._name; } public get color(): Color { return this._color; } public get size(): Size { return this._size; } } class Inventory { private _products: Product[] = []; public add(product: Product): void { this._products.push(product); } addArray(products: Product[]) { for (const product of products) { this.add(product); } } public get products(): Product[] { return this._products; } } ``` ### 違反 讓我們描述一個實作產品過濾類別的場景。讓我們加入按顏色過濾產品的功能。 ``` class ProductsFilter { byColor(inventory: Inventory, color: Color): Product[] { return inventory.products.filter(p => p.color === color); } } ``` 我們已經測試了此程式碼並將其部署到生產中。 幾天后,客戶請求一項新功能 - 也按大小過濾。然後我們修改該類別以支援新的要求。 **現在違反了開閉原則!** ``` class ProductsFilter { byColor(inventory: Inventory, color: Color): Product[] { return inventory.products.filter(p => p.color === color); } bySize(inventory: Inventory, size: Size): Product[] { return inventory.products.filter(p => p.size === size); } } ``` ### 解決 在不違反 OCP 的情況下實現過濾機制的正確方法應該使用「規範」類別。 ``` abstract class Specification { public abstract isValid(product: Product): boolean; } class ColorSpecification extends Specification { private _color: Color; constructor (color) { super(); this._color = color; } public isValid(product: Product): boolean { return product.color === this._color; } } class SizeSpecification extends Specification { private _size: Size; constructor (size) { super(); this._size = size; } public isValid(product: Product): boolean { return product.size === this._size; } } // A robust mechanism to allow different combinations of specifications class AndSpecification extends Specification { private _specifications: Specification[]; // "...rest" operator, groups the arguments into an array constructor ((...specifications): Specification[]) { super(); this._specifications = specifications; } public isValid (product: Product): boolean { return this._specifications.every(specification => specification.isValid(product)); } } class ProductsFilter { public filter (inventory: Inventory, specification: Specification): Product[] { return inventory.products.filter(product => specification.isValid(product)); } } ``` #### 用法: ``` const p1: Product = new Product('Apple', Color.GREEN, Size.LARGE); const p2: Product = new Product('Pear', Color.GREEN, Size.LARGE); const p3: Product = new Product('Grapes', Color.GREEN, Size.SMALL); const p4: Product = new Product('Blueberries', Color.BLUE, Size.LARGE); const p5: Product = new Product('Watermelon', Color.RED, Size.LARGE); const inventory: Inventory = new Inventory(); inventory.addArray([p1, p2, p3, p4, p5]); const greenColorSpec: ColorSpecification = new ColorSpecification(Color.GREEN); const largeSizeSpec: SizeSpecification = new SizeSpecification(Size.LARGE); const andSpec: AndSpecification = new AndSpecification(greenColorSpec, largeSizeSpec); const productsFilter: ProductsFilter = new ProductsFilter(); const filteredProducts: Product[] = productsFilter.filter(inventory, andSpec); // All large green products ``` 過濾機制現在是完全可擴展的。現有的類別不應該再被修改。 如果有新的過濾要求,我們只需建立一個新規範即可。或者如果需要更改規範組合,可以透過使用`AndSpecification`類別輕鬆完成。 --- 3. L=里氏替換原理(LSP) ---------------- 里氏替換原則(LSP)是軟體元件靈活性和穩健性的重要規則。它由 Barbara Liskov 提出,並成為 SOLID 原則的基本要素。 LSP 規定**超類別的物件應該可以用子類別的物件替換,而不影響程式的正確性。**換句話說,子類別應該擴展超類別的行為而不改變其原始功能。採用這種方法可以提高軟體元件的質量,確保可重複使用性並減少意外的副作用。 ### 違反 下面的範例說明了違反里氏替換原則 (LSP) 的場景。當`Rectangle`物件被`Square`物件取代時,透過檢查程序的行為可以觀察到這種違規的跡象。 #### 聲明: ``` class Rectangle { protected _width: number; protected _height: number; constructor (width: number, height: number) { this._width = width; this._height = height; } get width (): number { return this._width; } get height (): number { return this._height; } set width (width: number) { this._width = width; } set height (height: number) { this._height = height; } getArea (): number { return this._width * this._height; } } // A square is also rectangle class Square extends Rectangle { get width (): number { return this._width; } get height (): number { return this._height; } set height (height: number) { this._height = this._width = height; // Changing both width & height } set width (width: number) { this._width = this._height = width; // Changing both width & height } } function increaseRectangleWidth(rectangle: Rectangle, byAmount: number) { rectangle.width += byAmount; } ``` #### 用法: ``` const rectangle: Rectangle = new Rectangle(5, 5); const square: Square = new Square(5, 5); console.log(rectangle.getArea()); // Expected: 25, Got: 25 (V) console.log(square.getArea()); // Expected: 25, Got: 25 (V) // LSP Violation Indication: Can't replace object 'rectangle' (superclass) with 'square' (subclass) since the results would be different. increaseRectangleWidth(rectangle, 5); increaseRectangleWidth(square, 5); console.log(rectangle.getArea()); // Expected: 50, Got: 50 (V) // LSP Violation, increaseRectangleWidth() changed both width and height of the square, unexpected behavior. console.log(square.getArea()); //Expected: 50, Got: 100 (X) ``` ### 解決 重構的程式碼現在遵循 LSP,確保超類別`Shape`的物件可以替換為子類別`Rectangle`和`Square`的物件,而不會影響計算面積的正確性,也不會引入任何改變程式行為的不必要的副作用。 #### 聲明: ``` abstract class Shape { public abstract getArea(): number; } class Rectangle extends Shape { private _width: number; private _height: number; constructor (width: number, height: number) { super(); this._width = width; this._height = height; } getArea (): number { return this._width * this._height; } } class Square extends Shape { private _side: number; constructor (side: number) { super(); this._side = side; } getArea (): number { return this._side * this._side; } } function displayArea (shape: Shape): void { console.log(shape.getArea()); } ``` #### 用法: ``` const rectangle: Rectangle = new Rectangle(5, 10); const square: Square = new Square(5); // The rectangle's area is correctly calculated displayArea(rectangle); // Expected: 50, Got: 50 (V) // The square's area is correctly calculated displayArea(square); // Expected: 25, Got: 25 (V) ``` --- 4. I = 介面隔離原則 (ISP) ------------------- 介面隔離原則 (ISP) 強調建立特定於客戶端的介面而不是一刀切的重要性。 這種方法根據客戶的需求集中類,消除了類別必須實現它實際上不使用或不需要的方法的情況。 透過應用介面隔離原則,軟體系統可以以更靈活、易於理解和易於重構的方式建構。讓我們來看一個例子。 ### 違反 這裡違反了 ISP 規則,因為`Robot`必須實現完全沒有必要的`eat()`函數。 ``` interface Worker { work(): void; eat(): void; } class Developer implements Worker { public work(): void { console.log('Coding..'); } public eat(): void { console.log('Eating..'); } } class Robot implements Worker { public work(): void { console.log('Building a car..'); } // ISP Violation: Robot is forced to implement this function even when unnecessary public eat(): void { throw new Error('Cannot eat!'); } } ``` ### 解決 下面的範例代表了我們之前遇到的問題的解決方案。現在,介面更加簡潔且更加特定於客戶端,允許客戶端類別僅實現與其相關的方法。 ``` interface Workable { work(): void; } interface Eatable { eat(): void; } class Developer implements Workable, Eatable { public work(): void { console.log('Coding..'); } public eat(): void { console.log('Eating...'); } } class Robot implements Workable { public work(): void { console.log('Building a car..'); } // No need to implement eat(), adhering ISP. } ``` #### ISP 前後: ![重構前後的介面隔離原則](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/szh5wkpkc30z4t91j5oy.png) --- 5. D = 依賴倒置原理(DIP) ------------------ 依賴倒置原則(DIP)是最終的SOLID原則,重點是透過使用抽象來減少低層模組(例如資料讀取/寫入)和高層模組(執行關鍵操作)之間的耦合。 DIP 對於設計能夠適應變化、模組化且易於更新的軟體至關重要。 **DIP 的關鍵準則是:** 1. **高層模組不應該依賴低層模組。兩者都應該依賴抽象。**這意味著應用程式的功能不應該依賴特定的實現,以便使系統更加靈活並且更容易更新或替換低階實現。 2. **抽像不應該依賴細節。細節應該取決於抽象。**這鼓勵設計專注於實際需要什麼操作,而不是如何實現這些操作。 ### 違反 讓我們來看一個展示依賴倒置原則 (DIP) 違規的範例。 `MessageProcessor` (高階模組)緊密耦合並直接依賴`FileLogger` (低階模組),違反了原則,因為它不依賴抽象層,而是依賴特定的類別實作。 **額外獎勵:**這也違反了開閉原則(OCP)。如果我們想要更改日誌記錄機制以寫入資料庫而不是文件,我們將被迫直接修改`MessageProcessor`函數。 ``` import fs from 'fs'; // Low Level Module class FileLogger { logMessage(message: string): void { fs.writeFileSync('somefile.txt', message); } } // High Level Module class MessageProcessor { // DIP Violation: This high-level module is is tightly coupled with the low-level module (FileLogger), making the system less flexible and harder to maintain or extend. private logger = new FileLogger(); processMessage(message: string): void { this.logger.logMessage(message); } } ``` ### 解決 以下重構的程式碼表示為了遵守依賴倒置原則 (DIP) 所需進行的變更。與前面的範例相反,高階類別`MessageProcessor`持有特定低階類別`FileLogger`的私有屬性,現在它持有`Logger`類型的私有屬性(表示抽象層的介面)。 這種更好的方法減少了類別之間的依賴關係,從而使程式碼更具可擴展性和可維護性。 #### 聲明: ``` import fs from 'fs'; // Abstraction Layer interface Logger { logMessage(message: string): void; } // Low Level Module #1 class FileLogger implements Logger { logMessage(message: string): void { fs.writeFileSync('somefile.txt', message); } } // Low Level Module #2 class ConsoleLogger implements Logger { logMessage(message: string): void { console.log(message); } } // High Level Module class MessageProcessor { // Resolved: The high level module is now loosely coupled with the low level logger modules. private _logger: Logger; constructor (logger: Logger) { this._logger = logger; } processMessage (message: string): void { this._logger.logMessage(message); } } ``` #### 用法: ``` const fileLogger = new FileLogger(); const consoleLogger = new ConsoleLogger(); // Now the logging mechanism can be easily replaced const messageProcessor = new MessageProcessor(consoleLogger); messageProcessor.processMessage('Hello'); ``` #### DIP 之前和之後: ![重構前後的依賴倒置原則](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kju8qfpie60b104vuz90.png) 結論 -- 透過遵循 SOLID 原則,開發人員在開發或維護任何規模的軟體系統時,可以避免常見的陷阱,例如緊密耦合、缺乏靈活性、程式碼可重複使用性差以及一般維護困難。掌握這些原則是成為更好的軟體工程師的又一步。 --- 原文出處:https://dev.to/idanref/solid-the-5-golden-rules-to-level-up-your-coding-skills-2p82

如何編寫有用的 commit 訊息(我的提交訊息範本)

我們都曾在某個時刻經歷過有關 git commit 訊息的混亂。 ![XKCD - 隨著專案的拖延,我的 git 提交訊息的資訊量越來越少](https://thepracticaldev.s3.amazonaws.com/i/xn60rbbj7353tb5gtkh1.png) 我也不例外。我的部落格的提交訊息如下所示: ``` fixxxx stuff post post post post posts mmm posts front maddy Add chris oliver add syntax article add git patch article fix video video arty art art Fix links oops ``` 因為我部落格的 git 歷史記錄只有我自己看過,所以沒關係。我已經接受了我永遠無法在我的部落格中充分利用 git 的事實,而且我完全同意這一點。 不幸的是,有些人對待有多個貢獻者的真實專案就像我對待我的部落格一樣。我發現這種做法是無知而不是懶惰的結果。因此,我將分享一些關於如何在實際專案中使用提交訊息的技巧。 ### 為什麼要關心? 😤[我不在乎,跳到模板!](#the-final-template) 🚀 Git 是一個強大的工具,即使您只使用它來保存程式碼更改歷史記錄並且不利用其最強大的功能。 然而,你會發現你挖掘得越深,git 就會變得越強大。您還會發現 git 的許多最有用的功能都是在提交訊息有用的假設下運作的。 想想你上次使用`git blame`是什麼時候。如果您發現一條提交訊息,上面`fixed a bad bug` ,這會有幫助嗎?可能不是,您可能試圖找到有關您正在處理的程式碼的更多上下文;你需要解釋什麼以及為什麼。 Git 提交訊息必須包含每次更改背後的內容和原因,以便明天勇敢的 git 探索者能夠進入提交作者的頭腦。如果提交訊息不包含該訊息,為什麼還要寫一個?提交訊息只有在對將來某個時候試圖理解更改的人有用時才有用。 為了建立一個良好的提交訊息的模板,我將把提交訊息分成幾個部分。 ### 首先,主題行 在提交訊息中,第一行(有時稱為主題行)應與正文隔離。理想情況下,這一行總結了提交中所做的更改。 當我寫主題行時,我嘗試完成這句話,“這次提交將......” 例如,我可能會編寫一個主題行,內容類似於`Remove unused, commented code` 。這可以很好地結束我的句子:“此提交將刪除未使用的帶註釋的程式碼。” 在設定主題行格式時,需要記住一兩個規則。 首先,主題行中的第一個字元應大寫;這只是一個常見的約定。根據我的經驗,它還使閱讀一長串的單行提交清單變得更加容易。 其次,您的提交訊息不應超過五十個字元。這是因為 GitHub 等工具會將該行截斷為 50 個字元。因此,為了讓其他人能夠有效地瀏覽和理解你的主題行,你應該嘗試用五十個字符來總結整個變化。 我的提交訊息範本的第一行如下所示: `Summarize the change in less than 50 characters` ### 接下來,第一個正文“段落” 在某些提交中,主題行足以傳達整個想法。例如,如果您的提交將`Add a comma to the README` ,您可能不需要自己解釋。 然而,在大多數提交中,您的更改可能會受益於一些額外的上下文。我們不希望未來的開發人員在嘗試理解更改背後的原因時錯過上下文。 這就是訊息正文發揮作用的地方。我將正文分為“段落”,這些“段落”只是鬆散定義的由空格分隔的文字字串。它們可以是要點、句子或其他東西;重要的是它們從冷開始就易於閱讀和理解。 過去,我通常使用提交訊息正文的第一段來解釋我所做的事情。這些天,我已經不再關注*「什麼」* ,而是開始記錄*「為什麼」* 。 [Ben Orenstein 最近改變了我對提交訊息格式的看法](https://twitter.com/r00k/status/1175100703829909505?s=20): {% 推特 1175100703829909505 %} 因此,在這種情況下,我們想要引導我們做出改變*的原因*。 這是一個例子: ``` Refactor the coupon UI Because: - The old UI code is fairly slow - There were a few unused dependencies - The old UI has aged poorly ``` 這些「段落」的偉大之處在於只有一個格式規則:72 個字元換行。這更多的是一種遺留傳統,而不是任何實質的東西。然而,主要原因是這允許 git 縮進一些空間(假設最大字元限制為 80)。我建議遵循這條規則,儘管它並不總是嚴格必要的。 這是到目前為止的提交訊息範本: ``` Summarize the change in less than 50 characters Because: - Explain the reasons you made this change - Make a new bullet for each reason - Each line should be under 72 characters ``` ### 現在是第二正文“段落” 既然我們已經總結了更改並分享了進行更改的原因,那麼以較長的形式準確地解釋我們所做的事情可能是謹慎的做法。 我用第二個「段落」來更詳細地解釋我在更改中所做的事情,例如: ``` Refactor the coupon UI Because: - The old UI code is fairly slow - There were a few unused dependencies - The old UI has aged poorly I thought it was necessary to remove some of the old coupon UI code. Unfortunately, it has aged pretty poorly, and I think this refactor makes the code much easier to support in the long-run. Primarily, this commit improves the performance of the coupon component. It also removes some unused dependencies. ``` 提交正文的這一部分應該比 50 個字元的摘要更深入地解釋所做的事情。格式由您決定(只要您以 72 個字元換行即可)。 這是更新後的模板: ``` Summarize the change in less than 50 characters Because: - Explain the reasons you made this change - Make a new bullet for each reason - Each line should be under 72 characters Explain exactly what was done in this commit with more depth than the 50 character subject line. Remember to wrap at 72 characters! ``` ### 其他部分:附加註釋和合著者 此時,我們正在編寫有效且連貫的提交訊息。然而,有時提交訊息需要一些額外的註釋。這可以在最後一節中完成。 例如: ``` Refactor the coupon UI Because: - The old UI code is fairly slow - There were a few unused dependencies - The old UI has aged poorly I thought it was necessary to remove some of the old coupon UI code. Unfortunately, it has aged pretty poorly, and I think this refactor makes the code much easier to support in the long-run. Primarily, this commit improves the performance of the coupon component. It also removes some unused dependencies. These changes should resolve issue #1337. This commit removed the left-pad dependency, so please stop using it! Co-authored-by: nspinazz89 <[email protected]> ``` 在這個例子中我能夠: - 參考相關問題 - 加入一行以警告我刪除了依賴項 - 包含與我一起參與該提交的人員的引用 此時,任何查看此提交訊息的人都會知道: 1. 做了什麼一目了然 2. 為什麼需要改變 3. 有關已完成操作的詳細訊息 4. 有關變更的任何有用的詳細訊息 這使得我們的提交訊息對我們未來的自己和任何其他需要理解我們程式碼的開發人員來說更加有用。 即使您不同意我編寫提交訊息的方法,也很難否認我們必須編寫提交訊息,以便其他開發人員在閱讀我們的程式碼時能夠進入我們的視野。 我認為大多數人都同意“好”程式碼的標誌是可維護性,您可以透過編寫有助於其他人理解甚至將來更改您的程式碼的提交訊息來增強程式碼的可維護性。 ### 最終模板 ``` Summarize the change in less than 50 characters Because: - Explain the reasons you made this change - Make a new bullet for each reason - Each line should be under 72 characters Explain exactly what was done in this commit with more depth than the 50 character subject line. Remember to wrap at 72 characters! Include any additional notes, relevant links, or co-authors. ``` ### 還有更多... 這些天我寫了[很多文章](https://jh.codes),我經營一個[播客](https://www.devpath.fm),並且我已經開始發送一份關於我聽到的所有精彩故事的[時事通訊摘要](https://pages.convertkit.com/674caf55d4/f30f7753a7)。 您還可以在[Twitter](https://twitter.com/jakeherrington)上關注我,我在那裡製作一些愚蠢的表情包並談論如何成為開發人員。 --- 原文出處:https://dev.to/jacobherrington/how-to-write-useful-commit-messages-my-commit-message-template-20n9

如何將 .py 轉換為 .exe?一步步指導。

--- 標題: 如何將 .py 轉換為 .exe?一步步指導。 發表:真實 封面圖片:https://thepracticaldev.s3.amazonaws.com/i/3c27e6ni9a7preeeqo0v.jpg 描述:如何將 .py 轉換為 .exe 的說明 標籤: python, 初學者, oop, 學習 --- 自動 PY 到 EXE =========== 我們要使用的唯一工具是**Auto PY to EXE** ! **Auto PY to EXE**是一款令人驚嘆的應用程式,用於從專案中產生 .exe 文件,無論它是一個 .py 檔案還是任意數量的檔案。 該應用程式有一個漂亮的 GUI,如下所示: ![所有文字](https://warehouse-camo.cmh1.psfhosted.org/4fc81b16448c94eda8a266110b56284ca9883185/68747470733a2f2f692e696d6775722e636f6d2f6464304c43326e2e706e67) 如何開始 ---- 步驟一、安裝 ------ 使用 PyPI 安裝: 要安裝該應用程式,請在**cmd**中執行以下行: `pip install auto-py-to-exe` 若要開啟應用程式,請在**cmd**中執行此行: `auto-py-to-exe` 注意:如果您以這種方式安裝時遇到任何問題,或者您想從GitHub 安裝它,請前往\[主頁\] (https://pypi.org/project/auto-py-to-exe) 或觀看此說明影片「Auto PY to EXE」的開發者\[他自己\] (https://github.com/brentvollebregt)。 {% youtube OZSZHmWSOeM %} ### 欲了解更多附加訊息,請使用此 #### \[「使用 auto-py-to-exe 時的問題」\] (https://nitratine.net/blog/post/issues-when-using-auto-py-to-exe) 步驟 2. 轉換 -------- 您需要選擇幾個主要選項: 1. 選擇你的 .py 文件 2. 選擇“一個目錄”或“一個檔案”選項 3. 選擇其他文件 1. 選擇你的 .py 文件 -------------- 如果您有多個文件,請選擇一個來啟動程式。 2.1. 「一個目錄」選項 ------------- ![所有文字](https://thepracticaldev.s3.amazonaws.com/i/9mrf0i0cm0shdgoizjdz.JPG) 很簡單。當選擇“One Directory”選項時,“Auto PY to EXE”會將所有相依性放在**一個資料夾**中。您可以在“進階”選單中選擇輸出目錄。如果您有圖標和背景等媒體文件,如果您將媒體文件/資料夾放在輸出目錄中,那麼在 .exe 中使用它們應該不會有任何問題。 像這樣的東西: ![所有文字](https://thepracticaldev.s3.amazonaws.com/i/1a8b99f7f5gggq7fe7cv.JPG) 2.2. 「一個檔案」選項 ------------- ![所有文字](https://thepracticaldev.s3.amazonaws.com/i/cuq5tm4xsjnngoi6uqmc.JPG) 當選擇“One File”選項時,“Auto PY to EXE”將建立一個包含所有依賴項但**不包含媒體檔案的.exe 檔案**。如果您的程式只有**預設的 Windows GUI** ,沒有圖示、背景、媒體文件,或者您可以將媒體資料夾放在 .exe 文件附近,請隨意跳過以下說明。對於那些想要將媒體檔案打包到 .exe 檔案本身的人,請閱讀第 3 段。 3. 選擇其他文件 --------- 「Auto PY to EXE」中有一個名為「Additional Files」的選單,可讓您新增您選擇的檔案。但有一個問題。 「Auto PY to EXE」使用**pyinstaller**將資料解壓縮到臨時資料夾中,並將該目錄路徑儲存在 \_MEIPASS 環境變數中。您的專案將找不到必要的文件,因為路徑已更改,也不會看到新路徑。換句話說,如果選擇「一個檔案」選項,則在「其他檔案」功能表中選擇的檔案**將不會新增**到 .exe 檔案中。要解決此問題,您應該使用Auto PY to EXE 開發人員提供的程式碼\[此處\](https://nitratine.net/blog/post/issues-when-using-auto-py-to-exe/#debugging ) ``` def resource_path(relative_path): ``` ``` """ Get absolute path to resource, works for dev and for PyInstaller """ ``` ``` try: ``` ``` # PyInstaller creates a temp folder and stores path in _MEIPASS ``` ``` base_path = sys._MEIPASS ``` ``` except Exception: ``` ``` base_path = os.path.abspath(".") ``` ``` return os.path.join(base_path, relative_path) ``` 要在您的專案中使用此程式碼,請替換您*現在*擁有的媒體檔案的連結 例如: ``` setWindowIcon(QIcon('media\icons\logo.png')) ``` *和* ``` setWindowIcon(QIcon(resource_path('logo.png')) ``` 現在連結將被正確引用,並且所選檔案已成功打包到 .exe 檔案中。 用於比較: 之前可能有連結 ``` "C:\Users\User\PycharmProjects\media\icons\logo.png" ``` 之後可能有連結 ``` "C:\Users\User\AppData\Local\Temp\\_MEI34121\logo.png" ``` 按下**“轉換 .PY 至 .EXE”** ![所有文字](https://warehouse-camo.cmh1.psfhosted.org/d2f89e7dfcbbd3635e0f098b43dbc9df7c74b7a4/68747470733a2f2f692e696d6775722e636f6d2f663354456e5a492e706e67) 等待 ![所有文字](https://warehouse-camo.cmh1.psfhosted.org/a71bb45213b2285ac68eedc2994709c478deb12d/68747470733a2f2f692e696d6775722e636f6d2f4d6a644f4e63432e706e67) 步驟 3. 執行您的程式! ------------- 現在一切都完成了! 執行。測試一下。看看發生了什麼事。 確保一切正常。 #### 您建立了一個目錄 您需要的每個檔案都應該位於**單一目錄**中。 #### 你製作了一個文件 這樣你應該有**一個 .exe 檔**。如果您有需要並且正確完成,您的 .exe 檔案將包含其中的所有媒體。**您不需要任何帶有 .exe 檔案的媒體檔案/資料夾**即可正確顯示它們。 --- ### 聚苯乙烯 如果您對應加入哪些重要資訊有任何回饋或建議,請隨時告訴我! 本指南並未描述以各種可能的方式完成的每個可能的選項。 我希望您發現這些資訊有用! 祝您的專案順利! --- 原文出處:https://dev.to/eshleron/how-to-convert-py-to-exe-step-by-step-guide-3cfi

😻建立您自己的 CLI 版本的 MonkeyType 🙈

長話短說 ---- 在這個易於理解的教程中,您將學習如何在幾分鐘內建立自己的 MonkeyType CLI 版本。 😎 **您將學到什麼:✨** - 使用 Pythoncurses 模組建立具有**WPM**和**Accuracy**支援的強大打字 CLI 應用程式。 您準備好成為 CLI MonkeyTyper 了嗎? 😉 無論這是您的第一個 CLI 應用程式還是第 n 個應用程式。請隨意跟隨。 ![猴子在筆記型電腦上打字](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/unzjcx4ues1ot7m4h4hu.gif) --- 設定環境🙈 ----- > ℹ️不需要設定虛擬環境,我們不會使用任何外部相依性。 建立一個資料夾來保存專案的所有原始程式碼: ``` mkdir cli-monkeytype-python cd cli-monkeytype-python ``` 建立兩個新文件,我們將在其中編寫程式: ``` touch main.py typing_test.py ``` `main.py`檔案將作為我們應用程式的起點,而`typing_test.py`檔案將保存程式的所有邏輯。 > ℹ️對於Linux或Mac用戶,您不需要下載任何依賴項,我們將主要使用**curses** 、 **time**和**random**模組,這些模組都包含在Python標準庫中。 ⚠️**注意** > Windows 使用者可能必須安裝curses,因為它不包含在Windows 的Python 標準庫中。在繼續下一步之前,請確保已安裝它。 --- 讓我們來寫程式吧🐵 --------- > 💡 我們將在本節中研究應用程式的方法、大綱和實際編碼部分。 😵‍💫 ### 方法和概要👀 我們將在這裡採取不同的方法,而不是將所有程式碼都塞在`main`文件中。我們將把程式碼分成不同文件中的類別。 將有一個單獨的文件,其中包含一個負責封裝與打字測試相關的所有邏輯的類別。在主文件中,我們將呼叫此類的方法。聽起來,對吧?讓我們開始吧。 🚀 這是我們類別的骨架以及我們將要處理的所有方法。 ``` class TypingTest: def __init__(self, stdscr): pass def get_line_to_type(self): pass def display_wpm(self): pass def display_accuracy(self): pass def display_typed_chars(self): pass def display_details(self): pass def test_accuracy(self): pass def test_wpm(self): pass ``` 所有函數名稱都應該是不言自明的。如果您需要協助理解每個函數的作用,即使在查看了此大綱之後,為什麼還要閱讀這篇文章?只是開玩笑\*不是真的\*。 😏 > 🥱 這是一個適合初學者的應用程式。別擔心,一起編碼吧。 ### 真正的樂趣開始了! ![表演時間 GIF](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i0r36i2t9mrygd14wtop.gif) 我們將從導入模組並編寫`__init__`方法開始。這將初始化程式執行所需的所有術語。 ``` import curses import random import time class TypingTest: def __init__(self, stdscr): self.stdscr = stdscr self.to_type_text = self.get_line_to_type() self.user_typed_text = [] self.wpm = 0 self.start_time = time.time() # Initialize color pairs curses.init_pair(3, curses.COLOR_WHITE, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) # --SNIP-- ``` `stdscr`用於控制終端螢幕,對於建立使用者可以看到其擊鍵的基於文字的使用者介面至關重要。 ⌨️ `get_line_to_type`方法取得一行文字供使用者鍵入。該文字儲存在`self.to_type_text`變數中。當他們鍵入時,他們輸入的字元將保存在`self.user_typed_text`清單中。我們使用列表是因為當使用者更正錯誤輸入的字元時,彈出最後一項會更容易。 初始每分鐘字數 (WPM) 分數設定為 0,我們記錄測驗的開始時間。我們也初始化了一些**顏色對**,根據它們是否正確來指示字元上的顏色。稍後,我們將根據使用者打字所需的時間來計算**WPM** 。 現在,新增以下功能的程式碼 > ℹ️ 確保在專案根目錄中建立一個名為`typing_texts.txt`的新文件,其中包含幾行文字。參考:[點這裡](https://github.com/shricodev/blogs/blob/main/cli-monkeytype-python/typing_texts.txt)。 ``` # --SNIP-- def get_line_to_type(self): with open("typing_texts.txt", "r", encoding="utf-8") as file: lines = file.readlines() return random.choice(lines).strip() def display_wpm(self): self.stdscr.addstr(1, 0, f"WPM: {self.wpm}", curses.color_pair(3)) def display_accuracy(self): self.stdscr.addstr( 2, 0, f"Accuracy: {self.test_accuracy()}%", curses.color_pair(3), ) def display_typed_chars(self): for i, char in enumerate(self.user_typed_text): correct_character = self.to_type_text[i] # Use color pair 1 if correct, else color pair 2. color = 1 if char == correct_character else 2 self.stdscr.addstr(0, i, char, curses.color_pair(color)) def display_details(self): self.stdscr.addstr(self.to_type_text) self.display_wpm() self.display_accuracy() self.display_typed_chars() # --SNIP-- ``` 讓我總結一下這些方法,它們非常簡單: 🎯 `get_line_to_type(self)` :從名為「typing\_texts.txt」的檔案中擷取刪除了尾隨空格的隨機行。 🎯 `display_wpm(self)` :當使用者鍵入時在螢幕上的第一行顯示 WPM。 🎯 `display_accuracy(self)` :在螢幕上第 2 行顯示**準確率百分比。**準確率由我們即將編寫的`test_accuracy()`方法計算。 🎯 `display_typed_chars(self)` :顯示使用者在螢幕上輸入的字符,突出顯示一個顏色對(顏色 1)中的正確字符和另一個顏色對(顏色 2)中的錯誤字符。 🎯 `display_details(self)` :它本質上是一個輔助函數,幫助顯示上面所有顯示函數的內容。 好的,現在我們已經編寫了這些顯示方法,讓我們實現實際的邏輯來測試準確性和 WPM 本身。 新增以下程式碼行: ``` # --SNIP-- def test_accuracy(self): total_characters = min(len(self.user_typed_text), len(self.to_type_text)) # If there are no typed chars, show accuracy 0. if total_characters == 0: return 0.0 matching_characters = 0 for current_char, target_char in zip(self.user_typed_text, self.to_type_text): if current_char == target_char: matching_characters += 1 matching_percentage = (matching_characters / total_characters) * 100 return matching_percentage def test_wpm(self): # getkey method by default is blocking. # We do not want to wait until the user types each char to check WPM. # Else the entire logic will be faulty. self.stdscr.nodelay(True) while True: # Since we have nodelay = True, if not using max(), # users might end up with time.time() equal to start_time, # resulting in 0 and potentially causing a zero-divisible error in the below line. time_elapsed = max(time.time() - self.start_time, 1) # Considering the average word length in English is 5 characters self.wpm = round((len(self.user_typed_text) / (time_elapsed / 60)) / 5) self.stdscr.clear() self.display_details() self.stdscr.refresh() # Exit the loop when the user types in the total length of the text. if len(self.user_typed_text) == len(self.to_type_text): self.stdscr.nodelay(False) break # We have `nodelay = True`, so we don't want to wait for the keystroke. # If we do not get a key, it will throw an exception # in the below lines when accessing the key. try: key = self.stdscr.getkey() except Exception: continue # Check if the key is a single character before using ord() if isinstance(key, str) and len(key) == 1: if ord(key) == 27: # ASCII value for ESC break # If the user has not typed anything reset to the current time if not self.user_typed_text: self.start_time = time.time() if key in ("KEY_BACKSPACE", "\b", "\x7f"): if len(self.user_typed_text) > 0: self.user_typed_text.pop() elif len(self.user_typed_text) < len(self.to_type_text): self.user_typed_text.append(key) ``` 🎯 `test_accuracy(self)` :透過將使用者輸入的字元與目標文字進行比較,計算並返回打字準確度(以百分比形式)。如果字元匹配,則將匹配字元的計數加1。最後,計算匹配的百分比。 🎯 `test_wpm(self)` :計算每分鐘字數(WPM)並即時更新顯示。我們用一個**公式**來計算WPM,這不是我想出來的,我從網路複製的。它追蹤使用者輸入的內容,處理退格鍵,並在使用者完成輸入目標文字或按**ESC**時停止。 偉大的!這就是我們的**TypingTest**類別。 🎉 > ✅ 我們編寫程式碼的方式可以幫助我們輕鬆地將程式碼匯入到任何未來的專案中,並使維護變得更加容易。 是時候測試我們的實作了。 🙈 在`main.py`檔案中,加入以下程式碼行: ``` from curses import wrapper from typing_test import TypingTest def main(stdscr): stdscr.clear() stdscr.addstr("Welcome to the typing speed test") stdscr.addstr("\nPress any key to continue!") while True: typing_test = TypingTest(stdscr) stdscr.getkey() typing_test.test_wpm() stdscr.addstr( 3, 0, "Congratulations! You have completed the test! Press any key to continue...", ) stdscr.nodelay(False) key = stdscr.getkey() # Check if the key is a single character before using ord() if isinstance(key, str) and len(key) == 1: if ord(key) == 27: # ASCII value for ESC break if __name__ == "__main__": wrapper(main) ``` > 💡 注意:我們從curses `wrapper`方法內的main 函數,該函數處理curses 模組的初始化和清理。 在 main 中,我們建立**TypingTest**類別的實例並在無限循環中執行測試,這讓使用者可以繼續執行測試,直到他們決定按**ESC**退出。 讓我們看看它的實際效果。 🔥 ![打字測試演示](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t0eregzw35f8yq66blja.gif) > 🫵 如果你已經做到了這一步,我想指派一個小任務給你。目前,我們正在從文件中隨機選擇文字進行輸入。我希望您從網路上**抓取**輸入文字並使用該內容。請隨意在我的儲存庫中開啟包含您的變更的拉取請求。 > 如果您需要幫助,我已經參與了一個類似的 Python 抓取專案。請隨意[檢查](https://github.com/shricodev/IPO-Monitor-NEPSE)一下。 --- **包起來!** 🐒 ---------- 到目前為止,您已經建立了一個 Python CLI 應用程式來測試您在終端機中的打字速度。 本文的記錄原始碼可在此處取得: https://github.com/shricodev/blogs/tree/main/cli-monkeytype-python 非常感謝您的閱讀! 🎉🫡 > 在下面的評論部分寫下你的想法。 👇 {% cta https://twitter.com/shricodev %} 在 Twitter 上追蹤我 🐥 {% endcta %} {% 嵌入 https://dev.to/shricodev %} --- 原文出處:https://dev.to/shricodev/build-your-own-cli-version-of-monkeytype-bm7

70 個 JavaScript 面試問題

嗨大家好,新年快樂:煙火::煙火::煙火:! ---------------------- 這是一篇很長的文章,所以請耐心聽我一秒鐘或一個小時。每個問題的每個答案都有一個向上箭頭**↑**連結,可讓您返回到問題列表,這樣您就不會浪費時間上下滾動。 ### 問題 - [1. `undefined`和`null`有什麼差別?](#1-whats-the-difference-between-undefined-and-null) - [2. &amp;&amp; 運算子的作用是什麼?](#2-what-does-the-ampamp-operator-do) - [3. || 是什麼意思?運營商做什麼?](#3-what-does-the-operator-do) - [4. 使用 + 或一元加運算子是將字串轉換為數字的最快方法嗎?](#4-is-using-the-or-unary-plus-operator-the-fastest-way-in-converting-a-string-to-a-number) - [5.什麼是DOM?](#5-what-is-the-dom) - [6.什麼是事件傳播?](#6-what-is-event-propagation) - [7.什麼是事件冒泡?](#7-whats-event-bubbling) - [8. 什麼是事件擷取?](#8-whats-event-capturing) - [9. `event.preventDefault()`和`event.stopPropagation()`方法有什麼差別?](#9-whats-the-difference-between-eventpreventdefault-and-eventstoppropagation-methods) - [10. 如何知道元素中是否使用了`event.preventDefault()`方法?](#10-how-to-know-if-the-eventpreventdefault-method-was-used-in-an-element) - [11. 為什麼這段程式碼 obj.someprop.x 會拋出錯誤?](#11-why-does-this-code-objsomepropx-throw-an-error) - \[12.什麼是`event.target` ?\](#12-什麼是 eventtarget- ) - [13.什麼是`event.currentTarget` ?](#13-what-is-eventcurrenttarget) - [14. `==`和`===`有什麼差別?](#14-whats-the-difference-between-and-) - [15. 為什麼在 JavaScript 中比較兩個相似的物件時回傳 false?](#15-why-does-it-return-false-when-comparing-two-similar-objects-in-javascript) - [16. `!!`是什麼意思?運營商做什麼?](#16-what-does-the-operator-do) - [17. 如何計算一行中的多個表達式?](#17-how-to-evaluate-multiple-expressions-in-one-line) - [18.什麼是吊裝?](#18-what-is-hoisting) - [19.什麼是範圍?](#19-what-is-scope) - [20.什麼是閉包?](#20-what-are-closures) - [21. JavaScript 中的假值是什麼?](#21-what-are-the-falsy-values-in-javascript) - [22. 如何檢查一個值是否為假值?](#22-how-to-check-if-a-value-is-falsy) - [23. `"use strict"`有什麼作用?](#23-what-does-use-strict-do) - [24. JavaScript 中`this`的值是什麼?](#24-whats-the-value-of-this-in-javascript) - [25. 物件的`prototype`是什麼?](#25-what-is-the-prototype-of-an-object) - \[26.什麼是 IIFE,它有什麼用?\](#26-what-is-an-iife-what-is-the-use-of-it ) - [27. `Function.prototype.apply`方法有什麼用?](#27-what-is-the-use-functionprototypeapply-method) - [28. `Function.prototype.call`方法有什麼用?](#28-what-is-the-use-functionprototypecall-method) - [29. `Function.prototype.apply`和`Function.prototype.call`有什麼差別?](#29-whats-the-difference-between-functionprototypeapply-and-functionprototypecall) - [30. `Function.prototype.bind`的用法是什麼?](#30-what-is-the-usage-of-functionprototypebind) - \[31.什麼是函數式程式設計以及 JavaScript 的哪些特性使其成為函數式語言的候選者?\](#31-什麼是函數式程式設計和 javascript 的特性是什麼-使其成為函數式語言的候選者 ) - [32.什麼是高階函數?](#32-what-are-higher-order-functions) - [33.為什麼函數被稱為First-class Objects?](#33-why-are-functions-called-firstclass-objects) - \[34.手動實作`Array.prototype.map`方法。\](#34-手動實作 arrayprototypemap-method ) - [35. 手動實作`Array.prototype.filter`方法。](#35-implement-the-arrayprototypefilter-method-by-hand) - [36. 手動實作`Array.prototype.reduce`方法。](#36-implement-the-arrayprototypereduce-method-by-hand) - [37.什麼是`arguments`物件?](#37-what-is-the-arguments-object) - [38. 如何創造沒有**原型的**物件?](#38-how-to-create-an-object-without-a-prototype) - [39. 為什麼當你呼叫這個函數時,這段程式碼中的`b`會變成全域變數?](#39-why-does-b-in-this-code-become-a-global-variable-when-you-call-this-function) - [40.什麼是**ECMAScript** ?](#40-what-is-ecmascript) - [41. **ES6**或**ECMAScript 2015**有哪些新功能?](#41-what-are-the-new-features-in-es6-or-ecmascript-2015) - [42. `var` 、 `let`和`const`關鍵字有什麼差別?](#42-whats-the-difference-between-var-let-and-const-keywords) - [43. 什麼是**箭頭函數**?](#43-what-are-arrow-functions) - [44.什麼是**類別**?](#44-what-are-classes) - [45.什麼是**模板文字**?](#45-what-are-template-literals) - [46.什麼是**物件解構**?](#46-what-is-object-destructuring) - [47.什麼是`ES6 Modules` ?](#47-what-are-es6-modules) - [48.什麼是`Set`物件以及它如何運作?](#48-what-is-the-set-object-and-how-does-it-work) - [49. 什麼是回呼函數?](#49-what-is-a-callback-function) - [50. 什麼是**Promise** ?](#50-what-are-promises) - [51. 什麼是*async/await*以及它是如何運作的?](#51-what-is-asyncawait-and-how-does-it-work) - [52. **Spread 運算子**和**Rest 運算**子有什麼差別?](#52-whats-the-difference-between-spread-operator-and-rest-operator) - [53. 什麼是**預設參數**?](#53-what-are-default-parameters) - [54.什麼是**包裝物件**?](#54-what-are-wrapper-objects) - [55.**隱性強制**和**顯性**強制有什麼差別?](#55-what-is-the-difference-between-implicit-and-explicit-coercion) - [56. 什麼是`NaN` ?以及如何檢查值是否為`NaN` ?](#56-what-is-nan-and-how-to-check-if-a-value-is-nan) - [57. 如何檢查一個值是否為一個**陣列**?](#57-how-to-check-if-a-value-is-an-array) - [58. 如何在不使用`%`或模運算子的情況下檢查數字是否為偶數?](#58-how-to-check-if-a-number-is-even-without-using-the-or-modulo-operator) - [59. 如何檢查物件中是否存在某個屬性?](#59-how-to-check-if-a-certain-property-exists-in-an-object) - [60.什麼是**AJAX** ?](#60-what-is-ajax) - [61. JavaScript 中建立物件的方式有哪些?](#61-what-are-the-ways-of-making-objects-in-javascript) - [62. `Object.seal`和`Object.freeze`方法有什麼不同?](#62-whats-the-difference-between-objectseal-and-objectfreeze-methods) - [63. `in`運算子和物件中的`hasOwnProperty`方法有什麼差別?](#63-whats-the-difference-between-the-in-operator-and-the-hasownproperty-method-in-objects) - [64. JavaScript中處理**非同步程式碼的**方法有哪些?](#64-what-are-the-ways-to-deal-with-asynchronous-code-in-javasscript) - [65.**函數表達式**和**函數宣告**有什麼不同?](#65-whats-the-difference-between-a-function-expression-and-function-declaration) - \[66.一個函數有多少種*呼叫*方式?\]( 66-函數可以有多少種方式被呼叫) ================= - [67. 什麼是*記憶*,它有什麼用?](#67-what-is-memoization-and-whats-the-use-it) - [68. 實現記憶輔助功能。](#68-implement-a-memoization-helper-function) - [69. 為什麼`typeof null`回傳`object` ?如何檢查一個值是否為`null` ?](#69-why-does-typeof-null-return-object-how-to-check-if-a-value-is-null) - [`new`關鍵字有什麼作用?](#70-what-does-the-new-keyword-do) ### 1. `undefined`和`null`有什麼差別? [^](#the-questions "返回問題")在了解`undefined`和`null`之間的差異之前,我們必須先了解它們之間的相似之處。 - 它們屬於**JavaScript 的**7 種基本型別。 ``` let primitiveTypes = ['string','number','null','undefined','boolean','symbol', 'bigint']; ``` - 它們是**虛假的**價值觀。使用`Boolean(value)`或`!!value`將其轉換為布林值時計算結果為 false 的值。 ``` console.log(!!null); //logs false console.log(!!undefined); //logs false console.log(Boolean(null)); //logs false console.log(Boolean(undefined)); //logs false ``` 好吧,我們來談談差異。 - `undefined`是尚未指派特定值的變數的預設值。或一個沒有**明確**回傳值的函數。 `console.log(1)` 。或物件中不存在的屬性。 JavaScript 引擎為我們完成了**指派**`undefined`值的任務。 ``` let _thisIsUndefined; const doNothing = () => {}; const someObj = { a : "ay", b : "bee", c : "si" }; console.log(_thisIsUndefined); //logs undefined console.log(doNothing()); //logs undefined console.log(someObj["d"]); //logs undefined ``` - `null`是**「代表無值的值」** 。 `null`是已**明確**定義給變數的值。在此範例中,當`fs.readFile`方法未引發錯誤時,我們得到`null`值。 ``` fs.readFile('path/to/file', (e,data) => { console.log(e); //it logs null when no error occurred if(e){ console.log(e); } console.log(data); }); ``` 當比較`null`和`undefined`時,使用`==`時我們得到`true` ,使用`===`時得到`false` 。您可以[在此處](#14-whats-the-difference-between-and-)閱讀原因。 ``` console.log(null == undefined); // logs true console.log(null === undefined); // logs false ``` ### 2. `&&`運算子的作用是什麼? [^](#the-questions "返回問題") `&&`或**邏輯 AND**運算子在其運算元中尋找第一個*假*表達式並傳回它,如果沒有找到任何*假*表達式,則傳回最後一個表達式。它採用短路來防止不必要的工作。在我的一個專案中關閉資料庫連線時,我在`catch`區塊中使用了它。 ``` console.log(false && 1 && []); //logs false console.log(" " && true && 5); //logs 5 ``` 使用**if**語句。 ``` const router: Router = Router(); router.get('/endpoint', (req: Request, res: Response) => { let conMobile: PoolConnection; try { //do some db operations } catch (e) { if (conMobile) { conMobile.release(); } } }); ``` 使用**&amp;&amp;**運算子。 ``` const router: Router = Router(); router.get('/endpoint', (req: Request, res: Response) => { let conMobile: PoolConnection; try { //do some db operations } catch (e) { conMobile && conMobile.release() } }); ``` ### 3. `||`是什麼意思?運營商做什麼? [↑](#the-questions "返回問題") `||` or**邏輯 OR**運算子尋找其運算元中的第一個*真值*表達式並傳回它。這也採用短路來防止不必要的工作。在**ES6預設函數參數**被支援之前,它被用來初始化函數中的預設參數值。 ``` console.log(null || 1 || undefined); //logs 1 function logName(name) { var n = name || "Mark"; console.log(n); } logName(); //logs "Mark" ``` ### 4. 使用**+**或一元加運算子是將字串轉換為數字的最快方法嗎? [^](#the-questions "返回問題")根據[MDN 文件,](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus) `+`是將字串轉換為數字的最快方法,因為如果該值已經是數字,它不會對該值執行任何操作。 ### 5.什麼是**DOM** ? [^](#the-questions "返回問題") **DOM**代表**文件物件模型,**是 HTML 和 XML 文件的介面 ( **API** )。當瀏覽器第一次讀取(*解析*)我們的 HTML 文件時,它會建立一個大物件,一個基於 HTML 文件的非常大的物件,這就是**DOM** 。它是根據 HTML 文件建模的樹狀結構。 **DOM**用於互動和修改**DOM 結構**或特定元素或節點。 想像一下,如果我們有這樣的 HTML 結構。 ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document Object Model</title> </head> <body> <div> <p> <span></span> </p> <label></label> <input> </div> </body> </html> ``` 等效的**DOM**應該是這樣的。 ![DOM 等效項](https://thepracticaldev.s3.amazonaws.com/i/mbqphfbjfie45ynj0teo.png) **JavaScript**中的`document`物件代表**DOM** 。它為我們提供了許多方法,我們可以用來選擇元素來更新元素內容等等。 ### 6.什麼是**事件傳播**? [↑](#the-questions "返回問題")當某個**事件**發生在**DOM**元素上時,該**事件**並非完全發生在該元素上。在**冒泡階段**,**事件**向上冒泡,或到達其父級、祖父母、祖父母的父級,直到一直到達`window` ,而在**捕獲階段**,事件從`window`開始向下到達觸發的元素事件或`<a href="#12-what-is-eventtarget-">event.target</a>` 。 **事件傳播**分為**三個**階段。 1. [捕獲階段](#8-whats-event-capturing)-事件從`window`開始,然後向下到達每個元素,直到到達目標元素。 2. [目標階段](#12-what-is-eventtarget-)– 事件已到達目標元素。 3. [冒泡階段](#7-whats-event-bubbling)-事件從目標元素冒起,然後向上移動到每個元素,直到到達`window` 。 ![事件傳播](https://thepracticaldev.s3.amazonaws.com/i/hjayqa99iejfhbsujlqd.png) ### 7.什麼是**事件冒泡**? [↑](#the-questions "返回問題")當某個**事件**發生在**DOM**元素上時,該**事件**並非完全發生在該元素上。在**冒泡階段**,**事件**向上冒泡,或到達其父級、祖父母、祖父母的父級,直到一直到達`window` 。 如果我們有一個像這樣的範例標記。 ``` <div class="grandparent"> <div class="parent"> <div class="child">1</div> </div> </div> ``` 還有我們的js程式碼。 ``` function addEvent(el, event, callback, isCapture = false) { if (!el || !event || !callback || typeof callback !== 'function') return; if (typeof el === 'string') { el = document.querySelector(el); }; el.addEventListener(event, callback, isCapture); } addEvent(document, 'DOMContentLoaded', () => { const child = document.querySelector('.child'); const parent = document.querySelector('.parent'); const grandparent = document.querySelector('.grandparent'); addEvent(child, 'click', function (e) { console.log('child'); }); addEvent(parent, 'click', function (e) { console.log('parent'); }); addEvent(grandparent, 'click', function (e) { console.log('grandparent'); }); addEvent(document, 'click', function (e) { console.log('document'); }); addEvent('html', 'click', function (e) { console.log('html'); }) addEvent(window, 'click', function (e) { console.log('window'); }) }); ``` `addEventListener`方法有第三個可選參數**useCapture ,**預設值為`false`事件將在**冒泡階段**發生,如果為`true` ,事件將在**捕獲階段**發生。如果我們點擊`child`元素,它會分別在**控制台**上記錄`child` 、 `parent`元素、 `grandparent` 、 `html` 、 `document`和`window` 。這就是**事件冒泡**。 ### 8. 什麼是**事件擷取**? [↑](#the-questions "返回問題")當某個**事件**發生在**DOM**元素上時,該**事件**並非完全發生在該元素上。在**捕獲階段**,事件從`window`開始一直到觸發事件的元素。 如果我們有一個像這樣的範例標記。 ``` <div class="grandparent"> <div class="parent"> <div class="child">1</div> </div> </div> ``` 還有我們的js程式碼。 ``` function addEvent(el, event, callback, isCapture = false) { if (!el || !event || !callback || typeof callback !== 'function') return; if (typeof el === 'string') { el = document.querySelector(el); }; el.addEventListener(event, callback, isCapture); } addEvent(document, 'DOMContentLoaded', () => { const child = document.querySelector('.child'); const parent = document.querySelector('.parent'); const grandparent = document.querySelector('.grandparent'); addEvent(child, 'click', function (e) { console.log('child'); }, true); addEvent(parent, 'click', function (e) { console.log('parent'); }, true); addEvent(grandparent, 'click', function (e) { console.log('grandparent'); }, true); addEvent(document, 'click', function (e) { console.log('document'); }, true); addEvent('html', 'click', function (e) { console.log('html'); }, true) addEvent(window, 'click', function (e) { console.log('window'); }, true) }); ``` `addEventListener`方法有第三個可選參數**useCapture ,**預設值為`false`事件將在**冒泡階段**發生,如果為`true` ,事件將在**捕獲階段**發生。如果我們點擊`child`元素,它會分別在**控制台**上記錄`window` 、 `document` 、 `html` 、 `grandparent` 、 `parent`和`child` 。這就是**事件捕獲**。 ### 9. `event.preventDefault()`和`event.stopPropagation()`方法有什麼差別? [↑](#the-questions "返回問題") `event.preventDefault()`方法**阻止**元素的預設行為。如果在`form`元素中使用,它**會阻止**其提交。如果在`anchor`元素中使用,它**會阻止**其導航。如果在`contextmenu`中使用,它**會阻止**其顯示或顯示。而`event.stopPropagation()`方法會停止事件的傳播或停止事件在[冒泡](#7-whats-event-bubbling)或[捕獲](#8-whats-event-capturing)階段發生。 ### 10. 如何知道元素中是否使用了`event.preventDefault()`方法? [↑](#the-questions "返回問題")我們可以使用事件物件中的`event.defaultPrevented`屬性。它傳回一個`boolean` ,指示是否在特定元素中呼叫了`event.preventDefault()` 。 ### 11. 為什麼這段程式碼`obj.someprop.x`會拋出錯誤? ``` const obj = {}; console.log(obj.someprop.x); ``` [^](#the-questions "返回問題")顯然,由於我們嘗試存取 a 的原因,這會引發錯誤 `someprop`屬性中的`x`屬性具有`undefined`值。請記住,物件中的**屬性**本身並不存在,且其**原型**具有預設值`undefined`且`undefined`沒有屬性`x` 。 ### 12.什麼是**event.target** ? [↑](#the-questions "返回問題")最簡單來說, **event.target**是**發生**事件的元素或**觸發**事件的元素。 HTML 標記範例。 ``` <div onclick="clickFunc(event)" style="text-align: center;margin:15px; border:1px solid red;border-radius:3px;"> <div style="margin: 25px; border:1px solid royalblue;border-radius:3px;"> <div style="margin:25px;border:1px solid skyblue;border-radius:3px;"> <button style="margin:10px"> Button </button> </div> </div> </div> ``` JavaScript 範例。 ``` function clickFunc(event) { console.log(event.target); } ``` 如果您單擊按鈕,它會記錄**按鈕**標記,即使我們將事件附加在最外部的`div`上,它也會始終記錄**按鈕**,因此我們可以得出結論, **event.target**是觸發事件的元素。 ### 13.什麼是**event.currentTarget** ? [↑](#the-questions "返回問題") **event.currentTarget**是我們**明確**附加事件處理程序的元素。 複製**問題 12**中的標記。 HTML 標記範例。 ``` <div onclick="clickFunc(event)" style="text-align: center;margin:15px; border:1px solid red;border-radius:3px;"> <div style="margin: 25px; border:1px solid royalblue;border-radius:3px;"> <div style="margin:25px;border:1px solid skyblue;border-radius:3px;"> <button style="margin:10px"> Button </button> </div> </div> </div> ``` 並且稍微改變我們的**JS** 。 ``` function clickFunc(event) { console.log(event.currentTarget); } ``` 如果您按一下該按鈕,即使我們按一下該按鈕,它也會記錄最外層的**div**標記。在此範例中,我們可以得出結論, **event.currentTarget**是我們附加事件處理程序的元素。 ### 14. `==`和`===`有什麼差別? [^](#the-questions "返回問題") `==` \_\_(抽象相等)\_\_ 和`===` \_\_(嚴格相等)\_\_ 之間的區別在於`==`在*強制轉換*後按**值**進行比較,而`===`在不進行*強制轉換的*情況下按**值**和**類型**進行比較。 讓我們更深入地研究`==` 。那麼首先我們來談談*強制*。 *強制轉換*是將一個值轉換為另一種類型的過程。在本例中, `==`進行*隱式強制轉換*。在比較兩個值之前, `==`需要執行一些條件。 假設我們必須比較`x == y`值。 1. 如果`x`和`y`具有相同的類型。 然後將它們與`===`運算子進行比較。 2. 如果`x`為`null`且`y` `undefined` ,則傳回`true` 。 3. 如果`x` `undefined`且`y`為`null`則傳回`true` 。 4. 如果`x`是`number`類型, `y`是`string`類型 然後回傳`x == toNumber(y)` 。 5. 如果`x`是`string`類型, `y`是`number`類型 然後返回`toNumber(x) == y` 。 6. 如果`x`是`boolean`類型 然後返回`toNumber(x) == y` 。 7. 如果`y`是`boolean`類型 然後回傳`x == toNumber(y)` 。 8. 如果`x`是`string` 、 `symbol`或`number`且`y`是 type `object` 然後回傳`x == toPrimitive(y)` 。 9. 如果`x`是`object`且`x`是`string` 、 `symbol` 然後返回`toPrimitive(x) == y` 。 10. 返回`false` 。 **注意:** `toPrimitive`首先使用物件中的`valueOf`方法,然後使用`toString`方法來取得該物件的原始值。 讓我們舉個例子。 | `x` | `y` | `x == y` | | ------------- |:-------------:| ----------------: | | `5` | `5` | `true` | | `1` | `'1'` | `true` | | `null` | `undefined` | `true` | | `0` | `false` | `true` | | `'1,2'` | `[1,2]` | `true` | | `'[object Object]'` | `{}` | `true` | 這些範例都傳回`true` 。 **第一個範例**屬於**條件一**,因為`x`和`y`具有相同的類型和值。 **第二個範例**轉到**條件四,**在比較之前將`y`轉換為`number` 。 **第三個例子**涉及**條件二**。 **第四個範例**轉到**條件七,**因為`y`是`boolean` 。 **第五個範例**適用於**條件八**。使用`toString()`方法將陣列轉換為`string` ,該方法傳回`1,2` 。 **最後一個例子**適用於**條件十**。使用傳回`[object Object]`的`toString()`方法將該物件轉換為`string` 。 | `x` | `y` | `x === y` | | ------------- |:-------------:| ----------------: | | `5` | `5` | `true` | | `1` | `'1'` | `false` | | `null` | `undefined` | `false` | | `0` | `false` | `false` | | `'1,2'` | `[1,2]` | `false` | | `'[object Object]'` | `{}` | `false` | 如果我們使用`===`運算符,則除第一個範例之外的所有比較都將傳回`false` ,因為它們不具有相同的類型,而第一個範例將傳回`true` ,因為兩者俱有相同的類型和值。 ### 15. 為什麼在 JavaScript 中比較兩個相似的物件時回傳**false** ? [^](#the-questions "返回問題")假設我們有下面的例子。 ``` let a = { a: 1 }; let b = { a: 1 }; let c = a; console.log(a === b); // logs false even though they have the same property console.log(a === c); // logs true hmm ``` **JavaScript**以不同的方式比較*物件*和*基元*。在*基元*中,它透過**值**來比較它們,而在*物件*中,它透過**引用**或**儲存變數的記憶體位址**來比較它們。這就是為什麼第一個`console.log`語句回傳`false`而第二個`console.log`語句回傳`true`的原因。 `a`和`c`有相同的引用,而`a`和`b`則不同。 ### 16. **!!**是什麼意思?運營商做什麼? [↑](#the-questions "返回問題")**雙非**運算子或**!!**將右側的值強制轉換為布林值。基本上,這是一種將值轉換為布林值的奇特方法。 ``` console.log(!!null); //logs false console.log(!!undefined); //logs false console.log(!!''); //logs false console.log(!!0); //logs false console.log(!!NaN); //logs false console.log(!!' '); //logs true console.log(!!{}); //logs true console.log(!![]); //logs true console.log(!!1); //logs true console.log(!![].length); //logs false ``` ### 17. 如何計算一行中的多個表達式? [↑](#the-questions "返回問題")我們可以使用`,`或逗號運算子來計算一行中的多個表達式。它從左到右計算並傳回右側最後一項或最後一個操作數的值。 ``` let x = 5; x = (x++ , x = addFive(x), x *= 2, x -= 5, x += 10); function addFive(num) { return num + 5; } ``` 如果記錄`x`的值,它將是**27** 。首先,我們**增加**x 的值,它將是**6** ,然後我們呼叫函數`addFive(6)`並將 6 作為參數傳遞,並將結果分配給`x` , `x`的新值將是**11** 。之後,我們將`x`的當前值乘以**2**並將其分配給`x` , `x`的更新值將是**22** 。然後,我們將`x`的當前值減去 5 並將結果指派給`x` ,更新後的值將是**17** 。最後,我們將`x`的值增加 10 並將更新後的值指派給`x` ,現在`x`的值將是**27** 。 ### 18.什麼是**吊裝**? [^](#the-questions "返回問題")**提升**是一個術語,用於描述將*變數*和*函數*移動到其*(全域或函數)*作用域的頂部(即我們定義該變數或函數的位置)。 要理解**提升**,我必須解釋*執行上下文*。 **執行上下文**是目前正在執行的「程式碼環境」。**執行上下文**有兩個階段*:編譯*和*執行*。 **編譯**- 在此階段,它獲取所有*函數聲明*並將它們*提升*到作用域的頂部,以便我們稍後可以引用它們並獲取所有*變數聲明***(使用 var 關鍵字聲明)** ,並將它們*提升*並給它們一個默認值*未定義*的 . **執行**- 在此階段,它將值指派給先前*提升的*變數,並*執行*或*呼叫*函數**(物件中的方法)** 。 **注意:**只有使用*var*關鍵字宣告的**函數宣告**和變數才會*被提升*,而不是**函數表達式**或**箭頭函數**、 `let`和`const`關鍵字。 好吧,假設我們在下面的*全域範圍*內有一個範例程式碼。 ``` console.log(y); y = 1; console.log(y); console.log(greet("Mark")); function greet(name){ return 'Hello ' + name + '!'; } var y; ``` 此程式碼記錄`undefined` , `1` , `Hello Mark!`分別。 所以*編譯*階段看起來像這樣。 ``` function greet(name) { return 'Hello ' + name + '!'; } var y; //implicit "undefined" assignment //waiting for "compilation" phase to finish //then start "execution" phase /* console.log(y); y = 1; console.log(y); console.log(greet("Mark")); */ ``` 出於範例目的,我對變數和*函數呼叫*的*賦值*進行了評論。 *編譯*階段完成後,它開始*執行*階段,呼叫方法並向變數賦值。 ``` function greet(name) { return 'Hello ' + name + '!'; } var y; //start "execution" phase console.log(y); y = 1; console.log(y); console.log(greet("Mark")); ``` ### 19.什麼是**範圍**? [↑](#the-questions "返回問題") JavaScript 中的**作用域**是我們可以有效存取變數或函數的**區域**。 JavaScript 有三種類型的作用域。**全域作用域**、**函數作用域**和**區塊作用域(ES6)** 。 - **全域作用域**- 在全域命名空間中宣告的變數或函數位於全域作用域中,因此可以在程式碼中的任何位置存取。 ``` //global namespace var g = "global"; function globalFunc(){ function innerFunc(){ console.log(g); // can access "g" because "g" is a global variable } innerFunc(); } ``` - **函數作用域**- 函數內聲明的變數、函數和參數可以在該函數內部存取,但不能在函數外部存取。 ``` function myFavoriteFunc(a) { if (true) { var b = "Hello " + a; } return b; } myFavoriteFunc("World"); console.log(a); // Throws a ReferenceError "a" is not defined console.log(b); // does not continue here ``` - **區塊作用域**- 在區塊`{}`內宣告的變數**( `let` 、 `const` )**只能在區塊內存取。 ``` function testBlock(){ if(true){ let z = 5; } return z; } testBlock(); // Throws a ReferenceError "z" is not defined ``` **範圍**也是一組查找變數的規則。如果一個變數在**當前作用域中**不存在,它會在**外部作用域中查找**並蒐索該變數,如果不存在,它會再次**查找,**直到到達**全域作用域。**如果該變數存在,那麼我們可以使用它,如果不存在,我們可以使用它來拋出錯誤。它搜尋**最近的**變數,一旦找到它就停止**搜尋**或**尋找**。這稱為**作用域鏈**。 ``` /* Scope Chain Inside inner function perspective inner's scope -> outer's scope -> global's scope */ //Global Scope var variable1 = "Comrades"; var variable2 = "Sayonara"; function outer(){ //outer's scope var variable1 = "World"; function inner(){ //inner's scope var variable2 = "Hello"; console.log(variable2 + " " + variable1); } inner(); } outer(); // logs Hello World // because (variable2 = "Hello") and (variable1 = "World") are the nearest // variables inside inner's scope. ``` ![範圍](https://thepracticaldev.s3.amazonaws.com/i/l81b3nmdonimex0qsgyr.png) ### 20.什麼是**閉包**? [^](#the-questions "返回問題")這可能是所有這些問題中最難的問題,因為**閉包**是一個有爭議的話題。那我就從我的理解來解釋。 **閉包**只是函數在宣告時記住其當前作用域、其父函數作用域、其父函數的父函數作用域上的變數和參數的引用的能力,直到在**作用域鏈**的幫助下到達全域作用域。基本上它是聲明函數時建立的**作用域**。 例子是解釋閉包的好方法。 ``` //Global's Scope var globalVar = "abc"; function a(){ //testClosures's Scope console.log(globalVar); } a(); //logs "abc" /* Scope Chain Inside a function perspective a's scope -> global's scope */ ``` 在此範例中,當我們宣告`a`函數時**,全域**作用域是`a's`*閉包*的一部分。 ![a的閉包](https://thepracticaldev.s3.amazonaws.com/i/teatokuw4xvgtlzbzhn8.png) 變數`globalVar`在影像中沒有值的原因是該變數的值可以根據我們呼叫`a`**位置**和**時間**而改變。 但在上面的範例中, `globalVar`變數的值為**abc** 。 好吧,讓我們來看一個複雜的例子。 ``` var globalVar = "global"; var outerVar = "outer" function outerFunc(outerParam) { function innerFunc(innerParam) { console.log(globalVar, outerParam, innerParam); } return innerFunc; } const x = outerFunc(outerVar); outerVar = "outer-2"; globalVar = "guess" x("inner"); ``` ![複雜的](https://thepracticaldev.s3.amazonaws.com/i/e4hxm7zvz8eun2ppenwp.png) 這將列印“猜測外部內部”。對此的解釋是,當我們呼叫`outerFunc`函數並將`innerFunc`函數的回傳值指派給變數`x`時,即使我們將新值**outer-2**指派給`outerVar`變數, `outerParam`也會具有**outer**值,因為 重新分配發生在呼叫`outer`函數之後,當我們呼叫`outerFunc`函數時,它會在**作用域鏈**中尋找`outerVar`的值,而`outerVar`的值為**「outer」** 。現在,當我們呼叫引用了`innerFunc`的`x`變數時, `innerParam`的值為**inner,**因為這是我們在呼叫中傳遞的值,而`globalVar`變數的值為**猜測**,因為在呼叫`x`變數之前,我們為`globalVar`分配了一個新值,並且在呼叫`x`時**作用域鏈**中`globalVar`的值是**猜測**。 我們有一個例子來示範沒有正確理解閉包的問題。 ``` const arrFuncs = []; for(var i = 0; i < 5; i++){ arrFuncs.push(function (){ return i; }); } console.log(i); // i is 5 for (let i = 0; i < arrFuncs.length; i++) { console.log(arrFuncs[i]()); // all logs "5" } ``` 由於**Closures**的原因,此程式碼無法按我們的預期工作。 `var`關鍵字建立一個全域變數,當我們推送一個函數時 我們返回全域變數`i` 。因此,當我們在循環之後呼叫該陣列中的其中一個函數時,它會記錄`5` ,因為我們得到 `i`的目前值為`5` ,我們可以存取它,因為它是全域變數。因為**閉包**保留該變數的**引用,**而不是其建立時的**值**。我們可以使用**IIFES**或將`var`關鍵字變更為`let`來解決此問題,以實現區塊作用域。 ### 21. **JavaScript**中的**假**值是什麼? [↑](#the-questions "返回問題") ``` const falsyValues = ['', 0, null, undefined, NaN, false]; ``` **假**值是轉換為布林值時變成**false 的**值。 ### 22. 如何檢查一個值是否為**假值**? [↑](#the-questions "返回問題")使用**布林**函數或雙非運算符**[!!](#16-what-does-the-operator-do)** ### 23. `"use strict"`有什麼作用? [^](#the-questions "返回問題") `"use strict"`是**JavaScript**中的 ES5 功能,它使我們的程式碼在*函數*或*整個腳本*中處於**嚴格模式**。**嚴格模式**幫助我們避免程式碼早期出現**錯誤**並為其加入限制。 **嚴格模式**給我們的限制。 - 分配或存取未宣告的變數。 ``` function returnY(){ "use strict"; y = 123; return y; } ``` - 為唯讀或不可寫的全域變數賦值; ``` "use strict"; var NaN = NaN; var undefined = undefined; var Infinity = "and beyond"; ``` - 刪除不可刪除的屬性。 ``` "use strict"; const obj = {}; Object.defineProperty(obj, 'x', { value : '1' }); delete obj.x; ``` - 參數名稱重複。 ``` "use strict"; function someFunc(a, b, b, c){ } ``` - 使用**eval**函數建立變數。 ``` "use strict"; eval("var x = 1;"); console.log(x); //Throws a Reference Error x is not defined ``` - **該**值的預設值是`undefined` 。 ``` "use strict"; function showMeThis(){ return this; } showMeThis(); //returns undefined ``` **嚴格模式**的限制遠不止這些。 ### 24. JavaScript 中`this`的值是什麼? [↑](#the-questions "返回問題")基本上, `this`是指目前正在執行或呼叫函數的物件的值。我說**目前**是因為**它**的值會根據我們使用它的上下文和使用它的位置而改變。 ``` const carDetails = { name: "Ford Mustang", yearBought: 2005, getName(){ return this.name; }, isRegistered: true }; console.log(carDetails.getName()); // logs Ford Mustang ``` 這是我們通常所期望的,因為在**getName**方法中我們傳回`this.name` ,在此上下文中`this`指的是`carDetails`物件,該物件目前是正在執行的函數的「擁有者」物件。 好吧,讓我們加入一些程式碼讓它變得奇怪。在`console.log`語句下面加入這三行程式碼 ``` var name = "Ford Ranger"; var getCarName = carDetails.getName; console.log(getCarName()); // logs Ford Ranger ``` 第二個`console.log`語句印製了**「Ford Ranger」**一詞,這很奇怪,因為在我們的第一個`console.log`語句中它印了**「Ford Mustang」** 。原因是`getCarName`方法有一個不同的「擁有者」物件,即`window`物件。在全域作用域中使用`var`關鍵字聲明變數會在`window`物件中附加與變數同名的屬性。請記住,當未使用`"use strict"`時,全域範圍內的`this`指的是`window`物件。 ``` console.log(getCarName === window.getCarName); //logs true console.log(getCarName === this.getCarName); // logs true ``` 本例中的`this`和`window`指的是同一個物件。 解決此問題的一種方法是使用函數中的`<a href="#27-what-is-the-use-functionprototypeapply-method">apply</a>`和`<a href="#28-what-is-the-use-functionprototypecall-method">call</a>`方法。 ``` console.log(getCarName.apply(carDetails)); //logs Ford Mustang console.log(getCarName.call(carDetails)); //logs Ford Mustang ``` `apply`和`call`方法期望第一個參數是一個物件,該物件將是該函數內`this`的值。 **IIFE** (即**立即呼叫函數表達式)** 、在全域作用域中宣告的函數、物件內部方法中的**匿名函數**和內部函數都有一個指向**window**物件的預設**值**。 ``` (function (){ console.log(this); })(); //logs the "window" object function iHateThis(){ console.log(this); } iHateThis(); //logs the "window" object const myFavoriteObj = { guessThis(){ function getThis(){ console.log(this); } getThis(); }, name: 'Marko Polo', thisIsAnnoying(callback){ callback(); } }; myFavoriteObj.guessThis(); //logs the "window" object myFavoriteObj.thisIsAnnoying(function (){ console.log(this); //logs the "window" object }); ``` 如果我們想要取得`myFavoriteObj`物件中的`name`屬性**(Marko Polo)**的值,有兩種方法可以解決這個問題。 首先,我們將`this`的值保存在變數中。 ``` const myFavoriteObj = { guessThis(){ const self = this; //saves the this value to the "self" variable function getName(){ console.log(self.name); } getName(); }, name: 'Marko Polo', thisIsAnnoying(callback){ callback(); } }; ``` 在此圖像中,我們保存`this`的值,該值將是`myFavoriteObj`物件。所以我們可以在`getName`內部函數中存取它。 其次,我們使用**ES6[箭頭函數](#43-what-are-arrow-functions)**。 ``` const myFavoriteObj = { guessThis(){ const getName = () => { //copies the value of "this" outside of this arrow function console.log(this.name); } getName(); }, name: 'Marko Polo', thisIsAnnoying(callback){ callback(); } }; ``` [箭頭函數](#43-what-are-arrow-functions)沒有自己的`this` 。它複製封閉詞法範圍的`this`值,或複製`getName`內部函數外部的`this`值(即`myFavoriteObj`物件)。我們也可以根據[函數的呼叫方式](#66-how-many-ways-can-a-function-be-invoked)來決定`this`的值。 ### 25. 物件的`prototype`是什麼? [↑](#the-questions "返回問題")最簡單的`prototype`是一個物件的*藍圖*。如果目前物件中確實存在它,則將其用作**屬性**和**方法**的後備。這是在物件之間共享屬性和功能的方式。這是 JavaScript**原型繼承**的核心概念。 ``` const o = {}; console.log(o.toString()); // logs [object Object] ``` 即使`o.toString`方法不存在於`o`物件中,它也不會拋出錯誤,而是傳回字串`[object Object]` 。當物件中不存在屬性時,它會尋找其**原型**,如果仍然不存在,則會尋找**原型的原型**,依此類推,直到在**原型鏈**中找到具有相同屬性的屬性。**原型鏈**的末尾在**Object.prototype**之後為`null` 。 ``` console.log(o.toString === Object.prototype.toString); // logs true // which means we we're looking up the Prototype Chain and it reached // the Object.prototype and used the "toString" method. ``` ### 26. 什麼是**IIFE** ,它有什麼用? [^](#the-questions "返回問題") **IIFE**或**立即呼叫函數表達式**是在建立或宣告後將被呼叫或執行的函數。建立**IIFE**的語法是,我們將`function (){}`包裝在括號`()`或**分組運算**子內,以將函數視為表達式,然後用另一個括號`()`呼叫它。所以**IIFE**看起來像這樣`(function(){})()` 。 ``` (function () { }()); (function () { })(); (function named(params) { })(); (() => { })(); (function (global) { })(window); const utility = (function () { return { //utilities }; })(); ``` 這些範例都是有效的**IIFE** 。倒數第二個範例顯示我們可以將參數傳遞給**IIFE**函數。最後一個範例表明我們可以將**IIFE**的結果保存到變數中,以便稍後引用它。 **IIFE**的最佳用途是進行初始化設定功能,並避免與全域範圍內的其他變數**發生命名衝突**或污染全域名稱空間。讓我們舉個例子。 ``` <script src="https://cdnurl.com/somelibrary.js"></script> ``` 假設我們有一個指向庫`somelibrary.js`的連結,該庫公開了我們可以在程式碼中使用的一些全域函數,但該庫有兩個我們不使用`createGraph`和`drawGraph`方法,因為這些方法中有錯誤。我們想要實作我們自己的`createGraph`和`drawGraph`方法。 - 解決這個問題的一種方法是改變腳本的結構。 ``` <script src="https://cdnurl.com/somelibrary.js"></script> <script> function createGraph() { // createGraph logic here } function drawGraph() { // drawGraph logic here } </script> ``` 當我們使用這個解決方案時,我們將覆蓋庫為我們提供的這兩種方法。 - 解決這個問題的另一種方法是更改我們自己的輔助函數的名稱。 ``` <script src="https://cdnurl.com/somelibrary.js"></script> <script> function myCreateGraph() { // createGraph logic here } function myDrawGraph() { // drawGraph logic here } </script> ``` 當我們使用此解決方案時,我們還將這些函數呼叫更改為新函數名稱。 - 另一種方法是使用**IIFE** 。 ``` <script src="https://cdnurl.com/somelibrary.js"></script> <script> const graphUtility = (function () { function createGraph() { // createGraph logic here } function drawGraph() { // drawGraph logic here } return { createGraph, drawGraph } })(); </script> ``` 在此解決方案中,我們建立一個實用程式變數,它是**IIFE**的結果,它傳回一個包含`createGraph`和`drawGraph`兩個方法的物件。 **IIFE**解決的另一個問題就是這個例子。 ``` var li = document.querySelectorAll('.list-group > li'); for (var i = 0, len = li.length; i < len; i++) { li[i].addEventListener('click', function (e) { console.log(i); }) } ``` 假設我們有一個`ul`元素,其類別為**list-group** ,並且它有 5 個`li`子元素。當我們**點擊**單一`li`元素時,我們希望`console.log` `i`的值。 但我們想要的程式碼中的行為不起作用。相反,它會在對`li`元素的任何**點擊**中記錄`5` 。我們遇到的問題是由於**閉包的**工作方式造成的。**閉包**只是函數記住其當前作用域、其父函數作用域和全域作用域中的變數引用的能力。當我們在全域範圍內使用`var`關鍵字聲明變數時,顯然我們正在建立一個全域變數`i` 。因此,當我們單擊`li`元素時,它會記錄**5** ,因為這是我們稍後在回調函數中引用它時的`i`值。 - 解決這個問題的一種方法是**IIFE** 。 ``` var li = document.querySelectorAll('.list-group > li'); for (var i = 0, len = li.length; i < len; i++) { (function (currentIndex) { li[currentIndex].addEventListener('click', function (e) { console.log(currentIndex); }) })(i); } ``` 這個解決方案之所以有效,是因為**IIFE**為每次迭代建立一個新範圍,並且我們捕獲`i`的值並將其傳遞到`currentIndex`參數中,因此當我們呼叫**IIFE**時,每次迭代的`currentIndex`值都是不同的。 ### 27. `Function.prototype.apply`方法有什麼用? [^](#the-questions "返回問題") `apply`呼叫一個函數,在呼叫時指定`this`或該函數的「所有者」物件。 ``` const details = { message: 'Hello World!' }; function getMessage(){ return this.message; } getMessage.apply(details); // returns 'Hello World!' ``` 這個方法的工作方式類似於`<a href="#28-what-is-the-use-functionprototypecall-method">Function.prototype.call</a>`唯一的差異是我們傳遞參數的方式。在`apply`中,我們將參數作為陣列傳遞。 ``` const person = { name: "Marko Polo" }; function greeting(greetingMessage) { return `${greetingMessage} ${this.name}`; } greeting.apply(person, ['Hello']); // returns "Hello Marko Polo!" ``` ### 28. `Function.prototype.call`方法有什麼用? [^](#the-questions "返回問題")此`call`呼叫一個函數,指定呼叫時該函數的`this`或「擁有者」物件。 ``` const details = { message: 'Hello World!' }; function getMessage(){ return this.message; } getMessage.call(details); // returns 'Hello World!' ``` 這個方法的工作方式類似於`<a href="#27-what-is-the-use-functionprototypeapply-method">Function.prototype.apply</a>`唯一的差異是我們傳遞參數的方式。在`call`中,我們直接傳遞參數,對於每個參數`,`用逗號分隔它們。 ``` const person = { name: "Marko Polo" }; function greeting(greetingMessage) { return `${greetingMessage} ${this.name}`; } greeting.call(person, 'Hello'); // returns "Hello Marko Polo!" ``` ### 29. `Function.prototype.apply`和`Function.prototype.call`有什麼差別? [↑](#the-questions "返回問題") `apply`和`call`之間的唯一區別是我們如何在被呼叫的函數中傳遞**參數**。在`apply`中,我們將參數作為**陣列**傳遞,而在`call`中,我們直接在參數列表中傳遞參數。 ``` const obj1 = { result:0 }; const obj2 = { result:0 }; function reduceAdd(){ let result = 0; for(let i = 0, len = arguments.length; i < len; i++){ result += arguments[i]; } this.result = result; } reduceAdd.apply(obj1, [1, 2, 3, 4, 5]); // returns 15 reduceAdd.call(obj2, 1, 2, 3, 4, 5); // returns 15 ``` ### 30. `Function.prototype.bind`的用法是什麼? [↑](#the-questions "返回問題") `bind`方法傳回一個新*綁定的*函數 到特定的`this`值或“所有者”物件,因此我們可以稍後在程式碼中使用它。 `call` 、 `apply`方法立即呼叫函數,而不是像`bind`方法那樣傳回一個新函數。 ``` import React from 'react'; class MyComponent extends React.Component { constructor(props){ super(props); this.state = { value : "" } this.handleChange = this.handleChange.bind(this); // Binds the "handleChange" method to the "MyComponent" component } handleChange(e){ //do something amazing here } render(){ return ( <> <input type={this.props.type} value={this.state.value} onChange={this.handleChange} /> </> ) } } ``` ### 31.什麼是**函數式程式設計**? **JavaScript**的哪些特性使其成為**函數式語言**的候選者? [^](#the-questions "返回問題")**函數式程式設計**是一種**聲明式**程式設計範式或模式,它介紹如何**使用表達式來**計算值而不改變傳遞給它的參數的函數來建立應用程式。 JavaScript**陣列**具有**map** 、 **filter** 、 **reduce**方法,這些方法是函數式程式設計世界中最著名的函數,因為它們非常有用,而且它們不會改變或改變陣列,這使得這些函數變得**純粹**,並且JavaScript 支援**閉包**和**高階函數**,它們是**函數式程式語言**的一個特徵。 - **map**方法建立一個新陣列,其中包含對陣列中每個元素呼叫提供的回調函數的結果。 ``` const words = ["Functional", "Procedural", "Object-Oriented"]; const wordsLength = words.map(word => word.length); ``` - **filter**方法會建立一個新陣列,其中包含透過回調函數中測試的所有元素。 ``` const data = [ { name: 'Mark', isRegistered: true }, { name: 'Mary', isRegistered: false }, { name: 'Mae', isRegistered: true } ]; const registeredUsers = data.filter(user => user.isRegistered); ``` - **reduce**方法對累加器和陣列中的每個元素(從左到右)套用函數,將其減少為單一值。 ``` const strs = ["I", " ", "am", " ", "Iron", " ", "Man"]; const result = strs.reduce((acc, currentStr) => acc + currentStr, ""); ``` ### 32.什麼是**高階函數**? [^](#the-questions "返回問題")**高階函數**是可以傳回函數或接收具有函數值的一個或多個參數的函數。 ``` function higherOrderFunction(param,callback){ return callback(param); } ``` ### 33.為什麼函數被稱為**First-class Objects** ? [^](#the-questions "返回問題") JavaScript 中的 \_\_Functions\_\_ 是**一流物件**,因為它們被視為該語言中的任何其他值。它們可以分配給**變數**,可以是稱為**方法的物件的屬性**,可以是**陣列中的專案**,可以**作為參數傳遞給函數**,也可以**作為函數的值返回**。函數與**JavaScript**中任何其他值之間的唯一區別是**函數**可以被呼叫。 ### 34. 手動實作`Array.prototype.map`方法。 [↑](#the-questions "返回問題") ``` function map(arr, mapCallback) { // First, we check if the parameters passed are right. if (!Array.isArray(arr) || !arr.length || typeof mapCallback !== 'function') { return []; } else { let result = []; // We're making a results array every time we call this function // because we don't want to mutate the original array. for (let i = 0, len = arr.length; i < len; i++) { result.push(mapCallback(arr[i], i, arr)); // push the result of the mapCallback in the 'result' array } return result; // return the result array } } ``` 正如`Array.prototype.map`方法的MDN描述。 **map() 方法建立一個新陣列,其中包含對呼叫陣列中的每個元素呼叫所提供函數的結果。** ### 35. 手動實作`Array.prototype.filter`方法。 [↑](#the-questions "返回問題") ``` function filter(arr, filterCallback) { // First, we check if the parameters passed are right. if (!Array.isArray(arr) || !arr.length || typeof filterCallback !== 'function') { return []; } else { let result = []; // We're making a results array every time we call this function // because we don't want to mutate the original array. for (let i = 0, len = arr.length; i < len; i++) { // check if the return value of the filterCallback is true or "truthy" if (filterCallback(arr[i], i, arr)) { // push the current item in the 'result' array if the condition is true result.push(arr[i]); } } return result; // return the result array } } ``` 正如`Array.prototype.filter`方法的 MDN 描述。 **filter() 方法建立一個新陣列,其中包含透過所提供函數實現的測試的所有元素。** ### 36. 手動實作`Array.prototype.reduce`方法。 [↑](#the-questions "返回問題") ``js 函數reduce(arr,reduceCallback,initialValue){ // 首先,我們檢查傳遞的參數是否正確。 if (!Array.isArray(arr) || !arr.length || typeof reduceCallback !== 'function') { ``` return []; ``` } 別的 { ``` // If no initialValue has been passed to the function we're gonna use the ``` ``` let hasInitialValue = initialValue !== undefined; ``` ``` let value = hasInitialValue ? initialValue : arr[0]; ``` ``` // first array item as the initialValue ``` ``` // Then we're gonna start looping at index 1 if there is no ``` ``` // initialValue has been passed to the function else we start at 0 if ``` ``` // there is an initialValue. ``` ``` for (let i = hasInitialValue ? 0 : 1, len = arr.length; i < len; i++) { ``` ``` // Then for every iteration we assign the result of the ``` ``` // reduceCallback to the variable value. ``` ``` value = reduceCallback(value, arr[i], i, arr); ``` ``` } ``` ``` return value; ``` } } ``` As the MDN description of the <code>Array.prototype.reduce</code> method. __The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.__ ###37. What is the __arguments__ object? [&uarr;](#the-questions "Back To Questions") The __arguments__ object is a collection of parameter values pass in a function. It's an __Array-like__ object because it has a __length__ property and we can access individual values using array indexing notation <code>arguments[1]</code> but it does not have the built-in methods in an array <code>forEach</code>,<code>reduce</code>,<code>filter</code> and <code>map</code>. It helps us know the number of arguments pass in a function. We can convert the <code>arguments</code> object into an array using the <code>Array.prototype.slice</code>. ``` 函數一(){ 返回 Array.prototype.slice.call(參數); } ``` Note: __the <code>arguments</code> object does not work on ES6 arrow functions.__ ``` 函數一(){ 返回參數; } 常數二 = 函數 () { 返回參數; } 常量三 = 函數三() { 返回參數; } const 四 = () =&gt; 參數; 四(); // 拋出錯誤 - 參數未定義 ``` When we invoke the function <code>four</code> it throws a <code>ReferenceError: arguments is not defined</code> error. We can solve this problem if your enviroment supports the __rest syntax__. ``` const 四 = (...args) =&gt; args; ``` This puts all parameter values in an array automatically. ###38. How to create an object without a __prototype__? [&uarr;](#the-questions "Back To Questions") We can create an object without a _prototype_ using the <code>Object.create</code> method. ``` 常數 o1 = {}; console.log(o1.toString()); // Logs \[object Object\] 取得此方法到Object.prototype const o2 = Object.create(null); // 第一個參數是物件「o2」的原型,在此 // case 將為 null 指定我們不需要任何原型 console.log(o2.toString()); // 拋出錯誤 o2.toString 不是函數 ``` ###39. Why does <code>b</code> in this code become a global variable when you call this function? [&uarr;](#the-questions "Back To Questions") ``` 函數 myFunc() { 令a = b = 0; } myFunc(); ``` The reason for this is that __assignment operator__ or __=__ has right-to-left __associativity__ or __evaluation__. What this means is that when multiple assignment operators appear in a single expression they evaluated from right to left. So our code becomes likes this. ``` 函數 myFunc() { 令 a = (b = 0); } myFunc(); ``` First, the expression <code>b = 0</code> evaluated and in this example <code>b</code> is not declared. So, The JS Engine makes a global variable <code>b</code> outside this function after that the return value of the expression <code>b = 0</code> would be 0 and it's assigned to the new local variable <code>a</code> with a <code>let</code> keyword. We can solve this problem by declaring the variables first before assigning them with value. ``` 函數 myFunc() { 令 a,b; a = b = 0; } myFunc(); ``` ###40. <div id="ecmascript">What is __ECMAScript__</div>? [&uarr;](#the-questions "Back To Questions") __ECMAScript__ is a standard for making scripting languages which means that __JavaScript__ follows the specification changes in __ECMAScript__ standard because it is the __blueprint__ of __JavaScript__. ###41. What are the new features in __ES6__ or __ECMAScript 2015__? [&uarr;](#the-questions "Back To Questions") * [Arrow Functions](#43-what-are-arrow-functions) * [Classes](#44-what-are-classes) * [Template Strings](#45-what-are-template-literals) * __Enhanced Object literals__ * [Object Destructuring](#46-what-is-object-destructuring) * [Promises](#50-what-are-promises) * __Generators__ * [Modules](#47-what-are-es6-modules) * Symbol * __Proxies__ * [Sets](#48-what-is-the-set-object-and-how-does-it-work) * [Default Function parameters](#53-what-are-default-parameters) * [Rest and Spread](#52-whats-the-difference-between-spread-operator-and-rest-operator) * [Block Scoping with <code>let</code> and <code>const</code>](#42-whats-the-difference-between-var-let-and-const-keywords) ###42. What's the difference between <code>var</code>, <code>let</code> and <code>const</code> keywords? [&uarr;](#the-questions "Back To Questions") Variables declared with <code>var</code> keyword are _function scoped_. What this means that variables can be accessed across that function even if we declare that variable inside a block. ``` 函數給MeX(showX) { 如果(顯示X){ ``` var x = 5; ``` } 返回x; } console.log(giveMeX(false)); console.log(giveMeX(true)); ``` The first <code>console.log</code> statement logs <code>undefined</code> and the second <code>5</code>. We can access the <code>x</code> variable due to the reason that it gets _hoisted_ at the top of the function scope. So our function code is intepreted like this. ``` 函數給MeX(showX) { 變數 x; // 有一個預設值未定義 如果(顯示X){ ``` x = 5; ``` } 返回x; } ``` If you are wondering why it logs <code>undefined</code> in the first <code>console.log</code> statement remember variables declared without an initial value has a default value of <code>undefined</code>. Variables declared with <code>let</code> and <code>const</code> keyword are _block scoped_. What this means that variable can only be accessed on that block <code>{}</code> on where we declare it. ``` 函數給MeX(showX) { 如果(顯示X){ ``` let x = 5; ``` } 返回x; } 函數給MeY(顯示Y){ 如果(顯示Y){ ``` let y = 5; ``` } 返回y; } ``` If we call this functions with an argument of <code>false</code> it throws a <code>Reference Error</code> because we can't access the <code>x</code> and <code>y</code> variables outside that block and those variables are not _hoisted_. There is also a difference between <code>let</code> and <code>const</code> we can assign new values using <code>let</code> but we can't in <code>const</code> but <code>const</code> are mutable meaning. What this means is if the value that we assign to a <code>const</code> is an object we can change the values of those properties but can't reassign a new value to that variable. ###43. What are __Arrow functions__? [&uarr;](#the-questions "Back To Questions") __Arrow Functions__ are a new way of making functions in JavaScript. __Arrow Functions__ takes a little time in making functions and has a cleaner syntax than a __function expression__ because we omit the <code>function</code> keyword in making them. ``` //ES5版本 var getCurrentDate = 函數 (){ 返回新日期(); } //ES6版本 const getCurrentDate = () =&gt; new Date(); ``` In this example, in the ES5 Version have <code>function(){}</code> declaration and <code>return</code> keyword needed to make a function and return a value respectively. In the __Arrow Function__ version we only need the <code>()</code> parentheses and we don't need a <code>return</code> statement because __Arrow Functions__ have a implicit return if we have only one expression or value to return. ``` //ES5版本 函數問候(名稱){ return '你好' + 名字 + '!'; } //ES6版本 const 問候 = (name) =&gt; `Hello ${name}` ; constgreet2 = 名稱 =&gt; `Hello ${name}` ; ``` We can also parameters in __Arrow functions__ the same as the __function expressions__ and __function declarations__. If we have one parameter in an __Arrow Function__ we can omit the parentheses it is also valid. ``` const getArgs = () =&gt; 參數 const getArgs2 = (...休息) =&gt; 休息 ``` __Arrow functions__ don't have access to the <code>arguments</code> object. So calling the first <code>getArgs</code> func will throw an Error. Instead we can use the __rest parameters__ to get all the arguments passed in an arrow function. ``` 常量資料 = { 結果:0, 數字:\[1,2,3,4,5\], 計算結果() { ``` // "this" here refers to the "data" object ``` ``` const addAll = () => { ``` ``` // arrow functions "copies" the "this" value of ``` ``` // the lexical enclosing function ``` ``` return this.nums.reduce((total, cur) => total + cur, 0) ``` ``` }; ``` ``` this.result = addAll(); ``` } }; ``` __Arrow functions__ don't have their own <code>this</code> value. It captures or gets the <code>this</code> value of lexically enclosing function or in this example, the <code>addAll</code> function copies the <code>this</code> value of the <code>computeResult</code> method and if we declare an arrow function in the global scope the value of <code>this</code> would be the <code>window</code> object. ###44. What are __Classes__? [&uarr;](#the-questions "Back To Questions") __Classes__ is the new way of writing _constructor functions_ in __JavaScript__. It is _syntactic sugar_ for using _constructor functions_, it still uses __prototypes__ and __Prototype-Based Inheritance__ under the hood. ``` //ES5版本 函數人(名字,姓氏,年齡,地址){ ``` this.firstName = firstName; ``` ``` this.lastName = lastName; ``` ``` this.age = age; ``` ``` this.address = address; ``` } Person.self = 函數(){ ``` return this; ``` } Person.prototype.toString = function(){ ``` return "[object Person]"; ``` } Person.prototype.getFullName = function (){ ``` return this.firstName + " " + this.lastName; ``` } //ES6版本 類人{ ``` constructor(firstName, lastName, age, address){ ``` ``` this.lastName = lastName; ``` ``` this.firstName = firstName; ``` ``` this.age = age; ``` ``` this.address = address; ``` ``` } ``` ``` static self() { ``` ``` return this; ``` ``` } ``` ``` toString(){ ``` ``` return "[object Person]"; ``` ``` } ``` ``` getFullName(){ ``` ``` return `${this.firstName} ${this.lastName}`; ``` ``` } ``` } ``` __Overriding Methods__ and __Inheriting from another class__. ``` //ES5版本 Employee.prototype = Object.create(Person.prototype); 函數 Employee(名字, 姓氏, 年齡, 地址, 職位名稱, 開始年份) { Person.call(this, 名字, 姓氏, 年齡, 地址); this.jobTitle = jobTitle; this.yearStarted = YearStarted; } Employee.prototype.describe = function () { return `I am ${this.getFullName()} and I have a position of ${this.jobTitle} and I started at ${this.yearStarted}` ; } Employee.prototype.toString = function () { 返回“\[物件員工\]”; } //ES6版本 class Employee extends Person { //繼承自「Person」類 建構函數(名字,姓氏,年齡,地址,工作標題,開始年份){ ``` super(firstName, lastName, age, address); ``` ``` this.jobTitle = jobTitle; ``` ``` this.yearStarted = yearStarted; ``` } 描述() { ``` return `I am ${this.getFullName()} and I have a position of ${this.jobTitle} and I started at ${this.yearStarted}`; ``` } toString() { // 重寫「Person」的「toString」方法 ``` return "[object Employee]"; ``` } } ``` So how do we know that it uses _prototypes_ under the hood? ``` 類別東西{ } 函數 AnotherSomething(){ } const as = new AnotherSomething(); const s = new Something(); console.log(typeof Something); // 記錄“函數” console.log(AnotherSomething 類型); // 記錄“函數” console.log(as.toString()); // 記錄“\[物件物件\]” console.log(as.toString()); // 記錄“\[物件物件\]” console.log(as.toString === Object.prototype.toString); console.log(s.toString === Object.prototype.toString); // 兩個日誌都回傳 true 表示我們仍在使用 // 底層原型,因為 Object.prototype 是 // 原型鏈的最後一部分和“Something” // 和「AnotherSomething」都繼承自Object.prototype ``` ###45. What are __Template Literals__? [&uarr;](#the-questions "Back To Questions") __Template Literals__ are a new way of making __strings__ in JavaScript. We can make __Template Literal__ by using the backtick or back-quote symbol. ``` //ES5版本 vargreet = '嗨,我是馬克'; //ES6版本 讓問候 = `Hi I'm Mark` ; ``` In the ES5 version, we need to escape the <code>'</code> using the <code>\\</code> to _escape_ the normal functionality of that symbol which in this case is to finish that string value. In Template Literals, we don't need to do that. ``` //ES5版本 var 最後一個字 = '\\n' - ' 在' - '我\\n' - '鋼鐵人\\n'; //ES6版本 讓最後一個單字=` ``` I ``` ``` Am ``` 鋼鐵人 `; ``` In the ES5 version, we need to add this <code>\n</code> to have a new line in our string. In Template Literals, we don't need to do that. ``` //ES5版本 函數問候(名稱){ return '你好' + 名字 + '!'; } //ES6版本 const 問候 = 名稱 =&gt; { 返回`Hello ${name} !` ; } ``` In the ES5 version, If we need to add an expression or value in a string we need to use the <code>+</code> or string concatenation operator. In Template Literals, we can embed an expression using <code>${expr}</code> which makes it cleaner than the ES5 version. ###46. What is __Object Destructuring__? [&uarr;](#the-questions "Back To Questions") __Object Destructuring__ is a new and cleaner way of __getting__ or __extracting__ values from an object or an array. Suppose we have an object that looks like this. ``` 常量僱員 = { 名字:“馬可”, 姓氏:“波羅”, 職位:“軟體開發人員”, 聘用年份:2017 }; ``` The old way of getting properties from an object is we make a variable t

堅實的原則:它們堅如磐石是有充分理由的!

剛開始接觸**物件導向編程**,對**SOLID**感到有點迷失?不用擔心,在本文中,我將向您解釋它並提供如何在程式碼開發中使用它的範例。 什麼是固體? ------ 在物件導向程式設計中, **SOLID**是五個設計原則的縮寫,旨在增強對軟體的理解、開發和維護。 透過應用這組原則,您應該注意到錯誤的減少、程式碼品質的提高、程式碼組織性更強、耦合性降低、重構增強以及程式碼重用的鼓勵。讓我們來看看他們。 1. S-單一職責原則 ----------- ![建議零售價](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v564d0p0s36fwo6imofo.png) > SRP - 單一職責原則 這確實很簡單,但非常重要:**一個類別應該有一個且只有一個改變的理由。** 不再建立具有多種功能和職責的類,是嗎?您可能遇到甚至建立了一個可以完成所有操作的類,即所謂的*God Class* 。目前看起來似乎沒問題,但是當您需要更改該類別的邏輯時,肯定會出現問題。 > 上帝類別:在OOP中,這是一個`do`或`knows`太多事情的類別。 ``` class ProfileManager { authenticateUser(username: string, password: string): boolean { // Authenticate logic } showUserProfile(username: string): UserProfile { // Show user profile logic } updateUserProfile(username: string): UserProfile { // Update user profile logic } setUserPermissions(username: string): void { // Set permission logic } } ``` 此**ProfileManager**類別執行**四個**不同的任務,違反了 SRP 原則。它正在驗證和更新資料、進行演示,最重要的是,它正在設定權限,所有這些都是同時進行的。 ### 這可能導致的問題 - `Lack of cohesion -`一個類別不應該承擔不屬於它自己的責任; - `Too much information in one place -`你的類別最終會產生許多依賴性並且難以進行更改; - `Challenges in implementing automated tests -`很難模擬這樣的類別。 現在,將**SRP**應用到`ProfileManager`類別中,讓我們來看看這個原則可以帶來的改進: ``` class AuthenticationManager { authenticateUser(username: string, password: string): boolean { // Authenticate logic } } class UserProfileManager { showUserProfile(username: string): UserProfile { // Show user profile logic } updateUserProfile(username: string): UserProfile { // Update user profile logic } } class PermissionManager { setUserPermissions(username: string): void { // Set permission logic } } ``` 您可能想知道, `can I apply this only to classes?`答案是:**完全不是**。您也可以(並且應該)將其應用於方法和函數。 ``` // ❌ function processTasks(taskList: Task[]): void { taskList.forEach((task) => { // Processing logic involving multiple responsibilities updateTaskStatus(task); displayTaskDetails(task); validateTaskCompletion(task); verifyTaskExistence(task); }); } // ✅ function updateTaskStatus(task: Task): Task { // Logic for updating task status return { ...task, completed: true }; } function displayTaskDetails(task: Task): void { // Logic for displaying task details console.log(`Task ID: ${task.id}, Description: ${task.description}`); } function validateTaskCompletion(task: Task): boolean { // Logic for validating task completion return task.completed; } function verifyTaskExistence(task: Task): boolean { // Logic for verifying task existence return tasks.some((t) => t.id === task.id); } ``` 美麗、優雅、有組織的程式碼。這個原則是其他原則的基礎;透過應用它,您應該建立高品質、可讀且可維護的程式碼。 2. O——開閉原則 ---------- ![OCP](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/epfur4p9r55iwbk9i4yy.png) > OCP-開閉原則 **物件或實體應該對擴充開放,但對修改關閉。**如果您需要加入功能,最好擴展而不是修改原始程式碼。 想像一下,您需要一個類別來計算某些多邊形的面積。 ``` class Circle { radius: number; constructor(radius: number) { this.radius = radius; } area(): number { return Math.PI * this.radius ** 2; } } class Square { sideLength: number; constructor(sideLength: number) { this.sideLength = sideLength; } calculateArea(): number { return this.sideLength ** 2; } } class areaCalculator { totalArea(shapes: Shape[]): number { let total = 0; shapes.forEach((shape) => { if (shape instanceof Square) { total += (shape as any).calculateArea(); } else { total += shape.area(); } }); return total; } } ``` `areaCalculator`類別的任務是計算不同多邊形的面積,每個多邊形都有自己的面積邏輯。如果您,'lil dev,需要加入新形狀,例如三角形或矩形,您會發現自己**需要**更改此類來進行更改,對吧?這就是你遇到問題的地方,違反了`Open-Closed Principle` 。 我想到了什麼解決方案?可能會在類別中加入另一個方法並完成,問題解決了🤩。不完全是,年輕學徒😓,這就是問題所在! **修改現有類別以新增行為會帶來嚴重的風險,可能會將錯誤引入到已執行的內容中。** > 請記住:OCP 堅持認為類別應該對修改關閉,對擴展開放。 看看重構程式碼帶來的美妙之處: ``` interface Shape { area(): number; } class Circle implements Shape { radius: number; constructor(radius: number) { this.radius = radius; } area(): number { return Math.PI * this.radius ** 2; } } class Square implements Shape { sideLength: number; constructor(sideLength: number) { this.sideLength = sideLength; } area(): number { return this.sideLength ** 2; } } class AreaCalculator { totalArea(shapes: Shape[]): number { let total = 0; shapes.forEach((shape) => { total += shape.area(); }); return total; } } ``` 查看`AreaCalculator`類別:它不再需要知道要呼叫哪些方法來註冊該類別。它可以透過呼叫介面強加的契約來正確地呼叫區域方法,這是它唯一需要的。 > 只要它們實作了 Shape 接口,一切就可以正常運作。 &lt;br/&gt; > 分離介面背後的可擴展行為並反轉依賴關係。 &gt; > [鮑伯叔叔](https://en.wikipedia.org/wiki/Robert_C._Martin) - `Open for extension:`您可以為類別新增功能或行為,而無需變更其原始程式碼。 - `Closed for modification:`如果您的類別已經具有可以正常工作的功能或行為,請不要更改其原始程式碼以加入新內容。 3. L——里氏代換原理 ------------ ![LSP](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/62uow23fsa5zk2wz5fz5.png) > LSP - 里氏替換原理 里氏替換原則指出**衍生類別必須可替換其基底類別。** 這個原則由 Barbara Liskov 在 1987 年提出,閱讀她的解釋可能會有點複雜。不過,不用擔心,我將提供另一個解釋和範例來幫助您理解。 > 如果對於 S 類型的每個物件 o1 都有一個 T 類型的物件 o2,使得對於所有用 T 定義的程式 P,當 o1 取代 o2 時 P 的行為保持不變,則 S 是 T 的子類型。 &gt; > 芭芭拉‧利斯科夫,1987 你做對了?不,可能不是。是的,我第一次讀時不明白(接下來的一百遍也不明白),但等等,還有另一種解釋: > 如果 S 是 T 的子類型,則程式中類型 T 的物件可以用類型 S 的物件替換,而不改變該程式的屬性。 &gt; > [維基百科](https://en.wikipedia.org/wiki/Liskov_substitution_principle) 如果您更喜歡視覺學習者,請不要擔心,這裡有一個例子: ``` class Person { speakName() { return "I am a person!"; } } class Child extends Person { speakName() { return "I am a child!"; } } const person = new Person(); const child = new Child(); function printName(message: string) { console.log(message); } printName(person.speakName()); // I am a person! printName(child.speakName()); // I am a child! ``` 父類別和衍生類別作為參數傳遞,程式碼繼續按預期工作。魔法?是的,這就是我們的朋友倒鉤的魔力。 ### 違規行為範例: - 重寫/實作一個不執行任何操作的方法; - 從基類傳回不同類型的值。 - 拋出意外的異常; 4. I——介面隔離原則 ------------ ![網際網路服務供應商](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qbdmugukrcacuqthho5x.png) > ISP-介面隔離原則 這句話說**不應該強迫一個類別實作它不使用的介面和方法。**建立更具體的介面比建立大而通用的介面更好。 在下面的範例中,建立一個**Book**介面來抽象化書籍行為,然後類別實作該介面: ``` interface Book { read(): void; download(): void; } class OnlineBook implements Book { read(): void { // does something } download(): void { // does something } } class PhysicalBook implements Book { read(): void { // does something } download(): void { // This implementation doesn't make sense for a book // it violates the Interface Segregation Principle } } ``` 通用`Book`介面迫使`PhysicalBook`類別做出毫無意義的行為(*或者我們在 Matrix 中下載實體書籍?* )並且違反了**ISP**和**LSP**原則。 使用**ISP**解決此問題: ``` interface Readable { read(): void; } interface Downloadable { download(): void; } class OnlineBook implements Readable, Downloadable { read(): void { // does something } download(): void { // does something } } class PhysicalBook implements Readable { read(): void { // does something } } ``` 現在好多了。我們從`Book`介面中刪除了`download()`方法,並將其加入到派生介面`Downloadable`中。這樣,行為就可以在我們的上下文中正確隔離,並且我們仍然尊重**介面隔離原則**。 5.D-依賴倒置原則 ---------- ![沾](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/42aomc36xq804pyldlis.png) > DIP - 依賴倒置原理 這個是這樣的:**依賴抽象而不是實現。** > 高層模組不應該依賴低層模組。兩者都應該依賴抽象。 &gt; > 抽像不應該依賴細節。細節應該取決於抽象。 &gt; > 鮑伯叔叔 現在我將展示一個簡單的程式碼來說明 DIP。在此範例中,有一個從資料庫取得使用者的服務。首先,讓我們建立一個與資料庫連接的具體類別: ``` // Low-level module class MySQLDatabase { getUserData(id: number): string { // Logic to fetch user data from MySQL database } } ``` 現在,讓我們建立一個取決於具體實作的服務類別: ``` // High-level module class UserService { private database: MySQLDatabase; constructor() { this.database = new MySQLDatabase(); } getUser(id: number): string { return this.database.getUserData(id); } } ``` 在上面的範例中, `UserService`直接依賴`MySQLDatabase`的具體實作。這違反了**DIP** ,因為**高級**類別 UserService 直接依賴**低階**類別。 如果我們想要切換到不同的資料庫系統(例如PostgreSQL),我們需要修改UserService類,這`AWFUL`了! 讓我們使用**DIP**修復此程式碼。高級類別`UserService`不應依賴特定實現,而應依賴抽象。讓我們建立一個`Database`介面作為抽象: ``` // Abstract interface (abstraction) for the low-level module interface Database { getUserData(id: number): string; } ``` 現在, `MySQLDatabase`和`PostgreSQLDatabase`的具體實作應該要實作這個介面: ``` class MySQLDatabase implements Database { getUserData(id: number): string { // Logic to fetch user data from MySQL database } } // Another low-level module implementing the Database interface class PostgreSQLDatabase implements Database { getUserData(id: number): string { // Logic to fetch user data from PostgreSQL database } } ``` 最後,UserService 類別可以依賴`Database`抽象: ``` class UserService { private database: Database; constructor(database: Database) { this.database = database; } getUser(id: number): string { return this.database.getUserData(id); } } ``` 這樣, `UserService`類別依賴`Database`抽象,而不是具體實現,滿足**依賴倒置原則**。 結論 -- 透過採用這些原則,開發人員可以建立更能適應變化的系統,使維護變得更容易,並隨著時間的推移提高程式碼品質。 本文的全部內容源自各種其他文章、我的個人筆記以及我**在深入研究物件導向程式設計 (OOP) 領域**時遇到的數十個線上影片。範例中使用的程式碼片段是基於我對這些原則的解釋和理解而建立的。我真的希望,我的小學徒,我能為促進你的理解和學習進步做出貢獻。 衷心希望您喜歡這篇文章,別忘了關注! 註:圖片取自[本文](https://medium.com/backticks-tildes/the-s-o-l-i-d-principles-in-pictures-b34ce2f1e898) --- 原文出處:https://dev.to/lukeskw/solid-principles-theyre-rock-solid-for-good-reason-31hn

從 Next.js 到 Rails 再到 Elixir:我的 React.js 倦怠之旅

我自 2019 年以來一直是 Web 開發人員。我使用 React.js 和基於 React 的框架,如 Gatsby、Next、Remix、Astro 和 Hydrogen。我從來沒有對這些工具感到完全滿意,但是,作為一個深入 JS 生態系統的初學者,我從同行那裡聽到的都是這樣的話:「這就是方式,任何其他程式語言要么慢,要么老」。 ![就是這樣](https://media.giphy.com/media/stnjSj2vpLcM4rwmEH/giphy.gif) 結果,我習慣了巨大的複雜性:多個獨立的儲存庫、數千個函式庫和框架來實現簡單的事情、GraphQL、微服務、無伺服器、靜態網站產生、增量靜態再生、部分水化、 redux 、redux-thunk、babel、webpack、react 伺服器元件、伺服器操作等。這個清單還可以再持續 10 分鐘。 直到有一天我說**受夠了!** 讓我們來看看我慢慢發瘋的完整時間線。這需要一段時間,在閱讀長篇文章之前,請隨意煮點咖啡! --- ## 倦怠的時間表 ### [Gatsby.js](https://www.gatsbyjs.com/) 我記得完成我的訓練營並想:“我終於能夠建立我的作品集了!”,所以我做到了。只有一個小問題,我想在 Google 上建立索引,但是使用舊的「create-react-app」使這項任務幾乎不可能完成。很快我了解了 SEO 和 React 的水合循環,這讓我找到了這個問題的「解決方案」:Gatsby.js。靜態網站產生的想法對當時的我來說簡直是革命性的,畢竟沒有什麼比預先渲染 HTML 檔案更快了,對吧? 我決定透過閱讀文件來學習這個新框架,讓我告訴你,這**不是**一次有趣的體驗。我以前從未聽說過 GraphQL,顯然,您需要它來產生所有靜態檔案(到底是什麼???)。我問我的一些網友,很難學習這些過度設計的廢話是否正常,他們回答說「技能問題,再努力一點!」。於是我更加努力,終於學會了之後,我把我的個人網站移植到了Gatsby上。 ![再努力一點](https://media.giphy.com/media/gzRiZROEyDCznPofKj/giphy.gif) 我的大部分頁面都成功在 Google 上建立了索引,幾個月來,我對結果非常滿意。然後另一個問題出現了:我的**很多**開發者朋友開始說“Gatsby 死了!建立 Next 是為了簡化靜態站點生成並提供伺服器端渲染”。 ### [Next.js](https://nextjs.org/) 我快速瀏覽了 Next 文件並**立即**愛上了它。我能夠在沒有 GraphQL 的情況下用三分之一的程式碼做與 Gatsby 相同的事情!我再次將我的作品集移植到另一個框架:Next。 這次我確實有一次美好的經驗。部署到 Vercel 輕而易舉,「getStaticProps」和「getServerSideProps」功能很簡單,但功能非常強大,我可以選擇每個頁面的渲染樣式,整體來說非常靈活。 不幸的是,我透過慘痛的教訓學到了一些東西:在 JavaScript 生態系統中,所有美好的事情都會結束。 ### [混音](https://remix.run/) 我清楚記得 Remix 發佈時的情景。多名科技影響者開始發布有關它的內容(一如既往)。然而,當時我在主頁上看到它不支援靜態網站生成,只支援伺服器端渲染,所以我想「等一下,這些年來投資於 [JAMstack](https://jamstack.org/) 都被扔在這裡了嗎?不可能,這個框架不會長久」。然而,令我驚訝的是,Remix 不僅生存了下來,而且還被 Shopify 收購 https://shopify.engineering/remix-joins-shopify ,並成為 Next 的重要競爭對手。 幾個月過去了,我決定嘗試看看。我再一次感到驚訝,Remix 的主要座右銘是使用 Web 基礎知識,而不是像 Next 這樣過於複雜的快取系統。因此,在Remix 中編碼時,我腦中需要的思維模型要簡單10 倍:沒有全域狀態管理器,只需使用URL,更少的客戶端狀態,將所有邏輯移至伺服器,並使用cookie,無需使用完整堆疊中間的 REST API 非常簡單,只需將資料庫查詢移至「loader」函數即可。 ### 離開矩陣 ![離開矩陣](https://media.giphy.com/media/11e0gEWxYoSYTK/giphy.gif) 然後,突然間,真相呈現在我面前,我服下了紅色藥丸。我的腦海中開始浮現出多個問題:Remix 不就像所有其他「古老而無聊」的框架(如 Rails、Laravel 和 Django)一樣嗎?幾十年來,我們一直在使用伺服器端渲染進行全端 Web 開發,但 JavaScript 黑手黨集體認為這種方法是垃圾,將所有內容移至客戶端才是未來。難道同一個黑手黨認為 Rails 一直都是對的嗎?用 JS 框架做所有那些過度設計的怪物不是正確的舉動嗎?我開始質疑一切。這種「新」的 Web 開發方式更加簡單、快速。 ### 我已經完成了 Next 和 Vercel 我透過 [Next.js 應用程式路由器](https://nextjs.org/docs/app) 達到了臨界點。以下是 Vercel 向 Next 推送的所有錯誤的完整清單: - 曾經簡單的:「getStaticProps」和「getServerSideProps」函數現在變得複雜而麻煩。目前,沒有特定的位置來新增 API 呼叫或資料庫查詢,您可以將它們寫入任何您想要的位置!在多年前使用 PHP 犯了同樣的錯誤之後,我們開始再次將業務邏輯與 UI 混合。難道前端開發者不吸取過去的教訓嗎?如果我刪除按鈕會發生什麼事?這是否會破壞我的使用者身份驗證流程,因為資料庫呼叫位於其中?您的前端應該 100% 可廢棄且可更換。你相對於競爭對手的競爭優勢在於業務邏輯,它應該與 UI 層完全隔離。 ![可怕的 Next.js 程式碼](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kp41ds14loo21xgimcza.png) - 接下來是伺服器優先。這聽起來沒那麼糟吧?畢竟,這解決了 SEO 問題並立即向用戶展示新鮮內容。問題在於,大多數現有的 Next 程式碼庫都依賴客戶端程式庫,例如樣式元件和一些全域狀態管理器。這是什麼意思?隨著此類重大變化的不斷發生,您的應用程式將在幾週而不是幾年內變成遺留軟體。更多的時間花在保持所有依賴項最新上,而不是做重要的事情:發布功能。 - Vercel 從 Meta 聘請了多名 React 核心團隊成員。這帶來了嚴重的利益衝突,因為這些工程師現在(據稱)正在發布有利於 Next 的功能,而不是優先考慮那些可以幫助所有基於 React 的框架(如 Remix)的功能。 ![Vercel 正在破壞 React](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9ye40ykjgrd3z10t5nx7.png) 我再也受不了了。我對自己說:你知道嗎?我厭倦了一遍又一遍地重新學習相同的框架,我完全不同意這種新的範式。 毫不奇怪,其他內容創作者也經歷了類似的情況: https://youtu.be/zkCBSz353fc?si=z3-FDVgcB3xfp06h https://youtu.be/Zt8mO_Aqzw8?si=10fy1d-ZoB7t3Uc_ --- ## 啟蒙之路 我非常累。在厭倦了所有的 React 工具後,我開始了尋找更簡單的 Web 框架的旅程。以下是我一直在尋找的先決條件: - 含電池 - 約定優於配置 - 良好的開發體驗 - 現代化且高性能的前端 我的第一個反應是查看 [Stack Overflow Survey 2023](https://survey.stackoverflow.co/2023/#section-most-popular-technologies-web-frameworks-and-technologies) 中的頂級框架。我立即從清單中刪除了所有與 JS、C# 和 Java 相關的內容。我從來沒有興趣學習後兩個,它們看起來醜陋且冗長。所以剩下的選項是:Laravel (PHP)、Django (Python)、Rails (Ruby) 和 Phoenix (Elixir)。 Python 是我在網路工程學位期間使用的語言,我獲得了非常愉快的體驗。 Django 似乎遵循約定優於配置的理念,但最終讓我放棄它的是沒有一個好的內建工具來在前端工作。論壇上的大多數人都說他們使用[HTMX](https://htmx.org/) 和[Alpine](https://alpinejs.dev/),但是,兩者都是您需要安裝的外部依賴項。 放棄Laravel 是非常困難的,因為它具有驚人的成本效益,有數百個官方軟體包可以處理新創公司可能需要的幾乎所有內容,例如託管、身份驗證、條紋支付等。對於前端,他們創造了[慣性。Node.js](https://inertiajs.com/),這是一種非常簡單而優雅的方式,可以在前端使用 React 的同時保持 Laravel 的高生產力和強大功能。百分之百誠實地說,我沒有選擇 Laravel 的唯一原因是 PHP 的語法,它看起來很難看,到處都是一堆 `$` 和 `->`。 ### Ruby on Rails Ruby on Rails 無需介紹。它是 Web 開發框架的元年,其革命性的「15 分鐘建立部落格」至今仍令人印象深刻。在我開始抱怨我發現的所有問題之前,讓我們先從好的方面開始。 與 Python 類似,Ruby 是一種可以向非技術人員展示的語言,他們會理解該軟體想要做什麼。它是**迄今為止**我見過的最容易閱讀和最美麗的語言。我很快就意識到,[編寫視覺上令人愉悅的程式碼](https://world.hey.com/dhh/a-writer-s-ruby-2050b634) 是Rails 團隊的首要任務,這對我來說來說是新的。 更不用說 Rails 幾乎發明了「包含電池」和「約定優於配置」的哲學,所以這不會是一個問題。在一份文件中,我提供了任何類型的 Web 應用程式所需的一切。 在前端,有 [Hotwire](https://hotwired.dev/),這是一種非常簡單且輕量級的方法,可以實現 SPA 框架提供的所有 UX 改進。我一直很好奇測試這個庫的極限,它看起來非常有前途。 好吧,Rails 在紙面上滿足了我想要的框架的所有先決條件。我們來試試吧!我在本地測試的第一件事是“railsscaffold”命令。我立即感到震驚。一個指令就能產生 CRUD 所需的一切?決不! ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/58lbioexmot9412kojr5.png) 在 Node + React 領域,要實現相同的目標,我需要手動編寫所有程式碼(這裡沒有生成器)並安裝一堆程式庫,例如:Vite、prisma、express、react router、redux、redux-thunk 、 vitest、cypress 、react 測試庫、zod、typescript、eslint、prettier、1000 個不同的插件,甚至可能還有GraphQL 或tRPC。基本上就是一個已經有 900 個依賴項的 package.json。 在“railsscaffold”最初的震驚之後,當我從控制器打開程式碼時,我再次震驚了: ``` class ArticlesController < ApplicationController def index @articles = Article.all end def show @article = Article.find(params[:id]) end def new @article = Article.new end def create @article = Article.new(article_params) if @article.save redirect_to @article else render :new, status: :unprocessable_entity end end def edit @article = Article.find(params[:id]) end def update @article = Article.find(params[:id]) if @article.update(article_params) redirect_to @article else render :edit, status: :unprocessable_entity end end def destroy @article = Article.find(params[:id]) @article.destroy redirect_to root_path, status: :see_other end private def article_params params.require(:article).permit(:title, :body) end end ``` 這是所有後端程式碼嗎?只需幾行?這不可能!這非常簡單,看起來就像一個「低程式碼」工具。它簡單、優雅、可讀性極強,這是我們在 JS 領域很少見的。 好吧,好吧,你現在一定在想:「這個來自網路的瘋狂 React 開發者說他最終使用了 Elixir,所以 ruby 一定有問題!」。你是對的,我的匿名朋友,有些事情讓我很惱火,讓我們談談。 首先,我們需要解決房間裡的大象:從 React + Typescript 轉向動態類型語言並不容易。從我開始編寫程式碼的那一刻起,我的 VScode 上就沒有出現智慧感知或充滿程式碼建議的下拉式選單,我感到盲目和迷失。這是一種可怕的感覺,我可能會在函數名稱上輸入錯誤,直到網站投入使用時才意識到!我知道我們可以編寫測試,但這是我希望在 IDE 上立即辨識的錯誤類型,而不是在測試或部署期間辨識。 另一件我以為我會喜歡但最終討厭它的事情是:太多的魔法。在 Typescript 程式碼庫中,我可以點擊任何類別或函數的頂部,前往原始程式碼並查看其實作方式。在 Rails 上,我到底在哪裡進行驗證(例如)?我是否在控制器內建立私有函數?有專門的資料夾嗎?不,正確的位置是在模型內部。為什麼?因為這就是它的工作原理,所以您要么採用該約定,要么很難編寫 Ruby 程式碼。我根本無法對一切在幕後如何運作產生“直覺”,我必須盲目地相信維護者在組織一切方面做得很好。 為了解決我的挫折感,我開始寫前端程式碼。如何建立元件? [部分](https://guides.rubyonrails.org/layouts_and_rendering.html#using-partials)。如何定義該元件的 prop 類型?沒有辦法做到這一點,您需要打開它並直觀地查找其中的所有變數。做一些互動怎麼樣?建立國家?嗯,有帶有 [Stimulus](https://stimulus.hotwired.dev/) 的 Hotwire,但是正如您所看到的,您需要手動建立“重新渲染”功能,它沒有找到一種方法像React 這樣改變狀態後自動重新渲染頁面。 ``` // src/controllers/slideshow_controller.js import { Controller } from "@hotwired/stimulus" export default class extends Controller { static targets = [ "slide" ] initialize() { this.index = 0 this.showCurrentSlide() } next() { this.index++ this.showCurrentSlide() } previous() { this.index-- this.showCurrentSlide() } showCurrentSlide() { this.slideTargets.forEach((element, index) => { element.hidden = index !== this.index }) } } ``` 我再一次感到沮喪。我非常接近找到完美的框架!如果 Rails 失敗,我想嘗試的下一個框架是什麼?靈丹妙藥。 ### 長生不老藥和鳳凰 我必須說實話,我已經沒有耐心了。我嘗試了多種不同的生態系統,我幾乎確信要堅持使用 Ruby on Rails,並放棄對完美的追求。直到我的 YouTube 推薦部分出現了一個影片: https://www.youtube.com/live/bfrzGXM-Z88?si=Xsa7yCKeVSY5R3sT 堅持,稍等!在這裡我們可以看到一位 React 開發人員說了很多關於函數式程式設計、Elixir 和 Phoenix Live View 的好話。也許我應該嘗試一下! 我做的第一件事就是打開Elixir 和Phoenix 的文件,我真的很喜歡這樣一個事實:所有包都使用[Hex Docs](https://hexdocs.pm/) 以相同的方式進行記錄,您只需要取得習慣於單一介面以學習新事物。 另一個好處是,您只需閱讀文件即可真正學習 Elixir,無需昂貴的課程!在其他所有生態系統中,我必須透過付費課程學習語言,然後透過閱讀文件來學習框架。 然後是時候開始編寫程式碼了。很快我就明白函數式程式設計與 OOP 有很大不同。我們來做一個小小的比較: ``` // JS const obj = {name: "daniel"} obj.age = 25 // result: obj = {name: "daniel", age: 25} ``` ``` # Elixir obj = %{name: "daniel"} obj = Map.put(obj, :age, 25) # result: obj = %{name: "daniel", age: 25} ``` 或者您可以使用管道運算子透過更簡單的語法實現相同的效果: ``` # Elixir with pipe operator obj = %{name: "daniel"} |> Map.put(:age, 25) # result: obj = %{name: "daniel", age: 25} ``` 最初,您可能會發現它的可讀性較差且更複雜,但我保證隨著時間的推移它會變得有意義!嗯,至少對我來說是這樣。身為 React 開發人員,我已經習慣了到處都可以看到多個函數,甚至前端元件也是函數!更不用說建立類別有時被 JavaScript 黑手黨視為一種程式碼味道。我的大腦已經針對這種新範式進行了“塑造”,這對我來說很自然。自從我在大學獲得網路工程學位以來,我上過幾門關於物件導向程式設計的課程,但它從來沒有「受歡迎」。我無法將複雜的問題建模為類別和物件。隨著時間的推移,使用多個函數來「改變」一個變數是我在腦海中建模的方式。 主要框架怎麼樣?包含鳳凰電池嗎?約定優於配置? **是的!** 老實說,生態系統與 Rails 不在同一水平,但已經達到了 95%。除非您需要非常具體的功能,Phoenix 都能滿足您的需求。 我幾乎被 Elixir 迷住了,我的清單中缺少兩件事:良好的開發人員體驗和現代/高效能的前端程式碼。 José Valim 宣布他正在嘗試為該語言加入類型,但 Elixir 目前還沒有這些類型,所以我很擔心。如何在沒有類型的情況下獲得智能感知和自動完成?很快我發現這些功能不一定相關。在 VScode 上安裝 [ElixirLS 擴充功能](https://marketplace.visualstudio.com/items?itemName=JakeBecker.elixir-ls) 後,我感到很驚訝。可以在隨機資料夾的隨機模組內定義函數,將其導入其他位置,並取得它的智慧感知和文件!我從靜態類型語言中獲得了這些好處,而無需編寫類型的麻煩,簡直太棒了! https://elixir-lang.org/blog/2022/10/05/my-future-with-elixir-set-theoretic-types/ 我對前端的最後一個擔憂是由 Phoenix [Live View](https://hexdocs.pm/phoenix_live_view/welcome.html) 解決的。在程式碼方面,這正是文件主頁中讓我信服的部分: ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5sjzj90khytebnk523fm.png) 您可以為每個元件定義“props”,如果類型不匹配,您的 IDE 中會出現錯誤,就像 React 一樣!感人的! 使用者體驗怎麼樣?每當使用者點擊連結時是否會載入整個頁面?一定不行!即時視圖與客戶端建立 WebSocket 連接,然後每次頁面轉換只是透過 Websocket 進行內容交換,不會發出新的 HTTP 請求。此外,所有狀態都在伺服器端進行管理,這意味著 Trello 等豐富的用戶體驗過去由於加載過多的 JavaScript 而在客戶端非常卡頓,現在變得非常快! Elixir 處理所有複雜的狀態邏輯並將頁面的更新部分傳送到前端。看看這裡的完整解釋: https://youtu.be/wrmVk2czqMg?si=ZoWAlPjQC-svmV3Y 由於我們使用 WebSocket 來建立 UI,因此建立像 Twitter 這樣的「即時」應用程式只需要幾行程式碼! https://youtu.be/MZvmYaFkNJI?si=gAow6oIjgf8_OTkg ## 結論 可以肯定地說,「完美的技術堆疊」並不存在。解決所有問題的靈丹妙藥是我們在腦中創造的幻覺,以不斷尋找和建構最優化的工具。 然而,在個人層面上,完美的堆疊確實存在。因為每個開發人員都有偏好,您可以輕鬆找到適合您標準的工具。如果你有和我類似的旅程,完美的可能就是長生不老藥和鳳凰!所以試試看吧,也許你會像我現在一樣喜歡它。 如果您讀到了這篇文章的結尾,那您就太棒了!非常感謝您抽出寶貴的時間,希望我能為您的職業生涯帶來一些價值。 ![結束](https://media.giphy.com/media/lD76yTC5zxZPG/giphy.gif) --- 原文出處:https://dev.to/danielbergholz/from-nextjs-to-rails-then-elixir-my-journey-through-reactjs-burnout-h8d

SOLID 是你最需要的程式設計原則!

剛開始**物件導向程式設計**,不知道**SOLID**?別擔心,在本文中我將向您解釋它並舉例說明如何在開發程式碼時使用它。 - [什麼是 SOLID?](#什麼是 SOLID) - [S - 單一責任原則](#s-single-responsibility-principle) - [開閉原則](#the-開閉原則) - [L - 里氏替換原理](#l-里氏替換原理) - [I - 介面隔離原則](#i-interface-segregation-principle) - [D - 依賴倒置原則](#d-dependency-inversion-principle) - [結論](#conclusion) ##什麼是實體? 在物件導向程式設計中,術語 SOLID 是五個設計假設的縮寫,旨在促進理解、開發和維護軟體。 當使用這套原則時,可以顯著減少錯誤的產生,提高程式碼質量,產生更有組織的程式碼,減少耦合,改進重構並鼓勵程式碼重複使用。 ## S - 單一職責原則 ![單一責任原則範例](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oebel9z9m0pupvh0bg02.png) >*SRP - 單一職責原則* 這原則說**一個類別必須有一個且只有一個改變的理由** 就是這樣,不要建立具有多種功能和職責的類別。您可能已經完成或遇到一個可以做所有事情的類,例如“God Class”。在那一刻看起來一切都很好,但是當需要對這個類別的邏輯進行任何更改時,問題肯定會開始出現。 >**God Class - God Class:** 在物件導向程式設計中,它是一個知道太多或做太多事情的類別。 ``` class Task { createTask(){/*...*/} updateTask(){/*...*/} deleteTask(){/*...*/} showAllTasks(){/*...*/} existsTask(){/*...*/} TaskCompleter(){/*...*/} } ``` 這個 **Task** 類別透過執行 **四個** 不同的任務來打破 **SRP** 原則。它正在處理**任務**的資料、顯示、驗證和驗證。 ### 這可能導致的問題: - 「缺乏連結」-一個類別不應該承擔不屬於它自己的責任; - 「太多的資訊在一起」 - 你的類別將有很多依賴項並且很難進行更改; - 「實現自動化測試的困難」 - 很難[“mock”](https://pt.wikipedia.org/wiki/Objeto_Mock)這種類型的類別; 現在將 **SRP** 應用於 *Task* 類,讓我們看看這個原則可以帶來的改進: ``` class TaskHandler{ createTask() {/*...*/} updateTask() {/*...*/} deleteTask() {/*...*/} } class TaskViewer{ showAllTasks() {/*...*/} } class TaskChecker { existsTask() {/*...*/} } class TaskCompleter { completeTask() {/*...*/} } ``` >您可以將建立、更新和刪除放在單獨的類別中,但根據專案的上下文和大小,最好避免不必要的複雜性。 也許您問過自己「我只能將其應用於類別嗎?」不,相反,您也可以將其應用於方法和函數。 ``` //❌ function emailClients(clients: IClient[]) { clients.forEach((client)=>{ const clientRecord = db.find(client); if(clientRecord){ sendEmail(client); } }) } //✅ function isClientActive(client: IClient):boolean { const clientRecord = db.find(client); return !!clientRecord; } function getActiveClients(clients: IClient[]):<IClient | undefined> { return clients.filter(isClientActive); } function emailClients(clients: IClient[]):void { const activeClients = getActiveClients(clients); activeClients?.forEach(sandEmail); } ``` 更美觀、優雅、更有組織的程式碼。這個原則是其他原則的基礎,透過應用它,您將建立優質、易於閱讀和易於維護的程式碼。 ## O - 開閉原則 ![開閉原則範例](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qk0e24cnjefd5e8r0h6c.png) >*OCP - 開閉原則* 這個原則說的是**物件或實體必須對擴充功能開放,但對修改關閉**,如果需要加入功能,最好對其進行擴展而不是更改其原始程式碼。 想像一個學校辦公室的小型系統,其中有兩個班級代表學生的課程表:小學和高中。另外還有一個班級,定義了學生的班級。 ``` class EnsinoFundamental { gradeCurricularFundamental(){} } class EnsinoMedio {     gradeCurricularMedio(){} } class SecretariaEscola { aulasDoAluno: string; cadastrarAula(aulasAluno){ if(aulasAluno instanceof EnsinoFundamental){ this.aulasDoAluno = aulasAluno.gradeCurricularFundamental(); } else if(aulasAluno.ensino instanceof EnsinoMedio){ this.aulasDoAluno = aulasAluno.gradeCurricularMedio(); } } } ``` `SecretariaEscola` 類別負責檢查學生的教育程度,以便在註冊課程時應用正確的業務規則。現在想像一下,這所學校在系統中加入了技術教育和課程表,那麼就需要修改這個課程,對吧?但是,這樣你就會遇到一個問題,那就是違反了*SOLID 的「開閉原則” *。 我想到了什麼解決方案?可能在類別中加入一個“else if”,就這樣,問題解決了。不是小學徒😐,這就是問題所在! **透過更改現有類別以加入新行為,我們面臨著將錯誤引入到已經執行的內容中的嚴重風險。** >**記住:** **OCP** 認為課程必須針對更改關閉並針對擴充功能開放。 看看重構程式碼所帶來的美妙之處: ``` interface gradeCurricular {     gradeDeAulas(); } class EnsinoFundamental implements gradeCurricular {     gradeDeAulas(){} } class EnsinoMedio implements gradeCurricular {     gradeDeAulas(){} } class EnsinoTecnico implements gradeCurricular {     gradeDeAulas(){} } class SecretariaEscola {     aulasDoAluno: string;     cadastrarAula(aulasAluno: gradeCurricular) {         this.aulasDoAluno = aulasAluno.gradeDeAulas();     } } ``` 看到 `SecretariaEscola` 類,它不再需要知道要呼叫哪些方法來註冊該類別。它將能夠為建立的任何新型教學模式正確註冊課程表,請注意,我加入了“EnsinoTecnico”,無需更改原始程式碼。 >*自從我實作了 `gradeCurrarily` 介面以來。* >介面背後的獨立可擴展行為和反向依賴關係。 >鮑伯叔叔 - `開放擴充`:您可以為類別加入一些新功能或行為,而無需更改其原始程式碼。 -「修改關閉」:如果您的類別已經具有不存在任何問題的功能或行為,請勿變更其原始程式碼以新增內容。 ## L - 里氏替換原則 ![里氏替換原理範例](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eyrl3p96aqzowf72ipcb.png) >*LSP - 里氏替換原理* 里氏替換原則 — **A** **衍生類別必須可以被其基底類別取代**。 *兄弟* Liskov 在 1987 年的一次會議上介紹的這個原理在閱讀他的解釋時有點難以理解,但是不用擔心,我將向您展示另一個解釋和一個示例來幫助您理解。 > 如果對於 S 類型的每個物件 o1 都有一個 T 類型的物件 o2,這樣,對於用 T 定義的所有程式 P,當 o1 被 o2 取代時 P 的行為不變,那麼 S 是 T 的子類型 你明白了嗎?不,我第一次讀它時(或其他十次)也不明白它,但等等,還有另一種解釋: > 如果 S 是 T 的子類型,則程式中類型 T 的物件可以用類型 S 的物件替換,而不必變更該程式的屬性。 - [維基百科](https://pt.wikipedia.org/wiki/Princ%C3%ADpio_da_substitui%C3%A7%C3%A3o_de_Liskov)。 如果您更直觀,我有一個程式碼範例: ``` class Fulano { falarNome() { return "sou fulano!"; } } class Sicrano extends Fulano { falarNome() { return "sou sicrano!"; } } const a = new Fulano(); const b = new Sicrano(); function imprimirNome(msg: string) { console.log(msg); } imprimirNome(a.falarNome()); // sou fulano! imprimirNome(b.falarNome()); // sou sicrano! ``` 父類別和衍生類別作為參數傳遞,並且程式碼繼續按預期工作,神奇嗎?沒什麼,這就是我們利斯科夫兄弟的原則。 ### 違規範例: - 覆蓋/實作一個不執行任何操作的方法; - 拋出意外的異常; - 從基底類別傳回不同類型的值; ## I - 介面隔離原則 ![範例介面隔離原則](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p88do8ivd00s9aofo5yq.png) >*ISP - 介面隔離原則* 介面隔離原則 — **不應強迫類別實作它不會使用的介面和方法。** 該原則表明,建立更具體的介面比建立通用介面更好。 在下面的範例中,建立了一個「Animal」接口來抽象化動物行為,然後類別實作該接口,請參閱: ``` interface Animal { comer(); dormir(); voar(); } class Pato implements Animal{ comer(){/*faz algo*/}; dormir(){/*faz algo*/}; voar(){/*faz algo*/}; } class Peixe implements Animal{ comer(){/*faz algo*/}; dormir(){/*faz algo*/}; voar(){/*faz algo*/}; // Esta implementação não faz sentido para um peixe // ela viola o Princípio da Segregação da Interface } ``` 通用介面「Animal」強制「Peixe」類別具有有意義的行為,最終違反了 **ISP** 原則和 **LSP** 原則。 使用 **ISP** 解決此問題: ``` interface Animal { comer(); dormir(); } interface AnimalQueVoa extends Animal { voar(); } class Peixe implements Animal{ comer(){/*faz algo*/}; dormir(){/*faz algo*/}; } class Pato implements AnimalQueVoa { comer(){/*faz algo*/}; dormir(){/*faz algo*/}; voar(){/*faz algo*/}; } ``` 現在更好了,“voar()”方法已從“Animal”介面中刪除,我們將其加入到派生介面“AnimalQueVoa”中。這樣,行為就在我們的上下文中被正確隔離,並且我們仍然尊重介面隔離的原則。 ## D - 依賴倒置原則 ![依賴倒置原則範例](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9s5ywa9xijb41c1z2l1a.png) > *DIP — 依賴倒置原理* 依賴倒置原則 — **依賴抽象,而不是實現。** > 1. 高層模組不應該依賴低層模組。兩者都必須依賴抽象。 > > 2. 抽像不應該依賴細節。細節必須依賴抽象。 > > - *叔叔鮑伯* 在下面的範例中,我將展示一個簡單的程式碼來說明**DIP**。在此範例中,我們有一個透過不同方式(例如電子郵件和簡訊)發送訊息的通知系統。首先讓我們為這些通知方式建立具體的類別: ``` class EmailNotification { send(message) { console.log(`Enviando e-mail: ${message}`); } } class SMSNotification { send(message) { console.log(`Enviando SMS: ${message}`); } } ``` 現在,讓我們建立一個依賴這些具體實作的服務類別: ``` class NotificationService { constructor() { this.emailNotification = new EmailNotification(); this.smsNotification = new SMSNotification(); } sendNotifications(message) { this.emailNotification.send(message); this.smsNotification.send(message); } } ``` 在上面的例子中,`NotificationService`直接依賴`EmailNotification`和`SMSNotification`的具體實作。這違反了 DIP,因為高級 `NotificationService` 類別直接依賴低階類別。 讓我們使用 **DIP** 修復此程式碼。高級“NotificationService”類別不應依賴具體實現,而應依賴抽象。讓我們建立一個「Notification」介面作為抽象: ``` // Abstração para o envio de notificações interface Notification { send(message) {} } ``` 現在,具體的「EmailNotification」和「SMSNotification」實作必須實作此介面: ``` class EmailNotification implements Notification { send(message) { console.log(`Enviando e-mail: ${message}`); } } class SMSNotification implements Notification { send(message) { console.log(`Enviando SMS: ${message}`); } } ``` 最後,通知服務類別可以依賴「Notification」抽象: ``` class NotificationService { constructor(notificationMethod: Notification) { this.notificationMethod = notificationMethod; } sendNotification(message) { this.notificationMethod.send(message); } } ``` 這樣,「NotificationService」服務類別依賴「Notification」抽象,而不是具體實現,從而滿足**依賴倒置原則**。 ## 結論 透過採用這些原則,開發人員可以建立更能適應變化的系統,使維護變得更容易,並隨著時間的推移提高程式碼品質。 所有這些內容都是基於我學習 OOP 期間在網上找到的筆記、其他文章和影片,其中的解釋接近原理的作者,而示例中使用的程式碼是我根據自己對 OOP 的理解建立的。原則。讀者,我希望我對您的學習進程有所幫助。 --- 原文出處:https://dev.to/clintonrocha98/era-solid-o-que-me-faltava-bhp

全端工具箱🧰:Python🐍版

## 簡介 以下是專注於全端開發不同面向的 Python 函式庫;有些專注於 Web 應用程式開發,有些專注於後端,有些則兩者兼而有之。 ![Gif引言](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8eodxlxdlgr0xh6lrvhz.gif) --- ## 1. [Taipy](https://github.com/Avaiga/taipy) Taipy 是一個開源 Python 庫,用於建立生產就緒的應用程式前端和後端。 它旨在加快應用程式開發,從最初的原型到生產就緒的應用程式。 🔑特點: - 豐富的互動性 - 為您的佈局、樣式等提供更多自訂功能(無需 CSS) - 多頁和多用戶應用程式 - 圖形管道編輯器 - 與 Taipy 前端功能整合以實現端到端部署 - 日程安排 - 筆記型電腦相容 ![Taipy](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1rk0w837hwaq0akybw6o.png) --- ![QueenB GIF](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0un08vhstrk6zpst5yti.gif) https://github.com/Avaiga/taipy 您的支持意義重大🌱,並且在許多方面為我們帶來了很大的幫助,例如寫文章! 🙏 --- ## 2.[Prefect](https://github.com/PrefectHQ/prefect) Prefect 是一個提供資料管道開發的框架。 它透過注重簡單性和用戶友好性而與 Airflow 等競爭對手區分開來。 如果您想要一個具有各種功能但比 Airflow 更容易學習的成熟產品,Prefect 是一個很好的中間產品。 🔑特點: - 直覺且使用者友好的控制面板 - 快取等智慧功能 - 以流程為基礎的架構,可輕鬆融入工作流程組織 - 動態參數化與依賴管理 - 混合執行(本地/雲端) ![完美](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p94g40hwv04gkfmvklda.png) --- ## 3. [Streamlit](https://github.com/streamlit/streamlit) Streamlit 是一個遊戲規則改變者,可以快速、簡單地建立 Web 應用程式。 此資料應用程式框架將其從更完整、更複雜的解決方案轉變為快速、用戶友好的解決方案。 🔑特點: - Pythonic框架 - 互動式小部件 - 使用者友善性 ![Streamlit](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ddntytwa95tgp37kykcc.png) --- ## 4.[氣流](https://github.com/apache/airflow) Apache Airflow 是一個開源平台,專為調度和監控工作流程而設計。 它是編排複雜資料管道和 ETL 流程的絕佳選擇,因為它在過去十年中一直是管道領域的重要參與者。 該庫的完整性與陡峭的學習曲線有關。 🔑特點: - 基於DAG的工作流程定義 - 包括 DAG 視覺化的完整介面,可追蹤故障並管理重試。 - 各種集成 - 動態任務執行和調度 - 以Python為中心的設計 - 社區支持 ![氣流](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lm89iyieg07c2rgzm2jb.png) --- ## 5. [Brython](https://github.com/brython-dev/brython) Brython 將 Python 帶到了前端,因為這個名字重新組合了「瀏覽器」和「Python」。 它引入了直接在 Web 應用程式中執行 Python 程式碼的獨特概念。 這種創新方法可讓您使用 Python 建立互動式 Web 體驗。 🔑特點: - 易於集成,因為它將 Python 邏輯直接整合到瀏覽器中 - 相容於不同的網頁瀏覽器 ![Brython](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9a7w7lqd9b5rtpahnolr.png) --- ## 6. [達世幣](https://github.com/plotly/dash) Dash 由 Plotly 建立,是一個利用 Plotlys 元件完整性的 Web 應用程式框架。 眾所周知,它是一個完整的解決方案,因此需要更長的時間來掌握。 🔑特點: - 基於元件的架構 - 強大的互動式儀表板 - 即時資料更新 ![破折號](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yp5xw24ulak6mnwwos69.png) --- ## 7. [Dagster](https://github.com/dagster-io/dagster) Dagster 是本次編譯中較新的函式庫之一,它是一個雲端原生資料管道編排,旨在統一資料整合、工作流程編排和監控。 與其他工具相比,Dagster 強調工作流程建立和管理的 DataOps 面向。 🔑特點: - 聲明式管道設置 - 固執己見的結構 - 版本控制 - 與 Hadoop 集成 - 全面的元資料跟踪 ![Dagster](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hz78m7rein4asbyp9buf.png) --- ## 8. [SQLAlchemy](https://github.com/sqlalchemy/sqlalchemy) SQLAlchemy 是一個用於處理資料庫互動的 Python 函式庫。 它是一個連接Python程式設計和關係資料庫的多功能工具包。 掌握這個庫的時間較長,但好處是實實在在的。 🔑特點: - SQL 表達式語言 - 物件關係映射(ORM) - 對資料庫的廣泛支持 - 複雜查詢支持 ![SQL](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/owtvt0kv5gt45r33ulra.png) --- ## 9. [芹菜](https://github.com/celery/celery) Celery 是一個 Python 函式庫,用作建立後端應用程式的框架。 它處理分散式任務處理、作業執行和工作流程。 它是一個完整的解決方案和廣泛的功能集,具有更陡峭的學習曲線。 🔑特點: - 平行處理 - 可擴展性 - 任務調度 - 非同步處理 ![芹菜](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p50my0xtbncfskb4y1ga.png) --- ## 10. [Peewee](https://github.com/coleifer/peewee) 與 SQAlchemy 一樣,Peewee 是一個簡化資料庫互動的 Python 函式庫。 它與競爭對手的不同之處在於用戶友好且簡單的設定。 該庫是中小型專案的最佳選擇。 🔑特點: - 輕量級框架 - 資料庫支持 - Python式文法 ![Peewee](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8tmvc7y9vkb2mdpj88jq.png) --- ## 11. [Kedro](https://github.com/kedro-org/kedro) Kedro 是一個開源 Python 框架。 它為生產就緒的資料科學管道提供了一個工具箱。 事實上,Kedro 可以輕鬆地與成熟的 Python ML 庫集成,並提供統一的方法來實現端到端框架。 🔑特點: - 資料目錄 - 筆記本集成 - 專案模板 - 有自己的觀點,因為它強制執行特定的約定 ![Kedro](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x2z12ofiibpd5c9ggs7s.png) --- ## 結論 Python 被認為是人工智慧和機器學習應用程式的首選語言。 為了簡化和自動化這些應用程式,Python 見證了框架庫的出現。 這些程式庫有助於 Web 應用程式開發、後端服務以及開源全端應用程式的建立。 --- ![新秀圖片](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/25oebh36ha622u74kpli.gif) 我剛開始我的內容創作之旅;如果您有任何問題或回饋,請隨時與我們聯繫! --- 原文出處:https://dev.to/taipy/full-stack-toolbox-python-edition-20h2