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

标签:#ia

找到 1570 篇相关文章

AI 资讯

React useIsomorphicLayoutEffect: Fix the SSR useLayoutEffect Warning (2026)

You added a useLayoutEffect to measure a tooltip, shipped it, and the next time your Next.js (or Remix, or Gatsby) dev server rendered a page on the server, the console lit up: Warning: useLayoutEffect does nothing on the server, because its effect cannot be encoded into the server renderer's output format. This will lead to a mismatch between the initial, non-hydrated UI and the intended UI. To avoid this, useLayoutEffect should only be used in components that render exclusively on the client. The warning is correct, the suggested fix ("only use it on the client") is unhelpful, and the obvious workaround — just switch to useEffect — quietly reintroduces the visual bug you used useLayoutEffect to kill in the first place. useIsomorphicLayoutEffect is the small hook that resolves the standoff. This post explains exactly why the warning happens, why the two naive fixes are both wrong, and what the one-line hook actually does. Why useLayoutEffect Exists At All React gives you two effect hooks that look nearly identical: useEffect runs after the browser has painted. Its callback is queued and fires asynchronously once the frame is on screen. useLayoutEffect runs before the browser paints, synchronously, right after React has mutated the DOM but before the user sees anything. That timing difference is the whole point. If you need to read layout — getBoundingClientRect , scrollHeight , the measured width of a node — and then write a style based on it, you have to do it before paint. Otherwise the user sees one frame of the wrong layout, then a flicker as your useEffect corrects it. The canonical example is a tooltip that has to position itself relative to its own measured size: function Tooltip ({ targetRect , children }) { const ref = useRef < HTMLDivElement > ( null ); const [ pos , setPos ] = useState ({ top : 0 , left : 0 }); useLayoutEffect (() => { const { height , width } = ref . current ! . getBoundingClientRect (); // place the tooltip above the target, centered s

2026-06-25 原文 →
AI 资讯

GitHub ships a one-click self-revoke for users whose credentials just leaked

You forwarded the phishing email to the security channel about ninety seconds too late. The laptop is already cooperating with someone else. Your personal access token, the one you minted "just for that one script", is on its way to whatever Discord pays for stolen tokens this week. Now what? For users on GitHub Enterprise, what was previously a clickthrough checklist you complete while your hands shake is now one button. On June 24 the GitHub Changelog announced a self-service credential revocation flow under Settings, Credentials. From that view a user can see counts of every credential they have generated or authorized through SSO, then revoke or delete all of them in a single action. Personal access tokens, SSH keys, OAuth tokens, SSO authorizations: gone together. What actually shipped Containment used to be a manual scavenger hunt. PATs sat under Developer Settings. SSH keys lived one tab over. OAuth apps you forgot you authorized two years ago hid behind a different submenu. SSO was its own world. In practice that meant during an incident you forgot something, and the something you forgot was the credential the attacker actually wanted. The new view collapses that surface onto one screen. Counts on one side, a revoke-or-delete-everything action on the other. Whoever wrote it had clearly pictured the 3am screenshot: a user who has just been told to "rotate everything" and has no idea where "everything" lives. GitHub frames this as a complement to an earlier enterprise-owner capability that lets admins with the "Manage enterprise credentials" permission bulk-revoke across one user or many. So there are now two pairs of hands on the kill switch: the user, and the org. (Whichever one notices first.) Why a pipeline owner should care Because users are the trust boundary you keep pretending is somebody else's problem. A leaked PAT in a CI pipeline is rarely a CI bug. It is a human who pasted the token into a script, then a laptop, then a sync folder, then a backup,

2026-06-25 原文 →
AI 资讯

Apache Iceberg in Production: Compaction, Catalogs, and the Pitfalls Nobody Warns You About

