<?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 Luis Aguilar on Medium]]></title>
        <description><![CDATA[Stories by Luis Aguilar on Medium]]></description>
        <link>https://medium.com/@insomniocode?source=rss-121574e21f73------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wyzYQN7lIP1c_43kkUlw9A.jpeg</url>
            <title>Stories by Luis Aguilar on Medium</title>
            <link>https://medium.com/@insomniocode?source=rss-121574e21f73------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 15 Nov 2026 10:05:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@insomniocode/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[What’s new in pdfmake-wrapper 2.0.0!]]></title>
            <link>https://medium.com/@insomniocode/whats-new-in-pdfmake-wrapper-2-0-0-c676096bbf23?source=rss-121574e21f73------2</link>
            <guid isPermaLink="false">https://medium.com/p/c676096bbf23</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[pdfmake]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[svg]]></category>
            <dc:creator><![CDATA[Luis Aguilar]]></dc:creator>
            <pubDate>Sat, 19 Oct 2019 20:33:52 GMT</pubDate>
            <atom:updated>2019-10-19T20:33:52.079Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m7H86pFz2KH2_oEReSmxeQ.png" /></figure><p>New version 2.0.0 of <a href="https://github.com/Lugriz/pdfmake-wrapper"><strong>pdfmake-wrapper</strong></a> is here! This version has great features about security, vectors (shapes), icons, custom fonts, SVG support and a new tool to generate fonts. There are few changes about the installation and configuration as well.</p><h3>Pdfmake is installed separately</h3><p>In the previous version pdfmake-wrapper included pdfmake by default, now, you need to install pdfmake by apart, the reason is to give flexibility to update pdfmake if you need it, this version was built considering from pdfmake@0.1.60 to new minor versions.</p><h3>Custom fonts</h3><p>Now is possible to customize fonts to your PDF documents. This lib does easier to use custom fonts than pdfmake.To use custom fonts in pdfmake you need to generate them, but doing that is tedious, you need to access to the package itself in your <em>(node_modules/pdfmake)</em>, create directories, install some dependencies like <strong>gulp </strong>and it does not allow you to put your fonts wherever you want (you can read the process <a href="https://pdfmake.github.io/docs/fonts/custom-fonts-client-side/">here</a>). To tackle this, a new tool was built to generate them. This is called <a href="https://github.com/Lugriz/pdfmake-font-generator"><strong>pdfmake-font-generator</strong></a><strong> </strong>which allows you to read the fonts to generate wherever they are and save the generated file anywhere. After that, you need to import the generated file as your custom fonts. More about custom fonts <a href="https://github.com/Lugriz/pdfmake-wrapper#generate-custom-fonts">here</a>.</p><h3>Icon support</h3><p>This is a great feature of pdfmake and this one comes to pdfmake-wrapper as well. The process to use icons in your PDF documents is similar to use custom fonts, you can download icons from <a href="http://fontello.com/">fontello</a>. More about icons <a href="https://github.com/Lugriz/pdfmake-wrapper#how-to-use-icons">here</a>.</p><h3>Relative and absolute positions</h3><p>Another feature is to use relative and absolute positions allowing us to set our objects in a specific position on the page by giving the point where the object will be placed.</p><h3>Drawing shapes</h3><p>Another super cool feature is the possibility of drawing shapes in our PDF documents, but in an easy way. Pdfmake-wrapper tries to do the things easier for developers. This package has four types of shapes which are <strong>Line</strong>, <strong>Rect</strong>, <strong>Ellipse</strong> and <strong>Polyline</strong>. Now you can draw and create nice PDF docs using shapes. More about shapes <a href="https://github.com/Lugriz/pdfmake-wrapper#canvasivector---canvas">here</a>.</p><h3>SVG support</h3><p>Now you can use SVG in your PDF documents, but this feature is limited since you need to pass the svg string directly in the new SVG(&#39;&lt;svg&gt;....&lt;/svg&gt;&#39;).end, this will be improved later. More about svg <a href="https://github.com/Lugriz/pdfmake-wrapper#svgsvg-string---svg">here</a>.</p><h3>Security feature</h3><p>The last nice feature is about security, now, you can add password to your documents, prompting for a password when an user opens the file and permission privileges, allowing defines the actions are allowed in a document. More about security <a href="https://github.com/Lugriz/pdfmake-wrapper#userpasswordpassword-string---void">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c676096bbf23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript: Iterator and iterable protocols]]></title>
            <link>https://medium.com/@insomniocode/javascript-iterator-and-iterable-protocols-583b700305ce?source=rss-121574e21f73------2</link>
            <guid isPermaLink="false">https://medium.com/p/583b700305ce</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[iterators]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[core-concepts]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Luis Aguilar]]></dc:creator>
            <pubDate>Sun, 22 Sep 2019 03:55:26 GMT</pubDate>
            <atom:updated>2019-09-23T02:14:12.170Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5X1DB9Yp16gnp8jtG2nIMA.png" /></figure><h3>Introduction</h3><p>This time I’m going to talk about an interesting feature of javascript that probably is not as well known, but it could help us to understand how other features work.</p><h3>What are they?</h3><p>In javascript there are features to iterate collections, for example, <strong>for </strong>loops, <strong>map </strong>method and <strong>forEach</strong> method. Iterators are another way to iterate collections, but they allow us to customize the result of the iterations. Now imagine you have an object and you could do this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*64RHvkavf64BTlXCG-rieA.png" /><figcaption>The object can be literal or a class instance</figcaption></figure><p>By doing this you need to know how these protocols work.</p><h3>Iterator protocol</h3><p>The iterator protocol defines an standard to produce a sequence of values. This protocol is really an object that contains a <strong>next()</strong> method and this one returns another object with two properties, <strong>value</strong> and <strong>done</strong>. Similar to this which is an iterator that returns a counter, the important is that an iterator is an object which returns another object with two properties, <strong>value</strong> and <strong>done</strong> (this is just an example of how an iterator looks if we implement it from scratch):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*Xfw9ap89_jpvgW1pqn_Rtw.png" /></figure><p>The <strong>next()</strong> method always returns an object with <strong>value</strong> and <strong>done</strong> properties. The <strong>value</strong> property contains the value to be returned and the <strong>done</strong> property indicates the termination of the iterator. You can call the next method whenever you want, but in this example after the third call, you will be receiving <strong>{ value: undefined, done: true }. </strong>If you consume this code, you need to check when the property <strong>done</strong> is <em>true</em> in your code logic, but you won’t do that in this way, if you need something like this, it’s better to use <strong>Generators </strong>(I’ll write about it later).</p><p>This was just our own explicit implementation of an iterator (just to understand how it works) which returns a simple counter. Since javascript has an easy way to implement it and write it, we are going to implement this protocol using the implicit way later.</p><h3>Iterable protocol</h3><p>The iterable protocol allows an object to be iterable and customize its iteration behavior. By being an iterable object it needs to implement an <strong>@@iterator </strong>method (an iterator key), by creating this key/property you need to implement the constant <strong>Symbol.iterator,</strong> this method needs to returns an iterator protocol. we are going to use our own explicit iterator protocol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*_HhN800_ycm3tnwMdIJP7Q.png" /><figcaption>becoming an object to iterable</figcaption></figure><p>Probably this can be a bit confusing, it’s ok, as I mentioned above, javascript has a better way to implement a function that returns an iterator which is called <strong>Generator</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*5obhSEKkAfeboOAaH7PI9A.png" /><figcaption>becoming an object to iterable using a generator</figcaption></figure><p>Is this stranger than the previous example?… Let me explain it.</p><p>You can see an asterisk in the function statement (<strong>function*</strong>), the asterisk indicates that the function is a generator which returns an iterator. Another thing is the <strong>yield </strong>keyword, this one returns the value when the <strong>next()</strong> method is called and freezes the execution up to a <strong>next()</strong> is called again returning the next <strong>yield</strong>. Remember that the generator returns an iterator, therefore, when this function is called is not executed immediately, it returns the iterator protocol (similar to our explicit iterator). This example can clear up the confusion (The generators return extra methods).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*_jh3n5M5_MplBU4sF-rUlA.png" /><figcaption>Generator example</figcaption></figure><p>For a deeper understanding of this code, you need to know <strong>Generators</strong> in javascript, but it’s not a problem if you don’t know it by now. I’ll write a next post talking about <strong>Generators</strong> as well. Since you need to know iterators to understand <strong>Generators </strong>in<strong> </strong>detail. you can check on<strong> </strong><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator"><strong>MDN</strong></a><strong> </strong>too.</p><h4>What is the different?</h4><p>The <strong>iterator protocol</strong> allows to an object to produce a sequence of values, which can be used by other expressions that use this one to iterate and display the values.</p><p>The <strong>iterable protocol</strong> indicates that an object is iterable and uses the <strong>iterator protocol</strong> in it. so, you can iterate it using, for example, <strong>for…of</strong> and the spread operator (<strong>[…obj]</strong>).</p><h3>Relation with for…of and spread operator</h3><p>The reason for the <strong>for…of</strong> and <strong>spread operator</strong> work is because internally these call to those protocols, checking if the object has the <strong>iterable protocol </strong>which indicates that the object can be iterated and therefore, it contains the <strong>iterator protocol</strong> to produce its values using the <strong>next()</strong> method that it has.</p><p>Try to do this <strong>[…myCustomObject]</strong> or <strong>for (let p of myCustomObject) {}</strong> without implementing the protocols, you’ll see a type error:</p><blockquote>TypeError: myCustomObject is not iterable</blockquote><h3>Built-in iterables objects</h3><p>In javascript there are objects that implement these protocols, for example, Array, String, Set, Map, TypeArray (Int16Array, etc…). This is the reason you can use <strong>spread operator</strong> and <strong>for…of </strong>on them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=583b700305ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Search algorithm: Double front and back]]></title>
            <link>https://medium.com/@insomniocode/search-algorithm-double-front-and-back-20f5f28512e7?source=rss-121574e21f73------2</link>
            <guid isPermaLink="false">https://medium.com/p/20f5f28512e7</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[search-algorithm]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[searching-algorithm]]></category>
            <dc:creator><![CDATA[Luis Aguilar]]></dc:creator>
            <pubDate>Mon, 05 Aug 2019 05:01:40 GMT</pubDate>
            <atom:updated>2019-08-13T22:27:09.214Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bHkiTeKzmTmi_ahFKkkURg.png" /><figcaption>I didn’t know what name to put it</figcaption></figure><h3>Introduction</h3><p>Hi! I wrote a search algorithm that works similar to <a href="https://medium.com/@insomniocode/search-algorithm-front-and-back-unsorted-86d7a4bfc258"><em>Front and back</em></a><em> </em>search algorithm, but this one works double faster then <em>front and back.</em> I was looking for an algorithm similar or if the algorithm exists, but I found nothing. If you know some algorithm like this, please, comment below about it. By now, I just want to show you this one and how it works.</p><p>If you are wondering about the name, I didn’t know how to name it. But it works similar to <em>front and back. </em>If you have some suggestion about a name, comment it.</p><p><strong>Time complexity:</strong> O(n)</p><p><strong>Space complexity:</strong> O(1)</p><h3>How it works</h3><p>The difference between this algorithm and the <em>front and back</em> is that this one has two extra indexes for searching, but these start from the middle, one of these decreases its value by one and the another one increases its value by one. In short words, two indexes work from the beginning to the middle and the other indexes works from the middle to the end. It probably seems confusing, but in the example you will understand better.</p><h3>Implementation</h3><p>Here the implementation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*r6Yqd2jI0fj7gspPjDG7MQ.png" /><figcaption>The algorithm written in Python</figcaption></figure><p>How you can see, this algorithm has four indexes, <strong>headfront</strong> and <strong>headBack</strong> interact from the position 0 to the middle, where <strong>headFront</strong> starts in position 0 and <strong>headBack </strong>in the middle, while <strong>headFront</strong> increases its value by one, <strong>headBack</strong> decreases its value by one until <strong>headFront</strong> being greater than <strong>headBack</strong> or when the value searched is found, the <strong>tailFront</strong> and <strong>tailBack</strong> perform the same, but on the other side.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20f5f28512e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Search algorithm: Front and back (unsorted)]]></title>
            <link>https://medium.com/@insomniocode/search-algorithm-front-and-back-unsorted-86d7a4bfc258?source=rss-121574e21f73------2</link>
            <guid isPermaLink="false">https://medium.com/p/86d7a4bfc258</guid>
            <category><![CDATA[algoritmos]]></category>
            <category><![CDATA[algorithmic-design]]></category>
            <category><![CDATA[searching-algorithm]]></category>
            <category><![CDATA[front-and-back-algorithm]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Luis Aguilar]]></dc:creator>
            <pubDate>Sat, 03 Aug 2019 19:16:54 GMT</pubDate>
            <atom:updated>2019-08-13T22:26:23.615Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*skIWQBGWr1m51bZ0VKXChA.png" /></figure><h3>Introduction</h3><p>This time we’ll implement an algorithm to search an element in an unsorted array. The most common algorithm to search an element in an unsorted array is using a linear search, checking element by element from the beginning to the end, this algorithm takes <strong>O(n)</strong> complexity. Using the <strong>front and back</strong> algorithm can take us a half of time.</p><p><strong>Time Complexity:</strong> O(n)</p><p><strong>Space complexity:</strong> O(1)</p><h3>How it works</h3><p>The way of this algorithm works is similar to a linear search, but the difference is that uses two indexes to search, the first one starts to the beginning (position 0) and the second one starts to the end (position length -1).</p><p>The first index starts from the position 0 to up and the second one starts from the last position to down, when the first index is greater then the second one the iterations stop or when the value is found.</p><h3>Implementation</h3><p>Now, we’ll implement the algorithm in python:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*Hx9GZrgsx-L8-H2MsZ5EEw.png" /><figcaption>Front and back algorithm</figcaption></figure><p>This is an easy algorithm to implement and useful. Now you can perform searches a little faster.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86d7a4bfc258" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data structure: Stack]]></title>
            <link>https://medium.com/@insomniocode/data-structure-stack-acfe9bedff49?source=rss-121574e21f73------2</link>
            <guid isPermaLink="false">https://medium.com/p/acfe9bedff49</guid>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[algoritmos]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Luis Aguilar]]></dc:creator>
            <pubDate>Tue, 30 Jul 2019 07:03:07 GMT</pubDate>
            <atom:updated>2019-07-30T07:03:07.895Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*0vXf0Lz5ALfzJf3quixjDQ.png" /><figcaption>Pop()</figcaption></figure><h3>Introduction</h3><p>A stack is a linear data structure that follows a <strong>LIFO</strong> (First In Last Out) order. There is a common example about a <em>stack, </em>imagine a stack of plates, the plate that is placed first is the last to leave the stack and the last that is placed is the first to leave it.</p><p>Another example could be the back button in the browser, each time you navigate on pages, the pages are stacked <em>(push) </em>and when you click on the back button it removes your last visited page <em>(pop), </em>then the forward button stack is filled <em>(push)</em> with the page that the back button was removing <em>(pop). </em>Therefore, the first visited page is the last to leave the stack and the last one is the first to leave it.</p><p>I tried to explain the functionality of a stack using a simple example like the back button.</p><h3>Operations</h3><p>A stack is an <strong>ADT</strong> (Abstract Data Type) that mentions what operations will perform but not how it will be implemented, this means that you can implement a <em>stack</em> using a linked list data structure, therefore, the <em>stack </em>name is gained for the operations it does. It contains the following basics operations:</p><ul><li>push(data) — Inserts a data in the stack</li><li>pop() — Removes the last data inserted in the stack</li><li>peek() — Displays the last data inserted in the stack, but it doesn’t remove it</li><li>isEmpty() — Displays if the stack is empty</li></ul><h3>Implementation</h3><p>It’s time to implement a <em>stack,</em> first of all, we need to create the <em>stack</em> class and the <em>node</em> class, I’ll explain in detail about them.</p><h4>Implementing the Node class</h4><p>A node is a structure which contains the passed data and the reference to another node. It looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*bGAfrELqrO9ISHqXE2g-qQ.png" /><figcaption>Node class</figcaption></figure><h4>Implementing the Stack Class</h4><p>The <em>Stack</em> class will contain the operations that it needs and use the <em>node</em> class in it. We are going to implement the class constructor and then, we’ll create and explain each method (operation) it has.</p><p>This is a basic stack class</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*_G-plis-eKvQE_Ukb4faZw.png" /><figcaption>Stack class</figcaption></figure><h4>Push(data)</h4><p>This method adds items or elements to the <em>stack,</em> it creates a new node and checks if the list is empty, if it is, assigns the node to the head (it is the first element), else, the new node points to the <em>head </em>property becoming it as the next node of it and the new one is become to the first one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*cW8PJs6AEezPVVgIXfov1w.png" /><figcaption>Push method of the Stack class</figcaption></figure><h4>Pop()</h4><p>It checks if the list is not empty, otherwise, it has nothing to remove. It assigns the head to its next node and returns the obtained value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*E66wz0xHYa_8Z-rsYDGINg.png" /><figcaption>Pop method of the Stack class</figcaption></figure><h4>peek()</h4><p>It just returns the last element in the list, returning <strong>null</strong> (None in python) if the list is empty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*i760bL2g5zdL1Zn0AlLXnQ.png" /><figcaption>Peek method of the Stack class</figcaption></figure><h4>isEmpty()</h4><p>This method returns a boolean telling us whether the list is empty or not, the way of knowing if a list is empty, it’s checking if the head is <strong>null</strong> (None in python).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*5B8oX_EKrNAwAbZHSiSciA.png" /><figcaption>empty method of the Stack class</figcaption></figure><p>This is a basic implementation of a <em>stack</em>, you can also add extra properties like <strong>length </strong>and a method to get it, this would displays the number of elements that the list has.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acfe9bedff49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sorting: Bubble sort]]></title>
            <link>https://medium.com/@insomniocode/sorting-bubble-sort-be9bda9bd18c?source=rss-121574e21f73------2</link>
            <guid isPermaLink="false">https://medium.com/p/be9bda9bd18c</guid>
            <category><![CDATA[algoritmos]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[sorting-algorithms]]></category>
            <category><![CDATA[bubble-sort]]></category>
            <dc:creator><![CDATA[Luis Aguilar]]></dc:creator>
            <pubDate>Mon, 15 Jul 2019 05:46:32 GMT</pubDate>
            <atom:updated>2019-07-15T05:46:32.676Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ulVygQBoBVWcMjlXV5zrzw.png" /><figcaption>Bubble sort</figcaption></figure><h3>Introduction</h3><p>In this story I’m going to talk about how to implement the bubble sort algorithm and how it works, well, I’ll try to explain it in an easy way.</p><p><strong>Time complexity: </strong>O(n²)</p><h3>Implementation</h3><p>First of all I’ll show you how the algorithm is implemented, so, in this time I’ll use Python language to implement the sorting algorithm. This is how the bubble sort looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*6HqxinD6DqEdUsjewtYdNA.png" /><figcaption>Bubble sort algorithm implemented in Python</figcaption></figure><h3>Explanation</h3><p>The first loop (<strong>for i in range(len(arr)):</strong>) gets the first element in the array to compare it with the other elements, by doing this it is used the second loop (<strong>for j in range(i+1, len(arr)):</strong>), for example, the first loop gets the position <strong>0</strong> in the array, the second loop starts in the position <strong>i+1,</strong> the value of <strong>“i”</strong> is <strong>0 </strong>in this time, therefore, <strong>i+1</strong> is equal to <strong>0+1 = 1, </strong>then the position <strong>0</strong> is compared with the position <strong>1</strong> in the array (<strong>arr[ i ] &gt; arr[ j ]</strong>), if the first position is greater than the second one their values are swapped, the second loop repeats the process getting the next position and comparing the values and so on. When the second loop ends, the first loop gets the next position and the second loop repeats the process starting one position up of the first loop.</p><p>In short words the first loop gets the main position which is compared with the other positions (the second loop’s work).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_XFWaiX0ZoJfjjnE3tXpHg.png" /></figure><p>This is my explanation about the algorithm, I hope you find it useful to understand how the algorithm works and how to implement it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be9bda9bd18c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linux: Creating a desktop shortcut (Launcher)]]></title>
            <link>https://medium.com/@insomniocode/linux-creating-a-desktop-shortcut-launcher-2088d1e3c83e?source=rss-121574e21f73------2</link>
            <guid isPermaLink="false">https://medium.com/p/2088d1e3c83e</guid>
            <category><![CDATA[desktop-shortcut]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[debian]]></category>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[launcher]]></category>
            <dc:creator><![CDATA[Luis Aguilar]]></dc:creator>
            <pubDate>Mon, 29 Apr 2019 05:50:18 GMT</pubDate>
            <atom:updated>2019-07-10T00:23:24.325Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cDf9B-tmdYTdVkDoYxQu1A.png" /></figure><h3>Introduction</h3><p>Hi everyone! in this story I’m going to talk about how to create a desktop shortcut. Sometimes when downloading applications aren’t <strong>.deb</strong> files (in debian distributions), instead, they are downloaded as compressed files and when they are decompressed, they return us an application’s folder, in this cases we need to create a desktop shortcut.</p><h3>Creating the .desktop file</h3><p>The first step is to create a file with <em>.desktop</em> extension (create it where you want), the file name can be the app name by convention (or you can name it as you want). In this example the file will be named <strong>myapp.desktop.</strong></p><p>A basic <strong>.desktop</strong> file looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*Zd9GFnS_g1QGhTA9323CLA.png" /></figure><h3>Moving the file</h3><p>Once you’ve created the file, you need to move it to the <strong>/usr/share/applications</strong> or <strong>~/.local/share/applications, </strong>in these folders live all the <strong>.desktop</strong> files in your system.</p><p>moving the file in the terminal (use <strong><em>sudo</em></strong> if is required)</p><blockquote>$ sudo mv myapp.desktop /usr/share/applications</blockquote><p>or</p><blockquote>$ sudo mv myapp.desktop ~/.local/share/applications</blockquote><p>now you will be able to look the application shortcut on the application menu.</p><h3>Conclusion</h3><p>It’s annoying when some applications don’t create a desktop shortcut, because we need to find the folder to run the app, by example, <strong>Postman </strong>(it’s an app to do requests, it’s useful to test API’s). So, by creating these shortcuts, we avoid this tedious search.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2088d1e3c83e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular: Creating a PDF using pdfmake-wrapper]]></title>
            <link>https://medium.com/@insomniocode/angular-creating-a-pdf-using-pdfmake-wrapper-9ad3d8deca2e?source=rss-121574e21f73------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ad3d8deca2e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[pdfmake]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[pdf]]></category>
            <dc:creator><![CDATA[Luis Aguilar]]></dc:creator>
            <pubDate>Sat, 09 Feb 2019 03:45:45 GMT</pubDate>
            <atom:updated>2019-02-09T03:45:45.867Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*a9yndpKiU9d7yqRLzgGf4Q.png" /></figure><h3>Introduction</h3><p>Hi everyone!. In this story I’m going to talk about how to create a PDF using a library called <a href="https://github.com/Lugriz/pdfmake-wrapper"><strong>pdfmake-wrapper</strong></a>, (this is a brief introduction of <strong>pdfmake-wrapper</strong>), this one helps us generate a PDF in an easy way. If you’ve used the original <strong>pdfmake</strong> library, you know how confusing it is when the document starts to grow up, the object becomes so large that it’s tedious to maintain it.</p><h4>Installation</h4><p>First of all, you need to install the library:</p><blockquote>$ npm i pdfmake-wrapper — save</blockquote><p><strong>Note: </strong>This library includes <strong>pdfmake</strong> internally. you don’t need to install it.</p><h4>Usage</h4><p>Once you’ve installed the package, you can start creating a PDF document:</p><p>You need to import the library where you’re going to use it and create an instance of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*9AqV1n4zZzirgduR3m1MoQ.png" /></figure><p>This is a simple PDF document that shows us a <em>“Hello world!” </em>text.</p><p>You can use images on your PDF documents in a simple way, and avoid transforming an image to base64 first. You can pass the URLs, base64 or images previously configured using the keys that you assign to them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*qnQIvA-FnYGU8Zl53Z0VGw.png" /></figure><h4>Conclusion</h4><p>This library helps us generate PDF documents in an easy way, writting a few lines of code and an easy understanding about the document. It’s easier to understand a document with describable methods than a large object. For more details check the <a href="https://github.com/Lugriz/pdfmake-wrapper">github repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ad3d8deca2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular: Imágenes por defecto.]]></title>
            <link>https://medium.com/@insomniocode/angular-im%C3%A1genes-por-defecto-cfaeaefbf22d?source=rss-121574e21f73------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfaeaefbf22d</guid>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[image]]></category>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[fallback]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Luis Aguilar]]></dc:creator>
            <pubDate>Sun, 20 Jan 2019 22:54:21 GMT</pubDate>
            <atom:updated>2019-01-20T22:54:21.162Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*MCJlRDOghcQFh-GSVBpV1A.png" /></figure><h3>Introducción</h3><p>En este post quiero compartirles una forma de como adjuntar imágenes por defecto en <strong>Angular. </strong>Muchas veces en los proyectos tenemos la necesidad de poner imágenes por defecto, ya sea una imagen de perfil (por defecto), cuando el usuario no tiene alguna imágen en su perfil o cuando alguna imágen de alguna publicación no carga. Cualquiera que sea la situación, siempre necesitamos una imágen de emergencia. para no ver este tipo de cosas en nuestros proyectos:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/100/1*SlyzIBegASMPI5TSFwEbEA.gif" /><figcaption>No se encuentra la imágen</figcaption></figure><h3>Alternativas</h3><p>Existen librarías que solucionan este problema, que se implementan de la siguiente forma:</p><blockquote>&lt;img src=”https://domain.com/original-image.png” fallback=”https://domain.com/emergency-image.png” /&gt;</blockquote><p>Colocando literalmente la imagen por defecto (fallback) ó:</p><blockquote>&lt;img src=”https://domain.com/original-image.png” [fallback]=”variableWithEmergencyImage” /&gt;</blockquote><p>Manteniendo una varibale con la imágen por defecto.</p><p>Esto es una muy buena alternativa, pero el problema es que en cada etiqueta <strong>IMG </strong>tienes que colocar la imagen por defecto, si en una vista tienes 5 imágenes, tendrás que poner en cada una de ellas la imágen de emergencia. Esto se vuelve incómodo cuando el proyecto requiere actualización, cuando se desea cambiar el recurso (El dominio, por ejemplo), si tienes la imágen de emergencia en una variable, esto ya sería más cómodo al hacer la actualización, pero el código sigue viendose sucio. lleno de <strong>fallback=”https://domain.com/emergency-image.png” </strong>ó <strong>[fallback]=”variableWithEmergencyImage” </strong>(tienes que declarar la variable que contendrá la imagen en cada componente). Pero ¿qué pasa cuando tenemos distintas imágenes de emergencia?… Por ejemplo, una para foto perfil, otra para publicaciones, etc… nuestro código se vería aún más sucio.</p><h3>ng-fallimg</h3><p><a href="https://www.npmjs.com/package/ng-fallimg">ng-fallimg</a> es una librería para este tipo de situaciones, pero de una manera más cómoda y limpia.</p><p>Primero instalmos la librería:</p><blockquote>$ npm install ng-fallimg — save</blockquote><p>Una vez instalado, lo importamos en nuestro módulo principal (comúnmente AppModule) utilizando el método estático <strong>forRoot({ … }), </strong>el cual recibe un objecto con las imágenes de emergencia que vamos a utilizar, obligatoriamente se define una propiedad <em>default </em>al cual se le asigna un recurso de alguna imágen, este puede ser un recurso externo (https://anotherdomain.com/picture.png), local (/assets/picture.png) o en base64 ( data:image/png; base64, … ):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*gniRw71okpBQuvZbUnUn1Q.png" /><figcaption>app.module.ts</figcaption></figure><p>El método <strong>forRoot({ … }) </strong>inicia el servicio que administra internamente el dicionario de imágenes que se le pasan como parámetro. Sólo tendrás que utilizar el método <strong>forRoot({ … }) </strong>una vez, y será donde quieras iniciar el servicio (normalmente los servicios que sirven para toda la aplicación se inician en el módulo principal), ya que si lo llamas en otro módulo (Algún módulo de característica) estarías creando otra instancia del mismo.</p><p>Ahora en <strong>app.component.html </strong>podemos utilizar la directiva <em>ng-fallimg:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*JJlhMIOQz1chZzIA8UeSfw.png" /><figcaption>app.component.ts</figcaption></figure><p>Cuando la imágen principal (“<strong>/image-fails.png</strong>”) no cargue, se cargará la imágen por defecto.</p><h3>Multiples imágenes por defecto</h3><p>Como habíamos comentado, <strong>ng-fallimg</strong> recibe las imágenes por defecto que necesites:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*woV3cZCu3oM8QK_RaaNaiw.png" /><figcaption>app.module.ts</figcaption></figure><p>Ahora para decirle a <strong>ng-fallimg </strong>qué imágen tomar de todas las que tenemos, le pasamos el nombre de la propiedad:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*uqZ2urN5mNulKjfRL92OGg.png" /><figcaption>app.component.ts</figcaption></figure><p><strong>Nota: </strong>Si no se le pasa nada a la directiva (ng-fallimg) toma la imagen de la propiedad <strong>default</strong>.</p><h3><strong>Utilizando ng-fallimg en otro módulo</strong></h3><p>Si utilizamos ng-fallimg en otro módulo, tenemos que importar el módulo <strong>NgFallimgModule </strong>(como es normalmente en Angular) para poder usar la directiva (<strong>ng-fallimg</strong>), pero ahora sin usar el método <strong>forRoot({ … }) </strong>ya que el servicio lo tenemos listo en el módulo principal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*hfLe868F2k7jEUdpVLGolA.png" /><figcaption>page1.module.ts (otro módule)</figcaption></figure><p>Y ocupar la directiva normalmente:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*JJlhMIOQz1chZzIA8UeSfw.png" /><figcaption>page1.component.ts</figcaption></figure><p><strong>Nota: NgFallimgModule </strong>contiene el servicio que contiene las imágenes y la directiva (ng-fallimg) que le da la funcionalidad de poner la imágen de emergencia a las etiquetas <strong>IMG.</strong></p><h3>Conclusión</h3><p>Esta librería nos facilita el control de las imágenes rotas en nuestros proyectos, de una manera más cómoda y limpia, si el recurso cambia, solo tenemos que ir al archivo donde está nuestro diccionario de imágenes y modificar el recurso, sin tocar ningún otro archivo. Para más detalle del paquete, checa en npm: <a href="https://www.npmjs.com/package/ng-fallimg">ng-fallimg</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfaeaefbf22d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creando una librería Angular y subiéndola a NPM]]></title>
            <link>https://medium.com/@insomniocode/creando-una-librer%C3%ADa-angular-y-subi%C3%A9ndola-a-npm-f78d212e8e71?source=rss-121574e21f73------2</link>
            <guid isPermaLink="false">https://medium.com/p/f78d212e8e71</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[npm-package]]></category>
            <category><![CDATA[angular-cli]]></category>
            <category><![CDATA[npm]]></category>
            <dc:creator><![CDATA[Luis Aguilar]]></dc:creator>
            <pubDate>Wed, 02 Jan 2019 23:24:28 GMT</pubDate>
            <atom:updated>2019-01-03T00:08:10.624Z</atom:updated>
            <content:encoded><![CDATA[<h3>Crear una librería Angular y subirla a NPM</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E77qxGh3J38Is15rBKRFNg.png" /></figure><h3>Introducción</h3><p>He buscado en la web sobre <strong><em>cómo crear un paquetes de NPM usando Angular</em></strong> pero no he encontrado contenido completo de ello y menos en Español. Así que decidí escribir este Storie para compartir la forma en cómo yo desarrollo una librería Angular y cómo subirla a Github y a NPM.</p><blockquote><strong>NOTA: </strong>Se considera que el lector ya tiene instalado <em>angular-cli.</em></blockquote><h3>Creando una librería</h3><p>Lo primero que tenemos que hacer es crear un nuevo proyecto <em>Angular, </em>en este caso yo le llamaré <strong>“my-project”</strong><em>, </em>para eso utilizamos el comando:</p><blockquote>$ ng new my-project</blockquote><p>Una vez creado el proyecto, nos posicionamos en la raíz, y en la terminal escribimos lo siguiente (el CLI de <em>Angular </em>nos proporciona un comando para crear una librería):</p><blockquote>$ ng generate library my-lib</blockquote><p>Esto nos genera una librería localizada en <strong>“projects/my-lib”</strong>, como se muestra a continuación:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/1*PZDQBOYT1z8lLVfRgnyUhw.png" /></figure><p>Aquí es donde escribimos nuestra librería. Como el proposito de este post es enseñar como crear una librería y no una librería en especifico, no vamos a escribir mucho código. Por el momento vamos a eliminar los archivos que no nos sirven y sólo dejaré los archivos<strong> my-lib.component.ts, my-lib.component.spec.ts </strong>y<strong> my-lib.module.ts. </strong>En este ejemplo solo usaremos un componente con su respectivo archivo de pruebas y el módulo, pero puedes generar directivas, servicios, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*jzV28Z4-BGHYrgwg7DsODQ.png" /></figure><p>En nuestra librería tenemos un archivo llamado <strong>public_api.ts </strong>ahí es donde se encuentran todas las clases, componentes, directivas, etc.. que nuestra librería va a compartir. Si agregamos algún otro archivo, como por ejemplo una interfaz que se va a compartir con el usuario que ocupe nuestra librería, la agregamos a nuestro <strong>public_api.ts. </strong>Los archivos que son de uso interno para la librería y que no serán compartidos con el usuario, simplemente no se agregan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*pbNZJDSWBoQg1VEC22dDag.png" /><figcaption>public_api.ts</figcaption></figure><p>En este caso solo exportamos el módulo ya que es el que contiene el componente a compartir. Ahora podemos escribir nuestra librería como nosotros queramos.</p><h3>Transpilando la librería</h3><p>Una vez escrita nuestra librería, es hora de prepararla como librería genérica. El comando <strong>ng generate library </strong>nos crea un directorio en la cual podemos escribir una librería, pero solo es la preparación, falta transpilarla para hacerla una librería un poco más profesional y compatible. y para eso nos vamos a apoyar de <a href="https://github.com/ng-packagr/ng-packagr"><strong>ng-packagr,</strong></a><strong> </strong>es un paquete que nos simplifica la creación/transpilación de librerías para <em>Angular.</em></p><p>Instalamos <strong>ng-packagr.</strong></p><blockquote>$ npm install ng-packagr — save-dev</blockquote><p>En nuestro <strong>package.json</strong> del proyecto root <strong>my-project </strong>creamos un nuevo script, que nos ayudará a transpilar nuestra librería usando <strong>ng-packagr</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*KDLRiEFwp5LEdIMGelNLMA.png" /><figcaption>package.json of the my-project root</figcaption></figure><p>El nombre del script puede ser cualquiera, en este caso yo le puse <strong>“build:lib” </strong>y apunta al archivo <strong>ng-package.json </strong>que es el que le indica dónde está la librería y como la va a transpilar. Ahora ejecutamos nuestro nuevo comando:</p><blockquote>$ npm run build:lib</blockquote><p>Esto generará una carpeta <strong>dist</strong> en el proyecto raíz (my-project) con la librería transpilada.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*HKAr1GSrH3kUEQTw6j0x8A.png" /><figcaption>transpiled lib</figcaption></figure><p>Antes de transpilar la librería, recomiendo hacer algunas modificaciones en el <strong>package.json </strong>que se encuentra dentro de nuestra librería (projects/my-lib), indicando la descripción, repositorio, autor y todo lo necesario para subir una librería a NPM <a href="https://docs.npmjs.com/files/package.json">(aquí</a> les dejo las opciones que soporta el archivo <strong>package.json</strong>)<strong>, </strong>crear el archivo <strong>LICENSE </strong>(ya sea que lo creen manual o desde el repositorio) y modificar el <strong>README.md </strong>indicando el uso de la librería. Vamos a modificar nuestro script (build:lib) para copiar el <strong>README.md </strong>y el archivo <strong>LICENSE</strong> en nuestra librería transpilada.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*_PiClHrq2psb4EZjhh2IsA.png" /></figure><p>Ahora nuestra librería transpilada con el archivo <strong>README.md</strong> y <strong>LICENSE</strong> se vería así:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/1*ESEeJ-szkAN_-cwRr7w_6A.png" /></figure><p><strong>Nota: </strong>Como puedes darte cuenta el proyecto raíz solo sirve como contenedor para generar nuestra librería.</p><p>Podemos crear otros scripts en nuestro <strong>package.json, </strong>por ejemplo, para hacer pruebas unitarias a nuestra librería.</p><h3>¿Qué subir a Github?</h3><p>En Github se sube el proyecto completo (<strong>my-project</strong>), con el <strong>README.md</strong> que describe el uso de la librería, y es donde se encuentran los comandos y las dependencias para hacer el transpilado.</p><h3>¿Qué subir a NPM?</h3><p>Para NPM entramos a la carpeta <strong>dist </strong>que se generó al correr el comando <strong>npm run build:lib </strong>y entramos a la carpeta <strong>my-lib.</strong></p><blockquote>$ cd dist/my-lib</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/190/1*kUxXy4om7iZwpDDu8Nm7bQ.png" /><figcaption>transpiled lib</figcaption></figure><p>Esto es lo que se subirá a NPM.</p><p>Una vez posicionado en la carpeta <strong>dist/my-lib, </strong>en nuestra terminal accedemos a nuestra cuenta de NPM:</p><blockquote>$ npm login</blockquote><p>les pedirá las credenciales y hacemos la publicación de nuestro paquete:</p><blockquote>$ npm publish</blockquote><p><strong>Nota: </strong>Recuerda que cada modificación a nuestro paquete hay que cambiar la versión del mismo. Para más detalles de como profundizar con NPM les puedo compartir <a href="https://docs.npmjs.com/">este enlace</a>.</p><h3>Conclusión</h3><p>Es importante escribir código reutilizable para poder usarlos en proyectos futuros y evitar reescribir una funcionalidad, ahora con NPM podemos crear nuestras propias librerías y compartirlas con otros desarrolladores de una manera fácil.</p><h4>Otras stories</h4><ul><li><a href="https://medium.com/@insomniocode/angular-autenticaci%C3%B3n-usando-interceptors-a26c167270f4">Angular: Autenticación usando interceptors.</a></li><li><a href="https://medium.com/@insomniocode/typescript-path-mapping-22459288d3db">Typescript: Path mapping</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f78d212e8e71" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>