<?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 Maximilien Monteil on Medium]]></title>
        <description><![CDATA[Stories by Maximilien Monteil on Medium]]></description>
        <link>https://medium.com/@mntlmaxi?source=rss-ef6729d722c9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PID-Rofr52Y7tf3UmAo00g.jpeg</url>
            <title>Stories by Maximilien Monteil on Medium</title>
            <link>https://medium.com/@mntlmaxi?source=rss-ef6729d722c9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 05:15:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mntlmaxi/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 start Coding up your Design System in Vue]]></title>
            <link>https://medium.com/@mntlmaxi/how-to-start-coding-up-your-design-system-in-vue-ee8144e5bbe1?source=rss-ef6729d722c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee8144e5bbe1</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Maximilien Monteil]]></dc:creator>
            <pubDate>Fri, 31 Jan 2020 19:23:24 GMT</pubDate>
            <atom:updated>2020-02-01T07:52:12.246Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ya6B0zROC3b2aioh.png" /></figure><p>Imagine this, you create your web app for this new epic idea and you implement the core functionality. The design can come later you think.</p><p>Well later is now, you’re gaining traction and getting feedback, the time has come to overhaul or completely recreate your design!</p><p>In this article I’ll go over the tools and methods you can use to achieve just that.</p><p>I personally fell into this situation with my web app Mylo, a workout management application. As it grew and came into contact with users, issues arose with color contrast, inconsistencies, and more.</p><p>Fixing these issues can be described in two pillars:</p><ul><li>Design System (how everything will look)</li><li>Implementation (how to apply the look)</li></ul><p>(I focus on look here but understand that design is only about 20% look, the rest must be considerations about the user experience)</p><p>Going through this has taught me a lot but also made obvious how much more there is to learn. If you find any mistakes or have some tips please let me know :D</p><p>I’ll be using <a href="https://tailwindcss.com/">TailwindCSS</a> in this article but everything applies just as well without.</p><h3>Pillar 1: Design System</h3><p>The first step, which is all the rage these days, is having a design system. A design system is essentially a visual codebase of your software, and just like a codebase, it is a complete and specific description of what the application should look like under almost any circumstance.</p><p>And so, the more you look into what makes up a design system, the more it feels like an impossible task. A complete design system involves the colors, spacing rules, text styles, buttons, containers, branding, accessibility, and so much more.</p><p>The best and most exhaustive resource I’ve found is the <a href="https://designsystemchecklist.com/">Design System Checklist</a>.</p><p>Therefore I feel more comfortable refering to what I have as a design library with loose guidelines. It works out because I can just refer to myself for any design questons ;)</p><p>So we’ll be going over how to implement elements like buttons, icons, colors and a few input types.</p><h3>Pillar 2: Implementation</h3><h3>Directory Structure</h3><p>Coding up design elements is amazing for reusability and consistency but it isn’t very useful if components are all across the app in random, hard to access locations. We want them organized.</p><p>I recommend putting the smallest/atomic elements into the src/components folder and then into their own subfolders (icons, inputs, buttons, etc.)<br> Compound components, built out of the smaller ones, can be placed into the src/layouts folder, again with their own subfolders.</p><h3>Colors</h3><p>Defining and enforcing colors is a good first step.</p><p>You generally have a clear discrete set of colors that your app allows, to bring them in you can either modify the TailwindCSS config file or add them as CSS variables.</p><p>Here is how it looks in TailwindCSS, I overwrote the default colors to enforce the use of the system colors but you can also extend the default theme and add your own colors.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6bc5cf19f2a416924e9bdf6873f54d98/href">https://medium.com/media/6bc5cf19f2a416924e9bdf6873f54d98/href</a></iframe><p><a href="https://tailwindcss.com/docs/theme/">TailwindCSS Docs — Theme Configuration</a></p><p>If you’re not using tailwind this can also be achieved using css variables like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9713d0735600e22f2f68a3dd4c434c8/href">https://medium.com/media/a9713d0735600e22f2f68a3dd4c434c8/href</a></iframe><h3>Icons</h3><p>First off I recommend using SVG icons because of how configurable they are. You can change their size without any quality loss, dynamically change their color, and their file size is generally smaller than an equivalent png/jpg.</p><p>Getting the actual SVGs can be done through the export options of design tools like Figma, Sketch, or Illustrator.</p><p>Once you have the files you can further optimize them with SVGO, there is a command line tool and a web based one.</p><ul><li><a href="https://github.com/svg/svgo">GitHub - svg/svgo: SVG Optimizer for Node.js and CLI. ⚙️</a></li><li><a href="https://github.com/jakearchibald/svgomg">GitHub - jakearchibald/svgomg: Web GUI for SVGO</a></li></ul><p>Both work automatically by pointing them to the file though the web version makes the available options more accessible. Make sure to have a look at the final result to make sure your icons still look fine.</p><p>Then we bring the icons into our Vue app, I used a method recommended in the Vue Cookbook. It’s a system made by Sarah Drasner, the SVG queen, and you can find the link for it <a href="https://vuejs.org/v2/cookbook/editable-svg-icons.html">here</a>.</p><p>To make it work with TailwindCSS, you’ll need to make a couple of changes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46178c90eb8923aa9c36b0ad7bd0f8ef/href">https://medium.com/media/46178c90eb8923aa9c36b0ad7bd0f8ef/href</a></iframe><p>Since SVGs themselves are rather light, it felt like a lot of overhead to use full components, so I made some further changes to make use of functional components, you can check out my fork here:</p><p><a href="https://github.com/MaxMonteil/vue-sample-svg-icons">MaxMonteil/vue-sample-svg-icons</a></p><h3>Buttons</h3><p>Initially I wanted to bring in buttons the same way as with icons, using Vue components but that ended up being deceptively complicated. The component had to work with buttons, links, or a router-link (using vue-router).</p><p>Supporting links was important for accessibility and semantics as links are meant to take you to another page whereas buttons should not.</p><p>As a solution I extracted the common classes into their own utilities in TailwindCSS, which in pure css is just a normal class rule.</p><p>Some examples:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6124a150cc34e6e5262de1e02259967/href">https://medium.com/media/c6124a150cc34e6e5262de1e02259967/href</a></iframe><h3>Text Inputs</h3><p>For inputs we can use Vue components but there are a few things to take into consideration.</p><p>Our wrapper components need to be lightweight and transparent, we can do that by using functional components and attaching all attributes and event listeners.</p><p>I also took the chance to include the label into the component. It fits the design, is more accessible, and ensures I never forget them.</p><p>Start off with a BaseInput.vue component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b74878fa91fcea5cac391024fbb37fbf/href">https://medium.com/media/b74878fa91fcea5cac391024fbb37fbf/href</a></iframe><p>And here is an example use of BaseInput.vue:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07a2762a8685f15438d5ff0c4dfa1db8/href">https://medium.com/media/07a2762a8685f15438d5ff0c4dfa1db8/href</a></iframe><p>Notice how we call the BaseInput.vue component. Surprisingly, imported components are not exposed in functional components when using the template format. So instead we place the imported components into injections. They could also placed into props if you prefer.</p><p>This method was brought up in this github issue:</p><p><a href="https://github.com/vuejs/vue/issues/7492">Functional single file component with components option. · Issue #7492 · vuejs/vue</a></p><h3>Radio Buttons</h3><p>After all the elements we’ve done so far, Radio Buttons are not too different. The difference is that styling them can be more involved. While it is possible to use standard buttons instead, I wanted to use the default radio buttons, again for semantics and accessibility.</p><p>The trick I found was to use the behavior of labels wrapping radio buttons.<br> The buttons by themselves are small and hard to touch/click but if you wrap them in a label, clicking anywhere on the label box will also select the radio button.<br>Using this, I styled radio buttons by actually making the label look as I wanted and hiding the radio buttons inside the label.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6757e3e48759b5db1f300abe087044be/href">https://medium.com/media/6757e3e48759b5db1f300abe087044be/href</a></iframe><p>Be careful when hiding the radio button as it still needs to be visible to screen readers, tailwind offers a class for this, in standard css that looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8ac7861307c11ac80597617efe367bc/href">https://medium.com/media/a8ac7861307c11ac80597617efe367bc/href</a></iframe><p>As for the v-slot and all the ORs (||), I explain those in the next section about select inputs.</p><p>A really helpful resource that also goes over checkboxes:</p><p><a href="https://www.smashingmagazine.com/2017/08/creating-custom-inputs-vue-js">Smashing Magazine — Creating Custom Inputs in VueJS</a></p><h3>Select Input</h3><p>The select component is a fun one to wrap both in terms of design and functionality.</p><p>Design wise it was surprising to discover how “hacky” it is to change the default downward arrow. There are a few ways to do it but the trick I went with is to remove the default style by setting appearance: none; and then bringing in my SVG of choice with the URL function of CSS.</p><p>To do something similar you will need to encode your SVG tag into a URL compatible string, I found this site to do just that:</p><p><a href="https://yoksel.github.io/url-encoder/">URL-encoder for SVG</a></p><p>Then there are a few more positioning and spacing styles to place the icon where you want.</p><p>For functionality, the end user should retain control over how the drop-down values are displayed, the go to solution is to use scoped slots. With this method our component can support any array of values.</p><p>This is because the official Vue doc shows examples using a String Array and an Object Array to populate the select.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5eeedeec689ad1fb293268b3eb6b19b0/href">https://medium.com/media/5eeedeec689ad1fb293268b3eb6b19b0/href</a></iframe><p>These wrapper components also offer the chance to enforce best practices like a label for an input and an empty disabled first option for better iOS support.</p><h3>Conclusion</h3><p>Well you’ve reached the end, this covers all the components I brought in from my design library. It really just scratches the surface of what is possible and I couldn’t hope to be fully exhaustive. Nonetheless, I hope this helped you out and encouraged you to tackle that redesign or even just start to design!</p><p>The next step after wrapping all these input fields would be to compose them into a form or other layout for reuse, these are some of the components you’d place into the src/layouts folder. You can expect a follow up article once I finish it up myself :D</p><p>Feel free to leave any comments below and if you have questions or want to follow up, you can find me on twitter <a href="https://twitter.com/maxmonteil">@MaxMonteil</a></p><h4>Other helpful links</h4><ul><li><a href="https://markus.oberlehner.net/blog/setting-up-tailwind-css-with-vue/">Setting up Tailwind CSS with Vue.js</a></li><li><a href="https://markus.oberlehner.net/blog/reusable-functional-vue-components-with-tailwind-css/">Reusable Functional Vue.js Components with Tailwind CSS</a></li></ul><p><em>Originally published at </em><a href="https://dev.to/maxmonteil/how-to-start-coding-up-your-design-system-in-vue-1m08"><em>https://dev.to</em></a><em> on January 31, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee8144e5bbe1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Quick Look at Open Source Licenses — What you need to know]]></title>
            <link>https://medium.com/@mntlmaxi/a-quick-look-at-open-source-licenses-what-you-need-to-know-4ed7c792299d?source=rss-ef6729d722c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ed7c792299d</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Maximilien Monteil]]></dc:creator>
            <pubDate>Tue, 21 May 2019 19:11:15 GMT</pubDate>
            <atom:updated>2019-05-21T19:11:15.709Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Quick Look at Open Source Licenses — What you need to know</h3><h4>Knowing how open and free open-source software actually is could help protect you and your work</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rCJZ6lqiOz1f80xT" /><figcaption>Photo by <a href="https://unsplash.com/@imansyahmp?utm_source=medium&amp;utm_medium=referral">Imansyah Muhamad Putera</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I keep reading about all these different licenses in the software world but the truth is I didn’t really grasp what most of them really meant. It was about time to fix that knowledge gap and in the spirit of open-source, I want to share with you a summary of the most popular open-source licenses.</p><p>I hope this helps you out as much as it helped me when you decide on a license for your next (or existing) project.</p><h3>Intro to Licensing</h3><h4>What does it mean to license software?</h4><p>Simply put, a software license is a legal instrument spelling out exactly what can and can’t be done with software. Things like how it can be used, modified, distributed, and more.</p><p>But before that, the fact that a license can be granted on software is possible because all software (at least under United States copyright law) is copyrighted from the moment a work is “fixed”.</p><p>Copyright then, is a form of intellectual property that grants the creators of original work the legal right to decide what happens to it. These aren’t exclusive rights (where you can do absolutely anything you want) because your actions are still limited by copyright law. In this article we’ll look at the granted right to license your software.</p><h4>Why should I even care?</h4><p>Its nice to know why licenses on software exist but what does this have to do with you and why should you care?</p><p>The first and most obvious reason is that a license can help protect you in the case of theft, misuse, or illegal (as per the license) distribution of the software in question.</p><p>For example, if you inadvertently placed an MIT license on your code (or the permissive ISC license that comes default with <em>npm init</em>) you have made it okay for anyone to modify, distribute, or even profit from your work.</p><p>Even if your goal is to have your work spread far and wide with absolutely no restrictions, you are still better off putting a license that explicitly says so because unlicensed software is still fully under copyright and thus protected. What this means is that, legally, no one can use your work without risking repercussions until the software enters Public Domain which takes years.</p><p>You might think then, why not just put it directly into Public Domain, well that comes with it’s own issues. Your best bet is to put a very permissive license like the BSD 0-Clause license.</p><p>It also means that any public repository on Github without a license (yours or not) isn’t actually free to use even if the code is visible because of copyright.</p><h4>What can I do then?</h4><p>As with everything legal, things can get complicated pretty fast. In order to help simplify things we’re going to look at some of the most common software licenses to see what they allow and what they forbid.</p><p>The moral of the story though is this: Whenever you can, do put an actual official license or at the very least mention it by name.</p><h3>Licenses</h3><h4>MIT (and ISC)</h4><p>Probably the one you’ve seen the most, this is one of the most permissive licenses you can place on software.<br>It pretty much says that you can do anything you want with the software without any issues, the only thing asked of you is to include a copy of the original copyright and license notice with every copy of the software.</p><p>The ISC license is essentially the same as the MIT one but without the clauses made unnecessary by the <a href="https://en.wikipedia.org/wiki/Berne_Convention">Berne Convention</a>.</p><p>A lot of famous software use this license such as: Node.js, Vuejs, SQLAlchemy, Ruby on Rails, and many more.</p><p><a href="https://opensource.org/licenses/MIT">The MIT License</a></p><h4><strong>Apache License 2.0</strong></h4><p>Another very permissive license that lets you do almost anything you want with the original work.</p><p>It does still have a few requirements:</p><ul><li>Unmodified parts must still have the same Apache 2.0 license</li><li>In already licensed files, all original copyright, patent, trademark, and attribution notices must be kept*</li><li>If you make significant changes to licensed files, you must state what these changes are</li></ul><p>Additionally, with this license you aren’t allowed to use the original trademark (logo, contributor names, etc.) to endorse and promote your own software.</p><p>*As of version 2.0, it is allowed to include the license by reference instead of having it in every file.</p><p><a href="https://www.apache.org/licenses/LICENSE-2.0">Apache License, Version 2.0</a></p><h4>BSD Licenses</h4><p>Unlike the others, BSD is both it’s own license and a family of licenses which allow different levels of freedom.</p><p><strong>3-Clause<br></strong>The most common version is the 3-clause license also known as “BSD License 2.0” or “Revised BSD License”.<br>This version of the license allows unlimited redistribution for whatever purpose as long as you leave the copyright notices and the license’s warranty disclaimers.<br>Similar to the Apache license, there is a restriction on using the names of contributors for promotion and endorsement without specific permission.</p><p><strong>2-Clause aka FreeBSD License<br></strong>The main difference between this version and the 3-clause is the omission of the non-endorsement clause. The 2-clause version is pretty much equivalent to the ISC license.</p><p><strong>0-Clause<br></strong>The most permissive license possible, this version lets you do anything you want with the software and doesn’t even require that the copyright notice or license be kept in either the source code or binary.</p><p><a href="https://en.wikipedia.org/wiki/BSD_licenses">BSD licenses - Wikipedia</a></p><h4>GNU General Public License</h4><p>The GNU set of licenses were originally developed with/for the GNU project which aims to let computer users have the complete freedom to do whatever they through the development of software that offers 4 essential freedoms:</p><ul><li>Run the program</li><li>Study and change the program in source code form</li><li>Redistribute exact copies</li><li>Distribute modified versions</li></ul><p><a href="https://www.gnu.org/philosophy/philosophy.html">Philosophy of the GNU Project - GNU Project - Free Software Foundation</a></p><p>An important particularity of GPL licenses is that they are copyleft. This means that in addition to offering you the right to do what you want with the software, any derivative work must be distributed with the same license. This serves to guarantee the continued freedom of the software.</p><p>There are 3 main types of the license that you may find. GPL versions 2 and 3, and the Lesser GPL.</p><p>Both versions 2 and 3 require that you keep track of changes made as well as bundle the software with build and install instructions.</p><p>The Lesser General Public License (LGPL) is generally intended for libraries, with it, derived worked must still keep the same license but applications that use LGPL software don’t have to be under the same license themselves.</p><ul><li><a href="https://www.gnu.org/manual/blurbs.html">GNU Package Blurbs - GNU Project - Free Software Foundation</a></li><li><a href="https://www.gnu.org/licenses/licenses.html">Licenses - GNU Project - Free Software Foundation</a></li></ul><h3>Conclusion</h3><p>This covers a few of the more common open source licenses that you may find while going through code. It is certainly not an exhaustive list and I really recommend you look into the different licenses available as there might be another one that better suits your needs.</p><p>Either ways, I hope you now feel more informed about software licenses and will be more confident about licensing your own work.</p><p>For a digestible look into more licenses I really recommend tl;drLegal.</p><p><a href="https://tldrlegal.com/licenses/browse">Browse Licenses - TLDRLegal</a></p><h3>Disclaimer</h3><p>None of the information in this article is legal advice.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ed7c792299d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make Your Vue App Last with IndexedDB]]></title>
            <link>https://medium.com/@mntlmaxi/make-your-vue-app-last-with-indexeddb-66f02708830e?source=rss-ef6729d722c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/66f02708830e</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Maximilien Monteil]]></dc:creator>
            <pubDate>Sun, 10 Feb 2019 21:01:54 GMT</pubDate>
            <atom:updated>2020-09-12T18:41:18.545Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<h3>How to Add Client-Side Storage with Vue Part 2</h3><h4>Take client-side storage to the next level with IndexedDB!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PKKYbWsXaLbBUCNz" /><figcaption>Photo by <a href="https://unsplash.com/@steve_j?utm_source=medium&amp;utm_medium=referral">Steve Johnson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Taking things further</h3><p>In my <a href="https://medium.com/@mntlmaxi/how-to-add-client-side-storage-with-vue-c6c72c301f23">previous post</a> we took our Todo list application and upgraded it with support for client-side storage using the localStorage API.</p><p>We then went a step further and added Vuex to the app. This let us separate concerns even more and make our storage solution very modular.</p><p>In this article, we will once again move forward with our Todo app and implement client-side storage with IndexedDB.</p><p>IndexedDB is a lower level client than localStorage but it can store significant amounts of data. Now none of these might sound beneficial for our app, after all it is a very simple todo list, but in this series, we’re in the business of over engineering, additionally one future idea could be to turn this into a PWA which will require the use of IndexedDB.</p><p>By the end of the article, we’ll modify the app to default to using IndexedDB for storage and fallback to localStorage if the browser doesn’t support it or there was some error.</p><h3>IndexedDB overview</h3><p>IndexedDB is the API to use for client-side storage if you want to store complex data, files, or even blobs in the browser. If we one day want to turn our app into a PWA, we need to have storage implemented using IndexedDB.</p><p>The way this database works is completely different from localStorage and comes with some extra complexity. It is a transaction based database system that is described by MDN as a JavaScript-based object-oriented database.</p><p>What this means is that data isn’t stored in a table with rows and columns as with SQL-based RDBMS but rather with JavaScript objects that are accessible/indexed with a key.</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API">Find out more at MDN</a></p><h4>Old School DB</h4><p>I described IndexedDB as being transaction based and this has huge ramifications on how we work with it.</p><p>Modifying elements in the database first means creating a transaction and making a request to do the operation. We then need to listen for the right kind of DOM event.</p><p>In today’s JavaScript landscape this method of interaction might seem rather clunky, we expect to instead be dealing with promises. Luckily there’s a library by Jake Archibald that wraps up IndexedDB with promises.</p><p><a href="https://github.com/jakearchibald/idb">jakearchibald/idb</a></p><h4>IndexedDB Concepts</h4><p>IndexedDB works in a rather different way from other database systems, before continuing here are a few terms and what they mean in this context.</p><ul><li>Database — First level of IndexedDB, this is where all the object stores are kept. You can create as many databases as you want but usually a single one per app is sufficient.</li><li>Transaction — Every action in IndexedDB works through a transaction. In order to access any action you’ll first need to create a transaction off of which you will then listen for events on completion. They are useful to maintain the integrity, if one of the operation fails, the whole action is cancelled. The idb library wraps these up in promises (among other things).</li><li>Object Store — Object stores are similar to tables or relations in traditional relational databases. Each is meant to hold one kind of entity. For our app we’ll make two stores, one for “Todos” and one for “Completed” todos.</li></ul><p>There are a few other concepts to know when working with IndexedDB but these are the ones we’ll use for the project.</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB">IndexedDB concepts at MDN</a></p><h3>Setup</h3><p>If you want to follow along clone the vuexRefactor branch from the git repo with the following command:</p><pre>$ git clone -b vuexRefactor --single-branch <a href="https://github.com/MaxMonteil/VueTodo.git">https://github.com/MaxMonteil/VueTodo.git</a></pre><p>The final project is available from the indexedDB branch.</p><pre>$ git clone -b indexedDB --single-branch <a href="https://github.com/MaxMonteil/VueTodo.git">https://github.com/MaxMonteil/VueTodo.git</a></pre><p>Next install idb to make it easier to work with IndexedDB.</p><pre>$ npm install idb</pre><p>Once your app first creates a database on your browser it won’t change unless you update the version or delete it. Instead of dealing with versions while you’re still setting it up, you might prefer to delete the whole database and then reload the page.</p><p>To do that in Chrome, go into the developer console in the ‘Application’ tab, click on IndexedDB and then you should see the database name you chose. There you can delete or refresh the database.</p><h3>Initializing IndexedDB</h3><p>Create a new indexedDBService.js file in the api/ folder.</p><p>The first thing to do is to create our database and it’s object stores.</p><p>You’ll see that we first check if the browser supports IndexedDB, if it doesn’t we return an error that we will deal with later in the Vuex store.</p><p>The openDbmethod takes the name of the database, the version, and a callback that will initialize the database and define the schemas.</p><p>What the version does isn’t particularly useful for our small app but it helps ensure our application database is up to date, it is also the only point in time when it is possible to update or change it’s schema.</p><p>* Since writing this article idb has had a new update that changes the function names from *Db to *DB so it’s openDB now. Thank you Willy Kurmann for noticing!</p><p><a href="https://github.com/jakearchibald/idb/blob/master/changes.md#opening-a-database">jakearchibald/idb</a></p><pre>// if installed from npm use &#39;openDB&#39;<br>import { openDb } from ‘idb’</pre><pre>const dbPromise = _ =&gt; {<br>  if (!(‘indexedDB’ in window)) {<br>    throw new Error(‘Browser does not support IndexedDB’)<br>  }</pre><pre>  // if installed from npm use &#39;openDB&#39;<br>  return openDb(‘VueTodoDB’, 1, upgradeDb =&gt; {<br>    if (!upgradeDb.objectStoreNames.contains(‘todos’)) {<br>      upgradeDb.createObjectStore(‘todos’)<br>    }</pre><pre>    if (!upgradeDb.objectStoreNames.contains(‘completed’)) {<br>      upgradeDb.createObjectStore(‘completed’)<br>    }<br>  })<br>}</pre><h3>Managing Data</h3><p>In the previous version of the app where we used localStorage, we had two methods, one to save data to storage and another to check storage aptly named checkStorage and saveToStorage respectively.</p><p>To benefit from this modularity we want to make sure we export the same methods, let’s implement them.</p><h4>Saving to Storage</h4><p>To save to storage we’ll just do as we did with localStorage by overwriting storage since our data is very simple. We use the put method instead of add, this lets us create new items but also overwrite them.</p><p>We also get to see transactions in action.</p><p>First off, we can only call the put method off of a transaction object as they’re in charge of managing IndexedDB operations.</p><p>Lastly it’s the transaction that we actually return in a promise which will resolve when the operation completes, either successfully or not.</p><pre>const saveToStorage = async (storeName, tasks) =&gt; {<br>  try {<br>    const db = await dbPromise()<br>    const tx = db.transaction(storeName, ‘readwrite’)<br>    const store = tx.objectStore(storeName)</pre><pre>    store.put(tasks, storeName)</pre><pre>    return tx.complete<br>  } catch (error) {<br>    return error<br>  }<br>}</pre><h4>Checking Storage</h4><pre>const checkStorage = async storeName =&gt; {<br>  try {<br>    const db = await dbPromise()<br>    const tx = db.transaction(storeName, ‘readonly’)<br>    const store = tx.objectStore(storeName)</pre><pre>    return store.get(storeName)<br>  } catch (error) {<br>    return error<br>  }<br>}</pre><p>This function is simply going to get the data from the object store we created earlier, since we just overwrite it each time there’s no need for an index.</p><p>Finally don’t forget to export both functions.</p><pre><em>export</em> <em>default</em> {<br>  checkStorage,<br>  saveToStorage<br>}</pre><h3>Making it all work</h3><p>We’ve now set up IndexedDB in it’s own service file, we just need to link it up with our Vuex store.</p><p>The goal here is to add IndexedDB as our main storage solution and use localStorage as a fallback. We’ll rewrite our store checkStorage and saveTodos methods.</p><pre>import ls from ‘./api/localStorageService’<br>import idbs from ‘./api/indexedDBService’</pre><pre>export default new Vuex.Store({<br>  actions: {<br>    checkStorage ({ state, commit }) {<br>      state.dataFields.forEach(async field =&gt; {<br>        try {<br>          let data = await idbs.checkStorage(field)</pre><pre>          // IndexedDB did not find the data, try localStorage<br>          if (data === undefined) data = ls.checkStorage(field)</pre><pre>          // LocalStorage did not find the data, reset it<br>          if (data === null) data = []</pre><pre>          commit(‘setState’, { field, data })<br>        } catch (e) {<br>          // The value in storage was invalid or corrupt so just set it to blank<br>          commit(‘setState’, { field, data: [] })<br>        }<br>      })<br>    },<br>    async saveTodos ({ state }) {<br>      try {<br>        await Promise.all(state.dataFields.map(field =&gt; {<br>          return idbs.saveToStorage(field, state[field]))<br>        })<br>      } catch (e) {<br>        state.dataFields.forEach(field =&gt; {<br>          return ls.saveToStorage(field, state[field])<br>        })<br>      }<br>    }<br>  }<br>})</pre><p>Now we get to see the benefits of using Vuex and separating concerns. No changes needed to be made to our Vue components and the changes we made to the store were only to enable the use of both storage options.</p><p>No matter how simple your application is, a proper architecture can save you hours of trouble, effort, and pain.</p><h3>Bringing it all Together</h3><p>We’re done!</p><p>Now our app can use 2 different client-side storage solutions depending on what the browser supports.</p><p>If you’re on your way to building a PWA or need a client-side storage option for more complex data I hope this guide has helped you get started. If you want to learn more check out these resources:</p><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API">MDN</a></li><li><a href="https://developers.google.com/web/ilt/pwa/working-with-indexeddb">Google Web for Developers</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66f02708830e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Add Client-Side Storage with Vue]]></title>
            <link>https://medium.com/@mntlmaxi/how-to-add-client-side-storage-with-vue-c6c72c301f23?source=rss-ef6729d722c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6c72c301f23</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[internet]]></category>
            <dc:creator><![CDATA[Maximilien Monteil]]></dc:creator>
            <pubDate>Wed, 06 Feb 2019 06:06:51 GMT</pubDate>
            <atom:updated>2019-02-11T07:04:48.627Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<h3>Make Your Vue App Last with Local Storage</h3><h4>Keep your user’s data available with or without a connection using Vue and LocalStorage</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DTpDveGP4qJak--_" /><figcaption>Photo by <a href="https://unsplash.com/@rawpixel?utm_source=medium&amp;utm_medium=referral">rawpixel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>No Internet, No Problem</h3><p>The web is undoubtedly an amazing platform enabling people to communicate, share, and experience things in insane ways that weren’t possible until recently. As web-developers, we have the honor of creating such experiences.</p><p>The internet is great but only if you can access it. When you can’t, user’s shouldn’t be permanently deprived of it’s services. One way to solve this is by using Client-Side storage.</p><p>Client-Side storage enables users to access their data even when offline, it also serves the double purpose of speeding up interactions. With data stored locally, your site or app might not even need to send a server request and wait for a response.</p><p>A faster and more practical internet is our goal so let’s look at one way to get there.</p><h3>What we will do</h3><p>In a <a href="https://medium.com/@mntlmaxi/dry-vue-how-to-reuse-and-prepopulate-forms-83068e142c70">previous article</a> we created a ToDo list app, it worked as expected but reloading the page would remove all the tasks we had set. We’re going to look at one method of storing this information on the browser.</p><h3>Client-Side Options</h3><p>There are a few ways to implement client-side storage each with it’s pros and cons.</p><h4>LocalStorage</h4><p>LocalStorage is one of the storage mechanisms in the Web Storage API that allows browsers to store information using key-value pairs. It is best suited for simple data values because it can only store strings. If you have to use LocalStorage for more complicated data you will have to parse it into JSON and back.</p><h4>IndexedDB</h4><p>If you want to store more complex data, files, or even blobs in the browser IndexedDB is what you’re looking for. It is also the database you would need when making a PWA.</p><p>IndexedDB is a transaction based database system that is described by MDN as <em>a JavaScript-based object-oriented database</em>. What this means is that data isn’t stored in table with rows and columns as with SQL-based RDBMS but rather with JavaScript objects that are accessible/indexed with a key.</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API">Read more at MDN</a></p><p>I’ve also written another article where we implement IndexedDB.</p><p><a href="https://medium.com/@mntlmaxi/make-your-vue-app-last-with-indexeddb-66f02708830e">Make Your Vue App Last with IndexedDB</a></p><p>For our ToDo app LocalStorage is more than enough so lets implement it.</p><h3>Setup</h3><p>If you want to follow along git clone the proper todo list branch to get started.</p><pre>$ git clone -b formReuse --single-branch https://github.com/MaxMonteil/VueTodo.git</pre><p>The final project is found at:</p><pre>$ git clone -b localStorage --single-branch https://github.com/MaxMonteil/VueTodo.git</pre><h3>Adding LocalStorage</h3><p>Actually adding localStorage to our todo app is incredibly simple and works in two steps.</p><p>The first step is to check localStorage for already exisiting data with which to fill our component (aka Read), the second step is to save the state of our todos into localStorage (aka Write).</p><p>To do this, we will use two of the methods offered by the localStorage API, getItem and setItem.</p><h4>Reading from Storage</h4><p>In order load data into the component at the right moment, we will hook into the component lifecycle using mounted.</p><p>There, we check if localStorage has values associated with the ‘todos’ and ‘completed’ keys, it makes sense to use the key names as we do in our component data. We can actually take it a step further and have an extra value called dataFields which would hold the name of any future values we would like to store on the client.</p><p>In our checkStorage method we assume that any error means the data is corrupted and we can then simply remove it.</p><p>Another thing to keep in mind is that localStorage only accepts string values, for arrays and objects, we need to parse the data into JSON and back.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5ce4165c73e17b5f22b1d8a0a5be09e/href">https://medium.com/media/b5ce4165c73e17b5f22b1d8a0a5be09e/href</a></iframe><h4>Writing to Storage</h4><p>Saving our todos is just as simple.</p><p>We will create a saveTodos method that will go through our useful dataFields array, stringify the data and store it.</p><p>What about edits?</p><p>To be aware that a todo has been edited we also need to emit an event from the ListItem component and listen to it in TodoList.</p><p>With that, all we need to do is call the method whenever we add, delete, edit, or complete a todo!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5808725d9cb3e7b4d4d44b7983512fd5/href">https://medium.com/media/5808725d9cb3e7b4d4d44b7983512fd5/href</a></iframe><h3>Taking things further</h3><p>Now our todo app has persistent data, you can try it out by adding some tasks and reloading the page, you’ll see that they’re still present.</p><p>Making it work is only the start. There are actually a few extra things we could do to help make our app more maintainable, they might not make sense for a simple app such as this but in larger programs it is critical.</p><p>One thing to do is to decouple our obvious dependency on localStorage. Currently all the storage related code is right inside the component, if we ever want to switch to using IndexedDB it would require quite a bit of rewriting, it gets even worse if you also want to add calls to a server where more data is stored.</p><h4>Refactor refactor refactor</h4><p>The first thing we will do is add Vuex to our app. It isn’t absolutely necessary but it does set us up for whatever future changes we might go through. Vuex will help us separate concerns even more by ensuring components only deal with the data and actions that directly concern them.</p><p>Add vuex to the app with</p><pre>$ vue add vuex</pre><p>Next we move the state and every method changing it from our component to the store.</p><p>The way I usually work with Vuex is to only dispatch actions from components. In the store these actions will then manage calls to mutations or other actions. To make this as practical as possible, I try to make my mutations simple and atomic so it often happens that an action will call a mutation multiple times with different arguments. This works well since mutations are meant to only directly change the state and finish rather fast.</p><p>Of course this is just how I personally use it, with an application as simple as ours you can skip using actions all together.</p><h4>Abstract abstract abstract</h4><p>The next step is to reduce our dependence on LocalStorage, or at least make it as painless as possible to change or even switch away from it.</p><p>To do that we’ll create an api/ folder with a localStorageService.js file. There we place all calls to localStorage from the store.</p><p>The advantage of this is whenever we want to change how localStorage behaves we can just make changes there, even better, if we decide to use something else, the other option only needs to export functions with the same signature.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7da5f0c365e2ae8f44bb13c1d63f4b77/href">https://medium.com/media/7da5f0c365e2ae8f44bb13c1d63f4b77/href</a></iframe><p>You can get the code for that from this branch:</p><pre>$ git clone -b vuexRefactor--single-branch https://github.com/MaxMonteil/VueTodo.git</pre><h3>Conclusion</h3><p>We’ve updated our todo app to now keep it’s state saved even if the page reloads or if the user leaves and returns to it later. This also has the added benefit of not needing to make calls to a server each time the page loads.</p><p>Even more than that, we started future-proofing the app for future updates, our client-side storage option is super modular and components are nicely compartmentalized.</p><p>Hopefully this helped you out in your own projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6c72c301f23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[21st Century Journaling for Developers]]></title>
            <link>https://medium.com/@mntlmaxi/21st-century-journaling-for-developers-f3a1c2a8eb4e?source=rss-ef6729d722c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3a1c2a8eb4e</guid>
            <category><![CDATA[journaling]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[vim]]></category>
            <dc:creator><![CDATA[Maximilien Monteil]]></dc:creator>
            <pubDate>Sun, 27 Jan 2019 11:32:46 GMT</pubDate>
            <atom:updated>2019-01-27T11:32:46.231Z</atom:updated>
            <content:encoded><![CDATA[<h4>Pen and paper worked so well because they never got in your way, let’s assemble a version for today.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-FvbwM0qkZsF_5s1" /><figcaption>Photo by <a href="https://unsplash.com/@alejandroescamilla?utm_source=medium&amp;utm_medium=referral">Alejandro Escamilla</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Why even journal?</h3><p>I can’t make you start journaling regularly but I would like you to at least consider this amazing habit that you might have been missing out on.</p><p>Personally, I journal every day because my mind often feels like a jumbled mess and taking things out onto a structured format helps me organize myself and my day. I have had times when I had to face complex thoughts and emotions, for most of my life I advocated just sitting down and thinking things through but it didn’t always suffice.</p><p>This article is aimed at developers only because of the proposed solution. Just as you might not be able to model entire programs in your head, so it is for the mind. There comes a point where software becomes complex enough that you need other tools to reason about it, same goes for the mind which could arguably be considered as complex software.</p><h3>What does the right journal need?</h3><p>When I started journaling I used whatever pen and a booklet I had on hand. It actually worked great as an unconstrained medium to write in but there were logistical problems. Booklets started to pile up, it was impossible to accurately locate an entry, and to be honest my handwriting is horrible, especially when trying to write at the speed of thought.</p><p>I then moved to using Google Docs but that required internet an connection and too many steps outside of my workflow to get started. My last attempt was to use a dedicated journaling app for Windows called Glimpses. That one worked great for a very long time and really cemented my journaling habit but eventually it failed. It had some issues with syncing and I always had to boot back into Windows to write.</p><h4>The dev life</h4><p>My journaling needed the kind of flexibility I had with pen and paper while still being highly structured. My first thought was to make my own program but I never got around to it, instead I found a tool to which I added more tools, and now I have a veritable tool belt that hits all the nails:</p><ul><li>Cross platform (Linux/Windows)</li><li>Flexible</li><li>Easily to insert into my current workflow</li><li>Minimalist</li><li>Upgradeable and extensible</li></ul><p>I found this in an open source terminal application called <em>jrnl</em>, paired with a few aliases, Vim (or whatever you want), and many plugins, it’s as close to perfect as I’ve found.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1k2mlPNgtqSoDk66TXXmjQ.png" /><figcaption>Clean and minimal journaling environment 👌</figcaption></figure><h3>The case for Bash</h3><p>When I first started using Linux, I found the terminal to be an archaic and clunky option that never really understood what I wanted to do. Today when I boot into Windows, the thought of actually navigating the explorer <em>with a mouse</em> gives me shudders of inefficiency.</p><p>Now, the first thing I do in Linux, is open a terminal and check for updates, it’s a reflex, a habit, and thus the best place to add another action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O-moO3vUViNrP654PYX-bw.png" /><figcaption>It might seem scary at first but it becomes a second home.</figcaption></figure><p>Now, I log in, check for updates, open another terminal and start journaling as they run.</p><p>Here’s how you can set this up for yourself.</p><h3>Install jrnl</h3><p>Go to their <a href="http://jrnl.sh/installation.html">website</a> and follow their installation instructions, if you are installing jrnl with pip and it doesn’t work, <strong>do not use sudo</strong>, instead try with the --user flag.</p><p>Once that is done we have a few config files to work on.</p><h4>jrnl Config</h4><p>In your home directory create a file named .jrnl_config. If you are on Windows place it at C:\Users\[Your Username]\.jrnl_config.</p><p>In it place the following:</p><pre>.jrnl_config</pre><pre>{<br>    “journals”: {<br>        “default”: {<br>            “journal”: “/mnt/HDD/Documents/journal/journal.txt”,<br>            “encrypt”: true<br>        }<br>    },<br>    “editor”: “vim +Wrap +Goyo +EndOfLine”,<br>    “encrypt”: false,<br>    “default_hour”: 9,<br>    “default_minute”: 0,<br>    “timeformat”: “%a, %d %b %Y %H:%M”,<br>    “tagsymbols”: “@”,<br>    “highlight”: true,<br>    “linewrap”: 120<br>}</pre><p>These are my personal settings and will most likely be different based on your setup. For example I have a common hard drive that I use in each OS so that’s where I’m placing my journal, I also preferred a different date-time format.</p><p>One current downside is that it has to be a .txt file, personally I’d like to be able to have different formats like markdown.</p><p>For the ”editor” setting we have the command to run with our chosen editor, in this case Vim, we’ll go over the other arguments next.</p><h3>Vim Configuration</h3><p>How you choose to configure Vim can be a very personal thing.</p><p>Therefore what I recommend here is just that, my chosen ways to create a super minimalist and focused writing environment for journaling.</p><p>Our plugins and commands will ensure this line in jrnl_config works:</p><p>”editor”: “vim +Wrap +Goyo +EndOfLine”</p><h4>Wrap</h4><p>When writing in vim, long lines will not wrap how you might expect them to, this command will enable ‘normal’ wrapping.</p><p>command! -nargs=* Wrap set wrap linebreak nolist</p><p>Use it with :Wrap.</p><p>Source: <a href="http://vimcasts.org/episodes/soft-wrapping-text/">Vimcasts</a></p><h4>Goyo</h4><p>This one is actually 2 vim Plugins, Goyo and Limelight.</p><p>Goyo enables distraction free margins while Limelight offers ‘hyperfocus-writing’.</p><p>These are vim plugins so make sure you have a plugin manager installed, if you don’t know which you can use <a href="https://github.com/VundleVim/Vundle.vim">Vundle</a>.</p><ul><li><a href="https://github.com/junegunn/goyo.vim">GitHub - junegunn/goyo.vim: :tulip: Distraction-free writing in Vim</a></li><li><a href="https://github.com/junegunn/limelight.vim">GitHub - junegunn/limelight.vim: :flashlight: All the world&#39;s indeed a stage and we are merely players</a></li></ul><p>After enabling them in your .vimrc, we need to add a few changes to ensure they work perfectly. We want Goyo and Limelight to be enabled at the same time and, due to a quirk of Goyo, make sure that quitting vim completely quits.</p><pre>.vimrc</pre><pre>“ Goyo Config<br>“ 120 is a subjective value that I like<br>let g:goyo_width = 120</pre><pre>“ Ensure :q to quit even when Goyo is active<br>function! s:goyo_enter()<br>    execute ‘Limelight’<br>    let b:quitting = 0<br>    let b:quitting_bang = 0<br>    autocmd QuitPre &lt;buffer&gt; let b:quitting = 1<br>    cabbrev &lt;buffer&gt; q! let b:quitting_bang = 1 &lt;bar&gt; q!<br>endfunction</pre><pre>function! s:goyo_leave()<br>    execute ‘Limelight!’<br>    “ Quit Vim if this is the only remaining buffer<br>    if b:quitting &amp;&amp; len(filter(range(1, bufnr(‘$’)), ‘buflisted(v:val)’)) == 1<br>        if b:quitting_bang<br>            qa!<br>        else<br>            qa<br>        endif<br>    endif<br>endfunction</pre><p>Source: <a href="https://github.com/junegunn/goyo.vim/issues/16#issuecomment-39919692">Github</a><br>I just added the Limelight execution.</p><h4>EndOfLine</h4><p>This is simply a normal Vim command that I needed to be able to give it as a flag to the vim launching command. You’ll see the use for this when we look at jrnl templates.</p><p>command EndOfLine normal! $</p><h3>jrnl Extras</h3><p>We now have jrnl and our editor configured for an excellent journaling experience but you might be looking to take it a bit further, here are 2 extra things you can do.</p><h4>jrnl Templates</h4><p>When journaling, even though you might want complete freedom, it sometimes helps to have some structure.</p><p>The way to do this with jrnl is by importing a file as an entry which we then use as our template. These could be questions or goals you always end up writing when journaling or things you want to make sure you think about like listing 3 things you were thankful for or what goals you want to focus on today.</p><p>Now while jrnl doesn’t directly support templates, it makes a new entry with a template that you then need to reopen and edit. I’ve enabled this with a bash alias, one for the morning and one for the evening. This depends on how your template is set up.</p><pre>.bashrc</pre><pre>alias jrnlm=’jrnl &lt; path/to/template/file.txt &amp;&amp; jrnl -1 --edit’<br>alias jrnle=’jrnl -on today --edit’</pre><p>The EndOfLine argument when launching Vim will ensure our cursor is at the right place to then write our entry’s title. If you don’t use templates then it isn’t necessary.</p><h4>Journal Exporting</h4><p>Journals are a rather static format, once written you’re not meant to go back and change things, what would be nice is to then export our entries to a PDF. We’ll write a bash function to do this it could then be called regularly with a Cronjob and create a PDF library of your journal.</p><p>This particular function assumes you write your .txt files with markdown syntax and that you have pandoc installed to manage the markdown to PDF transformation.</p><pre>.bashrc</pre><pre>function exportJrnl { jrnl — export markdown | pandoc --pdf-engine=xelatex -s -o “$1”; }</pre><p>As an argument, the function takes the name and/or path to export the journal and will turn the whole journal into a PDF. You can change the jrnl flags to only get the entries of the past year or month.</p><h3>Conclusion</h3><p>I can’t make you start journaling but I hope this at least gives you an incentive to try it out. If you were already interested but couldn’t find a way to fit it into your existing workflow hopefully this method will inspire you.</p><p>Journaling is honestly fun and incredibly helpful, but for developers today I think that’s not enough, we also need to be able to tinker and apply our own personal touches, with this setup there really are no limits to what you can do.</p><p>Cheers and happy journaling!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3a1c2a8eb4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DRY Vue: How to Reuse and Prepopulate forms]]></title>
            <link>https://medium.com/@mntlmaxi/dry-vue-how-to-reuse-and-prepopulate-forms-83068e142c70?source=rss-ef6729d722c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/83068e142c70</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Maximilien Monteil]]></dc:creator>
            <pubDate>Mon, 14 Jan 2019 10:23:01 GMT</pubDate>
            <atom:updated>2019-02-06T05:30:59.183Z</atom:updated>
            <content:encoded><![CDATA[<h3>DRY Vue: How to Reuse and Prepopulate Forms</h3><h4>Good code is DRY, good UX is simple. Forms appear all over but how can we reuse them in Vue?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DNi0xRUxDSwOVYF2" /><figcaption>Photo by <a href="https://unsplash.com/@zanonluca?utm_source=medium&amp;utm_medium=referral">Luca Zanon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A project I’m currently working on uses forms quite liberally. There are different forms for each element type that a user can create (4) and another one when editing these same elements.</p><p>As I was designing these views I immediately knew that both creation and editing should use the exact same form. From a UX stand point it makes sense, your user has just used a form to create an element, editing it shouldn’t require learning a new form.</p><p>That’s where the problem begins. In Adobe XD, reusing a form is a simple as copy-pasting it, but in Vue how could I reuse the same component? More importantly, how could I prepopulate a form with the data of the element to edit?</p><p>Intense web searches didn’t help me find an answer so here I am sharing what worked for me in the hopes that it can help others facing the same problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*VriGd17edR_Z5wRb5VN23g.png" /><figcaption>What we will be making, notice the first todo being edited</figcaption></figure><h3>Setup</h3><p>We will setup a really basic todo list app to give us a form that we can then reuse and prepopulate. Yes, I know, another todo list app but stay with me, the todo part only serves as container for the really juicy code.</p><p>I’ve set up a basic Todo List with Vue if you want to follow along, clone it with this command:</p><pre>$ git clone -b basicTodoList --single-branch <a href="https://github.com/MaxMonteil/VueFormReuse.git">https://github.com/MaxMonteil/VueTodo.gi</a>t</pre><p>Otherwise get the whole project from the formReuse branch:</p><pre>$ git clone -b formReuse --single-branch <a href="https://github.com/MaxMonteil/VueFormReuse.git">https://github.com/MaxMonteil/VueTodo.git</a></pre><p>Once cloned, you can run it locally with</p><pre>$ npm install<br>$ npm run serve</pre><h3>Displaying the Form</h3><p>The first thing we’ll want to do is create an entry point for our <em>creation</em> form to appear.</p><p>Depending on your situation, there are quite a few options of where you’d want your form to reappear. For example, in a more involved application with a more complex form, a modal might make a lot more sense.</p><p>If that’s the case for you check out portal-vue, it isn’t absolutely necessary but it might help simplify your code.</p><p><a href="https://github.com/LinusBorg/portal-vue">LinusBorg/portal-vue</a></p><p>In our case, we are going to have the form appear inside the ListItem component directly, thus replacing the current content.</p><p>To toggle whether we show the form or the content, we will add an editing field to our component’s data.</p><pre>ListItem.vue</pre><pre>  &lt;template&gt;<br>    &lt;li class=&quot;todo-item&quot; :class=&quot;{ completed: isCompleted }&quot;&gt;<br>+     &lt;div class=&quot;todo-content&quot; v-if=&quot;!editing&quot;&gt;<br>        &lt;p&gt;{{ todo.priority }} | {{ todo.title }}&lt;/p&gt;<br>        &lt;span&gt;<br>          ...<br>+         &lt;button @click=&quot;editTodo&quot; v-if=&quot;!editing&quot;&gt;<br>        &lt;/span&gt;<br>+     &lt;/div&gt;</pre><pre>+     &lt;todo-form v-else/&gt;<br>    &lt;/li&gt;<br>  &lt;/template&gt;</pre><pre>  &lt;script&gt;<br>+ import TodoForm from &#39;./TodoForm.vue&#39;<br>  <br>  export default {<br>    name: &#39;ListItem&#39;,<br>    components: {<br>+     TodoForm<br>    },<br>    data () {<br>      return {<br>+       editing: false<br>      }<br>    },<br>    methods: {<br>+     editTodo () {<br>+       this.editing = !this.editing<br>+     }<br>    }<br>   }<br>  &lt;/script&gt;</pre><p>Note that we will also need to move a few CSS styles around.</p><h3>Toggling the Form</h3><p>We have the editing field in our ListItem component but that is only one half of the equation because we still can’t close it. To close the form we will need something like a cancel button but that belongs in the form component itself, not the list item.</p><p>To do this, our form needs to know whether it is being displayed to edit or to create a todo.</p><p>We will use our very important populateWith prop which defaults to an object with an ‘empty’ property.</p><p>You could have it be a literal empty object but I feel it helps to explicitly state what we consider ‘empty’, it also massively simplifies the whole process of checking whether said object is empty or not.</p><p>Note that we can’t have an object as the default value, it must instead be returned by a function.</p><pre>TodoForm.vue</pre><pre>  &lt;template&gt;<br>    &lt;form @submit.prevent=&quot;submit&quot; id=&quot;todo-form&quot;&gt;<br>      ...<br>+     &lt;button @click=&quot;close&quot; v-if=&quot;!populateWith.empty&quot;&gt;X&lt;/button<br>    &lt;/form&gt;<br>  &lt;/template&gt;</pre><pre>  &lt;script&gt;<br>  export default {<br>    name: &#39;TodoForm&#39;,<br>+   props: {<br>+     populateWith: {<br>+       type: Object,<br>+       default: () =&gt; ({ empty: true })<br>+     }<br>+   },<br>+   methods: {<br>+     close () {<br>+       this.$emit(&#39;close&#39;)<br>+     }<br>    }<br>   }<br>  &lt;/script&gt;</pre><pre><br>ListItem.vue</pre><pre>      &lt;todo-form<br>        v-else<br>+       @close=&quot;editTodo&quot;/&gt;</pre><p>Now, if the object is empty, that means the form is being used to <em>create</em> a todo, otherwise it is being used to <em>edit</em> one and we can show our cancel button.<br>This button will then emit to our ListItem thus toggling our editing property and hiding the form.</p><h3>Populating the Form</h3><p>Next we need to supply our form with the data it needs to populate itself.<br>From our ListItem component, all we need to do is pass the todo object through the populateWith prop to our form.<br>This works out well for us as the empty property will now be undefined which is falsy.</p><pre>ListItem.vue</pre><pre>      &lt;todo-form<br>        v-else<br>+       :populateWith=&quot;todo&quot;<br>        @close=&quot;editTodo&quot;/&gt;</pre><p>To then ensure our form populates itself at the right moment, we will hook into the component’s lifecycle with the created() method and overwrite the component’s data.</p><pre>TodoForm.vue</pre><pre>  &lt;script&gt;<br>  export default {<br>+   created () {<br>+     if (!this.populateWith.empty) {<br>+       this.todo = this.populateWith<br>+     }<br>+   }<br>  }<br>  &lt;/script&gt;</pre><p>Here our object is very simple and an assignment statement is all you need. With more complex objects, especially with the way v-model works as well as how Vue manages reactivity you might have to use more involved methods to copy the object.</p><p>One method that could work for you is to stringify then parse the object.</p><pre>this.todo = JSON.parse(JSON.stringify(this.populateWith))</pre><p>If your object is more complicated, is deeply nested, or has a circular structure, this might not work, you will have to make a deep copy.</p><p>The last thing to do is make sure that the form closes once the user submits their edits which is as simple as calling this.close().</p><h3>Wrap Up</h3><p>We now have a method of reusing forms in vue, thus avoiding repetition. I’ll admit I don’t know if this is the best method to reuse forms but it worked for me and I couldn’t find any other sources explaining this.</p><p>Hopefully it helps solve some of the problems you might be facing.</p><p>Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83068e142c70" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Raspberry Pi + IFTTT: Is There Power at Home?]]></title>
            <link>https://medium.com/@mntlmaxi/raspberry-pi-ifttt-is-there-power-at-home-fc6eab6b6816?source=rss-ef6729d722c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc6eab6b6816</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[dropbox]]></category>
            <dc:creator><![CDATA[Maximilien Monteil]]></dc:creator>
            <pubDate>Sun, 06 Jan 2019 18:54:50 GMT</pubDate>
            <atom:updated>2020-11-24T04:20:53.021Z</atom:updated>
            <content:encoded><![CDATA[<h4>Raspberry Pi, IFTTT, Dropbox, and a Cron Job will answer the question.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cvPeh37jK1HOBU1Q" /><figcaption>Photo by <a href="https://unsplash.com/@_louisreed?utm_source=medium&amp;utm_medium=referral">Louis Reed</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I live in a place where the power cuts regularly. It usually only happens about twice a day and lasts only a few seconds, it’s become part of daily life here, you get used to it.</p><p>But recently, the power went out and stayed out for over 24 hours.</p><p>This has happened a few times before, and each time there’s nothing I can do about it. I have to move to a coffee shop or similar to continue working hoping that by the time I return, the power will be too.</p><p>I’m sure a lot of people face a similar problem, maybe even more often than I do. You’re out and you don’t know when you can come back home, hell you never know if the power went out while you were away.</p><p>I thus wanted to solve this problem with a solution that would let me know when the power is back or just check if it’s on. Let’s get into it!</p><h3>Considerations</h3><p>The idea is that I need something I can plug in at home and communicate with. Once the device is powered on it can check whether or not I asked about the power situation and answer.</p><p>A Raspberry Pi is the perfect, low-power option here, and it’s what I had on hand so we’ll go with that.</p><h4>Communication</h4><p>Next, we need a way to talk to and receive answers from the Raspberry Pi. Not only does it need to be as cheap as possible (preferably free), it must be able to store the message.</p><p>This is important because if the Pi is currently powered off, it has no way of receiving a message and I don’t want to be constantly pinging it until it does.</p><p>Here are a few options I considered:</p><p><strong>Twilio</strong><br>Lets you send and receive SMS messages with their API. It has a free tier but only until you run out of credit. It also can’t store our messages.</p><p><strong>Gmail</strong><br>This option lets us store our messages but it would require every person following this guide to create a new email address. I don’t know if Google would mind, otherwise this is a valid option.</p><p><strong>IFTTT + Dropbox</strong><br>IFTTT offers a bunch of different applets and services that together allow us to both communicate with the Pi and store our messages, all for free (though there are some limitations). This is what we’ll go with.</p><h3>IFTTT Setup</h3><p>If you don’t have one already, the first step is to create an account at IFTTT</p><p><a href="https://ifttt.com/">IFTTT - Automate business &amp; home</a></p><p>In order for us to have two-way communication with our Raspberry Pi, we’re going to need to create two IFTTT applets, a <em>Sender</em> and a <em>Listener</em>. But before making these applets we have to connect our IFTTT account to a few services.</p><p>Head over to <em>My Applets</em> and go to the <em>Services</em> tab. There, we’re going to add the SMS, Dropbox, and Webhooks services. For an SMS free method, connect Google Assistant and Gmail (or even Facebook Messenger) instead of SMS. Of course you can mix and match them as you wish. I’ll explain what each does and how to set them up next.</p><h4>Sender Applet</h4><p>First we will make the applet that allows us to send messages to our Raspberry Pi. The messages won’t be sent directly, instead we want to store them somewhere the Pi can check once it goes online, for that we will use Dropbox.</p><ol><li>Click on <em>New Applet</em> and then on the blue <em>+this</em></li><li>Search for the SMS service and click on it (you can instead add Google Assistant, Gmail, or any other service with you which you can send a message)</li><li>We’ll be choosing the <em>Send IFTTT any SMS </em>option</li><li>Click on the blue +<em>that</em></li><li>Search for the Dropbox service and click on it</li><li>Choose the <em>Append to a text file</em> option</li><li>Fill it out as per the image, you can change the file name and location if you want but keep them in mind</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*PoDHIrqkuQZhRw1jCCA60A.png" /></figure><p>Perfect! Now if you send an SMS to IFTTT (you can get the number in the settings of the SMS service) you should see a new file appear in your Dropbox at the path you gave. Be aware that there is a limit to the number of SMS that IFTTT can send and receive (100 in US and Canada, 10 elsewhere per month).</p><h4>Listener Applet</h4><p>Next we can make the second applet which will let our Raspberry Pi talk to us.</p><ol><li>Just like before, create a new applet but for +<em>this</em> choose Webhooks</li><li>Click on the <em>Receive a web request</em> option</li><li>Give your event a name, I went with <em>there_is_power</em></li><li>For <em>+that</em> I chose SMS as my messaging service</li><li>You can write whatever message you want to receive here or put {{Value1}} if you want our script to decide on the message</li></ol><p>That’s it for IFTTT</p><p>We now have a way to send a message that the Pi can read and a way for it to then communicate with us.</p><p>The next step is to enable the Dropbox API so that our Pi can check for a message.</p><h3>Dropbox Setup</h3><p>First go to the Dropbox App Console and click <em>Create app</em></p><p><a href="https://www.dropbox.com/developers/apps">Login - Dropbox</a></p><p>Fill in the info as below, we’re choosing Dropbox API, Full Dropbox access, and naming our app <em>isTherePower</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ro0f-vtxw3gcjhqR51PQyw.png" /></figure><p>Then, in the Dropbox console, click the <em>Generate</em> button under the Generate access token<em> </em>heading to obtain your token, save it for the next step.</p><h3>Time to Script</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*CjZ1bXHdzfUfQm0o1g4A0w.png" /><figcaption>Yup, that’s part of our script</figcaption></figure><p>Since we’ll be working on a Raspberry Pi, the go to language is Python.</p><p>Clone the project from github to the home directory of your Pi and install it with these commands.</p><pre>$ git clone <a href="https://github.com/MaxMonteil/isTherePower.git">https://github.com/MaxMonteil/isTherePower.git</a><br>$ pipenv install</pre><p>Note that you might need to install git, pip3, and pipenv if you don’t already have them, they’re aren’t obligatory but it makes the process a whole lot simpler.</p><pre>$ sudo apt-get install python3-pip git</pre><pre># if you want to use pipenv<br>$ pip3 install --user pipenv</pre><p>If you’re not using pipenv, install Requests and Dropbox</p><pre>$ pip3 install requests dropbox</pre><h4>The Script</h4><pre>import os<br>import dropbox<br>import requests</pre><pre><br>def main():<br>    folderPath = &#39;/IFTTT/SMS/&#39;<br>    fileName = &#39;is_there_power.txt&#39;</pre><pre>    print(&#39;Connecting to Dropbox...&#39;)  # Instantiate dropbox object<br>    dbx = dropbox.Dropbox(os.environ[&#39;DBX_ACCESS_TOKEN&#39;])</pre><pre>    print(&#39;Searching for message...&#39;)<br>    searchResult = dbx.files_search(folderPath, fileName, max_results=1)</pre><pre>    if len(searchResult.matches) == 1:<br>        print(&#39;Message found! Sending reply...&#39;)<br>        requests.post(&#39;https://maker.ifttt.com/trigger/there_is_power/with/key/&#39;<br>                      + os.environ[&#39;WEBHOOK_KEY&#39;],<br>                      data={&#39;value1&#39;: &#39;Looks like there is power!&#39;})</pre><pre>        # cleanup<br>        print(&#39;Reply sent, cleaning up...&#39;)<br>        dbx.files_delete(folderPath + fileName)<br>        print(&#39;Done!&#39;)</pre><pre>    else:<br>        print(&#39;No message received. Exiting.&#39;)</pre><pre><br>if __name__ == &#39;__main__&#39;:<br>    main()</pre><p>First we import the required packages, here I bring in os because I placed sensitive variables in a .env file in the same directory. If you know you wont be sharing your version of the script, you can remove the import and replace every os.environ[] with your actual information.</p><p>In our main function, we set our folder path and file name according to what we put in the <em>Sender Applet</em>, note that here we do need the file extension.</p><p>Next, we need to prepare our Dropbox object to allow us to interact with the API, this is where you use the Access token you got in the Dropbox Console.</p><p>With this Dropbox object authenticating us, we can check if a message was sent. We do that by searching for our message file, if there is only one result it means a message was sent. This is the reason we chose to append a line in the <em>Sender Applet</em> instead of creating a new file. We don’t read the file but simply check for its existence.</p><p>If a message was sent, we then use our IFTTT Webhook URL to send a POST request. The data we send will be the message that you receive when the Pi answers. Take note if you changed the event name, it is used in this URL.</p><p>Finally, once we’ve sent our reply we can delete the file, this is like the Pi saying it has read your message.</p><p>With this we have the main setup for our script, but next, we want the Raspberry Pi to automatically check for messages at the right moments.</p><h3>Checking for messages on boot</h3><p>The first time we want the Pi to check for messages and answer is right when it boots up, when power returns. The problem with checking right on boot is that the Pi might not yet be connected to your router and even then, it may be connected but not have WiFi access.</p><p>Let’s solve each of these.</p><h4>Wait to Connect to Router</h4><p>First let’s make the Pi run the script only once it has finished connecting to the router.</p><p>We will create a service using systemd to run our script at the right time.</p><pre>pi ~$ sudo systemctl edit --force --full isTherePower.service</pre><p>This opens an editor, write the following.</p><pre>[Unit]<br>Description=If asked, tell the user there is power<br>After=network-online.target</pre><pre>[Service]<br>Type=idle<br>User=pi<br>WorkingDirectory=/home/pi/isTherePower</pre><pre># If using pipenv<br>ExecStart=/home/pi/.local/bin/pipenv run python /home/pi/isTherePower/isTherePower.py</pre><pre># Otherwise<br>ExecStart=/usr/bin/python3 /home/pi/isTherePower/isTherePower.py</pre><pre>[Install]<br>WantedBy=multi-user.target</pre><p>To quit nano and save press CTRL + X then Y then press enter.</p><p>Now let’s check if our new service was added.</p><pre>pi ~$ systemctl status isTherePower.service</pre><p>It should give you back your service’s name, description, and say it is inactive.</p><p>Next we can enable our service with</p><pre>pi ~$ sudo systemctl enable isTherePower.service</pre><p>Finally we can test if it works (if you’ve sent a message to dropbox) by restarting the pi or running:</p><pre>pi ~$ sudo systemctl start isTherePower.service</pre><p>Sources:<br><a href="https://raspberrypi.stackexchange.com/questions/78991/running-a-script-after-an-internet-connection-is-established">https://raspberrypi.stackexchange.com/questions/78991/running-a-script-after-an-internet-connection-is-established</a><br><a href="https://www.raspberrypi-spy.co.uk/2015/10/how-to-autorun-a-python-script-on-boot-using-systemd/">https://www.raspberrypi-spy.co.uk/2015/10/how-to-autorun-a-python-script-on-boot-using-systemd/</a></p><h4>Wait for WiFi</h4><p>We’ve solved the first problem of when to run the script, now we need to make sure that when it runs, the Pi has access to the internet.</p><p>To do that we’ll add a new function that will keep trying to connect to the internet, once it does, we can go ahead with the rest of the program.</p><pre>def wait_for_internet_connection(url=&#39;http://www.example.com&#39;, timeout=3):<br>    print(&#39;Waiting for an internet connection...&#39;)<br>    while True:<br>        try:<br>            requests.head(url, timeout=timeout)<br>            print(&#39;Connection OK&#39;)<br>            return<br>        except requests.ConnectionError:<br>            pass</pre><p>I’m using <a href="http://www.example.com/">www.example.com</a> here as a website that is certain to stay online for the foreseeable future. You could also use <a href="http://www.google.com./">www.google.com.</a></p><p>In the loop we issue a HEAD request because our goal isn’t to receive and download any HTML, that would just slow us down. A HEAD request will just ping the URL and get the headers.</p><p>Of course don’t forget to call our new function before main.</p><pre>if __name__ == &#39;__main__&#39;:<br>    wait_for_internet_connection()<br>    main()</pre><p>With this, we have a program that will alert you whenever the Pi powers on and sees that you’ve sent a message asking about power.</p><p>You could totally stop here but I the Pi to be able to answer even when there was power, otherwise without an answer I might think there was an outage.</p><h3>Checking for messages while powered on</h3><p>There are many ways for the Pi to check if you’ve sent a message. With our setup, that means watching when the <em>is_there_power</em> is created and/or changed.</p><p><strong>Dropbox Webhooks</strong><br>The Dropbox API offers its own Webhooks to alert you when a file or folder changes. I think this would be the best option but you need to allow your Raspberry Pi to be accessible from the internet which my router and ISP do not allow.</p><p><strong>Cron Job</strong><br>Cron allows Linux to run commands or scripts periodically at a given date and time. While not as slick as Webhooks, this allows us to check Dropbox every once in a while and see if you’ve sent a message.</p><h4>Creating a Cron job</h4><p>Cron works by creating jobs. Each is a single line in a file that will run the specified command at every given interval.</p><p>The syntax for a Cron job is as follows</p><pre>* * * * * command to execute<br>- - - - -<br>| | | | |<br>| | | | ----- Day (0 - 7) (Sunday=0 or 7)<br>| | | ------- Month (1 - 12)<br>| | --------- Day of the month (1 - 31)<br>| ----------- Hour (0 - 23)<br>------------- Minute (0 - 59)</pre><p>If you want to learn more about Cron read this article</p><p><a href="https://www.cyberciti.biz/faq/how-do-i-add-jobs-to-cron-under-linux-or-unix-oses/">How To Add Jobs To cron Under Linux or UNIX - nixCraft</a></p><p>For our program, I think every 30 minutes is a reasonable time to check, worst case that amounts to 48 times a day. It does mean that it can take up to 30 minutes for the Pi to answer. It’s totally up to you to find a frequency you like.</p><p>To create (or edit) a Cron job enter:</p><pre>pi ~$ crontab -e</pre><p>You might be prompted to choose an editor, nano is the easiest to use so go with that if you’re not sure.</p><p>At the end of the file, add the following line</p><pre># if using pipenv<br>*/30 * * * * cd /home/pi/isTherePower; /home/pi/.local/bin/pipenv run python isTherePower.py 2&gt;&amp;1</pre><pre># otherwise<br>*/30 * * * * python3 /home/pi/isTherePower.py 2&gt;&amp;1</pre><p>The 2&gt;&amp;1 at the end is to prevent Cron from sending you emails each time it runs a job.</p><p>If you also want to store the print statements of our program into a log add</p><pre>&gt;&gt; /path/to/file/log.txt</pre><p>right after isTherePower.py (including the &gt;&gt;), it will output the print statements to a log.txt file at the path you write.</p><h3>Conclusion</h3><p>And with that our little program is done!</p><p>You’ll never be caught by surprise again by the power situation in your home. We also got to work with a bunch of different services and technologies to create a solution to a problem that is still far too common.</p><h4>Improvements</h4><ul><li>Prevent the Cron job from running constantly in the background if you’re home</li><li>If you can, use Dropbox Webhooks</li><li>Change the text written in dropbox to also include the time</li><li>Let the Pi keep a log of when the power cuts</li><li>Use Telegram for both messaging and storing</li><li>Try out different IFTTT services</li></ul><p>Thank you for reading!</p><p>Leave any comments and suggestions you may have!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc6eab6b6816" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>