Apache Iceberg looked like the answer to everything when we first adopted it. Open format, ACID transactions, time travel, schema evolution. We migrated our Hive tables, ran a few queries, and felt good about life. Three months later, our S3 costs doubled. Queries that used to take 10 seconds were taking 4 minutes. Metadata operations were timing out. Nobody on the team could explain why. That was the beginning of a real education in how Iceberg actually behaves in production. This post covers what I wish someone had told us before we went all-in. The Small Files Problem Is Not Optional Iceberg is append-friendly by design. Every micro-batch write, every streaming insert, every incremental load creates new Parquet files. Each file also gets its own metadata entry. After a week of hourly loads, you might have 10,000 files in a single partition where you wanted 20. The result: Iceberg's metadata layer has to plan queries across thousands of file manifests. Planning takes longer than execution. Your 10-second query becomes a 4-minute query, and your users start filing tickets. Fix: automate compaction from day one. In Spark, compaction is called rewrite_data_files . The basic call looks like this: -- Run this on a schedule, not on-demand CALL iceberg_catalog . system . rewrite_data_files ( table => 'analytics.events' , strategy => 'binpack' , options => map ( 'target-file-size-bytes' , '134217728' , -- 128MB target per file 'min-input-files' , '5' -- only compact if 5+ small files exist ) ) Target file size of 128MB to 512MB is the practical sweet spot. Smaller than that, you still have too many files. Larger, and your query engines cannot parallelize reads efficiently. If you are not using Spark, PyIceberg exposes compaction through the table maintenance API (as of 0.7.x). For Flink or Trino-only shops, schedule compaction as a separate Spark job. Yes, it is annoying, but it is the right call. Hidden Partitioning Is the Feature You Are Probably Ignoring Old Hive parti

2026-06-25 原文 →
AI 资讯

Inbox Zero for Devs: How I Built a JavaScript Script to Destroy Gmail Spam

