今日已更新 217 条资讯 | 累计 37466 条内容
关于我们

标签:#Java

找到 1191 篇相关文章

AI 资讯

How do you regression-test a ReDoS fix without hanging CI?

A known-bad regex is useful evidence, but putting it directly in the test process can hang the runner before the timeout assertion fires. The boundary I am using: run each adversarial case in a fresh worker thread or child process let the parent own a hard timeout and terminate the child keep semantic-parity fixtures separate from timing guards require the safer replacement to pass both suites record the timeout class and bounded elapsed time as evidence Browser workers have the same trap: startup time should not consume the execution budget, and output limits matter alongside time limits. Disclosure: I maintain MonoTools. I recently tightened its browser-local Regex Tester around a 300 ms post-startup Worker budget, named groups, replacement previews, and regression cases: try the bounded tester What does your team treat as a deterministic CI failure receipt for ReDoS: an exit code, a timeout class, an elapsed-time range, or something else?

2026-08-15 原文 →
AI 资讯

Environment Variables the Safe Way

Why Environment Variables Matter Every app has secrets: API keys, database URLs, admin passwords. Hardcoding them in source code is a one-way ticket to leaks. Even if your repo is private, you never know who forks it or what CI logs expose. Environment variables are the standard way to keep configuration out of code. But using them safely requires a few habits that go beyond just process.env . The Basics: Loading and Accessing In Node.js, you read env vars with process.env . But you should not access them raw everywhere. Create a central config module that validates and exposes them. // config.js const required = [ ' DB_URL ' , ' API_KEY ' , ' PORT ' ]; for ( const key of required ) { if ( ! process . env [ key ]) { throw new Error ( `Missing required env var: ${ key } ` ); } } module . exports = { dbUrl : process . env . DB_URL , apiKey : process . env . API_KEY , port : parseInt ( process . env . PORT , 10 ), }; Fail fast at startup. If a required variable is missing, crash immediately rather than failing later in a confusing way. Never Commit .env Files Tools like dotenv load variables from a .env file for local development. That file must stay out of version control. Add .env to your .gitignore immediately. Also add .env.local , .env.production , etc. if you use them. Instead of committing the actual values, commit a .env.example with placeholder or fake values. This documents what is needed without exposing anything. # .env.example DB_URL = postgres :// user : password @ localhost : 5432 / mydb API_KEY = your - api - key - here PORT = 3000 Use a Validation Library Manual checks are fine for small projects, but for anything serious use a schema validator like envalid or joi . They give you type coercion, defaults, and clear error messages. // with envalid const { cleanEnv , str , num } = require ( ' envalid ' ); const env = cleanEnv ( process . env , { DB_URL : str (), API_KEY : str (), PORT : num ({ default : 3000 }), }); module . exports = env ; This catches m

2026-08-15 原文 →
AI 资讯

جعلنا موقعنا غير قابل للضغط مرتين، ولم يكن الخطأ في الكود

