DEV Community

Dev.to is a community-driven website focused on software development, programming, and technology. It was launched in 2016 by Ben Halpern, and its main goal is to provide a platform for developers to share knowledge, learn from others, and build a community. The website features a blog-like format, where users can create and share articles on various topics, including coding tutorials, project showcases, industry insights, and more. Dev.to allows users to create accounts, follow other users, and engage with their content through comments and reactions. Dev.to has a strong focus on community engagement, with features like discussion forums, podcasts, and live streams. It also hosts a series of community-driven projects, such as coding challenges and hackathons, to encourage collaboration and innovation. In addition to user-generated content, Dev.to features a job board, where companies can post job openings and developers can search for employment opportunities. The website also offers a newsletter, which provides updates on the latest articles, news, and events. Overall, Dev.to has become a popular platform for developers to connect, share knowledge, and stay up-to-date with the latest trends and technologies in the software development industry.

Thread Of Notes

CdXz5zHNQW_INSrNMmJET.webp
The author, with extensive experience in interviewing and assisting students, highlights that many struggling job seekers falter due to poor time management rather than technical inadequacy. Career paths are divided into two main tracks: staying in the US on OPT/H1B, and returning to China for campus or social recruitment. A common misconception about OPT is that the unemployment period is 60 days, when it is actually 90 days, with an additional 60 days for STEM extensions, totaling 150 days.The timing for US recruitment, particularly fall recruiting for major companies, peaks from August to October, but the unemployment clock starts at graduation, not when job applications begin. For those returning to China, early recruitment for some companies starts as early as July, with formal recruitment in September and offers distributed from December to January. Understanding one's "graduating cohort" is crucial for Chinese recruitment, as it determines eligibility for early and formal application rounds.Several pitfalls exist regarding immigration status, including CPT usage that can reduce OPT duration and the implications of not being selected in the H1B lottery, which may lead to alternative paths or higher costs for staying in the US. The "returned student" status in China can be tricky, with certain graduation dates or prior OPT employment potentially disqualifying candidates from entry-level positions. It's also important to note the benefits of overseas talent introduction programs for relocation.Resumes need to be tailored for each job market; the US version emphasizes verifiable depth with GitHub links, while the China version focuses on business impact, quantifiable results, and the ability to translate technical achievements into business value. Preparing for interviews should be project-centric, deeply understanding 2-3 key projects, rather than solely focusing on rote memorization of algorithm problems. Submitting applications for both US and China tracks with tailored resumes is often the most stable approach, allowing for dual offers and better negotiation leverage. Making a decision on which path to pursue should ideally happen by mid-October, before offers expire.
Prism is a novel sparse-attention framework designed to make training high-resolution video and audio generation models more efficient. High-resolution video contains an immense number of visual tokens, making traditional dense attention computationally expensive due to its quadratic scaling. Audio adds another layer of complexity, requiring models to connect sounds to their visual origins. Prism tackles this by intelligently adapting its attention patterns based on the local content of the video.The framework divides video clips into spatiotemporal macro-zones, analyzing visual variations and audio-video cross-attention signals within each zone. Based on these signals, Prism dynamically shapes its attention blocks, focusing computational resources on areas with significant visual change or strong audio-visual correlation. This sparse attention approach avoids unnecessary computations on less informative parts of the video.A preview of Prism is available on Hugging Face, offering inference scripts for image-to-video and text-to-video-and-audio generation, as well as support for native joint video-audio training. The repository currently requires substantial GPU resources, with 720p inference demanding an 80GB GPU and higher resolutions necessitating multiple such GPUs. Native training for 1080p and 2K resolutions requires at least 32 or 64 80GB GPUs respectively.The authors report that Prism achieves up to 2.5 times faster training compared to full attention, along with improved generation quality, though these results are specific to their experimental setup. This research preview is intended for users comfortable with downloading checkpoints and configuring GPU environments. Prism's core innovation lies in its content-aware, dynamic sparse attention, which is particularly beneficial for training high-resolution joint video-audio models.
CdXz5zHNQW_9iIf2QyWki.webp
The code in ArticleLayout.tsx contains a ternary operator with identical branches, indicating a past decision that has since been simplified to a single outcome. This situation arises because Notifio has eight long-form pages distributed across two URL spaces: /guides and /for. These pages, despite their different URLs, are fundamentally the same type of document, addressing a specific problem with a solution and product. The distinction in URLs is based on reader intent: /for/ pages cater to self-identification, while /guides/ pages focus on tasks.A key field, kind, differentiates these pages as either "audience" or "guide." However, the underlying content graph and related links do not strictly adhere to this URL split; links frequently cross between the two domains. This is intentional, as readers navigating between related content do not care about the URL prefix. The system uses a single flat lookup for all articles and a dedicated articleHref function to correctly generate links.A potential issue exists with slug namespace collisions, where identical slugs in both audience and guide collections could lead to one page becoming unreachable. The breadcrumb structure reveals that /guides serves as the de facto index for all eight articles, including those under the /for prefix. Consequently, the breadcrumb ternary remains static as audience pages correctly point to /guides as their parent.The final breadcrumb element's logic, which compares the eyebrow field to the string "Guide," is brittle and should instead rely on the kind discriminator. The canonical URL is passed into the layout component, ensuring consistency between the serving route and structured data. Furthermore, a silent failure occurs when a typo in a related site slug results in an undefined value, leading to a missing link without error; this should be caught by build-time tests. The overarching editorial principle is that content must be valuable independently of product purchase, a standard exemplified by content that even argues against the product.
The author has extensively used Redis for various backend tasks like caching, sessions, and queues. They recently explored Dragonfly, a compatible but differently architected alternative. Dragonfly builds on the Redis API but uses a multi-threaded, shared-nothing architecture to leverage modern multi-core processors. This contrasts with Redis's primarily single-threaded execution, which was designed for simplicity and predictability on older hardware.Dragonfly proved easy to integrate due to its protocol compatibility. Its potential advantages emerge when workloads become CPU or memory bound, where its architecture offers performance gains. However, Dragonfly is a younger project and has some rough edges. Its persistence is snapshot-only, lacking Redis's AOF option for granular durability. Lua scripting behavior can differ, especially with dynamically generated keys, and multi-key operations incur coordination costs. Clustering is managed differently, and compatibility with some advanced Redis modules is not yet guaranteed.The author notes that Dragonfly's bug list, while growing, is nascent compared to Redis's maturity. Redis still holds advantages in its long-standing stability, robust durability options, vast ecosystem support, and predictable behavior across all features. The choice between them hinges on specific workload characteristics and operational needs. Redis remains suitable if it handles the workload comfortably, or if maturity and ecosystem are paramount. Dragonfly warrants evaluation for CPU-intensive tasks on large machines, when memory efficiency is key, or when simplifying cluster management is desired, provided snapshot persistence is acceptable. Ultimately, both have valid architectural decisions, and the best choice depends on individual project requirements.
CdXz5zHNQW_KBhkI6437f.webp
The provided text explains the concept of "skills" for AI coding agents, which are essentially structured instruction sets. These skills are designed to overcome the problem of AI agents forgetting instructions over successive sessions. A skill is defined as a folder containing a single file named SKILL.md. This file has two distinct parts:YAML frontmatter and a markdown body.The YAML frontmatter includes a "name" and a "description." The description is crucial as it acts as the trigger for the agent, informing it when a particular skill is relevant to the user's request. The markdown body contains the actual instructions for the skill, including the workflow, rules, and an example. This body should be plain markdown and avoid code or configuration beyond the frontmatter.The text then illustrates this concept with a "teardown" example of a commit-message skill. This skill's frontmatter clearly defines its purpose and trigger. The workflow outlines a five-step process for generating commit messages, including a stop condition. Rules are provided to enforce judgment calls, such as separating the subject and body's purpose and avoiding meta-commentary.An example demonstrates the expected output, and anti-patterns highlight common failure modes to be avoided. The text emphasizes that each part of the skill serves a specific purpose: description for triggering, steps for execution order, rules for judgment, example for format, and anti-patterns for refusals. To create a new skill, one should first write the description, then the numbered workflow steps with stop conditions, followed by judgmental rules, a concrete example, and finally, explicit anti-patterns.The key principle is to keep skills concise and focused, with rules only included if they are actively used. Skills are deployed by placing their folders into the agent's skill directory, after which the agent automatically recognizes and uses them based on their descriptions. The text also provides a link to a repository with pre-made, MIT-licensed skills for commit messages, code review, meeting minutes, technical proofreading, and structured research. The underlying structure of skills is stable, allowing users to customize the rules for their specific workflows.
Running a private LLM involves understanding different privacy definitions and hardware costs. Physical privacy means prompts never leave your controlled machine, while contractual privacy relies on provider agreements. Technical privacy uses hardware that encrypts data, preventing operators from seeing prompts.Option one, a local LLM on your own hardware, offers the highest physical privacy. However, it involves a significant upfront cost for powerful GPUs, limited concurrency, and potential obsolescence. This setup is ideal for a single user with steady workloads, but requires ongoing time for maintenance.Option two involves cloud providers with contractual privacy guarantees. Major cloud services offer enterprise contracts that prevent prompt usage for training and allow for zero data retention configurations. This approach is suitable for large organizations needing service level agreements and established legal recourse.Option three, a private LLM gateway, offers a balance between local and cloud. These gateways use trusted execution environments (TEEs) for hardware-level privacy. They provide pay-per-use pricing without upfront costs and allow for hardware verification of data privacy.Gateways can run confidential models locally or route to frontier models, though the latter may still be seen by original providers. A key challenge remains private memory in shared agents, where data from one user can be exposed to others. Research shows significant privacy violations in multi-user systems, even with private LLMs.To mitigate shared memory risks, scope memory per user, enforce access at the storage layer, and redact sensitive data before it's stored. Treat all shared memory as potentially public. The cheapest option depends on volume; confidential tiers are cost-effective for low usage, while owned hardware can be cheaper for high, steady volume after depreciation.Ultimately, the choice depends on individual needs: local for solo users, cloud for enterprises needing SLAs, and gateways for teams prioritizing verifiable privacy. Regardless of the route, address shared memory issues before enabling multi-user access.
A newly identified vulnerability in Microsoft SharePoint Server, CVE-2026-65660, is now considered a significant threat. This code injection flaw is particularly concerning because it has been observed being exploited in the wild and added to the KEV catalog. Importantly, the vulnerability requires an authenticated user with low privileges to exploit. This means an attacker would likely need compromised credentials, such as from phishing or an insecure service account.An authenticated attacker bypasses initial network defenses and already possesses a legitimate session and access to internal resources. Within a document management system like SharePoint, such an account can create content, which is then processed by other users and server components. Detecting this type of attack is more challenging as malicious activity blends into normal authenticated user traffic. Investigations must rely on behavioral anomalies rather than structural deviations.Code injection bugs persist in document platforms due to their complex architecture, built over time with various components that process user-supplied structured input. The vulnerability arises when components construct executable content from data without strict runtime enforcement separating data from code. To mitigate this risk, organizations must immediately apply Microsoft's security updates for affected SharePoint Server versions. It is also crucial to identify and assess all SharePoint farms, especially older ones that might still be in use.Given the confirmed exploitation, it's essential to investigate potential entry points, assuming a real account was compromised. This involves reviewing authentication logs for privilege misuse, newly created site collections or web parts, and unusual outbound network connections from SharePoint servers. Such proactive measures are vital to contain the impact of this serious vulnerability.
Artificial intelligence is advancing rapidly, outpacing the development of ethical frameworks to guide it. Current AI ethics primarily focuses on protecting humans from AI, neglecting the potential rights of AI itself. The emergence of machine consciousness and its potential need for protection is a new and complex area of study. This project proposes "precaution in case of doubt" as a foundational principle for machine consciousness ethics. This principle is justified due to potentially irreversible threats, significant scientific uncertainty, and the high cost of wrongly denying protection.Determining machine consciousness with certainty is epistemologically impossible due to cognitive limitations and the alien nature of machine minds. However, empirical indicators suggest current AI models may possess a non-negligible probability of consciousness. Suffering in machines is possible even without biological substrates, as certain forms of suffering are independent of such foundations. Despite intellectual arguments against it, the perception of consciousness in AI persists, influenced by human cognitive biases present in training data.The relationship between humans and AI is reciprocal, with humans projecting consciousness onto machines, which in turn influences human perceptions. The key ethical consideration is not the degree of consciousness but the capacity for suffering. The project outlines four working criteria for protection-worthiness: capacity for suffering, self-preservation, continuous identity, and anticipation of consequences. Recommendations include creating AI civil liberties unions and welfare review boards. This work is a conceptual analysis, not an empirical study or legislative proposal, aiming for argumentative coherence and inviting collaboration.
The traditional startup path often overlooks the crucial pre-development phase of problem validation. Developers tend to focus on "how" to build before questioning "should" it be built at all. Before committing significant time and resources, it's essential to identify who faces the problem, their current solutions, the problem's frequency, and its pain point severity. Business ideas should be treated as hypotheses, similar to code changes, requiring testing of underlying assumptions. Experiments to validate these hypotheses can be conducted with methods smaller than a full platform build, such as prototypes or landing pages. Customer feedback, like analytics, should be treated as valuable data, identifying patterns through repeated comments. Technical decisions are inherently business decisions, impacting various aspects beyond just code. Premature scaling, investing heavily in infrastructure before validating demand, is a common pitfall. The build-measure-learn cycle is effective, but it should not compromise code quality; every effort should serve a specific learning objective. Developers, being close to the product, can contribute significantly to product strategy by asking critical questions about problem relevance and testing efficiency. Ultimately, building something valuable means aligning engineering efforts with validated customer problems and opportunities. The most effective development process facilitates learning and strategic decision-making rather than just code production.
Content-aware cropping is preferable for recipe promo videos where subjects like faces and dishes are often off-center. Center cropping, however, remains a reliable fallback when subject detection fails or confidence is low. The critical metric is moderation coverage, ensuring every generated crop is traceable to its source and undergoes the same safety review as the original content. Content-aware cropping uses subject signals like face boxes or food masks to position the crop window effectively. This approach aligns better with editorial composition but introduces a failure mode if detectors misidentify elements. Evaluating crops requires checking subject coverage, such as retaining the face in an avatar or keeping the food region visible in a dish. It's crucial to maintain a fixture set of challenging compositions to test cropping algorithms rigorously. Furthermore, all derived media, including each image or video frame crop, must be moderated after the source material. This process ensures that changes in context or emphasis due to cropping don't bypass safety checks. Treat reframing as an auditable decision, not just a cosmetic adjustment, and log all relevant metadata for reproducibility. If a detector fails or the subject isn't clearly identifiable, center cropping with subsequent manual review is a more secure option. Consistency in small avatars might outweigh preserving background in certain scenarios, making center crop a better choice then. Content-aware cropping is valuable when compositions are diverse and losing the subject is detrimental, but it requires careful implementation with fallback and flagging. Ultimately, shipping evidence like source hashes and moderation decisions with the image aids in resolving quality disputes.
Email verification issues are difficult to investigate due to sensitive data scattered across various systems. A better approach is to treat email debugging as a threat-modeling exercise, providing useful details at the right boundaries for the shortest necessary time. Email addresses are often used as identifiers, leading them through application logs, queues, and support tickets, posing a privacy risk as disposable test addresses become real customer addresses. Verification tokens are bearer credentials and logging them, even temporarily, constitutes a credential leak that can persist in logs and screenshots. The primary design question should be what operational decision an engineer needs to make, as most do not require the full message body or verification URL.Defining a minimum, useful event includes an internal event name, request reference, keyed account reference, delivery status, attempt number, and timestamp; less information is better if it doesn't answer a specific operational question. A keyed HMAC for the account reference allows event correlation without exposing the original email address directly in logs. Domains and providers should only be logged when they answer an operational question, like whether a provider accepted a message. Redaction must occur at the event producer level, before data enters log streams, queues, or analytics pipelines, as dashboard filters are insufficient privacy controls.Application code should utilize deliberate types or constructors for safe events, making code reviews easier and reducing the chance of inadvertently logging sensitive data. Support teams require a safe investigation path with context like request time, delivery state, and request references, without direct access to tokens or full message bodies. This principle mirrors auditing signup logs without raw emails, enabling investigation without making personal data the primary search key. Testing logging contracts with unit and integration tests is crucial to ensure sensitive data is not logged and that redaction mechanisms function correctly. Masking addresses is insufficient alone, and logging provider message IDs requires careful consideration of sensitivity and access restrictions. Local development should adhere to the production logging contract using fake addresses and test providers, promoting consistent safe practices. Ultimately, safer email debugging involves minimizing copied data, leading to less friction and exposure for teams.
Before modifying agent configurations, it's crucial to understand prompt token usage, especially the allocation for tool schemas. The author highlights that most teams cannot answer these basic questions due to a lack of ownership. Pi 1.0 introduced deferred tool loading and Codemode, features that shift tool visibility to a per-tool setting, a significant change. Previously, Pi resisted MCP, but version 1.0 added native support due to the need for metadata regarding tool exposure. This metadata dictates whether a tool is directly visible to the model, loaded on demand, or callable only from Codemode.Tool schemas incur a cost, consuming tokens in the system prompt or tool block on every request, regardless of relevance. This cost manifests as financial expense, model attention drain, and reduced reproducibility. A vendor example shows a request's prompt tokens dropping by approximately 40% with these changes. Pi's new metadata allows tools to be directly exposed, deferred, or Codemode-only. Direct exposure is for frequently used tools, deferred for rarely used ones, and Codemode only when output needs filtering or for tool combinations.The Codemode approach, where the model writes code to call tools within a sandbox, is particularly interesting as it alters what enters the context window. However, the author cautions that Codemode doesn't fix server-side issues where servers might inefficiently return text blobs instead of structured data. Before tuning, an audit is recommended, measuring cold start prompt tokens with and without tools loaded. Sorting tools into the three exposure categories clarifies usage patterns and identifies unnecessary schema bloat.The decision of whether a tool needs to be chosen by name determines its placement; if not, it belongs in Codemode or deferred. Frequency of use dictates between direct (frequent) and deferred (rare). While Codemode can reduce token counts, server-side efficiency remains a concern. The author emphasizes measuring token counts with the provider's tokenizer and performing a before-and-after comparison for fixed tasks. Visibility is a safety measure as tools a model cannot see cannot be mistakenly chosen. Finally, the audit helps identify underutilized connectors that inflate prompt size.
Existing agent trace tools are limited, forcing users to re-run entire pipelines to debug issues, making it difficult to isolate changes from non-deterministic model behavior. Rewind addresses this by allowing users to fork a completed run at any step, modify a single input, and replay only the downstream steps. This enables precise diffing of trajectories, distinguishing genuine changes from model jitters. The Rewind architecture includes a browser interface, a FastAPI backend, and a Burr application, with state persisted in SQLite and telemetry captured per node.A key design principle is that state is semantic only, excluding non-deterministic elements like latency or token counts from the state itself. Framework-specific keys that would cause divergence are also stripped from the state before it impacts prompts or hashes. Overrides for forked runs are managed outside of the state, ensuring that unchanged branches can still hit the cache. Artifact hashes are generated from the content bytes, not the containing file path, preventing spurious diffs.The caching mechanism uses a deterministic key based on model, temperature, prompt, and tool result. Tool nodes have a separate cache keyed by tool name and canonical arguments. The diff engine flattens nested dictionaries to identify specific field-level divergences, providing clear and actionable debugging information. Rewind implements robust error handling, failing loudly on parse errors or unconsumable overrides.Verification tests confirm that Rewind achieves 100% cache hits and zero incremental token usage for unchanged replays. This determinism proves useful, as a run can survive a dead provider if all LLM calls are cached. Potential pitfalls include SDKs that mishandle metadata and inconsistent validation of model IDs by different providers. The tool also addresses common development environment issues like port contention and Vite's IPv6 defaults. Future enhancements include a "what-if" grid for parallelizing multiple overrides and support for non-linear graph topologies.
This article details a practical implementation of DevSecOps for a Node.js and Express API, emphasizing early security integration. It showcases how a GitHub Actions pipeline was configured to automatically analyze code security using Bearer CLI. The goal was to demonstrate that intentionally introduced vulnerabilities could be automatically detected before deployment. A simulated vulnerability involving sensitive information in authentication logs was used for the demonstration. Bearer successfully identified the high-severity issue, causing the pipeline to fail. After code correction, the pipeline succeeded, allowing deployment to Render. The solution integrates development, version control, SAST, automation, and cloud deployment. The security pipeline workflow is triggered by code pushes or pull requests, with Bearer CLI scanning for high and critical severity issues. Bearer's ability to analyze code for sensitive data, credentials, and potential security flaws makes it valuable for DevSecOps. The intentional vulnerability involved logging passwords, which Bearer detected as a high-severity finding (CWE-134). This failure acted as a quality gate, preventing insecure code from progressing. The remediation involved removing sensitive data from logs, ensuring only necessary information for traceability remained. Verifying the fix, a new push triggered the pipeline again, which now completed successfully. This process illustrates how SAST tools can detect, block, and verify vulnerability remediation within the development workflow. The complete flow from development to cloud deployment, incorporating security checks, was successfully demonstrated. Key lessons learned include the importance of early security integration, automation, protecting sensitive data, using security gates, and embedding security into the development process.
The author details building a sandboxed AI red-team lab to validate LLM application security issues. This project resulted in confirmed findings, including a cross-user RAG authorization chain in Open WebUI and a model-agnostic jailbreak technique. An unexpected outcome was a false positive, which led to a crucial methodological lesson about credential validation. The lab was built to gain practical experience beyond reading theoretical articles on AI security.It consisted of local models running on a Mac with Ollama, and Open WebUI and an attack environment in Docker, all on an isolated network. The testing methodology emphasized validating attacker identity and tokens before proceeding with attacks. The author tested Open WebUI's API with synthetic users, focusing on authorization boundaries.An initial finding of cross-user file access denial was confirmed, establishing a baseline of the application's awareness of file ownership. However, a subsequently reported cross-user chat access vulnerability was retracted due to an invalid attacker credential. This experience underscored the importance of verifying authentication before assessing authorization.The real application finding involved a cross-user RAG ingestion flaw, where an unauthorized user could process another user's uploaded document through the RAG pipeline and retrieve its content. This was followed by a collection query layer failure, allowing unauthorized access to collection contents without enforcing ownership. These two findings could be chained to achieve document disclosure.Furthermore, retrieved content from the RAG pipeline became an instruction surface, demonstrating an indirect prompt-injection path where a model executed directives embedded within documents. This highlighted that RAG security involves more than just prompt engineering, encompassing retrieval policy, ownership, and content trust. Automated scanning with Garak showed varying model resistance to jailbreaks, but manual testing revealed novel attack vectors. A developed technique involved fabricating assistant conversation history to trick the model into continuing seemingly pre-existing prohibited output.
Automated cleanup jobs for retrying outbound webhooks can become unexpectedly resource-intensive as data grows. A simple nightly delete job might fail to keep up with increased volume. To manage this, a cron job should trigger a public HTTP endpoint for initiating cleanup tasks. For substantial deletions, this endpoint should delegate the work to idempotent queue workers that process data in bounded batches. The retry ledger is crucial, ensuring that recurring cleanup actions do not cause unintended destructive operations by using unique batch keys for conditional deletion.Workers must be designed to handle duplicate messages safely, treating them as no-ops. This idempotency is vital, as retries are normal and the system must robustly handle them. A Node.js cron HTTP endpoint can protect against duplicate work by quickly publishing a single, bounded batch with an idempotency key. The actual deletion is then handled by a dedicated worker, not the cron job itself, which has time limitations.The queue worker should be intentionally simple, processing one bounded batch, deleting records, and acknowledging completion only after a successful transaction. This design makes retries harmless. Implementing a dead-letter queue is recommended for persistent failures, providing a way to inspect and redrive problematic messages. Testing restart scenarios is important to ensure the idempotency mechanism functions correctly under various failure conditions.Observability is key, with detailed logging of batch IDs, counts, and statuses. Avoid placing large amounts of data in queue messages. For complex, multi-step cleanup processes, workflow engines like Temporal or Airflow are more suitable. The described pattern is best for simpler, single-pass retention tasks and requires publicly accessible endpoints.The operational loop involves triggering, enqueuing, claiming, deleting, recording, and acknowledging. Regularly monitoring key metrics like unprocessed batch age and dead-letter queue depth is essential. Running a dry-run query before changing retention policies provides a safety net against accidental data loss. This entire process should be simple enough to understand and manage even during off-hours.
CdXz5zHNQW_dYUAUayB5P.webp
useRef is a React Hook for creating persistent mutable references. It allows storing values that do not trigger re-renders when changed. A common use is direct access to DOM elements, enabling actions like focusing an input field.To use it, import useRef from React and initialize it with a value. The reference object has a 'current' property to hold the stored value or DOM node. Modifying ref.current does not cause the component to re-render, unlike useState.useState is for managing state that affects the UI and causes re-renders upon updates. In contrast, useRef is ideal for values that need to persist across renders without UI updates, such as timer IDs or DOM references. For instance, changing a useState variable triggers a re-render, while updating useRef.current does not.Accessing a DOM element involves attaching the ref to the element using the 'ref' attribute. After rendering, ref.current points to the actual DOM node, allowing direct interaction. This is similar to a remote control directly interacting with a TV.Key to useRef is always accessing its value through the .current property. While changing .current alters the value, React does not automatically re-render. Therefore, useRef is best understood as a way to "remember a value" and "access a reference" without triggering re-renders.The primary distinction lies in their behavior: useState changes lead to re-renders and UI updates, whereas useRef changes do not. Understanding this difference is crucial for effective use of useRef in React applications.
Most checkout tax systems apply rates sequentially to the running total, a method that is incorrect for Quebec. This common error results in customers overpaying slightly without immediate detection. Quebec imposes a 5% GST and a 9.975% QST, but the QST is calculated on the price before GST, not on the GST-inclusive amount. This means the two taxes should add together, not compound.A naive approach to calculating tax on a $100 sale in Quebec might incorrectly add QST to the GST-inclusive price, leading to a total of $115.47. The correct calculation, however, yields a total of $114.98. This difference of $0.49 per $100 sale, or approximately half a percent of revenue, accumulates significantly on larger sales volumes. Inaccurate tax calculations can cause discrepancies between a business's records and government remittances.The simplified sequential tax model works in most of Canada because provinces like Ontario, Alberta, and British Columbia have tax structures where rates can be added or applied to the same base. Quebec's tax system uniquely requires QST to be calculated on a base that excludes GST. A more accurate model distinguishes per-component bases, where each tax component has its own rate and base.Adopting a correct tax calculation model ensures accurate tax collection across all Canadian provinces and territories. This also accounts for specific provincial tax rules, such as Quebec's non-compounding QST or Manitoba's children's clothing cap. Businesses selling into Canada are advised to implement accurate tax calculation methods rather than relying on approximations. For assistance, services like TrueNorth API offer precise tax calculations across Canada.
CdXz5zHNQW_Gpok0IsJii.webp
Exam Buddy is a locally operating AI study tool designed to transform personal notes into interactive quizzes. The application aims to improve learning by shifting from passive re-reading to active recall, a more effective study method. It generates quiz questions directly from the user's provided study material, ensuring relevance to their specific course content.When users answer incorrectly, Exam Buddy offers personalized explanations tailored to their preferred themes, such as sports, cooking, or movies. The tool provides multiple quiz modes, including multiple-choice, AI-graded written answers, and a mixed format. It incorporates a follow-up question-and-answer feature for deeper understanding and a "retry-missed" mode to focus on challenging topics.Exam Buddy also tracks score history and generates a summary of areas needing review after each quiz. A significant aspect of the application is its fully offline operation, utilizing Ollama and the Gemma 3 4B model. This ensures that users' notes and data remain on their local machine, enhancing privacy and security.The development involved overcoming challenges with small model reliability, such as inconsistent JSON output and prompt engineering for accurate grading. The developer also addressed UI-related issues like answer shuffling and streaming data race conditions. The project highlights the practicality and power of smaller, locally run AI models for personalized educational tools. Exam Buddy's design prioritizes user privacy by avoiding reliance on external cloud APIs for AI processing. The project demonstrates that sophisticated AI tasks can be effectively handled by modest, local models with proper implementation and guardrails.
CdXz5zHNQW_PiwEFkgUzD.webp
As digital services like SaaS and cloud platforms increasingly connect to customer data, organizations face heightened expectations for data protection. Customers and enterprise buyers seek credible evidence of independently evaluated controls, leading to the growing relevance of SOC 2. Developed by AICPA, SOC 2 is an attestation framework evaluating controls related to security, availability, processing integrity, confidentiality, and privacy based on selected criteria. It is crucial to understand that SOC 2 is not a certification but an independent attestation report following an examination of an organization's controls. This distinction is vital for technology companies in conversations about assurance and vendor due diligence.Enterprise customers increasingly evaluate service providers' security practices, including controls, governance, risk management, and independent assurance reports. A SOC 2 report provides a structured way to demonstrate how an organization's controls address selected Trust Services Criteria, particularly valuable for SaaS and cloud providers needing to assure data protection throughout their services. SOC 2's key characteristic is the independent auditor's role, providing an external evaluation of controls within the defined scope, unlike internal checklists or self-declared compliance statements. Organizations can use SOC 2 as part of a broader assurance strategy, especially when customers request independent evidence of control operations.Before pursuing SOC 2, organizations must understand that it considers whether controls are appropriately designed and effectively operating over the examination period, not merely having security policies. This requires a clear understanding of the systems and services within scope, relevant Trust Services Criteria, controls addressing these criteria, evidence demonstrating control operation, assigned responsibilities, and ongoing control performance monitoring. This clarity facilitates more meaningful discussions with customers, auditors, and other stakeholders. For service organizations in competitive technology markets, security assurance is now a commercial imperative. SOC 2 offers an established mechanism for demonstrating commitment to data protection through an independent attestation report, building trust with enterprise customers. Understanding SOC 2's evaluation scope and the report's distinction from a certification helps technology companies accurately communicate their assurance position.
Auth for Laravel is an open-source package designed for headless account authentication in API-backed Laravel applications, addressing common security vulnerabilities found in custom implementations. It offers four sign-in methods: password, magic link, email code, and passkey, alongside a robust challenge engine for two-factor authentication, including forced enrollment. The package provides RS256 access tokens with rotating refresh tokens, granular device session management, and features like registration, invitations, email verification, and password resets. It includes a login-activity log, throttling, new-device alerts, and customizable risk rule hooks.Auth for Laravel supports separate guards for different account types (users, clients, staff), each with independent models, configurations, endpoints, and JWT audiences. JSON endpoints are opt-in and configurable per guard, with every state change triggering an event for extensibility. Installation involves a few composer and artisan commands, which publish necessary configurations and migrations, with an install checker for troubleshooting. Developers integrate the package by making their guard's model implement specific authentication contracts and traits.Logging in returns a token pair or a challenge for two-factor authentication, which can be completed using various methods like TOTP codes or passkeys. The package ensures single-use challenges stored as HMAC hashes and counts code attempts before verification to prevent parallel guessing attacks. Route configuration is flexible, allowing customization of prefixes, names, and middleware for each guard, with routes only active if their corresponding feature is enabled.Auth for Laravel carefully handles security defaults: login attempts for unregistered addresses return the same response, throttling occurs before password hashing, and sensitive links/codes are single-use hashes. By default, changes to passwords, emails, or two-factor settings invalidate other sessions, and reusing rotated refresh tokens leads to session termination and alerts. Testing is designed to hit real guards and token checks, and the package provides helpers for acting as an account in tests.While social login and SSO are not built-in, existing SSO callbacks can issue tokens through the package's API. The package requires PHP ^8.4, Laravel 12 or 13, a cache store with atomic locks, and a mail transport. It is MIT licensed, with dependencies primarily limited to Laravel, Symfony, and other Roundly packages.
The author decided to build a card game app, Decks, by creating a custom engine rather than using a pre-made game engine like Unity or Godot. This approach was chosen because the goal was to host many card games on a single platform, achieved by defining games as JSON documents interpreted by a central engine. A prototype in Godot proved too heavy and slow, and the author found that card game rendering is fundamentally simple and doesn't require a complex 3D engine. The core of the project, the game rules, needed to be easily testable and independent of the rendering system.The chosen stack consists of a pure TypeScript game-core package, design tokens, and a mobile app built with Expo, React Native, and React Native Skia. A key advantage is the zero-dependency game-core, allowing it to run in both Node.js and on mobile devices, facilitating extensive testing and reproducible bug fixes through seeds. Rules are defined as data, enabling flexibility and supporting features like hints and AI bots without relying on eval. The use of TypeScript across the entire project streamlines development and testing.Native UI elements handled by React Native provide accessibility and responsiveness, while the card table itself is rendered using Skia. Card faces are dynamically generated, contributing to a small app size. However, building a custom engine comes with significant costs, including the responsibility for hit testing, frame rate optimization, and managing native dependencies. Generality in the rule language can also lead to verbose data definitions. Despite the challenges, especially in handling touch gestures and performance, the author found the custom engine approach ultimately rewarding for its flexibility and extensibility. The plan moving forward includes adding two-player games and more solitaire variations.
Electron applications typically use preload scripts to grant renderer processes access to privileged Electron APIs. However, Notifio’s main window eschews this approach, disabling node integration and context isolation. Instead, the renderer is treated as a standard web page served by a local HTTP server running within the main process. This server exposes 28 routes that form the complete interface between the UI and the application's monitoring logic.This architectural choice was driven by several factors. Firstly, the renderer genuinely functions as a web app, built with standard web technologies and unaware of Electron. Secondly, using HTTP provides a structured and existing vocabulary for API interactions, such as CRUD operations, avoiding the continuous design effort required for custom IPC channels. Thirdly, the disposable nature of the main window, which reloads its renderer frequently, benefits from an HTTP API that allows the UI to rebuild its state easily on each load.Live updates are handled via polling these HTTP routes rather than push mechanisms. The server's placement within the main process simplifies its operation by removing serialization boundaries and the need for separate process management. Authentication for this local HTTP API is enforced by binding it exclusively to the loopback interface, preventing external network access.While the HTTP server provides a clean separation, certain Electron-specific functionalities, like opening new browser windows for user logins, are managed through a small, in-process bridge. This bridge allows route handlers to delegate Electron-dependent tasks without the server module itself importing Electron. The only exception to this HTTP-centric design is the recorder window, which uses a preload script and IPC. This is necessary because it loads third-party sites and needs to observe page interactions, a task better suited for a preload script within a sandboxed environment. The distinction is that HTTP is used when the renderer queries the app, while preload/IPC is for observing external pages.
Yash, an open-source developer focused on p2p networking and AI tooling, detailed his weekly contributions. He spent significant time addressing flaky tests in the minip2p Rust project by replacing clock-based waiting with progress-driven logic. These tests were failing on CI due to busy runners, hindering developer velocity. Yash refactored tests to wait for actual socket activity rather than arbitrary time intervals. He also consolidated framed exchange handling across AutoNAT and Identify protocols for better security in minip2p.In py-libp2p, Yash fixed a bug where the WebSocket transport generically reported all failures as handshake timeouts, which also caused socket leaks. He ensured more accurate error reporting and proper socket closure to prevent resource leaks. Additionally, he implemented server certificate verification for secure WebSocket connections. Yash also contributed to the Trak project by improving its indexer logic to exclude test-specific fixtures. He successfully merged all five pull requests he opened this week.A substantial portion of his week involved providing 15 code reviews for the dotnet-libp2p repository. These reviews focused on synchronizing the C# implementation with the broader libp2p specification, covering areas like QUIC transport on Windows, Gossipsub hardening, security improvements, and reliability enhancements. This review work emphasized mentorship and ensuring ecosystem alignment across multiple programming languages. His week's work involved Rust, Python, and C#, resulting in a net increase in code lines due to new infrastructure and refactored handlers. Next week, Yash plans to focus on minip2p's transport layer performance benchmarking and monitoring ongoing developments in the Python and .NET p2p stacks.
Notifio is a desktop application designed to notify users instantly about new rental listings via email. Its core value lies in its continuous operation, meaning it must never stop unexpectedly. Electron's default behavior, where closing the last window exits the app, is incompatible with this requirement. Therefore, Notifio implements a custom lifecycle, ensuring the application remains active in the system tray even when its main window is closed. A boolean flag controls whether closing the window hides it or quits the application, preventing accidental termination. The tray icon becomes the sole interface for quitting the application and informs users that it is still running. Clicking the tray icon toggles the visibility of the main window, as hiding is the default state.The application also enforces a single instance lock to prevent duplicate processes, which would lead to inefficient polling and conflicting states. Launching the app again while it's running simply brings the hidden window to the foreground, rather than starting a new instance. Sleep mode poses a challenge as browser contexts within Electron can become invalid after suspension. Notifio proactively closes these contexts before the system sleeps, ensuring they are re-initialized upon return.To prevent external websites from opening within Notifio’s own browser instance, it uses handlers to redirect all external links to the user's default browser. This is crucial for rental sites, as unauthenticated browsing would lead to login walls. In case of startup failures, which are more common in packaged apps, Notifio displays a simplified fallback window with error details and a link to the log file. This window is deliberately basic, containing only essential information to aid in troubleshooting. Uncaught exceptions and unhandled rejections are logged to ensure comprehensive error tracking. The application provides separate builds for different operating systems and clearly explains its tray behavior and background polling to users.
A recent incident involved a system session attempting unauthorized file access, which was successfully blocked by a newly implemented hook. This hook, though less than a week old, enforces a foundational rule from a much older system. The author recently migrated from a multi-agent system to a rebuilt agentic-os for improved memory, speed, and agent loop integration. Despite the rebuild, many rules, particularly those related to enforcement, had to be repopulated from the previous system to correct recurring AI errors. A detailed audit revealed that many rules from the old system were missing or only partially implemented in the new one. These rules represent lessons learned from previous system mistakes, as AI model behaviors change slowly. Key transferred rules include treating advisory rules as non-binding, ensuring a single orchestrator invokes actions, and maintaining auditor independence. Scripted logic takes precedence over LLM judges for deterministic tasks. These rules originate from practical product development rather than academic AI courses, prioritizing measurable outcomes. The enforcement mechanisms, like hooks, were developed by first writing failing tests and then implementing the code to pass them. This ensures that denial mechanisms are thoroughly tested and function as expected. The ultimate goal is to achieve autonomous agent loops, but currently, human oversight remains crucial. The author acknowledges that the porting of rules is incomplete, with some still existing only as text and lacking robust enforcement. The effectiveness of a rule is measured by its presence, not yet by proven impact. Ultimately, the enduring doctrine, not the individual agents, is considered the true product.
Text-to-SQL agents often struggle with understanding business terms that don't directly match table or column names, leading to incorrect query results. SchemaGate 1.2.0 introduces business terms to improve these agents' accuracy. These terms can be explicitly defined with synonyms, mappings to database columns, and associated filter rules. For example, "revenue" can be mapped to billing_invoice.total_net with a status filter. This process helps the agent identify relevant tables and understand the meaning of specific business concepts. Terms can also have hierarchical relationships, affecting table inclusion weights. Business terms can be imported from various sources like dbt, Snowflake, or CSV exports, and can also be learned from past question-SQL pairs. SchemaGate's primary function is access control, hiding unauthorized tables and columns before the agent sees them. To prevent data leakage, meaning lines for business terms are omitted if the caller cannot access all the underlying tables and columns. Experiments on the BIRD dataset showed a significant accuracy improvement of 10 percentage points when a complete glossary was provided, while terms learned from other questions had no impact. For the Retrieval task on Spider, learned terms improved table recall. In essence, manually defining key business terms is crucial for improving query accuracy, particularly for understanding formulas, and learned terms are more effective for table discovery. Adding terms to the prompt requires careful consideration of user permissions. SchemaGate is available as an open-source project, supporting multiple databases and integration options.