<?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 Mipsmonsta on Medium]]></title>
        <description><![CDATA[Stories by Mipsmonsta on Medium]]></description>
        <link>https://medium.com/@mipsmonsta?source=rss-2e71d1e75abd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FD7xspzBIG463bKM4OyX0A.png</url>
            <title>Stories by Mipsmonsta on Medium</title>
            <link>https://medium.com/@mipsmonsta?source=rss-2e71d1e75abd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 06:07:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mipsmonsta/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[Fast Python Prime Counting using Optimised Sieve of Eratosthenes]]></title>
            <link>https://mipsmonsta.medium.com/fast-python-prime-counting-using-optimised-sieve-of-eratosthenes-6f645d8f658?source=rss-2e71d1e75abd------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f645d8f658</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[prime-numbers]]></category>
            <category><![CDATA[leetcode-medium]]></category>
            <dc:creator><![CDATA[Mipsmonsta]]></dc:creator>
            <pubDate>Mon, 24 Oct 2022 03:58:50 GMT</pubDate>
            <atom:updated>2022-10-24T03:58:50.653Z</atom:updated>
            <content:encoded><![CDATA[<p>Harnessing the slice ability of Python</p><p>Sieve of Eratosthenes is a simple and ancient algorithm used to find the prime numbers. It is one of the most efficient ways to find small prime numbers.</p><p>For a given upper limit n, the algorithm works by iteratively marking the multiples of primes as composite, starting from 2. Once all multiples of 2 have been marked composite, the muliples of next prime, ie 3 are marked composite. This process continues until p ≤= sqrt(n) where p is a prime number.</p><p>Algorithm to implement in Python is as such:</p><pre>def countPrimes(self, n: int) -&gt; int:</pre><pre>    if n &lt;= 2:<br>        return 0</pre><pre>    sieve = [1]*(n) # 0, 1, 2, ... n-1, exclude n since find primes          <br>                    # less than n; true means prime</pre><pre>    sieve[0] = 0<br>    sieve[1] = 0</pre><pre>    p = 2 # first prime<br>    while p*p &lt;= n:<br>        for i in range(p*p, n):    <br>            if i % p == 0: # multiples of p, <br>                       # so make as composites (not primes)<br>                sieve[i] = 0</pre><pre>        for i in range(p+1, n): # find the next prime p<br>            if sieve[i]:<br>                p = i<br>                break</pre><pre>    return sum(sieve)</pre><p>While the above is a faithful reproduction of the <a href="https://brilliant.org/wiki/sieve-of-eratosthenes/#:~:text=Sieve%20of%20Eratosthenes%20is%20a,as%20composite%2C%20starting%20from%202.">algorithm</a>, it is slow. If you look at the “While” loop, it’s basically execution with O(n*n) time. Hence, if you attempt the question on leetcode of <a href="https://leetcode.com/problems/count-primes/">counting prime</a>, you will have time limit error. Their testcases have very high value of n. So even if you know how to code the Sieve of Eratosthenes, you still need to optimise the run-time.</p><p>Python does have the slicing features. We oft extract a shallow copy of an iterable list using <a href="https://stackoverflow.com/questions/509211/understanding-slicing"><em>array[start:end:step] </em></a>syntax. <strong>But we seldom using it to change out the values of the slice.</strong></p><p>Focusing on the section of the code to optimise:</p><pre>for p in range(2, int(n**0.5) + 1):<br>    if sieve[p]: # is a prime<br>        # multiples of p is marked as 0 i.e. composite<br>        sieve[p*p:n:p] = [0]*len(sieve[p*p:n:p])      </pre><p>The above optimised code of marking composite starting from the first mutiple of p (after p itself) which is p*p to end of sieve array, and finding the next prime <strong>is fast at O(n) i.e. linear time</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f645d8f658" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FAQ of Bitwise Manipulation and their Semantics]]></title>
            <link>https://mipsmonsta.medium.com/compendium-of-bitwise-manipulation-and-their-semantics-19c629132234?source=rss-2e71d1e75abd------2</link>
            <guid isPermaLink="false">https://medium.com/p/19c629132234</guid>
            <category><![CDATA[bitwise-operator]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Mipsmonsta]]></dc:creator>
            <pubDate>Thu, 15 Sep 2022 12:32:16 GMT</pubDate>
            <atom:updated>2022-10-30T01:45:47.226Z</atom:updated>
            <content:encoded><![CDATA[<p>I am bad at bitwise operations. So what better way then to create an aide memoir of my learnings. I will update as life goes along.</p><p><strong>Given an array with two repeated numbers and one single number, how to find the single number using XOR?</strong></p><pre>e.g. array = [4, 4, 8]</pre><pre>def findSingleNumber(array):</pre><pre>    result = 0<br>    for num in array:<br>        result ^= num<br>    return result </pre><pre>Output of findSingleNumber([4, 4, 8]) will be 8.</pre><p>The above works, because an xor of two repeated number will be zero. And zero xor with the single number will be the single number. Key here is xor will only be 1 when the two xor-ed bits are <strong>clear </strong>and <strong>set </strong>bits.</p><h4><strong>How to find the least significant set bit?</strong></h4><pre>def getLeastSignificantSetBit(num :int):<br>    result = num &amp; (-num)<br>    return result</pre><pre>E.g. num == 4, i.e. 0b000…0100.<br>-4 or -num is 0b111...1100<br>result returns 0b000...0100 </pre><h4>How to remove the rightmost set bit or the least significant set bit?</h4><pre>n&amp;(n-1) <strong>will remove the rightmost</strong> in binary representation of n. <br>For example if n = 10110100, then n &amp; (n-1) = 10110100 &amp; 10110011 = 10110000,</pre><h4>How do you reverse a bit string (represented by a 32 bit unsigned integer) fast?</h4><pre>def reverseBits(self, n: int) -&gt; int:<br>    result = 0<br>    <br>    for i in range(32):<br>        result = (result &lt;&lt; 1) |(n &amp; 1) # push from left <br>                                       # to right using</pre><pre>        n //= 2 # pop from left</pre><pre>     return result</pre><h4><strong>How to check if a positive integer number n is of power of two fast?</strong></h4><pre>def isPowerOfTwo(self, n: int) -&gt; bool:<br>    return n &amp; (n-1) == 0 # 100 &amp; 011 == 0</pre><pre># explaination: e.g. 0100 &amp; 0011 == 0</pre><h4>How do you generate a fixed length bitmask from 0…00 to 1…000 in Python? What is the use?</h4><pre>for i in range(2**length, 2**(length+1)):<br>    bitmask = bin(i)[3:]</pre><pre># Above code generate bit mask 0..00 to 1..11<br># E.g. if length == 3: 2**3 is 1000 and<br># 2**4 - 1 is 1111 (2**4 is 10000).<br># The function call bin(i) produces binary string of &quot;0b1000&quot; to <br># &quot;0b1111&quot;,so bin(i)[3:] removes prefix &quot;0b1&quot; to give us the fixed # <br># length(3) bitmask.</pre><h4>What is the use? — Creating a<a href="https://leetcode.com/problems/subsets/"> Power Set </a>from a list of integers.</h4><pre>from typing import List</pre><pre>class Solution:<br>def subsets(self, nums: List[int]) -&gt; List[List[int]]:<br>    powerSet = []<br>    length = len(nums)</pre><pre>    for i in range(2**length, 2**(length+1)):</pre><pre>        bitmask = bin(i)[3:]<br>        aSet = []<br>        for j in range(length):<br>            if bitmask[length - j - 1] == &quot;1&quot;:<br>                aSet.append(nums[j])<br>                powerSet.append(aSet)</pre><pre>    return powerSet</pre><pre>nums = [1,2,3]<br>Ouput = [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3], [4], [1, 4], [2, 4], [1, 2, 4], [3, 4], [1, 3, 4], [2, 3, 4], [1, 2, 3, 4]]</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19c629132234" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Negative Numbers are Represented in Python?]]></title>
            <link>https://mipsmonsta.medium.com/how-negative-numbers-are-represented-in-python-243c2a594015?source=rss-2e71d1e75abd------2</link>
            <guid isPermaLink="false">https://medium.com/p/243c2a594015</guid>
            <category><![CDATA[bitwise-operator]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Mipsmonsta]]></dc:creator>
            <pubDate>Wed, 14 Sep 2022 10:19:10 GMT</pubDate>
            <atom:updated>2022-09-14T10:19:10.115Z</atom:updated>
            <content:encoded><![CDATA[<p>We all learn our binary representation of integers in high school or Introduction to Programming 101 classes.</p><p>The other day, when I was playing with bit-wise masking using Python, I was puzzled how Python represents negative numbers.</p><p>Turns out, it’s not too different and as usual, you need to use Two’s Complements to decipher. As Python’s integer type uses a variable number of bits to represent integers, it might be confusing for us older folks to understand how to work with the bit string after masking. Let’s look at some code and output.</p><pre>class Solution:</pre><pre>    def maskingIntoBitString(self, negativeNumber: int):<br>        assert negativeNumber &lt; 0<br>        mask = 0xFFFFFFFF <br>        return negativeNumber &amp; mask</pre><pre>&gt; result = s.maskingIntoBitString(-4)<br>&gt; 11111111111111111111111111111100 </pre><p>If you print out the variable result, the output will be 4294967292.</p><p>So how do we get back -4 from the bitstring of 11111111111111111111111111111100?</p><p>Try this code :)</p><pre>def negativeRepToNumber(self, bitList: List[str]):</pre><pre>&quot;&quot;&quot; In order to allow bit-wise operations, python represents negative number e.g. -4 as 111....11100. So we need to flip the bits and add 1 to get the postive number than add sign.</pre><pre>&quot;&quot;&quot;<br>    for i in range(len(bitList)):<br>        if bitList[i] == &quot;0&quot;:</pre><pre>            bitList[i] = &quot;1&quot;</pre><pre>        else:</pre><pre>            bitList[i] = &quot;0&quot;</pre><pre>        return -(int(&quot;&quot;.join(bitList), 2) + 1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HoHTedKO0d5L0xqA" /><figcaption>Photo by <a href="https://unsplash.com/@mbaumi?utm_source=medium&amp;utm_medium=referral">Mika Baumeister</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=243c2a594015" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang: Creating Images and Drawing — Simply Explained (Part 2)]]></title>
            <link>https://mipsmonsta.medium.com/golang-creating-images-and-drawing-simply-explained-part-2-4cf4aad2f85b?source=rss-2e71d1e75abd------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cf4aad2f85b</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[compositing]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Mipsmonsta]]></dc:creator>
            <pubDate>Sun, 03 Apr 2022 09:46:00 GMT</pubDate>
            <atom:updated>2022-04-03T09:46:00.731Z</atom:updated>
            <content:encoded><![CDATA[<h3>Golang: Creating Images and Drawing — Simply Explained (Part 2)</h3><h4>Drawing functions to unleash your creativity</h4><p>In the <a href="https://mipsmonsta.medium.com/golang-creating-images-and-drawing-simply-explained-part-1-31097e92d6e2">first part of the titular article (i.e. Part 1)</a>, we were introduced to the various data structs and the image.Image interface in the standard golang library.</p><p>In this part 2, let’s look at compositing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1TmExuQwSY8KgG8X" /><figcaption>Photo by <a href="https://unsplash.com/@jekafe?utm_source=medium&amp;utm_medium=referral">Jessica Felicio</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Compositing</h4><p>Compositing is where you have a few images and you want to layer them onto each other. It’s not just so simple as putting one image on top of the other, or overlapping them. In the process of compositing you actually use the alpha channels of each image to describe not the opacity but the shape of the image to layer.</p><p>A seminal paper describing how the source image and the destination image can be composited together was put forth by <a href="https://keithp.com/~keithp/porterduff/p253-porter.pdf">Thomas Porter and Tom Duff</a>. There are 12 compositing modes that can be invoked using Porter/Duff operations. However, in Golang’s <a href="https://go.dev/blog/image-draw">official blog article</a>, it’s stated:</p><blockquote>The Porter-Duff paper presented <a href="http://www.w3.org/TR/SVGCompositing/examples/compop-porterduff-examples.png">12 different composition operators</a>, but with an explicit mask, only 2 of these are needed in practice: source-over-destination and source. In Go, these operators are represented by the Over and Src constants.</blockquote><blockquote>The Over operator performs the natural layering of a source image over a destination image: the change to the destination image is smaller where the source (after masking) is more transparent (that is, has lower alpha).</blockquote><blockquote>The Src operator merely copies the source (after masking) with no regard for the destination image’s original content. For fully opaque source and mask images, the two operators produce the same output, but the Src operator is usually faster.</blockquote><p>The two functions in the small image/draw package that you must be familar to use in compositing are. But I would like to focus on the Draw function in this article.</p><pre>func Draw(dst Image, r image.Rectangle, src image.Image, sp image.Point, op Op)<br>func DrawMask(dst Image, r image.Rectangle, src image.Image, sp image.Point, mask image.Image, mp image.Point, op Op)</pre><h4>Draw function Dissected</h4><p>The dst image is just a image.Image. Image structs such as pointer to image.RGBA are accepted since they implement the image.Image interface.</p><blockquote>Note, it’s the <a href="https://pkg.go.dev/image#RGBA">pointer to image.RGBA </a>that is implementing the image.Image interface. I say again so it will save you less grief.</blockquote><p>Usually, you will use image.NewRGBA(image.Rect(0, 0, image_width, image_height) to give you a pointer to image.RGBA.</p><p>If you want to use a fixed sized and solid colored destination image, you could do the following</p><pre>imgWidth = 276 // integer pixels<br>imgHeight = 174 //integer pixels</pre><pre>bgColor := image.White</pre><pre>rgba := image.NewRGBA(image.Rect(0,0, imgWidth, imgHeight))</pre><pre>draw.Draw(rgba, rgba.Bounds(), bgColor, image.Pt(0, 0), draw.Src)</pre><pre>//rgba will now be a white colored image of imgWidth width and imgHeight height</pre><p>Recall the draw function signature:</p><pre>func Draw(dst Image, r image.Rectangle, src image.Image, sp image.Point, op Op)</pre><p>Notice that for<em> r</em>, we use the rgba.Bounds() which return the bounds of the rgba rectangle. This is the destination bounding rectangle that will be drawn over. Parameter <em>src</em> (source) is the image.White, which is a image.Uniform struct representing a solid color that is infinite-sized.</p><p>You say infinited-sized? Then do we state the source image size to “draw” onto the “destination image”? <strong>No.</strong> The Draw function assumes that the destination bounding rectangle, where compositing is going to happen, is the same size as the rectangle slice of the source image that will be composited. Hence, in the parameter <em>sp, </em>which is an image.Point, we are setting where is the top-left point in source image that will correspond to minimum-x and minimum-y point of the destination bounding rectangle. <em>This is the most confusing part of using the draw function. Re-read this part if you do not understand. Don’t just gloss over.</em></p><p>Finally, the op parameter accepts<em> Src </em>or <em>Over</em> operations. From the official golang blog:</p><blockquote>The Over operator performs the natural layering of a source image over a destination image: the change to the destination image is smaller where the source (after masking) is more transparent (that is, has lower alpha).</blockquote><blockquote>The Src operator merely copies the source (after masking) with no regard for the destination image’s original content.</blockquote><p>In the case of the draw function, since a nil mask is used (akin to using a fully opaque mask), Src and Over operations are the same, i.e. the source image will just be “drawn” over the destination fully (and you cannot see below the source for the destination pixels at all).</p><h4>More complex example</h4><p>Below is a piece of code I wrote to print a QR code at the top-left or top-right or bottom-left or bottom right of the a rectangular white image background.</p><pre>func PrintQRCodeWithWhiteBgImageWithURL(url string, width, height int, corner int, offsetCorner int) (image.Image, error) {</pre><pre>   rgba := image.NewRGBA(image.Rect(0, 0, width, height))</pre><pre>   qr, err := generateQRCodeImageFromURL(url, 512)<br>        if err != nil {<br>                return nil, err<br>        }</pre><pre>   //resize QR code - half of the shortest end<br>        var ss int<br>        if width &lt; height {<br>                ss = width<br>        } else {<br>                ss = height<br>        }<br>        scaleTo := ss / 2<br>        qr_scaled := ScaleImage(&amp;qr, scaleTo, scaleTo, ScaleBestQ)<br>        // f, err := os.Create(&quot;./test/test_qr.png&quot;)</pre><pre>   //draw white background<br>        bg := image.White<br>        draw.Draw(rgba, rgba.Bounds(), bg, image.Point{X: 0, Y: 0},   <br>                  draw.Src)</pre><pre>   //compute qr top left point in dst<br>        var topLeftQR image.Point<br>        switch corner {<br>        case QRLowerRightCorner:<br>                topLeftQR = image.Point{X: width - scaleTo - <br>                offsetCorner, Y: height - scaleTo - offsetCorner}    <br>        case QRLowerLeftCorner:<br>                topLeftQR = image.Point{X: offsetCorner, Y: height - <br>                scaleTo - offsetCorner}<br>        case QRUpperRightCorner:<br>                topLeftQR = image.Point{X: width - scaleTo - <br>                offsetCorner, Y: offsetCorner}<br>        case QRUpperLeftCorner:<br>                topLeftQR = image.Point{X: offsetCorner, Y: <br>                offsetCorner}<br>        case QRMiddle:<br>                topLeftQR = image.Point{X: width/2 - scaleTo/2, Y:   <br>                height/2 - scaleTo/2}<br>        default:<br>                return nil, fmt.Errorf(&quot;wrong argument for parameter corner&quot;)<br>        }</pre><pre>        //draw QR on background<br>        draw.Draw(rgba, image.Rect(topLeftQR.X, topLeftQR.Y, <br>             topLeftQR.X+scaleTo, topLeftQR.Y+scaleTo), qr_scaled, <br>             image.Point{X: 0, Y: 0}, draw.Src)<br>        <br>        return rgba, nil<br>}</pre><p>Okay. That’s all for today. Happy Golang coding! Do follow me if you like the article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cf4aad2f85b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang: Creating Images and Drawing — Simply Explained (Part 1)]]></title>
            <link>https://mipsmonsta.medium.com/golang-creating-images-and-drawing-simply-explained-part-1-31097e92d6e2?source=rss-2e71d1e75abd------2</link>
            <guid isPermaLink="false">https://medium.com/p/31097e92d6e2</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[image]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[compositing]]></category>
            <dc:creator><![CDATA[Mipsmonsta]]></dc:creator>
            <pubDate>Thu, 24 Mar 2022 07:01:28 GMT</pubDate>
            <atom:updated>2022-03-24T07:01:28.039Z</atom:updated>
            <content:encoded><![CDATA[<h3>Golang: Creating Images and Drawing — Simply Explained (Part 1)</h3><p>Let your right brain work with your left to unleash your artistic talent</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_qsRuJHIe5OtGZyD" /><figcaption>Photo by <a href="https://unsplash.com/@eduardo_mekmuffin?utm_source=medium&amp;utm_medium=referral">Eddy Klaus</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Understanding the key elements of the framework</h3><p>Golang is useful and oft mentioned for it’s web development functions. So let’s take sometime to understand the components of the imaging framework to get the lay of the land.</p><h4>Interface image.Image</h4><p>The interface is what you need to know first. Any types in Golang can be said to follow the image.Image interface if it implements:</p><ol><li>Function that returns a color model — this color model is how the data translating to pixels are stored in binary format;</li><li>Function that returns the bounding rectangle — this represents the size of the rectangle that forms the bounding geometry of the image; and</li><li>Function that returns the color.Color at the input x and y integer coordinates.</li></ol><pre>type Image interface {<br>	<br>	ColorModel() <a href="https://pkg.go.dev/image/color">color</a>.<a href="https://pkg.go.dev/image/color#Model">Model</a><br>	<br>	Bounds() <a href="https://pkg.go.dev/image#Rectangle">Rectangle</a><br>	<br>	At(x, y <a href="https://pkg.go.dev/builtin#int">int</a>) <a href="https://pkg.go.dev/image/color">color</a>.<a href="https://pkg.go.dev/image/color#Color">Color</a><br>}</pre><h4><strong>Interface draw.Image</strong></h4><p>The image.Image interface with the At function is like a read only image. It can only tell you the color at each coordinate of the pixel. What if we want to create an image. That’s where the interface draw.Image comes in under the <a href="https://pkg.go.dev/image/draw#Image">image/draw package</a>.</p><pre>type Image interface {<br>	<a href="https://pkg.go.dev/image">image</a>.<a href="https://pkg.go.dev/image#Image">Image</a><br>	Set(x, y <a href="https://pkg.go.dev/builtin#int">int</a>, c <a href="https://pkg.go.dev/image/color">color</a>.<a href="https://pkg.go.dev/image/color#Color">Color</a>)<br>}</pre><p>As the official documents say, the draw.Image interface is a image.Image interface with a Set function to set the color for a particular x and y pixel coordinate. Obviously this is required for your to draw on the image.</p><p>The above are two interfaces, but to those familar with Golang, you would know that we need structures to be implementing these interfaces. So let’s look at the supporting structs.</p><h4>Actual Structs</h4><p>The structs that support the two aforementioned interfaces are listed below:</p><ul><li>Gray —8-bit greyscale</li><li>Gray16– 16–bit greyscale</li><li>CMYK</li><li>Paletted</li><li>RGBA — most commonly know color model of red, green, blue and alpha channels, each 8 bits</li><li>NRGBA — non-alpha-premultiplied 32-bit color (each channel is 8-bit)</li><li>NRGBA64 — non-alpha-premultiplied 64-bit color (each channel is 16-bit)</li><li>NYCbCrA — non-alpha-premultiplied Y’CbCr-with-alpha (8-bit for each of Luma and the two chroma components; JPEG, VP8, MPEG codecs etc use this color model)</li><li>Alpha — a single channel (alpha) 8-bit</li><li>Alpha16 — a single channel (alpha) 16-bit</li></ul><blockquote>It’s important to say that if you read the documentation, it’s the pointers of the structs that conform to the two interfaces.</blockquote><h4>Now that I know about the structs, but how do you get the structs then?</h4><p>We have to look at packages such as image/jpeg and image/png etc. These are packages that allow you to open say a jpeg image file and <a href="https://pkg.go.dev/image/jpeg#Decode"><strong>Decode </strong></a>the file into image.Image instances. Example code below:</p><pre>import _ &quot;image/jpeg&quot; //will call the init() function of the package<br>                      //thus enabling working with jpeg file</pre><pre>func OpenImage(path string) (image.Image, error) {<br>        f, err := os.Open(path)<br>        if err != nil {<br>                fmt.Println(err)<br>                return nil, err<br>        }<br>        defer f.Close()</pre><pre>img, format, err := image.Decode(f)<br>        if err != nil {<br>                e := fmt.Errorf(&quot;error in decoding: %w&quot;, err)<br>                return nil, e<br>        }</pre><pre>if format != &quot;jpeg&quot; &amp;&amp; format != &quot;png&quot; {<br>                e := fmt.Errorf(&quot;error in image format - not jpeg&quot;)<br>                return nil, e<br>        }</pre><pre>return img, nil<br>}</pre><p>If you want to manipulate the image, yes, then you need to get the color.Color at each pixel. Here is sample code to extract the color.Color that represents each pixels and storing them into a color tensor [][]color.Color.</p><pre>func GetImageTensor(img image.Image) (pixels [][]color.Color) {<br>        size := img.Bounds().Size()<br>        for i := 0; i &lt; size.X; i++ {<br>                var y []color.Color<br>                for j := 0; j &lt; size.Y; j++ {<br>                        y = append(y, img.At(i, j))<br>                }<br>                pixels = append(pixels, y) // 2 by 2 slices where   <br>                                    //each contains a color.color<br>        }<br>        return<br>}</pre><p>Then with the color tensor, we can manipulate individual color at each pixel in the RGBA format and store then as a image.RGBA struct whose pointer form implements the image.Image interface.</p><pre>func ConvertGreyScale(pixels *[][]color.Color) image.Image {</pre><pre>        p := *pixels<br>        wg := sync.WaitGroup{}<br>        rect := image.Rect(0, 0, len(p), len(p[0]))<br>        newImage := image.NewRGBA(rect)<br>        for x := 0; x &lt; len(p); x++ {<br>                for y := 0; y &lt; len(p[0]); y++ {<br>                        wg.Add(1)<br>                        go func(x, y int) {<br>                                pix := p[x][y]<br>                                originalColor, ok := color.RGBAModel.Convert(pix).(color.RGBA)<br>                                if !ok {<br>                                        log.Fatalf(&quot;color.color conversion went wrong&quot;)<br>                                }<br>                                grey := uint8(float64(originalColor.R)*0.21 + float64(originalColor.G)*0.72 + float64(originalColor.B)*0.07)<br>                                col := color.RGBA{<br>                                        grey,<br>                                        grey,<br>                                        grey,<br>                                        originalColor.A,<br>                                }<br>                                newImage.Set(x, y, col)</pre><pre>        wg.Done()<br>                        }(x, y)<br>                }<br>        }<br>        return newImage<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*SEqCuD_waUPHMh4JrN_lJw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*Bq7XeIC6W4ps5bzTkKttHA.jpeg" /><figcaption>Original image (courtesy of CC) and the grayscaled image</figcaption></figure><p>Note that image/color package in the standard library includes function that is able to convert the colors from one format to another e.g.<a href="https://pkg.go.dev/image/color?utm_source=gopls#CMYKToRGB"> func CMYKToRGB(c, m, y, k uint8) (uint8, uint8, uint8)</a>.</p><p>Now you would know enough to read a jpeg file and how to manipulate the color of each pixels. Let’s pause here. In part 2, I will talk about basic drawing, which is where draw.Image comes into play.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*qk-1jkJVbxOIZ7nZ5348bA.png" /><figcaption>Example of the draw library where you can place your own QR code through compositing</figcaption></figure><p>Happy Golang coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31097e92d6e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang: gRPC Steps Explained]]></title>
            <link>https://mipsmonsta.medium.com/golang-grpc-steps-explained-31afa08559?source=rss-2e71d1e75abd------2</link>
            <guid isPermaLink="false">https://medium.com/p/31afa08559</guid>
            <category><![CDATA[golang-grpc]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Mipsmonsta]]></dc:creator>
            <pubDate>Mon, 07 Mar 2022 11:02:22 GMT</pubDate>
            <atom:updated>2022-03-07T11:02:22.999Z</atom:updated>
            <content:encoded><![CDATA[<h4>Step by step guide</h4><h3>High level overview of gRPC</h3><ol><li>Define service using protocol buffer language</li><li>Generate native code magic glue to tie readable protobuf definition and code (server &amp; client application code you will write)</li><li>Write Server side code</li><li>Write Client side code</li></ol><p>First, what is gRPC? We know RPC stands for Remote Procedure Call. I have also done an article here to cover how to use the net/rpc standard library package to build one. gRPC is an open-source <em>universal</em> RPC framework built by Google. Why universal? The data exchange format via the network between the server and client is based on protocol buffer format. This format is written only to be machine readable. BUT a human-readable protocol buffer language is used to defined this format. The universal part comes from the fact that codes manipulating this format can be generated in various languages, not just in Golang, but in java, python etc. This has the added advantage that your client and server go don’t have to use the same language codebase.</p><p>Let try to create a gRPC for a chinese food delivery service, using the protocol buffer language. At the time of writing it is in version 3. Note also that you should not use camelCase but could use “_” for descriptors.</p><pre>syntax = &quot;proto3&quot;;<br>option go_package = &quot;domain.com/me/takeout&quot;</pre><pre>service Takeouts {<br>   rpc GetDish(DishRequest) returns (DishReply) {}</pre><pre>}</pre><pre>message DishRequest {<br>   string dish_name = 1;<br>   int32 dish_id = 2;<br>   int32 dish_special_request = 4;</pre><pre>}</pre><pre>message Dish {<br>   string dish_name = 1;<br>   int32 dish_id = 2;<br>   int32 last_cooked = 3;<br>}</pre><pre>message DishReply {<br>   Dish dish = 1;<br>}</pre><p>Let’s create a folder named service and keep the takeout.proto there.</p><p>Second, let’s use the protoc compiler to whip out up the magic clue mentioned in step 2. In the service folder, execute the below command:</p><pre>protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative takeout.proto</pre><p>Third, time to write our server code in the server folder. There are two sub-steps: (1) Create the service:</p><pre>type takeoutService struct {<br>   takeouts.UnimplementedTakeoutsServer<br>}</pre><p>The takeoutService type is the service handler for the Takeouts service. We define the GetDish() method of the server struct:</p><pre>func (s *takeoutService) GetDish(ctx context.Context), in *takeout.DishRequest) (*takeout.DishReply, error) {</pre><pre>   //... some code to get the dish based on DishRequest</pre><pre>   d := takeout.Dish{</pre><pre>     Dish_name: &quot;General Tso&#39;s Chicken&quot;,</pre><pre>     ... <br>   }</pre><pre>   return &amp;takeout.DishReply{Dish: &amp;d}, nil<br>}</pre><p>And sub-step (2), which create the server and register the service (“or handler”). The takeout.Register&lt;GetDish&gt;ServiceServer, where the &lt;GetDish&gt; is the name of your rpc function.</p><pre>lis, err := net.Listen(&quot;tcp&quot;, &quot;:50051&quot;)<br>s := grpc.NewServer() //create gRPC Server</pre><pre>takeout.RegisterGetDishServiceServer(s, &amp;takeoutService{})//register handler</pre><pre>log.Fatal(s.Serve(lis))<br> // crash the program is cannot create the server</pre><p>Fourth and final step — writing the client software. The final step has three substeps: (1) Establishing a connection to the server:</p><pre>func setupGrpcConnection(addr string) (*grpc.ClientConn, err) {<br>   return grpc.DialContext(context.background(), <br>          addr, <br>          grpc.WithTransportCredentials(insecure.NewCredentials()),<br>          grpc.WithBlock(), //block the function until conn                           <br>//established<br>   )</pre><pre>} // a connection will be returned</pre><p>You will have to use addr in the format such as “127.0.0.1:50051”.</p><p>(2) We need a client next and we can make use of the generated magic code glue again…</p><pre>func getDishServiceClient(conn *grpc.ClientConn) takeout.GetDishServiceClient {<br>   return takeout.NewGetDishServiceClient(conn)//this is from            <br>                                               //generated code<br>                                               //connection from (1)</pre><pre>}</pre><p>The last sub-step is to call the GetDish method in the generated takeout package (3) below. Again, <em>takeout.GetDishServiceClient </em>is generated code<em>.</em></p><pre>func getDish(client takeout.GetDishServiceClient, <br>             u *takeout.DishRequest,) (*takeout.DishReply, error){</pre><pre>   return client.GetDish(context.Background(), u)<br>}</pre><p>I must say that one of the downside of using Protocol buffer is that you must remember these steps. It’s a side effect of using the magic generated glue. It does get addictive. In the meantime, happy golang.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z-YFAVQx6BpMmglF" /><figcaption>Photo by <a href="https://unsplash.com/@almosbech?utm_source=medium&amp;utm_medium=referral">Almos Bechtold</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31afa08559" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[E-Paper (Golang Port) — Epd for the Raspberry Pi]]></title>
            <link>https://mipsmonsta.medium.com/e-paper-golang-port-epd-for-the-raspberry-pi-6f7d9c09f4f3?source=rss-2e71d1e75abd------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f7d9c09f4f3</guid>
            <category><![CDATA[e-paper]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[raspberry-pi-hat]]></category>
            <dc:creator><![CDATA[Mipsmonsta]]></dc:creator>
            <pubDate>Tue, 01 Mar 2022 10:49:32 GMT</pubDate>
            <atom:updated>2022-03-23T03:01:55.946Z</atom:updated>
            <content:encoded><![CDATA[<h3>E-Paper (Golang Port) — Epd for the Raspberry Pi</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FA2wDViGzJXud_Rz0cBr0Q.jpeg" /></figure><h3>Introduction</h3><p>I have the e-paper hat for the Raspberry Pi, specifically the <a href="https://www.waveshare.com/wiki/2.7inch_e-Paper_HAT">2.7 inch display</a>.</p><p>As I was tickering with Golang as a system programming, I wondered whether I could control the hat using the Go language. After much research, I found the <a href="https://periph.io/">periph.io</a> project, which supports communications via the SPI interface used by the hat. Hence, I started writing the port, converting from the python library to a small <a href="https://github.com/mipsmonsta/epd">Go library</a>.</p><h3>Communication via SPI</h3><p>The connections to the hat for the 2.7 inch are as follows, with SPI related lines and GPIO pin in bold and <em>italics</em>:</p><pre>VCC 3.3V<br>GND <br>DIN SPI MOSI Pin:GPIO10 <br>CLK SPI SCK Pin: GPIO11 <br>CS SPI chip select (Low active) Pin: GPIO8 <br>DC Data/Command control pin (High for data, and low for command) Pin: GPIO25 <br>RST External reset pin (Low for reset) Pin: GPIO17 <br>BUSY Busy state output pin (Low for busy) Pin: GPIO24</pre><p>Notice that MISO is not set since no data is pulled from the display to the Raspberry Pi.</p><p>For MOSI communication, a byte is sent to the hat at time, whether as command or data.</p><h3>API</h3><p>epdconfig.go — data struct to keep port, connection and pins’ information.</p><p>The Digital_writeRST, Digital_writeDC, Digital_writeCS and Digital_readBS are exported outside the go module and represents the low-level way to interact with the pins. These should be called by encapsulating functions in the epd library. You should not have to use these functions yourself. Setup of the epdconfig should also be called by the epd library Setup function.</p><p>epd.go — data struct where you will initiate and use in your program. imageutil/imageutil.go — where you can use the functions written to manipulate images.</p><p><em>Sample usage</em></p><blockquote><em>e := epd.Epd{ Config: epd_config.EpdConfig{}, } e.Setup() e.Clear()</em></blockquote><blockquote><em>img, err := imageutil.OpenImage(“../imageutil/test/test_portrait.jpg”) if err != nil { fmt.Println(err) os.Exit(1) }</em></blockquote><blockquote><em>e.Display(&amp;img)</em></blockquote><blockquote><em>time.Sleep(5*time.Second)</em></blockquote><blockquote><em>img, err = imageutil.OpenImage(“../imageutil/test/test_shiba.jpg”) if err != nil { fmt.Println(err) os.Exit(1) }</em></blockquote><blockquote><em>e.Display(&amp;img)</em></blockquote><blockquote><em>e.Sleep()</em></blockquote><h3>Road map of features:</h3><p>Implemented:</p><ul><li>Display image in monochrome (1 bit black and white)</li><li><a href="https://en.wikipedia.org/wiki/Floyd%E2%80%93Steinberg_dithering">Flody-Steinberg Dithering</a></li><li>Auto detect orientation (portriat or landscape) and fit onto the screen size</li><li>4 Shades Grayscale display of image (newly implemented on 2 March 2022)</li><li>Added text display function; auto-wrapped for UTF-8 strings (New in Mar 2022)</li></ul><p>Future features:</p><ul><li>? Customisable sigmoid curve for tuning 4 Shades Grayscale</li></ul><p>Happy Golang, and have fun with tinkering with the Raspberry Pi.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f7d9c09f4f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Salient Points for Protocol Buffers]]></title>
            <link>https://mipsmonsta.medium.com/salient-points-for-protocol-buffers-f2a759ceb48?source=rss-2e71d1e75abd------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2a759ceb48</guid>
            <category><![CDATA[protocol-buffers]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Mipsmonsta]]></dc:creator>
            <pubDate>Thu, 17 Feb 2022 10:30:51 GMT</pubDate>
            <atom:updated>2022-02-18T01:04:17.435Z</atom:updated>
            <content:encoded><![CDATA[<h4>Simply Explained (for Golang)</h4><h4>How to start .proto file?</h4><pre>syntax = &quot;proto3&quot;;</pre><p>Without the line above, the complier for protocol buffer will assume the syntax is based on proto2.</p><h4>Specify Field Types</h4><p>All fields are scalar type: string, float, int32, int64, uint32, uint64, sint32, sint64, fixed32 (always 4 bytes), fixed64 , bool, string, bytes etc.</p><pre>message Foo { //this is a message type<br>   string query = 1;<br>   int64 large_number = 2;<br>   bool is_bar = 3;<br>   bool is_foo = 4;</pre><pre>}</pre><p>Notice the use of underscore as convention for the field names. You can also have multiple message types in the same .proto file. Notice message name starts in big <strong>cap</strong>.</p><p><em>Default values</em></p><pre>strings ----&gt; empty string<br>bytes ------&gt; empty bytes<br>bool -------&gt; false<br>numeric types --&gt; zero<br>enums ------&gt; default value is the first defined enum value, which     <br>              must be 0</pre><p><em>Composite Types — Enum</em></p><pre>message SearchRequest {<br>  ...<br>  enum Corpus {<br>     UNIVERSAL = 0;<br>     WEB = 1;<br>  }<br>}</pre><p>Every enum definition must contain a constant that maps to zero as its first element. This is so that the default value aforementioned can work.</p><p>If the same enum constants are used in other enum definition, you need the line: option allow_alias = true;</p><pre>message SearchResponse {<br>   ... <br>   enum EnumAllowinAlias {<br>      option allow_alias = true;<br>      UNIVERSAL = 0; //already used in previous enum Corpus</pre><pre>   }<br>}</pre><h4>Including Maps in definitions</h4><pre>message SearchWithMapParams {<br>   map&lt;string, Project&gt; projects = 5; // where Project is a message<br>}</pre><h4>Handling removal of fields</h4><p>When you remove a field, you need to prevent the field numbers from being reused. What you need to do is to create reserved fields to “block” these field numbers. If not done, when other reuse the field numbers, severe compatibility can result.</p><pre>message Foo {<br>   string query = 1;<br>   reserved 2, 3 to 4;<br>   reserved &quot;is_bar&quot;, &quot;is_foo&quot;, &quot;large_number&quot;;<br>}</pre><h4>Nesting other message types</h4><p>Other messages can be included as field types i.e. nested. For example:</p><pre>message BigBar {<br>   repeated NestedBar inner_bar = 1;<br>}</pre><pre>message NestedBar {<br>   int32 weight = 1;<br>   string brand = 2;<br>   repeated string packaging = 3;<br>}</pre><p>Here, the repeated keywork ensures you can use other messages as field types inside your message.</p><h4>More nesting…</h4><p>You can fall in love with nesting deeply :P</p><pre>message BigBar {<br>   message NestedBar {<br>      int32 weight = 1;<br>      string brand = 2;<br>      repeated string packaging = 3;<br>   } <br>   repeated NestedBar a_bar = 1; //repeated key again</pre><pre>}</pre><p>Furthermore…</p><pre>message Outer {<br>   message Middle {<br>     message Inner {<br>        int64 something = 1;<br>        string another = 2;</pre><pre>     }<br>  }<br>}</pre><h4>Importing .proto files</h4><p>To help in nesting, you can import definitions from other .proto files</p><pre>import &quot;otherproject/some_protos.proto&quot;;</pre><p>The protocol compiler searches for imported files in a set of folders specified on the protocol CLI using the flag,</p><pre>-I or --proto_path</pre><h4>Placeholder .proto file</h4><p>Imagine if you need to move your .proto file to a new file location. All your other .proto files importing the .proto file will need to be updated with a new import line. That will be a lot of work. Is there a better way?</p><p>To save the day, you can use the “import public” syntax such as —</p><p>new proto file:</p><pre>//foo.proto<br>//All definitions of messages are moved here</pre><p>old proto file to be modified:</p><pre>//bar.proto<br>import public &quot;foo.proto&quot; //this line is added</pre><p>other proto file using bar.proto:</p><pre>//client.proto<br>import &quot;old.proto&quot;; //continue to import the old proto file</pre><h4>Oneof fields</h4><p>If you have mutiple fields in a message and at most one field will be set at the same time, you can enforce filling one field by using the oneof feature.</p><pre>message SlimMessage {</pre><pre>  oneof a_name {<br>    string this = 1;<br>    bool or_that = 4;</pre><pre>  }<br>}</pre><h4>Defining Services in .proto file</h4><pre>service AService {<br>   rpc Provide(Request) returns (Response);</pre><pre>}</pre><h4><strong>Compiling to .pb.go</strong></h4><p>In go, the protobuf go compiler generates .pb.go file with a type for each message type in your file.</p><h4>Generating your classes in go</h4><pre>protoc --proto_path=IMPORT_PATH --go_out=DST_DIR path/to/file.proto</pre><p><strong>GRPC support in go</strong></p><p>If you are using grpc, you also need to generate the grpc go files with an additioanl flag of “ go-grpc_out=.”</p><pre>protoc -I=. --go_out=./chunky --go-grpc_out=./chunky  ./chunky/chunk.proto</pre><p>Above example generates the file into the relative folder of ./chunky</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2a759ceb48" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang: Understanding how Go HTML template system prevents Crossed Site Attack (XSS)]]></title>
            <link>https://systemweakness.com/golang-understanding-how-go-html-template-system-prevents-crossed-site-attack-xss-ee862478ed29?source=rss-2e71d1e75abd------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee862478ed29</guid>
            <category><![CDATA[xss-attack]]></category>
            <category><![CDATA[html-templates]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Mipsmonsta]]></dc:creator>
            <pubDate>Thu, 10 Feb 2022 10:15:12 GMT</pubDate>
            <atom:updated>2022-02-15T06:31:43.268Z</atom:updated>
            <content:encoded><![CDATA[<p>We often hear about XSS attacks and the importance of escaping user-submitted content. These attacks are deemed basic and developers may not fully appreciate how easy it is to trigger the attacks. The aim of this article is to show you code on how to go about a XSS attack using Golang, and then to cover how the <em>html/template package</em>, if used correctly, with the right security model in mind, will prevent such attacks.</p><h4>Simulating a XSS attack</h4><p><strong>Step 1</strong>: Create a html page with user input form. We named this index.html.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;</pre><pre>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;Document&lt;/title&gt;<br>&lt;/head&gt;</pre><pre>&lt;body&gt;</pre><pre>    &lt;form action=&quot;/processed&quot; method=&quot;post&quot;&gt;<br>        &lt;label for=&quot;textField&quot;&gt;Enter some text&lt;/label&gt;<br>        &lt;input type=&quot;text&quot; name=&quot;textField&quot; id=&quot;textField&quot;&gt;&lt;br&gt;<br>        &lt;input type=&quot;submit&quot; value=&quot;Submit&quot;&gt;</pre><pre>    &lt;/form&gt;</pre><pre>&lt;/body&gt;</pre><pre>&lt;/html&gt;</pre><p><strong>Step 2</strong>. Create a <em>processed.html </em>file that will return and show the form content extracted from the user. The markup in the file uses html/templates actions.</p><pre>&lt;!DOCTYPE <em>html</em>&gt;<br>&lt;html <em>lang</em>=&quot;en&quot;&gt;<br>&lt;head&gt;<br>&lt;meta <em>charset</em>=&quot;UTF-8&quot;&gt;<br>&lt;meta <em>http-equiv</em>=&quot;X-UA-Compatible&quot; <em>content</em>=&quot;IE=edge&quot;&gt;<br>&lt;meta <em>name</em>=&quot;viewport&quot; <em>content</em>=&quot;width=device-width, initial-scale=1.0&quot;&gt;</pre><pre>&lt;title&gt;Document&lt;/title&gt;<br>&lt;/head&gt;<br>  &lt;body&gt;</pre><pre>    {{if .}}<br>    {{.}}<br>    {{else}}<br>    &lt;p&gt;Nothing to see here&lt;/p&gt;<br>    {{end}}</pre><pre>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>In the <a href="https://pkg.go.dev/html/template#hdr-Contexts">action markup</a>, we are just assessing whether the (.) action is empty or nil, and if so, print the default paragraph “Nothing to see here”. Otherwise, print the action data represented by the (.).</p><p><strong>Step 3.</strong> In our<em> main.go</em> file, we setup a HandleFunc to associate the url pattern of “/trigger” with <em>index.html</em> file and likewise the url pattern of “/processed” with <em>processed.html </em>file.</p><pre>package main</pre><pre>import (<br>        &quot;html/template&quot;<br>        &quot;net/http&quot;<br>)</pre><pre>var t *template.Template = template.Must(template.ParseFiles(&quot;./templates/index.html&quot;))<br>var p *template.Template = template.Must(template.ParseFiles(&quot;./templates/processed.html&quot;))</pre><pre>func main() {</pre><pre>http.HandleFunc(&quot;/&quot;, index)<br>        http.HandleFunc(&quot;/trigger&quot;, handlerTrigger)<br>        http.HandleFunc(&quot;/processed&quot;, handlerProcessedUnsafe)</pre><pre>http.ListenAndServe(&quot;:8080&quot;, nil)<br>}</pre><pre>func handlerTrigger(w http.ResponseWriter, r *http.Request) {</pre><pre>t.Execute(w, nil)<br>}</pre><pre>func handlerProcessedUnsafe(w http.ResponseWriter, r *http.Request) {<br>        err := r.ParseForm()<br>        if err != nil {<br>                http.Error(w, &quot;Something is wrong&quot;, http.StatusInternalServerError)<br>                return<br>        }<br>        content := r.FormValue(&quot;textField&quot;)<br>        p.Execute(w, template.HTML(content)) <br>}</pre><pre>func index(w http.ResponseWriter, r *http.Request) {<br>        // always redirect<br>        if r.URL.Path != &quot;/&quot; {<br>                http.Error(w, &quot;Nothing to see here&quot;, http.StatusNotFound)<br>                return<br>        }</pre><pre>        http.Redirect(w, r, &quot;/trigger&quot;, http.StatusSeeOther)<br>}</pre><p>When we run the main.go file and enter through URL “http://localhost:8080”, we will see the form served by our little go program.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*kSoqQ8BIIULRSAv4ds9MqQ.png" /></figure><p>Let’s enter in some text (in picture above it’s “test”), and click “submit”.</p><p>The page will redirect to “localhost:8080/processed” showing unexpectedly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*27eQEPZth3npwXQyVFTiHQ.png" /></figure><p><strong>Step 4</strong>: Let’s pressed back and this time enter “&lt;script&gt;alert(“You have been hacked!”&lt;/script&gt; in the form box.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*eND4loTZJCx7ymxDNFanKw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nGxKW0TCa40HDz_4h6Tx7g.png" /></figure><p>Voila.</p><h4>Understanding how Safe is the Go HTML template system</h4><p>If you have read thus far, I am happy to tell you Go HTML template system will protect from the XSS attack. I actually have to add an extra line of code to allow the XSS attack to go through. And this line of code in the main.go program is:</p><pre>p.Execute(w, template.HTML(content))</pre><p>or more specifically:</p><pre>template.HTML(content)</pre><p>The template.HTML function when used on a user provided input (in this case: content variable), will preserved the input as it is. There will not be “treatment” to make “safe” the input.</p><p>If we didn’t use template.HTML function, i.e.</p><pre>p.Execute(w, content)</pre><p>The result is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*_qmAP0nIDEFHQI7Q-x3yIA.png" /></figure><p>or if we look at the html source</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*ssXjUmryqdV1hS818dWrOg.png" /></figure><p>The gibberish distortion of the script text is what is known as <strong>html escaping</strong>. Go HTML template system is actually context-aware and works on the sound security model of:</p><blockquote>HTML templates treat data values as plain text which should be encoded so they can be safely embedded in an HTML document. The escaping is contextual, so actions can appear within JavaScript, CSS, and URI contexts.</blockquote><blockquote>The security model used by this package assumes that template authors are trusted, while Execute’s data parameter is not…</blockquote><h4>So next time when you use the Go html template system, you know how it is handling “unsafe” user data.</h4><p>Happy Golang coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee862478ed29" width="1" height="1" alt=""><hr><p><a href="https://systemweakness.com/golang-understanding-how-go-html-template-system-prevents-crossed-site-attack-xss-ee862478ed29">Golang: Understanding how Go HTML template system prevents Crossed Site Attack (XSS)</a> was originally published in <a href="https://systemweakness.com/">System Weakness</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang: Using buffered channel like a mutex]]></title>
            <link>https://towardsdev.com/golang-using-buffered-channel-like-a-mutex-9c7c80ec5c27?source=rss-2e71d1e75abd------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c7c80ec5c27</guid>
            <category><![CDATA[buffered-channel]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[channel]]></category>
            <category><![CDATA[synchronization]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Mipsmonsta]]></dc:creator>
            <pubDate>Thu, 03 Feb 2022 03:20:15 GMT</pubDate>
            <atom:updated>2022-02-11T07:31:38.279Z</atom:updated>
            <content:encoded><![CDATA[<p>In the sync library that’s part of the official Go package, the following statement is made:</p><blockquote>Package sync provides basic synchronization primitives such as mutual exclusion locks. Other than the Once and WaitGroup types, most are intended for use by low-level library routines. <strong>Higher-level synchronization is better done via channels </strong>and communication.</blockquote><p>In most of the examples that you can find covering the topic of allowing concurrent accesses, there are plenty on using mutex to solve the problem. However, there is hardly any examples to show how channels can be used to provide synchronization. Hence, the<strong> impetus</strong> for writing this article.</p><h4>Property of a Mutex lock</h4><p>In order for a mutex lock to work, it needs to be “locked” when you are accessing the shared variable and “unlocked” when done. The same lock should also be used instead of multiple locks, lest race conditions rear their heads.</p><h4>Property of an unbuffered channel and unfitness</h4><p>A sender channel will block when filled if there is no receiver. The same will happen if there is a receiver channel, but no sender. <a href="https://mipsmonsta.medium.com/understanding-blocking-nature-of-golang-channel-2c1c95bf5d82">See this past article that I touched on this block behavior.</a> The exact blocking behavior makes an unbuffered channel unfit to be used like a lock. So let’s turn to a buffered channel to examine it.</p><h4>Property of buffered channel with size 1 and fitness</h4><p>A buffered channel with size 1 “slot” has the property that if the single slot is filled, the channel will block and cannot accommodate more. But once the slot is “vacated” using a receiver, the channel will unblock.</p><p>Clearly, the <strong>blocking behavior of a buffered channel is desirable and mirrors that of the mutex lock</strong>:</p><p><em>blocked when filled &lt;-&gt; locked</em></p><p><em>unblocked when unfilled &lt;-&gt; unlocked</em></p><p>Let’s make use of the property in the example code to demonstrate the fitness.</p><h4>Demonstration code using Buffered Channel as a “lock”</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JR0q0BMvgJBeLc8G" /><figcaption>Photo by <a href="https://unsplash.com/@rgaleria?utm_source=medium&amp;utm_medium=referral">Ricardo Gomez Angel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s imagine we have a list of names that we want to be written into a file, but we need the same name to be encoded in consecutive sequence say for 100,000 times before encoding other names i.e. no interleaving of names is allowed.</p><pre>package main</pre><pre>import (<br>        &quot;errors&quot;<br>        &quot;fmt&quot;<br>        &quot;os&quot;<br>        &quot;sync&quot;<br>)</pre><pre>func main() {<br>        file, err := os.Create(&quot;record.txt&quot;)</pre><pre><br>        defer func() {<br>                if err := recover(); err != nil {<br>                        fmt.Printf(&quot;Error encounter: %w&quot;, err)<br>                }<br>                file.Close()<br>        }()</pre><pre>        if err != nil {<br>                panic(errors.New(&quot;Cannot create/open file&quot;))<br>        }</pre><pre>        ss := []string{ //string slice literals<br>                &quot;James&quot;,<br>                &quot;Avery&quot;,<br>                &quot;Peter&quot;,<br>                &quot;John&quot;,<br>                &quot;Beau&quot;,<br>        }</pre><pre>        chanLock := make(chan int, 1) //1<br>        var wg sync.WaitGroup</pre><pre>        for _, str := range ss { //2<br>                wg.Add(1) //amended thanks to response from Wang        <br>                          //Sheng</pre><pre>                go func(aString string) {<br>                        <br>                        chanLock &lt;- 1 //3<br>                        for i := 0; i &lt; 1000; i++ {<br>                                file.WriteString(aString + &quot;\n&quot;)<br>                        }<br>                        &lt;-chanLock //4<br>                        wg.Done() //5<br>                }(str) //pass by value<br>        }</pre><pre>        wg.Wait()</pre><pre>}</pre><p>In the code above, in 1, a buffered channel of size 1 is created. We then create as many go routines as there are names in the string slice <em>ss </em>in //2. To synchonise the writing of the names to the single record.txt file, we use the chanLock by “filling” it in //3 and then “vacating” it in //4. This allows other go routines to work on the same record file, but one at a time.</p><p>Notice that we still need the waitgroup to ensure the main program is not done before the go routines have completed their tasks.</p><h4>Benchmarking — Channel vs Mutex</h4><p>Let’s do some benchmarking. We refactor the code into two function — DoFileWriteWithChan and DoFileWriteWithMutex.</p><pre>package mutexChan</pre><pre>import (<br>        &quot;os&quot;<br>        &quot;sync&quot;<br>)</pre><pre>func DoFileWriteWithChan(file *os.File, ss *[]string) {  <br>        var wg sync.WaitGroup</pre><pre>chanLock := make(chan int, 1)</pre><pre>for _, str := range *ss {<br>         wg.Add(1)</pre><pre>         go func(aString string) {<br>                        chanLock &lt;- 1<br>                        for i := 0; i &lt; 1000; i++ {      <br>                                file.WriteString(aString + &quot;\n&quot;)<br>                        }<br>                        &lt;-chanLock<br>                        wg.Done()<br>                }(str) //pass by value<br>        }</pre><pre>        wg.Wait()<br>}</pre><p>And…</p><pre>func DoFileWriteWithMutex(file *os.File, ss *[]string) {</pre><pre>var wg sync.WaitGroup</pre><pre>var mutex sync.RWMutex</pre><pre>for _, str := range *ss {<br>        wg.Add(1)</pre><pre>        go func(aString string) {<br>                        mutex.Lock()<br>                        for i := 0; i &lt; 1000; i++ {      <br>                                file.WriteString(aString + &quot;\n&quot;)<br>                        }<br>                        mutex.Unlock()<br>                        wg.Done()<br>                }(str) //pass by value<br>        }</pre><pre>        wg.Wait()<br>}</pre><p>Once refactored, we can write our test benchmark:</p><pre>package mutexChan</pre><pre>import (<br>        &quot;os&quot;<br>        &quot;testing&quot;<br>)</pre><pre>var ss []string</pre><pre>func init() {<br>        ss = []string{ //string slice literals<br>                &quot;testJames&quot;,<br>                &quot;testAvery&quot;,<br>                &quot;testPeter&quot;,<br>                &quot;testJohn&quot;,<br>                &quot;testBeau&quot;,<br>        }<br>}</pre><pre>func BenchmarkChan(b *testing.B) {</pre><pre>        for n := 0; n &lt; b.N; n++ {<br>                file, _ := os.Create(&quot;record_test.txt&quot;)  <br>                DoFileWriteWithChan(file, &amp;ss)<br>                file.Close()<br>        }</pre><pre>}</pre><pre>func BenchmarkMutex(b *testing.B) {</pre><pre>        for n := 0; n &lt; b.N; n++ {<br>                file, _ := os.Create(&quot;record_test.txt&quot;)  <br>                DoFileWriteWithMutex(file, &amp;ss)<br>                file.Close()<br>        }</pre><pre>}</pre><p>Run the test with</p><pre>$ go test -bench=. -benchtime=3s</pre><p>And the result bench:</p><pre>goos: windows<br>goarch: amd64pkg: mutexChan<br>cpu: AMD Ryzen 5 3500U with Radeon Vega Mobile Gfx       <br>BenchmarkChan-8              135          25548516 ns/op <br>BenchmarkMutex-8             144          25587003 ns/op <br>PASS<br>ok      mutexChan       11.811s</pre><p>Conclusion: All things being equal, if looking at the ns/op rate, using buffered channel or Sync.RWMutex are comparable in performance.</p><p>I hope you find this article useful in your journey to learn Golang. Happy Golang coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c7c80ec5c27" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/golang-using-buffered-channel-like-a-mutex-9c7c80ec5c27">Golang: Using buffered channel like a mutex</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>