<?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 Nguyễn Hoàng Cương Lê on Medium]]></title>
        <description><![CDATA[Stories by Nguyễn Hoàng Cương Lê on Medium]]></description>
        <link>https://medium.com/@hoangcuong9331?source=rss-d8c4c37e4b14------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*8S7qA5QY5OH8kFXD.jpg</url>
            <title>Stories by Nguyễn Hoàng Cương Lê on Medium</title>
            <link>https://medium.com/@hoangcuong9331?source=rss-d8c4c37e4b14------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 11:35:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hoangcuong9331/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[How to use vImage to manipulate images?]]></title>
            <link>https://hoangcuong9331.medium.com/was-how-to-use-vimage-to-manipulate-images-5aacfd4c133f?source=rss-d8c4c37e4b14------2</link>
            <guid isPermaLink="false">https://medium.com/p/5aacfd4c133f</guid>
            <dc:creator><![CDATA[Nguyễn Hoàng Cương Lê]]></dc:creator>
            <pubDate>Thu, 16 Feb 2023 06:46:47 GMT</pubDate>
            <atom:updated>2023-04-09T12:12:36.051Z</atom:updated>
            <content:encoded><![CDATA[<p><em>In this article, you will learn how pixel data can be handled purely by Swift 5. Apple says: “</em><a href="https://developer.apple.com/documentation/accelerate/vimage"><em>vImage is a high-performance image processing framework. It includes functions for …</em></a><em>” so it will improve your code’s performance too.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*luX9C_NBKlsX_zDD" /><figcaption>Photo by <a href="https://unsplash.com/@zalfaimani?utm_source=medium&amp;utm_medium=referral">Zalfa Imani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1. Getting started</h3><ul><li>We need to get CVPixelBuffer first. Basically, you will need to get it from AVPhotoCapture or UIImage. Below are 2 good sources of how to create it. (if you don’t know it yet, I will cover it in the next part)</li><li><a href="https://developer.apple.com/tutorials/sample-apps/capturingphotos-captureandsave">https://developer.apple.com/tutorials/sample-apps/capturingphotos-captureandsave</a></li><li><a href="https://stackoverflow.com/questions/44462087/how-to-convert-a-uiimage-to-a-cvpixelbuffer">https://stackoverflow.com/questions/44462087/how-to-convert-a-uiimage-to-a-cvpixelbuffer</a></li></ul><h3>2. Understand CVPixelBuffer</h3><ul><li>So what is CVPixelBuffer, and how it helps us to process images? Right away!</li><li>Maybe you knew it, but pixel is what digital images are actually made of. It usually contains 4 channel: Red, Green, Blue, and Alpha.</li><li>CVPixelBuffer is the input for vImage. It contains a 2-dimentional array of pixels. Width, height of that plain are equal with the UIImage width height that we get it from.</li><li>CVPixelBuffer can contains different kind of pixel. If we have a RGBA_8888, it means in every pixel, the channel order is R, G, B, A and each have 8 bits allocated.</li></ul><h3>3. Rotate image</h3><p>In this example, I will show you how to rotate an image 90 degrees, by creating an extension of CVPixelBuffer</p><p>First, we create a place to put our code:</p><pre><br>// 1<br>import Foundation<br>import Accelerate<br><br>extension CVPixelBuffer {<br>    func rotate90Degrees() -&gt; CVPixelBuffer {<br>        // put the next section code here<br>    }<br>}<br><br>// 2<br>extension UnsafeMutableRawPointer {<br>    // Converts the vImage buffer to CVPixelBuffer<br>    func toCVPixelBuffer(pixelBuffer: CVPixelBuffer, targetWidth: Int, targetHeight: Int, targetImageRowBytes: Int) -&gt; CVPixelBuffer {<br>        let pixelBufferType = CVPixelBufferGetPixelFormatType(pixelBuffer)<br>        let releaseCallBack: CVPixelBufferReleaseBytesCallback = {mutablePointer, pointer in<br>            if let pointer = pointer {<br>                free(UnsafeMutableRawPointer(mutating: pointer))<br>            }<br>        }<br><br>        var targetPixelBuffer: CVPixelBuffer?<br>        let conversionStatus = CVPixelBufferCreateWithBytes(nil, targetWidth, targetHeight, pixelBufferType, self, targetImageRowBytes, releaseCallBack, nil, nil, &amp;targetPixelBuffer)<br><br>        guard conversionStatus == kCVReturnSuccess else {<br>            free(self)<br>            print(&quot;toCVPixelBuffer Error \(conversionStatus)&quot;)<br>        }<br>        guard let targetPixelBuffer = targetPixelBuffer else {<br>            free(self)<br>            print(&quot;Unknown Error&quot;)<br>        }<br>        return targetPixelBuffer<br>    }<br>}</pre><pre>//3<br>CVPixelBufferLockBaseAddress(self, .readOnly)<br>defer { CVPixelBufferUnlockBaseAddress(self, .readOnly) }<br><br>guard let baseAddress = CVPixelBufferGetBaseAddress(self) {<br>     return<br>}<br>        <br>//4<br>let width = UInt(CVPixelBufferGetWidth(self))<br>let height = UInt(CVPixelBufferGetHeight(self))<br><br>//5<br>let inputImageRowBytes = CVPixelBufferGetBytesPerRow(self)<br>let outputImageRowBytes = inputImageRowBytes / Int(width) * Int(height)<br><br>//6       <br>var inBuffer = vImage_Buffer(<br>     data: baseAddress,<br>     height: height,<br>     width: width,<br>     rowBytes: inputImageRowBytes)<br>        <br> guard let targetImageBytes = malloc(Int(width) * outputImageRowBytes) else {<br>     return<br> }<br> var outBuffer = vImage_Buffer(<br>     data: targetImageBytes,<br>     height: width,<br>     width: height,<br>     rowBytes: outputImageRowBytes)<br>        <br>//7<br>var backgroundColor: Array&lt;UInt8&gt; = [0, 0, 0, 0]<br>let fillBackground: vImage_Flags = UInt32(kvImageBackgroundColorFill)<br><br>//8<br>let rotateError = vImageRotate90_ARGB8888(&amp;inBuffer, &amp;outBuffer, 3, &amp;backgroundColor, fillBackground)<br>        <br>guard rotateError == kvImageNoError else {<br>     free(targetImageBytes)<br>     print(&quot;vImage Error \(rotateError)&quot;)<br>}<br><br>return try targetImageBytes.toCVPixelBuffer(pixelBuffer: self, targetWidth: Int(height), targetHeight: Int(width), targetImageRowBytes: outputImageRowBytes)</pre><h4>let break down these things:</h4><ol><li>We import Accelerate library, it provides us the vImage framework we are working with.</li><li>We convert UnsafeMutableRawPointer into a CVPixelBuffer, by providing it width, height, and rowBytes. Simply said, the process is like we convert an data array into a 2D structure.</li><li>Before and after getting CVPixelBuffer by it address, we must lock-unlock it.</li><li>We obtain width, height of the pixel buffer.</li><li>Row Bytes count is the bytes per pixel multiplied by the width of the image (so if a CVPixelBuffer is RGB_888 and wide 1080 pixel, Row Bytes count of it would be 8 * 3 * 1080). Because we rotate it 90 degrees, Row Bytes count of the output Buffer should be calculated as:<br> — — Bytes per pixel * height of the original image, aka<br> — — Row Bytes count / width * height</li><li>We create vImage_Buffer input from CVPixelBuffer input, and an empty vImage_Buffer output with the size we calculated.</li><li>We create an option to fill any pixel left with white color.</li><li>We actually perform the rotate action here. Finally, we check if there is any error and convert the result to CVPixelBuffer.</li></ol><h3>3. Remove alpha channel</h3><pre>        CVPixelBufferLockBaseAddress(self, .readOnly)<br>        defer { CVPixelBufferUnlockBaseAddress(self, .readOnly) }<br><br>        guard let baseAddress = CVPixelBufferGetBaseAddress(self) else {<br>            print(&quot;vImage Error \(rotateError)&quot;)<br>        }<br>        <br>        let width = UInt(CVPixelBufferGetWidth(self))<br>        let height = UInt(CVPixelBufferGetHeight(self))<br>        let inputImageRowBytes = CVPixelBufferGetBytesPerRow(self)<br>        // 1<br>        let outputImageRowBytes = inputImageRowBytes / 4 * 3<br>        <br>        var inBuffer = vImage_Buffer(<br>            data: baseAddress,<br>            height: height,<br>            width: width,<br>            rowBytes: inputImageRowBytes)<br>        <br>        guard let targetImageBytes = malloc(Int(height) * outputImageRowBytes) else {<br>            return<br>        }<br>        var outBuffer = vImage_Buffer(data: targetImageBytes,<br>                                      height: height,<br>                                      width: width,<br>                                      rowBytes: outputImageRowBytes)<br>        <br>        // 2<br>        let convertError = vImageConvert_RGBA8888toRGB888(&amp;inBuffer, &amp;outBuffer, vImage_Flags(0))<br>        <br>        guard convertError == kvImageNoError else {<br>            free(targetImageBytes)<br>            print(&quot;vImage Error \(convertError)&quot;)<br>        }<br><br>        return try targetImageBytes.toCVPixelBuffer(pixelBuffer: self, targetWidth: Int(width), targetHeight: Int(height), targetImageRowBytes: outputImageRowBytes)<br>    }</pre><h4>So this is what we do different this time:</h4><ol><li>Because the alpha channel will be removed, the result bitmap will have 3 channels instead of 4.</li><li>We remove alpha channel, RGBA -&gt; RGB. We can use it for BGRA -&gt;BGR too.</li></ol><h3>5. Conclusion</h3><p>These are my explanation of vImage and pixel buffer, followed with 2 must know example of how to work with them. I believe you can do it better and solve more complex problems. See you next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5aacfd4c133f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic things you need to know about Swift’s Array]]></title>
            <link>https://hoangcuong9331.medium.com/basic-things-you-need-to-know-about-swifts-array-e3438015029e?source=rss-d8c4c37e4b14------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3438015029e</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Nguyễn Hoàng Cương Lê]]></dc:creator>
            <pubDate>Sun, 06 Jun 2021 13:27:37 GMT</pubDate>
            <atom:updated>2021-06-06T13:31:53.992Z</atom:updated>
            <content:encoded><![CDATA[<p>These tips is your must-know when dealing with arrays in Swift.</p><p>This blog post covers:</p><ul><li>Access Array’s Element safely</li><li>Array with Higher Order Functions</li><li>Array’s Extension</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N76wwbK5J8KT_mkL" /><figcaption>Photo by <a href="https://unsplash.com/@eugenezhyvchik?utm_source=medium&amp;utm_medium=referral">Eugene Zhyvchik</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1. Access array’s element safely</h3><p>Swift has something called Optional, it is a wrapper that helps us interact with objects that could absent. Like this:</p><pre>if foo != nil {<br>    print(foo!)<br>} else {<br>    // if the code go here, that means foo is absent<br>}</pre><p>This helps developers can branch out exceptional cases, make modules more reliable and less error-prone. Swift’s Array has some functions that can return Optional, others will crash if your demanded element isn’t there.</p><pre>+-----------------+-------------------------------+<br>| return Optional |     don&#39;t return Optional     |<br>+-----------------+-------------------------------+<br>| first           |   Random Access (like foo[0]) |<br>| last            |   removeFirst()               |<br>| popFirst()      |   removeLast()                |<br>| popLast()       |                               |<br>+-----------------+-------------------------------+</pre><p>Swift’s Array has many more APIs that help you access, safely or not, array elements. My advice is to read Apple documents carefully and decide what to do in each scenario.</p><h4>When we can unsafely access element?</h4><blockquote>You can decide in each case you can unsafely access element or not within your module. In contrast, if you got an array from a server or another module, you should always access elements in a careful way.</blockquote><h3>2. Array with Higher Order Functions</h3><p>Higher Order Functions (HOF) are functions that return functions or take other functions as arguments. These are some common Array’s HOF:</p><h4>Map</h4><p>Iterate through your array to create another array with the same length.</p><pre><strong>let</strong> names = [&quot;Jean&quot;, &quot;Stiffany&quot;, &quot;Henry&quot;]</pre><pre>names.map({ name <strong>in</strong><br>    <strong>return</strong> name.lowercased()<br>})</pre><pre>// or</pre><pre>names.map { $0.lowercased() }</pre><pre>print(names)<br>// [&quot;jean&quot;, &quot;stiffany&quot;, &quot;henry&quot;]</pre><h4>Filter</h4><p>Iterate through your array to find elements that match some criteria.</p><pre><strong>let</strong> numbers = [1, 4, 6, 2, 5]</pre><pre>numbers.filter { number <strong>in<br>   if</strong> number &lt; 5 {<br>     <strong> return</strong> <strong>true<br>   </strong>} <strong>else</strong> {<br><strong>      return</strong> <strong>false<br></strong>   }<br>}</pre><pre>// or</pre><pre>numbers.filter({ $0 &lt; 5 })</pre><pre>print(numbers)<br>// [1, 4, 2]</pre><h4>Reduce</h4><p>Iterate through your array to calculate an overall result.</p><pre><strong>let</strong> numbers = [1, 4, 6, 2, 5]</pre><pre><strong>let</strong> initialResult = 0<br>numbers.reduce(initialResult) { result, number <strong>in<br>    </strong>result + number<br>}</pre><pre>// or </pre><pre>numbers.reduce(0) { $1 + $0 }</pre><pre>print(numbers)<br>// 18</pre><h4>RemoveAll(where:)</h4><p>Iterate through your array and delete elements that match some criteria.</p><pre><strong>var</strong> numbers = [1, 4, 6, 2, 5]</pre><pre>numbers.removeAll { number <strong>in<br>   if</strong> number &gt;= 5 {<br>      <strong>return</strong> <strong>true<br>   </strong>} <strong>else</strong> {<br>      <strong>return</strong> <strong>false<br>   </strong>}<br>}</pre><pre>// or</pre><pre>numbers.removeAll(where: { $0 &gt;= 5 })</pre><pre>print(numbers)<br>// [1, 4, 2]</pre><p>There are a lot more HOF functions built-in for Array. The point is Array will take your function and execute it for every element, no exception. In contrast, for loop gives you the ability to skip any element you want.</p><h3>3. Array’s extension</h3><p>With Extension, you can add more functionality to Array, like below, I created a way to Random Access Array’s Element safely:</p><pre><strong>extension</strong> Array {     <br>   <strong>func</strong> element(at index: Int) -&gt; Element? {         <br>      <strong>if</strong> index &gt;= 0, index &lt; count {             <br>         <strong>return</strong> self[index]<br>      }       <br>      <strong>return</strong> nil   <br>   }<br>}</pre><p>Especially, you can extend Array where its Element is some specified kind. In the below code, I intend to ignore any RowData that has no content:</p><pre><strong>class</strong> RowData {<br>   <strong>var</strong> title: String = &quot;&quot;<br>   <strong>var</strong> content: String = &quot;&quot;<br>   <strong>var</strong> icon: String = &quot;&quot;<br>}</pre><pre><strong>extension</strong> Array <strong>where</strong> Element == RowData {<br>   <strong>mutating</strong> <strong>func</strong> appendIfNeeded(<strong>_</strong> newElement: RowData) {<br>      <strong>if </strong>!newElement.content.isEmpty {<br>         <strong>self</strong>.append(newElement)<br>      }<br>   }</pre><pre><strong>   mutating</strong> <strong>func</strong> appendIfNeeded(contentsOf: [RowData]) {<br>      contentsOf.forEach { rowData <strong>in<br>         self</strong>.appendIfNeeded(rowData)<br>      }<br>   }<br>}</pre><blockquote>Credits:</blockquote><blockquote><a href="https://www.swiftbysundell.com/articles/the-power-of-extensions-in-swift/">https://www.swiftbysundell.com/articles/the-power-of-extensions-in-swift/</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3438015029e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to effectively maintain other’s code without documentation]]></title>
            <link>https://hoangcuong9331.medium.com/how-to-effectively-maintain-others-code-without-documentation-626d7985d015?source=rss-d8c4c37e4b14------2</link>
            <guid isPermaLink="false">https://medium.com/p/626d7985d015</guid>
            <category><![CDATA[maintaining]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[experience]]></category>
            <category><![CDATA[programing]]></category>
            <dc:creator><![CDATA[Nguyễn Hoàng Cương Lê]]></dc:creator>
            <pubDate>Sat, 27 Mar 2021 14:23:25 GMT</pubDate>
            <atom:updated>2022-06-27T03:47:27.915Z</atom:updated>
            <content:encoded><![CDATA[<h4>Have you ever been given a project that has only code, and no documentation or comment? The task could be to maintain or refactor old code, but these questions always pop up: “How do I even start?”, “What am I supposed to do?” or “Do I need to cry?” :)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mYTQe3aP6IxOVqFiy2C6qw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@codestorm?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Safar Safarov</a> on Unsplash</figcaption></figure><blockquote>In this article, I will share with you some good practices I used to handle four developers’ work when they resigned from my company and left no documentation.</blockquote><ol><li><strong>Understand the project</strong></li></ol><p>First thing you need to get yourself to the current state of the system. I have met a project whose code isn’t fully updated on GitHub, so you should make sure that your given code is the latest commit by building, running the code, and comparing it to the living app.</p><p>Base on the previous developer’s mindset, modules could be reused a lot or the code is duplicated everywhere. What ever it be, my advice is to write down or draw the project’s overall structure, it can be whatever diagram you familiar with. And if you are lazy to draw manually, you can search “Auto generate class diagram for …”.</p><blockquote>Note: <strong>For my familiar language, Swift, you can check out this </strong><a href="https://martinmitrevski.com/2016/10/12/swift-class-diagrams-and-more/"><strong>link</strong></a><strong>, they provide a wonderful tool to create class diagrams for you. A note is that you can temporarily remove pods if you don’t want them in the diagram.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bb9yWr2e91_wIGK9BFxjTg.png" /><figcaption>A automated class diagram look something like this. It is much easier to read than plain code right?</figcaption></figure><p>A good practice is trying to break the code in a way that you can easily see. In that way, you will understand the structure more in the process, just make sure you commit all your important changes first.</p><figure><img alt="I change background colors of the app to study other’s code and module structure" src="https://cdn-images-1.medium.com/max/409/1*gHVSDGAKlKl4HMJAfXe52w.png" /><figcaption>I change background colors of the app to study other’s code and module structure</figcaption></figure><p>After some reading and studying that should take you no more than half a day, you can now start to do the tasks.</p><p>2. <strong>Start to write code carefully</strong></p><p>Any time you want to fix a method, try to analyze all module that it impact, add it to a checklist and retest whenever you’ve done your task. This will prevent you from most regressive bugs.</p><figure><img alt="A checklist should be something simple" src="https://cdn-images-1.medium.com/max/380/1*tfJ_H3q9RVtOL5rnvYD0fA.png" /><figcaption>A checklist should be something simple</figcaption></figure><blockquote>Note: <strong>Using a text editor that has global search will make the process much faster</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*K8Z0_v-LdYZ4WDFTAmjZJA.png" /><figcaption>Global search in Xcode help me do the trick everyday</figcaption></figure><p>3. <strong>Start to write the document</strong></p><p>Documentation is extremely important for helping yourself in future updates. But if there is no documentation in the first place, the manager will likely give a tight schedule or not encourage you enough to create it. Despite you can:</p><p><strong>Create guidelines:</strong> You should split branch or add environments that wrap up configuration changes, these will be your future guidelines of how to run your code for different purposes. A normal project, besides “master” and feature branches, usually needs two more branches for user acceptance test and live app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*liPbtz2dPQy69DdF8EQAAw.png" /><figcaption>A normal project usually needs two or more branch for user acceptance test and live app</figcaption></figure><p><strong>Write code that explains itself:</strong> A function named “fetchDataAndUpdateTableView” is pretty lame but it can tell what it does for you instead of writing one more line to tell the same thing. And if you encounter some function’s name that don’t describe fully its functionality, don’t hesitate to update it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O9GFg9ss1gEDXTQ94zRafg.jpeg" /></figure><blockquote>Note: <strong>Don’t hesitate to touch running code (these memes are truly wrong), just remember to chop down these changes small enough and commit it so you can roll back later.</strong></blockquote><h3>Conclusion</h3><p>Working with others’ code undocumented is unarguably one of the most frustrating parts of a developer’s life. Through this article, you learned techniques I used to overcome the vale of tears. I hope you will get through too and move forward in your career. See you next time.</p><h3>Resources</h3><p><a href="https://martinmitrevski.com/2016/10/12/swift-class-diagrams-and-more/">https://martinmitrevski.com/2016/10/12/swift-class-diagrams-and-more/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=626d7985d015" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>