Hey dev community! 👋 As developers, our inboxes often turn into a graveyard of job alerts (LinkedIn, Indeed, ZipRecruiter) and tech newsletters we subscribe to with the intention of "reading later" but never actually open. The result? Important emails get lost, and we get the dreaded "Account storage is almost full" notification. Recently, I hit that wall. I had thousands of accumulated emails. While Gmail allows you to create filters for incoming mail, it doesn't have a native feature to say: "Delete this email automatically after 7 days" . So, I decided to solve it the way we solve everything: by writing some code. 🛠️ The Solution: Google Apps Script + JavaScript Since the Google Workspace ecosystem runs on a JavaScript-based environment, I put together a custom script. Fun fact: a simple loop originally failed due to Google's strict 6-minute execution limit. To fix this, I optimized the code to process emails in batches of 100 , preventing the server from timing out. Here is the final production-ready script: function cleanSpamTsunami() { // 1. Loop to delete ALL Job Board emails in batches of 100 var continueJobSearch = true; while (continueJobSearch) { var jobThreads = GmailApp.search('computrabajo OR indeed OR linkedin OR OCC OR neuvoo OR talent.com OR jooble', 0, 100); if (jobThreads.length > 0) { Logger.log('Deleting a batch of ' + jobThreads.length + ' job alert emails...'); GmailApp.moveThreadsToTrash(jobThreads); } else { Logger.log('No more job alerts found!'); continueJobSearch = false; // Break the loop } } // 2. Loop to delete old Newsletters (older than 7 days) in batches of 100 var continueNewsletters = true; while (continueNewsletters) { var newsletterThreads = GmailApp.search('unsubscribe OR "cancelar suscripción" older_than:7d', 0, 100); if (newsletterThreads.length > 0) { Logger.log('Deleting a batch of ' + newsletterThreads.length + ' old newsletters...'); GmailApp.moveThreadsToTrash(newsletterThreads); } else { Logger.log('No more old newslett

2026-06-25 原文 →
AI 资讯

The Missing Manual: 160+ free Dev guides on debugging, Programming, infrastructure, AI and more

There's a specific kind of bad documentation that I think we've all suffered through. You search for "what is a goroutine" or "how do database transactions work" and you get one of two things: either a six-page academic paper that assumes you already know the answer, or a tutorial so watered-down it covers nothing real. What you actually want is someone like that senior engineer at your company the one who, when you finally work up the nerve to ask a dumb question, sits down and actually explains the thing. Not just the what, but the why. Not just the happy path, but the part where you'll get confused at 2am and what to do about it. I've been building that resource. It's called The Missing Manual. Here's the pitch in one sentence: it's a free, growing library of developer guides written like advice from a battle-hardened friend who genuinely wants you to understand the thing, not just copy the code. Some examples of what's in there right now: Reading a Stack Trace at 2am — starts with "that wall of text is not an attack, it's a map," then teaches you the four-step method that works in Python, JavaScript, Java, or whatever you're using. Includes the site-packages/ vs your-own-code trick that turns 40-line traces into 2-line ones. Go From Zero - covers the basics, but also the deep stuff that most Go tutorials skip: what the GMP scheduler actually does, how escape analysis decides what lives on the heap, why goroutines are cheap in a way OS threads aren't. Mental-model-first, the whole way through. Docker Without the Magic - doesn't just show you docker run. Explains what a namespace and a cgroup actually are, so when Docker does something weird, you have somewhere to start. Why Is My Query Slow? - the real answer, including EXPLAIN, index cardinality, the N+1 problem, and what "using index" in a query plan actually means vs what you want it to mean. There are 160+ guides across debugging, databases, infrastructure, networking, APIs, AI/ML, performance, and programmin

2026-06-25 原文 →
AI 资讯

Legacy code não envelhece como vinho: quanto mais espera, pior fica

Semana passada eu passei três horas debugando um bug que deveria levar 20 minutos. O problema? Um módulo de validação escrito em 2019 que ninguém mexe "porque funciona". Spoiler: não funcionava mais, e quando finalmente abri o arquivo, encontrei um // TODO: refactor this datado de 2020. Por que legacy vira bola de neve A indústria trata código legado como se fosse dívida técnica opcional — algo que você paga "quando tiver tempo". Mas código legado se comporta mais como mofo: se espalha, contamina áreas adjacentes, e quanto mais você ignora, mais cara fica a limpeza. O ciclo é previsível: você herda um projeto ou feature antiga, vê que está "meio bagunçado mas roda", adiciona sua feature com um if a mais, e segue em frente. Seis meses depois, outra pessoa faz o mesmo. Um ano depois, aquele arquivo tem 800 linhas, cinco níveis de if aninhados, e zero testes. Ninguém mais entende o fluxo completo, então cada mudança vira uma sessão de especulação: "se eu mexer aqui, quebra ali?" O custo real de esperar Esse código "que funciona" tem um custo oculto que aparece em três formas: Velocidade de desenvolvimento despenca. Features que deveriam levar dois dias levam uma semana porque você passa mais tempo entendendo o contexto do que escrevendo código novo. Bugs aumentam exponencialmente. Código sem testes e com lógica embolada é um gerador de regressões. Você corrige um edge case e quebra outro que nem sabia que existava. Onboarding vira tortura. Novo dev no time? Boa sorte explicando por que aquele service tem três formas diferentes de fazer autenticação, ou por que a mesma validação está copiada em sete lugares. Sinais de que você está sentado em cima de uma bomba Nem todo código antigo é legacy tóxico. Aqui estão os red flags que indicam que você precisa agir agora: // Red flag #1: comentários mentirosos ou inúteis function processPayment ( order ) { // Process the payment const user = order . user ; // TODO: fix this later // HACK: don't touch this, breaks prod if ( user

2026-06-24 原文 →
AI 资讯

How to Fetch Real-Time Options Chain Data in Python (Without Paying $99/mo)

If you've ever tried to pull live options data into a Python script, you've probably hit the same wall I did: the cheapest real-time providers start at $99/mo. Here's how to do it for $20/mo — or free if you stay within 1,000 credits/day. What You'll Need Python 3.8+ requests library ( pip install requests ) An API key from market-option.com (free tier available, no card required) Fetching a Full Options Chain import os import requests API_KEY = os . environ [ " MARKET_OPTIONS_KEY " ] BASE_URL = " https://market-option.com/api/v1 " def get_chain ( ticker : str ) -> list [ dict ]: res = requests . get ( f " { BASE_URL } /options/chain/ { ticker } " , params = { " apiKey " : API_KEY }, ) res . raise_for_status () return res . json ()[ " results " ] contracts = get_chain ( " SPY " ) print ( f " { len ( contracts ) } contracts returned " ) print ( contracts [ 0 ]) Each contract in results looks like this: { "details" : { "contract_type" : "call" , "strike_price" : 530 , "expiration_date" : "2026-01-17" , "ticker" : "O:SPY260117C00530000" }, "last_quote" : { "bid" : 3.45 , "ask" : 3.50 , "midpoint" : 3.475 }, "greeks" : { "delta" : 0.42 , "gamma" : 0.031 , "theta" : -0.18 , "vega" : 0.29 }, "implied_volatility" : 0.182 , "open_interest" : 12418 } Filtering by Expiration and Strike def get_near_the_money ( ticker : str , expiration : str , spot : float , width : float = 0.05 ): """ Return contracts within ±width% of spot price. """ contracts = get_chain ( ticker ) low = spot * ( 1 - width ) high = spot * ( 1 + width ) return [ c for c in contracts if c [ " details " ][ " expiration_date " ] == expiration and low <= c [ " details " ][ " strike_price " ] <= high ] atm = get_near_the_money ( " SPY " , " 2026-01-17 " , spot = 530 ) for c in atm : print ( c [ " details " ][ " strike_price " ], c [ " details " ][ " contract_type " ], c [ " last_quote " ][ " bid " ], c [ " greeks " ][ " delta " ], ) Scanning for High IV Contracts def high_iv_scan ( ticker : str , iv_threshold :

2026-06-24 原文 →
AI 资讯

Git com múltiplas contas: configure trabalho e pessoal no mesmo computador

Você já fez um commit no repositório do trabalho e percebeu que estava com o seu e-mail pessoal? Ou o contrário? Esse é um dos erros mais comuns de quem usa Git com múltiplas contas no mesmo computador. Neste tutorial você vai aprender a configurar tudo corretamente, de uma vez, usando chaves SSH separadas e .gitconfig condicional — sem gambiarras. O problema Por padrão o Git usa uma configuração global: git config --global user.name "Seu Nome" git config --global user.email "seu@email.com" Isso significa que todos os repositórios no seu computador usam o mesmo usuário. Quando você tem contas separadas (ex: joao@empresa.com no GitLab da empresa e joao@gmail.com no GitLab pessoal), os commits vão sair com o e-mail errado. A solução profissional envolve duas partes: Chaves SSH separadas para cada conta .gitconfig condicional que aplica o usuário certo — e a chave SSH certa — por pasta Passo 1 — Gerar as chaves SSH Abra o terminal e gere uma chave para cada conta. Use nomes diferentes para não sobrescrever: # Chave para a conta pessoal ssh-keygen -t ed25519 -C "joao@gmail.com" -f ~/.ssh/id_ed25519_pessoal # Chave para a conta do trabalho ssh-keygen -t ed25519 -C "joao@empresa.com" -f ~/.ssh/id_ed25519_trabalho 💡 Por que ed25519 ? É o algoritmo mais moderno, mais seguro e recomendado pelo GitHub, GitLab e Bitbucket. Evite RSA a menos que seu servidor seja muito antigo. Ao final você terá quatro arquivos em ~/.ssh/ : id_ed25519_pessoal ← chave privada (nunca compartilhe) id_ed25519_pessoal.pub ← chave pública (você registra no GitLab) id_ed25519_trabalho id_ed25519_trabalho.pub Passo 2 — Registrar as chaves no GitLab Para cada conta: Copie o conteúdo da chave pública: # Pessoal cat ~/.ssh/id_ed25519_pessoal.pub # Trabalho cat ~/.ssh/id_ed25519_trabalho.pub Acesse Settings → SSH and GPG keys → New SSH key na conta correspondente e cole o conteúdo. Faça isso nas duas contas , cada uma com a sua respectiva chave pública. Passo 3 — Configurar o Git por pasta (o pulo do gato)

2026-06-24 原文 →
AI 资讯

The emergence of the web data infrastructure layer for AI

AI is booming. New use cases are emerging each day. To capitalize on the technology’s potential, enterprises require data at scale. In many cases, though, the relevant information is blocked or unstructured, which limits its use by AI models. To understand this challenge, consider the foundation of the web itself. The web was not designed…

2026-06-24 原文 →