مرتين خلال أسابيع صار موقعنا يبدو سليمًا تمامًا ولا يستجيب للضغط. الصفحة تُحمَّل، والتصميم في مكانه، والكونسول نظيف، والزوار لا يستطيعون فتح أي رابط. في المرتين لم يكن السبب خطأً برمجيًا بالمعنى المعتاد. كان سلوكًا موثّقًا في المتصفح يعمل كما صُمّم تمامًا، لكنه انطبق على نطاق أوسع مما توقّعنا. والأخطر أن اختباراتنا الآلية مرّت بنجاح في الحالتين. الحادثة الأولى: إعداد واحد عطّل سبعين عنصرًا أضفنا ويدجت مساعد ذكي للموقع، وفيه إعداد يفتح نافذة المحادثة تلقائيًا عند دخول الزائر. فعّلناه. بعدها صارت الصفحة ميتة. الروابط لا تُفتح، والأزرار لا تستجيب، وحقول البحث لا تستقبل كتابة. السبب أن الويدجت يعتمد نمطًا شائعًا في نوافذ الحوار: عند فتح النافذة، يضع السمة inert على كل ما عداها حتى لا يتشتت التركيز ولا يهرب مؤشر لوحة المفاتيح خارجها. سلوك صحيح ومطلوب في الحوارات. المشكلة أن الفتح التلقائي يجعل هذه الحالة هي حالة الصفحة الافتراضية عند كل زيارة . سبعون عنصرًا في الصفحة ورثوا inert ، وبقوا كذلك حتى يغلق الزائر نافذة لم يطلب فتحها أصلًا. // ما يفعله الويدجت عند الفتح document . querySelectorAll ( ' body > *:not(.assistant-root) ' ) . forEach (( el ) => el . setAttribute ( ' inert ' , '' )); و inert ليست سمة تجميلية. الفحص السريع يوضح مداها: const el = document . querySelector ( ' a.main-cta ' ); el . offsetParent !== null ; // true — العنصر مرئي getComputedStyle ( el ). pointerEvents ; // 'auto' — لا شيء يمنع المؤشر el . getBoundingClientRect (). width ; // 180 — له مساحة حقيقية el . matches ( ' :disabled ' ); // false — ليس معطّلًا el . closest ( ' [inert] ' ) !== null ; // true ← هنا الجواب كل فحص اعتدنا عليه يقول إن العنصر سليم. inert تعمل في طبقة أخرى: تُخرج العنصر وكل أبنائه من شجرة الوصول، وتلغي استقباله لأحداث المؤشر والتركيز، بلا أي أثر في الأنماط المحسوبة . لماذا مرّت الاختبارات اختباراتنا كانت تسأل الأسئلة المعتادة: هل العنصر موجود في الـDOM؟ هل هو مرئي؟ هل نصّه صحيح؟ الإجابات كلها نعم. ما كشف العطل كان لقطة شاشة نظر إليها إنسان ، ثم محاولة ضغط واحدة. الفحوص البرمجية كانت تصف صفحة سليمة بينما الزائر يرى صفحة جامدة. إن كنت تستخدم أي مكوّن يطبّق inert ، أضف هذا التأك

2026-08-15 原文 →
AI 资讯

Should your daily batch job live inside your main application?

