🔍 搜尋結果:create

🔍 搜尋結果:create

如何讓 AI 融入您的使用者(Next.js、OpenAI、CopilotKit)

長話短說 ---- 在本文中,您將了解如何建立基於 AI 的行銷活動管理應用程式,該應用程式可讓您建立和分析廣告活動,從而使您能夠為您的業務做出正確的決策。 我們將介紹如何: - 使用 Next.js 建立 Web 應用程式, - 使用 CopilotKit 將 AI 助理整合到軟體應用程式中,以及 - 建立特定於操作的人工智慧副駕駛來處理應用程式中的各種任務。 - 建立一名競選經理 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9xqpz356qm79t90f1l87.gif) --- CopilotKit:建構應用內人工智慧副駕駛的框架 -------------------------- CopilotKit是一個[開源的AI副駕駛平台](https://github.com/CopilotKit/CopilotKit)。我們可以輕鬆地將強大的人工智慧整合到您的 React 應用程式中。 建造: - ChatBot:上下文感知的應用內聊天機器人,可以在應用程式內執行操作 💬 - CopilotTextArea:人工智慧驅動的文字字段,具有上下文感知自動完成和插入功能📝 - 聯合代理:應用程式內人工智慧代理,可以與您的應用程式和使用者互動🤖 ![https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3 .amazonaws.com%2Fuploads%2Farticles%2Fx3us3vc140aun0dvrdof.gif](https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fx3us3vc140aun0dvrdof.gif) {% cta https://git.new/devtoarticle1 %} Star CopilotKit ⭐️ {% endcta %} --- 先決條件 ---- 要完全理解本教程,您需要對 React 或 Next.js 有基本的了解。 我們還將利用以下內容: - [Radix UI](https://www.radix-ui.com/) - 用於為應用程式建立可存取的 UI 元件。 - [OpenAI API 金鑰](https://platform.openai.com/api-keys)- 使我們能夠使用 GPT 模型執行各種任務。 - [CopilotKit](https://github.com/CopilotKit/CopilotKit) - 一個開源副駕駛框架,用於建立自訂 AI 聊天機器人、應用程式內 AI 代理程式和文字區域。 --- 專案設定和套件安裝 --------- 首先,透過在終端機中執行以下程式碼片段來建立 Next.js 應用程式: ``` npx create-next-app campaign-manager ``` 選擇您首選的配置設定。在本教學中,我們將使用 TypeScript 和 Next.js App Router。 ![Next.js 應用程式安裝](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xboujt60i6lpoaqgjyap.png) 接下來,將[Heroicons](https://www.npmjs.com/package/@heroicons/react) 、 [Radix UI](https://www.radix-ui.com/)及其原始元件安裝到專案中。 ``` npm install @heroicons/react @radix-ui/react-avatar @radix-ui/react-dialog @radix-ui/react-dropdown-menu @radix-ui/react-icons @radix-ui/react-label @radix-ui/react-popover @radix-ui/react-select @radix-ui/react-slot @radix-ui/react-tabs ``` 另外,安裝[Recharts 程式庫](https://recharts.org/en-US)(一個用於建立互動式圖表的 React 程式庫)以及以下實用程式套件: ``` npm install recharts class-variance-authority clsx cmdk date-fns lodash react-day-picker tailwind-merge tailwindcss-animate ``` 最後,安裝[CopilotKit 軟體套件](https://docs.copilotkit.ai/getting-started/quickstart-chatbot)。這些套件使 AI copilot 能夠從 React 狀態檢索資料並在應用程式中做出決策。 ``` npm install @copilotkit/react-ui @copilotkit/react-textarea @copilotkit/react-core @copilotkit/backend ``` 恭喜!您現在已準備好建立應用程式。 --- 使用 Next.js 建立 Campaign Manager 應用程式 ----------------------------------- 在本節中,我將引導您建立活動管理器應用程式的使用者介面。 首先,讓我們進行一些初始設定。 在`src`資料夾中建立一個`components`和`lib`資料夾。 ``` cd src mkdir components lib ``` 在**`lib`**資料夾中,我們將聲明應用程式的靜態類型和預設活動。因此,在**`lib`**資料夾中建立**`data.ts`**和**`types.ts`**檔案。 ``` cd lib touch data.ts type.ts ``` 將下面的程式碼片段複製到`type.ts`檔中。它聲明了活動屬性及其資料類型。 ``` export interface Campaign { id: string; objective?: | "brand-awareness" | "lead-generation" | "sales-conversion" | "website-traffic" | "engagement"; title: string; keywords: string; url: string; headline: string; description: string; budget: number; bidStrategy?: "manual-cpc" | "cpa" | "cpm"; bidAmount?: number; segment?: string; } ``` 為應用程式建立預設的行銷活動清單並將其複製到`data.ts`檔案中。 ``` import { Campaign } from "./types"; export let DEFAULT_CAMPAIGNS: Campaign[] = [ { id: "1", title: "CopilotKit", url: "https://www.copilotkit.ai", headline: "Copilot Kit - The Open-Source Copilot Framework", description: "Build, deploy, and operate fully custom AI Copilots. In-app AI chatbots, AI agents, AI Textareas and more.", budget: 10000, keywords: "AI, chatbot, open-source, copilot, framework", }, { id: "2", title: "EcoHome Essentials", url: "https://www.ecohomeessentials.com", headline: "Sustainable Living Made Easy", description: "Discover our eco-friendly products that make sustainable living effortless. Shop now for green alternatives!", budget: 7500, keywords: "eco-friendly, sustainable, green products, home essentials", }, { id: "3", title: "TechGear Solutions", url: "https://www.techgearsolutions.com", headline: "Innovative Tech for the Modern World", description: "Find the latest gadgets and tech solutions. Upgrade your life with smart technology today!", budget: 12000, keywords: "tech, gadgets, innovative, modern, electronics", }, { id: "4", title: "Global Travels", url: "https://www.globaltravels.com", headline: "Travel the World with Confidence", description: "Experience bespoke travel packages tailored to your dreams. Luxury, adventure, relaxation—your journey starts here.", budget: 20000, keywords: "travel, luxury, adventure, tours, global", }, { id: "5", title: "FreshFit Meals", url: "https://www.freshfitmeals.com", headline: "Healthy Eating, Simplified", description: "Nutritious, delicious meals delivered to your door. Eating well has never been easier or tastier.", budget: 5000, keywords: "healthy, meals, nutrition, delivery, fit", }, ]; ``` 由於我們使用 Radix UI 建立可以使用 TailwindCSS 輕鬆自訂的基本 UI 元件,因此請在**`lib`**資料夾中建立一個**`utils.ts`**文件,並將以下程式碼片段複製到該文件中。 ``` //👉🏻 The lib folder now contains 3 files - data.ts, type.ts, util.ts //👇🏻 Copy the code below into the "lib/util.ts" file. import { type ClassValue, clsx } from "clsx"; import { twMerge } from "tailwind-merge"; export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)); } export function randomId() { return Math.random().toString(36).substring(2, 15); } ``` 導航到`components`資料夾並在其中建立其他三個資料夾。 ``` cd components mkdir app dashboard ui ``` `components/app`資料夾將包含應用程式中使用的各種元件,而儀表板資料夾包含某些元素的 UI 元件。 `ui`資料夾包含使用 Radix UI 建立的多個 UI 元素。將[專案儲存庫中的這些元素](https://github.com/CopilotKit/campaign-manager-demo/tree/main/src/components/ui)複製到該資料夾中。 恭喜! `ui`資料夾應包含必要的 UI 元素。現在,我們可以使用它們來建立應用程式中所需的各種元件。 ### 建立應用程式 UI 元件 在這裡,我將引導您完成為應用程式建立使用者介面的過程。 ![應用程式使用者介面](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9l4lvv4394gg033oatwq.png) 首先,導航至**`app/page.tsx`**檔案並將以下程式碼片段貼到其中。該文件呈現在**`components/app`**資料夾中聲明的 App 元件。 ``` "use client"; import { App } from "@/components/app/App"; export default function DashboardPage() { return <App />; } ``` 在`components/app`資料夾中建立`App.tsx` 、 `CampaignForm.tsx` 、 `MainNav.tsx`和`UserNav.tsx`檔案。 ``` cd components/app touch App.tsx CampaignForm.tsx MainNav.tsx UserNav.tsx ``` 將下面的程式碼片段複製到`App.tsx`檔案中。 ``` "use client"; import { DEFAULT_CAMPAIGNS } from "@/lib/data"; import { Campaign } from "@/lib/types"; import { randomId } from "@/lib/utils"; import { Dashboard } from "../dashboard/Dashboard"; import { CampaignForm } from "./CampaignForm"; import { useState } from "react"; import _ from "lodash"; export function App() { //👇🏻 default segments const [segments, setSegments] = useState<string[]>([ "Millennials/Female/Urban", "Parents/30s/Suburbs", "Seniors/Female/Rural", "Professionals/40s/Midwest", "Gamers/Male", ]); const [campaigns, setCampaigns] = useState<Campaign[]>( _.cloneDeep(DEFAULT_CAMPAIGNS) ); //👇🏻 updates campaign list function saveCampaign(campaign: Campaign) { //👇🏻 newly created campaign if (campaign.id === "") { campaign.id = randomId(); setCampaigns([campaign, ...campaigns]); } else { //👇🏻 existing campaign - search for the campaign and updates the campaign list const index = campaigns.findIndex((c) => c.id === campaign.id); if (index === -1) { setCampaigns([...campaigns, campaign]); } else { campaigns[index] = campaign; setCampaigns([...campaigns]); } } } const [currentCampaign, setCurrentCampaign] = useState<Campaign | undefined>( undefined ); return ( <div className='relative'> <CampaignForm segments={segments} currentCampaign={currentCampaign} setCurrentCampaign={setCurrentCampaign} saveCampaign={(campaign) => { if (campaign) { saveCampaign(campaign); } setCurrentCampaign(undefined); }} /> <Dashboard campaigns={campaigns} setCurrentCampaign={setCurrentCampaign} segments={segments} setSegments={setSegments} /> </div> ); } ``` - 從上面的程式碼片段來看, - 我為行銷活動建立了預設細分列表,並對已定義的行銷活動列表進行了深層複製。 - `saveCampaign`函數接受行銷活動作為參數。如果行銷活動沒有 ID,則表示它是新建立的,因此會將其新增至行銷活動清單。否則,它會找到該活動並更新其屬性。 - `Dashboard`和`CampaignForm`元件接受細分和行銷活動作為 props。 [Dashboard 元件](https://github.com/CopilotKit/campaign-manager-demo/blob/main/src/components/dashboard/Dashboard.tsx)在儀表板上顯示各種 UI 元素,而[CampaignForm 元件](https://github.com/CopilotKit/campaign-manager-demo/blob/main/src/components/app/CampaignForm.tsx)使用戶能夠在應用程式中建立和保存新的行銷活動。 您也可以使用[GitHub 儲存庫](https://github.com/CopilotKit/campaign-manager-demo/tree/main/src/components)中的程式碼片段來更新儀表板和應用程式元件。 恭喜!您應該有一個有效的 Web 應用程式,可讓使用者查看和建立新的行銷活動。 在接下來的部分中,您將了解如何將 CopilotKit 加入到應用程式中,以根據每個行銷活動的目標和預算進行分析和決策。 ![應用概述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4phyaucli8pdcbe625u4.gif) --- 使用 CopilotKit 透過 AI 分析廣告活動 -------------------------- 在這裡,您將學習如何將人工智慧加入到應用程式中,以幫助您分析行銷活動並做出最佳決策。 在繼續之前,請造訪[OpenAI 開發者平台](https://platform.openai.com/api-keys)並建立一個新的金鑰。 ![取得 OpenAI API 金鑰](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/02972pt2aj3kf9l5suqq.png) 建立一個`.env.local`檔案並將新建立的金鑰複製到該檔案中。 ``` OPENAI_API_KEY=<YOUR_OPENAI_SECRET_KEY> OPENAI_MODEL=gpt-4-1106-preview ``` 接下來,您需要為 CopilotKit 建立 API 端點。在 Next.js 應用程式資料夾中,建立一個包含`route.ts`檔案的`api/copilotkit`資料夾。 ``` cd app mkdir api && cd api mkdir copilotkit && cd copilotkit touch route.ts ``` 將下面的程式碼片段複製到`route.ts`檔中。 [CopilotKit 後端](https://docs.copilotkit.ai/reference/CopilotBackend)接受使用者的請求並使用 OpenAI 模型做出決策。 ``` import { CopilotBackend, OpenAIAdapter } from "@copilotkit/backend"; export const runtime = "edge"; export async function POST(req: Request): Promise<Response> { const copilotKit = new CopilotBackend({}); const openaiModel = process.env["OPENAI_MODEL"]; return copilotKit.response(req, new OpenAIAdapter({ model: openaiModel })); } ``` 若要將您的應用程式連接到此 API 端點,請更新`app/page.tsx`文件,如下所示: ``` "use client"; import { App } from "@/components/app/App"; import { CopilotKit } from "@copilotkit/react-core"; import { CopilotSidebar } from "@copilotkit/react-ui"; export default function DashboardPage() { return ( <CopilotKit url='/api/copilotkit/'> <CopilotSidebar instructions='Help the user create and manage ad campaigns.' defaultOpen={true} labels={{ title: "Campaign Manager Copilot", initial: "Hello there! I can help you manage your ad campaigns. What campaign would you like to work on?", }} clickOutsideToClose={false} > <App /> </CopilotSidebar> </CopilotKit> ); } ``` `CopilotKit`元件包裝整個應用程式並接受包含 API 端點連結的`url`屬性。 `CopilotSidebar`元件為應用程式加入了一個聊天機器人側邊欄面板,使我們能夠向 CopilotKit 提供各種指令。 ![將 CopilotKit 加入 Next.js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wzh8ui253ftzmgtrcksd.gif) ### 如何讓AI副駕駛執行各種動作 CopilotKit 提供了兩個鉤子,使我們能夠處理使用者的請求並插入應用程式狀態: [useCopilotAction](https://docs.copilotkit.ai/reference/useCopilotAction)和[useMakeCopilotReadable](https://docs.copilotkit.ai/reference/useMakeCopilotReadable) 。 `useCopilotAction`掛鉤可讓您定義 CopilotKit 執行的動作。它接受包含以下參數的物件: - name - 操作的名稱。 - 描述 - 操作的描述。 - 參數 - 包含所需參數清單的陣列。 - render - 預設的自訂函數或字串。 - handler - 由操作觸發的可執行函數。 ``` useCopilotAction({ name: "sayHello", description: "Say hello to someone.", parameters: [ { name: "name", type: "string", description: "name of the person to say greet", }, ], render: "Process greeting message...", handler: async ({ name }) => { alert(`Hello, ${name}!`); }, }); ``` `useMakeCopilotReadable`掛鉤向 CopilotKit 提供應用程式狀態。 ``` import { useMakeCopilotReadable } from "@copilotkit/react-core"; const appState = ...; useMakeCopilotReadable(JSON.stringify(appState)); ``` CopilotKit 還允許您為使用者提示提供上下文,使其能夠做出充分且準確的決策。 將`guidance.ts`和`script.ts`加入到專案內的`lib`資料夾中,並將此[指導](https://github.com/CopilotKit/campaign-manager-demo/blob/main/src/lib/guideline.ts)和[腳本建議](https://github.com/CopilotKit/campaign-manager-demo/blob/main/src/lib/script.ts)複製到檔案中,以便 CopilotKit 做出決策。 在應用程式元件中,將當前日期、腳本建議和指導傳遞到 CopilotKit。 ``` import { GUIDELINE } from "@/lib/guideline"; import { SCRIPT_SUGGESTION } from "@/lib/script"; import { useCopilotAction, useMakeCopilotReadable, } from "@copilotkit/react-core"; export function App() { //-- 👉🏻 ...other component functions //👇🏻 Ground the Copilot with domain-specific knowledge for this use-case: marketing campaigns. useMakeCopilotReadable(GUIDELINE); useMakeCopilotReadable(SCRIPT_SUGGESTION); //👇🏻 Provide the Copilot with the current date. useMakeCopilotReadable("Today's date is " + new Date().toDateString()); return ( <div className='relative'> <CampaignForm segments={segments} currentCampaign={currentCampaign} setCurrentCampaign={setCurrentCampaign} saveCampaign={(campaign) => { if (campaign) { saveCampaign(campaign); } setCurrentCampaign(undefined); }} /> <Dashboard campaigns={campaigns} setCurrentCampaign={setCurrentCampaign} segments={segments} setSegments={setSegments} /> </div> ); } ``` 在`App`元件中建立一個 CopilotKit 操作,該操作可在使用者提供此類指令時建立新的活動或編輯現有的活動。 ``` useCopilotAction({ name: "updateCurrentCampaign", description: "Edit an existing campaign or create a new one. To update only a part of a campaign, provide the id of the campaign to edit and the new values only.", parameters: [ { name: "id", description: "The id of the campaign to edit. If empty, a new campaign will be created", type: "string", }, { name: "title", description: "The title of the campaign", type: "string", required: false, }, { name: "keywords", description: "Search keywords for the campaign", type: "string", required: false, }, { name: "url", description: "The URL to link the ad to. Most of the time, the user will provide this value, leave it empty unless asked by the user.", type: "string", required: false, }, { name: "headline", description: "The headline displayed in the ad. This should be a 5-10 words", type: "string", required: false, }, { name: "description", description: "The description displayed in the ad. This should be a short text", type: "string", required: false, }, { name: "budget", description: "The budget of the campaign", type: "number", required: false, }, { name: "objective", description: "The objective of the campaign", type: "string", enum: [ "brand-awareness", "lead-generation", "sales-conversion", "website-traffic", "engagement", ], }, { name: "bidStrategy", description: "The bid strategy of the campaign", type: "string", enum: ["manual-cpc", "cpa", "cpm"], required: false, }, { name: "bidAmount", description: "The bid amount of the campaign", type: "number", required: false, }, { name: "segment", description: "The segment of the campaign", type: "string", required: false, enum: segments, }, ], handler: (campaign) => { const newValue = _.assign( _.cloneDeep(currentCampaign), _.omitBy(campaign, _.isUndefined) ) as Campaign; setCurrentCampaign(newValue); }, render: (props) => { if (props.status === "complete") { return "Campaign updated successfully"; } else { return "Updating campaign"; } }, }); ``` {% 嵌入 https://www.youtube.com/watch?v=gCJpH6Tnj5g %} 新增另一個模擬 API 呼叫的操作,以允許 CopilotKit 從先前建立的活動中檢索歷史資料。 ``` // Provide this component's Copilot with the ability to retrieve historical cost data for certain keywords. // Will be called automatically when needed by the Copilot. useCopilotAction({ name: "retrieveHistoricalData", description: "Retrieve historical data for certain keywords", parameters: [ { name: "keywords", description: "The keywords to retrieve data for", type: "string", }, { name: "type", description: "The type of data to retrieve for the keywords.", type: "string", enum: ["CPM", "CPA", "CPC"], }, ], handler: async ({ type }) => { // fake an API call that retrieves historical data for cost for certain keywords based on campaign type (CPM, CPA, CPC) await new Promise((resolve) => setTimeout(resolve, 2000)); function getRandomValue(min: number, max: number) { return (Math.random() * (max - min) + min).toFixed(2); } if (type == "CPM") { return getRandomValue(0.5, 10); } else if (type == "CPA") { return getRandomValue(5, 100); } else if (type == "CPC") { return getRandomValue(0.2, 2); } }, render: (props) => { // Custom in-chat component rendering. Different components can be rendered based on the status of the action. let label = "Retrieving historical data ..."; if (props.args.type) { label = `Retrieving ${props.args.type} for keywords ...`; } if (props.status === "complete") { label = `Done retrieving ${props.args.type} for keywords.`; } const done = props.status === "complete"; return ( <div className=''> <div className=' w-full relative max-w-xs'> <div className='absolute inset-0 h-full w-full bg-gradient-to-r from-blue-500 to-teal-500 transform scale-[0.80] bg-red-500 rounded-full blur-3xl' /> <div className='relative shadow-xl bg-gray-900 border border-gray-800 px-4 py-8 h-full overflow-hidden rounded-2xl flex flex-col justify-end items-start'> <h1 className='font-bold text-sm text-white mb-4 relative z-50'> {label} </h1> <p className='font-normal text-base text-teal-200 mb-2 relative z-50 whitespace-pre'> {props.args.type && `Historical ${props.args.type}: ${props.result || "..."}`} </p> </div> </div> </div> ); }, }); ``` ![應用程式預覽](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kz3xm63ciq5q3kyooz9s.gif) 恭喜!您已完成本教學的專案。 結論 -- [CopilotKit](https://copilotkit.ai/)是一款令人難以置信的工具,可讓您在幾分鐘內將 AI Copilot 加入到您的產品中。無論您是對人工智慧聊天機器人和助理感興趣,還是對複雜任務的自動化感興趣,CopilotKit 都能讓您輕鬆實現。 如果您需要建立 AI 產品或將 AI 工具整合到您的軟體應用程式中,您應該考慮 CopilotKit。 您可以在 GitHub 上找到本教學的源程式碼: <https://github.com/CopilotKit/campaign-manager-demo> 感謝您的閱讀! --- 原文出處:https://dev.to/copilotkit/build-an-ai-powered-campaign-manager-nextjs-openai-copilotkit-59ii

我用新的程式語言微調了我的模型。你也可以做到! 🚀

我使用 OpenAI ChatGPT-4 一段時間了。 對此我沒什麼好說的。 但有時,這還不夠。 在[Winglang](https://github.com/winglang/wing)中,我們希望使用 OpenAI 和 ChatGPT-4 根據我們的文件回答人們的問題。 您的選擇是: - 使用[OpenAI 助理](https://platform.openai.com/docs/assistants/overview?context=with-streaming)或任何其他基於向量的資料庫 (RAG)。由於 Wing 看起來像 JS,所以效果很好,但仍然有很多錯誤。 - 將整個文件傳遞到上下文視窗的成本非常高。 很快,我們意識到這是行不通的。 是時候舉辦我們自己的法學碩士課程了。 ![問題](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o9x9ng6feh6x739djcb0.gif) --- 您的 LLM 資料集 ========== 在訓練模型之前,我們需要建立用於訓練模型的資料。在我們的例子中,是 Winglang 文件。我會做一些非常簡單的事情。 1. 從網站地圖中提取所有 URL,設定 GET 請求並收集內容。 2. 解析它;我們希望將所有 HTML 轉換為可讀內容。 3. 使用 ChatGPT 4 執行它,將內容轉換為 CSV 作為資料集。 它應該是這樣的: ![法學碩士資料集](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e2xq8lm4b31k8pop4gmc.png) 完成後,儲存包含一列名為`text`的 CSV 並新增問題和答案。我們稍後會用到它。它應該看起來像這樣: ``` text <s>[INST]How to define a variable in Winglang[/INST] let a = 'Hello';</s> <s>[INST]How to create a new lambda[/INST] bring cloud; let func = new cloud.Function(inflight () => { log('Hello from the cloud!'); });</s> ``` 將其保存在電腦上名為`data`新資料夾中。 --- Autotrain,您的模型 ============== 我的電腦很弱,所以我決定使用更小的模型 - 7b 參數: `mistralai/Mistral-7B-v0.1` 訓練模型的方法有數百萬種。我們將使用 Huggingface Autotrain。我們將使用他們的 CLI,而不執行任何 Python 程式碼🚀 當您使用 Huggingface 的 Autotrain 時,您可以在電腦上訓練它(這裡是我的方法)或在他們的伺服器上訓練它(付費)並訓練更大的模型。 我的舊 Macbook Pro M1 2021 沒有 GPU。 讓我們安裝自動訓練。 ``` pip install -U autotrain-advanced autotrain setup > setup_logs.txt ``` 然後,我們需要做的就是執行 autotrain 指令: ``` autotrain llm \ --train \ --model "mistralai/Mistral-7B-Instruct-v0.2" \ --project-name "autotrain-wing" \ --data-path data/ \ --text-column text \ --lr "0.0002" \ --batch-size "1" \ --epochs "3" \ --block-size "1024" \ --warmup-ratio "0.1" \ --lora-r "16" \ --lora-alpha "32" \ --lora-dropout "0.05" \ --weight-decay "0.01" \ --gradient-accumulation "4" \ --quantization "int4" \ --mixed-precision "fp16" \ --peft ``` 完成後,您將擁有一個名為“autotrain-wing”的新目錄,其中包含新的微調模型🚀 --- 玩模型 --- 要使用模型,請先執行: ``` pip install transformers torch ``` 完成後,使用以下程式碼建立一個名為 invoke.py 的新 Python 檔案: ``` from transformers import pipeline # Path to your local model directory model_path = "./autotrain-wing" # Load the model and tokenizer from the local directory classifier = pipeline("text-classification", model=model_path, tokenizer=model_path) # Example text to classify text = "Example text to classify" result = classifier(text) print(result) ``` 然後您可以透過執行 CLI 命令來執行它: ``` python invoke.py ``` 你就完成了🚀 --- 繼續攻讀法學碩士 -------- 我仍在學習法學碩士。 我意識到的一件事是追蹤模型的變化並不容易。 你不能真正將它與 Git 一起使用,因為模型可以達到非常大的大小 &gt; 100 GB;這沒有多大意義——git 不能很好地處理它。 更好的方法是使用名為[KitOps 的](https://github.com/jozu-ai/kitops/)工具。 我認為它很快就會成為法學碩士世界的標準,所以請確保你給這個庫加註星標,以便以後可以使用它。 1. 下載最新的[KitOps 版本](https://github.com/jozu-ai/kitops/releases/tag/v0.1.3)並[安裝它](https://kitops.ml/docs/cli/installation.html)。 2. 轉到模型資料夾並執行命令來打包您的 LLM: ``` kit pack . ``` 3. 您也可以透過執行將其推送到 Docker hub ``` kit pack . -t [your registry address]/[your repository name]/mymodelkit:latest ``` > 💡 要了解如何使用 DockerHub,[請檢查此](https://kitops.ml/docs/quick-start.html) {% cta https://github.com/jozu-ai/kitops %}⭐️ Star KitOps,以便您稍後可以再次找到它⭐️{% endcta %} [![星庫](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/362tc5831i5ozbsau2o3.png)](https://github.com/jozu-ai/kitops) --- 我建立了一個新的 YouTube 頻道,主要是關於開源行銷:) (例如如何獲得星星、叉子和客戶端) 如果您對此感興趣,請隨時在這裡訂閱: https://www.youtube.com/@nevo-david?sub\_confirmation=1 --- 原文出處:https://dev.to/github20k/i-fine-tuned-my-model-on-a-new-programming-language-you-can-do-it-too-449

深入探討 Javascript 函數式編程

[訂閱我的程式設計 YouTube 頻道](https://www.youtube.com/@alexmercedcoder) [訂閱我的資料 YouTube 頻道](https://www.youtube.com/@alexmerceddata) 函數式程式設計 (FP) 在軟體開發領域獲得了巨大的關注,JavaScript 開發人員越來越多地轉向這種範例,以更有效地解決問題並減少錯誤。從本質上講,函數式程式設計強調使用純函數、不變性以及柯里化、記憶化和 monad 等先進技術來建立更清晰、更可預測的程式碼。 在這篇文章中,我們將深入研究每個概念,以了解它們的工作原理以及它們在 JavaScript 開發中的重要性。我們將探索**純函數**的無副作用性質、用於維護狀態可預測性的**不變性**、用於增強函數重用和組合的**柯里化**、用於優化性能的**記憶化**以及用於以函數式風格處理副作用的**monad** 。 無論您是函數式程式設計的新手,還是希望加深對其在 JavaScript 中的應用的理解,這篇文章都將為您提供堅實的基礎和實際範例,以便將這些原則整合到您的編碼實踐中。讓我們揭開這些概念的神秘面紗,看看它們如何改變您編寫 JavaScript 程式碼的方式。 1. 純函數 ------ **純函數**是一種函數,在給定相同的輸入的情況下,將始終返回相同的輸出,並且不會導致任何可觀察到的副作用。這個概念在函數式程式設計中至關重要,因為它允許開發人員編寫更可預測和可測試的程式碼。 ### 在 JavaScript 中使用純函數的好處: - **可預測性:**由於純函數不依賴或修改其範圍之外的資料狀態,因此它們更容易推理和除錯。 - **可重複使用性:**純函數可以在應用程式的不同部分重複使用,而無需考慮外部上下文。 - **可測試性:**沒有隱藏狀態或副作用,純函數很容易測試;輸入和輸出是您需要考慮的全部。 ### JavaScript 中純函數的範例: 考慮一個簡單的函數來計算矩形的面積: ``` function rectangleArea(length, width) { return length * width; } ``` 這個函數是純粹的,因為它總是使用相同的參數來傳回相同的結果,而且它不會修改任何外部狀態或產生副作用。 ### 常見陷阱以及如何避免它們: 雖然純函數提供了許多好處,但開發人員在嘗試將它們整合到與資料庫、外部服務或全域狀態互動的應用程式時可能會面臨挑戰。以下是保持純度的一些技巧: - **避免副作用:**不要修改函數內的任何外部變數或物件。 - **本機處理狀態:**如果您的函數需要存取應用程式狀態,請考慮將狀態作為參數傳遞並傳回新狀態而不修改原始狀態。 透過理解和實現純函數,開發人員可以在充分利用 JavaScript 中函數式程式設計的全部功能方面邁出重要一步。 2. 不變性 ------ **不變性**是指資料建立後永不更改的原則。您無需修改現有物件,而是建立一個包含所需變更的新物件。這是函數式程式設計的基石,因為它有助於防止副作用並在應用程式的整個生命週期中保持資料的完整性。 ### JavaScript 如何處理不變性: 預設情況下,JavaScript 物件和陣列是可變的,這表示在需要時必須注意強制執行不變性。但是,有幾種技術和工具可以提供幫助: - **使用`const` :**雖然`const`不會使變數變得不可變,但它可以防止將變數辨識碼重新指派給新值,這是邁向不變性的一步。 - **Object.freeze():**此方法可以透過防止向物件新增屬性和修改現有屬性來使物件不可變。 - **陣列和物件的擴展語法:**使用擴展語法可以幫助建立新的陣列或物件,同時合併現有陣列或物件的元素或屬性,而無需修改原始陣列或物件。 ### 確保 JavaScript 中資料不變性的技術: 1. **寫入時複製:**始終建立一個新的物件或陣列,而不是修改現有的物件或陣列。例如: ``` const original = { a: 1, b: 2 }; const modified = { ...original, b: 3 }; // 'original' is not changed ``` 2. **使用函式庫:**像 Immutable.js 這樣的函式庫提供了高度最佳化的持久不可變資料結構,可以簡化不變性的實作。 ### 幫助實施不變性的函式庫: - **Immutable.js:**提供一系列本質上不可變的資料結構。 - **immer:**允許您透過使用臨時草稿狀態並套用變更來產生新的不可變狀態,以更方便的方式處理不可變狀態。 透過將不變性整合到 JavaScript 專案中,您可以增強資料完整性、提高應用程式效能(透過減少防禦性複製的需求)並提高程式碼的可預測性。它完全符合函數式程式設計的原則,從而產生更乾淨、更健壯的軟體。 3.柯里化 ----- **柯里化**是函數式程式設計中的一種變革性技術,其中具有多個參數的函數被轉換為一系列函數,每個函數採用一個參數。這種方法不僅使您的函數更加模組化,而且還增強了程式碼的可重複使用性和可組合性。 ### JavaScript 柯里化的實際用途: 柯里化允許建立高階函數,這些函數可以在應用程式的不同點使用不同的參數進行自訂和重複使用。它特別適用於: - **事件處理:**建立針對特定事件自訂的部分應用函數,但重複使用通用處理程序邏輯。 - **API 呼叫:**使用預定義參數(例如 API 金鑰或使用者 ID)設定函數,這些參數可以在不同的呼叫中重複使用。 ### 說明柯里化的逐步範例: 考慮一個簡單的函數來加兩個數字: ``` function add(a, b) { return a + b; } // Curried version of the add function function curriedAdd(a) { return function(b) { return a + b; }; } const addFive = curriedAdd(5); console.log(addFive(3)); // Outputs: 8 ``` 此範例展示了柯里化如何將簡單的加法函數轉變為更通用和可重複使用的函數。 ### 柯里化與部分應用: 雖然柯里化和部分應用都涉及將函數分解為更簡單、更具體的函數,但它們並不相同: - **柯里化(Currying):**將具有多個參數的函數轉換為一系列巢狀函數,每個函數只接受一個參數。 - **部分應用:**涉及透過預先填充一些參數來建立具有較少參數的函數。 這兩種技術在函數式程式設計中都很有價值,可以用來簡化複雜的函數簽名並提高程式碼模組化。 透過利用柯里化,開發人員可以增強函數的可重複使用性和組合性,從而在 JavaScript 專案中產生更清晰、更易於維護的程式碼。 4. 記憶 ----- **記憶化**是函數式程式設計中使用的最佳化技術,透過儲存昂貴的函數呼叫的結果並在相同的輸入再次發生時返回快取的結果來加速電腦程式。它在 JavaScript 中對於優化涉及繁重計算任務的應用程式的效能特別有用。 ### 為什麼記憶化在 JavaScript 很重要: - **效率:**減少使用相同參數重複呼叫函數所需的計算次數。 - **效能:**透過快取耗時操作的結果來提高應用程式回應能力。 - **可擴展性:**透過最小化計算開銷來幫助管理更大的資料集或更複雜的演算法。 ### 實現記憶化:範例和常用方法: 以下是 JavaScript 中記憶函數的基本範例: ``` function memoize(fn) { const cache = {}; return function(...args) { const key = args.toString(); if (!cache[key]) { cache[key] = fn.apply(this, args); } return cache[key]; }; } const factorial = memoize(function(x) { if (x === 0) { return 1; } else { return x * factorial(x - 1); } }); console.log(factorial(5)); // Calculates and caches the result console.log(factorial(5)); // Returns the cached result ``` 此範例示範了記憶化如何快取階乘計算的結果,從而顯著減少重複呼叫的計算時間。 ### 記憶化的優點和潛在缺點: #### 好處: - 顯著減少重複操作的處理時間。 - 透過避免冗餘計算來提高應用程式效率。 - 易於用高階函數實現。 #### 缺點: - 由於快取而增加記憶體使用量。 - 不適合具有不確定性輸出的函數或具有副作用的函數。 透過理解和實現記憶化,開發人員可以優化他們的 JavaScript 應用程式,使其更快、更有效率。然而,重要的是要考慮額外記憶體使用方面的權衡,並確保僅在能夠提供明顯好處的地方應用記憶化。 5. 單子 ----- **Monad**是函數式程式設計中使用的抽象資料類型,用於處理副作用,同時保持純函數原則。它們將行為和邏輯封裝在靈活的可連結結構中,允許順序操作,同時保持函數的純淨。 ### Monad 簡介及其在 FP 中的意義: Monad 提供了一個以受控方式處理副作用(如 IO、狀態、異常等)的框架,有助於保持功能的純度和可組合性。在 JavaScript 中,Promise 是一個常見的一元結構範例,可以乾淨且有效率地管理非同步操作。 ### JavaScript 中 Monad 的範例: - **Promises:**透過封裝待處理操作、成功值或錯誤來處理非同步操作,允許方法連結(如`.then()`和`.catch()` ): ``` new Promise((resolve, reject) => { setTimeout(() => resolve("Data fetched"), 1000); }) .then(data => console.log(data)) .catch(error => console.error(error)); ``` - **Maybe Monad:**透過封裝可能存在或不存在的值來幫助處理 null 或未定義的錯誤: ``` function Maybe(value) { this.value = value; } Maybe.prototype.bind = function(transform) { return this.value == null ? this : new Maybe(transform(this.value)); }; Maybe.prototype.toString = function() { return `Maybe(${this.value})`; }; const result = new Maybe("Hello, world!").bind(value => value.toUpperCase()); console.log(result.toString()); // Outputs: Maybe(HELLO, WORLD!) ``` ### Monad 定律與結構: Monad 必須遵循三個核心定律——同一性、關聯性和單位——以確保它們的行為可預測: - **同一性:**直接應用函數或透過 monad 傳遞函數應該會產生相同的結果。 - **關聯性:**執行操作的順序(連結)不影響結果。 - **單位:**一個值必須能夠被提升為一個單子而不改變其行為。 理解這些定律對於在函數式程式設計中有效地實現或利用 monad 至關重要。 ### Monad 如何管理副作用並保持功能純度: 透過封裝副作用,monad 允許開發人員保持程式碼庫的其餘部分純淨,從而更易於理解和維護。它們使副作用可預測和可管理,這對於維護狀態一致性和錯誤處理可能變得具有挑戰性的大型應用程式至關重要。 透過利用 monad,開發人員可以增強 JavaScript 應用程式的功能,確保它們以功能性的方式處理副作用,從而提高程式碼的可靠性和可維護性。 6. 這些概念如何相互關聯 ------------- 純函數、不變性、柯里化、記憶化和 monad 的概念不僅僅是單獨的元素,而是增強 JavaScript 應用程式的健全性和可維護性的互連工具。以下是他們如何共同創造一個有凝聚力的函數式程式設計環境。 ### 建立功能協同: - **純函數與不變性:**純函數確保函數沒有副作用,並為相同的輸入傳回相同的輸出,並透過防止資料意外變更的不變性來補充。它們共同確保了可預測且穩定的程式碼庫。 - **柯里化和記憶化:**柯里化允許將函數分解為更簡單的單參數函數,這些函數更易於管理和記憶。然後可以將記憶化應用於這些柯里化函數以緩存其結果,透過避免重複計算來優化應用程式的效能。 - **Monad 和純函數:** Monad 有助於以受控方式管理副作用,這使得純函數即使在處理 I/O 或狀態轉換等操作時也能保持純淨。這種副作用的封裝保留了功能架構的完整性。 ### 範例:一個小型功能模組: 讓我們考慮一個將這些概念結合在一起的實際範例。假設我們正在建立一個簡單的用戶註冊模組: ``` // A pure function to validate user input const validateInput = input => input.trim() !== ''; // A curried function for creating a user object const createUser = name => ({ id: Date.now(), name }); // Memoizing the createUser function to avoid redundant operations const memoizedCreateUser = memoize(createUser); // A monad for handling potential null values in user input const getUser = input => new Maybe(input).bind(validateInput); // Example usage const input = getUser(' John Doe '); const user = input.bind(memoizedCreateUser); console.log(user.toString()); // Outputs user details or empty Maybe ``` 在此範例中, `validateInput`是確保輸入有效性的純函數。 `createUser`是一個柯里化和記憶化的函數,針對效能進行了最佳化,而`getUser`使用 monad 來安全地處理潛在的 null 值。 結論: --- 理解和整合這些函數式程式設計概念可以顯著提高 JavaScript 程式碼的品質和可維護性。透過同時使用純函數、不變性、柯里化、記憶化和 monad,開發人員可以建立更可靠、更有效率、更乾淨的應用程式。 透過採用這些相互關聯的原則,JavaScript 開發人員可以充分利用函數式程式設計的潛力來編寫更好、更永續的程式碼。 --- 原文出處:https://dev.to/alexmercedcoder/deep-dive-into-functional-programming-in-javascript-851

🚀 21 個將你的開發技能帶上月球的工具 🌝

我見過數百種人工智慧工具,其中許多正在改變世界。 作為開發人員,總是有很多事情需要學習,因此專注於節省時間來處理重要的事情非常重要。 我將介紹 21 個供開發人員使用的工具,它們可以讓您的生活更輕鬆,特別是在開發人員體驗方面。 相信我,這份清單會讓你大吃一驚! 我們開始做吧。 --- 1. [Taipy](https://github.com/Avaiga/taipy) - 將資料和人工智慧演算法整合到生產就緒的 Web 應用程式中。 ---------------------------------------------------------------------------- ![打字](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wd10iiofzmt4or4db6ej.png) Taipy 是一個開源 Python 庫,可用於輕鬆的端到端應用程式開發,具有假設分析、智慧管道執行、內建調度和部署工具。 我相信你們大多數人都不明白 Taipy 用於為基於 Python 的應用程式建立 GUI 介面並改進資料流管理。 關鍵是性能,而 Taipy 是最佳選擇。 雖然 Streamlit 是一種流行的工具,但在處理大型資料集時,其效能可能會顯著下降,這使得它在生產級使用上不切實際。 另一方面,Taipy 在不犧牲性能的情況下提供了簡單性和易用性。透過嘗試 Taipy,您將親身體驗其用戶友好的介面和高效的資料處理。 ![大資料支持](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xnvk0tozn0lgj083rzcb.gif) Taipy 有許多整合選項,可以輕鬆地與領先的資料平台連接。 ![整合](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7yv31uir3erina587zp8.png) 開始使用以下命令。 ``` pip install taipy ``` 我們來談談最新的[Taipy v3.1 版本](https://docs.taipy.io/en/latest/relnotes/)。 最新版本使得在 Taipy 的多功能零件物件中可視化任何 HTML 或 Python 物件成為可能。 這意味著[Folium](https://python-visualization.github.io/folium/latest/) 、 [Bokeh](https://bokeh.org/) 、 [Vega-Altair](https://altair-viz.github.io/)和[Matplotlib](https://matplotlib.org/)等程式庫現在可用於視覺化。 這也帶來了對[Plotly python](https://plotly.com/python/)的原生支持,使繪製圖表變得更加容易。 他們還使用分散式運算提高了效能,但最好的部分是 Taipy,它的所有依賴項現在都與 Python 3.12 完全相容,因此您可以在使用 Taipy 進行專案的同時使用最新的工具和程式庫。 您可以閱讀[文件](https://docs.taipy.io/en/latest/)。 ![用例](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xdvnbejf9aivxmqsd3hx.png) 另一個有用的事情是,Taipy 團隊提供了一個名為[Taipy Studio](https://docs.taipy.io/en/latest/manuals/studio/)的 VSCode 擴充功能來加速 Taipy 應用程式的建置。 ![太皮工作室](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kc1umm5hcxes0ydbuspb.png) 您也可以使用 Taipy 雲端部署應用程式。 如果您想閱讀部落格來了解程式碼庫結構,您可以閱讀 HuggingFace[的使用 Taipy 在 Python 中為您的 LLM 建立 Web 介面](https://huggingface.co/blog/Alex1337/create-a-web-interface-for-your-llm-in-python)。 嘗試新技術通常很困難,但 Taipy 提供了[10 多個演示教程,](https://docs.taipy.io/en/release-3.1/gallery/)其中包含程式碼和適當的文件供您遵循。 ![示範](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4wigid2aokt6spkkoivr.png) 例如,一些演示範例和專案想法: - [即時污染儀表板](https://docs.taipy.io/en/release-3.0/knowledge_base/demos/pollution_sensors/) 使用工廠周圍的感測器測量空氣品質的用例,展示 Taipy 儀表板流資料的能力。檢查[GitHub 儲存庫](https://github.com/Avaiga/demo-realtime-pollution)。 - [詐欺辨識](https://docs.taipy.io/en/release-3.0/knowledge_base/demos/fraud_detection/) Taipy 應用程式可分析信用卡交易以偵測詐欺行為。檢查[GitHub 儲存庫](https://github.com/Avaiga/demo-fraud-detection)。 - [新冠儀表板](https://docs.taipy.io/en/release-3.0/knowledge_base/demos/covid_dashboard/) 這使用 2020 年的 Covid 資料集。還有一個預測頁面來預測傷亡人數。檢查[GitHub 儲存庫](https://github.com/Avaiga/demo-covid-dashboard)。 - [建立 LLM 聊天機器人](https://docs.taipy.io/en/release-3.0/knowledge_base/demos/chatbot/) 該演示展示了 Taipy 使最終用戶能夠使用 LLM 執行推理的能力。在這裡,我們使用 GPT-3 建立一個聊天機器人,並將對話顯示在互動式聊天介面中。您可以輕鬆更改程式碼以使用任何其他 API 或模型。檢查[GitHub 儲存庫](https://github.com/Avaiga/demo-chatbot)。 - [即時人臉辨識](https://docs.taipy.io/en/release-3.0/knowledge_base/demos/face_recognition/) 該演示將人臉辨識無縫整合到我們的平台中,使用網路攝影機提供使用者友好的即時人臉偵測體驗。檢查[GitHub 儲存庫](https://github.com/Avaiga/demo-face-recognition)。 這些用例非常驚人,所以一定要檢查一下。 Taipy 在 GitHub 上有 8.2k+ Stars,並且處於`v3.1`版本,因此它們正在不斷改進。 {% cta https://github.com/Avaiga/taipy %} Star Taipy ⭐️ {% endcta %} --- 2. [DevToys](https://github.com/DevToys-app/DevToys) - 開發者的瑞士軍刀。 ---------------------------------------------------------------- ![開發玩具](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7zfl1wjr01fdvca6wxbi.png) DevToys 協助完成日常開發任務,例如格式化 JSON、比較文字和測試 RegExp。 這樣,就無需使用不可信的網站來處理您的資料執行簡單的任務。透過智慧型偵測,DevToys 可以偵測用於複製到 Windows 剪貼簿的資料的最佳工具。 緊湊的覆蓋範圍讓您可以保持應用程式較小並位於其他視窗之上。最好的部分是可以同時使用應用程式的多個實例。 我可以肯定地說,開發人員甚至不知道這個很棒的專案。 最後是一款專為 Windows 生態系統設計的軟體。哈哈! ![工具](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i7wd60jsgdb5tx2t2adi.png) 他們提供的一些工具是: > 轉換器 - JSON &lt;&gt; YAML - 時間戳 - 數基數 - 規劃任務解析器 ![轉換器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g8x784fx53x6ia02zal0.png) > 編碼器/解碼器 - 超文本標記語言 - 網址 - Base64 文字與圖片 - 壓縮包 - 智威湯遜解碼器 ![編碼器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/73ts4x1vtcy4yswsmytw.png) > 格式化程式 - JSON - SQL - XML ![XML](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e5dc8ko2baywta82ymq5.png) > 發電機 - 哈希(MD5、SHA1、SHA256、SHA512) - UUID 1 和 4 - 洛雷姆·伊普蘇姆 - 校驗和 ![發電機](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cwsq8xig6jf69wr99iuv.png) > 文字 - 逃脫/逃脫 - 檢驗員和箱子轉換器 - 正規表示式測試器 - 文字比較 - XML驗證器 - 降價預覽 ![MD預覽](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vcbkse1i5324qg3xu1yd.png) ![文字差異](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hlqqib4fcjimc03pdrwr.png) > 形象的 - 色盲模擬器 - 顏色選擇器和對比度 - PNG / JPEG 壓縮器 - 影像轉換器 ![圖形工具](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/631upekcqzh62xyrdjwt.png) 我不了解你,但我不會錯過這個! 您可以閱讀[如何執行 DevToys](https://github.com/DevToys-app/DevToys?tab=readme-ov-file#how-to-run-devtoys) 。 關於許可證的註解。 DevToys 使用的授權允許將應用程式作為試用軟體或共享軟體重新分發而無需進行任何更改。然而,作者 Etienne BAUDOUX 和 BenjaminT 不希望你這樣做。如果您認為自己有充分的理由這樣做,請先與我們聯絡討論。 他們在 GitHub 上有 23k Stars,並且使用 C#。 {% cta https://github.com/DevToys-app/DevToys %} 明星 DevToys ⭐️ {% endcta %} --- 3. [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) 。 就開源流行度而言,他們仍然是新的,但他們的社群是迄今為止我見過的最好的社群之一。加入他們,成為 Pieces 的一部分! {% cta https://github.com/pieces-app/ %} 星星碎片 ⭐️ {% endcta %} --- 4. [Infisical-](https://github.com/Infisical/infisical)秘密管理平台。 -------------------------------------------------------------- ![內部的](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jrolzjdnkky1r694h9av.png) Infisical 是一個開源秘密管理平台,團隊可以用它來集中 API 金鑰、資料庫憑證和設定等秘密。 他們讓每個人(而不僅僅是安全團隊)都可以更輕鬆地進行秘密管理,這意味著從頭開始重新設計整個開發人員體驗。 就我個人而言,我不介意使用 .env 文件,因為我並不特別謹慎。不過,您可以閱讀[立即停止使用 .env 檔案!](https://dev.to/gregorygaines/stop-using-env-files-now-kp0)由格雷戈里來理解。 他們提供了四種 SDK,分別用於<a href="">Node.js</a> 、 <a href="">Python</a> 、 <a href="">Java</a>和<a href="">.Net</a> 。您可以自行託管或使用他們的雲端。 開始使用以下 npm 指令。 ``` npm install @infisical/sdk ``` 這是使用入門 (Node.js SDK) 的方法。 ``` import { InfisicalClient, LogLevel } from "@infisical/sdk"; const client = new InfisicalClient({ clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", logLevel: LogLevel.Error }); const secrets = await client.listSecrets({ environment: "dev", projectId: "PROJECT_ID", path: "/foo/bar/", includeImports: false }); ``` ![內部](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h3eu288l470du91b66pd.png) Infisical 還提供了一組工具來自動防止 git 歷史記錄的秘密洩露。可以使用預提交掛鉤或透過與 GitHub 等平台直接整合在 Infisical CLI 層級上設定此功能。 您可以閱讀[文件](https://infisical.com/docs/documentation/getting-started/introduction)並檢查如何[安裝 CLI](https://infisical.com/docs/cli/overview) ,這是使用它的最佳方式。 Infisical 還可用於將機密注入 Kubernetes 叢集和自動部署,以便應用程式使用最新的機密。有很多整合選項可用。 ![內部](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5x0tvt5ycaiqhggv6wml.png) 在使用整個原始程式碼之前一定要檢查他們的[許可證](https://github.com/Infisical/infisical/blob/main/LICENSE),因為他們有一些受 MIT Expat 保護的企業級程式碼,但不用擔心,大部分程式碼都是免費使用的。 他們在 GitHub 上擁有超過 11k 顆星星,並且發布了超過 125 個版本,因此他們正在不斷發展。另外,Infiscial CLI 的安裝次數超過 540 萬次,因此非常值得信賴。 {% cta https://github.com/Infisical/infisical %} 明星 Infisical ⭐️ {% endcta %} --- 5. [Mintlify](https://github.com/mintlify/writer) - 在建置時出現的文件。 -------------------------------------------------------------- ![精簡](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gvk07kmn8p48cpssogov.png) Mintlify 是一款由人工智慧驅動的文件編寫器,您只需 1 秒鐘即可編寫程式碼文件 :D 幾個月前我發現了 Mintlify,從那時起我就一直是它的粉絲。我見過很多公司使用它,甚至我使用我的商務電子郵件產生了完整的文件,結果證明這是非常簡單和體面的。如果您需要詳細的文件,Mintlify 就是解決方案。 主要用例是根據我們將在此處討論的程式碼產生文件。當您編寫程式碼時,它會自動記錄程式碼,以便其他人更容易跟上。 您可以安裝[VSCode 擴充功能](https://marketplace.visualstudio.com/items?itemName=mintlify.document)或將其安裝在[IntelliJ](https://plugins.jetbrains.com/plugin/18606-mintlify-doc-writer)上。 您只需突出顯示程式碼或將遊標放在要記錄的行上。然後點選「編寫文件」按鈕(或按 ⌘ + 。) 您可以閱讀[文件](https://github.com/mintlify/writer?tab=readme-ov-file#%EF%B8%8F-mintlify-writer)和[安全指南](https://writer.mintlify.com/security)。 如果您更喜歡教程,那麼您可以觀看[Mintlify 的工作原理](https://www.loom.com/embed/3dbfcd7e0e1b47519d957746e05bf0f4)。它支援 10 多種程式語言,並支援許多文件字串格式,例如 JSDoc、reST、NumPy 等。 順便說一句,他們的網站連結是[writer.mintlify.com](https://writer.mintlify.com/) ;回購協議中目前的似乎是錯誤的。 Mintlify 是一個方便的工具,用於記錄程式碼,這是每個開發人員都應該做的事情。它使其他人更容易有效地理解您的程式碼。 它在 GitHub 上有大約 2.5k 顆星,基於 TypeScript 建置,受到許多開發人員的喜愛。 {% cta https://github.com/mintlify/writer %} Star Mintlify ⭐️ {% endcta %} --- 6. [Replexica](https://github.com/replexica/replexica) - 用於 React 的 AI 支援的 i18n 工具包。 ------------------------------------------------------------------------------------ ![反射](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/htgshukxy927iy37ui33.png) 在地化方面的困難是真實存在的,因此人工智慧的幫助絕對是一個很酷的概念。 Replexica 是 React 的 i18n 工具包,可快速發布多語言應用程式。它不需要將文字提取到 JSON 檔案中,並使用 AI 支援的 API 進行內容處理。 它有以下兩個部分: 1. Replexica Compiler - React 的開源編譯器插件。 2. Replexica API - 雲端中的 i18n API,使用 LLM 執行翻譯。 (基於使用情況,它有免費套餐) 支援的一些 i18n 格式包括: 1. 無 JSON 的 Replexica 編譯器格式。 2. Markdown 內容的 .md 檔案。 3. 基於舊版 JSON 和 YAML 的格式。 當他們達到 500 星時,他們也在 DEV 上發布了官方公告。我是第一批讀者之一(少於 3 個反應)。 它們涵蓋了很多內容,因此您應該閱讀 Max 的[《We Got 500 Stars What Next》](https://dev.to/maxprilutskiy/we-got-500-github-stars-whats-next-2njc) 。 為了給出 Replexica 背後的總體思路,這是基本 Next.js 應用程式所需的唯一更改,以使其支援多語言。 開始使用以下 npm 指令。 ``` // install pnpm add replexica @replexica/react @replexica/compiler // login to Replexica API. pnpm replexica auth --login ``` 您可以這樣使用它。 ``` // next.config.mjs // Import Replexica Compiler import replexica from '@replexica/compiler'; /** @type {import('next').NextConfig} */ const nextConfig = {}; // Define Replexica configuration /** @type {import('@replexica/compiler').ReplexicaConfig} */ const replexicaConfig = { locale: { source: 'en', targets: ['es'], }, }; // Wrap Next.js config with Replexica Compiler export default replexica.next( replexicaConfig, nextConfig, ); ``` 您可以閱讀如何[開始使用](https://github.com/replexica/replexica/blob/main/getting-started.md)以及清楚記錄的有關[幕後使用內容的](https://github.com/replexica/replexica?tab=readme-ov-file#whats-under-the-hood)內容。 Replexica 編譯器支援 Next.js App Router,Replexica API 支援英文🇺🇸和西班牙文🇪🇸。他們計劃接下來發布 Next.js Pages Router + 法語🇫🇷語言支援! 他們在 GitHub 上擁有 740 多個 Star,並且基於 TypeScript 建置。您應該密切關注該專案以獲得進一步進展! {% cta https://github.com/replexica/replexica %} Star Replexica ⭐️ {% endcta %} --- 7. [Flowise](https://github.com/FlowiseAI/Flowise) - 拖放 UI 來建立您的客製化 LLM 流程。 --------------------------------------------------------------------------- ![弗洛伊薩伊](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r5bp43nil764fhe4a05z.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://dev-to-uploads.s3.amazonaws.com/uploads/articles/ahk2ovjrpq1qk3r5pfot.png) 您可以閱讀[文件](https://docs.flowiseai.com/)。 ![流程化人工智慧](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/trkltpn5lk1y1pte0smd.png) 雲端主機不可用,因此您必須使用這些[說明](https://github.com/FlowiseAI/Flowise?tab=readme-ov-file#-self-host)自行託管。 讓我們探討一些用例: - 假設您有一個網站(可以是商店、電子商務網站或部落格),並且您希望廢棄該網站的所有相關連結,並讓法學碩士回答您網站上的任何問題。您可以按照此[逐步教學](https://docs.flowiseai.com/use-cases/web-scrape-qna)來了解如何實現相同的目標。 ![刮刀](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e91sz2mga5wvc0x2hp2g.png) - 您還可以建立一個自訂工具,該工具將能夠呼叫 Webhook 端點並將必要的參數傳遞到 Webhook 主體中。請依照本[指南](https://docs.flowiseai.com/use-cases/webhook-tool)使用 Make.com 建立 Webhook 工作流程。 ![網路鉤子](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ckyivo9dvue461jc9pv4.png) 還有許多其他用例,例如建立 SQL QnA 或與 API 互動。 FlowiseAI 在 GitHub 上擁有超過 27,500 個 Star,並擁有超過 10,000 個分叉,因此具有良好的整體比率。 {% cta https://github.com/FlowiseAI/Flowise %} 明星 Flowise ⭐️ {% endcta %} --- 8. [Hexo](https://github.com/hexojs/hexo) - 一個快速、簡單且功能強大的部落格框架。 --------------------------------------------------------------- ![六角形](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6vos07fyydiupqqplo2s.png) 大多數開發人員更喜歡自己的博客,如果您也是如此。 Hexo 可能是你不知道的工具。 Hexo 支援許多功能,例如超快的生成速度,支援 GitHub Flavored Markdown 和大多數 Octopress 插件,提供對 GitHub Pages、Heroku 等的一命令部署,以及可實現無限擴展性的強大 API 和數百個主題和插件。 這意味著您可以用 Markdown(或其他標記語言)編寫帖子,Hexo 在幾秒鐘內生成具有漂亮主題的靜態檔案。 開始使用以下 npm 指令。 ``` npm install hexo-cli -g ``` 您可以這樣使用它。 ``` // Setup your blog hexo init blog // Start the server hexo server // Create a new post hexo new "Hello Hexo" ``` 您可以閱讀[文件](https://hexo.io/docs/),查看 Hexo 提供的所有[400 多個外掛程式](https://hexo.io/plugins/)和[主題集](https://hexo.io/themes/)。據我所知,這些外掛程式支援廣泛的用例,例如 Hexo 的 Ansible 部署器外掛程式。 您可以查看有關在[Hexo 上編寫和組織內容的](https://www.youtube.com/watch?v=AIqBubK6ZLc&t=6s)YouTube 教學。 Hexo 在 GitHub 上擁有超過 38,000 顆星,並被 GitHub 上超過 125,000 名開發者使用。它們位於`v7`版本中,解壓縮後大小為`629 kB` 。 {% cta https://github.com/hexojs/hexo %} Star Hexo ⭐️ {% endcta %} --- 9.[螢幕截圖到程式碼](https://github.com/abi/screenshot-to-code)- 放入螢幕截圖並將其轉換為乾淨的程式碼。 --------------------------------------------------------------------------- ![截圖到程式碼](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5akiyz5telxqqsj32ftu.png) 這個開源專案廣泛流行,但許多開發人員仍然不了解它。它可以幫助您以 10 倍的速度建立使用者介面。 這是一個簡單的工具,可以使用 AI 將螢幕截圖、模型和 Figma 設計轉換為乾淨、實用的程式碼。 該應用程式有一個 React/Vite 前端和一個 FastAPI 後端。如果您想使用 Claude Sonnet 或獲得實驗視訊支持,您將需要一個能夠存取 GPT-4 Vision API 的 OpenAI API 金鑰或一個 Anthropic 金鑰。您可以閱讀[指南](https://github.com/abi/screenshot-to-code?tab=readme-ov-file#-getting-started)來開始。 您可以在託管版本上[即時試用](https://screenshottocode.com/),並觀看 wiki 上提供的[一系列演示影片](https://github.com/abi/screenshot-to-code/wiki/Screen-Recording-to-Code)。 他們在 GitHub 上擁有超過 47k 顆星星,並支援許多技術堆疊,例如 React 和 Vue,以及不錯的 AI 模型,例如 GPT-4 Vision、Claude 3 Sonnet 和 DALL-E 3。 {% cta https://github.com/abi/screenshot-to-code %} 將螢幕截圖轉為程式碼 ⭐️ {% endcta %} --- 10. [Appsmith](https://github.com/appsmithorg/appsmith) - 建立管理面板、內部工具和儀表板的平台。 ----------------------------------------------------------------------------- ![應用史密斯](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rt7s0r3wz2leec83cl17.png) 管理面板和儀表板是任何軟體創意(在大多數情況下)的一些常見部分,我嘗試從頭開始建立它,這會帶來很多痛苦和不必要的辛苦工作。 您可能已經看到組織建立了內部應用程式,例如儀表板、資料庫 GUI、管理面板、批准應用程式、客戶支援儀表板等,以幫助其團隊執行日常操作。正如我所說,Appsmith 是一個開源工具,可以實現這些內部應用程式的快速開發。 首先,請觀看這個[YouTube 影片](https://www.youtube.com/watch?v=NnaJdA1A11s),該影片在 100 秒內解釋了 Appsmith。 {% 嵌入 https://www.youtube.com/watch?v=NnaJdA1A11s %} 他們提供拖放小部件來建立 UI。 您可以使用 45 多個可自訂的小工具在幾分鐘內建立漂亮的響應式 UI,而無需編寫一行 HTML/CSS。尋找[小部件的完整清單](https://www.appsmith.com/widgets)。 ![按鈕點擊小工具](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kqpnnslvsvjl4gifseon.png) ![驗證](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/489fly7tvknz2uv2mgei.png) Appsmith 幾乎可以在 GUI 上的小部件屬性、事件偵聽器、查詢和其他設定內的任何位置編寫 JavaScript 程式碼。 Appsmith 支援在`{{ }}`內編寫單行程式碼,並將括號之間編寫的任何內容解釋為 JavaScript 表達式。 ``` /*Filter the data array received from a query*/ {{ QueryName.data.filter((row) => row.id > 5 ) }} or {{ storeValue("userID", 42); console.log(appsmith.store.userID); showAlert("userID saved"); }} ``` 您需要使用立即呼叫函數表達式(IIFE)來編寫多行。 例如,無效程式碼和有效程式碼。 ``` // invalid code /*Call a query to fetch the results and filter the data*/ {{ const array = QueryName.data; const filterArray = array.filter((row) => row.id > 5); return filterArray; }} /* Check the selected option and return the value*/ {{ if (Dropdown.selectedOptionValue === "1") { return "Option 1"; } else { return "Option 2"; } }} // valid code /* Call a query and then manipulate its result */ {{ (function() { const array = QueryName.data; const filterArray = array.filter((row) => row.id > 5); return filterArray; })() }} /* Verify the selected option and return the value*/ {{ (function() { if (Dropdown.selectedOptionValue === "1") { return "Option 1"; } else { return "Option 2"; } })() }} ``` 您可以透過幾個簡單的步驟建立從簡單的 CRUD 應用程式到複雜的多步驟工作流程的任何內容: 1. 與資料庫或 API 整合。 Appsmith 支援最受歡迎的資料庫和 REST API。 2. 使用內建小工具建立您的應用程式佈局。 3. 在編輯器中的任何位置使用查詢和 JavaScript 來表達您的業務邏輯。 4. Appsmith 支援使用 Git 進行版本控制,以使用分支來協作建立應用程式來追蹤和回滾變更。部署應用程式並分享:) ![應用史密斯](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yltcrmuzwdoydrwyqjpp.png) 您可以閱讀[文件](https://docs.appsmith.com/)和[操作指南](https://docs.appsmith.com/connect-data/how-to-guides),例如如何將其連接到本機資料來源或\[如何與第三方工具整合\](與第三方工具整合)。 您可以自行託管或使用雲端。他們還提供[20 多個模板](https://www.appsmith.com/templates),以便您可以快速入門。一些有用的是: - [維修訂單管理](https://www.appsmith.com/template/Maintenance-Order-Management) - [加密即時追蹤器](https://www.appsmith.com/template/crypto-live-tracker) - [內容管理系統](https://www.appsmith.com/template/content-management-system) - [WhatsApp 信使](https://www.appsmith.com/template/whatsapp-messenger) Appsmith 在 GitHub 上擁有超過 31,000 顆星,發布了 200 多個版本。 {% cta https://github.com/appsmithorg/appsmith %} Star Appsmith ⭐️ {% endcta %} --- 11. [BlockNote](https://github.com/TypeCellOS/BlockNote) - 基於區塊(Notion 樣式)且可擴充的富文本編輯器。 -------------------------------------------------------------------------------------- ![區塊註釋](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eddx8cld0g492w3a8fjh.png) 人們常說,除非您正在學習新東西,否則不要重新發明輪子。 Blocknote 是開源的 Block 為基礎的 React 富文本編輯器。您可以輕鬆地將現代文字編輯體驗加入到您的應用程式中。 Blocknote 建構在 Prosemirror 和 Tiptap 之上。 它們有很多功能,如下所示。 ![特徵](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h9kd6xnkg9fa5j29frot.png) ![特徵](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ezuz7ywh6vefixmpeyzk.png) 您可以輕鬆自訂內建 UI 元件,或建立自訂區塊、內聯內容和樣式。如果您想更進一步,您可以使用額外的 Prosemirror 或 TipTap 外掛程式來擴充核心編輯器。 其他庫雖然功能強大,但通常具有相當陡峭的學習曲線,並且要求您自訂編輯器的每個細節。這可能需要數月的專門工作。 相反,BlockNote 只需最少的設定即可提供出色的體驗,包括現成的動畫 UI。 開始使用以下 npm 指令。 ``` npm install @blocknote/core @blocknote/react ``` 您可以這樣使用它。透過`useCreateBlockNote`鉤子,我們可以建立一個新的編輯器實例,然後使用`theBlockNoteView`元件來渲染它。 `@blocknote/react/style.css`也被匯入來新增編輯器的預設樣式和 BlockNote 匯出的 Inter 字體(可選)。 ``` import "@blocknote/core/fonts/inter.css"; import { BlockNoteView, useCreateBlockNote } from "@blocknote/react"; import "@blocknote/react/style.css"; export default function App() { // Creates a new editor instance. const editor = useCreateBlockNote(); // Renders the editor instance using a React component. return <BlockNoteView editor={editor} />; } ``` 您可以閱讀可用的[文件](https://www.blocknotejs.org/docs)和[ui 元件](https://www.blocknotejs.org/docs/ui-components)。 您應該嘗試一下,特別是因為它包含廣泛的功能,例如「斜線」選單、流暢的動畫以及建立即時協作應用程式的潛力。 ![削減](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0i7ob8nrhpl7r70k6527.png) 斜線選單 ![即時協作](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/id22qol6y0838zgwad3y.png) 即時協作 ![格式](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d8maems8tfhtehw9lkol.png) 格式選單 他們還提供了[20 多個範例](https://www.blocknotejs.org/examples)以及預覽和程式碼,您可以使用它們來快速跟進。 ![例子](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4uillknk0ogkcvpula7b.png) Blocknote 在 GitHub 上擁有超過 5,000 顆星,並有超過 1,500 名開發者在使用。 {% cta https://github.com/TypeCellOS/BlockNote %} 星 BlockNote ⭐️ {% endcta %} --- 12. [CopilotKit](https://github.com/CopilotKit/CopilotKit) - 在數小時內為您的產品提供 AI Copilot。 ------------------------------------------------------------------------------------- ![副駕駛套件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nzuxjfog2ldam3csrl62.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 多個版本,這意味著它們正在不斷改進。 {% cta https://github.com/CopilotKit/CopilotKit %} Star CopilotKit ⭐️ {% endcta %} --- 13.[自動完成](https://github.com/withfig/autocomplete)- IDE 風格的自動完成功能適用於您現有的終端和 shell。 ---------------------------------------------------------------------------------- ![自動完成](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8i8vcidsa023jf8r9382.png) [Fig](https://fig.io/?ref=github_autocomplete)讓命令列對個人來說更容易,對團隊來說更具協作性。 他們最受歡迎的產品是自動完成。當您鍵入時,Fig 會在現有終端機中彈出子命令、選項和上下文相關的參數。 最好的部分是您也可以將 Fig 的自動完成功能用於您自己的工具。以下是建立私人完成的方法: ``` import { ai } from "@fig/autocomplete-generators" ... generators: [ ai({ // the prompt prompt: "Generate a git commit message", // Send any relevant local context. message: async ({ executeShellCommand }) => { return executeShellCommand("git diff") }, //Turn each newline into a suggestion (can specify instead a `postProcess1 function if more flexibility is required) splitOn: "\n", }) ] ``` 您可以閱讀[Fig.io/docs](https://fig.io/docs/getting-started)了解如何開始。 他們在 GitHub 上有 24k+ Stars,這對於經常使用 shell 或終端機的開發人員來說非常有用。 {% cta https://github.com/withfig/autocomplete %} 星狀自動完成 ⭐️ {% endcta %} --- 14. [Tooljet](https://github.com/ToolJet/ToolJet) - 用於建立業務應用程式的低程式碼平台。 ---------------------------------------------------------------------- ![工具噴射器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xhipvjl2wnthjccgrpij.png) 我們都建立前端,但它通常非常複雜並且涉及很多因素。這樣可以省去很多麻煩。 ToolJet 是一個開源低程式碼框架,可以用最少的工程工作來建置和部署內部工具。 ToolJet 的拖放式前端建構器可讓您在幾分鐘內建立複雜的響應式前端。 您可以整合各種資料來源,包括PostgreSQL、MongoDB、Elasticsearch等資料庫;具有 OpenAPI 規範和 OAuth2 支援的 API 端點; SaaS 工具,例如 Stripe、Slack、Google Sheets、Airtable 和 Notion;以及 S3、GCS 和 Minio 等物件儲存服務來取得和寫入資料。一切 :) 這就是 Tooljet 的工作原理。 ![工具噴射器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r6vv09z7ioma1ce2ttei.png) 您可以在 ToolJet 中開發多步驟工作流程以自動化業務流程。除了建置和自動化工作流程之外,ToolJet 還可以在您的應用程式中輕鬆整合這些工作流程。 ![工作流程](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eh2vk3kih9fhck6okf67.png) 您可以閱讀此[快速入門指南](https://docs.tooljet.com/docs/getting-started/quickstart-guide),該指南向您展示如何使用 ToolJet 在幾分鐘內建立員工目錄應用程式。該應用程式將讓您透過漂亮的用戶介面追蹤和更新員工資訊。 查看可用[功能列表](https://github.com/ToolJet/ToolJet?tab=readme-ov-file#all-features),包括 45 多個內建響應式元件、50 多個資料來源等等。 您可以閱讀[文件](https://docs.tooljet.com/docs/)並查看[操作指南](https://docs.tooljet.com/docs/how-to/use-url-params-on-load)。 它們在 GitHub 上有 26k+ Stars,並且基於 JavaScript 建置。他們也獲得了 GitHub 的資助,從而建立了巨大的信任。 {% cta https://github.com/ToolJet/ToolJet %} Star ToolJet ⭐️ {% endcta %} --- 15. [Apitable](https://github.com/apitable/apitable) - 用於建立協作應用程式的 API 導向的低程式碼平台。 --------------------------------------------------------------------------------- ![有能力的](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/58syhvpb2fn6hhlyrtst.png) APITable 是一個面向 API 的低程式碼平台,用於建立協作應用程式,並表示它比所有其他 Airtable 開源替代品都要好。 有很多很酷的功能,例如: - 即時協作。 ![即時協作](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/58kpvpab2nj92421yvy3.gif) - 您可以產生自動表單。 ![形式](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0jo084gg0cd9xiud3nz3.gif) - 無限的跨錶連結。 ![交叉表](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jnvb9sdp3uqrcn55hwug.gif) - API 第一個面板。 ![API第一個面板](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7u48ue4rl0q41rhh6bif.gif) - 強大的行/列功能。 ![行列](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/apxqwp84awdbj7cdw5yu.gif) 您可以閱讀完整的[功能清單](https://github.com/apitable/apitable?tab=readme-ov-file#-features)。 您可以嘗試[apitable](https://aitable.ai/)並在 apitable 的[live Gitpod demo](https://gitpod.io/#https://github.com/apitable/apitable)中查看該專案的演示。 您也可以閱讀[安裝指南](https://github.com/apitable/apitable?tab=readme-ov-file#installation),在本機或雲端運算環境中安裝 APITable。 {% cta https://github.com/apitable/apitable %} Star Apitable ⭐️ {% endcta %} --- 16. [n8n](https://github.com/n8n-io/n8n) - 工作流程自動化工具。 ----------------------------------------------------- ![n8n](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4pqsc84nhgj0b9dhfaxo.png) n8n 是一個可擴展的工作流程自動化工具。透過公平程式碼分發模型,n8n 將始終擁有可見的原始程式碼,可用於自託管,並允許您加入自訂函數、邏輯和應用程式。 每個開發人員都想使用的工具。自動化是生產力和簡單性的關鍵。 ![n8n](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rxnp57kw5szbpj6mfs1p.png) n8n 基於節點的方法使其具有高度通用性,使您能夠將任何事物連接到任何事物。 有[400 多個集成選項](https://n8n.io/integrations),這幾乎是瘋狂的! 您可以看到所有[安裝](https://docs.n8n.io/choose-n8n/)選項,包括 Docker、npm 和自架。 開始使用以下命令。 ``` npx n8n ``` 此命令將下載啟動 n8n 所需的所有內容。然後,您可以透過開啟`http://localhost:5678`來存取 n8n 並開始建置工作流程。 在 YouTube 上觀看此[快速入門影片](https://www.youtube.com/watch?v=1MwSoB0gnM4)! {% 嵌入 https://www.youtube.com/watch?v=1MwSoB0gnM4 %} 您可以閱讀[文件](https://docs.n8n.io/)並閱讀本[指南](https://docs.n8n.io/try-it-out/),以便根據您的需求快速開始。 他們還提供初學者和中級[課程,](https://docs.n8n.io/courses/)以便輕鬆學習。 他們在 GitHub 上有 39k+ Stars,並提供兩個包供整體使用。 {% cta https://github.com/n8n-io/n8n %} 明星 n8n ⭐️ {% endcta %} --- 17. [DOMPurify](https://github.com/cure53/DOMPurify) - 一個僅限 DOM、超快、超級容忍 XSS 的 HTML 清理程式。 ---------------------------------------------------------------------------------------- ![DOM純化](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r846r2hmmw9d9wzvbocz.png) DOMPurify 是一款僅限 DOM、超快、超級容忍 XSS 的 HTML、MathML 和 SVG 清理工具。作為開發人員,我們的應用程式需要它來確保它們足夠安全。 DOMPurify 可以淨化 HTML 並防止 XSS 攻擊。 您可以向 DOMPurify 提供一個充滿髒 HTML 的字串,它將傳回一個包含乾淨 HTML 的字串(除非另有配置)。 DOMPurify 將刪除所有包含危險 HTML 的內容,從而防止 XSS 攻擊和其他惡意行為。這也太快了。 他們使用瀏覽器提供的技術並將其轉變為 XSS 過濾器。您的瀏覽器速度越快,DOMPurify 的速度就越快。 DOMPurify 使用 JavaScript 編寫,適用於所有現代瀏覽器(Safari (10+)、Opera (15+)、Edge、Firefox 和 Chrome - 以及幾乎所有使用 Blink、Gecko 或 WebKit 的其他瀏覽器)。它不會在 MSIE 或其他舊版瀏覽器上中斷。它根本什麼都不做。 開始使用以下 npm 指令。 ``` npm install dompurify npm install jsdom // or use the unminified development version <script type="text/javascript" src="src/purify.js"></script> ``` 您可以這樣使用它。 ``` const createDOMPurify = require('dompurify'); const { JSDOM } = require('jsdom'); const window = new JSDOM('').window; const DOMPurify = createDOMPurify(window); const clean = DOMPurify.sanitize('<b>hello there</b>'); ``` 如果您遇到問題,請參閱[文件](https://github.com/cure53/DOMPurify?tab=readme-ov-file#how-do-i-use-it)。他們已經記錄了使用腳本或在伺服器端執行它。 您可以看到一些 [純化樣品](https://github.com/cure53/DOMPurify?tab=readme-ov-file#some-purification-samples-please)並觀看[現場演示](https://cure53.de/purify)。 使用起來也非常簡單。 DOMPurify 於 2014 年 2 月啟動,同時版本已達 v3.1.0。 其中涉及到很多概念,我渴望探索它們。如果您有任何與此相關的令人興奮的事情,請告訴我。 我發現的另一個有用的替代方案是[validator.js](https://github.com/validatorjs/validator.js) 。 他們在 GitHub 上擁有超過 12,000 顆星,被超過 30 萬開發者使用,每週下載量超過 5,475,000 次,這使得他們非常可信。 {% cta https://github.com/cure53/DOMPurify %} 明星 DOMPurify ⭐️ {% endcta %} --- 18. [OpenDevin](https://github.com/OpenDevin/OpenDevin) - 更少的程式碼,更多的內容。 ----------------------------------------------------------------------- ![奧彭文](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4on63bb02g4x4ny8gtcn.png) ![奧彭文](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l0yepod2rye2jk5r12dt.png) 這是一個開源專案,旨在複製 Devin,一名自主人工智慧軟體工程師,能夠執行複雜的工程任務並在軟體開發專案上與用戶積極協作。該計畫致力於透過開源社群的力量複製、增強和創新 Devin。 只是想讓你知道,這是在德文被介紹之前。 您可以閱讀帶有要求的[安裝說明](https://github.com/OpenDevin/OpenDevin?tab=readme-ov-file#installation)。 他們使用 LiteLLM,因此您可以使用任何基礎模型來執行 OpenDevin,包括 OpenAI、Claude 和 Gemini。 如果您想為 OpenDevin 做出貢獻,您可以查看 [演示](https://github.com/OpenDevin/OpenDevin/blob/main/README.md#opendevin-code-less-make-more)和[貢獻指南](https://github.com/OpenDevin/OpenDevin/blob/main/CONTRIBUTING.md)。 它在 GitHub 上擁有超過 10,700 個 Star,並且正在快速成長。 {% cta https://github.com/OpenDevin/OpenDevin %} 明星 OpenDevin ⭐️ {% endcta %} --- 19. [Amplification-](https://github.com/amplication/amplication)後端開發平台。 ----------------------------------------------------------------------- ![放大](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w7yi3kvwrniredj4lp5r.png) 我想我們都同意,如果我們要達到標準,設定後端並從頭開始是很困難的。 我知道 Appwrite 和 Supabase 在功能方面要好得多,但每種情況都是獨特的,這可能會點擊而不是那些。 ![放大](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d5wud5sef1lpwzi8zdq2.png) Amplication 旨在徹底改變可擴展且安全的 Node.js 應用程式的建立。 他們消除了重複的編碼任務,並提供可立即投入生產的基礎設施程式碼,這些程式碼根據您的規範精心定制,並遵循行業最佳實踐。 其用戶友好的介面促進了 API、資料模型、資料庫、身份驗證和授權的無縫整合。 Amplication 建立在靈活的、基於插件的架構之上,允許輕鬆定製程式碼並提供大量整合選項。 ![特徵](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q3lc27fgvk8yearir13z.png) ![特徵](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4zgix42tplg9hwko3a7u.png) 您可以閱讀[文件](https://docs.amplication.com/)並查看可用的[社群插件](https://docs.amplication.com/plugins-list/)清單。 他們還提供了[逐步教程](https://docs.amplication.com/tutorials/#step-by-step-tutorials),以幫助您使用 Angular 或 React 建立應用程式。 Amplification 在 GitHub 上擁有超過 13k 顆星,發布了 170 多個版本,因此它們不斷發展。 {% cta https://github.com/amplication/amplication %} 星狀放大 ⭐️ {% endcta %} --- 20. [Embla 旋轉木馬](https://github.com/davidjerleke/embla-carousel)-。 ------------------------------------------------------------------ ![Embla 旋轉木馬](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aj2expoo15t6xhgcm3hi.png) 我們都在應用程式中使用輪播,有時會切換到網格佈局,因為輪播並不總是好看,但這會改變您對輪播的看法。 我之所以了解 Embla Carousel,是因為 Shadcn/ui 在他們的 UI 系統中使用了它。 Embla Carousel 是一個簡單的輪播庫,具有出色的流暢運動和出色的滑動精度。它與庫無關、無依賴性且 100% 開源。 如果您不確定,我建議您查看[基本的實例](https://www.embla-carousel.com/examples/predefined/)。 ![例子](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/paqu3ozlvhk5km5746pe.png) ![例子](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8qxfvmn83et836zon4ua.png) ![例子](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/abukp6j29gsaade7eci8.png) ![例子](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/locv2kqksvpl0ha8a9te.png) 我最喜歡的是視差,它可以提供非常酷且平滑的過渡。 它們支援 CDN、react、Vue、Svelte 和 Solid。 開始使用以下 npm 指令 (react)。 ``` npm install embla-carousel-react --save ``` 您可以這樣使用它。 Embla Carousel 提供了方便的 useEmblaCarousel 鉤子,用於與 React 無縫整合。最小的設定需要一個溢出包裝器和一個滾動容器。 `useEmblaCarousel`掛鉤將 Embla Carousel 選項作為第一個參數。您還需要使用 useEffect 存取 API ``` import React, { useEffect } from 'react' import useEmblaCarousel from 'embla-carousel-react' export function EmblaCarousel() { const [emblaRef, emblaApi] = useEmblaCarousel({ loop: false }) useEffect(() => { if (emblaApi) { console.log(emblaApi.slideNodes()) // Access API } }, [emblaApi]) return ( <div className="embla" ref={emblaRef}> <div className="embla__container"> <div className="embla__slide">Slide 1</div> <div className="embla__slide">Slide 2</div> <div className="embla__slide">Slide 3</div> </div> </div> ) } ``` 他們還提供了一組插件,您可以加入它們以實現自動播放等額外功能。 ``` npm install embla-carousel-autoplay --save ``` ``` import React, { useEffect } from 'react' import useEmblaCarousel from 'embla-carousel-react' import Autoplay from 'embla-carousel-autoplay' export function EmblaCarousel() { const [emblaRef] = useEmblaCarousel({ loop: false }, [Autoplay()]) return ( <div className="embla" ref={emblaRef}> <div className="embla__container"> <div className="embla__slide">Slide 1</div> <div className="embla__slide">Slide 2</div> <div className="embla__slide">Slide 3</div> </div> </div> ) } ``` 尋找[插件的完整列表](https://www.embla-carousel.com/plugins/),包括自動滾動和滾輪手勢。 您可以閱讀有關如何實現不同部分(例如斷點或上一個/下一個按鈕)的[文件](https://www.embla-carousel.com/get-started/)和[指南](https://www.embla-carousel.com/guides/)。 最讓我驚訝的部分是,您可以使用他們的[生成器](https://www.embla-carousel.com/examples/generator/)使用您自己的一組選項來產生自訂輪播。 ![發電機](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5wlq7l44bwl681644xf3.png) ![發電機](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2r1y3kr926h87clbqosw.png) 它們在 GitHub 上擁有 4.9K 顆星,並被超過 26000 名開發人員使用。如果我必須使用一個,我肯定會使用這個。 {% cta repo %} 明星名稱 ⭐️ {% endcta %} --- [21.Documenso](https://github.com/documenso/documenso) - 開源 DocuSign 替代方案。 -------------------------------------------------------------------------- ![文獻](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cttvudzx02wqsu04qt8v.gif) 如果您從事自由職業並需要簽署協議,這是最佳選擇。我們不應該浪費時間,而應該專注於重要的事情。 以數位方式簽署文件應該既快速又簡單,並且應該成為全球簽署的每個文件的最佳實踐。 如今,這在技術上相當簡單,但它也為每個簽名引入了一個新方:簽名工具提供者。 此專案的技術堆疊包括 TypeScript、Next.js、Prisma、Tailwind CSS、shadcn/ui、NextAuth.js、react-email、tRPC、@documenso/pdf-sign、React-PDF、PDF-Lib、Stripe 和韋爾塞爾。 ![特徵](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ziz58jqi2qtl6p6sx62w.png) ![特徵](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f8zrln5zlywkb6k10n09.png) 免費套餐可讓您每月簽署 10 份文件,這已經足夠了。 您可以閱讀本文以了解如何[設定專案](https://github.com/documenso/documenso?tab=readme-ov-file#developer-setup)。 您可以閱讀[文件](https://github.com/documenso/documenso?tab=readme-ov-file#developer-quickstart)。 我知道這不是一個非常廣泛的用例,但您仍然可以從程式碼中學習,因此這始終是一個優點。 他們在 GitHub 上擁有超過 5800 顆星,並且發布了`v1.5`版本。 不是很流行但非常有用。 {% cta https://github.com/documenso/documenso %} 明星 documenso ⭐️ {% endcta %} --- 哇! 這花了我很長很長的時間來寫。我希望你喜歡它。 我知道人工智慧工具有時太多了,但我們應該使用它們來讓我們的工作更輕鬆。我的意思是,這就是我們所做的正確的事情,讓生活變得更輕鬆。 我嘗試涵蓋廣泛的工具。 不管怎樣,請讓我們知道您的想法以及您計劃在您的工作流程中使用這些工具嗎? 祝你有美好的一天!直到下一次。 我建立了很多技術內容,因此如果您能在 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/) | |------------|----------| 關注 Taipy 以了解更多此類內容。 {% 嵌入 https://dev.to/taipy %} --- 原文出處:https://dev.to/taipy/21-tools-to-take-your-dev-skills-to-the-moon-53mf

使用 Wing 建立 React 應用程式

ReactJS 庫已經上市很久了,我們都非常了解它的強大功能。我們都知道如何使用 ReactJS 建立 UI、建立元件等等。如果您不了解 React,您可以使用大量線上免費資源。 在本部落格中,我們將研究 Wing 以及如何建立連接到 Wing 後端的 React 應用程式。 Wing 是世界上第一個在雲端服務上執行的雲端程式語言。 Wing 讓開發人員可以輕鬆建置和部署雲端應用程式。 Wing 使得在單一模型中編寫基礎設施程式碼 (terraform) 和應用程式程式碼成為可能。 Wing 附帶一個標準函式庫“cloud”,並有“Api”方法。 Api 方法表示客戶端可以透過 Internet 呼叫的 HTTP 端點的集合。此 Api 方法可用於建立一個 API,該 API 可以作為後端 API 來儲存和擷取資料。 您可以嘗試使用 Winglang 語言並了解它在[遊樂場功能](http://winglang.io/play)中的工作原理。 讓我們建立一個 React 應用程式,它將連接到使用 Wing 建立的 API。 安裝 -- 在您的裝置中安裝[Wing 工具鏈](https://www.winglang.io/)。確保您的裝置中有 Node.js 18.13.0 或更高版本。要安裝 Wing Toolchain,請在您的裝置中執行以下命令 - ``` npm install -g winglang ``` 安裝[VS Code 市場](https://marketplace.visualstudio.com/items?itemName=Monada.vscode-wing)上提供的 Wing VS code 擴充。 您可以檢查已安裝的 Wing CLI 的版本: ``` wing --version ``` 建立專案 ---- 在檔案系統中建立專案目錄並為其指定所需的名稱。在 VS Code 中開啟此目錄。在專案目錄中建立一個名為 backend 的目錄。 在後端目錄中建立一個名為“main.w”的文件,並將以下程式碼貼到其中: ``` bring cloud; let queue = new cloud.Queue(); let bucket = new cloud.Bucket(); let counter = new cloud.Counter(); queue.setConsumer(inflight (body: str): void => { let next = counter.inc(); let key = "key-{next}"; bucket.put(key, body); }); ``` *注意:如果您在整個過程中遇到任何困難,我們建議您加入我們的[Slack 頻道](https://t.winglang.io/slack)* 在本地執行 Wing 工具鏈以檢查其是否按預期工作。在終端機中執行此命令: ``` wing run backend/main.w ``` 輸出顯示將是: ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qd30iznhw0qt8io0quad.jpg) 這是 Wing Console,它充當模擬器,您可以在其中嘗試、測試和試驗雲端應用程式,看看它是否正常工作。 建立反應應用程式 -------- 現在讓我們建立一個 React App 作為前端,然後將其連接到我們建立的 Wing 後端。 我們將使用`create-react-app`在您的專案目錄中建立 React App。確保您位於主專案目錄內,而不是後端目錄內。 打開一個新終端機並執行以下命令: ``` npx create-react-app client cd client npm i --save @babel/plugin-proposal-private-property-in-object npm start ``` 一旦您看到 React 應用程式成功執行,您可以使用`CTRL+C`關閉伺服器。 連接Wing後端 -------- 現在,我們將 Wing 後端連接到我們的 React 應用程式。它將允許我們從 Wing 後端獲取資料並將其顯示在使用者介面上。 開啟`backend/main.w`檔案並將其內容替換為: 對於 Windows: ``` bring ex; bring cloud; let react = new ex.ReactApp( useBuildCommand: true, projectPath: "../client", buildCommand: "npm run start", ); ``` 對於Linux: ``` bring ex; bring cloud; let react = new ex.ReactApp( projectPath: "../client", ); ``` 使用`CTRL+C`終止`wing run`正在執行的終端,並使用設定`BROWSER=none`環境變數再次執行它: 對於 Windows: ``` set BROWSER=none wing run backend/main.w ``` 對於 Linux/Mac: ``` BROWSER=none wing run backend/main.w ``` `BROWSER=none`將限制 React 在每次執行時開啟一個新的瀏覽器視窗。 現在,您已經成功執行了一個連接到 Wing 工具鏈後端的 React 應用程式。 將配置從後端傳遞到前端 ----------- Wing 在`client/public/wing.js`中產生一個`wing.js`文件,該文件將配置從 Wing 後端傳遞到前端程式碼。 該文件的目前內容將包含: ``` // This file is generated by Wing window.wingEnv = {}; ``` 將以下程式碼加入`backend/main.w` : ``` react.addEnvironment("key1", "value1"); ``` 正在執行的`wing run`會將此鍵值對新增至`client/public/wing.js` : ``` // This file is generated by wing window.wingEnv = { "key1": "value1" }; ``` 現在,您需要將前端程式碼連結到`wing.js`檔案。將以下程式碼複製並貼上到`client/public/index.html`檔案中的`<title>`標記上方: ``` <script src="./wing.js"></script> ``` 我們將從後端獲取標題並將其顯示在 React 應用程式中。將`client/src/App.js`檔案中的「Learn React」(出現在第 18 行左右)字串替換為以下程式碼: ``` {window.wingEnv.title || "Learn React"} ``` 此表達式顯示從 React 應用程式中的 wingEnv 物件動態取得的標題。如果 wingEnv 物件沒有 title 屬性或 window.wingEnv.title 的值為假,它將顯示預設標題「Learn React」。 返回`backend/main.w`並加入以下程式碼: ``` react.addEnvironment("title", "Learn React with Wing"); ``` 這將在`wing.js`檔案中加入包含`Learn React with Wing`訊息的`title`鍵。 從後台取得標題 ------- 現在我們知道如何從客戶端向後端傳遞參數(資料)。我們可以使用這種做法在客戶端設定`window.wingEnv.apiUrl`並從後端取得標題。 我們需要透過在`backend/main.w`檔案中加入以下程式碼來啟用跨域資源共享(CORS): ``` let api = new cloud.Api( cors: true ); ``` 這會將`apiUrl`鍵和後端 API 的目前 URL 新增到`main.w`檔案中。 在後端 API 中建立`/title`路由。將此程式碼加入`backend/main.w`檔案: ``` api.get("/title", inflight () => { return { status: 200, body: "Hello from the API" }; }); ``` 當向`/tite`端點發出 GET 請求時,伺服器將使用 HTTP 狀態碼 200 和`Hello from the API`進行回應。 您可以根據您的意願更改此正文資訊。 將以下程式碼替換為`client/src/App.js`中的內容: ``` import logo from './logo.svg'; import { useEffect, useState } from "react"; import './App.css'; function App() { const [title, setTitle] = useState("Default Value"); const getTitle = async () => { const response = await fetch(`${window.wingEnv.apiUrl}/title`); setTitle(await response.text()); } useEffect(() => { getTitle(); }, []); return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> {title} </header> </div> ); } export default App; ``` 在這裡,我們使用`fetch`方法從後端 API 取得標題, `useState`和`useEffect`鉤子用於將取得的標題儲存在`title`變數中。 最終輸出將是: ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gkc56eurzhzr3n3s28f4.png) 恭喜!您已成功建立一個從 Wing 工具鏈後端取得資料的 React 應用程式。 這就是您如何將資料儲存在 Winglang 後端並獲取它以將其顯示在前端 UI 上。 有什麼地方卡住了嗎?請查看我們的影片教程,我們已經實際解釋了整個過程: {% 嵌入 https://www.youtube.com/embed/LMDnTCRXzJU?si=vuFGkqoK2fKBXb00 %} --- 原文出處:https://dev.to/ayush2390/create-react-app-with-wing-30hm

我又建立了另一個 JavaScript 框架

**現在是 2024 年,您又建立了另一個 JavaScript 框架。說真的,夥計!** 當您談論另一個 Javascript 框架時,您可能會笑並認為有大量經過驗證的選項,為什麼還要建立另一個框架? 🤷‍♂️ 讓我與您分享我的個人故事,它導致了新的 Javascript 框架的發展。但如果你不關心我的可悲的故事,這裡是 TLDR: > **TiniJS**是一個元框架,由基於 Google [Lit](https://lit.dev/)庫的**Web 元件**技術提供支援。 > 您可以先下載[入門範本](https://github.com/tinijs/bare-starter)或使用 CLI 初始化應用程式,執行`npx @tinijs/cli@latest new my-app`並按照說明進行操作。 > 有關更多詳細訊息,請參閱下面的**“入門”**部分或存取<https://tinijs.dev/> 。 故事 -- ![Javascript 框架太多](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kwi99az05w9syfgn7833.jpeg) 開個玩笑吧,我不是 Javascript 的專家,但我想稍微介紹一下我的背景,這樣您可能就會知道我關於前端 Web 開發的煩惱故事。我曾經是 Angular 1 版本的開發人員,目前主要使用 Vue,偶爾使用 jQuery。我有這**3 個 PITA** (Pain In The \*beep\*)經歷,這促使我嘗試使用 TiniJS 框架。 > **PITA #1 - 建立良好的 UI/UX 很困難,既乏味又耗時!** 早在 2010 年左右,就有兩種不同類型的網站:一種有大量文本、連結,幾乎沒有一些圖片;另一種有大量文本、連結,幾乎沒有一些圖片。其他的則包含大量的圖形元素,例如 GIF 圖像、Flash 背景、彩虹遊標… 人們往往有**後端難前端容易的**刻板印象。這有點正確,但不完全正確,我的意思是,我該怪誰,對吧?因為只要有一點 HTML 和 CSS 知識,您就可以非常輕鬆地建立靜態網站。但是,為了建立良好的 UI/UX,還有很多事情需要考慮。你必須成為更多事情的大師,而它們一點也不容易! ![前端開發不容易!](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/77sp9asranurm9xcldl5.png) > **PITA #2 - CSS 框架缺乏功能並且自訂它們不是很有效!** 人們意識到前端開發的困難,開始建立CSS框架來幫助解決這個問題。 Bootstrap是這一趨勢的先驅之一,其他流行的有:Foundation、Semantic UI、Bulma、Skeleton、Pure CSS…這些CSS框架很棒,毫無疑問,它們幫助我們建立一個好的UI/使用者體驗更快,但它們也有自己的限制。 首先,儘管所有框架都提供了一定的方式來定制樣式,但總的來說,我覺得這對我來說不是很容易和可重用。 ![客製化CSS框架效率不是很高](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2lhj75s0sy977e8d5e48.jpg) 二是功能缺失。我的意思是,它們主要是 CSS,它們提供一些功能,通常是作為 JQuery 的插件。大多數情況下,您必須編寫自己的 Javascript 才能使功能正常運作。 > **PITA #3 - JavaScript 框架勢不可擋,而且有點多餘!** 進入現代 Web 開發時代,Javascript 框架已成為新趨勢。但問題是我們有太多的選擇,這既是福也是禍。它們提供了很棒的功能,但互通性不太好,您不能只從一個框架中取出一段程式碼並在另一個框架中使用它。特別是,為特定框架建立一個具有單獨套件的 UI 系統是一項非常艱鉅的任務。 ![前端 Web 開發是碎片化的](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4cx44vzf0guksn2horak.png) 每次我開始一個專案或做某種前端工作時,前端web的碎片化對我來說都有些痛苦。這似乎就是生活方式,無可避免,不是嗎?請不要誤會我的意思,我並不反對任何框架,我傾向於選擇解決方案而不是技術,所以如果它適合你,就用它吧。但我想知道有什麼辦法可以以某種方式統一或縮小前端開發經驗的差距嗎? 🤔 介紹 TiniJS --------- 這就是我嘗試**TiniJS 框架**一段時間的原因。它是基於[Lit](https://lit.dev/)庫、使用本機**Web 元件**技術開發 Web/桌面/行動應用程式的工具集合。感謝[Lit](https://lit.dev/)團隊建立了一個出色的工具,幫助我們更輕鬆地使用標準 Web 元件。 它的目標是盡可能**標準化、小型化和多功能化**。與其他框架和元框架沒有真正的可比性,但總體而言,它具有相似的功能,但另一方面也有關鍵的區別。它既是替代選擇,也是對其他框架的補充。您可以使用 TiniJS 建立各種類型的應用程式:**登陸頁面、SPA、PWA、桌面應用程式、行動應用程式**…就功能而言,任何在 Javascript 中工作的內容都應該在 TiniJS 應用程式中正常運作。 整個系統由幾個部分組成,這是一個快速介紹。 > 請注意,**並非所有部件現在都可用**,該專案還處於早期階段,有些是**之前的實驗**,我盡力盡快將它們投入使用。但我的時間和資源有限,所以請耐心等待,如果可能的話請幫助我。 🙇‍♂️ > V1 的計畫及其路線圖可在<https://github.com/tinijs/tinijs>找到 ### 核 **TiniJS 的**核心提供了傳統的專案結構和簡化的開發流程。有**用於組織內容的資料夾**,**用於開發的本機伺服器**,在分發時,您可以選擇 Vite 或 Parcel 或 Webpack 來**建立產品**。 核心還包括:用於在頁面之間導航的**路由器**、用於全域狀態管理的簡單**儲存**、支援**PWA** ,... 您可以嘗試[Try TiniJS 中的範例專案(範例照片庫應用程式)](https://stackblitz.com/edit/try-tinijs?file=app%2Fapp.ts) ### 使用者介面系統 TiniJS 有一個專用的**UI 庫,我的目標是提供每個常用的元件和區塊甚至整個頁面**。元件以特殊的方式建置,它們是自訂元素,不僅可以與 TiniJS 一起使用,還可以與其他框架或不使用框架一起使用。 ![保持UI概念](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rshg9gol388nf0gsw1jt.png) 使用可重複使用元件很容易,通常是以將 props 傳遞給自訂元素標籤的形式。自訂可以透過 props 或 CSS `::part()`或自訂主題系列或完全克隆元件來源來完成,... 元件還能夠以盡可能小的努力適應幾乎所有設計系統。這是透過主題系統實現的,概念是這樣的: - 元件**只寫一次**,它們是**無頭的**(沒有特定的樣式) - 主題被組織成**系列**(又稱設計系統),系列定義自己的基本特徵,例如:Bootstrap、Material、Fluent、Spectrum,... - 根據基本特徵,一個系列有風格變體,稱為**“皮膚”** ,例如,Bootstrap 系列可能有:淺色皮膚、深色皮膚… 考慮到主題概念,任何應用程式都可以具有以下主題功能: - **一個**主題系列 - 可能是當今存在的所有網路應用程式中的 80% 到 90%,只有 1 種特定風格相當於 TiniJS 1 主題系列。 - **一個**主題系列 + 多個皮膚 - 常見的用例是亮/暗模式,相當於 TiniJS 1 主題系列,具有來自同一系列的多個皮膚。 - **多個**主題系列 - 高度個人化的應用程式可能有多個主題系列,每個系列都有一個或多個皮膚,將根據使用者參考應用某個主題。 UI 使用詳細資訊將在[主頁](https://tinijs.dev/ui)上提供,現在您也可以在<https://ui.tinijs.dev/>查看實驗概念,以查看該概念的實際應用。 ### 網頁、PWA、混合桌面/行動設備 預設的 TiniJS 應用程式是**單頁應用程式**,它小而快速,可以直接部署為 Web 應用程式。但是,您也可以將 TiniJS 轉換為以下一種或所有類型的應用程式: - **漸進式 Web 應用程式**(PWA) - 使用單一 CLI 命令實作(即將推出) - 混合**桌面/行動**應用程式 - 使用 Tauri 2.0 或類似工具(todo:編寫指令) ### 靜態和伺服器 TiniJS 應用程式可以作為靜態網路啟動,無論大小,無需伺服器或資料庫。您始終可以使用 SaaS 服務來滿足幾乎任何後端需求。我還在開發`@tinijs/content` - 一個基於文件的內容管理系統,用於輕鬆管理多種類型的內容。靜態站點產生(SSG)或預渲染也在計劃中。 如果您需要處理後端任務並參考從 Node 伺服器而不是靜態主機為 Web 應用程式提供服務,則可選的 Nitro 伺服器用於**伺服器/API 路由**和其他**伺服器內容**。我的開發能力有限,因此第一個版本可能不支援伺服器端渲染(SSR),相反,我計劃使用半SSR,其中伺服器將為用戶提供單頁服務,並向機器人提供最少的伺服器端渲染內容。 ### 功能和模組 在功能方面,由於 TiniJS 應用程式**基於標準 Web 技術**,因此在瀏覽器中工作的任何程式庫和功能都可能在 TiniJS 應用程式中運作。因此,與其他框架相比,您可能**不必擔心功能**。您甚至可以在 TiniJS 應用程式中使用其他框架,例如初始化 Vue 應用程式並將其安裝到 TiniJS 頁面內的元素。 還有一個模組架構師,以便某些模組可以進入 TiniJS 應用程式的工作流程,建立更簡化的開發管道。 ### 工具 官方 CLI 工具提供了一些使用 TiniJS 應用程式的便利命令。 - `dev` - 啟動本機開發伺服器 - `build` - 建構生產分配 - `preview` - 在部署之前預覽生產版本 - `generate` - 生成元件、頁面、實用程式... 此外,CLI**足夠通用,可以在 TiniJS 應用程式以外的任何類型的專案中使用**。它具有可擴展的架構,您可以在其中擴展更多命令以用於其他自動化任務。一些官方擴展,例如`ui`命令(來自`@tinijs/ui` )用於處理 UI 任務或`content`命令(來自`@tinijs/content` )用於處理內容相關任務,...您可以根據自己的目的建立 CLI 擴展包私人或共享。 好了,說得夠多了,讓我看看一些行動吧! 👌 開始使用 ---- **Tini** (越南語中的“ [Tí nị](https://translate.google.com/?sl=vi&tl=en&text=t%C3%AD%20n%E1%BB%8B&op=translate) ”,意思是非常小、可愛的東西)。 為了快速建立**TiniJS**專案,您可以使用[CLI](https://tinijs.dev/cli)來初始化模板。 ``` npx @tinijs/cli@latest new my-app ``` 上面的命令透過下載**Bare**模板來建立一個應用程式。將來,我想提供幾個入門範本。您還可以建立自己的模板並與社區共享或供您自己私人使用。目前,這些模板可用: - [Bare](https://github.com/tinijs/bare-starter) (預設)- TiniJS 應用程式的最小結構。 - [空白](https://github.com/tinijs/blank-starter)(標誌`-t blank` )- 包含路由器、狀態管理、元標記管理和[Bootstrap 主題系列](https://tinijs.dev/ui)。 現在,在專案內部,您可以執行`npm run dev`來啟動開發伺服器。您可以透過編輯檔案`./app/app.ts`來開始開發,該檔案是應用程式的根元件。有關如何使用 Lit 處理自訂元素,請存取[Lit 元件](https://lit.dev/docs/components/overview/), `LitElement`和`TiniComponent`之間存在一些差異,但現在您可以像平常一樣修改`static styles`和`render()` 。 若要建立發行版,請執行`npm run build`並可選擇執行`npm run preview`以預覽生產版本。現在您可以將`.output`資料夾部署到任何靜態主機。 您可能需要查看這些範例以了解 TiniJS 應用程式如何運作的更多細節。 - 首頁 - <https://github.com/tinijs/tinijs/tree/main/apps/tinijs.dev> - 待辦事項應用程式 - <https://github.com/tinijs/tinijs/tree/main/examples/todo> 這就是**TiniJS 框架**的基本介紹。下次我們將探索**TiniJS 應用程式的結構並使用元件**。 欲了解更多訊息,請存取: <https://tinijs.dev> 謝謝您,編碼愉快! 💖 --- 原文出處:https://dev.to/lamnhan/ive-created-yet-another-javascript-framework-5c5o

Supabase Auth 現在支援匿名登入

Supabase Auth 現在支援[匿名登錄](https://supabase.com/docs/guides/auth/auth-anonymous),這是社群[最需要的功能](https://github.com/supabase/auth/issues/68)之一。 {% cta https://supabase.com/ga-week %} ⚡️ 了解有關 GA 週的更多資訊 {% endcta %} 匿名登入可用於建立尚未註冊您的應用程式的**臨時使用者**。這降低了新用戶試用您的產品的阻力,因為他們不必提供任何註冊憑證。 {% 嵌入 https://youtu.be/WNN7Pp5Ftk4 %} 啟用匿名登入 ------ 您今天可以從儀表板為您的專案[啟用匿名登入](https://supabase.com/dashboard/project/_/settings/auth): ![啟用功能截圖](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/24n0kagpgagq3h2bw145.png) 對於本機開發,請升級 Supabase CLI 並將設定新增至`config.toml`檔案: ``` [auth] enable_anonymous_sign_ins = true ``` 現在您可以透過[Javascript](https://supabase.com/docs/reference/javascript/auth-signinanonymously) 、 [Flutter](https://supabase.com/docs/reference/dart/auth-signinanonymously)或[Swift](https://supabase.com/docs/reference/swift/auth-signinanonymously) SDK 建立匿名使用者。以下是如何使用`supabase-js`建立匿名用戶。 ``` const { data, error } = await supabase .auth .signInAnonymously() ``` 術語 -- 使用匿名登入建立的個人資料也會經過`authenticated` ! 呼叫`.signInAnonymously()`後,您已將使用者移至驗證流程,我們將他們視為登入使用者: ![範例圖](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rjr5r7vj7pu4a8epqjol.png) 限制匿名用戶的存取 --------- 與永久使用者一樣,匿名使用者也保留在`auth.users`表中: |編號 |角色 |電子郵件 |是\_匿名 | | ------------------------------------------------ | ------------- | ----------------- | ------------ | | e053e470-afa1-4625-8963-37adb862fd11 |已驗證 |空|真實 | | 5563108e-ac81-4063-9288-4f3db068efa1 |已驗證 | [email protected] |假 | 匿名用戶可以透過用戶 JWT 中傳回的`is_anonymous`聲明來辨識,該聲明可從行級安全策略 (RLS) 存取。如果您想限制對應用程式中某些功能的存取,這會很有幫助。 例如,假設我們有一個線上論壇,用戶可以在其中建立和閱讀貼文。 給定這個表來儲存帖子: ``` create table public.posts ( id serial primary key, name text not null, description text ); ``` 如果我們只想允許永久用戶建立帖子,我們可以透過檢查 JWT `select auth.jwt() ->> 'is_anonymous'`來檢查使用者是否是匿名的。 在 RLS 策略中使用此函數: ``` create policy "Only permanent users can create posts" on public.posts for insert to authenticated -- Note: user is still authenticated with check ( (select auth.jwt() ->> 'is_anonymous')::boolean is false ); ``` RLS 為我們提供了建立各種規則的充分靈活性。 例如,允許永久用戶對所有帖子進行讀取存取,並限制匿名用戶只能存取今天建立的帖子: ``` create policy "Limit access to anonymous users" on public.posts for select to authenticated -- Note: user is still authenticated using ( case when (select (auth.jwt() ->> 'is_anonymous'))::boolean is true then (created_at >= current_date) else true end ); ``` 將匿名用戶轉換為永久用戶 ------------ 在某些時候,匿名用戶可能決定他們想要建立一個貼文。我們在這裡提示他們註冊一個帳戶,將他們轉換為永久用戶。 > 當匿名使用者俱有與其關聯的身份時,他們被視為永久使用者。 轉換後,使用者 ID 保持不變,這表示與使用者 ID 關聯的任何資料都將被保留。 Supabase Auth 提供了 2 種方法來實現此目的: 1-連結電子郵件或電話身份 2-連結 OAuth 身份 連結電子郵件或電話身份 ----------- 若要連結電子郵件或電話身分: ``` const { data, error } = await supabase .auth .updateUser({ email }) ``` 連結 OAuth 身份 ----------- 要將 OAuth 身分連結到匿名用戶,您需要為專案[啟用手動連結](https://supabase.com/dashboard/project/_/settings/auth)。了解[身分連結](https://supabase.com/docs/guides/auth/auth-identity-linking)如何與 Supabase Auth 配合使用。 ![打開](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pmyynoe9lqgn75owkb3f.png) 啟用後,您可以呼叫`linkIdentity()`方法: ``` const { data, error } = await supabase .auth .linkIdentity({ provider: 'google' }) ``` 冒充匿名用戶 ------ 在建立 RLS 策略來區分匿名使用者的存取權時,您可以利用 SQL 編輯器中的[使用者模擬功能](https://supabase.com/blog/studio-introducing-assistant)來測試您的策略: ![助理截圖](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6jlsj0419csvjtmrzg77.png) *SQL 編輯器中的資料庫角色設定。您可以從下拉清單中選擇使用者來模擬匿名使用者。* [使用者管理畫面](https://supabase.com/dashboard/project/_/auth/users)提供了匿名使用者過濾的選項,這可以幫助了解已建立了多少匿名使用者。 ![工具截圖](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zmx21h9idryi9yl4zi0s.png) 下一步是什麼 ------ 管理匿名用戶可能很棘手,尤其是當您的網站有大量訪客時。我們正在開發「自動清理」選項,以刪除超過 30 天不活動的匿名用戶。同時,由於匿名使用者儲存在資料庫的 auth 模式中,因此您可以透過執行下列查詢來清理孤立的匿名使用者: ``` -- deletes anonymous users created more than 30 days ago delete from auth.users where is_anonymous is true and created_at < now() - interval '30 days'; ``` 我們也正在開發[linter,](https://github.com/supabase/splinter/pull/28)以檢查您的 RLS 策略並突出顯示那些允許匿名用戶存取的策略 - 請繼續關注本月稍後的更新! 入門 -- - 文件:[匿名登入](https://supabase.com/docs/guides/auth/auth-anonymous) - API方法參考: [Javascript](https://supabase.com/docs/reference/javascript/auth-signinanonymously) 、 [Flutter](https://supabase.com/docs/reference/dart/auth-signinanonymously) 、 [Swift](https://supabase.com/docs/reference/swift/auth-signinanonymously) **更多關於 GA 週的訊息** - [斯帕巴斯威夫特](https://supabase.com/blog/supabase-swift) - [AWS Marketplace 上的 Supabase](https://supabase.com/blog/supabase-aws-marketplace) - [Supabase 開源黑客馬拉松 2024](https://supabase.com/blog/supabase-oss-hackathon) - [Supabase引導程式](https://supabase.com/blog/supabase-bootstrap) - \[分支現已公開 \](https://supabase.com/blog/branching-publicly-available) --- 原文出處:https://dev.to/supabase/supabase-auth-now-supports-anonymous-sign-ins-1j00

使用 AI-copilot(Next.js、gpt4、LangChain 和 CopilotKit)建立電子表格應用程式

**長話短說** -------- 在本文中,您將學習如何建立人工智慧驅動的電子表格應用程式,該應用程式允許您使用簡單的英語命令執行各種會計功能並輕鬆與資料互動。 我們將介紹如何: - 使用 Next.js 建立 Web 應用程式, - 使用 React Spreadsheet 建立電子表格應用程式,以及 - 使用 CopilotKit 將 AI 整合到軟體應用程式中。 - 讓電子表格更容易使用、更有趣 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ruxylrd07dga5ngw98np.gif) --- CopilotKit:建構應用內人工智慧副駕駛的框架 ========================== CopilotKit是一個[開源的AI副駕駛平台](https://github.com/CopilotKit/CopilotKit)。我們可以輕鬆地將強大的人工智慧整合到您的 React 應用程式中。 建造: - ChatBot:上下文感知的應用內聊天機器人,可以在應用程式內執行操作 💬 - CopilotTextArea:人工智慧驅動的文字字段,具有上下文感知自動完成和插入功能📝 - 聯合代理:應用程式內人工智慧代理,可以與您的應用程式和使用者互動🤖 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x3us3vc140aun0dvrdof.gif) {% cta https://github.com/CopilotKit/CopilotKit %} Star CopilotKit ⭐️ {% endcta %} (請原諒 AI 的拼字錯誤並給 CopilotKit 加上星號:) 現在回到文章! --- 先決條件 ---- 要完全理解本教程,您需要對 React 或 Next.js 有基本的了解。 以下是建立人工智慧驅動的電子表格應用程式所需的工具: - [React Spreadsheet](https://github.com/iddan/react-spreadsheet) - 一個簡單的包,使我們能夠在 React 應用程式中加入電子表格。 - [OpenAI API](https://platform.openai.com/api-keys) - 提供 API 金鑰,使我們能夠使用 ChatGPT 模型執行各種任務。 - [Tavily AI](https://tavily.com/) - 一個搜尋引擎,使人工智慧代理能夠在應用程式中進行研究並存取即時知識。 - [CopilotKit](https://github.com/CopilotKit) - 一個開源副駕駛框架,用於建立自訂 AI 聊天機器人、應用程式內 AI 代理程式和文字區域。 專案設定和套件安裝 --------- 首先,透過在終端機中執行以下程式碼片段來建立 Next.js 應用程式: ``` npx create-next-app spreadsheet-app ``` 選擇您首選的配置設定。在本教學中,我們將使用 TypeScript 和 Next.js App Router。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f2zg8z22tdgmlv4wmfil.png) 接下來,安裝[OpenAI 函式庫](https://platform.openai.com/docs/introduction)、 [Heroicons](https://www.npmjs.com/package/@heroicons/react)和[React Spreadsheet](https://github.com/iddan/react-spreadsheet)套件及其相依性: ``` npm install openai react-spreadsheet scheduler @heroicons/react ``` 最後,安裝 CopilotKit 軟體套件。這些套件使我們能夠從 React 狀態檢索資料並將 AI copilot 新增至應用程式。 ``` npm install @copilotkit/react-ui @copilotkit/react-textarea @copilotkit/react-core @copilotkit/backend ``` 恭喜!您現在已準備好建立應用程式。 --- 建立電子表格應用程式 ---------- 在本節中,我將引導您使用 React Spreadsheet 建立電子表格應用程式。 該應用程式分為兩個元件: `Sidebar`和`SingleSpreadsheet` 。 要設定這些元件,請導航至 Next.js 應用程式資料夾並建立一個包含以下檔案的`components`資料夾: ``` cd app mkdir components && cd components touch Sidebar.tsx SingleSpreadsheet.tsx ``` ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bd9crph3qdenb2eikfoh.png) 將新建立的元件匯入到**`app/page.tsx`**檔案中。 ``` "use client"; import React, { useState } from "react"; //👇🏻 import the components import { SpreadsheetData } from "./types"; import Sidebar from "./components/Sidebar"; import SingleSpreadsheet from "./components/SingleSpreadsheet"; const Main = () => { return ( <div className='flex'> <p>Hello world</p> </div> ); }; export default Main; ``` 接下來,建立將包含電子表格資料的 React 狀態,並將它們作為 props 傳遞到元件中。 ``` const Main = () => { //👇🏻 holds the title and data within a spreadsheet const [spreadsheets, setSpreadsheets] = React.useState<SpreadsheetData[]>([ { title: "Spreadsheet 1", data: [ [{ value: "" }, { value: "" }, { value: "" }], [{ value: "" }, { value: "" }, { value: "" }], [{ value: "" }, { value: "" }, { value: "" }], ], }, ]); //👇🏻 represents the index of a spreadsheet const [selectedSpreadsheetIndex, setSelectedSpreadsheetIndex] = useState(0); return ( <div className='flex'> <Sidebar spreadsheets={spreadsheets} selectedSpreadsheetIndex={selectedSpreadsheetIndex} setSelectedSpreadsheetIndex={setSelectedSpreadsheetIndex} /> <SingleSpreadsheet spreadsheet={spreadsheets[selectedSpreadsheetIndex]} setSpreadsheet={(spreadsheet) => { setSpreadsheets((prev) => { console.log("setSpreadsheet", spreadsheet); const newSpreadsheets = [...prev]; newSpreadsheets[selectedSpreadsheetIndex] = spreadsheet; return newSpreadsheets; }); }} /> </div> ); }; ``` 此程式碼片段建立了 React 狀態,用於保存電子表格資料及其索引,並將它們作為 props 傳遞到元件中。 `Sidebar`元件接受所有可用的電子表格, `SingleSpreadsheet`元件接收所有電子表格,包括更新電子表格資料的`setSpreadsheet`函數。 將下面的程式碼片段複製到`Sidebar.tsx`檔案中。它顯示應用程式中的所有電子表格,並允許使用者在它們之間進行切換。 ``` import React from "react"; import { SpreadsheetData } from "../types"; interface SidebarProps { spreadsheets: SpreadsheetData[]; selectedSpreadsheetIndex: number; setSelectedSpreadsheetIndex: (index: number) => void; } const Sidebar = ({ spreadsheets, selectedSpreadsheetIndex, setSelectedSpreadsheetIndex, }: SidebarProps) => { return ( <div className='w-64 h-screen bg-gray-800 text-white overflow-auto p-5'> <ul> {spreadsheets.map((spreadsheet, index) => ( <li key={index} className={`mb-4 cursor-pointer ${ index === selectedSpreadsheetIndex ? "ring-2 ring-blue-500 ring-inset p-3 rounded-lg" : "p-3" }`} onClick={() => setSelectedSpreadsheetIndex(index)} > {spreadsheet.title} </li> ))} </ul> </div> ); }; export default Sidebar; ``` ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c36qccuwa0knqokag5mk.gif) 更新`SingleSpreadsheet.tsx`文件,如下所示: ``` import React from "react"; import Spreadsheet from "react-spreadsheet"; import { SpreadsheetData, SpreadsheetRow } from "../types"; interface MainAreaProps { spreadsheet: SpreadsheetData; setSpreadsheet: (spreadsheet: SpreadsheetData) => void; } //👇🏻 adds a new row to the spreadsheet const addRow = () => { const numberOfColumns = spreadsheet.rows[0].length; const newRow: SpreadsheetRow = []; for (let i = 0; i < numberOfColumns; i++) { newRow.push({ value: "" }); } setSpreadsheet({ ...spreadsheet, rows: [...spreadsheet.rows, newRow], }); }; //👇🏻 adds a new column to the spreadsheet const addColumn = () => { const spreadsheetData = [...spreadsheet.data]; for (let i = 0; i < spreadsheet.data.length; i++) { spreadsheet.data[i].push({ value: "" }); } setSpreadsheet({ ...spreadsheet, data: spreadsheetData, }); }; const SingleSpreadsheet = ({ spreadsheet, setSpreadsheet }: MainAreaProps) => { return ( <div className='flex-1 overflow-auto p-5'> {/** -- Spreadsheet title ---*/} <div className='flex items-start'> {/** -- Spreadsheet rows and columns---*/} {/** -- Add column button ---*/} </div> {/** -- Add row button ---*/} </div> ); }; export default SingleSpreadsheet; ``` - 從上面的程式碼片段來看, ``` - The `SingleSpreadsheet.tsx` file includes the addRow and addColumn functions. ``` ``` - The `addRow` function calculates the current number of rows, adds a new row, and updates the spreadsheet accordingly. ``` ``` - Similarly, the `addColumn` function adds a new column to the spreadsheet. ``` ``` - The `SingleSpreadsheet` component renders placeholders for the user interface elements. ``` 更新`SingleSpreadsheet`元件以呈現電子表格標題、其資料以及新增行和列按鈕。 ``` return ( <div className='flex-1 overflow-auto p-5'> {/** -- Spreadsheet title ---*/} <input type='text' value={spreadsheet.title} className='w-full p-2 mb-5 text-center text-2xl font-bold outline-none bg-transparent' onChange={(e) => setSpreadsheet({ ...spreadsheet, title: e.target.value }) } /> {/** -- Spreadsheet rows and columns---*/} <div className='flex items-start'> <Spreadsheet data={spreadsheet.data} onChange={(data) => { console.log("data", data); setSpreadsheet({ ...spreadsheet, data: data as any }); }} /> {/** -- Add column button ---*/} <button className='bg-blue-500 text-white rounded-lg ml-6 w-8 h-8 mt-0.5' onClick={addColumn} > + </button> </div> {/** -- Add row button ---*/} <button className='bg-blue-500 text-white rounded-lg w-8 h-8 mt-5 ' onClick={addRow} > + </button> </div> ); ``` 為了確保一切按預期工作,請在`app`資料夾中建立一個`types.ts`文件,其中包含應用程式中聲明的所有靜態類型。 ``` export interface Cell { value: string; } export type SpreadsheetRow = Cell[]; export interface SpreadsheetData { title: string; rows: SpreadsheetRow[]; } ``` 恭喜! 🎉 您的電子表格應用程式應該可以完美執行。在接下來的部分中,您將了解如何新增 AI 副駕駛,以使用 CopilotKit 自動執行各種任務。 --- 使用 CopilotKit 改進應用程式功能 ---------------------- 在這裡,您將學習如何將 AI 副駕駛加入到電子表格應用程式,以使用 CopilotKit 自動執行複雜的操作。 CopilotKit 提供前端和[後端](https://docs.copilotkit.ai/getting-started/quickstart-backend)套件。它們使您能夠插入 React 狀態並使用 AI 代理在後端處理應用程式資料。 首先,我們將 CopilotKit React 元件新增到應用程式前端。 ### 將 CopilotKit 加入前端 在`app/page.tsx`中,將以下程式碼片段加入`Main`元件的頂部。 ``` import "@copilotkit/react-ui/styles.css"; import { CopilotKit } from "@copilotkit/react-core"; import { CopilotSidebar } from "@copilotkit/react-ui"; import { INSTRUCTIONS } from "./instructions"; const HomePage = () => { return ( <CopilotKit url='/api/copilotkit'> <CopilotSidebar instructions={INSTRUCTIONS} labels={{ initial: "Welcome to the spreadsheet app! How can I help you?", }} defaultOpen={true} clickOutsideToClose={false} > <Main /> </CopilotSidebar> </CopilotKit> ); }; const Main = () => { //--- Main component // }; export default HomePage; ``` - 從上面的程式碼片段來看, ``` - I imported the CopilotKit, its sidebar component, and CSS file to use its frontend components within the application. ``` ``` - The [CopilotKit component](https://docs.copilotkit.ai/reference/CopilotKit) accepts a `url` prop that represents the API server route where CopilotKit will be configured. ``` ``` - The Copilot component also renders the [CopilotSidebar component](https://docs.copilotkit.ai/reference/CopilotSidebar) , allowing users to provide custom instructions to the AI copilot within the application. ``` ``` - Lastly, you can export the `HomePage` component containing the `CopilotSidebar` and the `Main` components. ``` 從上面的程式碼片段中,您會注意到`CopilotSidebar`元件有一個`instructions`屬性。此屬性使您能夠為 CopilotKit 提供額外的上下文或指導。 因此,在`app`資料夾中建立`instructions.ts`檔案並將這些[命令](https://github.com/CopilotKit/spreadsheet-demo/blob/main/src/app/instructions.ts)複製到該檔案中。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/whs8k2ly9as7j4wn6h5o.png) 接下來,您需要將 CopilotKit 插入應用程式的狀態以存取應用程式的資料。為了實現這一點,CopilotKit 提供了兩個鉤子: [useCopilotAction](https://docs.copilotkit.ai/reference/useCopilotAction)和[useMakeCopilotReadable](https://docs.copilotkit.ai/reference/useMakeCopilotReadable) 。 [useCopilotAction](https://docs.copilotkit.ai/reference/useCopilotAction)掛鉤可讓您定義 CopilotKit 執行的動作。它接受包含以下參數的物件: - `name` - 操作的名稱。 - `description` - 操作的描述。 - `parameters` - 包含所需參數清單的陣列。 - `render` - 預設的自訂函數或字串。 - `handler` - 由操作觸發的可執行函數。 ``` useCopilotAction({ name: "sayHello", description: "Say hello to someone.", parameters: [ { name: "name", type: "string", description: "name of the person to say greet", }, ], render: "Process greeting message...", handler: async ({ name }) => { alert(`Hello, ${name}!`); }, }); ``` [useMakeCopilotReadable](https://docs.copilotkit.ai/reference/useMakeCopilotReadable)掛鉤向 CopilotKit 提供應用程式狀態。 ``` import { useMakeCopilotReadable } from "@copilotkit/react-core"; const appState = ...; useMakeCopilotReadable(JSON.stringify(appState)); ``` 現在,讓我們回到電子表格應用程式。在`SingleSpreadsheet`元件中,將應用程式狀態傳遞到 CopilotKit 中,如下所示。 ``` import { useCopilotAction, useMakeCopilotReadable, } from "@copilotkit/react-core"; const SingleSpreadsheet = ({ spreadsheet, setSpreadsheet }: MainAreaProps) => { //👇🏻 hook for providing the application state useMakeCopilotReadable( "This is the current spreadsheet: " + JSON.stringify(spreadsheet) ); // --- other lines of code }; ``` 接下來,您需要在`SingleSpreadsheet`元件中新增兩個操作,該元件在使用者更新電子表格資料並使用 CopilotKit 新增資料行時執行。 在繼續之前,請在`app`資料夾中建立一個包含`canonicalSpreadsheetData.ts`檔案的`utils`資料夾。 ``` cd app mkdir utils && cd utils touch canonicalSpreadsheetData.ts ``` 將下面的程式碼片段複製到檔案中。它接受對電子表格所做的更新,並將其轉換為電子表格中資料行所需的格式。 ``` import { SpreadsheetRow } from "../types" export interface RowLike { cells: CellLike[] | undefined; } export interface CellLike { value: string; } export function canonicalSpreadsheetData( rows: RowLike[] | undefined ): SpreadsheetRow[] { const canonicalRows: SpreadsheetRow[] = []; for (const row of rows || []) { const canonicalRow: SpreadsheetRow = []; for (const cell of row.cells || []) { canonicalRow.push({value: cell.value}); } canonicalRows.push(canonicalRow); } return canonicalRows; } ``` 現在,讓我們使用`SingleSpreadsheet`元件中的`useCopilotAction`掛鉤建立操作。複製下面的第一個操作: ``` import { canonicalSpreadsheetData } from "../utils/canonicalSpreadsheetData"; import { PreviewSpreadsheetChanges } from "./PreviewSpreadsheetChanges"; import { SpreadsheetData, SpreadsheetRow } from "../types"; import { useCopilotAction } from "@copilotkit/react-core"; useCopilotAction({ name: "suggestSpreadsheetOverride", description: "Suggest an override of the current spreadsheet", parameters: [ { name: "rows", type: "object[]", description: "The rows of the spreadsheet", attributes: [ { name: "cells", type: "object[]", description: "The cells of the row", attributes: [ { name: "value", type: "string", description: "The value of the cell", }, ], }, ], }, { name: "title", type: "string", description: "The title of the spreadsheet", required: false, }, ], render: (props) => { const { rows } = props.args const newRows = canonicalSpreadsheetData(rows); return ( <PreviewSpreadsheetChanges preCommitTitle="Replace contents" postCommitTitle="Changes committed" newRows={newRows} commit={(rows) => { const updatedSpreadsheet: SpreadsheetData = { title: spreadsheet.title, rows: rows, }; setSpreadsheet(updatedSpreadsheet); }} /> ) }, handler: ({ rows, title }) => { // Do nothing. // The preview component will optionally handle committing the changes. }, }); ``` 上面的程式碼片段執行使用者的任務並使用 CopilotKit 產生 UI 功能顯示結果預覽。 `suggestSpreadsheetOverride`操作傳回一個自訂元件 ( `PreviewSpreadsheetChanges` ),該元件接受以下內容為 props: - 要新增到電子表格的新資料行, - 一些文字 - `preCommitTitle`和`postCommitTitle` ,以及 - 更新電子表格的`commit`函數。 您很快就會學會如何使用它們。 在元件資料夾中建立`PreviewSpreadsheetChanges`元件,並將下列程式碼片段複製到檔案中: ``` import { CheckCircleIcon } from '@heroicons/react/20/solid' import { SpreadsheetRow } from '../types'; import { useState } from 'react'; import Spreadsheet from 'react-spreadsheet'; export interface PreviewSpreadsheetChanges { preCommitTitle: string; postCommitTitle: string; newRows: SpreadsheetRow[]; commit: (rows: SpreadsheetRow[]) => void; } export function PreviewSpreadsheetChanges(props: PreviewSpreadsheetChanges) { const [changesCommitted, setChangesCommitted] = useState(false); const commitChangesButton = () => { return ( <button className="inline-flex items-center gap-x-2 rounded-md bg-indigo-600 px-3.5 py-2.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600" onClick={() => { props.commit(props.newRows); setChangesCommitted(true); }} > {props.preCommitTitle} </button> ); } const changesCommittedButtonPlaceholder = () => { return ( <button className=" inline-flex items-center gap-x-2 rounded-md bg-gray-100 px-3.5 py-2.5 text-sm font-semibold text-green-600 shadow-sm cursor-not-allowed" disabled > {props.postCommitTitle} <CheckCircleIcon className="-mr-0.5 h-5 w-5" aria-hidden="true" /> </button> ); } return ( <div className="flex flex-col"> <Spreadsheet data={props.newRows} /> <div className="mt-5"> {changesCommitted ? changesCommittedButtonPlaceholder() : commitChangesButton() } </div> </div> ); } ``` `PreviewSpreadsheetChanges`元件傳回一個電子表格,其中包含從請求產生的資料和一個按鈕(帶有`preCommitTitle`文字),該按鈕允許您將這些變更提交到主電子表格表(透過觸發`commit`函數)。這可確保您在將結果新增至電子表格之前對結果感到滿意。 將下面的第二個操作加入到`SingleSpreadsheet`元件。 ``` useCopilotAction({ name: "appendToSpreadsheet", description: "Append rows to the current spreadsheet", parameters: [ { name: "rows", type: "object[]", description: "The new rows of the spreadsheet", attributes: [ { name: "cells", type: "object[]", description: "The cells of the row", attributes: [ { name: "value", type: "string", description: "The value of the cell", }, ], }, ], }, ], render: (props) => { const status = props.status; const { rows } = props.args const newRows = canonicalSpreadsheetData(rows); return ( <div> <p>Status: {status}</p> <Spreadsheet data={newRows} /> </div> ) }, handler: ({ rows }) => { const canonicalRows = canonicalSpreadsheetData(rows); const updatedSpreadsheet: SpreadsheetData = { title: spreadsheet.title, rows: [...spreadsheet.rows, ...canonicalRows], }; setSpreadsheet(updatedSpreadsheet); }, }); ``` `appendToSpreadsheet`操作透過在電子表格中新增資料行來更新電子表格。 以下是操作的簡短示範: \[https://www.youtube.com/watch?v=kGQ9xl5mSoQ\] 最後,在`Main`元件中新增一個操作,以便在使用者提供指令時建立一個新的電子表格。 ``` useCopilotAction({ name: "createSpreadsheet", description: "Create a new spreadsheet", parameters: [ { name: "rows", type: "object[]", description: "The rows of the spreadsheet", attributes: [ { name: "cells", type: "object[]", description: "The cells of the row", attributes: [ { name: "value", type: "string", description: "The value of the cell", }, ], }, ], }, { name: "title", type: "string", description: "The title of the spreadsheet", }, ], render: (props) => { const { rows, title } = props.args; const newRows = canonicalSpreadsheetData(rows); return ( <PreviewSpreadsheetChanges preCommitTitle="Create spreadsheet" postCommitTitle="Spreadsheet created" newRows={newRows} commit={ (rows) => { const newSpreadsheet: SpreadsheetData = { title: title || "Untitled Spreadsheet", rows: rows, }; setSpreadsheets((prev) => [...prev, newSpreadsheet]); setSelectedSpreadsheetIndex(spreadsheets.length); }} /> ); }, handler: ({ rows, title }) => { // Do nothing. // The preview component will optionally handle committing the changes. }, }); ``` 恭喜!您已成功為此應用程式建立所需的操作。現在,讓我們將應用程式連接到 Copilotkit 後端。 ### 將 Tavily AI 和 OpenAI 加入到 CopilotKit 在本教程的開頭,我向您介紹了[Tavily AI](https://tavily.com/) (一個為 AI 代理提供知識的搜尋引擎)和 OpenAI(一個使我們能夠存取[GPT-4 AI 模型的](https://openai.com/gpt-4)庫)。 在本部分中,您將了解如何取得 Tavily 和 OpenAI API 金鑰並將它們整合到 CopilotKit 中以建立高級智慧應用程式。 造訪[Tavily AI 網站](https://app.tavily.com/sign-in),建立一個帳戶,然後將您的 API 金鑰複製到您專案的`.env.local`檔案中。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w8shpxr5hh9r9kggk1jv.png) 接下來,導覽至[OpenAI 開發者平台](https://platform.openai.com/api-keys),建立 API 金鑰,並將其複製到`.env.local`檔案中。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f4ugtobr70wg6z6ru3cj.png) 以下是`.env.local`檔案的預覽,其中包括 API 金鑰並指定要使用的 OpenAI 模型。請注意,存取 GPT-4 模型需要[訂閱 ChatGPT Plus](https://openai.com/chatgpt/pricing) 。 ``` TAVILY_API_KEY=<your_API_key> OPENAI_MODEL=gpt-4-1106-preview OPENAI_API_KEY=<your_API_key> ``` 回到我們的應用程式,您需要為 Copilot 建立 API 路由。因此,建立一個包含`route.ts`的`api/copilotkit`資料夾並新增一個`tavily.ts`檔案。 ``` cd app mkdir api && cd api mkdir copilotkit && cd copilotkit touch route.ts tavily.ts ``` 在`tavily.ts`檔案中建立一個函數,該函數接受使用者的查詢,使用 Tavily Search API 對查詢進行研究,並使用[OpenAI GPT-4 模型](https://openai.com/gpt-4)總結結果。 ``` import OpenAI from "openai"; export async function research(query: string) { //👇🏻 sends the request to the Tavily Search API const response = await fetch("https://api.tavily.com/search", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ api_key: process.env.TAVILY_API_KEY, query, search_depth: "basic", include_answer: true, include_images: false, include_raw_content: false, max_results: 20, }), }); //👇🏻 the response const responseJson = await response.json(); const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY! }); //👇🏻 passes the response into the OpenAI GPT-4 model const completion = await openai.chat.completions.create({ messages: [ { role: "system", content: `Summarize the following JSON to answer the research query \`"${query}"\`: ${JSON.stringify( responseJson )} in plain English.`, }, ], model: process.env.OPENAI_MODEL, }); //👇🏻 returns the result return completion.choices[0].message.content; } ``` 最後,您可以透過將使用者的查詢傳遞到函數中並向 CopilotKit 提供其回應來執行`route.ts`檔案中的`research`函數。 ``` import { CopilotBackend, OpenAIAdapter } from "@copilotkit/backend"; import { Action } from "@copilotkit/shared"; import { research } from "./tavily"; //👇🏻 carries out a research on the user's query const researchAction: Action<any> = { name: "research", description: "Call this function to conduct research on a certain query.", parameters: [ { name: "query", type: "string", description: "The query for doing research. 5 characters or longer. Might be multiple words", }, ], handler: async ({ query }) => { console.log("Research query: ", query); const result = await research(query); console.log("Research result: ", result); return result; }, }; export async function POST(req: Request): Promise<Response> { const actions: Action<any>[] = []; if (process.env.TAVILY_API_KEY!) { actions.push(researchAction); } const copilotKit = new CopilotBackend({ actions: actions, }); const openaiModel = process.env.OPENAI_MODEL; return copilotKit.response(req, new OpenAIAdapter({ model: openaiModel })); } ``` 恭喜!您已完成本教學的專案。 結論 -- [CopilotKit](https://copilotkit.ai/)是一款令人難以置信的工具,可讓您在幾分鐘內將 AI Copilot 加入到您的產品中。無論您是對人工智慧聊天機器人和助理感興趣,還是對複雜任務的自動化感興趣,CopilotKit 都能讓您輕鬆實現。 如果您需要建立 AI 產品或將 AI 工具整合到您的軟體應用程式中,您應該考慮 CopilotKit。 您可以在 GitHub 上找到本教學的源程式碼: https://github.com/CopilotKit/spreadsheet-demo 感謝您的閱讀! --- 原文出處:https://dev.to/copilotkit/build-an-ai-powered-spreadsheet-app-nextjs-langchain-copilotkit-109d

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

✨使用這些工具成為進階 Linux 用戶😎💫

## 簡介 本文列出了開發人員可以在 Linux 電腦上安裝的六種出色工具。 🎉 請隨意探索這些工具,並為這些儲存庫加註星標。開源專案需要您的幫助! 🙏🏻 您準備好成為 **10X Linux 使用者** 了嗎? 🧠 開玩笑,你不會的,😆 但這些工具絕對可以加快你的日常工作量。 🏃🏻‍♂️💨 ![笑 GIF](https://media.giphy.com/media/3o72FfM5HJydzafgUE/giphy.gif) *** **1. [Ngrok](https://ngrok.com/)** > 💡 安全地在線上公開本機伺服器。 ![ngrok cli 工具](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y5rk3ko7fn4w8uvye1de.jpg) Ngrok 可協助您為本機 Web 伺服器建立公用 URL 🌐,以便您可以與團隊成員、客戶或全世界分享您正在進行的工作。 🌍 只需執行一個簡單的命令,Ngrok 就會啟動一條從公共端點到您的電腦的安全隧道。這使您可以在「localhost」上測試網站、應用程式和 API,而無需部署任何內容。 Ngrok 支援 HTTP 和 TCP 流量,因此您幾乎可以透過隧道傳輸任何內容 - Web 伺服器,甚至間接資料庫。它還提供有用的功能,例如自訂子網域和重播/檢查流量。 Ngrok 在以下主要領域提供協助: - 暫時分享一個僅在您的開發機器上執行的網站🖥️。 <br/> - 開發任何使用 webhook 的服務 🪝。 <br/> - 透過檢查網路流量來除錯 🧑‍💻 網路服務。 > ✨ 我不常使用這個工具,但我記得幾年前我第一次使用這個工具是為了向我的朋友展示我在本地建立的網站。 https://github.com/inconshreveable/ngrok 🌟 GitHub 上的 ngrok *** **2. [fzf](https://github.com/junegunn/fzf)** > 💡 命令列模糊查找器。 ![fzf cli 工具](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m0m9bdx5v5chokkc3ni3.jpg) 對於那些花費大量時間在終端工作的人來說,Fzf 是一個有用的工具🖥️。它可作為模糊查找器,可讓您快速搜尋並過濾檔案、命令歷史記錄、git 提交等資料清單。 這是它的工作原理。當您執行“fzf”命令時,它會在您鍵入時立即過濾下面的列表,以僅顯示匹配的結果。 這是一個可能的用例。 😯 ``` ls -la | fzf ``` ![fzf 工具使用案例](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/58xp7w58iahqf62mk285.png) 這種互動式方法使您可以快速輕鬆地找到所需內容,即使在長列表中也是如此。模糊匹配意味著它將找到部分匹配,因此您不必輸入全名。 🤯 https://github.com/junegunn/fzf 🌟 GitHub 上的 fzf *** **3. [Z](https://github.com/rupa/z)** > 💡 在不知道整個路徑的情況下跳轉目錄。 ![z cli 工具](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5a2mhiv09d5qomevhfan.jpg) 您是否曾經處理過具有深層巢狀資料夾結構的專案,並且必須不斷使用 cd 命令鍵入長目錄📂路徑? Z 解決了這個問題。 😉 一旦您安裝並開始使用 Z,它就會追蹤您最常存取的目錄。然後,您可以輸入一個短名稱來立即跳轉 🦘 到該資料夾,而不是輸入完整路徑。 ![Z工具使用](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7cvmisaqr0vkkmdkthx1.jpg) Z 使用**兩個因素**來決定要為您追蹤哪些目錄:您存取資料夾的**頻率**以及您最近**存取該資料夾的方式。 因此,您最常使用的資料夾將獲得最短的名稱。 https://github.com/rupa/z 🌟 GitHub 上的 Z *** **4. [遊俠](https://github.com/ranger/ranger)** > 💡 受 VIM 啟發的控制台檔案管理器。 ![ranger cli 檔案](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b396pdtrppbtdinamrts.jpg) Ranger 是一個**受 vim 啟發的**檔案管理器👮🏻,帶有控制台介面。它提供了一種易於使用且高效的方式來導航和檢視檔案系統。 Ranger 的一些主要特點是: - 多欄✨顯示 <br/> - 預覽所選檔案/目錄的📂 <br/> - 常見檔案操作(`create/chmod/copy/delete`/...) <br/> - 一次重新命名多個文件 <br/> - 類似 VIM 的控制台和熱鍵 ⌨️ ![ranger cli 檔案](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6d6m0lu91gkyi88ti7y0.png) https://github.com/ranger/ranger 🌟 GitHub 上的 Ranger *** **5. [Ncdu](https://www.howtoing.com/ncdu-a-ncurses-based-disk-usage-analyzer-and-tracker/)** > 💡 查看 Linux 系統上使用的檔案和磁碟空間。 Ncdu 是一個有用的命令列工具,可以幫助您有效地管理磁碟空間。 它以直觀方式顯示磁碟機上的空間使用情況,使您可以輕鬆辨識佔用最多空間的大檔案和資料夾。 當您執行 Ncdu 時,它會掃描您的檔案系統並在終端機中顯示互動式列表,向您顯示磁碟機上的每個資料夾以及它們使用了多少空間。您可以導航此清單以深入查看並查看子資料夾的空間使用情況📂。 ![ncdu cli 工具](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/70889hif0ue5w7ev04vu.png) 其簡單的介面使其易於使用,但功能強大,可用於分析磁碟使用情況和最佳化儲存。 如果您遇到磁碟空間💾填滿的問題,Ncdu 可以成為一個方便的工具來辨識罪魁禍首並採取行動。 👮🏻 *** **6。 [Exa](https://github.com/ogham/exa)** - _最好有_ > 💡 `ls` 指令的多彩替換。 ![exa cli 工具](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tykdqcgsnqdqcku9j8ro.jpg) > 🚨 Exa 現已不再維護,請使用 [eza](https://github.com/eza-community/eza)。它是 exa 的一個分支,增加了一些功能。但我仍在使用 Exa,而且效果很好。它們幾乎是一樣的。 Exa 是舊的「ls」指令的現代替代品,您在終端機中使用該指令列出檔案和資料夾。它為您提供當前目錄中更豐富多彩、詳細且易於閱讀的文件清單。 當您執行 **exa** 而不是 `ls` 時,您會看到一些不錯的改進。首先,它使用不同的顏色和圖示(啟用或停用)對文件類型進行顏色編碼💬,從而更容易一目了然地在視覺上區分文件。 它還會向您顯示額外的訊息,例如文件權限、所有者、大小等。 ![exa cli 工具](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dn2d0k7kgqkjp56a4ykl.png) https://github.com/ogham/exa 🌟 GitHub 上的 Exa *** > 如果您認為本文中未提及的任何其他方便的工具,請在下面的評論部分中分享。 👇🏻 那麼,這就是本文的內容。非常感謝您的閱讀! 🎉🫡 https://dev.to/shricodev --- 原文出處:https://dev.to/shricodev/be-a-10x-linux-user-with-these-tools-3g1f

從頭開始實作 JavaScript 概念

在本文中,我們透過從頭開始建立幾個關鍵元件來探索 JavaScript 的基本建構塊。當我們深入研究這些概念時,我們將應用一系列從基礎到複雜的技術,使這種探索對於 JavaScript 世界的新手和專業人士都很有價值。 大綱 ---- - [`memoize()`](#memoize) - [`Array.map()`](#arraymap) - [`Array.filter()`](#arrayfilter) - [`Array.reduce()`](#arrayreduce) - [`bind()`](#bind) - [`call()` 、 `apply()`](#callapply) - [`setInterval()`](#setinterval) - [`cloneDeep()`](#clonedeep) - [`debounce()`](#debounce) - [`throttle()`](#throttle) - [`Promise`](#promise) - \[ `EventEmitter` ) <a name="memoize"></a> `memoize()` ----------- ### 任務說明 重新建立`memoize`函數(來自“lodash”),該函數透過快取函數呼叫的結果來優化效能。透過傳回快取的結果而不是重新計算,可以確保使用相同參數的重複函數呼叫更快。 ### 執行 ``` function customSerializer(entity, cache = new WeakSet()) { if (typeof entity !== 'object' || entity === null) { return `${typeof entity}:${entity}`; } if (cache.has(entity)) { return 'CircularReference'; } cache.add(entity); let objKeys = Object.keys(entity).sort(); let keyRepresentations = objKeys.map(key => `${customSerializer(key, cache)}:${ customSerializer(entity[key], cache) }` ); if (Array.isArray(entity)) { return `Array:[${keyRepresentations.join(',')}]`; } return `Object:{${keyRepresentations.join(',')}}`; } function myMemoize(fn) { const cache = new Map(); return function memoized(...args) { const keyRep = args.map(arg => customSerializer(arg) ).join('-'); const key = `${typeof this}:${this}-${keyRep}`; if (cache.has(key)) { return cache.get(key); } else { const result = fn.apply(this, args); cache.set(key, result); return result; } }; } ``` ### 實施的關鍵面 1. **快取機制:**它使用`Map`物件`cache`來儲存函數呼叫的結果。選擇`Map`物件是因為其高效率的鍵值配對和檢索功能。 2. **Custom Serializer** : `customSerializer`函數將函數參數轉換為用作快取鍵的字串表示形式。此序列化考慮了基本類型、物件(包括巢狀物件)、陣列和循環參考。對於物件和陣列,它們的鍵經過排序以確保一致的字串表示形式,無論屬性聲明順序如何。 3. **序列化`this`** : `this`的值指的是函數所屬的物件。在 JavaScript 中,方法可以根據呼叫它們的物件(即呼叫它們的上下文)而有不同的行為。這是因為`this`提供了對上下文物件的屬性和方法的存取,並且其值可能會根據函數的呼叫方式而變化。 4. **循環引用**:當物件直接或透過其屬性間接引用自身時,就會發生循環引用。這可能發生在更複雜的資料結構中,例如,物件`A`包含對物件`B`的引用,而物件`B`則直接或間接引用物件`A` 。處理循環引用以避免無限循環至關重要。 5. **使用`WeakSet`進行自動垃圾收集**: `WeakSet`保留對其物件的「弱」引用,這表示如果沒有其他引用, `WeakSet`中物件的存在不會阻止該物件被垃圾收集。此行為在需要臨時追蹤物件存在而又不會不必要地延長其生命週期的情況下特別有用。由於`customSerializer`函數可能只需要在序列化過程中標記物件的存取,而不儲存額外的資料,因此使用`WeakSet`可以確保物件不會僅僅因為它們在集合中的存在而保持活動狀態,從而防止潛在的內存洩漏。 <a name="arraymap"></a> `Array.map()` ------------- ### 任務說明 重新建立`Array.map()` ,它將轉換函數作為參數。此轉換函數將在陣列的每個元素上執行,並採用三個參數:當前元素、目前元素的索引和陣列本身。 ### 實施的關鍵面 1. **記憶體預先分配**: `new Array(this.length)`用於建立預先確定大小的陣列,以優化記憶體分配並透過避免加入元素時動態調整大小來提高效能。 ### 執行 ``` Array.prototype.myMap = function(fn) { const result = new Array(this.length); for (let i = 0; i < this.length; i++) { result[i] = fn(this[i], i, this); } return result; } ``` <a name="arrayfilter"></a> `Array.filter()` ---------------- ### 任務說明 重新建立`Array.filter()` ,它將謂詞函數作為輸入,迭代呼叫它的陣列的元素,將謂詞應用於每個元素。它傳回一個新陣列,僅包含謂詞函數傳回`true`元素。 ### 實施的關鍵面 1. **動態記憶體分配**:它動態地將符合條件的元素加入到`filteredArray`中,從而在很少有元素通過謂詞函數的情況下使該方法更有效地使用記憶體。 ### 執行 ``` Array.prototype.myFilter = function(pred) { const filteredArray = []; for (let i = 0; i < this.length; i++) { if (pred(this[i], i, this)) { filteredArray.push(this[i]); } } return filteredArray; } ``` <a name="arrayreduce"></a> `Array.reduce()` ---------------- ### 任務說明 重新建立`Array.reduce()` ,它對陣列的每個元素執行`reducer`函數,從而產生單一輸出值。 `reducer`函數有四個參數:累加器、currentValue、currentIndex 和整個陣列。 ### 實施的關鍵面 1. **`initialValue` value** : `accumulator`和`startIndex`會根據是否將`initialValue`作為參數傳遞來初始化。如果提供了`initialValue` (意味著`arguments.length`至少為`2` ),則`accumulator`設定為此`initialValue` ,並且迭代從第0個元素開始。否則,如果未提供`initialValue` ,則將陣列本身的第 0 個元素用作`initialValue` 。 ### 執行 ``` Array.prototype.myReduce = function(callback, initialValue) { let accumulator = arguments.length >= 2 ? initialValue : this[0]; let startIndex = arguments.length >= 2 ? 0 : 1; for (let i = startIndex; i < this.length; i++) { accumulator = callback(accumulator, this[i], i, this); } return accumulator; } ``` <a name="bind"></a> `bind()` -------- ### 任務說明 重新建立`bind()`函數,該函數允許將物件以及預先指定的初始參數(如果有)作為呼叫原始函數的上下文傳遞。它還應該支援`new`運算符的使用,從而能夠建立新實例,同時維護正確的原型鏈。 ### 執行 ``` Function.prototype.mybind = function(context, ...bindArgs) { const self = this; const boundFunction = function(...callArgs) { const isNewOperatorUsed = new.target !== undefined; const thisContext = isNewOperatorUsed ? this : context; return self.apply(thisContext, bindArgs.concat(callArgs)); }; if (self.prototype) { boundFunction.prototype = Object.create(self.prototype); } return boundFunction; }; ``` ### 實施的關鍵面 1. **處理`new` Operator** :語句`const isNewOperatorUsed = new.target !== undefined;`檢查是否透過`new`運算子將`boundFunction`作為建構函數呼叫。如果使用`new`運算符,則`thisContext`將設定為新建立的物件 ( `this` ) 而不是提供的`context` ,確認實例化應使用新的上下文而不是綁定期間提供的上下文。 2. **原型保留**:為了維護原始函數的原型鏈, `mybind`有條件地將`boundFunction`的原型設定為繼承自`self.prototype`的新物件。此步驟確保從`boundFunction` (用作建構函數時)建立的實例正確地繼承原始函數原型的屬性。此機制保留了預期的繼承層次結構並維護instanceof 檢查。 ### 將`bind()`與`new`一起使用的範例 讓我們考慮一個簡單的建構函數,它建立代表汽車的物件: ``` function Car(make, model, year) { this.make = make; this.model = model; this.year = year; } ``` 想像一下,我們常常創造「豐田」品牌的`Car`物件。為了讓這個過程更有效率,我們可以使用`bind`為Toyotas建立一個專門的建構函數,預先填入`make`參數: ``` // Creating a specialized Toyota constructor with 'Toyota' // as the pre-set 'make' const ToyotaConstructor = Car.bind(null, 'Toyota'); // Now, we can create Toyota car instances // without specifying 'make' const myCar = new ToyotaConstructor('Camry', 2020); // Output: Car { make: 'Toyota', model: 'Camry', year: 2020 } console.log(myCar); ``` <a name="callapply"></a> `call()` 、 `apply()` -------------------- ### 任務說明 重新建立`call()`和`apply()`函數,它們允許使用給定的 this 值和單獨提供的參數來呼叫函數。 ### 執行 ``` Function.prototype.myCall = function(context, ...args) { const fnSymbol = Symbol('fnSymbol'); context[fnSymbol] = this; const result = context[fnSymbol](...args); delete context[fnSymbol]; return result; }; Function.prototype.myApply = function(context, args) { const fnSymbol = Symbol('fnSymbol'); context[fnSymbol] = this; const result = context[fnSymbol](...args); delete context[fnSymbol]; return result; }; ``` ### 實施的關鍵面 1. **屬性命名的符號用法**:為了防止覆蓋上下文物件上潛在的現有屬性或由於名稱衝突而導致意外行為,使用唯一的`Symbol`作為屬性名稱。這確保了我們的臨時屬性不會幹擾上下文物件的原始屬性。 2. **執行後清理**:函數呼叫執行後,新增到上下文物件中的臨時屬性將被刪除。此清理步驟對於避免在上下文物件上留下修改後的狀態至關重要。 <a name="setinterval"></a> `setInterval()` --------------- ### 任務說明 使用`setTimeout`重新建立`setInterval` 。此函數應以指定的時間間隔重複呼叫提供的回呼函數。它會傳回一個函數,當呼叫該函數時,該函數會停止間隔。 ### 執行 ``` function mySetInterval(callback, interval) { let timerId; const repeater = () => { callback(); timerId = setTimeout(repeater, interval); }; repeater(); return () => { clearTimeout(timerId); }; } ``` ### 實施的關鍵面 1. **取消功能**: `mySetInterval`傳回的函數提供了一種簡單直接的方法來取消正在進行的間隔,而無需在函數範圍之外公開或管理計時器 ID。 <a name="clonedeep"></a> `cloneDeep()` ------------- ### 任務說明 重新建立執行給定輸入的深度複製的`cloneDeep`函數(來自“lodash”)。該函數應該能夠複製複雜的資料結構,包括物件、陣列、映射、集合、日期和正規表示式,並保持每個元素的結構和類型完整性。 ### 執行 ``` function myCloneDeep(entity, map = new WeakMap()) { if (entity === null || typeof entity !== 'object') { return entity; } if (map.has(entity)) { return map.get(entity); } let cloned; switch (true) { case Array.isArray(entity): cloned = []; map.set(entity, cloned); cloned = entity.map(item => myCloneDeep(item, map)); break; case entity instanceof Date: cloned = new Date(entity.getTime()); break; case entity instanceof Map: cloned = new Map(Array.from(entity.entries(), ([key, val]) => [myCloneDeep(key, map), myCloneDeep(val, map)])); break; case entity instanceof Set: cloned = new Set(Array.from(entity.values(), val => myCloneDeep(val, map))); break; case entity instanceof RegExp: cloned = new RegExp(entity.source, entity.flags); break; default: cloned = Object.create( Object.getPrototypeOf(entity)); map.set(entity, cloned); for (let key in entity) { if (entity.hasOwnProperty(key)) { cloned[key] = myCloneDeep(entity[key], map); } } } return cloned; } ``` ### 實施的關鍵面 1. **循環引用處理**:利用`WeakMap`來追蹤已存取的物件。如果遇到已經克隆的物件,則返回先前克隆的物件,有效處理循環參考並防止堆疊溢位錯誤。 2. **特殊物件的處理**:區分幾種物件類型( `Array` 、 `Date` 、 `Map` 、 `Sets` 、 `RegExp` ),以確保每種類型都被適當地克隆,並保留其特定特徵。 ``` - **`Array`**: Recursively clones each element, ensuring deep cloning. ``` ``` - **`Date`**: Copies the date using its numeric value (timestamp). ``` ``` - **Maps and Sets**: Constructs a new instance, recursively cloning each entry (for `Map`) or value (for `Set`). ``` ``` - **`RegExp`**: Clones by creating a new instance with the source and flags of the original. ``` 3. **物件屬性的複製**:當輸入是普通物件時,它會建立一個與原始物件具有相同原型的物件,然後遞歸地複製每個自己的屬性,在保持原型鏈的同時確保深度克隆。 4. **效率和性能**:利用`WeakMap`進行記憶,有效處理具有重複引用和循環的複雜大型結構,透過避免冗餘克隆來確保最佳性能。 <a name="debounce"></a> `debounce()` ------------ ### 任務說明 重新建立`debounce`函數(來自“lodash”),它允許限制給定回調函數觸發的頻率。當在短時間內重複呼叫時,在指定的延遲後僅執行最後一次呼叫。 ``` function myDebounce(func, delay) { let timerId; const debounced = function(...args) { clearTimeout(timerId); timerId = setTimeout(() => { func.apply(this, args); }, delay); }; debounced.cancel = function() { clearTimeout(timerId); timerId = null; }; debounced.flush = function() { clearTimeout(timerId); func.apply(this, arguments); timerId = null; }; return debounced; } ``` ### 實施的關鍵面 1. **取消功能**:引入`.cancel`方法使外部控制能夠取消去抖函數的任何暫停執行。這增加了靈活性,允許響應特定事件或條件而取消去抖功能。 2. **透過 Flush 立即執行**: `.flush`方法允許立即執行去抖函數,而不考慮延遲。這在需要確保立即應用去抖函數的效果的情況下非常有用,例如,在卸載元件或完成互動之前。 <a name="throttle"></a> `throttle()` ------------ ### 任務說明 重新建立`throttle`函數(來自“lodash”),它確保給定的回調函數在每個指定的時間間隔內最多只呼叫一次(在我們的例子中是在開始時)。與去抖動不同,限制保證函數會定期執行,確保進行更新,儘管更新速度是受控的。 ### 執行 ``` function myThrottle(func, timeout) { let timerId = null; const throttled = function(...args) { if (timerId === null) { func.apply(this, args) timerId = setTimeout(() => { timerId = null; }, timeout) } } throttled.cancel = function() { clearTimeout(timerId); timerId = null; }; return throttled; } ``` ### 實施的關鍵面 1. **取消功能**:引入`.cancel`方法可以清除節流計時器的任何計劃重置。這在清理階段非常有用,例如 UI 庫/框架中的元件卸載,以防止過時的執行並有效管理資源。 <a name="promise"></a> `Promise` --------- ### 任務說明 重新建立`Promise`類別。它是為非同步程式設計的構造,允許暫停程式碼的執行,直到非同步進程完成。從本質上講,承諾代表了在其建立時不一定已知的值的代理。它允許您將處理程序與非同步操作的最終成功值或失敗原因相關聯。這使得非同步方法可以像同步方法一樣傳回值:非同步方法不是立即傳回最終值,而是傳回一個在未來某個時刻提供該值的承諾。 `Promise`包含處理已完成和拒絕狀態的方法( `then` 、 `catch` ),以及無論結果如何都執行程式碼的方法( `finally` )。 ``` class MyPromise { constructor(executor) { ... } then(onFulfilled, onRejected) { ... } catch(onRejected) { ... } finally(callback) { ... } } ``` ### `constructor`實現 ``` constructor(executor) { this.state = 'pending'; this.value = undefined; this.reason = undefined; this.onFulfilledCallbacks = []; this.onRejectedCallbacks = []; const resolve = (value) => { if (this.state === 'pending') { this.state = 'fulfilled'; this.value = value; this.onFulfilledCallbacks.forEach(fn => fn()); } }; const reject = (reason) => { if (this.state === 'pending') { this.state = 'rejected'; this.reason = reason; this.onRejectedCallbacks.forEach(fn => fn()); } }; try { executor(resolve, reject); } catch (error) { reject(error); } } ``` ### `constructor`實現的關鍵方面 1. **狀態管理**:以「待處理」狀態初始化。解決時切換為“已完成”,被拒絕時切換為“拒絕”。 2. **值和原因**:保存承諾的最終結果( `value` )或拒絕的原因( `reason` )。 - **處理非同步**:接受包含非同步操作的`executor`函數。 `executor`採用兩個函數, `resolve`和`reject` ,當呼叫它們時,將promise轉換到對應的狀態。 3. **回呼陣列**:維護回呼佇列( `onFulfilledCallbacks` 、 `onRejectedCallbacks` ),以用於等待解決或拒絕承諾的延遲操作。 ### `.then`實施 ``` resolvePromise(promise2, x, resolve, reject) { if (promise2 === x) { return reject(new TypeError( 'Chaining cycle detected for promise')); } if (x instanceof MyPromise) { x.then(resolve, reject); } else { resolve(x); } } then(onFulfilled, onRejected) { onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value; onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason; }; let promise2 = new MyPromise((resolve, reject) => { if (this.state === 'fulfilled') { setTimeout(() => { try { let x = onFulfilled(this.value); this.resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }); } else if (this.state === 'rejected') { setTimeout(() => { try { let x = onRejected(this.reason); this.resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }); } else if (this.state === 'pending') { this.onFulfilledCallbacks.push(() => { setTimeout(() => { try { let x = onFulfilled(this.value); this.resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }); }); this.onRejectedCallbacks.push(() => { setTimeout(() => { try { let x = onRejected(this.reason); this.resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }); }); } }); return promise2; } ``` ### `.then`實施的關鍵方面 1. **預設處理程序**:將非函數處理程序轉換為標識函數(用於實現)或拋出程序(用於拒絕),以確保承諾鏈中的正確轉發和錯誤處理。 2. **Promise 連結**: `then`方法允許連結 Promise,從而實現順序非同步操作。它會建立一個新的 Promise ( `promise2` ),該 Promise 取決於傳遞給它的回呼函數 ( `onFulfilled` 、 `onRejected` ) 的結果。 3. **處理解決方案和拒絕**:僅在當前承諾解決(履行或拒絕)後才會呼叫所提供的回調。每個回呼的結果 ( `x` ) 可能是一個值或另一個 Promise,決定了`promise2`的解析。 4. **防止連結循環**: `resolvePromise`函數檢查`promise2`是否與結果 ( `x` ) 相同,避免 Promise 等待自身的循環,從而導致`TypeError` 。 5. **支援 MyPromise 和 Non-Promise 值**:如果結果 ( `x` ) 是`MyPromise`的實例, `then`使用其解析或拒絕來解決`promise2` 。此功能支援基於 Promise 的操作的無縫集成,無論是來自`MyPromise`實例還是本機 JavaScript Promise,假設它們具有相似的行為。對於非 Promise 值,或當`onFulfilled`或`onRejected`只是傳回一個值時, `promise2`將使用該值進行解析,從而在 Promise 鏈中實現簡單的轉換或分支邏輯。 6. **非同步執行保證**:透過使用`setTimeout`延遲`onFulfilled`和`onRejected`的執行, `then`確保非同步為。此延遲保持一致的執行順序,確保`onFulfilled`和`onRejected`在執行堆疊清除後呼叫。 7. **錯誤處理**:如果`onFulfilled`或`onRejected`內發生異常, `promise2`會因錯誤而被拒絕,從而允許錯誤處理通過 Promise 鏈傳播。 ### `catch`並`finally`實現 ``` static resolve(value) { if (value instanceof MyPromise) { return value; } return new MyPromise((resolve, reject) => resolve(value)); } catch(onRejected) { return this.then(null, onRejected); } finally(callback) { return this.then( value => MyPromise.resolve(callback()) .then(() => value), reason => MyPromise.resolve(callback()) .then(() => { throw reason; }) ); } ``` ### `.catch`實施的關鍵面向: 1. **簡化的錯誤處理:** `.catch`方法是`.then(null, onRejected)`的簡寫,專門專注於處理拒絕場景。當只需要拒絕處理程序時,它允許更清晰的語法,從而提高程式碼的可讀性和可維護性。 2. **Promise Chaining 支援:**由於它在內部委託給`.then` ,所以`.catch`返回一個新的 Promise,從而保持 Promise 鏈功能。這允許在錯誤恢復或透過重新拋出或返回新的被拒絕的承諾傳播錯誤後繼續進行鏈操作。 3. **錯誤傳播:**如果提供了`onRejected`並且執行時沒有錯誤,則傳回的 Promise 將使用`onRejected`的傳回值進行解析,從而有效地允許 Promise 鏈中的錯誤復原。如果`onRejected`拋出錯誤或傳回被拒絕的 Promise,則錯誤會沿著鏈傳播。 ### `.finally`實現的關鍵面向: 1. **始終執行:** `.finally`方法確保執行提供的`callback` ,無論 Promise 是履行還是拒絕。這對於需要在非同步操作之後發生的清理操作特別有用,與其結果無關。 2. **傳回值保留:**雖然`.finally`中的`callback`不接收任何參數(與`.then`或`.catch`不同),但 Promise 的原始履行值或拒絕原因將被保留並透過鏈傳遞。從`.finally`傳回的 Promise 會以相同的值或原因被解析或拒絕,除非`callback`本身導致被拒絕的 Promise。 3. **錯誤處理與傳播:**如果`callback`執行成功, `.finally`傳回的 Promise 將按照與原始 Promise 相同的方式進行結算。但是,如果`callback`拋出錯誤或返回被拒絕的 Promise,則從`.finally`返回的 Promise 會因這個新錯誤而被拒絕,從而允許錯誤攔截並更改 Promise 鏈中的拒絕原因。 <a name="eventemitter"></a> `EventEmitter` -------------- ### 任務說明 重新建立`EventEmitter`類,該類別允許實現觀察者模式,使物件(稱為「發射器」)能夠發出命名事件,從而導致呼叫先前註冊的偵聽器(或「處理程序」)。這是 Node.js 中用於處理非同步事件的關鍵元件,廣泛用於發出訊號以及管理應用程式狀態和行為。實作自訂`EventEmitter`涉及建立用於註冊事件偵聽器、觸發事件和刪除偵聽器的方法。 ``` class MyEventEmitter { constructor() { this.events = {}; } on(eventName, listener) { if (!this.events[eventName]) { this.events[eventName] = []; } this.events[eventName].push(listener); } once(eventName, listener) { const onceWrapper = (...args) => { listener.apply(this, args); this.off(eventName, onceWrapper); }; this.on(eventName, onceWrapper); } emit(eventName, ...args) { const listeners = this.events[eventName]; if (listeners && listeners.length) { listeners.forEach((listener) => { listener.apply(this, args); }); } } off(eventName, listenerToRemove) { if (!this.events[eventName]) { return; } const filterListeners = (listener) => listener !== listenerToRemove; this.events[eventName] = this.events[eventName].filter(filterListeners); } } ``` ### `EventEmitter`實現的關鍵面 1. **EventListener Registration `.on` :**將偵聽器函數新增至指定事件的偵聽器陣列中,如果該事件名稱尚不存在則建立一個新陣列。 2. **一次性事件偵聽器`.once` :**註冊一個偵聽器,該偵聽器在呼叫一次後會自行刪除。它將原始偵聽器包裝在一個函數 ( `onceWrapper` ) 中,該函數也會在執行後刪除包裝器,確保偵聽器僅觸發一次。 3. **發出事件`.emit` :**觸發事件,使用提供的參數呼叫所有已註冊的偵聽器。它將參數應用於每個偵聽器函數,從而允許將資料傳遞給偵聽器。 4. **刪除事件偵聽器`.off` :**從事件偵聽器陣列中刪除特定偵聽器。如果事件在刪除後沒有偵聽器,則可以將其保留為空陣列或可選地進一步清理(此實作中未顯示)。 --- 原文出處:https://dev.to/antonzo/implementing-javascript-concepts-from-scratch-4623

給新手開發者的 Git 指南

🩺 醫生有聽診器。 🔧 機械師有扳手。 👨‍💻 我們開發人員,有 Git。 您是否注意到 Git 對於程式碼工作來說是如此不可或缺,以至於人們幾乎從未將其包含在他們的技術堆疊或簡歷中?假設你已經知道了,或至少足以應付,但你知道嗎? Git 是一個版本控制系統(VCS)。無所不在的技術使我們能夠儲存、更改程式碼並與他人合作。 > 🚨 作為免責聲明,我想指出 Git 是一個很大的話題。 Git 書籍已經出版,部落格文章也可能被誤認為是學術論文。這不是我來這裡的目的。**我不是 Git 專家**。我的目標是寫一篇我希望在學習 Git 時擁有的 Git 基礎文章。 作為開發人員,我們的日常工作圍繞著閱讀、編寫和審查程式碼。 Git 可以說是我們使用的最重要的工具之一。身為開發人員,掌握 Git 提供的特性和功能是您可以對自己進行的最佳投資之一。 讓我們開始吧 ![git](https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExMXZqODl2Zjk5cTUzYWo3Nnptam1qYWdqYm4xcmY5dXEyY2RzZWZrbCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/m0HehxSuVPd9CE3L4H/giphy.gif) > 如果您覺得我錯過了或應該更詳細地了解特定命令,請在下面的評論中告訴我。我將相應地更新這篇文章。 🙏 --- 當我們談論這個話題時 ---------- 如果您希望將 Git 技能運用到工作中並願意為 Glasskube 做出貢獻,我們於 2 月正式推出,我們的目標是成為 Kubernetes 套件管理的預設預設解決方案。有了您的支持,我們就能實現這一目標。表達您支持的最佳方式是在 GitHub 上為我們加註星標 ⭐ [![連小貓也喜歡送星星](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nzaxhc3f53sggz7v3bw4.jpeg)](https://github.com/glasskube/glasskube) --- 讓我們打好基礎 ------- Git 有沒有讓你感覺像 Peter Griffin 一樣? 如果您沒有以正確的方式學習 Git,您可能會不斷地摸不著頭腦,陷入同樣的問題,或者後悔有一天在終端中出現另一個合併衝突。讓我們定義一些基本的 Git 概念來確保這種情況不會發生。 ![git-2](https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExNjBqNHlnNjgwZHl4ZmdtMW8wbGJjYWJ5MmQyN2x4YXJpeXAxNWFsZCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/jcKiy2CqRIYM8W3E4p/giphy.gif) ### 分公司 在 Git 儲存庫中,您會發現一條開發主線,通常名為「main」或「master」( [已棄用](https://github.blog/changelog/2020-10-01-the-default-branch-for-newly-created-repositories-is-now-main/)),其中有幾個[分支](https://git-scm.com/book/en/v2/Git-Branching-Branches-in-a-Nutshell)分支。這些分支代表同時的工作流程,使開發人員能夠在同一專案中同時處理多個功能或修復。 ![Git 分支](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t3p5q80hldckku20urm0.png) ### 提交 Git 提交作為更新程式碼的捆綁包,捕獲專案程式碼在特定時間點的快照。每次提交都會記錄自上次記錄以來所做的更改,共同建立專案開發旅程的全面歷史。 ![Git 提交](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dcjp286j11bqkx0k9w35.png) 當引用提交時,您通常會使用其唯一標識的加密[雜湊](https://www.mikestreety.co.uk/blog/the-git-commit-hash/)。 例子: ``` git show abc123def456789 ``` 這顯示了有關該哈希提交的詳細資訊。 ### 標籤 Git[標籤](https://git-scm.com/book/en/v2/Git-Basics-Tagging)充當 Git 歷史中的地標,通常標記專案開發中的重要里程碑,例如`releases` 、 `versions`或`standout commits` 。這些標籤對於標記特定時間點非常有價值,通常代表專案旅程中的起點或主要成就。 ![Git 標籤](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/06uilykiq1ky6dtnr3ez.png) ### 頭 目前簽出分支上的最新提交由`HEAD`指示,充當儲存庫中任何引用的指標。當您位於特定分支時, `HEAD`指向該分支上的最新提交。有時, `HEAD`可以直接指向特定的提交( `detached HEAD`狀態),而不是指向分支的尖端。 ### 階段 了解 Git 階段對於導航 Git 工作流程至關重要。它們代表文件更改在提交到儲存庫之前發生的邏輯轉換。 讓我們深入研究一下 Git 階段的概念: ![Git 階段](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/96ndc8w183kh0tcb3uxb.png) #### 工作目錄👷 `working directory`是您編輯、修改和建立專案文件的位置。表示本機上檔案的目前狀態。 #### 暫存區🚉 `staging`區域就像一個保留區域或預提交區域,您可以在其中準備更改,然後再將更改提交到儲存庫。 > 這裡有用的指令: `git add` > `git rm`也可用於取消暫存更改 #### 本地儲存庫🗄️ 本機儲存庫是 Git 永久儲存已提交變更的位置。它允許您查看專案的歷史記錄,恢復到以前的狀態,並與同一程式碼庫上的其他人進行協作。 > 您可以使用以下指令提交暫存區域中準備好的變更: `git commit` #### 遠端儲存庫🛫 遠端儲存庫是一個集中位置,通常託管在伺服器(例如 GitHub、GitLab 或 Bitbucket)上,您可以在其中與其他人共用專案並進行協作。 > 您可以使用`git push`和`git pull`等命令將提交的變更從本機儲存庫推送/拉取到遠端儲存庫。 Git 入門 ------ 好吧,你必須從某個地方開始,在 Git 中那就是你的`workspace` 。您可以`fork`或`clone`現有儲存庫並擁有該工作區的副本,或者如果您在電腦上的新本機資料夾中全新開始,則必須使用`git init`將其轉換為 git 儲存庫。不容忽視的下一步是設定您的憑證。 ![Source: Shuai Li](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fqr8mylqjo91zurb7gmi.png) ### 憑證設定 當執行推送和拉取到遠端儲存庫時,您不想每次都輸入使用者名稱和密碼,只需執行以下命令即可避免這種情況: ``` git config --global credential.helper store ``` 第一次與遠端儲存庫互動時,Git 會提示您輸入使用者名稱和密碼。之後,您將不再收到提示 > 請務必注意,憑證以純文字格式儲存在`.git-credentials`檔案中。 若要檢查已配置的憑證,您可以使用下列命令: ``` git config --global credential.helper ``` ### 與分公司合作 在本地工作時,了解您目前所在的分支至關重要。這些命令很有幫助: ``` # Will show the changes in the local repository git branch # Or create a branch directly with git branch feature-branch-name ``` 若要在分支之間轉換,請使用: ``` git switch ``` 除了在它們之間進行轉換之外,您還可以使用: ``` git checkout # A shortcut to switch to a branch that is yet to be created with the -b flag git checkout -b feature-branch-name ``` 若要檢查儲存庫的狀態,請使用: ``` git status ``` 始終清楚了解當前分支的一個好方法是在終端機中查看它。許多終端插件可以幫助解決這個問題。這是[一個](https://gist.github.com/joseluisq/1e96c54fa4e1e5647940)。 ![終端視圖](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nycmbxgrtplax7q83g3n.png) ### 使用提交 在處理提交時,使用 git commit -m 記錄更改,使用 git amend 修改最近的提交,並盡力遵守[提交訊息約定](https://gist.github.com/qoomon/5dfcdf8eec66a051ecd85625518cfd13)。 ``` # Make sure to add a message to each commit git commit -m "meaningful message" ``` 如果您對上次提交進行了更改,則不必完全建立另一個提交,您可以使用 --amend 標誌來使用分階段變更來修改最近的提交 ``` # make your changes git add . git commit --amend # This will open your default text editor to modify the commit message if needed. git push origin your_branch --force ``` > ⚠️ 使用`--force`時要小心,因為它有可能涵蓋目標分支的歷史記錄。通常應避免在 main/master 分支上應用它。 > 根據經驗,最好經常提交,以避免遺失進度或意外重置未暫存的變更。之後可以透過壓縮多個提交或進行互動式變基來重寫歷史記錄。 使用`git log`顯示按時間順序排列的提交列表,從最近的提交開始並按時間倒推 操縱歷史 ---- 操縱歷史涉及一些強大的命令。 `Rebase`重寫提交歷史記錄, `Squashing`將多個提交合併為一個,而`Cherry-picking`選擇特定提交。 ### 變基和合併 將變基與合併進行比較是有意義的,因為它們的目標相同,但實現方式不同。關鍵的差異在於變基重寫了專案的歷史。對於重視清晰且易於理解的專案歷史的專案來說,這是理想的選擇。另一方面,合併透過產生新的合併提交來維護兩個分支歷史記錄。 在變基期間,功能分支的提交歷史記錄在移動到主分支的`HEAD`時會被重組 ![狐狸](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ytea832muxycodnkdlma.png) 這裡的工作流程非常簡單。 確保您位於要變基的分支上並從遠端儲存庫取得最新變更: ``` git checkout your_branch git fetch ``` 現在選擇您想要變基的分支並執行以下命令: ``` git rebase upstream_branch ``` 變基後,如果分支已推送到遠端儲存庫,您可能需要強制推送變更: ``` git push origin your_branch --force ``` > ⚠️ 使用`--force`時要小心,因為它有可能涵蓋目標分支的歷史記錄。通常應避免在 main/master 分支上應用它。 ### 擠壓 Git 壓縮用於將多個提交壓縮為單一、有凝聚力的提交。 ![git 擠壓](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/owzri2ufj3meqhtjjpc0.png) 這個概念很容易理解,如果使用的統一程式碼的方法是變基,則特別有用,因為歷史記錄會被改變,所以注意對專案歷史記錄的影響很重要。有時我很難執行擠壓,特別是使用互動式變基,幸運的是我們有一些工具可以幫助我們。這是我首選的壓縮方法,其中涉及將 HEAD 指標向後移動 X 次提交,同時保留分階段的變更。 ``` # Change to the number after HEAD~ depending on the commits you want to squash git reset --soft HEAD~X git commit -m "Your squashed commit message" git push origin your_branch --force ``` > ⚠️ 使用`--force`時要小心,因為它有可能涵蓋目標分支的歷史記錄。通常應避免在 main/master 分支上應用它。 ### 採櫻桃 櫻桃採摘對於選擇性地合併從一個分支到另一個分支的更改非常有用,特別是當合併整個分支不合需要或不可行時。然而,明智地使用櫻桃選擇很重要,因為如果應用不當,可能會導致重複提交和不同的歷史記錄 ![採櫻桃](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wxe90o4u26mikikee9f1.png) 要先執行此操作,您必須確定要選擇的提交的提交哈希,您可以使用`git log`來執行此操作。一旦確定了提交哈希,您就可以執行: ``` git checkout target_branch git cherry-pick <commit-hash> # Do this multiple times if multiple commits are wanted git push origin target_branch ``` 高級 Git 指令 --------- ### 簽署提交 對提交進行簽名是一種驗證 Git 中提交的真實性和完整性的方法。它允許您使用 GPG (GNU Privacy Guard) 金鑰對您的提交進行加密簽名,從而向 Git 保證您確實是該提交的作者。您可以透過建立 GPG 金鑰並將 Git 配置為在提交時使用該金鑰來實現此目的。 步驟如下: ``` # Generate a GPG key gpg --gen-key # Configure Git to Use Your GPG Key git config --global user.signingkey <your-gpg-key-id> # Add the public key to your GitHub account # Signing your commits with the -S flag git commit -S -m "Your commit message" # View signed commits git log --show-signature ``` ### 轉發日誌 我們還沒有探討的一個主題是 Git 引用,它們是指向儲存庫中各種物件的指針,主要是提交,還有標籤和分支。它們可作為 Git 歷史記錄中的命名點,允許使用者瀏覽儲存庫的時間軸並存取專案的特定快照。了解如何導航 git 引用非常有用,他們可以使用 git reflog 來做到這一點。 以下是一些好處: - 恢復遺失的提交或分支 - 除錯和故障排除 - 糾正錯誤 ### 互動式變基 互動式變基是一個強大的 Git 功能,可讓您以互動方式重寫提交歷史記錄。它使您能夠在將提交應用到分支之前對其進行修改、重新排序、組合或刪除。 為了使用它,您必須熟悉可能的操作,例如: - 選擇(“p”) - 改寫(“r”) - 編輯(“e”) - 壁球(“s”) - 刪除(“d”) ![互動式變基](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/98sngs9j2dl5awcmm8dt.png) 這是一個有用的[影片,](https://www.youtube.com/watch?v=qsTthZi23VE)用於學習如何在終端中執行互動式變基,我還在部落格文章的底部連結了一個有用的工具。 與 Git 協作 -------- ### 起源與上游 **來源**是複製本機 Git 儲存庫時與本機 Git 儲存庫關聯的預設遠端儲存庫。如果您分叉了一個儲存庫,那麼預設情況下該分叉將成為您的「原始」儲存庫。 另一方面,**上游**指的是您的儲存庫分叉的原始儲存庫。 為了讓您的分叉儲存庫與原始專案的最新更改保持同步,您可以從「上游」儲存庫中 git 取得更改,並將它們合併或變基到本機儲存庫中。 若要查看與本機 Git 儲存庫關聯的遠端儲存庫,請執行: ``` git remote -v ``` ### 衝突 不要驚慌,當嘗試合併或變基分支並檢測到衝突時,這只意味著存儲庫中同一文件或文件的不同版本之間存在衝突的更改,並且可以輕鬆解決(大多數情況下)。 ![合併衝突](https://media3.giphy.com/media/v1.Y2lkPTc5MGI3NjExbXRiM3o5cWd0OGZ3Z2NudGhlb2gyaXhheTRmcGx0bW5sN3UzNXJhYSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/cFkiFMDg3iFoI/giphy.gif) 它們通常在受影響的文件中指示,Git 在其中插入衝突標記`<<<<<<<` 、 `=======`和`>>>>>>>`以突出顯示衝突部分。 決定保留、修改或刪除哪些更改,確保產生的程式碼有意義並保留預期的功能。 手動解決衝突檔案中的衝突後,刪除衝突標記`<<<<<<<` 、 `=======`和`>>>>>>>`並根據需要調整程式碼。 對解決方案感到滿意後,請儲存衝突文件中的變更。 > 如果您在解決衝突時遇到問題,該[影片](https://www.youtube.com/watch?v=xNVM5UxlFSA)可以很好地解釋它。 流行的 Git 工作流程 ------------ ![git 工作流程](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x955re263jtueig35kyg.png) 存在各種 Git 工作流程,但需要注意的是,不存在通用的「最佳」Git 工作流程。相反,每種方法都有其自身的優點和缺點。讓我們來探索這些不同的工作流程,以了解它們的優點和缺點。 ![git 工作流程](https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExeTY0eTI3anV6YnJ3Y2Y3bzd6ZTE5dHJ6OG9hdDNsM3hwcW1ubHZiMCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/dSetNZo2AJfptAk9hp/giphy.gif) ### 功能分支工作流程🌱 每個新功能或錯誤修復都是在自己的分支中開發的,然後在完成後將其合併回主分支。 > - **優點**:隔離變更並減少衝突。 > - **弱點**:可能變得複雜並且需要勤奮的分行管理。 ### Gitflow 工作流程 🌊 Gitflow 定義了嚴格的分支模型,為不同類型的開發任務提供了預先定義的分支。 它包括長期分支,例如 main、develop、feature 分支、release 分支和 hotfix 分支。 > - **優點**:適合定期發布、長期維護的專案。 > - **缺點**:對於較小的團隊來說可能過於複雜 ### 分岔工作流程🍴 在此工作流程中,每個開發人員都會複製主儲存庫,但他們不會將變更直接推送到主儲存庫,而是將變更推送到自己的儲存庫分支。然後,開發人員建立拉取請求以提出對主儲存庫的更改,從而允許在合併之前進行程式碼審查和協作。 這是我們在開源 Glasskube 儲存庫上進行協作的工作流程。 > - **優點**:鼓勵外部貢獻者進行協作,而無需授予對主儲存庫的直接寫入存取權。 > - **弱點**:維持分支和主儲存庫之間的同步可能具有挑戰性。 ### 拉取請求工作流程 ⏩ 與分叉工作流程類似,但開發人員不是分叉,而是直接在主儲存庫中建立功能分支。 > - **優點**:促進團隊成員之間的程式碼審查、協作和知識共享。 > - **弱點**:對人類程式碼審查員的依賴可能會導致開發過程延遲。 ### 基於主幹的開發🪵 如果您所在的團隊專注於快速迭代和持續交付,您可能會使用基於主幹的開發,開發人員直接在主分支上工作,提交小而頻繁的變更。 > - **優勢**:促進快速迭代、持續集成,並專注於為生產提供小而頻繁的變更。 > - **缺點**:需要強大的自動化測試和部署管道來確保主分支的穩定性,可能不適合發佈時間表嚴格或功能開發複雜的專案。 ### 什麼叉子? 強烈建議在開源專案上進行分叉,因為您可以完全控制自己的儲存庫副本。您可以進行變更、嘗試新功能或修復錯誤,而不會影響原始專案。 > 💡 我花了很長時間才弄清楚,雖然分叉存儲庫作為單獨的實體開始,但它們保留了與原始存儲庫的連接。此連接可讓您追蹤原始專案中的變更並將您的分支與其他人所做的更新同步。 這就是為什麼即使您推送到原始存儲庫也是如此。您的變更也會顯示在遙控器上。 Git 備忘錄 ------- ``` # Clone a Repository git clone <repository_url> # Stage Changes for Commit git add <file(s)> # Commit Changes git commit -m "Commit message" # Push Changes to the Remote Repository git push # Force Push Changes (use with caution) git push --force # Reset Working Directory to Last Commit git reset --hard # Create a New Branch git branch <branch_name> # Switch to a Different Branch git checkout <branch_name> # Merge Changes from Another Branch git merge <branch_name> # Rebase Changes onto Another Branch (use with caution) git rebase <base_branch> # View Status of Working Directory git status # View Commit History git log # Undo Last Commit (use with caution) git reset --soft HEAD^ # Discard Changes in Working Directory git restore <file(s)> # Retrieve Lost Commit References git reflog # Interactive Rebase to Rearrange Commits git rebase --interactive HEAD~3 ``` --- 獎金!一些 Git 工具和資源可以讓您的生活更輕鬆。 -------------------------- - 互動式變基[工具](https://github.com/MitMaro/git-interactive-rebase-tool)。 - [Cdiff](https://github.com/amigrave/cdiff)查看豐富多彩的增量差異。 - 互動式 Git 分支[遊樂場](https://learngitbranching.js.org/?locale=en_US) --- 如果您喜歡這類內容並希望看到更多內容,請考慮在 GitHub 上給我們一個 Star 來支持我們🙏 [![連小貓也喜歡送星星](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nzaxhc3f53sggz7v3bw4.jpeg)](https://github.com/glasskube/glasskube) --- 原文出處:https://dev.to/glasskube/the-guide-to-git-i-never-had-1450

⚛️ 在 React 元件中組織程式碼

在 React 元件中組織程式碼有時經常被忽視,但在處理高階元件 (HoC)、 `forwardRef`和`memo`時,事情可能會變得複雜。如果處理不當,可能會導致程式碼混亂且難以維護。本文旨在透過提出一種更易於管理的方式來建立程式碼並提高工作效率來解決這些問題。 1️⃣ 在 React 元件中管理 HoC、 `forwardRef`和`memo` ------------------------------------------ ### 問題陳述 身為 React 開發人員,我經常在組織元件方面遇到困難,尤其是在合併`memo`和`forwardRef`時。以下的範例取自[React TypeScript Cheatsheet](https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/forward_and_create_ref) ,示範了這個挑戰: ``` import { forwardRef } from 'react'; interface FancyButtonProps { type: 'submit' | 'button'; children?: React.ReactNode; } export const FancyButton = forwardRef<HTMLButtonElement, FancyButtonProps>((props, ref) => ( <button ref={ref} className="MyClassName" type={props.type}> {props.children} </button> )); ``` 根據我自己的經驗,這段程式碼有幾個問題: - 與「裸」元件相比,由於元件包裝在`forwardRef`中,程式碼顯得混亂。 - 類型並不是真正處於最佳位置。與元件中使用的實際參數相比, `forwardRef`的泛型具有相反的順序: `<HTMLButtonElement, FancyButtonProps>`與`(props, ref)` 。 - 重構變得很麻煩,因為它需要仔細注意方括號和圓括號。假設您不再需要`forwardRef` 。即使有了彩虹括號之類的幫助,處理這些括號和圓括號有時也會令人沮喪,尤其是當元件很大時。 - 如果您想要為元件新增`memo`或某些類型的自訂 HoC,以及其中的某些狀態或函數,該怎麼辦?它會變得更加混亂: ``` import { forwardRef, memo } from 'react'; import { useStyles } from '@/modules/core/styles'; interface FancyButtonProps { type: 'submit' | 'button'; children?: React.ReactNode; } export const FancyButton = memo( forwardRef<HTMLButtonElement, FancyButtonProps>(({ type, children }, ref) => { const classes = useStyles(); return <button ref={ref} className={classes.button} type={props.type}> {children} </button> }) ); ``` ### 建議的解決方案 在厭倦了以這種方式組織元件程式碼時遇到的所有麻煩之後,我最終想出了一種方法來解決這些問題。考慮以下方法: ``` import { forwardRef, memo } from 'react'; import { useStyles } from '@/modules/core/styles'; interface FancyButtonProps { type: 'submit' | 'button'; children?: React.ReactNode; } const FancyButtonBase = ( { type, children }: FancyButtonProps, ref: React.ForwardedRef<HTMLButtonElement> ) => { const classes = useStyles(); return ( <button ref={ref} className={classes.button} type={type}> {children} </button> ); }; export const FancyButton = memo(forwardRef(FancyButtonBase)); ``` 該程式碼是不言自明的。元件的實際程式碼位於名稱帶有`Base`後綴的函陣列件中。然後我們匯出下面的元件,以及所有 HoC、 `memo`和`forwardRef` 。 此解決方案具有以下幾個優點: - 實際的元件程式碼與 HoC、 `memo`和`forwardRef`分離,使其類似於「裸」元件。 - 類型位於它們應該在的位置: `(props: FancyButtonProps, ref: React.ForwardedRef<HTMLButtonElement>` 。 - 如果您需要重構此程式碼,例如不再使用`ref` ,您只需刪除第二個參數和`forwardRef`而無需處理方括號和圓括號。 - 如果需要嵌套的 HoC,加入或修改它們很簡單,並且程式碼仍然可讀: ``` import { forwardRef, memo } from 'react'; import { useStyles } from '@/modules/core/styles'; import { withWhatever } from '@/modules/core/hocs'; interface FancyButtonProps { type: 'submit' | 'button'; children?: React.ReactNode; } const FancyButtonBase = ( { type, children }: FancyButtonProps, ref: React.ForwardedRef<HTMLButtonElement> ) => { const classes = useStyles(); return ( <button ref={ref} className={classes.button} type={type}> {children} </button> ); }; export const FancyButton = memo(forwardRef(withWhatever(FancyButtonBase))); ``` 這種方法為元件加入了一行程式碼,但顯著提高了可讀性和可維護性。即使不使用任何 HoC、 `memo`或`forwardRef` ,我仍然對「裸」元件執行此操作: `export const FancyButton = FancyButtonBase` 。 我們可以更進一步,嘗試使用一個非常有用但不太知名的 VSCode 擴充功能來提高我們的工作效率。 2️⃣ 透過「資料夾模板」擴充功能提高工作效率 ----------------------- 下面的 GIF 演示了[VSCode 中「資料夾模板」擴充功能](https://marketplace.visualstudio.com/items?itemName=Huuums.vscode-fast-folder-structure)的強大功能(載入 GIF 可能需要一點時間): ![資料夾模板擴充演示](https://res.cloudinary.com/dip6bddoz/image/upload/v1712480236/react-folder-templates-minest_e1qg9z.gif) 您只需輸入元件的名稱,瞧! 基本上,您也可以告訴 AI 為您編寫此樣板程式碼,但我發現使用此擴充功能要快得多,而且它是高度可自訂的。 如果您需要我分享我預先定義的 React 特定資料夾範本設置,請在評論中告訴我。 🏁 結論 ---- 在 React 元件中組織程式碼,尤其是在使用`memo` 、 `forwardRef`和 HoC 時,可能會是一項艱鉅的任務。然而,透過將實際的元件程式碼與 HoC 分開並確保正確的類型聲明,您可以建立更清晰、更易於維護的程式碼。此外,使用 VSCode 中的「資料夾範本」擴充功能等工具可以幫助簡化您的開發流程並提高工作效率。 如果你認為這是一篇好文章,你可能會發現我之前的文章也很有用: https://dev.to/itswillt/folder-structs-in-react-projects-3dp8 --- 原文出處:https://dev.to/itswillt/organizing-code-in-a-react-component-4coa

如何建構:人工智慧驅動的部落格平台(Next.js、Langchain 和 Supabase)

**長話短說** -------- 在本文中,您將學習如何建立一個人工智慧驅動的部落格平台,該平台可以搜尋網路並研究部落格文章的任何主題。 我們將涵蓋: - 用於應用程式框架的 Next.js 🖥️ - 法學碩士 OpenAI 🧠 - LangChain 和 Tavily 的網路搜尋人工智慧代理🤖 - 使用 CopilotKit 將 AI 整合到您的應用程式中 🪁 - Supabase 用於儲存和檢索部落格平台文章資料。 --- CopilotKit:開源 Copilot 框架 ======================== CopilotKit 是[開源 AI 副駕駛框架和平台。](https://github.com/CopilotKit/CopilotKit)我們可以輕鬆地將強大的人工智慧整合到您的 React 應用程式中。 建造: - ChatBots💬:上下文感知的應用內聊天機器人,可以在應用程式內執行操作 - CopilotTextArea📝:人工智慧驅動的文字字段,具有上下文感知自動完成和插入功能 - 聯合代理🤖:應用程式內人工智慧代理,可以與您的應用程式和使用者互動。由浪鏈提供技術支援。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i8gltoave8490fg234ro.gif) {% cta https://github.com/CopilotKit/CopilotKit %} Star CopilotKit ⭐️ {% endcta %} (原諒人工智慧的拼字錯誤並給一顆星:) 現在回到文章。 --- **先決條件** -------- 在開始建立應用程式之前,讓我們先查看建置應用程式所需的依賴項或套件 - `copilotkit/react-core` :CopilotKit 前端包,帶有 React hooks,用於向副駕駛提供應用程式狀態和操作(AI 功能) - `copilotkit/react-ui:`聊天機器人側邊欄 UI 的 CopilotKit 前端包 - `copilotkit/react-textarea:` CopilotKit 前端包,用於在演講者筆記中進行人工智慧輔助文字編輯。 - `LangChainJS:`用於開發由語言模型支援的應用程式的框架。 - `Tavily Search API:`幫助將法學碩士和人工智慧應用程式連接到可信賴的即時知識的 API。 安裝所有專案包和依賴項 ----------- 在安裝所有專案包和依賴項之前,我們首先在終端機上執行以下命令來建立 Nextjs 專案。 ``` npx create-next-app@latest ``` 然後系統會提示您選擇一些選項。請隨意標記它們,如下所示。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1j04grq2jykx6o606u1s.png) 之後,使用您選擇的文字編輯器開啟新建立的 Nextjs 專案。然後在命令列中執行以下命令來安裝所有專案包和依賴項。 ``` npm i @copilotkit/backend @copilotkit/shared @langchain/langgraph @copilotkit/react-core @copilotkit/react-ui @copilotkit/react-textarea @supabase/ssr @supabase/auth-helpers-nextjs ``` **建立部落格平台前端** ------------- 在本節中,我將引導您完成使用靜態內容建立部落格平台前端的過程,以定義平台的使用者介面。 首先,前往`/[root]/src/app`並建立一個名為`components`的資料夾。在 Components 資料夾中,建立一個名為`Article.tsx`的檔案。 之後,將以下程式碼新增至定義名為`Article`功能元件的檔案中,該元件將用於呈現文章建立表單。 ``` "use client"; import { useRef, useState } from "react"; export function Article() { // Define state variables for article outline, copilot text, and article title const [articleOutline, setArticleOutline] = useState(""); const [copilotText, setCopilotText] = useState(""); const [articleTitle, setArticleTitle] = useState(""); return ( // Form element for article input <form action={""} className="w-full h-full gap-10 flex flex-col items-center p-10"> {/* Input field for article title */} <div className="flex w-full items-start gap-3"> <textarea className="p-2 w-full h-12 rounded-lg flex-grow overflow-x-auto overflow-y-hidden whitespace-nowrap" id="title" name="title" value={articleTitle} placeholder="Article Title" onChange={(event) => setArticleTitle(event.target.value)} /> </div> {/* Textarea for article content */} <textarea className="p-4 w-full aspect-square font-bold text-xl bg-slate-800 text-white rounded-lg resize-none" id="content" name="content" value={copilotText} placeholder="Write your article content here" onChange={(event) => setCopilotText(event.target.value)} /> {/* Publish button */} <button type="submit" className="p-4 w-full !bg-slate-800 text-white rounded-lg">Publish</button> </form> ); } ``` 接下來,將另一個檔案新增到元件資料夾中,並將其命名為`Header.tsx` 。然後將以下程式碼新增至定義名為`Header`的功能元件的檔案中,該元件將呈現部落格平台的導覽列。 ``` import Link from "next/link"; export default function Header() { return ( <> <header className="flex flex-wrap sm:justify-start sm:flex-nowrap z-50 w-full bg-white border-b border-gray-200 text-sm py-3 sm:py-0 "> <nav className="relative max-w-7xl w-full mx-auto px-4 sm:flex sm:items-center sm:justify-between sm:px-6 lg:px-8" aria-label="Global"> <div className="flex items-center justify-between"> <Link className="flex-none text-xl font-semibold " href="/" aria-label="Brand"> AIBlogging </Link> </div> <div id="navbar-collapse-with-animation" className=""> <div className="flex flex-col gap-y-4 gap-x-0 mt-5 sm:flex-row sm:items-center sm:justify-end sm:gap-y-0 sm:gap-x-7 sm:mt-0 sm:ps-7"> <Link className="flex items-center font-medium text-gray-500 border-2 border-indigo-600 text-center p-2 rounded-md hover:text-blue-600 sm:border-s sm:my-6 " href="/writearticle"> Create Post </Link> </div> </div> </nav> </header> </> ); } ``` 之後,轉到`/[root]/src/app`並建立一個名為`writearticle`的資料夾。在`writearticle`資料夾中,建立一個名為`page.tsx`檔案。然後將以下程式碼加入匯入`Article`和`Header`元件的檔案中。然後,程式碼定義了一個名為`WriteArticle`的功能元件,它將呈現導覽列和文章建立表單。 ``` import { Article } from "../components/Article"; import Header from "../components/Header"; export default function WriteArticle() { return ( <> <Header /> <Article /> </> ); } ``` 接下來,前往`/[root]/src/page.tsx`文件,並新增以下程式碼,該程式碼定義一個名為`Home`功能元件,該元件呈現將顯示已發佈文章清單的部落格平台主頁。 ``` import Image from "next/image"; import Link from "next/link"; import Header from "./components/Header"; const Home = async () => { return ( <> <Header /> <div className="max-w-[85rem] h-full px-4 py-10 sm:px-6 lg:px-8 lg:py-14 mx-auto"> <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-6"> <Link key={""} className="group flex flex-col h-full bg-white border border-gray-200 hover:border-transparent hover:shadow-lg transition-all duration-300 rounded-xl p-5 " href={""}> <div className="aspect-w-16 aspect-h-11"> <Image className="object-cover h-48 w-96 rounded-xl" src={`https://source.unsplash.com/featured/?${encodeURIComponent( "hello world" )}`} width={500} height={500} alt="Image Description" /> </div> <div className="my-6"> <h3 className="text-xl font-semibold text-gray-800 "> Hello World </h3> </div> </Link> </div> </div> </> ); }; export default Home; ``` 之後,請轉到`next.config.js`檔案並加入以下程式碼,該程式碼允許您使用 Unsplash 中的圖像作為已發布文章的封面圖像。 ``` module.exports = { images: { remotePatterns: [ { protocol: "https", hostname: "source.unsplash.com", }, ], }, }; ``` 最後,在命令列上執行命令`npm run dev` ,然後導航到 http://localhost:3000/。現在您應該在瀏覽器上查看部落格平台前端,如下所示。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m319h0j3ta0xa1fhkezo.png) **將部落格平台與 CopilotKit 後端集成** --------------------------- 在本節中,我將引導您完成將部落格平台與 CopilotKit 後端整合的過程,CopilotKit 後端處理來自前端的請求,提供函數呼叫和各種 LLM 後端(例如 GPT)。此外,我們將整合一個名為 Tavily 的人工智慧代理,它可以研究網路上的任何主題。 首先,在根目錄中建立一個名為`.env.local`的檔案。然後在保存`ChatGPT`和`Tavily` Search API 金鑰的檔案中加入下面的環境變數。 ``` OPENAI_API_KEY="Your ChatGPT API key" TAVILY_API_KEY="Your Tavily Search API key" ``` 若要取得 ChatGPT API 金鑰,請導覽至 https://platform.openai.com/api-keys。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/co9getwdzh34u1k5cehf.png) 若要取得 Tavilly Search API 金鑰,請導覽至 https://app.tavily.com/home ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ju9syhy5w8oip67tyne0.png) 之後,轉到`/[root]/src/app`並建立一個名為`api`的資料夾。在`api`資料夾中,建立一個名為`copilotkit`的資料夾。在`copilotkit`資料夾中,建立一個名為`research.ts`的檔案。然後導航到[該 Research.ts gist 文件](https://gist.github.com/TheGreatBonnie/58dc21ebbeeb8cbb08df665db762738c),複製程式碼,並將其新增至**`research.ts`**檔案中 接下來,在`/[root]/src/app/api/copilotkit`資料夾中建立一個名為`route.ts`的檔案。該文件將包含設定後端功能來處理 POST 請求的程式碼。它有條件地包括對給定主題進行研究的“研究”操作。 現在在文件頂部導入以下模組。 ``` import { CopilotBackend, OpenAIAdapter } from "@copilotkit/backend"; // For backend functionality with CopilotKit. import { researchWithLangGraph } from "./research"; // Import a custom function for conducting research. import { AnnotatedFunction } from "@copilotkit/shared"; // For annotating functions with metadata. ``` 在上面的程式碼下面,定義一個執行時間環境變數和一個名為`researchAction`的函數,該函數使用下面的程式碼對某個主題進行研究。 ``` // Define a runtime environment variable, indicating the environment where the code is expected to run. export const runtime = "edge"; // Define an annotated function for research. This object includes metadata and an implementation for the function. const researchAction: AnnotatedFunction<any> = { name: "research", // Function name. description: "Call this function to conduct research on a certain topic. Respect other notes about when to call this function", // Function description. argumentAnnotations: [ // Annotations for arguments that the function accepts. { name: "topic", // Argument name. type: "string", // Argument type. description: "The topic to research. 5 characters or longer.", // Argument description. required: true, // Indicates that the argument is required. }, ], implementation: async (topic) => { // The actual function implementation. console.log("Researching topic: ", topic); // Log the research topic. return await researchWithLangGraph(topic); // Call the research function and return its result. }, }; ``` 然後在上面的程式碼下加入下面的程式碼來定義處理POST請求的非同步函數。 ``` // Define an asynchronous function that handles POST requests. export async function POST(req: Request): Promise<Response> { const actions: AnnotatedFunction<any>[] = []; // Initialize an array to hold actions. // Check if a specific environment variable is set, indicating access to certain functionality. if (process.env["TAVILY_API_KEY"]) { actions.push(researchAction); // Add the research action to the actions array if the condition is true. } // Instantiate CopilotBackend with the actions defined above. const copilotKit = new CopilotBackend({ actions: actions, }); // Use the CopilotBackend instance to generate a response for the incoming request using an OpenAIAdapter. return copilotKit.response(req, new OpenAIAdapter()); } ``` **將部落格平台與 CopilotKit 前端集成** --------------------------- 在本節中,我將引導您完成將部落格平台與 CopilotKit 前端整合的過程,以促進部落格文章研究和文章大綱生成。我們將使用聊天機器人側欄元件、copilot 文字區域元件、用於向 Copilot 提供應用程式狀態和其他資訊的 useMakeCopilotReadable 掛鉤,以及用於提供 Copilot 可以呼叫的操作的 useCopilotAction 掛鉤 首先,導入`/[root]/src/app/components/Article.tsx`檔案頂部的`useMakeCopilotReadable` 、 `useCopilotAction` 、 `CopilotTextarea`和`HTMLCopilotTextAreaElement`掛鉤。 ``` import { useMakeCopilotReadable, useCopilotAction, } from "@copilotkit/react-core"; import { CopilotTextarea, HTMLCopilotTextAreaElement, } from "@copilotkit/react-textarea"; ``` 在 Article 函數內的狀態變數下方,新增以下程式碼,該程式碼使用`useMakeCopilotReadable`掛鉤來新增將作為應用程式內聊天機器人的上下文產生的文章大綱。鉤子使副駕駛可以閱讀文章大綱。 ``` useMakeCopilotReadable("Blog article outline: " + JSON.stringify(articleOutline)); ``` 在`useMakeCopilotReadable`掛鉤下方,使用以下程式碼建立一個名為`copilotTextareaRef`的引用,該引用指向名為`HTMLCopilotTextAreaElement`的文字區域元素。 ``` const copilotTextareaRef = useRef<HTMLCopilotTextAreaElement>(null); ``` 在上面的程式碼下方,加入以下程式碼,該程式碼使用`useCopilotAction`掛鉤來設定名為`researchBlogArticleTopic`的操作,該操作將啟用對部落格文章的給定主題的研究。此操作採用兩個參數,稱為`articleTitle`和`articleOutline` ,這兩個參數可以產生文章標題和大綱。 該操作包含一個處理程序函數,該函數根據給定主題生成文章標題和大綱。在處理函數內部, `articleOutline`狀態會使用新產生的大綱進行更新,而`articleTitle`狀態會使用新產生的標題進行更新,如下所示。 ``` useCopilotAction( { name: "researchBlogArticleTopic", description: "Research a given topic for a blog article.", parameters: [ { name: "articleTitle", type: "string", description: "Title for a blog article.", required: true, }, { name: "articleOutline", type: "string", description:"Outline for a blog article that shows what the article covers.", required: true, }, ], handler: async ({ articleOutline, articleTitle }) => { setArticleOutline(articleOutline); setArticleTitle(articleTitle); }, }, [] ); ``` 在上面的程式碼下方,前往表單元件並新增以下`CopilotTextarea`元素,該元素將使您能夠為文章內容新增補全、插入和編輯。 ``` <CopilotTextarea value={copilotText} ref={copilotTextareaRef} placeholder="Write your article content here" onChange={(event) => setCopilotText(event.target.value)} className="p-4 w-full aspect-square font-bold text-xl bg-slate-800 text-white rounded-lg resize-none" placeholderStyle={{ color: "white", opacity: 0.5, }} autosuggestionsConfig={{ textareaPurpose: articleTitle, chatApiConfigs: { suggestionsApiConfig: { forwardedParams: { max_tokens: 5, stop: ["\n", ".", ","], }, }, insertionApiConfig: {}, }, debounceTime: 250, }} /> ``` 然後將Tailwindcss隱藏類別加入文章內容的Textarea中,如下所示。文字區域將保存文章的內容,並在文章發布後將其插入資料庫。 ``` {/* Textarea for article content */} <textarea className="p-4 w-full aspect-square font-bold text-xl bg-slate-800 text-white rounded-lg resize-none hidden" id="content" name="content" value={copilotText} placeholder="Write your article content here" onChange={(event) => setCopilotText(event.target.value)} /> ``` 之後,請前往`/[root]/src/app/writearticle/page.tsx`檔案並使用下面的程式碼匯入頂部的 CopilotKit 前端套件和樣式。 ``` import { CopilotKit } from "@copilotkit/react-core"; import { CopilotSidebar } from "@copilotkit/react-ui"; import "@copilotkit/react-ui/styles.css"; import "@copilotkit/react-textarea/styles.css"; ``` 然後使用`CopilotKit`和`CopilotSidebar`包裹Article元件,如下所示。 `CopilotKit`元件指定 CopilotKit 後端端點 ( `/api/copilotkit/openai/` ) 的 URL,而`CopilotSidebar`則呈現應用程式內聊天機器人,您可以提示您研究文章的任何主題。 ``` export default function WriteArticle() { return ( <> <Header /> <CopilotKit url="/api/copilotkit"> <CopilotSidebar instructions="Help the user research a blog article topic." defaultOpen={true} labels={{ title: "Blog Article Copilot", initial: "Hi you! 👋 I can help you research any topic for a blog article.", }} clickOutsideToClose={false}> <Article /> </CopilotSidebar> </CopilotKit> </> ); } ``` 之後,執行開發伺服器並導航到 http://localhost:3000/writearticle。您應該會看到應用程式內聊天機器人已整合到部落格平台中。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yx7m6fhxm9gdg942a0sq.png) 給右側的聊天機器人一個提示,例如“研究一篇關於生成人工智慧的部落格文章主題,然後給我文章大綱。”聊天機器人將開始研究該主題,然後產生部落格標題。 當您開始在編輯器上寫作時,您應該會看到內容自動建議,如下所示。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ocnhptqxnk5gopvlzfs8.png) **將部落格平台與 Supabase 資料庫集成** -------------------------- 在本節中,我將引導您完成將部落格平台與 Supabase 資料庫整合以插入和獲取部落格文章資料的過程。 首先,導覽至[supabase.com](http://supabase.com)並點擊主頁上的「啟動您的專案」按鈕。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/95n06a6aj55r5w959gz6.png) 然後新建一個專案,名為AiBloggingPlatform,如下圖所示。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lifhztowgy3g1v9wwnjk.png) 建立專案後,將 Supabase URL 和 API 金鑰新增至 env.local 檔案中的環境變數中,如下所示。 ``` NEXT_PUBLIC_SUPABASE_URL=”Your Supabase URL” NEXT_PUBLIC_SUPABASE_ANON_KEY=”Your Supabase API Key” ``` 之後,請前往 Supabase 上專案的儀表板並開啟 SQL 編輯器部分。然後將下列 SQL 程式碼新增至編輯器中,然後按一下 CTRL + Enter 鍵建立一個名為articles 的表。文章表包含 id、標題和內容行。 ``` create table if not exists articles ( id bigint primary key generated always as identity, title text, content text ); ``` 建立表格後,您應該會收到一條成功訊息,如下所示。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bjb84czwivk6ue7duj0b.png) 之後,轉到`/[root]/src/`資料夾並建立一個名為`utils`的資料夾。在`utils`資料夾內,建立一個名為`supabase.ts`文件,並新增以下用於建立並傳回 Supabase 用戶端的程式碼。 ``` // Importing necessary functions and types from the Supabase SSR package import { createServerClient, type CookieOptions } from '@supabase/ssr' // Define a function named 'supabase' that takes a 'CookieOptions' object as input export const supabase = (cookies: CookieOptions) => { // Retrieve cookies from the provided 'CookieOptions' object const cookieStore = cookies() // Create and return a Supabase client configured with environment variables and cookie handling return createServerClient( // Retrieve Supabase URL from environment variables process.env.NEXT_PUBLIC_SUPABASE_URL!, // Retrieve Supabase anonymous key from environment variables process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!, { cookies: { // Define a custom 'get' function to retrieve cookies by name from the cookie store get(name: string) { return cookieStore.get(name)?.value }, }, } ) } ``` 然後轉到`/[root]/src/app`資料夾並建立一個名為`serveractions`的資料夾。在`serveractions`資料夾中,建立一個名為`AddArticle.ts`的文件,並新增以下程式碼,將部落格文章資料插入到 Supabase 資料庫中。 ``` // Importing necessary functions and modules for server-side operations "use server"; import { createServerComponentClient } from "@supabase/auth-helpers-nextjs"; import { cookies } from "next/headers"; import { redirect } from "next/navigation"; // Define an asynchronous function named 'addArticle' that takes form data as input export async function addArticle(formData: any) { // Extract title and content from the provided form data const title = formData.get("title"); const content = formData.get("content"); // Retrieve cookies from the HTTP headers const cookieStore = cookies(); // Create a Supabase client configured with the provided cookies const supabase = createServerComponentClient({ cookies: () => cookieStore }); // Insert the article data into the 'articles' table on Supabase const { data, error } = await supabase.from("articles").insert([ { title, content, }, ]); // Check for errors during the insertion process if (error) { console.error("Error inserting data", error); return; } // Redirect the user to the home page after successfully adding the article redirect("/"); // Return a success message return { message: "Success" }; } ``` 之後,轉到`/[root]/src/app/components/Article.tsx`檔案並導入`addArticle`函數。 ``` import { addArticle } from "../serveractions/AddArticle"; ``` 然後加入`addArticle`函數作為表單動作參數,如下所示。 ``` // Form element for article input <form action={addArticle} className="w-full h-full gap-10 flex flex-col items-center p-10"> </form> ``` 之後,導覽至http://localhost:3000/writearticle,研究您選擇的主題,新增文章內容,然後點擊底部的發布按鈕來發布文章。 然後轉到 Supabase 上專案的儀表板並導航到表編輯器部分。您應該會看到您的文章資料已插入 Supabase 資料庫,如下所示。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fklcuyv5q5eq1ajmdjyv.png) 接下來,前往`/[root]/src/app/page.tsx`檔案並在頂部導入 cookie 和 supabase 套件。 ``` import { cookies } from "next/headers"; import { supabase } from "@/utils/supabase"; ``` 然後在 Home 函數中加入以下程式碼,從 Supabase 資料庫中取得文章資料。 ``` const { data: articles, error } = await supabase(cookies).from('articles').select('*') ``` 之後,更新如下所示的元素程式碼,以將已發佈的文章呈現在部落格平台主頁上。 ``` return ( <> <Header /> <div className="max-w-[85rem] h-full px-4 py-10 sm:px-6 lg:px-8 lg:py-14 mx-auto"> <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-6"> {articles?.map((post: any) => ( <Link key={post.id} className="group flex flex-col h-full bg-white border border-gray-200 hover:border-transparent hover:shadow-lg transition-all duration-300 rounded-xl p-5 " href={`/posts/${post.id}`}> <div className="aspect-w-16 aspect-h-11"> <Image className="object-cover h-48 w-96 rounded-xl" src={`https://source.unsplash.com/featured/?${encodeURIComponent( post.title )}`} width={500} height={500} alt="Image Description" /> </div> <div className="my-6"> <h3 className="text-xl font-semibold text-gray-800 "> {post.title} </h3> </div> </Link> ))} </div> </div> </> ); ``` 然後導航到[http://localhost:3000](http://localhost:3000/writearticle) ,您應該會看到您發布的文章,如下所示。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/429bilwyje2a4xh0il5n.png) 之後,轉到`/[root]/src/app`資料夾並建立一個名為`[id].`在`[id]`資料夾中,建立一個名為`page.tsx`的文件,並在頂部匯入以下套件和元件。 ``` import { supabase } from '@/utils/supabase'; import { cookies } from "next/headers"; import Header from '@/app/components/Header'; ``` 在導入下面,定義一個名為「getArticles」的非同步函數,該函數根據 id 參數從 supabase 資料庫檢索文章資料,如下所示。 ``` // Define an asynchronous function named 'getArticles' that retrieves article data based on the provided parameters async function getArticles(params: any) { // Extract the 'id' parameter from the provided 'params' object const { id } = params // Retrieve article data from Supabase database where the 'id' matches the provided value const { data, error } = await supabase(cookies) .from('articles') .select('*') .eq('id', id) .single(); // Return the retrieved data return data } ``` 在上面的程式碼下面,定義一個名為“Post”的函數,它將“params”作為 props,如下所示。 ``` // Define a default asynchronous function named 'Post' that takes 'params' as props export default async function Post({ params }: { params: any }) { // Retrieve the post data asynchronously based on the provided 'params' const post = await getArticles(params); // Return JSX to render the post details return ( <> {/* Render the header component */} <Header /> {/* Main content wrapper */} <div className="max-w-3xl px-4 pt-6 lg:pt-10 pb-12 sm:px-6 lg:px-8 mx-auto"> <div className="max-w-2xl"> <div className="space-y-5 md:space-y-8"> <div className="space-y-3"> {/* Render the post title */} <h2 className="text-2xl font-bold md:text-3xl dark:text-white"> {/* Render the post title only if 'post' is truthy */} {post && post.title} </h2> {/* Render the post content */} <p className="text-lg text-gray-800 dark:text-gray-200"> {/* Render the post content only if 'post' is truthy */} {post && post.content} </p> </div> </div> </div> </div> </> ); } ``` 之後,導覽至[http://localhost:3000](http://localhost:3000/writearticle)並點擊部落格平台主頁上顯示的文章。 然後您應該被重定向到文章的內容,如下所示。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ojie4iwb8qn56gd2a907.png) 結論 -- 總而言之,您可以使用 CopilotKit 建立應用內 AI 聊天機器人,該機器人可以查看當前應用程式狀態並在應用程式內執行操作。 AI 聊天機器人可以與您的應用程式前端、後端和第三方服務對話。 完整的原始碼:https://github.com/TheGreatBonnie/aipoweredblog --- 原文出處:https://dev.to/copilotkit/how-to-build-an-ai-powered-blogging-platform-nextjs-langchain-supabase-1hdp

使用 useReducer 和 Typescript 回應上下文。

--- 標題:使用 useReducer 和 Typescript 反應上下文。 發表:真實 說明:將 React Context API 與強類型化的縮減器和操作一起使用。 標籤: typescript、react、上下文、reducers --- [只是程式碼嗎?](https://codesandbox.io/s/context-reducer-ts-9ctis) React 應用程式中有很多處理狀態的選項。顯然你可以使用`setState`來處理一些小的邏輯,但是如果你有一個複雜的狀態需要管理怎麼辦? 也許您會使用 Redux 或 MobX 來處理這種情況,但也可以選擇使用 React Context,並且您不必安裝其他依賴項。 讓我們看看如何使用 Context API 和 Typescript 來管理複雜的狀態。 > 在本教程中,我們將建立一個帶有購物車計數器的產品清單。 首先,使用`create-react-app`建立一個新的 React 專案。 ``` npx create-react-app my-app --template typescript cd my-app/ ``` 接下來,在`src`目錄中建立一個新的`context.tsx`檔案。 ``` /*context.tsx*/ import React, { createContext } from 'react'; const AppContext = createContext({}); ``` 您可以使用任何您想要的值來初始化上下文 api,就這麼簡單,在本例中,我使用的是一個空物件。 現在讓我們建立一個初始狀態,其中產品清單為零,購物車計數器為零。另外,讓我們為此加入一些類型。 ``` /*context.tsx*/ import React, { createContext } from 'react'; type ProductType = { id: number; name: string; price: number; } type InitialStateType = { products: ProductType[]; shoppingCart: number; } const initialState = { products: [], shoppingCart: 0, } const AppContext = createContext<InitialStateType>(initialState); ``` 產品清單中的每個產品都有一個 ID、名稱和價格。 現在我們將使用減速器和操作來建立和刪除產品,並將購物車計數器加一。首先,建立一個名為`reducers.ts`的新檔案。 ``` /*reducers.ts*/ export const productReducer = (state, action) => { switch (action.type) { case 'CREATE_PRODUCT': return [ ...state, { id: action.payload.id, name: action.payload.name, price: action.payload.price, } ] case 'DELETE_PRODUCT': return [ ...state.filter(product => product.id !== action.payload.id), ] default: return state; } } export const shoppingCartReducer = (state, action) => { switch (action.type) { case 'ADD_PRODUCT': return state + 1; } } ``` 一個reducer函數接收兩個參數,第一個是狀態,我們在使用`useReducer`鉤子時傳遞,第二個是一個物件,表示事件和一些將改變狀態(動作)的資料。 在本例中,我們建立兩個減速器,一個用於產品,另一個用於購物車。在產品縮減器上,我們新增了兩個操作,一個用於建立新產品,另一個用於刪除任何產品。對於購物車減速器,我們加入的唯一操作是每次加入新產品時增加計數器。 正如您所看到的,為了建立產品,我們傳遞 id、名稱和價格,並使用新物件返回當前狀態。要刪除一個,我們只需要 id ,返回的是狀態,但沒有具有該 id 的產品。 現在讓我們更改上下文文件以導入這些減速器函數。 ``` /*context.tsx*/ import React, { createContext, useReducer } from 'react'; import { productReducer, shoppingCartReducer } from './reducers'; type ProductType = { id: number; name: string; price: number; } type InitialStateType = { products: ProductType[]; shoppingCart: number; } const intialState = { products: [], shoppingCart: 0, } const AppContext = createContext<{ state: InitialStateType; dispatch: React.Dispatch<any>; }>({ state: initialState, dispatch: () => null }); const mainReducer = ({ products, shoppingCart }, action) => ({ products: productReducer(products, action), shoppingCart: shoppingCartReducer(shoppingCart, action), }); const AppProvider: React.FC = ({ children }) => { const [state, dispatch] = useReducer(mainReducer, initialState); return ( <AppContext.Provider value={{state, dispatch}}> {children} </AppContext.Provider> ) } export { AppContext, AppProvider }; ``` 有一個`mainReducer`函數,它結合了我們將擁有的兩個減速器(產品減速器和購物車減速器),每個減速器管理狀態的選定部分。 此外,我們建立了`AppProvider`元件,在其中, `useReducer`鉤子採用`mainReducer`和初始狀態來傳回`state`和`dispatch` 。 我們將這些值傳遞到`AppContext.Provider`中,這樣做我們可以使用`useContext`鉤子存取`state`和`dispatch` 。 接下來,為減速器和操作加入這些類型。 ``` /*reducers.ts*/ type ActionMap<M extends { [index: string]: any }> = { [Key in keyof M]: M[Key] extends undefined ? { type: Key; } : { type: Key; payload: M[Key]; } }; export enum Types { Create = 'CREATE_PRODUCT', Delete = 'DELETE_PRODUCT', Add = 'ADD_PRODUCT', } // Product type ProductType = { id: number; name: string; price: number; } type ProductPayload = { [Types.Create] : { id: number; name: string; price: number; }; [Types.Delete]: { id: number; } } export type ProductActions = ActionMap<ProductPayload>[keyof ActionMap<ProductPayload>]; export const productReducer = (state: ProductType[], action: ProductActions | ShoppingCartActions) => { switch (action.type) { case Types.Create: return [ ...state, { id: action.payload.id, name: action.payload.name, price: action.payload.price, } ] case Types.Delete: return [ ...state.filter(product => product.id !== action.payload.id), ] default: return state; } } // ShoppingCart type ShoppingCartPayload = { [Types.Add]: undefined; } export type ShoppingCartActions = ActionMap<ShoppingCartPayload>[keyof ActionMap<ShoppingCartPayload>]; export const shoppingCartReducer = (state: number, action: ProductActions | ShoppingCartActions) => { switch (action.type) { case Types.Add: return state + 1; default: return state; } } ``` 我從這篇[文章](https://medium.com/hackernoon/finally-the-typescript-redux-hooks-events-blog-you-were-looking-for-c4663d823b01)中採用了這種方法,基本上我們正在檢查使用了哪個`action.type` ,並根據該方法,我們產生有效負載的類型。 --- **筆記** 您可以採取的另一種方法是使用像這樣的`Discriminated unions` 。 ``` type Action = | { type: 'ADD' } | { type: 'CREATE', create: object } | { type: 'DELETE', id: string }; ``` 在前面的程式碼中,所有這些類型都有一個稱為 type 的公共屬性。 Typescript 將為可區分的聯合建立類型保護,並讓我們現在根據我們正在使用的類型以及物件類型具有的其他屬性。 但在本教程中,我們為操作`type`和`payload`使用兩個常見屬性,並且`payload`物件類型會根據`type`而變化,因此可區分的聯合類型將無法運作。 --- 現在,讓我們將定義的類型匯入到`context`文件中。 ``` /*context.tsx*/ import React, { createContext, useReducer, Dispatch } from 'react'; import { productReducer, shoppingCartReducer, ProductActions, ShoppingCartActions } from './reducers'; type ProductType = { id: number; name: string; price: number; } type InitialStateType = { products: ProductType[]; shoppingCart: number; } const initialState = { products: [], shoppingCart: 0, } const AppContext = createContext<{ state: InitialStateType; dispatch: Dispatch<ProductActions | ShoppingCartActions>; }>({ state: initialState, dispatch: () => null }); const mainReducer = ({ products, shoppingCart }: InitialStateType, action: ProductActions | ShoppingCartActions) => ({ products: productReducer(products, action), shoppingCart: shoppingCartReducer(shoppingCart, action), }); const AppProvider: React.FC = ({ children }) => { const [state, dispatch] = useReducer(mainReducer, initialState); return ( <AppContext.Provider value={{state, dispatch}}> {children} </AppContext.Provider> ) } export { AppProvider, AppContext }; ``` 不要忘記用`AppProvider`包裝您的主要元件。 ``` /* App.tsx */ import React from 'react'; import { AppProvider } from './context'; import Products from './products'; const App = () => { <AppProvider> // your stuff <Products /> </AppProvider> } export default App ``` 建立一個`Products`元件並在其中加入以下程式碼。 ``` /* Products.tsx */ import React, { useContext } from 'react'; import { AppContext } from './context'; import { Types } from './reducers'; const Products = () => { const { state, dispatch } = useContex(AppContext); return ( <div> <button onClick={() => { dispatch({ type: Types.Add, }) }}> click </button> {state.shoppingCart} </div> ) } export default Products; ``` 現在一切都是強類型的。 您可以[在此處](https://codesandbox.io/s/context-reducer-ts-9ctis)查看程式碼。 #### 來源。 https://medium.com/hackernoon/finally-the-typescript-redux-hooks-events-blog-you-were-looking-for-c4663d823b01 --- 原文出處:https://dev.to/elisealcala/react-context-with-usereducer-and-typescript-4obm

21 個正在改變世界的人工智慧工具

世界上充滿了有前景的人工智慧工具,如 Sora、ChatGPT 以及更多即將推出的工具。 我收集了一些你必須使用的令人興奮的人工智慧工具。 該清單包括 Devin AI 的開源替代品、Notion、5 秒內的語音克隆、電子郵件自動化軟體以及您從未聽說過的工具。好奇心超載! 別忘了給他們加星號🌟 讓我們涵蓋這一切! --- 1. [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 v3.1 版本](https://docs.taipy.io/en/latest/relnotes/)。 最新版本使得在 Taipy 的多功能零件物件中可視化任何 HTML 或 Python 物件成為可能。 這意味著[Folium](https://python-visualization.github.io/folium/latest/) 、 [Bokeh](https://bokeh.org/) 、 [Vega-Altair](https://altair-viz.github.io/)和[Matplotlib](https://matplotlib.org/)等程式庫現在可用於視覺化。 這也帶來了對[Plotly python](https://plotly.com/python/)的原生支持,使繪製圖表變得更加容易。 ![陰謀蟒蛇](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xdewvex88md09hvu3s80.png) 他們還使用分散式運算提高了效能,但最好的部分是 Taipy,它的所有依賴項現在都與 Python 3.12 完全相容,因此您可以在使用 Taipy 進行專案的同時使用最新的工具和程式庫。 您可以閱讀[文件](https://docs.taipy.io/en/latest/)。 例如,您可以看到[聊天演示](https://docs.taipy.io/en/release-3.1/gallery/llm/5_chatbot/),它使用 OpenAI 的 GPT-4 API 來產生對您的訊息的回應。您可以輕鬆更改程式碼以使用任何其他 API 或模型。 ![聊天演示](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kug1mclhmzyad0hjchif.png) 另一個有用的事情是,Taipy 團隊提供了一個名為[Taipy Studio](https://docs.taipy.io/en/latest/manuals/studio/)的 VSCode 擴充功能來加速 Taipy 應用程式的建置。 ![太皮工作室](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kc1umm5hcxes0ydbuspb.png) 您也可以使用 Taipy 雲端部署應用程式。 如果您想閱讀部落格來了解程式碼庫結構,您可以閱讀 HuggingFace[的使用 Taipy 在 Python 中為您的 LLM 建立 Web 介面](https://huggingface.co/blog/Alex1337/create-a-web-interface-for-your-llm-in-python)。 嘗試新技術通常很困難,但 Taipy 提供了[10 多個演示教程,](https://docs.taipy.io/en/release-3.1/gallery/)其中包含程式碼和適當的文件供您遵循。 例如,一些現場演示範例和專案想法: - [新冠儀表板](https://covid-dashboard.taipy.cloud/Country) - [推文生成](https://tweet-generation.taipy.cloud/) - [資料視覺化](https://production-planning.taipy.cloud/Data-Visualization) - [即時人臉辨識](https://face-recognition.taipy.cloud/) - [國際象棋大師](https://github.com/KorieDrakeChaney/taipy-chess) Taipy 在 GitHub 上有 7k+ Stars,並且處於`v3`版本,因此它們正在不斷改進。 https://github.com/Avaiga/taipy Star Taipy ⭐️ --- 2. [PR Agent](https://github.com/Codium-ai/pr-agent) - 自動拉取請求分析、回饋、建議的工具。 ------------------------------------------------------------------------- ![公關代理](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6sq9u9ktdhdu4pax9u7i.gif) 這是一個開源工具,可幫助有效地審查和處理拉取請求。它有許多獨特的選項,並提供跨各種 git 提供者的廣泛的拉取請求功能。 每天有數百萬個開源專案和數百個 Pull 請求,因此有一個可以幫助您的朋友是非常好的事情。 我是開源維護者,所以我知道有時會變得多麼困難,特別是每天都要審查這麼多的 Pull 請求。 無論如何,這就是公關代理商的幕後工作方式。 ![建築學](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0kkd9vxxqhu99f2elv8c.png) 您必須使用`@CodiumAI-Agent /review`對拉取請求發表評論,代理商將透過對 PR 的審查進行回應。有很多可用的選項,例如`describe`和`improve` 。 他們也提供了 [PR-Agent 工具](https://pr-agent-docs.codium.ai/tools/),每個頁面都有一個專門的頁面來解釋如何使用它。 您可以閱讀[文件](https://pr-agent-docs.codium.ai/installation/)並查看[範例結果](https://github.com/Codium-ai/pr-agent?tab=readme-ov-file#example-results)。 最好的部分是您甚至可以將其作為[GitHub Action](https://pr-agent-docs.codium.ai/installation/github/#run-as-a-github-action)執行。他們還提供了一個專業版本,有更多的選擇,但免費套餐足以開始使用。 如果您正在尋找好的文章,我推薦[使用 CodiumAI PR-Agent 自動進行拉取請求審查和](https://rnemet.dev/posts/ai/codium-pragent/)[CodiumAI PR-Agent 讓開發人員的生活更輕鬆的 5 個原因](https://medium.com/@mengineer/5-reasons-why-codiumai-pr-agent-is-making-developers-lives-easier-e040be0f6a36)。這些提供了有關 PR Agent 的大量概述。 它們在 GitHub 上有大約 3800 個 Star,被 300 多名開發人員使用,並且是使用 Python 建構的。雖然它們可能不是非常受歡迎,但它們的用例非常好。 https://github.com/Codium-ai/pr-agent 明星公關代理人 ⭐️ --- 3. [Mintlify](https://github.com/mintlify/writer) - 在建置時出現的文件。 -------------------------------------------------------------- ![精簡](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gvk07kmn8p48cpssogov.png) Mintlify 是一款由人工智慧驅動的文件編寫器,您只需 1 秒鐘即可編寫程式碼文件 :D 幾個月前我發現了 Mintlify,從那時起我就一直是它的粉絲。我見過很多公司使用它,甚至我使用我的商務電子郵件產生了完整的文件,結果證明這是非常簡單和體面的。如果您需要詳細的文件,Mintlify 就是解決方案。 另一個用例是根據我們將在這裡討論的程式碼產生文件。 您可以安裝[VSCode 擴充功能](https://marketplace.visualstudio.com/items?itemName=mintlify.document)或將其安裝在[IntelliJ](https://plugins.jetbrains.com/plugin/18606-mintlify-doc-writer)上。 您只需突出顯示程式碼或將遊標放在要記錄的行上。然後點選「編寫文件」按鈕(或按 ⌘ + 。) 您可以閱讀[文件](https://github.com/mintlify/writer?tab=readme-ov-file#%EF%B8%8F-mintlify-writer)和[安全指南](https://writer.mintlify.com/security)。 如果您更喜歡教程,那麼您可以觀看[Mintlify 的工作原理](https://www.loom.com/embed/3dbfcd7e0e1b47519d957746e05bf0f4)。它支援 10 多種程式語言,並支援許多文件字串格式,例如 JSDoc、reST、NumPy 等。 順便說一句,他們的網站連結是[writer.mintlify.com](https://writer.mintlify.com/) ;回購協議中目前的似乎是錯誤的。 它在 GitHub 上有大約 2.4k 顆星,受到許多開發人員的喜愛,並且是使用 TypeScript 建構的。 https://github.com/mintlify/writer Star Mintlify ⭐️ --- 4.[螢幕截圖到程式碼](https://github.com/abi/screenshot-to-code)- 放入螢幕截圖並將其轉換為乾淨的程式碼。 --------------------------------------------------------------------------- ![截圖到程式碼](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5akiyz5telxqqsj32ftu.png) 這是一個非常受歡迎的開源專案,但我可以肯定地說,很多開發人員仍然沒有意識到這一點。使用此功能,您可以將使用者介面的建置速度提高 10 倍。 這是一個簡單的工具,可以使用 AI 將螢幕截圖、模型和 Figma 設計轉換為乾淨、實用的程式碼。 該應用程式有一個 React/Vite 前端和一個 FastAPI 後端。如果您想使用 Claude Sonnet 或實驗性視訊支持,您將需要一個能夠存取 GPT-4 Vision API 的 OpenAI API 金鑰或一個 Anthropic 金鑰。您可以閱讀[指南](https://github.com/abi/screenshot-to-code?tab=readme-ov-file#-getting-started)來開始。 您可以在託管版本上[即時試用](https://screenshottocode.com/),並觀看 wiki 上提供的[一系列演示影片](https://github.com/abi/screenshot-to-code/wiki/Screen-Recording-to-Code)。 他們在 GitHub 上擁有超過 47k 顆星星,並支援許多技術堆疊,例如 React 和 Vue,以及不錯的 AI 模型,例如 GPT-4 Vision、Claude 3 Sonnet 和 DALL-E 3。 https://github.com/abi/screenshot-to-code 將螢幕截圖轉為程式碼 ⭐️ --- 5. [FaceSwap](https://github.com/deepfakes/faceswap) - 適合所有人的 Deepfakes 軟體。 --------------------------------------------------------------------------- ![換臉](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ps8nidwchglscdrk0117.png) 我總是對 Deepfakes 著迷,因為這就是某些人工智慧的工作原理,尤其是使用影片的人工智慧。 相信我!我們中的許多人甚至不使用它來建立影片,我們只是修改程式碼來看看它的作用,不道德的使用並不能代表它的建立原因、我們現在如何使用它,或者我們對它的未來的看法。 您應該觀看此影片以了解電腦如何辨識臉!觀看[此影片](https://www.youtube.com/watch?v=aircAruvnKk)以了解神經網路的基本功能。 https://www.youtube.com/watch?v=R9OHn5ZF4Uo 您可以閱讀[INSTALL.md](https://github.com/deepfakes/faceswap/blob/master/INSTALL.md)以取得詳細的安裝指南。根據文件,您需要具有 CUDA 支援的現代 GPU 才能獲得最佳效能。許多 AMD GPU 透過 DirectML (Windows) 和 ROCm (Linux) 支援。 您可以閱讀<a href="">文件</a>、觀看[演示影片](https://www.dailymotion.com/video/x810mot)並存取他們的[部落格](https://faceswap.dev/blog/)以觀看具有其他用例的會議影片。 我最喜歡的事實是,他們有一個非常簡單的部分,介紹任何人如何為該專案做出貢獻,包括對生成模型感興趣的人、開發人員、非開發高級用戶、最終用戶,當然還有討厭者:) 他們在 GitHub 上有 48k+ Stars,這使得他們足夠可信。 https://github.com/deepfakes/faceswap 明星 FaceSwap ⭐️ --- 6. [Amica](https://github.com/semperai/amica) - 讓您可以在瀏覽器中輕鬆地與 3D 角色聊天。 ---------------------------------------------------------------------- ![朋友](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2nvizcn717h3cteocft5.png) Amica 是一個開源接口,用於透過語音合成和語音辨識與 3D 角色進行互動式通訊。 您可以匯入 VRM 文件,調整聲音以適合角色,並產生包含情緒表達的回應文字。 他們使用 Three.js、OpenAI、Whisper、Bakllava 等進行視覺處理。您可以閱讀[Amica 的工作原理](https://docs.heyamica.com/overview/how-amica-works)及其所涉及的[核心概念](https://docs.heyamica.com/overview/core-concepts)。 您可以克隆該存儲庫並使用它來[開始](https://docs.heyamica.com/getting-started/installation)。 ``` npm i npm run dev ``` 您可以閱讀[文件](https://docs.heyamica.com/)並查看[演示](https://amica.arbius.ai/),這真是太棒了:D ![示範](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/92iv9y2auly6tvenee82.png) 您可以觀看這段簡短的影片,了解它的功能。 https://www.youtube.com/watch?v=hUxAEnFiXH8 Amica 使用 Tauri 建立桌面應用程式。 他們在 GitHub 上有 400+ Stars,而且看起來非常容易使用。 https://github.com/semperai/amica Star Amica ⭐️ --- 7. [Bark](https://github.com/suno-ai/bark) - 文字提示的生成音訊模型。 --------------------------------------------------------- ![吠](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pt8h5filcsk9pcxsx0ky.png) Bark 是 Suno 建立的基於轉換器的文本到音訊模型。 Bark 可以產生高度逼真的多語言語音以及其他音訊 - 包括音樂、背景噪音和簡單的音效。 該模型還可以產生非語言交流,如笑、嘆息和哭泣。哇! 它擁有 MIT 許可證,這意味著它現在可用於商業用途。 Bark 支援超過 100 種語言的揚聲器預設。您可以[在此處](https://suno-ai.notion.site/8b8e8749ed514b0cbf3f699013548683?v=bc67cff786b04b50b3ceb756fd05f68c)查看支援的語音預設庫。 根據文件,Bark 嘗試匹配給定預設的語氣、音高、情緒和韻律,但目前不支援自訂語音複製。該模型還嘗試保留音樂、環境噪音等。這超出了任何人的需要。 您可以這樣使用它。如果您想將其與 Transformers 庫一起使用,請閱讀[本文](https://github.com/suno-ai/bark?tab=readme-ov-file#-transformers-usage)。 ``` from bark import SAMPLE_RATE, generate_audio, preload_models from scipy.io.wavfile import write as write_wav from IPython.display import Audio # download and load all models preload_models() # generate audio from text text_prompt = """ Hello, my name is Suno. And, uh — and I like pizza. [laughs] But I also have other interests such as playing tic tac toe. """ audio_array = generate_audio(text_prompt) # save audio to disk write_wav("bark_generation.wav", SAMPLE_RATE, audio_array) # play text in notebook Audio(audio_array, rate=SAMPLE_RATE) ``` Bark 開箱即用支援各種語言,並自動根據輸入文字確定語言。當提示使用程式碼轉換文字時,Bark 將嘗試使用相應語言的本地口音。 您可以在[Google Colab](https://colab.research.google.com/drive/1eJfA2XUa-mXwdMy7DoYKVYHI1iTd9Vkt?usp=sharing) & [Replicate](https://replicate.com/suno-ai/bark)閱讀<a href="">文件</a>並查看演示。 您也可以在筆記本部分閱讀有關語音一致性增強和其他形式的[範例](https://github.com/suno-ai/bark/tree/main/notebooks)。 ![聲音](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zirh2dimya9yt8p0e7ry.png) 它們支援多種語言,如英語、印地語、德語、法語等。 他們在 GitHub 上擁有 30k+ Stars,並且經營超過 300,000 人的社區,這使他們成為值得選擇的選擇。 https://github.com/suno-ai/bark 星樹 ⭐️ --- 8. [GPTDiscord](https://github.com/Kav-K/GPTDiscord) - Discord 的一體化 GPT 介面。 --------------------------------------------------------------------------- ![概述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kknaijkgi2rr7b0kefo7.png) 我是 Discord 上多個社群的成員,具有出色用例的機器人可以改善整體最終用戶體驗。 這個機器人的功能與 ChatGPT 網路相當,甚至在某些事情上做得更好! 它們支援一切,從多模態圖像理解、程式碼解釋、高級資料分析、文件問答、與 Wolfram Alpha 的網路連接聊天和 Google 存取、AI 審核、使用 DALL-E 生成圖像等等! 您可以閱讀 GPTDiscord 的所有高效[功能](https://github.com/Kav-K/GPTDiscord?tab=readme-ov-file#features)。 您可以閱讀[安裝指南](https://github.com/Kav-K/GPTDiscord/blob/main/detailed_guides/INSTALLATION.md)。 您可以查看[螢幕截圖](https://github.com/Kav-K/GPTDiscord?tab=readme-ov-file#screenshots)並查看不同目的的[詳細指南](https://github.com/Kav-K/GPTDiscord/tree/main/detailed_guides)清單。 他們在 GitHub 上有大約 1.8k+ Stars,而且肯定在進步。 https://github.com/Kav-K/GPTDiscord 星 GPTDiscord ⭐️ --- 9. [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/9vyo1eqfz3hh0rg3lmkz.png) ![高級](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a4qq1wm3wey3vihn9al4.png) 透過最先進的人工智慧,Upscayl 可以幫助您將低解析度影像變成高解析度。清脆又鋒利! 您可以閱讀[安裝指南](https://github.com/upscayl/upscayl?tab=readme-ov-file#-installation),並查看 Upscayl 之前/之後的[比較](https://github.com/upscayl/upscayl/blob/main/COMPARISONS.MD)。 ![比較](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3f14g2vv58ljhayluh8l.png) 它在 GitHub 上有 23k+ Stars,並且基於 TypeScript 建置。 https://github.com/upscayl/upscayl 明星 Upscayl ⭐️ --- 10. [AppFlowy](https://github.com/AppFlowy-IO/AppFlowy) - Notion 的開源替代品。 ------------------------------------------------------------------------ ![應用程式串流](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dovisje3bh7ec1h9uqau.png) AppFlowy 是一個由人工智慧驅動的安全工作空間,類似於您在不失去資料控制的情況下實現更多目標的概念。 ![產品](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ul096wqbsxrs8shvwp6c.png) 他們還提供行動應用程式,這是一個優點。 您可以閱讀[文件](https://docs.appflowy.io/docs)並了解[安裝方法](https://docs.appflowy.io/docs/appflowy/install-appflowy/installation-methods)。 他們還支援[使用 Supabase 自託管 AppFlowy](https://docs.appflowy.io/docs/guides/appflowy) 。對於喜歡 Supabase 功能或使用 Supabase 作為其基礎設施的用戶來說,這是理想的選擇。 您還應該檢查[此內容](https://docs.appflowy.io/docs/appflowy/product/data-storage)以了解有關資料儲存、Markdown、捷徑、主題、涉及的人工智慧和插件的更多資訊。 AppFlowy 在 GitHub 上擁有超過 47,000 顆星,發布了 64 個以上版本。 https://github.com/AppFlowy-IO/AppFlowy 明星 AppFlowy ⭐️ --- 11. [Leon](https://github.com/leon-ai/leon) - 您的開源個人助理。 ------------------------------------------------------- ![萊昂](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mnv85osce6ps9xodf07t.png) Leon 是一個開源個人助理,可以駐留在您的伺服器上。 當你要求他做事時,他就會做事。 你可以跟他說話,他也可以跟你說話。你也可以給他發短信,他也可以傳簡訊給你。如果您願意,Leon 可以透過離線方式與您溝通,以保護您的隱私。這是萊昂目前可以做的[技能](https://github.com/leon-ai/leon/tree/develop/skills)清單。 你應該讀一下[萊昂背後的故事](https://blog.getleon.ai/the-story-behind-leon/)。您還可以觀看此演示以了解有關 Leon 的更多資訊。 https://www.youtube.com/watch?v=p7GRGiicO1c ![特徵](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/70mddmgadcbfwzugd1bl.png) 這是Leon的高層架構模式。 ![建築學](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a6b9vgj3fagera0bsyur.png) 這是開始使用 npm 指令的方法。 ``` # install leon global cli npm install --global @leon-ai/cli # install leon leon create birth ``` 您可以閱讀[文件](https://docs.getleon.ai/)。 它在 GitHub 上擁有超過 14k 顆星,並且還在不斷增長。 https://github.com/leon-ai/leon 明星萊昂 ⭐️ --- 12. [n8n](https://github.com/n8n-io/n8n) - 工作流程自動化工具。 ----------------------------------------------------- ![n8n](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4pqsc84nhgj0b9dhfaxo.png) n8n 是一個可擴展的工作流程自動化工具。透過公平程式碼分發模型,n8n 將始終擁有可見的原始程式碼,可用於自託管,並允許您加入自訂函數、邏輯和應用程式。 ![n8n](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rxnp57kw5szbpj6mfs1p.png) n8n 基於節點的方法使其具有高度通用性,使您能夠將任何事物連接到任何事物。 有[400 多個集成選項](https://n8n.io/integrations),這幾乎是瘋狂的! 您可以看到所有[安裝](https://docs.n8n.io/choose-n8n/)選項,包括 Docker、npm 和自架。 開始使用以下命令。 ``` npx n8n ``` 此命令將下載啟動 n8n 所需的所有內容。然後,您可以透過開啟`http://localhost:5678`來存取 n8n 並開始建置工作流程。 在 YouTube 上觀看此[快速入門影片](https://www.youtube.com/watch?v=1MwSoB0gnM4)! https://www.youtube.com/watch?v=1MwSoB0gnM4 您可以閱讀[文件](https://docs.n8n.io/)並閱讀本[指南](https://docs.n8n.io/try-it-out/),以便根據您的需求快速開始。 他們還提供初學者和中級[課程,](https://docs.n8n.io/courses/)以便輕鬆學習。 他們在 GitHub 上有 39k+ Stars,並提供兩個包供整體使用。 https://github.com/n8n-io/n8n 明星 n8n ⭐️ --- 13. [Quivr](https://github.com/QuivrHQ/quivr) - 你的 GenAI 第二腦。 ------------------------------------------------------------- ![奎弗爾](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hl12fl88mdjmfkfath1t.png) Quivr,您的第二個大腦,利用 GenerativeAI 的力量成為您的私人助理!可以將其視為黑曜石,但增強了人工智慧功能。 ![統計資料](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5a27c2ubbmri0b2xlh1l.png) 您可以閱讀[安裝指南](https://github.com/QuivrHQ/quivr?tab=readme-ov-file#getting-started-)。 您可以閱讀[文件](https://docs.quivr.app/home/intro)並觀看[示範影片](https://github.com/QuivrHQ/quivr?tab=readme-ov-file#demo-highlights-)。 他們可以提供更好的免費套餐,但這足以在您端進行測試。 它在 GitHub 上擁有超過 30k 顆星,發布了 220 多個版本,這意味著它們正在不斷改進。 https://github.com/QuivrHQ/quivr Star Quivr ⭐️ --- 14. [meilisearch](https://github.com/meilisearch/meilisearch) - 適合您的應用程式、網站和工作流程的搜尋 API。 ---------------------------------------------------------------------------------------- ![搜尋](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s1rm66br9fbsa76n2e8i.png) Meilisearch 可協助您快速打造令人愉悅的搜尋體驗,提供開箱即用的功能來加快您的工作流程。 您一定看過可以使用`Ctrl + k`搜尋文件的軟體網站,例如 GitHub 或 Appwrite。那麼,meilisearch 可以幫助您實現相同的功能。 與 Algolia、Typesense 和 Elasticsearch 相比,這是唯一基於 Rust 建構的。您可以閱讀有關可用替代選項的[比較](https://www.meilisearch.com/docs/learn/what_is_meilisearch/comparison_to_alternatives):) Meilisearch 不應該是您的主要資料儲存。它是一個搜尋引擎,而不是一個資料庫。 Meilisearch 應僅包含您希望使用者搜尋的資料。如果您必須加入與搜尋無關的資料,請務必使這些字段不可搜尋,以提高相關性並縮短響應時間。 無論您是在開發網站還是應用程式,Meilisearch 都能提供直覺的即輸入即搜尋體驗,回應時間低於 50 毫秒。 他們提供[SDK 和庫,](https://www.meilisearch.com/docs/learn/what_is_meilisearch/sdks?utm_campaign=oss&utm_source=github&utm_medium=meilisearch&utm_content=sdks-link)用於 Meilsearch 和您喜歡的語言或框架之間的無縫整合。相信我,選擇的數量是瘋狂的。 他們還提供了一個[抓取工具](https://github.com/meilisearch/docs-scraper)來自動讀取文件內容並將其儲存到Meilisearch。 他們展示了許多[有用的功能](https://www.meilisearch.com/docs/learn/what_is_meilisearch/overview#features),例如即使查詢包含拼寫錯誤和拼寫錯誤(他們將其稱為`typo tolerance` ,您也可以獲得相關匹配。 有很多可用的選項,但讓我們看看如何使用 React 來做到這一點。 開始使用以下命令。 ``` yarn add react-instantsearch @meilisearch/instant-meilisearch # or npm install react-instantsearch @meilisearch/instant-meilisearch # or pnpm add react-instantsearch @meilisearch/instant-meilisearch ``` 您可以這樣使用它。 ``` import React from 'react'; import { InstantSearch, SearchBox, Hits, Highlight } from 'react-instantsearch'; import { instantMeiliSearch } from '@meilisearch/instant-meilisearch'; const { searchClient } = instantMeiliSearch( 'https://ms-adf78ae33284-106.lon.meilisearch.io', 'a63da4928426f12639e19d62886f621130f3fa9ff3c7534c5d179f0f51c4f303' ); const App = () => ( <InstantSearch indexName="steam-video-games" searchClient={searchClient} > <SearchBox /> <Hits hitComponent={Hit} /> </InstantSearch> ); const Hit = ({ hit }) => <Highlight attribute="name" hit={hit} />; export default App ``` 您可以查看此[codesandbox](https://codesandbox.io/p/sandbox/eager-dust-f98w2w)以取得詳細的範例以開始使用。 正如我所說,他們在幕後提供了很多東西。例如,您可以使用這些。 ``` npm install @meilisearch/autocomplete-client npm install @meilisearch/instant-meilisearch npm install meilisearch-docsearch ``` `meilisearch docsearch`的靈感來自 Algolia 搜尋文件元件。另外,非常詳細的文件以及每個 sdk 的範例和選項使它們成為人們的最愛。 您可以閱讀[文件](https://www.meilisearch.com/docs)並觀看[現場演示](https://where2watch.meilisearch.com/?utm_campaign=oss&utm_source=github&utm_medium=meilisearch&utm_content=demo-link)。 ![社區統計](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cxou5qe4p0va0h8r52ti.png) 他們在 GitHub 上有超過 42k 顆星,並且`v1.7`版本有 180 多個版本。 https://github.com/meilisearch/meilisearch 星 meilisearch ⭐️ --- 15.[收件匣清除](https://github.com/elie222/inbox-zero)- 幾分鐘內清理您的收件匣。 --------------------------------------------------------------- ![收件匣為零](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jz1krkg9btykpfoiuukd.png) 收件匣歸零是一款開源電子郵件應用程式,其目標是透過 AI 協助幫助您快速實現收件匣歸零。 它們得到了谷歌的批准,因此這是關注隱私的一個很好的部分。 ![經谷歌批准](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9fidgtozaj9y4feo4bbq.png) 它們使用 Postgres 作為資料庫,並基於 TypeScript 建置。 它們有一些瘋狂的功能,例如: > 您的電子郵件人工智慧助理 1. 人工智慧代理將讓您根據您提供的規則自動回覆、轉發或存檔電子郵件。 2. 他們的人工智慧計畫可以幫助你點擊接受或拒絕。一旦您確信人工智慧可以獨立工作,就可以開啟完全自動化。 3. 您可以用簡單的英語進行指導。就像與助手交談或向 ChatGPT 發送提示一樣簡單。 > 您可以自動封鎖冷電子郵件 您可以告訴「收件匣零」什麼對您來說構成冷郵件。它將根據您的指示阻止它們。 > 分析 了解收件匣是處理它的第一步。了解您的收件匣裡裝滿了什麼。它們還為您提供了立即採取行動的方法。 您可以閱讀核心[功能](https://github.com/elie222/inbox-zero?tab=readme-ov-file#key-features)並觀看[演示影片](https://github.com/elie222/inbox-zero?tab=readme-ov-file#demo-video)。您還可以查看他們的[看板](https://github.com/users/elie222/projects/1/views/1)以了解計劃內容。 他們在 GitHub 上擁有超過 1,500 個 Star,並且絕對值得更多。 https://github.com/elie222/inbox-zero 星收件匣零 ⭐️ --- 16. [Lively](https://github.com/rocksdanister/lively) - 允許使用者設定動畫桌面桌布和螢幕保護程式。 ----------------------------------------------------------------------------- ![活潑](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/60tld1a857herh12r5ci.png) 這只是為了好玩,我們可以使用程式碼學到很多關於它是如何完成的。 你可以看看這個[影片](https://www.pexels.com/video/blue-texture-abstract-leaves-7710243/),看看它看起來有多瘋狂。 ![風俗](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kb2ll571uc2jd2xrpmph.png) 他們提供[三種類型的壁紙,](https://github.com/rocksdanister/lively?tab=readme-ov-file#types-of-wallpapers)包括影片/GIF、網頁和應用程式/遊戲。 它基於 C# 和 live 支援的一些很酷的功能建置: 1. Lively 可以透過終端機的[命令列參數](https://github.com/rocksdanister/lively/wiki/Command-Line-Controls)進行控制。您可以將其與其他語言(例如 Python 或腳本軟體 AutoHotKey)整合。 2. 一組強大的[API](https://github.com/rocksdanister/lively/wiki/API) ,供開發人員建立互動式壁紙。取得硬體讀數、音訊圖表、音樂資訊等。 3. 當電腦上執行全螢幕應用程式/遊戲時(~0% CPU、GPU 使用率),桌布播放會暫停。 4. 您還可以利用[機器學習推理](https://github.com/rocksdanister/lively/wiki/Machine-Learning)來建立動態壁紙。您可以預測任何 2D 影像與相機的距離並產生類似 3D 的視差效果。酷:D 我見過很多人使用它,其中許多人甚至不知道它是開源的。 您可以使用[安裝程式](https://github.com/rocksdanister/lively/releases/download/v2.0.7.4/lively_setup_x86_full_v2074.exe)或透過[Microsoft Store](https://www.microsoft.com/store/productId/9NTM2QC6QWS7?ocid=pdpshare)下載它。 它是 2023 年 Microsoft Store 的獲勝者。 它在 GitHub 上擁有 13k+ Stars,有 60 個版本。 https://github.com/rocksdanister/lively 明星活潑 ⭐️ --- 17. [Netron](https://github.com/lutzroeder/netron) - 神經網路、深度學習和機器學習模型的視覺化工具。 ---------------------------------------------------------------------------- ![內創標誌](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uyvww60nqm4jrah526w2.png) Netron 是神經網路、深度學習和機器學習模型的檢視器。 Netron 支援 ONNX、TensorFlow Lite、Core ML、Keras、Caffe、Darknet、MXNet、PaddlePaddle、ncnn、MNN 和 TensorFlow.js。 Netron 對 PyTorch、TorchScript、TensorFlow、OpenVINO、RKNN、MediaPipe、ML.NET 和 scikit-learn 提供實驗性支援。 您可以閱讀有關[安裝說明](https://github.com/lutzroeder/netron?tab=readme-ov-file#install)。 您可以存取該[網站](https://netron.app/)並打開這些[範例模型文件](https://github.com/lutzroeder/netron?tab=readme-ov-file#models)以使用它來打開。例如,您可以看到這個[演示](https://netron.app/?url=https://github.com/onnx/models/raw/main/validated/vision/classification/squeezenet/model/squeezenet1.0-3.onnx)。 ![模型](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z1h4si8oue41x1i7dss5.png) 他們在 GitHub 上有 25k+ Stars,並且是基於 JavaScript 建構的。它們在`v7.5`上只有三個版本,考慮到我只使用了語義版本,這對我來說似乎很困惑。我們都同意這個用例非常出色。 https://github.com/lutzroeder/netron 明星 Netron ⭐️ --- 18. [Cursor](https://github.com/getcursor/cursor) - 以 VSCode 為基礎的人工智慧程式碼編輯器。 ---------------------------------------------------------------------------- ![游標](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k7em09r6owbz35zh8tt0.png) Cursor 是一款專為與 AI 結對程式設計而設計的程式碼編輯器。遊標適用於 Windows、Mac 和 Linux。 Cursor 不僅僅是 Visual Studio Code (VSC) 擴充功能。這是它自己的應用程式。但別擔心!這是VSC前叉。這意味著它擁有 VSC 所擁有的一切,但在此基礎上也建立了更多人工智慧功能。 https://github.com/anysphere/primpt 他們之前開源了[基於 Codemirror 的編輯器](https://github.com/getcursor/old)。 基於 VSCodium 的 Cursor 版本不是開源的,只有它們的[提示庫](https://github.com/anysphere/priompt)是開源的。 選項數量龐大,您可以查看[功能列表](https://docs.cursor.sh/features/chat),例如選擇用於聊天的 AI 模型、程式碼庫索引和自動終端偵錯。聽起來很酷,對吧:D 您應該檢查的一些功能是: - 允許您透過編輯程式碼庫的「偽程式碼」版本來進行編碼。 - 一旦錯誤出現在您的終端機中,就會自動修復錯誤。 - 要求 AI 更改程式碼區塊,查看編輯的內聯差異。 您也可以閱讀他們官方網站的[變更日誌](https://changelog.cursor.sh/?)。 您可以閱讀有關如何從[VSCode 遷移到 Cursor 的](https://docs.cursor.sh/get-started/moving-from-vsc-to-cursor)資訊。 他們也有定價模型,但免費套餐足以讓您進行測試! 他們在 GitHub 上擁有超過 19k+ 的 Star,並將繼續成長。正如我所說,這不是開源的,但將來可能會改變。 https://github.com/getcursor/cursor 星形遊標 ⭐️ --- 19. [VSCode 除錯視覺化工具](https://github.com/hediet/vscode-debug-visualizer)- VS Code 的擴展,可在偵錯期間可視化資料。 ------------------------------------------------------------------------------------------------- ![VSCode 除錯視覺化工具](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7hzgtqb6396zx73d3y62.png) 這個專案相當令人印象深刻。它不僅有助於高效除錯,還有助於透過視覺化學習基本概念,從長遠來看,這是無價的。 這是一個 VS Code 擴展,用於在偵錯時可視化資料結構。與 VS Code 的監視視圖類似,但具有豐富的監視值視覺化效果。 他們支援許多語言,如 Dart/Flutter、JS/TS、Go、Python、C#、Java、C++、Ruby、Rust 和 Swift,儘管它很基礎,所以這是一個優點。 其他語言和除錯器也可能有效。對於有基本支援的語言,只能視覺化 JSON 字串。您需要實作邏輯來為您的資料結建置立此 JSON。完全支援的語言提供資料提取器,可將一些眾所周知的資料結構轉換為 JSON。 安裝擴充功能後,您可以使用命令`Debug Visualizer: New View`開啟新的視覺化工具視圖。 您可以[在 market 上](https://marketplace.visualstudio.com/items?itemName=hediet.debug-visualizer)查看所有可用的[演示](https://github.com/hediet/vscode-debug-visualizer/blob/master/extension/README.md#selected-demos)並查看擴展。 您還可以查看他們的[視覺化遊樂場](https://hediet.github.io/visualization/?darkTheme=1),其中包含眾多選項。 他們在 GitHub 上擁有超過 7800 顆星,而且還在不斷增長。 https://github.com/hediet/vscode-debug-visualizer 明星 VSCode 除錯視覺化工具 ⭐️ --- 20. [OpenDevin](https://github.com/OpenDevin/OpenDevin) - 更少的程式碼,更多的內容。 ----------------------------------------------------------------------- ![奧彭文](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4on63bb02g4x4ny8gtcn.png) ![奧彭文](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l0yepod2rye2jk5r12dt.png) 這是一個開源專案,旨在複製 Devin,一名自主人工智慧軟體工程師,能夠執行複雜的工程任務並在軟體開發專案上與用戶積極協作。該計畫致力於透過開源社群的力量複製、增強和創新 Devin。 只是想讓你知道,這是在德文被介紹之前。 您可以閱讀帶有要求的[安裝說明](https://github.com/OpenDevin/OpenDevin?tab=readme-ov-file#installation)。 他們使用 LiteLLM,因此您可以使用任何基礎模型來執行 OpenDevin,包括 OpenAI、Claude 和 Gemini。 如果您想為 OpenDevin 做出貢獻,您可以查看 [演示](https://github.com/OpenDevin/OpenDevin/blob/main/README.md#opendevin-code-less-make-more)和[貢獻指南](https://github.com/OpenDevin/OpenDevin/blob/main/CONTRIBUTING.md)。 它在 GitHub 上擁有超過 10,700 個 Star,並且正在快速成長。 https://github.com/OpenDevin/OpenDevin 明星 OpenDevin ⭐️ --- 21.[即時語音克隆](https://github.com/CorentinJ/Real-Time-Voice-Cloning)-5秒克隆語音,即時產生任意語音。 ---------------------------------------------------------------------------------- ![即時語音克隆](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ftnuelce5cwng0nunp2h.png) 該專案是透過即時工作的聲碼器實現從說話者驗證到多說話者文字到語音合成 (SV2TTS) 的遷移學習。 SV2TTS是一個分為三個階段的深度學習架構。 在第一階段,人們從幾秒鐘的音訊中建立聲音的數位表示。 在第二和第三階段,該表示被用作參考來產生給定任意文字的語音。 您可以閱讀[如何設定](https://github.com/CorentinJ/Real-Time-Voice-Cloning?tab=readme-ov-file#setup)專案,其中包括安裝要求、下載預訓練模型、測試配置、下載資料集和啟動工具箱。 觀看下面所示的影片示範! https://www.youtube.com/watch?v=-O\_hYhToKoA 我一直喜歡開源專案的最好的部分是,他們甚至非常清楚地提到了替代方案,並且像往常一樣,他們推薦了一些[專案](https://github.com/CorentinJ/Real-Time-Voice-Cloning?tab=readme-ov-file#heads-up),這些專案將為您克隆的聲音提供更好的保真度及其表現力。 他們在 GitHub 上擁有 50k+ Stars,並且僅基於 Python 建置。到目前為止使用起來還是非常可信的。 https://github.com/CorentinJ/Real-Time-Voice-Cloning Star 即時語音克隆 ⭐️ --- 請在評論中告訴我您在此列表中發現了哪些有用的人工智慧工具:D 人工智慧正在改變世界,最好讓人工智慧成為你的朋友,而不是簡單地忽略它。 使用這些工具來提高工作效率並抓住機會創造非凡的東西。 祝你有美好的一天!直到下一次。 在 GitHub 和[Twitter](https://twitter.com/Anmol_Codes)上關注我。 https://github.com/Anmol-Baranwal 關注 Taipy 以了解更多此類內容。 https://dev.to/taipy --- 原文出處:https://dev.to/taipy/21-ai-tools-that-are-changing-the-world-1o54

我使用 Next.js、GPT4 和 CopilotKit 建立了 v0.dev 克隆

長話短說 ---- 在本文中,您將了解如何建立 Vercel 的 V0.dev 的克隆。這是一個很棒的專案,可以加入到您的投資組合中並磨練您的人工智慧能力。 我們將介紹使用: - 用於應用程式框架的 Next.js 🖥️ - 法學碩士 OpenAI 🧠 - v0 👾 的應用程式邏輯 - 使用 CopilotKit 將 AI 整合到您的應用程式中 🪁 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/shhjdu2k5s02gzoby3p0.gif) --- CopilotKit:應用內人工智慧的作業系統框架 ========================= CopilotKit 是[開源人工智慧副駕駛平台。](https://github.com/CopilotKit/CopilotKit)我們可以輕鬆地將強大的人工智慧整合到您的 React 應用程式中。 建造: - ChatBot:上下文感知的應用內聊天機器人,可以在應用程式內執行操作 💬 - CopilotTextArea:人工智慧驅動的文字字段,具有上下文感知自動完成和插入功能📝 - 聯合代理:應用程式內人工智慧代理,可以與您的應用程式和使用者互動🤖 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i8gltoave8490fg234ro.gif) {% cta https://github.com/CopilotKit/CopilotKit %} Star CopilotKit ⭐️ {% endcta %} (原諒人工智慧的拼字錯誤並給一顆星:) 現在回到文章。 --- 先決條件 ---- 要開始學習本教程,您需要具備以下條件: - 文字編輯器(VS Code、遊標) - React、Next.js、Typescript 和 Tailwind CSS 的基本知識。 - Node.js 安裝在您的 PC/Mac 上 - 套件管理器 (npm) - [OpenAI](https://platform.openai.com/docs/overview) API 金鑰 - [CopilotKit](https://docs.copilotkit.ai/getting-started/quickstart-textarea)安裝在您的 React 專案中 v0是什麼? ------ **v0**是[Vercel 開發的](https://vercel.com/blog/announcing-v0-generative-ui)生成式使用者介面 (UI) 工具,允許使用者給予提示並描述他們的想法,然後將其轉換為用於建立 Web 介面的 UI 程式碼。它利用[生成式 AI](https://medium.com/data-science-at-microsoft/generative-ai-openai-and-chatgpt-what-are-they-3c80397062c4)以及[React](https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started) 、 [Tailwind CSS](https://tailwindcss.com/)和[Shadcn UI](https://ui.shadcn.com/)等開源工具,根據使用者提供的描述產生程式碼。 *這是使用 v0 產生的 Web 應用程式 UI 的範例* https://v0.dev/t/nxGnMd1uVGc 了解專案要求 ------ 在本逐步教程結束時,克隆將具有以下專案要求: 1. **使用者輸入:**使用者輸入文字作為提示,描述他們想要產生的 UI。這將使用 CopilotKit 聊天機器人來完成,該聊天機器人由[CopilotSidebar](https://docs.copilotkit.ai/reference/CopilotSidebar)提供。 2. **CopilotKit 整合:** CopilotKit 將用於為 Web 應用程式提供 AI 功能以產生 UI。 3. **渲染 UI:**在 UI React/JSX 程式碼和渲染 UI 之間切換的切換開關。 使用 CopilotKit 建立 v0 克隆 ---------------------- **第 1 步:建立一個新的 Next.JS 應用程式** 在終端機中開啟工作區資料夾並執行以下命令建立新的 Next.js 應用程式: ``` npx create-next-app@latest copilotkit-v0-clone ``` 這將建立一個名為`copilotkit-v0-clone`新目錄,其中包含 Next.JS 專案結構,並安裝了所需的依賴項。它將在您的終端中顯示這一點,並對除最後一個之外的所有選項都選擇**“是”** ,因為建議使用預設`import alias` 。其他提示安裝我們將在專案中使用的 Typescript 和 TailwindCSS。 ![終端](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o6l07dxihdi8hw68kv4e.png) 使用`cd`指令導航到專案目錄,如下所示: ``` cd copilotkit-v0-clone ``` **步驟 2:設定 CopilotKit 後端端點。閱讀[文件](https://docs.copilotkit.ai/getting-started/quickstart-backend)以了解更多資訊。** 執行以下命令來安裝 CopilotKit 後端軟體包: ``` npm i @copilotkit/backend ``` 然後造訪 https://platform.openai.com/api-keys 以取得您的**GPT 4** OpenAI API 金鑰。 ![開放伊](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ise7y3qnb3cyg4j0mjr6.png) 取得 API 金鑰後,在根目錄中建立一個`.env.local`檔案。 `.env.local`檔案應該是這樣的: ``` OPENAI_API_KEY=Your OpenAI API key ``` 在**app**目錄下建立該目錄; `api/copilot/openai`並建立一個名為`route.ts`的檔案。該檔案用作 CopilotKit 請求和 OpenAI 互動的**後端**端點。它處理傳入的請求,使用 CopilotKit 處理它們,並傳回適當的回應。 我們將在`route.ts`檔案中建立一個POST請求函數,在post請求內部建立一個`CopilotBackend`類別的新實例,該類別提供了處理CopilotKit請求的方法。 然後,我們呼叫`CopilotBackend`實例的`response`方法,並傳遞請求物件 ( `req` ) 和`OpenAIAdapter`類別的新實例作為參數。此方法使用 CopilotKit 和 OpenAI API 處理請求並回傳回應。 如下面的程式碼所示,我們從`@copilotkit/backend`套件導入`CopilotBackend`和`OpenAIAdapter`類別。這些類別對於與 CopilotKit 和 OpenAI API 互動是必需的。 ``` import { CopilotBackend, OpenAIAdapter } from "@copilotkit/backend"; export const runtime = "edge"; export async function POST(req: Request): Promise<Response> { const copilotKit = new CopilotBackend(); return copilotKit.response(req, new OpenAIAdapter()); } ``` **步驟 3:為 v0 克隆建立元件** 我們將使用 Shadcn UI 庫中的元件。要處理這個問題,讓我們透過執行`shadcn-ui init`命令來設定 Shadcn UI 庫來設定您的專案 ``` npx shadcn-ui@latest init ``` 然後我們將用這個問題來配置components.json ``` Which style would you like to use? › Default Which color would you like to use as base color? › Slate Do you want to use CSS variables for colors? › no / yes ``` 我們在 Shadcn UI 中使用的元件是**按鈕**和**對話框**。那麼讓我們來安裝它們吧! 對於[按鈕](https://ui.shadcn.com/docs/components/button),執行此命令 ``` npx shadcn-ui@latest add button ``` 若要安裝[對話](https://ui.shadcn.com/docs/components/dialog)方塊元件,請執行以下命令 ``` npx shadcn-ui@latest add dialog ``` **第 4 步:設定 CopilotKit 前端。閱讀[文件](https://docs.copilotkit.ai/getting-started/quickstart-textarea)以了解更多資訊。** 若要安裝 CopilotKit 前端軟體包,請執行以下命令: ``` npm i @copilotkit/react-core @copilotkit/react-ui ``` 根據[CopilotKit 文件](https://docs.copilotkit.ai/getting-started/quickstart-textarea),要使用 CopilotKit,我們必須設定前端包裝器以透過 Copilot 傳遞任何 React 應用程式。當提示傳遞到 CopilotKit 時,它會透過 URL 將其傳送到 OpenAI,後者會回傳回應。 在**應用程式**目錄中,讓我們更新`layout.tsx`檔案。該文件將定義我們應用程式的佈局結構並將 CopilotKit 整合到前端。 輸入以下程式碼: ``` "use client"; import { CopilotKit } from "@copilotkit/react-core"; import "@copilotkit/react-textarea/styles.css"; // also import this if you want to use the CopilotTextarea component import "@copilotkit/react-ui/styles.css"; import { Inter } from "next/font/google"; import "./globals.css"; import { CopilotSidebar, } from "@copilotkit/react-ui"; const inter = Inter({ subsets: ["latin"] }); export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { return ( <html lang="en"> <body className={inter.className}> <CopilotKit url="/api/copilotkit/openai/"> <CopilotSidebar defaultOpen>{children}</CopilotSidebar> </CopilotKit> </body> </html> ); } ``` 該元件代表我們應用程式的根佈局。它使用 CopilotKit 包裝整個應用程式,根據我們在**步驟 2**中為後端建立的內容指定 CopilotKit 後端端點的 URL ( `/api/copilotkit/openai/` )。此外,它還包括一個 CopilotSidebar 元件,可作為 CopilotKit 的側邊欄,並將 Children 屬性作為其內容傳遞。 **第 5 步:設定主應用程式** 讓我們建立應用程式的結構。它將有一個標題、側邊欄和預覽畫面。 對於**Header** ,導航到**元件**目錄,如下所示, `src/components`然後建立一個`header.tsx`檔案並輸入以下程式碼: ``` import { CodeXmlIcon } from "lucide-react"; import { Button } from "./ui/button"; const Header = (props: { openCode: () => void }) => { return ( <div className="w-full h-20 bg-white flex justify-between items-center px-4"> <h1 className="text-xl font-bold">Copilot Kit</h1> <div className="flex gap-x-2"> <Button className=" px-6 py-1 rounded-md space-x-1" variant={"default"} onClick={props.openCode} > <span>Code</span> <CodeXmlIcon size={20} /> </Button> </div> </div> ); }; export default Header; ``` 對於**側欄,**建立一個`sidebar.tsx`檔案並輸入以下程式碼: ``` import { ReactNode } from "react"; const Sidebar = ({ children }: { children: ReactNode }) => { return ( <div className="w-[12%] min-h-full bg-white rounded-md p-4"> <h1 className="text-sm mb-1">History</h1> {children} </div> ); }; export default Sidebar; ``` 然後對於**預覽**螢幕,建立一個`preview-screen.tsx`檔案並輸入程式碼: ``` const PreviewScreen = ({ html_code }: { html_code: string }) => { return ( <div className="w-full h-full bg-white rounded-lg shadow-lg p-2 border"> <div dangerouslySetInnerHTML={{ __html: html_code }} /> </div> ); }; export default PreviewScreen; ``` 現在讓我們將它們放在一起,打開`page.tsx`檔案並貼上以下程式碼: ``` "use client"; import { useState } from "react"; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import Header from "@/components/header"; import Sidebar from "@/components/sidebar"; import PreviewScreen from "@/components/preview-screen"; import { Input } from "@/components/ui/input"; export default function Home() { const [code, setCode] = useState<string[]>([ `<h1 class="text-red-500">Hello World</h1>`, ]); const [codeToDisplay, setCodeToDisplay] = useState<string>(code[0] || ""); const [showDialog, setShowDialog] = useState<boolean>(false); const [codeCommand, setCodeCommand] = useState<string>(""); return ( <> <main className="bg-white min-h-screen px-4"> <Header openCode={() => setShowDialog(true)} /> <div className="w-full h-full min-h-[70vh] flex justify-between gap-x-1 "> <Sidebar> <div className="space-y-2"> {code.map((c, i) => ( <div key={i} className="w-full h-20 p-1 rounded-md bg-white border border-blue-600" onClick={() => setCodeToDisplay(c)} > v{i} </div> ))} </div> </Sidebar> <div className="w-10/12"> <PreviewScreen html_code={readableCode || ""} /> </div> </div> <div className="w-8/12 mx-auto p-1 rounded-full bg-primary flex my-4 outline-0"> <Input type="text" placeholder="Enter your code command" className="w-10/12 p-6 rounded-l-full outline-0 bg-primary text-white" value={codeCommand} onChange={(e) => setCodeCommand(e.target.value)} /> <button className="w-2/12 bg-white text-primary rounded-r-full" onClick={() => generateCode.run(context)} > Generate </button> </div> </main> <Dialog open={showDialog} onOpenChange={setShowDialog}> <DialogContent> <DialogHeader> <DialogTitle>View Code.</DialogTitle> <DialogDescription> You can use the following code to start integrating into your application. </DialogDescription> <div className="p-4 rounded bg-primary text-white my-2"> {readableCode} </div> </DialogHeader> </DialogContent> </Dialog> </> ); } ``` 我們來分解一下上面的程式碼: `const [code, setCode] = useState<string[]>([]);`將用於保存生成的程式碼 `const [codeToDisplay, setCodeToDisplay] = useState<string>(code[0] || "");`將用於保存預覽畫面上顯示的程式碼。 `const [showDialog, setShowDialog] = useState<boolean>(false);`這將保持對話框的狀態,該對話框顯示您可以複製的生成程式碼。 在下面的程式碼中,我們循環產生的程式碼(一串陣列)將其顯示在側邊欄上,這樣當我們選擇一個程式碼時,它就會顯示在預覽畫面上。 ``` <Sidebar> <div className="space-y-2"> {code.map((c, i) => ( <div key={i} className="w-full h-20 p-1 rounded-md bg-white border border-blue-600" onClick={() => setCodeToDisplay(c)} > v{i} </div> ))} </div> </Sidebar> ``` `<PreviewScreen html_code={codeToDisplay} />`在這裡,我們發送要在預覽畫面上顯示的程式碼。預覽畫面元件採用 CopilotKit 產生的程式碼字串,並使用`dangerouslySetInnerHTML`來呈現產生的程式碼。 下面我們有一個`Dialog`元件,它將顯示 CoplilotKit 產生的程式碼,可以將其複製並加入到您的程式碼中。 ``` <Dialog open={showDialog} onOpenChange={setShowDialog}> <DialogContent> <DialogHeader> <DialogTitle>View Code.</DialogTitle> <DialogDescription> You can use the following code to start integrating into your application. </DialogDescription> <div className="p-4 rounded bg-primary text-white my-2"> {readableCode} </div> </DialogHeader> </DialogContent> </Dialog> ``` **步驟6:實作主要應用程式邏輯** 在這一步驟中,我們將 CopilotKit 整合到我們的 v0 克隆應用程式中,以促進人工智慧驅動的 UI 生成。我們將使用 CopilotKit 的 React hook 來管理狀態,使元件可供 Copilot 讀取和操作,並與 OpenAI API 互動。 在您的`page.tsx`檔案中,匯入以下內容: ``` import { CopilotTask, useCopilotContext, useMakeCopilotReadable, } from "@copilotkit/react-core"; ``` 然後我們在`Home`元件中使用`CopilotTask`定義一個`generateCode`任務: ``` const readableCode = useMakeCopilotReadable(codeToDisplay); const generateCode = new CopilotTask({ instructions: codeCommand, actions: [ { name: "generateCode", description: "Create Code Snippet with React.js, tailwindcss.", parameters: [ { name: "code", type: "string", description: "Code to be generated", required: true, }, ], handler: async ({ code }) => { setCode((prev) => [...prev, code]); setCodeToDisplay(code); }, }, ], }); const context = useCopilotContext(); ``` 我們使用`useMakeCopilotReadable`來傳遞現有程式碼並確保可讀性。然後我們使用`CopilotTask`產生UI,並將`generateCode`任務綁定到**生成**按鈕,這樣就可以透過與按鈕元件互動來產生程式碼片段。 此操作由使用者互動觸發,並在呼叫時執行非同步`handler`函數。 `handler`將產生的程式碼新增至程式碼陣列中,更新應用程式狀態以包含新產生的程式碼片段,並將產生的程式碼傳送到預覽畫面上顯示和呈現,預覽畫面也可以複製。 此外, `instructions`屬性指定提供給 Copilot 的命令,該命令儲存在`codeCommand`狀態變數中。 有關`CopilotTask`運作方式的完整說明,請查看此處的文件:https://docs.copilotkit.ai/reference/CopilotTask **第 6 步:執行 v0 克隆應用程式** 至此,我們已經完成了 v0 克隆設置,然後可以透過執行來啟動開發伺服器 ``` npm run dev ``` ![終端](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6wm5oddqlzewca34ko0g.png) 可以使用此 URL 在瀏覽器中存取該 Web 應用程式 [http://本地主機:3000](http://localhost:3000/) 然後您可以輸入提示並點擊**“生成”。**這裡有些例子: - **定價頁面:**如下所示,這是產生的UI,有一個切換按鈕可以在UI和React程式碼之間切換: ![在](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cm3gyodvbl0x9i0uvxp9.png) 如果點擊右上角的**Code** &lt;/&gt; 按鈕,它會切換到產生的 UI 的 React 程式碼,如下所示: ![在](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1b5sruonnxl7x42ad8y1.png) - 註冊頁面 UI 範例: ![報名](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/350l7o66l6lq5d4kxiav.png) - 還有一個結帳頁面 ![查看](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dpj6j338fp2gavsvgtti.png) 要克隆專案並在本地執行它,請打開終端並執行以下命令: ``` git clone https://github.com/Tabintel/v0-copilot-next ``` 然後執行`npm install`以安裝專案所需的所有依賴項,並`npm run dev`來執行 Web 應用程式。 結論 -- 總而言之,您可以使用[CopilotKit](https://github.com/CopilotKit/CopilotKit)建立 v0 克隆,為您的設計提供 UI 提示。 CopilotKit 不僅適用於 UI 提示,它還可以用於建立[AI 驅動的 PowerPoint 生成器](https://dev.to/copilotkit/how-to-build-ai-powered-powerpoint-app-nextjs-openai-copilotkit-ji2)、 [AI 簡歷產生器](https://dev.to/copilotkit/how-to-build-the-with-nextjs-openai-1mhb)等應用程式。 可能性是無限的,立即查看 CopilotKit,將您的 AI 想法變為現實。 在[GitHub](https://github.com/Tabintel/v0-copilot-next)上取得完整原始碼。 從[文件](https://docs.copilotkit.ai/getting-started/quickstart-textarea)中了解有關如何使用 CopilotKit 的更多資訊。 另外,別忘了[Star CopilotKit!](https://github.com/CopilotKit/CopilotKit) ⭐ --- 原文出處:https://dev.to/copilotkit/i-created-a-v0-clone-with-nextjs-gpt4-copilotkit-3cmb

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 中建立 CLI 工具的指南

歡迎來到使用 JavaScript 的命令列介面 (CLI) 工具世界的令人興奮的旅程。 在本指南中,我將引導您建立 CLI 工具,該工具設定基本的專案結構,解釋每個步驟和程式碼片段,以確保您可以遵循。 設定您的開發環境 -------- 在我們深入 CLI 工具的世界之前,讓我們先設定我們的環境: 1. **安裝 Node.js 和 npm:**前往[Node.js 的官方網站](https://nodejs.org/en/)並下載建議的版本。安裝 Node.js 也會安裝 npm,這是您將用來處理 JavaScript 套件的套件管理器。 2. **驗證您的安裝:**開啟終端機並執行以下命令,確保所有內容均已正確安裝: ``` node --version npm --version ``` 查看版本號碼即可確認您已全部設定完畢! 建立您的 CLI 工具:專案設定自動化 ------------------- 我們的目標是建立一個能夠自動產生基本專案結構的 CLI 工具,從而省去您每次啟動新專案時手動建立資料夾和檔案的麻煩。 ### 第 1 步:啟動您的專案 1. **建立專案目錄:**這是 CLI 工具程式碼所在的位置。 ``` mkdir my-project-setup cd my-project-setup ``` 2. **初始化您的 npm 套件:**此步驟產生`package.json`文件,這對於管理專案的依賴項和配置至關重要。 ``` npm init -y ``` ### 第 2 步:建立 CLI 應用程式 1. **建立主檔案:**將此檔案命名為`index.js` 。它將包含 CLI 工具的邏輯。 2. **合併 Shebang 行:**在`index.js`的開頭新增: ``` #!/usr/bin/env node ``` ``` This line tells your system to use Node.js to execute this script. ``` 3. **實作邏輯:**下面的程式碼建立一個包含目錄和檔案的預定義專案結構: ``` const fs = require('fs'); // File System module to handle file operations // Define the project structure: directories and their respective files const projectStructure = { 'src': ['index.js'], 'public': ['index.html', 'styles.css'], }; // Iterate over the structure, creating directories and files Object.entries(projectStructure).forEach(([dir, files]) => { fs.mkdirSync(dir, { recursive: true }); // Create directories files.forEach(file => fs.writeFileSync(`${dir}/${file}`, '')); // Create files }); console.log("Project structure created successfully!"); ``` ``` Here's what each part of the code does: ``` - **需要 fs 模組:**這是 Node.js 的檔案系統模組,您將使用它來建立目錄和檔案。 - **定義專案結構:**我們指定要建立哪些目錄以及它們應包含哪些檔案。 - **建立目錄和檔案:**使用`fs.mkdirSync`和`fs.writeFileSync` ,腳本根據定義的結建置立每個目錄和檔案。 **4. 讓您的腳本可執行:**修改`package.json`以包含`"bin"`部分。這告訴 npm 哪個指令應該執行你的腳本: ``` `"bin": { ``` ``` "setup-project": "./index.js" ``` ``` }` ``` ### 第 3 步:在本地測試和連結您的工具 在分享您的工具之前,請先對其進行測試: 1. **連結您的工具:**在專案目錄中執行`npm link` 。此命令建立一個符號連結,允許您從終端中的任何位置執行 CLI 工具。 2. **執行您的工具:**只需在終端機的專案目錄中輸入`setup-project`即可。如果一切設定正確,您將看到“專案結構已成功建立!”訊息,以及提到的專案結構。 > 是的,就這樣! ### 第 4 步:增強功能 您的工具現在可以自動執行專案設置,但仍有改進的空間。考慮新增更多功能或處理使用者輸入來自訂專案結構。探索像`yargs`這樣的套件來解析命令列參數。您可以透過[此處的官方文件了解有關 yargs 的更多資訊。](https://yargs.js.org/) ### 第 5 步:在 npm 上分享您的工具 準備好與世界分享您的 CLI 工具了嗎?就是這樣: 1. **在 npm 上註冊:**如果您沒有帳戶,請在<https://www.npmjs.com/signup>建立帳戶。 2. **透過終端登入:**執行`npm login`並輸入您的 npm 憑證。 3. **發佈您的套件:**在您的專案目錄中,執行`npm publish` 。 恭喜!您的 CLI 工具現已在 npm 上提供,供所有人使用。 > 如果您已經關注我到這裡,請查看我用 Javascript 製作並發佈在 npm 上的第一個 CLI 工具:Naturalshell。 Naturalshell在您的終端中提供AI,現在無需記住shell命令! > 您可以[在此處查看 npm 套件](https://www.npmjs.com/package/naturalshell),[在此處查看 github 儲存庫](https://github.com/shreshthgoyal/naturalshell)。 > 請打 ⭐,並隨時加入新功能並與我一起在 naturalshell 上建置! > 該工具利用人工智慧來解析自然語言,並根據使用者的需求向使用者提供 shell 命令。除了提供命令之外,它還提供簡潔的解釋,確保使用者不僅知道要做什麼,而且了解其工作原理。憑藉直接在工具內編輯命令的便利性以及立即執行命令的能力,NaturalShell 提供了用戶友好、直觀的體驗 包起來 --- 您已經向使用 JavaScript 進行 CLI 工具開發的領域邁出了重要的第一步。透過建立一個簡單但實用的工具,您已經了解了建立、測試和發布 CLI 應用程式的基本知識。不斷嘗試、學習和建構。命令列是一個強大的盟友,現在,由您來指揮。快樂編碼! > 如果您發現本指南很有幫助並建立了您自己的出色 CLI 工具,我很樂意看到它!請在下面的評論部分分享您的 GitHub 儲存庫。讓我們一起建造吧! --- 原文出處:https://dev.to/shreshthgoyal/a-guide-to-building-cli-tools-in-javascript-28nn

令人難以置信的 JavaScript 動畫庫

概述 -- JavaScript 動畫庫已成為開發人員的必備工具,旨在透過迷人的互動式視覺元素來豐富 Web 應用程式。這些庫的發展極大地簡化了動畫過程,使其更易於存取。透過利用適當的函式庫,開發人員能夠製作令人印象深刻的動畫,從而增強網站和應用程式的參與度和使用者體驗。 動畫有可能大幅改變網站的美感和氛圍。當明智地利用它們來增強用戶體驗時,它們就會成為寶貴的資產。動畫在吸引註意力和增加網站停留時間方面特別有效,從而增加流量。 GSAP ------ ![總體規劃計劃](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p88xykg0uhg90oj4xckg.png) [GSAP(GreenSock 動畫平台)](https://greensock.com/gsap/)作為領先且強大的 JavaScript 動畫庫脫穎而出,專為速度和效率而設計。它擁有一系列功能,包括基於時間軸的動畫、SVG 支援和緩動功能。 GSAP 提供了各種預先設計的工具和功能,即使是網頁動畫新手也能快速有效地建立複雜的動畫。 GSAP 有助於跨 jQuery、Canvas 和 SVG 建立精美的高效能動畫。它與其他軟體和函式庫相容,例如[PixiPlugin](https://greensock.com/docs/v2/Plugins/PixiPlugin) 、 [WebGL](https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API) 、 [EaseJS](https://createjs.com/easeljs)等。 ### 好處 - 輕便快捷 - 廣泛的功能 - 可透過插件擴展 - 適應各種螢幕尺寸 - 支援所有主流瀏覽器 Anime.js ----- ![動漫.js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9suyvmlz3kzt9tooinls.png) [Anime.js](https://animejs.com/)以其簡單、速度和多功能性而聞名。這個緊湊的庫簡化了動畫過程,使開發人員能夠以最少的努力製作出視覺上引人注目的動畫。 Anime.js 支援多種效果,例如縮放、變形和旋轉,為開發人員提供了輕鬆建立複雜時間軸和動畫的工具。 ### 好處 - 直覺的API - 結構緊湊、適應性強 - 豐富的功能集 - 插件就緒架構 - 支援所有主流瀏覽器 Three.js ---- ![三.js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uqy0o2cm5obswsc9kp3y.png) [Three.js](https://threejs.org/)致力於產生 3D 視覺效果,提供一套強大的功能和工具。它建立在[WebGL](https://get.webgl.org/)之上,優化 GPU 使用以實現快速渲染,確保跨裝置(包括資源有限的裝置)的流暢效能。 Three.js 的多功能性允許建立廣泛的 3D 圖形和動畫,從簡單的形狀到複雜的模型。 Popmotion.io ------------ ![popmotion.io](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9u79jz8iilrbp65zx4h5.png) [Popmotion](https://popmotion.io/)在設計中優先考慮簡單性和易用性。它用[TypeScript](https://www.typescriptlang.org/)編寫,與任何接受數位輸入的 API 相容,提供簡單的 API 並支援主要瀏覽器。 Popmotion 的架構為[Framer Motion](https://www.framer.com/motion/)中的動畫提供支持,並且可以透過外掛程式進行擴充。 ### 好處 - 使用者友善的介面 - 可擴充的插件框架 - 響應式設計 - 支援所有主流瀏覽器 反應彈簧 ---- ![反應彈簧](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ny6fonq8dw3udlcejqfn.png) [React-spring](https://www.react-spring.dev/)專為 React 應用程式量身定制,透過其簡單的 API 提供跨所有主要瀏覽器的無縫動畫體驗。它不僅迎合 Web 環境,還支援 React-Native、React-Three-Fiber、React-Konva 和 React-ZDog。它的 TypeScript 基礎有助於輕鬆整合到現有專案中。 ### 好處 - 簡單易懂 - 啟用插件以增加功能 - 跨裝置回應 - 支援所有主流瀏覽器 Vivus - ![活](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t4zdqw3xeq1vxrrlgx1u.png) [Vivus](https://maxwellito.github.io/vivus/)專注於 SVG 動畫,具有易於使用的 API,確保跨所有主要瀏覽器的兼容性。它支援各種動畫樣式,例如延遲、同步或 OneByOne,並允許為每個 SVG 路徑自訂動畫腳本。 ### 好處 - 毫不費力地實施 - 插件擴充性 - 專用的 SVG 動畫功能 - 支援所有主流瀏覽器 Mo.js ----- ![Mo.js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v3rhzp2ggqfy8t61fvkd.png) [Mo.js](https://mojs.github.io/)是一個強大且適應性強的 JavaScript 動畫庫,具有簡單的 API 和瀏覽器支援。它以其高性能動畫和與密度無關的效果而著稱,確保在任何設備上都有出色的視覺品質。 Mo.js 提供了廣泛的動畫建立工具,包括用於動畫控制的播放器、曲線編輯器和用於自訂緩動和編輯的時間軸編輯器。 ### 好處 - 強大而靈活 - 直覺的API - 插件相容 - 專為響應式環境設計 - 支援所有主流瀏覽器 結論 -- 為您的專案選擇正確的動畫庫可能是一項艱鉅的任務。還有許多其他 JavaScript 動畫庫可用,每個庫都具有獨特的特性和功能。 您是否有此處未提及的最喜歡的圖書館?請在下面的評論中分享。我總是渴望探索新工具並擴展我的工具包! 如果您發現這有幫助並願意給我的專案一顆星以支持,我將不勝感激! [黏土主題🚀](https://github.com/lilxyzz/clay-theme) --- 原文出處:https://dev.to/lilxyzz/incredible-javascript-animation-libraries-30on