<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Randall Naar on Medium]]></title>
        <description><![CDATA[Stories by Randall Naar on Medium]]></description>
        <link>https://medium.com/@randynaar?source=rss-507825a98fec------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BJdm8qsWu0ycHuArP-zVMA.jpeg</url>
            <title>Stories by Randall Naar on Medium</title>
            <link>https://medium.com/@randynaar?source=rss-507825a98fec------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 11:00:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@randynaar/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[[DRAFT] Scuffed Intro to BitVM]]></title>
            <link>https://randynaar.medium.com/draft-scuffed-intro-to-bitvm-8e8aa0f75fad?source=rss-507825a98fec------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e8aa0f75fad</guid>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[layer-2]]></category>
            <category><![CDATA[bitvm]]></category>
            <dc:creator><![CDATA[Randall Naar]]></dc:creator>
            <pubDate>Thu, 22 Jan 2026 05:21:39 GMT</pubDate>
            <atom:updated>2026-01-22T05:21:39.961Z</atom:updated>
            <content:encoded><![CDATA[<p>Medium says I last updated this October 27th, 2023. It was a blog post I planned to finish but never did. I’m going to publish this as a draft with hopes that having this publicly incomplete will motivate me to finish.</p><p>— — — —</p><p>//Note that I’ll use Paul and Vicky for Prover and verifier</p><p>//Add a high-level intro</p><p>Bitvm is a new scheme in bitcoin that allows a wide range of arbitrary programs to be verified on-chain. The aim is to execute the programs off-chain and settle on-chain in case of a dispute, similar to the lightning model.</p><p>The BitVM paper focuses on the construction of programs using NAND gates, as will I, but active research in this space has yielded more expressive primitives. This guide won’t explore any of that.</p><p>To demonstrate the concept, I’m going to make an example bitvm program that uses 1 NAND gate. The goal is for the 1 NAND gate program to evaluate to true. In this example we’ll be given the role of “prover” and labeled “Paul” (yay for alliteration), which means we’ll construct the program and be responsible for providing inputs to it. The counterparty running our program will be the “verifier” labeled “Vicky”. Before entering the contract, both parties must enter a setup phase.</p><p>We’ll go more into detail later, but at a high level the setup phase involves making the program as the prover, sharing the program with the verifier, allowing the verifier to construct 2 taptrees, and making a series of presigned transactions that will help with fraud proofs later on. After all this is done, we broadcast the first transaction (the funding transaction) in our series of presigned transactions.</p><p>{image with the states of nand gates}</p><p>So how do we represent a NAND gate locking script that allows the nand inputs to be specified during spend time? Here’s some pseudocode written in an imperative style showing what’s happening (the locking script is the function and the witness will be the inputs on invocation):</p><p>function nandGate(a, b, c) {</p><p>let x;</p><p>if(sha256(a) == HASH_A_ZERO) {</p><p>x = 1;</p><p>}</p><p>else if (sha256(a) == HASH_A_ONE) {</p><p>x = 0;</p><p>}</p><p>else {</p><p>return new Error();</p><p>}</p><p>let y;</p><p>if(sha256(b) == HASH_B_ZERO) {</p><p>y = 1;</p><p>}</p><p>else if (sha256(b) == HASH_B_ONE) {</p><p>y = 0;</p><p>}</p><p>else {</p><p>return new Error();</p><p>}</p><p>let z;</p><p>if(sha256(c) == HASH_Z_ZERO) {</p><p>z = 1;</p><p>}</p><p>else if (sha256(c) == HASH_Z_ONE) {</p><p>z = 0;</p><p>}</p><p>else {</p><p>return new Error();</p><p>}</p><p>if(nand(x, y) != z) {</p><p>throw new Error();</p><p>};</p><p>}</p><p>Let’s say we locked a utxo using a script functionally similar to the above. To satisfy this gate, x, y, and z must be values that cause the value to return true. As the prover, I would give the verifier this program comprised of ’n=1’ logic gates and ask them to create 2*n challenge-response transactions. In our case this will be 2 transactions (a challenge and a response), and neither will be signed yet. We also need a final transaction for if/when the prover Paul verifies the last gate. The funding transaction is separate and must be signed last.</p><p>Message passing flow:</p><p>Paul -&gt; Vicky: The program</p><p>Vicky -&gt; Paul: a series of challenge-response transactions that he’ll have to sign the multisig inputs of (using sighash all to cover the other input).</p><p>/*</p><p>-Makes more sense to use input since I can say Vicky published teh challenge tx</p><p>*/</p><p>/*</p><p>Show image for visualization:</p><p><a href="https://github.com/BitVM/bitcoin-scripts/blob/main/presigned-tx-sequence.png">https://github.com/BitVM/bitcoin-scripts/blob/main/presigned-tx-sequence.png</a></p><p>*/</p><p><strong>================</strong></p><p>THE FUNDING / RESPONSE TX</p><p><strong>================</strong></p><p>The verifier then makes a multisig transaction that will serve as our first tx. It will reference one utxo given by the verifier, and one utxo given by the prover when the program was transferred, as the inputs. The outputs are designed to always be spent <em>*together*</em>.</p><p>It has the same output structure as the response transaction which is why I grouped them together. The response tx differs in that the input UTXOs have to be the outputs of the challenge tx.</p><p>The output of this transaction has 2 outputs:</p><p>-a 0-valued output that is locked with a taptree of hashlocks numbering the number of gates in the program guarded by a check verifying the Verifier’s signature</p><p>-imperative example of a hashlock:</p><p>-(x, s) =&gt; hash(x) == PREDEFINED_HASH_VALUE &amp;&amp; checksig(s)</p><p>-an output containing the funds, locked with a taptree.</p><p>-The taptree contains leaves for a:</p><p>-2 of 2</p><p>-equivocation slashing for the verifier to take the prover’s money (what supertestnet calls anti-contradiction)</p><p>-a timelock for the prover to take the money</p><p><strong>================</strong></p><p>THE CHALLENGE TX</p><p><strong>================</strong></p><p>The verifier is also responsible for making a response tx for the prover to use. The response transaction will take <em>*both*</em> outputs of the challenge tx as inputs. This transaction is intended for the Verifier to spend <em>*to*</em>, and the Prover to spend <em>*from*</em>.</p><p>The output of this transaction also has 2 outputs:</p><p>-a 0-valued output that is locked with a taptree, using the same hashlocks the output of the <em>*challenge*</em> transaction had, except with each leaf containing one gate’s logic converted to script. Note the trees for the challenge and response txs are <em>*different*</em>.*</p><p>-imperative example of leaf script:</p><p>-(x, a, b, c, m, s, k) =&gt; hash(x) == PREDEFINED_HASH_VALUE &amp;&amp; nand(a,b,c) &amp;&amp; checksig(m, s, k)</p><p>-an output containing the funds, locked with a taptree.</p><p>-The taptree contains leaves for a:</p><p>-2 of 2</p><p>-equivocation slashing for the verifier to take the prover’s money (what supertestnet calls anti-contradiction)</p><p>-a timelock for the <em>*verifier*</em> to take the money (assuming the prover can’t successfully solve the gate without contradicting themselves or failing the script)</p><p><strong>================</strong></p><p>Author’s Note</p><p><strong>================</strong></p><p>If the hashes in the hashlock don’t also include a checksig, on a second round of a challenge-response, the prover can force the first output to be spent without the money from the second output (since they already know one of the hashes). To prevent this, a signature check should be added. This isn’t explicitly said in the paper but it’s somewhat mentioned in the telegram. (telegram screenshot ref: A hashlock’s technical definition…)</p><p>-Mention how the multisig is sighash all and why that’s important</p><p>-Mention that we need one more transaction in case we end on the last leaf</p><p>-Mention that the prover can prove the same gate over and over whenver the verifier challenges. To prevent this, a verifier signature should be used instead</p><p>— — DONE AUTHORS NOTE — —</p><p>These are how the transactions will look for our case:</p><p>{Add some more images maybe? Link to Robin’s GH image may be enough}</p><p>—</p><p>Now that Vicky has made the txs for us, she signs all the inputs she can for each transaction except the first one.</p><p>She gives them to Paul, us, and we sign all the multisig inputs, <em>*including*</em> the first one. We then send it back to Vicky. When Vicky receives this she can sign the first input and broadcast the first challenge on-chain.</p><p><strong>— — -</strong></p><p>Now as the prover, there are 2 things I can do after the first transaction is published. I can give the inputs for the successful execution of the program encoded in this scheme (as hash preimages), I can lie and give faulty inputs, or I can choose to give no inputs at all.</p><p>/*</p><p>Show images of series of txs for each case</p><p>*/</p><p><strong>====</strong></p><p>Successful inputs</p><p><strong>===</strong></p><p>if we give Vicky the successful inputs, she can still spend the first output in the funding utxo even if she knows we’re right. There’s nothing we can do to stop her from challenging our gate. Because we have the correct inputs it’s annoying but not the end of the world. Maybe redeemable collateral requirements for Vicky can minimize this impact.</p><p><strong>====</strong></p><p>Unsuccessful inputs</p><p><strong>===</strong></p><p>If we give Vicky bad inputs, she’ll spend the funding tx into the challenge transaction. In this case it’s trivial to find the correct inputs since our challenge is a simple nand gate, but there are consequences for giving bad inputs. If she challenges us on-chain, and we provide the good inputs on-chain after giving her the bad inputs off-chain, she can use our bad inputs to take our money using the anti-contradictory script (link to super’s repo and just point to the script there).</p><p><strong>====</strong></p><p>No inputs</p><p><strong>===</strong></p><p>In this case we don’t give Vicky inputs because we refuse to or can’t. In this scenario Vicky can spend from the funding/response transaction to initiate the challenge. This forces Paul to reveal his inputs and if he knows it then he can spend into the final response tx. Otherwise he’d just be waiting it out until Vicky can take the funds.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e8aa0f75fad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI and subtractive programming]]></title>
            <link>https://randynaar.medium.com/ai-and-subtractive-programming-5c0173a9dfec?source=rss-507825a98fec------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c0173a9dfec</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Randall Naar]]></dc:creator>
            <pubDate>Sun, 06 Apr 2025 19:52:50 GMT</pubDate>
            <atom:updated>2026-06-07T18:56:41.743Z</atom:updated>
            <content:encoded><![CDATA[<p>The hot new term around the block is “vibe coding” and it’s now being touted as the future of programming. The term was coined by a famous AI researcher named Andrej Karpathy in a tweet about how AI allows one to code by giving feedback on the look and feel of an application made by AI. Feedback based on vibes. Ironically, some of the same people who love AI art denounce this new category of programming. Personally, I’m a proponent of this new movement.</p><p>I think the problems of AI art and AI programming are as categorically different as AI programming and human programming. I don’t mean this in an elitist sense or that AI will *never* replace me, but more in the sense that the thought patterns of a programmer are fundamentally different when using AI vs traditional programming.</p><p>Traditional programming is what I call ‘additive’. You start with a set of well-defined tools and use them to build a program from nothing. A good programming environment has no need for assumptions and any undefined behavior of your programming language is considered to be a bug. If you ask a designer of a programming language “what happens when I do this?” and they say “I don’t know”, that’s a sign of a language that will never get adopted.</p><p>With AI, in contrast, it’s okay to start with an “I don’t know” for many things and let AI fill in the blanks. Many times people will even notice that the AI has filled-in <strong>too many</strong> blanks and will have to drill down on aspects to remove or replace. This is why I frequently refer to AI as “subtractive” programming. It doesn’t rest on a foundation of hard-logic. Instead, it tries to tap into the knowledge-base of common human assumptions and the vibe coder’s primary job, in this case, is to reign in what’s generated and point the AI in the right direction to generate more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c0173a9dfec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A response to ‘Bitcoin Promoters Pay Ex-CIA Official For Propaganda’]]></title>
            <link>https://randynaar.medium.com/a-response-to-bitcoin-promoters-pay-ex-cia-official-for-propaganda-7285c3d4a341?source=rss-507825a98fec------2</link>
            <guid isPermaLink="false">https://medium.com/p/7285c3d4a341</guid>
            <category><![CDATA[forbes]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[debunk]]></category>
            <dc:creator><![CDATA[Randall Naar]]></dc:creator>
            <pubDate>Mon, 16 Dec 2024 18:11:28 GMT</pubDate>
            <atom:updated>2024-12-16T18:13:54.927Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UtiUHaOZVuzv-pkJGatvxw.png" /></figure><p>A quick response to a Forbes opinion piece from 2021</p><h3>Introduction</h3><p>Recently I’ve started making videos on TikTok with the goal of teaching people about Bitcoin, economics, cryptography, and privacy, and I’ve gotten the usual off-the-shelf critiques people have of Bitcoin. One video I made covered studies focusing on illicit activity on Bitcoin and crypto at large. In it, I referenced a report titled ‘An Analysis of Bitcoin’s Use in Illicit Finance,’ co-authored by a former CIA director.</p><p>Since this sounds like an interesting report, a critic googled it and found ‘Bitcoin Promoters Pay Ex-CIA Official For Propaganda’ by <a href="https://www.forbes.com/sites/davidblack/">David B. Black</a>. I thought to address it in my video, but I try to keep them under 40 seconds and didn’t want to waste time on it.</p><p>Unfortunately, the commenter who brought this article up argued that the Forbes opinion piece was more credible than the report. This spurred me to look for refutations detailing the bias and assumptions found in the article, but I couldn’t find any ready to send the commenter. I’m now writing this article to fill in that gap.</p><p>My arguments against the credibility of the article as a source of information concern its <strong>ad-hominem attacks and bias allegations </strong>and its <strong>misinterpretations of Bitcoin technology.</strong></p><p>I have a lot to say about the article, but I’ll try to keep some of the minor critique out for the sake of brevity.</p><p>The Forbes article can be found here:</p><p><a href="https://www.forbes.com/sites/davidblack/2021/04/22/bitcoin-promoters-pay-ex-cia-official-for-propaganda/">https://www.forbes.com/sites/davidblack/2021/04/22/bitcoin-promoters-pay-ex-cia-official-for-propaganda/</a></p><p>And the report can be found here:</p><p><a href="https://cryptoforinnovation.org/resources/Analysis_of_Bitcoin_in_Illicit_Finance.pdf">https://cryptoforinnovation.org/resources/Analysis_of_Bitcoin_in_Illicit_Finance.pdf</a></p><h3>Ad-Hominem Attacks and Bias Allegations</h3><p>The first problem I found with the Forbes article ‘Bitcoin Promoters Pay Ex-CIA Official For Propaganda’ is the author’s use of <strong>ad-hominem attacks and bias allegations</strong>. Near the beginning of David B. Black’s article, in the section ‘The report is self-serving’, he writes:</p><blockquote>“the people who wrote the report were bought and paid to do the job they did.”</blockquote><p>Here he claims the authors of the report are compromised because they were paid to conduct their research. This argument assumes that sponsorship inherently compromises integrity, which is not necessarily true.</p><p>The report’s authors are professionals with a reputation to uphold, including Michael Morell, an ex-CIA director, and his coauthors, Josh Kirshner and Thomas Schoenberger of Beacon Global Strategies. Their expertise and the company’s strategic advisory role are no less credible than that of auditors or researchers in any sponsored study. To dismiss their conclusions outright is to engage in an ad-hominem fallacy, attacking the source rather than the argument itself. Since their findings didn’t align with his worldview, he dismissed them as having been bought out by their sponsors.</p><p>Furthermore, Black begins to imply additional breaches in journalistic integrity by writing:</p><blockquote>The report references experts from a wide variety of name-brand institutions who are said to support the report’s conclusions. This is an important subject. Don’t you think the report’s authors could get more than one such expert to go on the record?</blockquote><p>I believe the companies and institutions he mentioned are the ones he has in his introduction:</p><blockquote>Major corporations, from Tesla to Square to MicroStrategy, are adding it to their balance sheets.</blockquote><p>All of these statements are derived from linked citations and can be <a href="https://www.reuters.com/article/us-tesla-crypto-currency/a-tesla-for-a-bitcoin-musk-drives-up-cryptocurrency-price-with-1-5-billion-purchase-idUSKBN2A81CG/">independently verified by anyone</a>. Whether or not the authors were sponsored, their findings rely on transparent data sources and verifiable evidence, making the sponsorship irrelevant to the conclusions drawn.</p><p>He even goes so far as to criticize the authors’ technical expertise without addressing the substance of their findings, which undermines the credibility of his argument:</p><blockquote>None of the report authors have any technical expertise. The ex-CIA man spent his early years on energy and East Asia, and then became a manager and communicator — which is what you would expect of someone who now spends lots of time working for media outlets like CBS</blockquote><h3>Misinterpretations of Bitcoin Technology</h3><p>My other big complaint is with how David B. Black offers his own misinterpretation of Bitcoin in his attempt to discredit the author, writing:</p><blockquote>“The blockchain ledger on which Bitcoin transactions are recorded…”</blockquote><blockquote>The way this is worded shows a lack of the most basic knowledge of how Bitcoin works, implying that Bitcoin is somehow not part and parcel of what some call the “blockchain ledger,” a phrase made up to describe one of the inextricable parts of the Bitcoin code base. In the normal world, transactions like buying a hose at a hardware store take place; some of those real-world transactions may later be recorded in a ledger; in Bitcoin, there is no difference between the transaction, the Bitcoin and the ledger.</blockquote><p>Bitcoin transactions can exist outside the blockchain — for instance, through second-layer technologies like the Lightning Network. This means that not all Bitcoin transactions are immediately or permanently recorded on the blockchain.</p><p>He also mentions how private Bitcoin is, mentioning “it’s as anonymous as cash”:</p><blockquote>It’s even better than wearing a mask when robbing a bank! It’s as anonymous as cash except that it enables the transacting parties to be an ocean away from each other.</blockquote><p>Oh how I wish this were true. I believe privacy is necessary for a free and open society to thrive but that’s besides the point. Bitcoin, in its current form, provides only limited tools for enhancing privacy between transaction participants. Privacy-enhancing technologies like CoinJoin and the Taproot upgrade are steps in the right direction, but it’s insufficient to being a better alternative than cash.</p><p>In reality, Bitcoin’s transparency has made it easier for law enforcement to track illicit activity, as seen in high-profile cases like the Bitfinex hack, <a href="https://decrypt.co/151168/bitfinex-hacker-revealed-razzlekhan-husband-billions-bitcoin">where stolen funds were traced through blockchain analysis</a>.</p><h3>Conclusion</h3><p>I can assure you my original notes on David B. Black’s Forbes article were much longer than this response, but I did promise brevity in my introduction.Hopefully, this writeup has raised some doubts about the credibility of the referenced article and I recommend reading both sources if you’re Bitcoin-curious. You can also read more about why Michael Morell decided to write this report <a href="https://www.thecipherbrief.com/column_article/my-experience-with-bitcoin-and-challenging-conventional-wisdom">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7285c3d4a341" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Yon entwodiksyon nan aprantisaj machin]]></title>
            <link>https://randynaar.medium.com/yon-entwodiksyon-nan-aprantisaj-machin-47455c4fa038?source=rss-507825a98fec------2</link>
            <guid isPermaLink="false">https://medium.com/p/47455c4fa038</guid>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[haitian-creole]]></category>
            <dc:creator><![CDATA[Randall Naar]]></dc:creator>
            <pubDate>Sun, 30 Jun 2024 04:33:19 GMT</pubDate>
            <atom:updated>2024-06-30T04:33:19.826Z</atom:updated>
            <content:encoded><![CDATA[<p><em>*This is an article I wrote back in 2016 translated into Hatian Creole (using ChatGPT) by request. In hindsight the english version is poorly written, so I hope the requester doesn’t blame ambiguities or mistakes on the translation 😂*</em></p><p>Resaman, m ap chèche bibliyotèk pou mwen ka itilize pou tout travay aprantisaj machin mwen yo. Kondisyon yo: rapid, efikas, egzak, epi dènye men pa pi piti, fasil pou itilize. Youn nan pi bon karakteristik yon bibliyotèk aprantisaj machin dwe genyen se fasilite pou itilize. Sa pral sove ou anpil tèt fè mal ak tan nan long tèm epi pifò nan menm bibliyotèk sa yo pral gen posiblite pou pèmèt yon nivo personnalizasyon tou.</p><p>Bibliyotèk mwen pral ekri sou jodi a se bibliyotèk Python scikit-learn. Mwen te ap jwe ak youn nan algoritm aprantisaj machin ki pi senp — Regression Lineyè Pi Piti Kare — epi mwen deside bay yon rezime rapid sou sa li fè, kijan li travay, ak kijan mwen itilize li pou analize pri fèmen aksyon Apple pandan yon ane.</p><p>Premyèman, mwen pral kòmanse ak ‘sa li fè’. Pwen prensipal la nan regression lineyè se pou predi yon ekwasyon lineyè nan fòm ‘y = ax + b’. Pwoblèm nan se ke nou sèlman gen yon pakèt ‘x’ ak ‘y’ epi nou pa konnen ekwasyon an depi nan konmansman an. Pou rezoud pwoblèm sa a, nou bay algoritm lan kèk echantiyon ‘x’ ak ‘y’ ki koresponn epi fè l ‘aprann’ ki fonksyon an ye. Koulye a, algoritm lan ka predi ekwasyon lineyè a ke ‘x’ ak ‘y’ yo bay ak predi nouvo ‘y’ pou nenpòt ‘x’. Pou egzanp, si mwen ta bay algoritm lan sa yo pè antre-sòti nan fòm (antre, sòti): (1,2),(2,3),(3,4), kisa li ta ka ban mwen pou nouvo antre ‘4’? Byen, premye nou dwe detèmine ekwasyon lineyè a itilize pou jenere pè sa yo ki mwen panse nou tout ka dakò ke pi byen modle pa y = x + 1. Konsa, ak yon ekwasyon ki adapte parfe ak done nou yo, nou ta dwe kapab atann algoritm nou an asime ekwasyon sa a, epi bay rezilta egzat. Kisa ki rive lè done yo pa adapte konsa fasil nan yon sèl ekwasyon lineyè? Algoritm lan dwe fè pi byen li kapab, epi eseye chwazi yon ekwasyon ki omwen eseye jwenn sòti a pi pre sa li ta dwe ye.</p><p>Algoritm lan travay lè li fè yon ekwasyon ak yon a ak b owaza epi konpare kijan li ka konvèti pwen x sa yo nan pwen y ki antre yo ak ekwasyon an. Lè nou di ‘kijan byen’, ou ta ka sipoze ke nou gen yon kalite metrik pou itilize pou kalkile erè, pou sa mwen ta di se kòrèk. ‘Fonksyon erè’ a itilize pou sa se som tout sòti espere nou yo (y’) soustrè pa sòti reyèl nou yo (y), kare: (y’ — y)². Konsa, nou ka akimile erè nou kòm tout pozitif, epi jwenn yon estimasyon egzat sou ki jan tout f(x) estime nou yo erè kolektivman. Yon lòt bagay pou remake se ke li fasil différenciable, menm anba sigma a. Koulye a, si nou konnen y’ se vrèman ‘ax’, epi nou vle wè kijan fonksyon erè nou an ap chanje an rapò ak pwòp a nou, nou ka différencier an rapò ak ‘a’ epi trete ‘x’ ak ‘y’ antre itilizatè yo kòm konstan. Koulye a, si derive a pozitif, nou vle fè ‘a’ nou pi ba (lè l sèvi avèk derive a miltipliye pa yon konstan echiye, epi soustrè valè sa a soti nan ‘a’) analojik ak fè valè fonksyon erè a pi ba ak diminye erè total nou an. Sa fèt atravè yon seri iterasyon epi se yon teknik yo rele ‘desant gradyan’. Sa a se menm différenciation an rapò ak entèsepsyon ‘b’, ak derive a esansyèlman menm jan li te lè y ap différenciation pa ‘a’, san yo pa règle chèn ki miltipliye derive a pa x. Finalman, nou pral rive nan yon minimòm kote derive a ta dwe 0 epi nou sispann, sa a se ‘a’ nou pral kenbe.</p><p>Fason mwen itilize li se analize aksyon Apple, ak done ki gen pri fèmen sot pase yo nan aksyon yo pandan yon ane soti jodi a. Done yo te pran nan Google, ki menm gen yon opsyon pou telechaje li nan fòma csv. Chak youn nan dat yo mwen konvèti nan yon nimewo ki reprezante jou nan ane biznis la li te ye (aksyon yo pa vann pandan jou ferye oswa wikenn), epi mwen itilize nimewo sa yo kòm ‘x’ pou fonksyon enkoni an. Algoritm regression lineyè a Lè sa a, predi yon ekwasyon lineyè ki pi byen adapte ak pwen yo ak pi ba kantite erè a epi kounye a li pral kite m predi pwen nan lavni lè l sèvi avèk ekwasyon devine a. Sa a se imaj liy lan ki te pwodwi soti nan fonksyon ekwasyon regression lineyè a.</p><p>Telechaje distribisyon Anaconda pou Python paske li pral pi fasil fason pou ou enstale bibliyotèk sci-kit aprann lan. Kòmand la se : conda install scikit-learn, jan sa parèt nan seksyon enstalasyon nan sit entènèt ofisyèl yo ‘<a href="http://scikit-learn.org/">http://scikit-learn.org/</a>&#39;.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47455c4fa038" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Callback Hell]]></title>
            <link>https://randynaar.medium.com/callback-hell-4a64d1ae8e10?source=rss-507825a98fec------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a64d1ae8e10</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Randall Naar]]></dc:creator>
            <pubDate>Wed, 03 Aug 2022 23:00:11 GMT</pubDate>
            <atom:updated>2022-08-03T23:00:11.276Z</atom:updated>
            <content:encoded><![CDATA[<p>A post I made as a reply so it didn’t get visibility: <a href="https://randynaar.medium.com/callback-hell-9b002169bda6">https://randynaar.medium.com/callback-hell-9b002169bda6</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a64d1ae8e10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Introduction to Bitcoin (part 2) — Wallets]]></title>
            <link>https://randynaar.medium.com/an-introduction-to-bitcoin-part-2-wallets-aaed0e9b3aa6?source=rss-507825a98fec------2</link>
            <guid isPermaLink="false">https://medium.com/p/aaed0e9b3aa6</guid>
            <dc:creator><![CDATA[Randall Naar]]></dc:creator>
            <pubDate>Wed, 03 Nov 2021 12:02:24 GMT</pubDate>
            <atom:updated>2023-01-23T01:17:39.847Z</atom:updated>
            <content:encoded><![CDATA[<h3>An Introduction to Bitcoin (part 2) — Wallets</h3><p>Let’s start off the ‘How’ of Bitcoin by defining one of the most fundamental concepts of any cryptocurrency, the “wallet”.</p><h3>How is Bitcoin transferred and received?</h3><p>A Bitcoin wallet is a program that allows you to send and receive Bitcoin. It’s similar to a mobile banking app that can be used to perform operations on an account except instead of the application performing operations on your banking account, it performs them on your Bitcoin account. A Bitcoin account is what I use to refer to a grouping of bitcoin in an individual’s possession on the blockchain. Every Bitcoin account is uniquely identified on the blockchain using something called an “address” which is a random looking sequence of characters that people can send money to using the Bitcoin wallet program. This address is generated by performing some mathematical operations on some other random-looking strings of characters called a “private key”.</p><p>In the Bitcoin wallet program, the “private key” usually comes first, while another piece of information called the “public key” is made from information in the “private key”. After the public key is made, the “address” is made using the public key.</p><p>The process looks something like this: private key -&gt; public key -&gt; address</p><p>The private key is *<strong>key</strong>* to this operation (😉) and its usage is similar to that of a pin number used to access a bank account. It should be kept secret and is the only thing needed to spend money on your Bitcoin account. The private key is used to perform mathematical operations on your data to make something called a *digital signature*. The only way to verify the digital signature was derived from a specific piece of data is something called a public key. The public key is created from the private key and is *not* secret.</p><p>When using the Bitcoin protocol, data is signed to assert ownership and tell other people that a piece of data (the signature) was derived by the owner of the signing/private key. To do that, the owner of the private key widely distributes their public key so that people can verify that it was them who signed a piece of data. The data can only be verified with the public key of the associated private key, so if any other public key is used then we’d know right away when verifying.</p><p>If I have bitcoin and want to send some to someone else, the person I’d like to send Bitcoin to must give me their address or public key. Using the recipient’s address in my Bitcoin wallet program, I can specify how much bitcoin I’d like to transfer. Once I confirm the transaction, the wallet program uses my private key to “sign” the information of my coins in the transaction so that when the transaction is broadcast to computers running Bitcoin nodes, they can be sure the transaction was made by the owner of the address those coins were last sent to.</p><p>After a transaction is broadcast to bitcoin nodes, it isn’t immediately placed in the blockchain. It’s first validated by the Bitcoin node that checks whether the coins used in the transaction actually belong to the owner of the private key. The transactions then go into something called a “mempool” which is where transactions go before being “processed” by miners. The mining process will be discussed in the 3rd part of my Introduction to Bitcoin series, so keep an eye out!</p><p>Edit: I made references to ‘encryption’ in a previous draft when that’s not what’s actually happening. Signing and encryption algorithms can be mutually exclusive and a basic transaction made by your wallet just signs the data without encrypting anything.</p><p>See <a href="https://crypto.stackexchange.com/questions/81272/how-to-encrypt-with-elliptic-curve-cryptography-ecc">https://crypto.stackexchange.com/questions/81272/how-to-encrypt-with-elliptic-curve-cryptography-ecc</a> and <a href="https://crypto.stackexchange.com/questions/52016/what-is-the-difference-between-encrypting-and-signing-in-ecc-asymmetric-algorith">https://crypto.stackexchange.com/questions/52016/what-is-the-difference-between-encrypting-and-signing-in-ecc-asymmetric-algorith</a> for more information about the different uses of Elliptic curve algorithms (ECDSA is the signing algorithm originally used in Bitcoin and it is mentioned in both)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aaed0e9b3aa6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Introduction to Bitcoin (part 1)]]></title>
            <link>https://randynaar.medium.com/an-introduction-to-bitcoin-part-1-ba23cc52be04?source=rss-507825a98fec------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba23cc52be04</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[introduction]]></category>
            <category><![CDATA[bitcoin]]></category>
            <dc:creator><![CDATA[Randall Naar]]></dc:creator>
            <pubDate>Tue, 05 Oct 2021 01:37:51 GMT</pubDate>
            <atom:updated>2022-08-20T15:23:03.542Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s weird how “Bitcoin” and “blockchain” have somehow become known in the public eye with so few people actually knowing what it is and how it works. I guess this isn’t anything new as words like “artificial intelligence” and “big data” have also become buzzwords known by the general public, but with Bitcoin it’s different. Bitcoin has financial implications for those who choose to be an “early” participant in the technology and so much faith is put on a system that’s so widely misunderstood.</p><p>I’m no expert myself but compared to the population at large I’d say I know a lot. So much so that I decided to write this post describing what Bitcoin is, first generally, then going into more specifics. It’s not meant for the particularly technical individual so don’t worry if you don’t know how to code or anything like that.</p><p>I’ll start by answering the questions that Wikipedia says are “considered basic in information gathering or problem solving” — the “Five Ws”. For those who don’t know what the Five Ws are (and for those that can’t remember), the Five Ws are “Who”, “What”, “When”, “Where”, “Why”, and the silent unofficial member of the group “How”.</p><h3>Who</h3><p>For this section I’ll give a brief blurb about the mysterious creator of Bitcoin and why there’s so much interest around them. As for who made Bitcoin, we don’t know. Well we do know “an” identity of the creator of Bitcoin, it’s just not the identity that the creator touts around in real life. We know a pseudonym of the person who created Bitcoin — that pseudonym being the name “Satoshi Nakamoto”. Is it crazy that the person who created a digital monetary system supporting over 900 billion US dollars in value is unknown? A little, but you get used to it over time.</p><p>Is there any risk to there being an anonymous creator of Bitcoin? Kind of. Satoshi is believed to be the largest owner of Bitcoin which means that if he/she ever decided to become active with their funds, they could distribute Bitcoin in a way that could depreciate the price of Bitcoin and incur an inflationary effect. Based on what we know of Satoshi from their online presence, this seems unlikely as that would be counterproductive to the whole project.</p><h3>What</h3><p>Bitcoin is the word we use to describe both the computer protocol and the currency itself. As a currency Bitcoin is like the US dollar or the Mexican peso except instead of being represented as dollars it’s represented as data on computers (think files on a computer or information in a database). This Bitcoin database is maintained by volunteers who decide to run the program (aka the ‘Bitcoin Node’ application) on their own computers.</p><h3>When</h3><p>Bitcoin was created over 10 years ago and distributed online for mass consumption as early as January 3rd 2009. For those who believe this is a new thing, it’s not, it’s just now getting popularized to an unprecedented extent.</p><h3>Where</h3><p>This question is a hard one to interpret so I’ll use this section to explain where the data is stored. The data for Bitcoin is stored on computers all around the world and a copy of it can even be downloaded by you. This makes it what we call “decentralized” because there’s no one person or organization that controls the data. Anyone can see anyone else’s data pseudonymized by something called an “address” which is one of the things that makes Bitcoin special.</p><h3>Why</h3><p>Bitcoin was created to create a more equitable monetary system. A monetary system where the rules are well-defined and unconditionally enforced. To make this happen a system was devised to make all transactions viewable by anyone from anywhere.</p><p>Making the Bitcoin system equitable means to make it accessible to everyone. It also means the power to change the rules at any time should not be governed by one individual or organization. Governance should instead be lead by the community of bitcoin users around the world. The information era of computers and the internet makes all of this possible by allowing anyone with an internet connection to participate in this new monetary system. With the growing diversity of Bitcoin’s user base, and without a particular nation’s government dictating the ordinance of the Bitcoin program’s development, it has truly become the currency of the community who believe in it.</p><h3>How</h3><p>This section is going to be the largest because the ‘How’ in ‘How Bitcoin works’ is what makes the technology so radically different from any financial system existing before it. I’d like to address each ‘How’ in their own section, but for the sake of brevity I’ll probably answer the ‘How’ questions in a follow-up blog post. Keep an eye out for part 2!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba23cc52be04" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Webpack Deep Dive Part 6: Running Loaders]]></title>
            <link>https://randynaar.medium.com/webpack-deep-dive-part-6-running-loaders-d6be19a3a035?source=rss-507825a98fec------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6be19a3a035</guid>
            <dc:creator><![CDATA[Randall Naar]]></dc:creator>
            <pubDate>Wed, 07 Jul 2021 03:03:00 GMT</pubDate>
            <atom:updated>2021-07-09T11:26:29.167Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6UjvZ7YvwYy_4iAa9UNWeg.png" /></figure><h3>Introduction</h3><p>It’s been around 4 months since my last webpack blog post. The reason it’s taken so long is because I’ve been spending most of my free time reading through an open source project I’d like to start a new series on. It’s a project you’ve almost undoubtedly heard of — Bitcoin.</p><p>More specifically, I want to make a blog series on the *original* Bitcoin source code (to better manage the scope of what I’d like to cover). Of course I still plan to finish this webpack blog, but Bitcoin has captivated most of my interest at the moment.</p><p>Coming back to this post, I’ve been messing around with the format for method descriptions. Most notably, now I have 3 sections for every method, the summary, the high level implementation details, and the annotated code snippet. This was done in an effort to keep the relevant code annotations close to where the code is described. The formatting is a bit off since I originally planned to make the method name under the ‘Method’ header be a small header, but Medium’s formatting makes the formatting for a small header almost indistinguishable from bolded paragraph text. To make the method names stand out when scrolling through, I ended up making them regular headers which can be a bit confusing because that first ‘doBuild’ header is the same size as the overall ‘Method’ section header.</p><h3>Recap</h3><p>After the invocation of the ‘resolve’ hook from the ‘NormalModuleFactory.js’ file we were reviewing last post, the ‘resolve’ hook’s continuation callback invokes the ‘afterResolve’ hook (who’s invocation is defined in a lambda within the NormalModuleFactory’s constructor; search for ‘afterResolve.callAsync’).</p><p>After the invocation of the ‘afterResolve’ hook from the ‘NormalModuleFactory.js’ file completes, the ‘afterResolve’ hook’s callback invokes the ‘createModule’ hook also in NormalModuleFactory.js’.</p><p>I won’t be going over what the ‘NormalModuleFactory.hooks.afterResolve’ and ‘NormalModuleFactory.hooks.createModule’ hooks do since they don’t seem to have any important ‘taps’ defined. The continuation callback of the NormalModuleFactory’s ‘createModule’ hook is a point of interest though.</p><p>Inside the ‘createModule’ hook’s continuation callback, a new ‘NormalModule’ is instantiated with ‘resolveData.createData’ passed into its constructor (remember that ‘resolveData’ was populated with data in invocation of the ‘resolve’ hook).</p><p>The created ‘NormalModule’ is then passed in to a different function called ‘callback’ which is a reference to the callback passed into the NormalModuleFactory’s ‘create’ method from the ‘Compilation.js’ file’s ‘_factorizeModule’.</p><p>When the callback nears completion, it calls the callback passed into ‘_factorizeModule’ (defined in ‘factorizeModule’) with the new module as a parameter. Near the end of the callback passed into ‘_factorizeModule’, another callback is called (one passed into ‘factorizeModule’) from ‘handleModuleCreation’.</p><p>As you can see, it starts to get confusing here so I’ll skip ahead and summarize a lot of the details of the webpack processing until we get to the important bits again. Basically the program flow from the ‘factorize’ callback defined in ‘handleModuleCreation’ invokes a method call to ‘compilation.addModule’ using the NormalModule created previously, and in the callback to ‘compilation.addModule’ we’ll eventually hit a line that has the method call ‘this.buildModule’ that also takes in the new module.</p><p>This leads to ‘compilation._buildModule’ being called, as is the paradigm with this codebase, and somewhere in ‘compilation._buildModule’, a call to the NormalModule’s ‘build’ method is made. In the NormalModule’s ‘build’ method, the NormalModule’s doBuild method is immediately invoked. The processing starting from the ‘NormalModule.doBuild’ method is what I’ll cover in this blog post.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tF2AyJQ8CMPY_V2jMNetcQ.png" /></figure><h3>Scope</h3><p>The code I’m analyzing is from commit 044173eb0 of webpack. The overall focus for today is how webpack executes the code for loaders. This process is almost entirely encapsulated within a function called <strong>runLoaders</strong>. The function is contained in a different repository from webpack (aptly named ‘<strong>loader-runner’</strong>) and is built into a package and imported into the webpack codebase. In essence, the ‘runLoaders’ function essentially uses all the loaders that were identified by the NormalModuleFactory’s ‘create’ method, and runs the collected loaders to apply the desired source code transformations.</p><h3>Methods</h3><h3>doBuild</h3><p><em>Found in: NormalModule.js</em></p><p><strong>Summary</strong></p><p>This method runs all the loader functions on the source code of the module being processed. The resultant source code after all the loaders functions have been run is placed into the ‘NormalModule._source’ property (and a source map is also optionally placed into a different property).</p><p><strong>High Level Implementation Details</strong></p><p>Creates something called a loaderContext from the parameters. Passes in ‘resource’ (a property set on the NormalModule from the NormalModuleFactory creation), ‘loaders’ (a property set on the NormalModule from the NormalModuleFactory creation), and ‘loaderContext’ (created at beginning of method) as parameters to ‘runLoaders’ function along with a readResource lambda (which will help resolve files) and a continuation callback. The callback calls an inline function, ‘processResult’, where the resultant source from the loaders is used to populate the ‘NormalModule._source’ property.</p><p><strong>Annotated Code Snippet</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c8f9b9927fbd71382dd49f5fb6bac99/href">https://medium.com/media/9c8f9b9927fbd71382dd49f5fb6bac99/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DfbLvkUYg56l1fqzAho7cA.png" /></figure><h3>runLoaders</h3><p><em>Found in: LoaderRunner.js</em></p><p><strong>Summary</strong></p><p>Defines new properties on the loaderContext, maps the loaders passed in as a paramter to loaderObjects, and uses ‘iteratePitchingLoaders’ to continue loader processing and execution.</p><p><strong>High Level Implementation Details</strong></p><p>This method is located in the ‘loader-runner’ library. Extracts properties from the parameter object (labeled ‘options’) into local variables. Breaks apart the ‘resource’ (found in the ‘options’ and which represents the file path put in ‘entry’) into path, query, and fragment variables. All the loaders identified in the NormalModuleFactory’s ‘factorize’ process (passed in as ‘loaders’ into runLoader’s parameter) are passed into ‘loader-runner.createLoaderObject’. The method then defines ‘getters’ for properties within the ‘loaderContext’. It then calls ‘iteratePitchingLoaders’.</p><p><strong>Annotated Code Snippet</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61d49e7fc520006c24ca6dbc6a8148a9/href">https://medium.com/media/61d49e7fc520006c24ca6dbc6a8148a9/href</a></iframe><h3>createLoaderObject</h3><p><em>Found in: LoaderRunner.js</em></p><p><strong>Summary</strong></p><p>Creates an object that enhances the loader objects created by the NormalModuleFactory’s factorize method.</p><p><strong>High Level Implementation Details</strong></p><p>This creates a loader object with a slew of loader-related properties like the path, query, and fragment of the module being built (retrieved in loader-runner.runLoaders). All properties of the loader object are defined within a setter for the object’s ‘request’ property (although the getter for the request property just reconstructs the original module path).</p><p><strong>Annotated Code Snippet</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c4125b62364f788ac977dfda2de0c2f/href">https://medium.com/media/5c4125b62364f788ac977dfda2de0c2f/href</a></iframe><h3>iteratePitchingLoaders</h3><p><em>Found in: LoaderRunner.js</em></p><p><strong>Summary</strong></p><p>Runs the ‘pitch’ function, defined as a property on the loaderObject, for all defined loaders in the order they’re defined.</p><p><strong>High Level Implementation Details</strong></p><p>The loader at the current ‘loaderContext.loaderIndex’ is passed into the ‘loadLoader’ method (which is imported from the ‘loadLoader.js’ file). The ‘loadLoader’ continuation callback sets ‘pitchExecuted’ on the loader object being processed to true and invokes the ‘pitch’ function on the loader by calling ‘runSyncOrAsync’ with the loaderContext as a parameter. If there is no ‘pitch’ function defined, ‘iteratePitchingLoaders’ is called recursively.</p><p>On the subsequent execution of ‘iteratePitchingLoaders’ from within ‘runSyncOrAsync’s continuation callback (called if things go successfully), a condition will get hit in ‘iteratePitchingLoaders’ that will increment the loaderIndex if the current loader has it’s pitchExecuted property set to true. The condition body will then recursively call ‘iteratePitchingLoaders’ again with the new loaderIndex value. After ‘loaderContext.loaderIndex’ exceeds the size of the array, ‘iteratePitchingLoaders’ calls ‘loader-runner.processResource’ (which semantically means all loader ‘pitch’ functions have been processed through the ‘loader-runner.iteratePitchingLoaders’ method).</p><p><strong>Annotated Code Snippet</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae9714ecc7cf9fc03cb3ca23b13196be/href">https://medium.com/media/ae9714ecc7cf9fc03cb3ca23b13196be/href</a></iframe><h3>loadLoader</h3><p><em>Found in: loadLoader.js</em></p><p><strong>Summary</strong></p><p>Loads in the module defined in the loader file into the ‘loader’ passed in to it’s parameter.</p><p><strong>High Level Implementation Details</strong></p><p>This takes in a ‘loader’ object (which just has a path at this point) and constructs and then calls ‘eval’ on an ‘import’ statement (if the loader file is marked as a module in the config) to load in object defined in the loader file. The loader will be ‘require’d if not defined as an es6 module in the webpack config. The resultant object that’s loaded is placed into ‘loader.normal’ if the module exported is of function type, and sets ‘loader.normal’ to ‘module.default’ if an object was loaded (which basically means an es6 module was exported from the loader file). The ‘pitch’ and ‘raw’ properties on the loader object are set to whatever is defined for those keys on the loader-exported object.</p><p><strong>Annotated Code Snippet</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6292191777610b563367d46aec674f95/href">https://medium.com/media/6292191777610b563367d46aec674f95/href</a></iframe><h3>processResource</h3><p><em>Found in: LoaderRunner.js</em></p><p><strong>Summary</strong></p><p>Reads in the file into a buffer and calls ‘iterateNormalLoaders’</p><p><strong>High Level Implementation Details</strong></p><p>Sets ‘LoaderIndex’ to the index of the last item in the loaderContext loaders array since it should be equal to the length of the array (which is not a valid index) when it gets here from ‘iteratePitchingLoaders’. This method then assigns the path of the file being processed from ‘loaderContext.resourcePath’ into a local variable named ‘resourcePath’. If ‘resourcePath’ is not null, ‘options.processResource’ is called which reads in the file specified in the resource into a buffer (options.processResource is defined in the ‘processOptions’ variable definition in the ‘runLoaders’ method; it’s ultimately derived from the ‘readResource’ property defined in the options parameter in the call to ‘runLoaders’ from NormalModule.js).’iterateNormalLoaders’ is then called with the buffer containing the file information passed in as a parameter. If the resourcePath isn’t present, ‘iterateNormalLoaders’ is called with no buffer.</p><p><strong>Annotated Code Snippet</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/044b283f01b89ed35314e83dbcd366d9/href">https://medium.com/media/044b283f01b89ed35314e83dbcd366d9/href</a></iframe><h3>iterateNormalLoaders</h3><p><em>Found in: LoaderRunner.js</em></p><p><strong>Summary</strong></p><p>Runs the ‘normal’ function property from the generated loaderObject for all defined loaders.</p><p><strong>High Level Implementation Details</strong></p><p>Looks to see where it’s ‘context.loaderIndex’ is and invokes the callback to continue the flow of execution if ‘context.loaderIndex’ is below 0. Otherwise it retrieves the loader at that loader index (by accessing the ‘loaderContext.loaders’ array) and calls ‘runSyncOrAsync’ on the loader object’s ‘normal’ function property (if not already executed). After running the ‘normal’ property on the loader using ‘runSyncOrAsync’, the continuation callback decrements the loaderIndex and calls ‘iterateNormalLoaders’ recursively (just like iteratePitchingLoaders).</p><p><strong>Annotated Code Snippet</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6dfca788161d9e5c6ba55b66aa4e663a/href">https://medium.com/media/6dfca788161d9e5c6ba55b66aa4e663a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5T3-3m4JdzmZvMxeTSKWmw.png" /></figure><h3>runSyncOrAsync</h3><p><em>Found in: LoaderRunner.js</em></p><p><strong>Summary</strong></p><p>This function is the one used to call every defined loader function retrieved in ‘loadLoader’ on the file buffer read in through processResource.</p><p><strong>High Level Implementation Details</strong></p><p>This function runs the loader functions by calling the ‘apply’ method (a property on all defined Javascript functions) on the loader’s ‘normal’ property (which should contain the default export of the loader file) while also passing in the loaderContext and the source file text as parameters.</p><p>It also defines ‘context.async’ to return a function that’s also defined in this function as ‘innerCallback’. When this ‘innerCallback’ function returned from the invocation of ‘context.async’ is called, it will pass the arguments passed into it into the continuation callback that will continue the flow of execution. So if the loader function calls ‘context.async’ (since ‘context’ is the first parameter passed into loader functions) then it will return a callback function that can take in asynchronous results when invoked.</p><p><strong>Annotated Code Snippet</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cd98ad13e9742719df2ca24a7b358af/href">https://medium.com/media/4cd98ad13e9742719df2ca24a7b358af/href</a></iframe><h3>Next Time</h3><p>I hope to get more into the code generation portion and work my way to the wrap-up of this series.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6be19a3a035" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Webpack Deep Dive Part 5: Loading Loaders]]></title>
            <link>https://medium.com/geekculture/webpack-deep-dive-part-5-loading-loaders-76496cca83e8?source=rss-507825a98fec------2</link>
            <guid isPermaLink="false">https://medium.com/p/76496cca83e8</guid>
            <dc:creator><![CDATA[Randall Naar]]></dc:creator>
            <pubDate>Mon, 08 Mar 2021 04:07:43 GMT</pubDate>
            <atom:updated>2021-03-15T20:25:55.456Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*HC9rHTj-5vsHjElurl026w.png" /></figure><h3>Introduction</h3><p>When I started writing this blog series I thought I would only spend 3 months on this at most but if you’ve taken notice of my posting pattern, its already been a lot longer than that. I’ve accepted my inability to post on a consistent schedule and have embraced my lackadaisical approach to blogging. I have to remember it’s a pastime intended for enjoyment and shouldn’t be forced at the expense of content quality (*cough* like my last post *cough*). To that end, blogging at a slower pace allows me to more objectively assess my own content and deliver better quality articles so that’s what I’ll be striving to do.</p><p>I honestly couldn’t remember what I was looking at in the codebase for the last article, but I was luckily able to read my old posts to get up to speed! I can now come back to writing informed by the feedback from one of my most loyal readers — myself. Expect a lot more drawings in this one and a lot more technical brevity because that’s the feedback I gave myself.</p><h3>Recap</h3><p>Last time we focused on the ‘addEntryItem’ call chain within the compilation.js file (kicked off by the ‘make’ hook in compiler.js). ‘compilation.addEntryItem’ ended up leading to the invocation of the ‘compilation.handleModuleCreation’ method which calls a method called ‘compilation.factorizeModule’. ‘compilation.factorizeModule’ ends up adding the parameters to a queue called the ‘factorizeQueue’ which ends up asynchronously calling ‘_factorizeModule’. The ‘_factorizeModule’ method essentially just invokes ‘create’ on the ‘factory’ that resides in its options parameter, which corresponds to the ‘NormalModuleFactory.create’ method that we’ll be inspecting today.</p><p><strong>I’ve made a sequence diagram showing which part we’re focusing on today as well:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3y_H8KbnyKkiuq_AfHQkfw.png" /></figure><h3>Context</h3><p>This section of the code requires the reader to know what a ‘loader’ is, so I decided to write my own informal explanation here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*DZ3k9rAg2peqCUIX8H_n6w.png" /></figure><h4>What is a loader?</h4><p>As you may already know, Webpack was a tool made to simplify dependency management for javascript files on the web. The webpack library does this by generating the javascript ‘bundles’ that will be run in the browser that combines all the javascript files your web page needs in one file. To add on to webpack’s functionality, the tool can also be made to generate javascript from files with arbitrary syntax. In fact, this is partly how the module bundling works. If I have a file ‘A.js’ that has the line ‘let libraryB = require(“b.js”)’, webpack is already compiling non-standard syntax since ‘require’ isn’t part of the ECMAScript standard (the standard that guides the implementation of Javascript in web browsers).</p><p>Since non-standard javascript was being interpreted and transformed anyway, the concept of a ‘loader’ ended up being a more abstract generalization of that concept who’s purpose is to transform the string content of a source code file. The implementation of a loader is defined to be any function that follows a specific interface and is properly registered in the webpack config. Loaders can transform a source file with invalid javascript syntax to be valid (like changing the contents of a React file to browser-compatible javascript), it could change invalid javascript to another form of invalid javascript (like transforming a React file to use Vue syntax), or it could even perform a transform from valid javascript to another form of valid javascript (which could be as simple a transform as deleting empty lines of code).</p><h3>Scope</h3><p>The code I’m analyzing is from commit da67529a2 of webpack. It will encompass the <strong>NormalModuleFactory.create</strong> method (spawned by the ‘compilation.factorizeModule’ method discussed at the end of the previous post) and the hooks <strong>factorize</strong> and <strong>resolve</strong> subsequently invoked within the <strong>NormalModuleFactory.js</strong> file. The code I’m reviewing today covers how webpack parses inline loaders and loader-directives, how webpack handles the retrieval of loaders specified in the webpack config (at a high level), and how module aliases (officially referred to as the ‘matchResource’ within a module) are used.</p><p>Why are we reviewing so few methods? Because the ‘resolve’ hook has a particularly beefy function attached to it that I had to refactor just to explain!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*6IQziScYb5eNqGcj4Q47UA.png" /></figure><h4>A note on refactoring</h4><p>My goal for these posts is usually not to refactor code, it’s to analyze the existing source code for webpack in an effort to understand what’s going on. Unfortunately the original source code confused me quite a bit and even when I started to understand what was going on, I didn’t know how to explain what was happening coherently. Towards that end I tried to break it down into smaller logical components to help my own understanding. In programming, this pretty much leads to the creation of functions and methods — hence the refactor. Since I used my refactored code to augment my own learning process, I decided why not use it to augment yours? The refactored code isn’t perfect but I believe it does provide improvements in clarity. For those of you concerned it will impede your original understanding of the webpack source code, rest assured, I will post github links above each refactored method leading to the corresponding lines in the original code base.</p><p>In my re-factored code we’ll be going over the newly minted <strong>resolve</strong>, <strong>getResourceData</strong>, <strong>resolveLoaders</strong>, <strong>getApplicableLoaders</strong>, <strong>tryGetInlineLoaderDirectives</strong>, and <strong>tryGetModuleAlias</strong> methods. I know it seems like a lot, but remember, it was all refactored from the one function attached to the ‘resolve’ hook so theoretically the code quantity shouldn’t be too big…</p><h3><strong>Method Summaries</strong></h3><p><strong>NormalModuleFactory.create</strong> — Not much going on here, this method just initializes some data (data not relevant to us for now) and kicks off the hooks for ‘beforeResolve’ and ‘factorize’</p><p><strong>NormalModuleFactory.hooks.factorize</strong> — calls ‘resolve’, ‘afterResolve’, and ‘createModule’ hooks</p><p><strong>NormalModuleFactory.hooks.resolve </strong>— calls the ‘resolve’ method</p><h3>Refactor Method Summaries</h3><p><strong>resolve</strong> — This function was created from the inline-defined lambda attached to the NormalModuleFactory’s ‘resolve’ hook (‘this.hooks.resolve’) from the NormalModuleFactory’s constructor. It was separated out into it’s own function to reduce inlining and shorten the constructor all-together. This hook gets called from the NormalModuleFactory’s ‘create’ call chain so moving this functionality out into its own method makes it easier to reference.</p><p>In essence, the method calls that this method orchestrates has the end goal of identifying all the loaders that should be run on the file (determined using the ‘request’ contained within the ‘resolve’ method’s ‘data’ parameter).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*P4bmVUN8cqwqTRL8SGy74Q.png" /></figure><p><strong>tryGetModuleAlias</strong> (called from ‘resolve’) — Webpack has a feature that allows you to use a different name for a file when regex testing to see which loaders should be used on the file. This is done through a directive in the specification of the file path. You must specify the replacement name in the following format ‘{{replacement_name}}!=!{{regular_path_to_file}}’. This method will return the module alias data (an object that contains the moduleAlias within the ‘resource’ property).</p><p><strong>tryGetInlineLoaderDirectives</strong> (called from ‘resolve’) — This method looks for certain characters prefixing the path to the file being processed. When present it can disable the usage of ‘PreAutoLoaders’, ‘AutoLoaders’, or ‘PrePostAutoLoaders’ on the file being processed. This method also processes directives that allow the explicit specification of loaders that should be used to process the file. The loaders are specified in the following format ‘{{loader1}}!{{loader2}}!{{loaderN}}!{{regular_path_to_file}}’. These directives can not be used within a module alias, but can be used in addition to one.</p><p><strong>getResourceData</strong> (called from ‘resolve’) — resolves the path to the file being processed if a relative path is found. In our case the entry file is the file being processed by the NormalModuleFactory. If there is no relative path and the entry string being processed includes a ‘scheme’, the string is invoked as a parameter to NormalModuleFactory’s ‘resolveForScheme’ hook.</p><p>*Scheme — an alphanumeric sequence (that can also include ‘+’ and ‘-’s) at the start of the string ending in a colon</p><p><strong>resolveLoaders</strong> (called from ‘resolve’) — This method retrieves all the loaders that should be applied to the file being processed and puts that information in ‘data.createData’ (which is ultimately what’s used to propagate data back to ‘NormalModuleFactory.create’)</p><p><strong>getApplicableLoaders</strong> (called from ‘resolveLoaders’) — This invokes a method on something called a ‘ruleset’ with the file path (or module alias) as one of the parameters. The return value of the ruleset invocation is an array of objects with the schema: {ident: string, loader: string, options: Object}. The ‘loader’ property holds the absolute path to the respective loader file. The output to the ‘getApplicableLoaders’ method is a subset of the ruleset array that respects the restrictions placed by the loader directives (i.e. The directive in a module path indicated by 2 exclamation marks at the beginning).</p><h3>Annotated Code Inspection</h3><p>It was a challenge trying to link my re-factored code to the original webpack source. Even so, I tried to do it to the best of my ability. In my opinion the refactor is a huge improvement. So much so that I kind of want to make a PR to the official codebase but don’t know if I have the time to get buy-in from the maintainers and prove that using Promises won’t inflict too much of a performance hit.</p><p>Anyway, onward to the annotated code inspection:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8835f9d3836569c7e0bb113b7a5453e9/href">https://medium.com/media/8835f9d3836569c7e0bb113b7a5453e9/href</a></iframe><h3>Next Time</h3><p>Looks like I might’ve missed my goals for technical brevity but what can I say, such is life. Next time look forward to the exploration of the rest of the hooks and callbacks called by ‘NormalModuleFactory.create’.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76496cca83e8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/webpack-deep-dive-part-5-loading-loaders-76496cca83e8">Webpack Deep Dive Part 5: Loading Loaders</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Webpack Deep Dive Part 4: Module Creation]]></title>
            <link>https://randynaar.medium.com/webpack-deep-dive-part-4-module-creation-6fa29e270e2a?source=rss-507825a98fec------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fa29e270e2a</guid>
            <dc:creator><![CDATA[Randall Naar]]></dc:creator>
            <pubDate>Fri, 01 Jan 2021 19:33:06 GMT</pubDate>
            <atom:updated>2021-02-23T11:05:46.639Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>It’s been a while since my last post but I’m finally back! I attribute my slow pace of publishing to my previous lack of structure, but now I’ve decided to dedicate time towards creating a structural framework for my future posts. Below is a detailed description of the sections that will compose my future posts:</p><p><strong>Introduction - </strong>This is where I’ll discuss updates to my blogging schedule, recent roadblocks I’ve overcome, and my overall blogging experience in general.</p><p><strong>Recap -</strong> This will give context on where we are in our exploration of the webpack codebase. It will cover what we did in the last post and should set the stage for the current post.</p><p><strong>Scope - </strong>This will tell the reader which files and methods I’ll be reviewing along with which commit of webpack I’ll be looking at.</p><p><strong>Method Summaries -</strong> This section reveals what I learned about each method described in the scope. The methods will usually be listed in the order that they appear in the call stack so that the summaries can lead into each other.</p><p><strong>Annotated Code Inspection -</strong> This is where I’ll comment on the code itself, leaving inline comments describing the implementations of various methods.</p><h3>Recap</h3><p>Up until this post we’ve been following what the webpack code does when run with it’s default configuration. We do this by calling the<a href="https://webpack.js.org/api/node/"> webpack function offered as part of the node API</a> and passing in an empty options object. <a href="https://github.com/webpack/webpack/blob/cbcd459d19865175b17bdf60b76d3da838f62a47/lib/webpack.js#L95">Using the ‘webpack’ function as an entry point to the webpack codebase,</a> we explored the inner logic of the function towards the goal of understanding the entire bundling flow.</p><p>On a surface level the ‘webpack’ function delegates its logic to other functions within the ‘webpack.js’ file. The 2 functions it delegates to are ‘createCompiler’ and ‘run’. ‘createCompiler’ configures the default values for the options object passed in and creates a ‘compiler’ object to return. The ‘run’ method is then called on the ‘compiler’ and the webpack function terminates.</p><p>Looking deeper into the compiler class, the code for the ‘run’ method calls another inline function labeled ‘run’. I won’t get too much into code critique here but worry not, I’ll circle back to this. The inline ‘run’ nested in the original ‘compiler.run’ method calls some hooks and delegates the execution to yet another method titled ‘compile’. In the ‘compile’ method a ‘compilation’ object is made and more hooks are invoked (with only some taking the ‘compilation’ object).</p><p>Looking at the structure of the code, it’s safe to say most of the logic is actually encapsulated within these hooks. The hooks ‘beforeRun’, ‘run’, ‘beforeCompile’, ‘compile’, ‘make’, and ‘finishMake’ (defined on the ‘this.hooks’ property on the compiler object) seem to collectively enable the bundling behavior, but what each hook does individually is a mystery I hope to unravel starting with this blog post.</p><p>The two hooks that accept the compilation object are ‘make’ and ‘finishMake’ which suggests that the ‘make’-related hooks are good candidates for further analysis. Looking at the attached functions for the ‘make’ hook (the functions that are invoked when the hook is called), the function registered with the identifier ‘EntryPlugin’ specifically seems to push the bundling forward. The hoooked ‘EntryPlugin’ function calls the ‘addEntry’ method on the compilation object which is what we’ll be looking at for this post.</p><h3>Scope</h3><p>The scope of this post will cover the methods ‘compilation.addEntry’ (invoked from the ‘make’ hook), ‘compilation._addEntryItem’, ‘compilation.addModuleChain’, and ‘compilation.handleModuleCreation’ within the file ‘compilation.js’. The code I’m analyzing is from commit <a href="https://github.com/webpack/webpack/tree/da67529a213ccb0e687d5f95144faad7bdf26a53">da67529a2 of webpack</a> and I’ll only be covering the execution paths taken when using an empty webpack options object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0E9-uTVn5XaqKy8PlBiKNw.png" /></figure><h4>addEntry</h4><p>The addEntry method enforces the ‘options’ parameter is an object and calls ‘_addEntryItem’ to take care of the real logic.</p><h4>_addEntryItem</h4><p>This method makes an ‘entryData’ object and sticks the ‘entry’ parameter in the ‘dependencies’ array property. This method then puts the ‘entry’ parameter in the ‘this.entries’ map (using the string “main” as a key) and calls the ‘addModuleChain’ method.</p><h4>addModuleChain</h4><p>‘addModuleChain’ gets something called the NormalModuleFactory from ‘this.dependencyFactories’ using the class constructor of the entry parameter as a key (‘entry.constructor’). This method then passes the created module factory into ‘handleModuleCreation’ along with the ‘dependency’ it received as a parameter.</p><h4>handleModuleCreation</h4><p>This is the meatiest method of this section. It calls the compiler class’s ‘factorize’ method and passes the returned, ‘factorized’ module into another method called ‘addModule’. The resultant module returned from ‘addModule’ is added to something called a dependency graph, checked for cyclic build dependencies before being passed into ‘buildModule’. The module that’s built is passed into ‘processModuleDependencies’ which scans the built module for dependencies and passes each of them into ‘handleModuleCreation’ leading to a recursive cycle of building modules.</p><h3><strong>Annotated Code Inspection</strong></h3><p><strong>context</strong>— The directory webpack was called from</p><p><strong>entry</strong> — An object containing information on the path for the file being processed</p><p><strong>optionsOrName</strong> — an object where, in our example, everything is set to null except the name</p><p><strong>callback</strong> — a callback that will resume execution of the bundling process</p><p>I’ll only write these parameters out once since all the subsequent methods take some variant of those same parameters. JSDoc comments exist as well, but hopefully I can give more information on what the parameters actually are with my informal descriptions above.</p><p>Now, let’s take a look at the ‘addEntry’ and the ‘_addEntryItem’ methods below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1e0e3e94652aabf0e19be5ad5082e7f/href">https://medium.com/media/f1e0e3e94652aabf0e19be5ad5082e7f/href</a></iframe><p>‘addModuleChain’ doesn’t do much in terms of logic. It basically just creates a module factory and passes that on to the next method ‘handleModuleCreation’:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdd69c1e63c8e8271887971003050f47/href">https://medium.com/media/bdd69c1e63c8e8271887971003050f47/href</a></iframe><p>Next we’ll go over the code of the last method in this post, ‘handleModuleCreation’:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84b5698ea62d727e74ea17c16f84c742/href">https://medium.com/media/84b5698ea62d727e74ea17c16f84c742/href</a></iframe><h3>Next Time</h3><p>Hopefully this post was a good introduction to these methods and you have a (very) rough idea of where the execution is headed. In the next post, Part 5, I’ll get into more detail about how ‘factorizeModule’ works and lend my comments to that code snippet as well. Until then, stay on the lookout for my next post and feel free to leave suggestions on how I can improve this series. As always, thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fa29e270e2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>