Most Spring Boot services end up with a scheduled job in them somewhere. A nightly reconciliation, a report, an export to some partner system. It starts small, and it goes in the main app because that's where the domain code already is. One artifact, one deployment, one pipeline. That's a real advantage and it's why most teams do it. This post is about when that stops being a good trade, how to split the job out, and when you shouldn't. The memory problem Look at how much memory each workload uses over a day. The API is fairly flat. Warm heap, connection pool, some caches. It moves with traffic but it doesn't swing much. The batch job uses close to nothing for 23 hours, jumps while it runs, then drops back to nothing. When both live in the same JVM, the pod has to be sized for the peak. So every replica of your API holds batch-sized memory all day, for a job that runs once. With three replicas you're reserving that headroom three times over so one job can use it once, at 2am. Memory limits are not like CPU limits CPU is compressible. Go over your CPU limit and the kernel throttles you. The app gets slower and keeps running. Memory doesn't work that way. There's no "run with less" mode. If the container goes over its memory limit, the kernel kills the process. What you get is a container that exited with code 137 (that's 128 + 9, where 9 is SIGKILL). What you don't get is anything useful in the logs. No OutOfMemoryError , no stack trace, no heap dump unless you configured one and it had time to write, no shutdown hook. The JVM was running fine, asked for another page of memory, and got killed for it. So a batch job sharing a pod with your API is a way for a nightly job to take down the pods serving traffic. If the job's working set grows (bigger dataset, a table that keeps growing, one unusually heavy day) the thing that dies is the API. There's a quieter version of the same problem. Even when the job stays under the limit, it allocates heavily and triggers longer GC

2026-08-14 原文 →
开源项目

🔥 laoma2053 / awesome-zhuiju-free - 免费无广告的追剧资源指南,人工精选资源、每天检测资源有效性。收录在线影视、影视APP、网盘搜索、磁力BT、字幕、TVBo

GitHub热门项目 | 免费无广告的追剧资源指南,人工精选资源、每天检测资源有效性。收录在线影视、影视APP、网盘搜索、磁力BT、字幕、TVBox / 影视仓空壳软件/配置地址、IPTV直播源、会员拼团、影视相关开源项目。开源,社区共同维护。 | Stars: 5,766 | 71 stars today | 语言: JavaScript

2026-08-14 原文 →
开发者

Creating modern forms with form.fscss — pure CSS

Floating labels. Inline validation. Custom checkboxes, radios, and a toggle switch. A gradient button with a press-down micro-interaction. Every bit of it below is CSS — no form library, no useState , no event listener wiring up a class toggle. That's form.fscss — the module in the FSCSS ecosystem. Same philosophy each time: solve the hard visual problem once, ship it as importable mixins, let the browser do the actual work. <script src= "https://cdn.jsdelivr.net/npm/fscss@1.1.24/exec.min.js" defer ></script> <style> @import (( * ) from form ) @ form-root () @ form-group (. form-group ) @ form-input (. form-input ) @ form-label (. form-label ) @ form-float (. form-group , . form-input , . form-label ) @ form-checkbox (. form-checkbox ) @ form-btn (. form-btn ) @ form-btn-primary (. form-btn-primary ) </style> <div class= "form-group" > <input class= "form-input" type= "text" placeholder= " " > <label class= "form-label" > Full name </label> </div> <label class= "form-checkbox" > <input type= "checkbox" checked ><span></span> I agree to the Terms </label> <button class= "form-btn form-btn-primary" > Create account </button> The two tricks doing all the work Forms feel like they need JavaScript because most tutorials reach for it immediately. Two native CSS mechanisms cover almost everything a "modern" form needs. Floating labels run entirely on :placeholder-shown . Give the input placeholder=" " — a literal space, not empty — and the browser now knows, purely in CSS, whether the field is empty and unfocused: .form-input :focus + .form-label , .form-input :not ( :placeholder-shown ) + .form-label { top : -9px ; font-size : 11px ; color : var ( --form-accent ); } No state, no class toggling on keyup. The label just reacts to what the browser already knows about the input. Checkboxes, radios, and the switch all use the classic checkbox-hack: the real <input> stays in the DOM (so it keeps native keyboard support and form submission) but is visually hidden, and a sibling

2026-08-14 原文 →
AI 资讯

One tool call, counted twice: a Google GenAI streaming double-dip in Sentry's JS SDK

This is a submission for DEV's Summer Bug Smash: Clear the Lineup powered by Sentry . The bug When you call @google/genai in streaming mode and the model asks to run a tool, Sentry's JavaScript SDK records that tool call to the span twice. One tool call in, two entries out. The attribute that carries them is gen_ai.response.tool_calls . It should hold one object per call. For a single streamed controlLight call it held two. Worse, the two did not even agree on their shape. Here is a real capture, which I come back to at the end: [ { "id" : "call_2079699" , "args" :{ "colorTemperature" : "warm" , "brightness" : 30 }, "name" : "controlLight" }, { "type" : "function" , "id" : "call_2079699" , "name" : "controlLight" , "arguments" :{ "colorTemperature" : "warm" , "brightness" : 30 }} ] Same id, same call, listed twice. One entry keys the parameters under args , the other under arguments . Anything reading this later sees two tool invocations where the model made one. Following the value The streaming instrumentation lives in packages/server-utils/src/ai/google-genai/streaming.ts . Every chunk of the stream runs through handleCandidateContent . That function wrote tool calls from two places: function handleCandidateContent ( chunk , state , recordOutputs ) { if ( Array . isArray ( chunk . functionCalls )) { state . toolCalls . push (... chunk . functionCalls ); // push #1 } for ( const candidate of chunk . candidates ?? []) { // ...finish reasons... for ( const part of candidate ?. content ?. parts ?? []) { if ( recordOutputs && part . text ) state . responseTexts . push ( part . text ); if ( part . functionCall ) { state . toolCalls . push ({ // push #2 type : ' function ' , id : part . functionCall . id , name : part . functionCall . name , arguments : part . functionCall . args , }); } } } } Push #1 spreads chunk.functionCalls into the accumulator. Push #2 walks candidate.content.parts and pushes every functionCall it finds. They look like two different sources. They

2026-08-14 原文 →
AI 资讯

Understanding Event-Driven Architecture in Modern Applications

Event-driven architecture is one of the most useful patterns for building applications that need to react to events instead of executing everything in a strict request-response sequence. Instead of thinking: User does something → Server performs everything → Response we can think: User does something → Event is created → Interested services react to it What Is an Event? An event represents something that happened. For example: { type : " USER_REGISTERED " , userId : " 12345 " , timestamp : Date . now () } Other parts of the application can listen for this event and perform their own tasks. For example: Email service sends a welcome email. Analytics service records the registration. Notification service creates a notification. Recommendation service creates initial recommendations. The registration service doesn't necessarily need to know how all of these tasks work. Why Use Event-Driven Architecture? The biggest advantage is decoupling. A traditional implementation might look like: await createUser (); await sendEmail (); await updateAnalytics (); await createNotification (); If the email service becomes slow, the entire operation can become slow. With events: await createUser (); publishEvent ({ type : " USER_REGISTERED " , userId : user . id }); Other services can process the event independently. Where Is It Useful? Event-driven systems are particularly useful for: Payment processing E-commerce Notifications Analytics Microservices IoT systems Background processing Real-time applications The Trade-Off Event-driven architecture isn't automatically better. It introduces additional complexity: Event delivery failures Duplicate events Ordering problems Debugging difficulties Event schema management For a small CRUD application, a simple architecture may be much easier. Final Thoughts Event-driven architecture is less about using a specific technology and more about changing how application components communicate. Once your application grows beyond a simple monolith, u

2026-08-14 原文 →
AI 资讯

200 OK Is Not Enough: Why Bot-Protected Sites Still Return Bad Data

Your crawl job finished successfully. That doesn't mean it got the data. Every scraping pipeline has a monitoring dashboard, and every monitoring dashboard has the same blind spot: it tracks whether requests succeeded, not whether the content that came back was real. A job that completes with a wall of green 200 status codes looks healthy. It can also be quietly wrong, page after page, for weeks, because a 200 response only tells you the server accepted the request. It says nothing about whether you're looking at the actual page or a version built specifically for visitors the site doesn't fully trust. That gap between "the request succeeded" and "the data is correct" is where most silent pipeline failures live, and it's getting wider as anti-bot systems get more sophisticated about what they serve instead of an outright block. What a "successful" response can actually contain A block used to be simple to detect: a 403, a 429, a connection reset. Modern anti-bot systems increasingly prefer a different approach, because an obvious block tells the requester exactly what happened and invites a fix. A soft block, served with a 200, doesn't. In practice, that 200 can be a challenge page, an interstitial that looks like real content in the raw response but is actually a JavaScript-driven verification step (a "just a moment" style page, a hidden CAPTCHA iframe, a redirect loop disguised as a normal page load). It can be a cached fragment, an old snapshot of the page served to anything that looks automated, so the price, availability, or listing you scraped is stale even though the request itself worked fine. It can be an empty state, a search results page or listing that legitimately returns "no results" to a request pattern the site doesn't recognize, even though a real visitor would see dozens of items. And increasingly, it can be a partial HTML shell: the server response contains the page skeleton, but the actual content only renders after JavaScript executes in a real

2026-08-14 原文 →
AI 资讯

npm 12 Released: Install Scripts Off by Default as Registry Moves to Explicit Trust

npm 12 introduces significant security-related changes, making certain installation behaviors opt-in. Notably, script allowances are now off by default, which requires explicit approval for running scripts, including implicit builds. The update also restricts non-registry sources and addresses community concerns about security risks from automatic script execution. By Daniel Curtis

2026-08-14 原文 →
AI 资讯

Add Model Fallback to an OpenAI-Compatible Node.js App

A single model can be unavailable, rate-limited, or temporarily slow. If your application already uses an OpenAI-compatible API, a simple fallback can make testing more resilient without introducing another SDK. This tutorial uses Node.js and the official OpenAI JavaScript package. It tries one model first and switches to a second model only when the first request fails. 1. Install the SDK npm install openai 2. Store the API key outside your code On macOS or Linux: export JINZEAI_API_KEY = "your_api_key_here" On PowerShell: $ env : JINZEAI_API_KEY = "your_api_key_here" Never commit a real API key. Rotate it immediately if it appears in a public repository, screenshot, or support message. 3. Create an OpenAI-compatible client import OpenAI from " openai " ; const client = new OpenAI ({ baseURL : " https://jinzeai.cc/v1 " , apiKey : process . env . JINZEAI_API_KEY , }); 4. Add a small fallback function const models = [ " deepseek-chat " , " qwen-flash " ]; async function completeWithFallback ( messages ) { let lastError ; for ( const model of models ) { try { const response = await client . chat . completions . create ({ model , messages , }); return { model , text : response . choices [ 0 ]. message . content , }; } catch ( error ) { lastError = error ; console . warn ( ` ${ model } failed: ${ error . status ?? " unknown status " } ` ); } } throw lastError ; } const result = await completeWithFallback ([ { role : " user " , content : " Explain model fallback in one sentence. " , }, ]); console . log ( `Model: ${ result . model } ` ); console . log ( result . text ); 5. Decide which errors should trigger fallback The minimal example retries on every error so the control flow is easy to see. A production application should be more selective. Fallback may be reasonable for: rate limits; upstream server errors; temporary timeouts; a model that is unavailable to the current account. Do not silently retry authentication errors. An HTTP 401 usually means the key is missing,

2026-08-14 原文 →
开发者

CSS Anchor Positioning: Building Tooltips Without JavaScript Positioning Hacks

Introduction Positioning a tooltip sounds simple. Put a small box next to a button. Done. But anyone who has built one knows that it can quickly turn into: position: absolute calculating coordinates listening for resize events handling scrolling checking whether the tooltip fits on screen and sometimes pulling in an entire positioning library Modern CSS is starting to change that. CSS Anchor Positioning lets us position one element relative to another directly in CSS. Let's look at what that means with a very simple tooltip. What Is CSS Anchor Positioning? CSS Anchor Positioning allows one element to act as an anchor and another element to position itself relative to that anchor. Think about UI components such as: Tooltips Dropdown menus Popovers Context menus Floating labels These elements usually need to appear next to another element. Instead of calculating where they belong with JavaScript, we can now describe that relationship in CSS. Conceptually, we're saying: "This button is my anchor. Position this tooltip relative to it." A Simple Example Imagine we have a button: <button class= "info-button" > More info </button> <div class= "tooltip" > Your changes are saved automatically. </div> We want the tooltip to appear directly below the button. First, let's make the button an anchor. .info-button { anchor-name : --info-button ; } We've now given the button an anchor name. Next, connect our tooltip to it. .tooltip { position : absolute ; position-anchor : --info-button ; top : anchor ( bottom ); left : anchor ( left ); margin-top : 8px ; } That's the interesting part. top : anchor ( bottom ); tells the browser: Position the top of the tooltip at the bottom of the anchor. And: left : anchor ( left ); aligns its left side with the button. No getBoundingClientRect() . No coordinate calculations. No resize listener just to figure out where the tooltip belongs. Why Is This Useful? Before Anchor Positioning, we often had to manage positioning ourselves. A simplified Jav

2026-08-14 原文 →
开发者

Hoisting

Hoisting in JavaScript is the engine’s behavior of moving declarations to the top of their scope (global or local) before execution. Because of hoisting, you can reference functions or variables in your code before the lines where they are defined. 1.Function Declaration Function declarations are hoisted in their entirety—both the declaration and the body. This means you can call a function before it appears in the source code. hello (); //Output: hello! function hello (){ console . log ( " hello! " ) } 2.var Declaration When you use var, JavaScript hoists the variable declaration, but not its assignment. Until the execution line reaches the assignment, the variable holds undefined. console . log ( num ); //Output: undefined var num = 10 ; console . log ( num ); //Output: 10

2026-08-14 原文 →
AI 资讯

How We Built an Instant AI Security & Code Auditor in Next.js & Convex

🚀 How We Built an Instant AI Security & Code Auditor in Next.js & Convex When building security or code auditing tools, speed is everything . Developers won't wait 45 seconds for a bloated PDF report—they want instant feedback on potential bugs, security leaks, or bad practices. Over the last week, we've been building BugZ AI , a lightweight scanner designed to analyze code repos and security links in under 5 seconds . Here is a breakdown of our stack and the architecture choices behind keeping real-time scans ultra-fast. 💡 Build in Public Update: We hit 175 total developer visits today on Day 4 of building out in the open! 🛠️ 1. The Tech Stack Frontend: Next.js 15 (App Router) + Tailwind CSS Backend & Database: Convex (for real-time reactive updates without manual polling) Auth: Clerk Mobile Sync: Capacitor (wrapping web assets into native Android) ⚡ 2. Solving the Speed Bottleneck The biggest challenge was stream handling. Instead of waiting for the entire LLM response to complete before rendering analysis to the UI, we used Convex's real-time mutations paired with edge streaming. This lets the user paste a link or snippet and see initial vulnerability checks pop up in real-time within < 20 seconds . 📈 3. What We Learned Building Out in the Open Keep the UI distraction-free: Developers hate bloated dashboards when a single search bar will do the job. Real-time > Batch: Showing progress indicators reduces drop-off rates significantly compared to static loader spinners. 🧪 Try it out & Drop Your Feedback! If you want to run a quick audit on your project or test a link, check out the live demo here: [INSERT YOUR BUGZ AI LINK HERE] I'd love to hear your feedback on the scanning speed and response accuracy. What features would make this a daily part of your dev workflow?

2026-08-14 原文 →