<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Ziga Brencic</title>
    <description>The latest articles on DEV Community by Ziga Brencic (@zigabrencic).</description>
    <link>https://dev.to/zigabrencic</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F280564%2Fad43cdc1-db47-408a-b20d-38656928be9d.jpg</url>
      <title>DEV Community: Ziga Brencic</title>
      <link>https://dev.to/zigabrencic</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/zigabrencic"/>
    <language>en</language>
    <item>
      <title>🐍 Python: Standard library</title>
      <dc:creator>Ziga Brencic</dc:creator>
      <pubDate>Mon, 11 Jan 2021 19:31:28 +0000</pubDate>
      <link>https://dev.to/zigabrencic/python-standard-library-137n</link>
      <guid>https://dev.to/zigabrencic/python-standard-library-137n</guid>
      <description>&lt;h1&gt;
  
  
  🐍 Python: Standard library
&lt;/h1&gt;

&lt;p&gt;Python, like all languages ships with an extended amount of modules/packages you can use. I'm always surprised how much is built into the library.&lt;/p&gt;

&lt;p&gt;Why is it so important to know what's available to you? Well for starters if you know what's at your disposal, you can reuse a lot of tools others wrote. Plus if you stick with the implementations form the standard library your code will be more robust, less external library dependencies, which is always a good practice in software development.&lt;/p&gt;

&lt;p&gt;Here's the thing &lt;code&gt;python&lt;/code&gt; standard is one of the most stable parts of the ecosystem out there. Core language developers are really, really careful with the changes they make. Changes are advertised in advance, tested, ... Which can't be said for all other libraries out there.&lt;/p&gt;

&lt;p&gt;Now to be clear. Use a library that's not part of the standard if it fits your need, but think twice, because every crap you bring into your codebase will make your life harder in the future.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://docs.python.org/3/py-modindex.html"&gt;Here&lt;/a&gt; you can find the list of all &lt;code&gt;python 3&lt;/code&gt; modules. In the next few paragraphs, we'll cover a few that are not too specialised.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to use a module?
&lt;/h2&gt;

&lt;p&gt;For example, module &lt;code&gt;collections&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;Module full of container like data types like: &lt;code&gt;OrderedDict&lt;/code&gt; and &lt;code&gt;deque&lt;/code&gt; (list-like container with fast appends and pops on either end).&lt;/p&gt;

&lt;p&gt;To import part of a module:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from collections import OrderedDict

d = OrderedDict()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or import the entire module:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import collections

d = collections.OrderedDict()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  IO
&lt;/h2&gt;

&lt;p&gt;One large aspect that has great support in &lt;code&gt;python&lt;/code&gt; is &lt;code&gt;IO&lt;/code&gt; writing to the disk and reading from it.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;json&lt;/code&gt;: Module for reading &lt;code&gt;.JSON&lt;/code&gt; files. More about &lt;code&gt;json&lt;/code&gt; in the upcoming post.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;csv&lt;/code&gt;: Write and read tabular data to and from delimited files.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;gzip&lt;/code&gt;: Interfaces for &lt;code&gt;gzip&lt;/code&gt; compression and decompression using file objects.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;hashlib&lt;/code&gt;: Secure hash and message digest algorithms.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;pathlib&lt;/code&gt;: Object-oriented filesystem paths. Supper handy to check if file paths exist, ... &lt;/li&gt;
&lt;li&gt;
&lt;code&gt;sqlite3&lt;/code&gt;: A DB-API implementation using &lt;code&gt;SQLite&lt;/code&gt; 3.x.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;aifc&lt;/code&gt;: Read and write audio files in &lt;code&gt;AIFF&lt;/code&gt; or &lt;code&gt;AIFC&lt;/code&gt; format.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;tarfile&lt;/code&gt;: Read and write &lt;code&gt;tar&lt;/code&gt;-format archive files.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;io&lt;/code&gt;: Core tools for working with streams of data (binary file readers ...).&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;zipfile&lt;/code&gt;: Read and write &lt;code&gt;ZIP&lt;/code&gt;-format archive files.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;xml&lt;/code&gt;: Package containing &lt;code&gt;XML&lt;/code&gt; processing modules&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;copy&lt;/code&gt;: Shallow and deep copy operations. To perform deep copies of objects.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;types&lt;/code&gt;: Names of built-in types. Use them to "fix" data structures.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;There are also some caching options:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from functools import lru_cache
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;lru_cache&lt;/code&gt; is a Last Recently Used cache, so there is no expiration time for the items in it.&lt;/p&gt;

&lt;p&gt;There's also &lt;code&gt;shelve&lt;/code&gt;: &lt;code&gt;python&lt;/code&gt; object persistence package, which allows you to store objects in &lt;code&gt;key&lt;/code&gt; &lt;code&gt;value&lt;/code&gt; like manner for the cycle of your program. For example, to create a shelve do:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;with shelve.open('spam') as db:
    db['eggs'] = 'eggs'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then you can call objects from the &lt;code&gt;db&lt;/code&gt; anywhere in the scope of &lt;code&gt;with&lt;/code&gt;. This was if the resource has already been loaded from the disk to the memory you can read the resource from the cache which is much faster than disk access.&lt;/p&gt;

&lt;h2&gt;
  
  
  Parallelization, background processes
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;threading&lt;/code&gt;: Thread-based parallelism.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;multiprocessing&lt;/code&gt;: Process-based parallelism.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;queue&lt;/code&gt;: The queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;asyncio&lt;/code&gt;: Asynchronous I/O. Execute code forward and let the processes run until it runs&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  GUI
&lt;/h2&gt;

&lt;p&gt;There's &lt;code&gt;tkinter&lt;/code&gt;. An interface to &lt;code&gt;Tcl/Tk&lt;/code&gt; for building really simple graphical user interfaces. I'm not a big fan of it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Reliability
&lt;/h2&gt;

&lt;p&gt;There are a few built-in modules in &lt;code&gt;python&lt;/code&gt; standard that can help you make your codebase more reliable, faster, readable and modular:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;warning&lt;/code&gt;: Issue warning messages.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;logging&lt;/code&gt;: Flexible event logging system for applications. Especially to store error logs.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;cProfile&lt;/code&gt;:  For profiling python programs. To measure how long certain portions of the code take to execute. Don't mindlessly optimise. Write the code. Identify the slow stuff and optimise that.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;pydoc&lt;/code&gt;:  Documentation generator and online help system.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;venv&lt;/code&gt;:  Creation of virtual environments. Use this to ensure that others can run your code by creating a virtual environment, fast. No extra dependencies needed.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Time
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;datetime&lt;/code&gt;: Basic date and time types.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;zoneinfo&lt;/code&gt;: IANA time zone support.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;time&lt;/code&gt;: Time access and conversions.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;calendar&lt;/code&gt;: Module for a calendar like operations.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Networking
&lt;/h2&gt;

&lt;p&gt;Networking tools are really well supported in &lt;code&gt;python&lt;/code&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;mailbox&lt;/code&gt;: Manipulate mailboxes in various formats.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;webbrowser&lt;/code&gt;: Easy-to-use controller for Web browsers.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;smtpd&lt;/code&gt;: A SMTP server implementation in Python.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;smtplib&lt;/code&gt;: SMTP protocol client&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;socketserver&lt;/code&gt;: A framework for network servers.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;ssl&lt;/code&gt;: TLS/SSL wrapper for socket objects.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;email&lt;/code&gt;: Package supporting the parsing, manipulating, and generating email messages.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;socket&lt;/code&gt;: Low-level networking interface.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;ftplib&lt;/code&gt;: FTP protocol client.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;html&lt;/code&gt;: Helpers for manipulating HTML.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;http&lt;/code&gt;: HTTP status codes and messages.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;urllib&lt;/code&gt;: URL handling module.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Math and numerics
&lt;/h2&gt;

&lt;p&gt;There's quite a few things you can do mathematics wise with pure &lt;code&gt;python&lt;/code&gt; before you bring in the crap like &lt;code&gt;scipy&lt;/code&gt; and &lt;code&gt;numpy&lt;/code&gt;. To some extent, those libraries are great but hide too much implementation details. Which is fucking dangers. So use the basics from &lt;code&gt;python&lt;/code&gt; whenever you can.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;statistics&lt;/code&gt;: Mathematical statistics functions.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;math&lt;/code&gt;: Math functions &lt;code&gt;exp&lt;/code&gt;, &lt;code&gt;sin&lt;/code&gt;, ...&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;cmath&lt;/code&gt;: Mathematical functions for complex numbers.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;random&lt;/code&gt;: Generate pseudo-random numbers with various common distributions.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Command line/OS interface
&lt;/h2&gt;

&lt;p&gt;Having a nice interface with the underlying OS is always nice. &lt;code&gt;bash&lt;/code&gt; is painful to write so if control from &lt;code&gt;python&lt;/code&gt; is on the table, sign me up.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;subprocess&lt;/code&gt;: Subprocess management.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;os&lt;/code&gt;: Module with &lt;code&gt;os.system()&lt;/code&gt; option that allows us to run shell commands among other functionality.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;sys&lt;/code&gt;: Access system-specific parameters and functions.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;sysconfig&lt;/code&gt;: Python's configuration information.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;syslog&lt;/code&gt;: An interface to the Unix &lt;code&gt;syslog&lt;/code&gt; library routines.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;pipes&lt;/code&gt;: Interface to shell pipelines.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;argparse&lt;/code&gt;: Command-line option and argument parsing library.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Other cool modules:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;difflib&lt;/code&gt;: Helpers for computing differences between objects. Can come in handy if you want to track changes. &lt;/li&gt;
&lt;li&gt;
&lt;code&gt;importlib&lt;/code&gt;: The implementation of the import machinery. This way you can import &lt;code&gt;python&lt;/code&gt; modules, packages, folders, ... programmatically and not by typing boilerplate code.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;pprint&lt;/code&gt;: Data pretty printer.&lt;/li&gt;
&lt;li&gt;'re`: Regular expression operations.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;That's it. In the upcoming post, we'll explore some of the features in-depth.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;🐍 Python series:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://minimalisticsoftware.com/blog/2021-01-04?id=cLjQS51OaFw"&gt;Crash course&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://minimalisticsoftware.com/blog/2021-01-05?id=cLjQS51OaFw"&gt;The editor PyCharm&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://minimalisticsoftware.com/blog/2021-01-06?id=cLjQS51OaFw"&gt;Basics&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Standard library&lt;/li&gt;
&lt;li&gt;&lt;a href="https://minimalisticsoftware.com/blog/2021-01-08?id=cLjQS51OaFw"&gt;JSON&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>python</category>
      <category>tutorial</category>
      <category>programming</category>
      <category>todayisearched</category>
    </item>
    <item>
      <title>🐍 Python: Crash course</title>
      <dc:creator>Ziga Brencic</dc:creator>
      <pubDate>Sat, 09 Jan 2021 15:31:55 +0000</pubDate>
      <link>https://dev.to/zigabrencic/python-crash-course-30kc</link>
      <guid>https://dev.to/zigabrencic/python-crash-course-30kc</guid>
      <description>&lt;p&gt;&lt;strong&gt;🐍 Python series:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Crash course&lt;/li&gt;
&lt;li&gt;&lt;a href="https://minimalisticsoftware.com/blog/2021-01-05?id=c63SkNzJuE9"&gt;The editor PyCharm&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://minimalisticsoftware.com/blog/2021-01-06?id=c63SkNzJuE9"&gt;Basics&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://minimalisticsoftware.com/blog/2021-01-07?id=c63SkNzJuE9"&gt;Standard library&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://minimalisticsoftware.com/blog/2021-01-08?id=c63SkNzJuE9"&gt;JSON&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Python is a scripting language that gained in popularity in recent years. &lt;/p&gt;

&lt;p&gt;Official site &lt;a href="https://www.python.org"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  How language came to be?
&lt;/h2&gt;

&lt;p&gt;Python was created in the late 1980s by Guido van Rossum as a Christmas project. Heh like this newsletter :P  &lt;/p&gt;

&lt;p&gt;The language was then officially released for the first time to the public in 1991.&lt;/p&gt;

&lt;p&gt;Python is a scripting language that is interpreted, rather than compiled into the machine code, which is one of the major reasons why &lt;code&gt;python&lt;/code&gt; is by design slower than &lt;code&gt;C++&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;Sure there's the option of converting &lt;code&gt;python&lt;/code&gt; to "C" with &lt;code&gt;Cython&lt;/code&gt; to achieve speedups. But pure &lt;code&gt;C&lt;/code&gt; and &lt;code&gt;C++&lt;/code&gt; will always be faster than the snake  🐍 .&lt;/p&gt;

&lt;h2&gt;
  
  
  Python versions
&lt;/h2&gt;

&lt;p&gt;There are two major versions of &lt;code&gt;python&lt;/code&gt; out there at the moment:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;python 2&lt;/code&gt; which you should use only if you have to work with legacy code.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;python 3&lt;/code&gt; with the latest version 3.9.1. You can find the docs &lt;a href="https://docs.python.org/3/"&gt;here&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Side note.  macOS still ships with &lt;code&gt;python2&lt;/code&gt; but is finally switching from &lt;code&gt;python2&lt;/code&gt; so if you run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt; python2
WARNING: Python 2.7 is not recommended.
This version is included in macOS for compatibility with legacy software.
Future versions of macOS will not include Python 2.7.
Instead, it is recommended that you transition to using 'python3' from within Terminal.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How to start python?
&lt;/h2&gt;

&lt;p&gt;To access &lt;code&gt;python3&lt;/code&gt; from the command line simply run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt; python3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will open the following command line interpreter:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt; python3
Python 3.9.0 (default, Nov 21 2020, 14:01:50)
[Clang 12.0.0 (clang-1200.0.32.27)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
&amp;gt;&amp;gt;&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;in which you can run commands.&lt;/p&gt;

&lt;h2&gt;
  
  
  Hello world
&lt;/h2&gt;

&lt;p&gt;To run the classical hello world type into the terminal:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; print("Hello, world!")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and press enter.  That's it.&lt;/p&gt;

&lt;p&gt;That's one way of using python, but I'm personally not a big fan of it. The alternative is to write scripts, which is a way to go if you indent to write more then five lines of code.&lt;/p&gt;

&lt;h2&gt;
  
  
  Run a script from the command line
&lt;/h2&gt;

&lt;p&gt;You can write scripts and run them directly from the terminal.&lt;/p&gt;

&lt;p&gt;Create a file called &lt;code&gt;hello_world.py&lt;/code&gt; and write to it the following line:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print("Hello world!")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Close the file.&lt;/p&gt;

&lt;p&gt;Now run in the command line:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt; python3 hello_world.py 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You should see:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt; python3 hello_world.py 
Hello, world!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Before we wrap up, there's something else I want to cover. Above example has one slight issue. It works fine in our simple case, but the moment our software grows into multiple scripts such "direct" commands become an issue. &lt;/p&gt;

&lt;p&gt;If we imported the &lt;code&gt;hello_world.py&lt;/code&gt; file to another &lt;code&gt;python&lt;/code&gt; program, the &lt;code&gt;print&lt;/code&gt; statement would be executed. But we want to execute the &lt;code&gt;print&lt;/code&gt; command only if we ran the program directly &lt;code&gt;python3 hello_world.py&lt;/code&gt; and not when we import our script. &lt;/p&gt;

&lt;p&gt;To solve the issue, we can use something called &lt;code&gt;__main__&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;code&gt;__main__&lt;/code&gt;
&lt;/h2&gt;

&lt;p&gt;To achieve the desired behaviour we correct our &lt;code&gt;hello_world.py&lt;/code&gt; example into:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if __name__ == "__main__":
    print("Hello, world!") 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Where &lt;code&gt;__name__&lt;/code&gt; will be equal to &lt;code&gt;"__main__"&lt;/code&gt; only if we run our &lt;code&gt;hello_world.py&lt;/code&gt; script directly. If we import our script to another &lt;code&gt;python&lt;/code&gt; program &lt;code&gt;__name__&lt;/code&gt; will be different.&lt;/p&gt;

&lt;p&gt;Now once we run the script &lt;code&gt;python&lt;/code&gt; will check if global variable &lt;code&gt;__name__&lt;/code&gt; is set to &lt;code&gt;"__main__"&lt;/code&gt; and then execute our code.&lt;/p&gt;

</description>
      <category>python</category>
      <category>beginners</category>
      <category>codenewbie</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Why you code?</title>
      <dc:creator>Ziga Brencic</dc:creator>
      <pubDate>Sun, 22 Dec 2019 19:44:50 +0000</pubDate>
      <link>https://dev.to/zigabrencic/why-you-code-3gcp</link>
      <guid>https://dev.to/zigabrencic/why-you-code-3gcp</guid>
      <description>&lt;p&gt;How would be your answer the question:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why you code?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let me know in the comments below and read on the story.&lt;/p&gt;

&lt;h2&gt;
  
  
  Motives
&lt;/h2&gt;

&lt;p&gt;I'm not a software developer not by training nor experience. I never worked as a professional software developer. Software is a tool for me, like math. I'm a physicist, after all, 🙂 I love doing math and writing code, but I prefer to stay in the physics lane for the majority of my time. So to no surprise, the conversations like the one below occur over and over:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;em&gt;Colleges&lt;/em&gt;: Why do you code? &lt;/li&gt;
&lt;li&gt;
&lt;em&gt;Me&lt;/em&gt;: Because it gives me an edge.&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;C&lt;/em&gt;: Huh OK.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Start
&lt;/h2&gt;

&lt;p&gt;I started coding (simple web site) in high school. As I started, I was really frustrated by coding. I would spend days banging my head against the wall. Most of the time, I had no clue what was going on. But I forged on because my studies required me to do some basic coding. I kind of despised coding. Physics and math was more fun.&lt;/p&gt;

&lt;p&gt;But it wasn't until my 2nd year at uni before I took a deep dive into coding. I realised that every physicist that was an excellent coder was perceived as an expert in the community. Those mini experts new something way better they anyone else. If you needed help with coding, you went to them. I figured that the coding skills could be my secret weapon.&lt;/p&gt;

&lt;h2&gt;
  
  
  Competition
&lt;/h2&gt;

&lt;p&gt;This will depend on your field of expertise. Still, no matter the profession, there are several things that the majority of people find hard and confusing. The harder or more boring the concepts are fewer people know then. As a result, you face less competition. There's a good analogy:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;A lot of people go to the mountains, but a few well-trained enthusiasts climb the highest peaks of the world. Higher we go thinner the air. There's far less competition at an altitude of 8km.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Use this to your advantage. Figure out what others despise. Most probably they don't like certain areas because they don't understand them. Dig into those, and your skills will be sought by others for the rest of your career.&lt;/p&gt;

&lt;h2&gt;
  
  
  Old technology
&lt;/h2&gt;

&lt;p&gt;Physicists,  write a lot of (shitty) code.  OK, a few can code really really well. I would claim that I'm somewhere in between the two poles.  As long as the code works (most of the time), we don't bother staying up to date with all new fancy tools and concepts. Yes, some are still convinced that &lt;code&gt;FORTRAN&lt;/code&gt; is easy. Some still send emails via &lt;code&gt;vim&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;So to no surprise, the first language I really learned was &lt;code&gt;C&lt;/code&gt; in 2013. Even the website we used for the course looked like it was written in the eighties. I found my sanity and at least switched from Windows to Unix in 2013. So I started my path by going down the &lt;code&gt;C&lt;/code&gt; rabbit hole. Then came across something called &lt;code&gt;C++&lt;/code&gt;. Then the dependency hell, build systems... you know how the rest of the story goes.&lt;/p&gt;

&lt;h1&gt;
  
  
  Frustration is the way
&lt;/h1&gt;

&lt;p&gt;Every time I tried something in software, I asked myself. Why is this so hard? It's not rocket science nor theoretical physics. I should be simple right? Yet on the contrary, when I decided to build my first proper web site, I read online that:&lt;/p&gt;

&lt;p&gt;I needed to sign up for &lt;strong&gt;AWS&lt;/strong&gt; account create an &lt;strong&gt;EC2 server&lt;/strong&gt; that runs on &lt;strong&gt;ubuntu&lt;/strong&gt;. &lt;strong&gt;SSH&lt;/strong&gt; to the server through &lt;strong&gt;bash&lt;/strong&gt; shell. Then install &lt;strong&gt;Nginx&lt;/strong&gt;, &lt;strong&gt;SSL&lt;/strong&gt; and &lt;strong&gt;uwsgi&lt;/strong&gt;. Then my application should use on the &lt;strong&gt;back-end&lt;/strong&gt; the &lt;strong&gt;python&lt;/strong&gt; &lt;strong&gt;Django&lt;/strong&gt; engine with &lt;strong&gt;PostgreSQL&lt;/strong&gt; database. On &lt;strong&gt;front-end&lt;/strong&gt; I should use &lt;strong&gt;react/vue/angular&lt;/strong&gt; with some &lt;strong&gt;HTML, JavaScript, CSS&lt;/strong&gt;. The application should be running in &lt;strong&gt;docker&lt;/strong&gt; containers so it can scale based on the web site traffic.  &lt;/p&gt;

&lt;p&gt;I knew that &lt;code&gt;python, CSS, HTML, JS&lt;/code&gt; were languages heard of &lt;code&gt;git&lt;/code&gt; and &lt;code&gt;bash&lt;/code&gt;. The rest was foreign to me. In a few years, I mastered enough of the above concepts that I'm capable of running a simple personal web site. Though I still have nightmares from time to time about the first experience with &lt;code&gt;Django&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;After coding for a while, I came to realise that:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Experienced developers fail a few times faster than junior ones.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;After coding for years, I still get stuck and frustrated every day. But these days I'm somehow cable of getting over the frustration in a matter of minutes instead of days 🙂 I guess that comes with experience so hang in there and embrace failure. 😉&lt;/p&gt;

&lt;h2&gt;
  
  
  Why?
&lt;/h2&gt;

&lt;p&gt;When I was picking up the software development skills, it took me years before I started seeing progress. The hard truth is:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;You learn how to write good software through years of practice.&lt;/strong&gt; &lt;/p&gt;

&lt;p&gt;There are no shortcuts. If you want to get good, you'll need to practice the craft. Nothing new here. But make sure you know the answer to the question:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why you code?&lt;/strong&gt; &lt;/p&gt;

&lt;p&gt;For me, software development is all about being able to:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Write fast code as fast as possible.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;As long as the code get's the job done in the reasonable amount of time I'm happy with it. There are cases where I have to take care of documentation, tests, share code with others then the &lt;strong&gt;why&lt;/strong&gt; slightly changes. &lt;/p&gt;

&lt;p&gt;For you the answer to the &lt;strong&gt;why&lt;/strong&gt; will probably be something completely different. Nothing wrong with that.  The &lt;strong&gt;why&lt;/strong&gt; should dictate how you improve your craft.&lt;/p&gt;

&lt;p&gt;As a result of my needs, these days, my proficiency lies in &lt;code&gt;python&lt;/code&gt; and &lt;code&gt;C++&lt;/code&gt;.  My work is mostly oriented around big data processing and simulations on clusters. Still, I come across other languages like &lt;code&gt;CSS&lt;/code&gt;, &lt;code&gt;HTML&lt;/code&gt;, &lt;code&gt;JS&lt;/code&gt;, &lt;code&gt;latex&lt;/code&gt;, (&lt;code&gt;bash&lt;/code&gt;) every day. A server crosses my desk from time to time. For me, quick and dirty solutions usually do the job. Though I sure kick my self later for writing the bad code. &lt;/p&gt;

</description>
      <category>beginners</category>
      <category>motivation</category>
      <category>codenewbie</category>
      <category>career</category>
    </item>
    <item>
      <title>Parameters object in C++</title>
      <dc:creator>Ziga Brencic</dc:creator>
      <pubDate>Thu, 12 Dec 2019 19:56:57 +0000</pubDate>
      <link>https://dev.to/zigabrencic/parameters-object-in-c-1an9</link>
      <guid>https://dev.to/zigabrencic/parameters-object-in-c-1an9</guid>
      <description>&lt;p&gt;&lt;strong&gt;How to consistently use a set of parameters throughout the larger codebase.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;I've done my fair share of data processing. And one thing that most big data software implementations I worked with didn't tackle correctly was parameter handling.&lt;/p&gt;

&lt;p&gt;The process usually goes like this. You write a class and hard code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;unsigned int num_of_users = 1401;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Before you know it, the variable &lt;code&gt;num_of_users&lt;/code&gt; is used in ten places all over the code. Then you update &lt;code&gt;num_of_users&lt;/code&gt; to &lt;code&gt;1402&lt;/code&gt;. But forget to update the variable at some of the places in the code. The code works but gives inconsistent results. After hours of searching for the needle in the haystack, you figure out what you forgot to update. OK, problem solved. Two days later, you're pulling out your hair because another variable is causing trouble.&lt;/p&gt;

&lt;h2&gt;
  
  
  Parameter object
&lt;/h2&gt;

&lt;p&gt;In software I try to stick to the paradigma:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;If you copy-paste your code/parameters, you are doing it wrong.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To avoid hardcoding and parameter pasting in a large codebase, I create an object that holds the values of all my parameters. Store, all parameters in one object, then access them whenever they are needed:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Parameters {
pubic:
    unsigned int num_of_users;

    // rest of parameters

    Parameters() {
        this-&amp;gt;num_of_users = 1501;
    }
};
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Then with initialization:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Parameters var;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;we get access to all parameters via:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var.num_of_users;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h2&gt;
  
  
  Passing Parameters object around
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--NDZ4YDR9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/91rs6wdx1ywbheotjnga.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--NDZ4YDR9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/91rs6wdx1ywbheotjnga.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let's say we want to have one instance of our parameter object and then pass the pointer to that object around. Smart pointers come in handy here:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;auto var = std::make_shared&amp;lt;Parameters&amp;gt;();
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;We can then pass the &lt;code&gt;var&lt;/code&gt; smart pointer into any part of the code/module that needs access to those parameters. For example, we need to pass the parameter to two processing modules:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ProcessingModuleA processing_module_a(var);
ProcessingModuleB processing_module_b(var);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Where &lt;code&gt;ProcessingModuleA&lt;/code&gt; is defined as:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class ProcessingModuleA{
public:

    // rest of the module code

    ProcessingModuleA(
        const std::shared_ptr&amp;lt;Parameters&amp;gt; &amp;amp;var){

        var.num_of_users; // accesible  

        // rest of the module code
    }
};
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h2&gt;
  
  
  Loading parameters
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--wU866spq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/3s13prcbrzkyb5mir7jv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--wU866spq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/3s13prcbrzkyb5mir7jv.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Another handy thing is if we can load parameters from the outside of our program. A JSON file, for example. So we can compile our &lt;code&gt;C++&lt;/code&gt; code once and then control the processing output via a JSON file. Advantages:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The considerable development process speed up. Since we don't have to recompile the code at each parameter change.&lt;/li&gt;
&lt;li&gt;We can store the parameters we used to produce specific data set and make the data set reproducible. As long as we know what code version was used ;)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now when we want to use the &lt;code&gt;parameters.JSON&lt;/code&gt; file as the input file the implementation becames a bit more technical. Example class implementation below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;string&amp;gt;
#include "json.hpp"

class Parameters {
pubic:
    unsigned int num_of_users;

    // rest of parameters

    Parameters(
        const std::string &amp;amp;parameters_location) {

        json parameters = read_json_file(parameters_location, "parameters.JSON");

        try {
            this-&amp;gt;num_of_users = parameters.at("num_of_users").get&amp;lt;unsinged int&amp;gt;();
        }
        catch(std::range_error &amp;amp;e) {
            std::cout &amp;lt;&amp;lt; e.what() &amp;lt;&amp;lt; std::endl;
            throw;
        }
        catch (...) {
            std::cout &amp;lt;&amp;lt; "Unknown exception occurred" &amp;lt;&amp;lt; std::endl;
            throw;
        }
    }
};
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;You should use &lt;code&gt;try&lt;/code&gt; and &lt;code&gt;catch&lt;/code&gt; block to ensure that you catch any errors that occur while reading the &lt;code&gt;JSON&lt;/code&gt; file. On what &lt;code&gt;read_json_file&lt;/code&gt; function does check the article &lt;a href="http://zigabrencic.com/posts/2019-11-19.html"&gt;JSON in C++: Read &amp;amp; Write&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Benefits for the development process
&lt;/h2&gt;

&lt;p&gt;Once the code is wired correctly, the processing becomes a breeze. Sure it takes a few minutes to set up. But once up and running, the loading of program parameters from the external &lt;code&gt;JSON&lt;/code&gt; file gives us a tremendous amount of speed up in the data analysis. As a result, we can get insights faster. Insights are what the whole big data and analytics are about anyway.&lt;/p&gt;

</description>
      <category>cpp</category>
      <category>codenewbie</category>
      <category>tutorial</category>
      <category>json</category>
    </item>
    <item>
      <title>Is Web Browser local storage available?</title>
      <dc:creator>Ziga Brencic</dc:creator>
      <pubDate>Tue, 10 Dec 2019 15:20:17 +0000</pubDate>
      <link>https://dev.to/zigabrencic/web-browser-local-storage-16jh</link>
      <guid>https://dev.to/zigabrencic/web-browser-local-storage-16jh</guid>
      <description>&lt;p&gt;Modern web browsers allow us to store data in the client's browser: not larger chunks but smaller amounts when it's convenient.&lt;/p&gt;

&lt;h2&gt;
  
  
  Interface
&lt;/h2&gt;

&lt;p&gt;To store the data to the &lt;code&gt;localStorage&lt;/code&gt; from JS simply do:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;localStorage.setItem('myCat', 'Tom');
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;or any other object (list, int, dict). Then to retrieve it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let cat = localStorage.getItem('myCat');
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;and to remove it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;localStorage.removeItem('myCat');
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;or to clear all items in the local storage that belong to the current domain, we are on:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;localStorage.clear();
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;There's another storage object &lt;code&gt;sessionStorage&lt;/code&gt;. Same interface as local storage though session storage get's purged once the user leaves the site. Friendly note: I would avoid storing any sensitive data (personal or security) into the local storage.&lt;/p&gt;

&lt;h2&gt;
  
  
  Local storage status
&lt;/h2&gt;

&lt;p&gt;Here's the thing. The local storage might not be available to us, or it might be full. So before we use the local storage in our web site code, we should check that we can.&lt;/p&gt;

&lt;h3&gt;
  
  
  Is local storage quota exceeded
&lt;/h3&gt;

&lt;p&gt;We get depending on the browser certain amount of space per web page domain:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Mobile:

&lt;ul&gt;
&lt;li&gt;Chrome, Firefox: 10MB&lt;/li&gt;
&lt;li&gt;Safari, iOS WebView: 5MB&lt;/li&gt;
&lt;li&gt;Android Browser: 2MB&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;Desktop:

&lt;ul&gt;
&lt;li&gt;Chrome, Firefox, IE: 10MB&lt;/li&gt;
&lt;li&gt;Safari: 5MB&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If we fill this space up with our web page, we won't be able to add any new elements to &lt;code&gt;localStorage&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Is local storage available
&lt;/h3&gt;

&lt;p&gt;Users can disable the use of local storage in the web browser.  Most won't, but there are enough geeks out there to cause us trouble. So we need to be able to check if the use of local storage is allowed.&lt;/p&gt;

&lt;p&gt;Side note: In Safari incognito mode, the &lt;code&gt;localStorage&lt;/code&gt; is blocked and will throw a quota exceeded error. So we might want to check if the browser is in incognito mode to be on the safe side.&lt;/p&gt;

&lt;h3&gt;
  
  
  Get Local storage status
&lt;/h3&gt;

&lt;p&gt;All right, let's write a function that will allow us to check if local storage is full and accessible. &lt;/p&gt;

&lt;p&gt;The function below tries to set the test object into the local storage and then remove it. If an error occurs, we catch it with the &lt;code&gt;try&lt;/code&gt; &lt;code&gt;catch&lt;/code&gt; block and then analyze what happened.&lt;/p&gt;

&lt;p&gt;Function &lt;code&gt;get_local_storage_status()&lt;/code&gt; will give us the status of &lt;code&gt;localStorage&lt;/code&gt; :&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;full&lt;/li&gt;
&lt;li&gt;unavailable&lt;/li&gt;
&lt;li&gt;available&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Full code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function get_local_storage_status() {
    let test = "test";
    try {
        // try setting an item
        localStorage.setItem("test", test);
        localStorage.removeItem("test");
    }
    catch(e)
    {   
        // browser specific checks if local storage was exceeded
        if (e.name === "QUATA_EXCEEDED_ERR" // Chrome
            || e.name === "NS_ERROR_DOM_QUATA_REACHED" //Firefox/Safari
        ) {
            // local storage is full
            return "full";
        } else {
            try{
                if(localStorage.remainingSpace === 0) {// IE
                    // local storage is full
                    return "full";
                }
            }catch (e) {
                // localStorage.remainingSpace doesn't exist
            }

            // local storage might not be available
            return "unavailable";
        }
    }   
    return "available";
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;We can then run the function with:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;get_local_storage_status();
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Or display the status in the console:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log(get_local_storage_status())
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;A convenient test to see if our script works is to disable local storage, for example in Firefox by:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Typing: &lt;code&gt;about:config&lt;/code&gt; in your address bar and hit enter. You'll see browser settings.&lt;/li&gt;
&lt;li&gt;Search for &lt;code&gt;dom.storage.enabled&lt;/code&gt; and change status to &lt;code&gt;false&lt;/code&gt;. Double mouse click on the setting should do the change.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Add your script to an example website and check in the browser &lt;code&gt;console&lt;/code&gt; for the status. If you managed to set up the Firefox settings correctly the &lt;code&gt;console.log(get_local_storage_status())&lt;/code&gt; should give you &lt;code&gt;"unavailable"&lt;/code&gt; status.&lt;/p&gt;

&lt;h2&gt;
  
  
  When is local storage convenient
&lt;/h2&gt;

&lt;p&gt;All right, we are equipped with the local storage. Now, where would we want to use it? &lt;/p&gt;

&lt;p&gt;Let's say that the user internet connection drops down, and the user wants to leave the web site. But some data will be lost if the user leaves the web site in the offline mode. Then local storage could come to our aid. We store data in the local storage until user reconnects to the internet with our website again. Again don't store any sensitive data in the local storage. &lt;/p&gt;

&lt;p&gt;Another use case of local storage would be to optimize the page load time by storing some page parts into the local storage. On the next load, just part of the page would have to be loaded.&lt;/p&gt;

&lt;p&gt;There's one more edge case we didn't cover here. The user's web browser doesn't support &lt;code&gt;HTML5&lt;/code&gt; and &lt;code&gt;localStorage&lt;/code&gt; at all. In that case well ...&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>tutorial</category>
      <category>analytics</category>
    </item>
    <item>
      <title>Don't do things globally in C++</title>
      <dc:creator>Ziga Brencic</dc:creator>
      <pubDate>Fri, 06 Dec 2019 10:01:23 +0000</pubDate>
      <link>https://dev.to/zigabrencic/don-t-do-things-globally-in-c-2n07</link>
      <guid>https://dev.to/zigabrencic/don-t-do-things-globally-in-c-2n07</guid>
      <description>&lt;p&gt;&lt;strong&gt;Don't expect other developers to have a computer size brain.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To often I come across a codebase where objects magically apeare in the code. Then I would ask the developer that wrote the code where the object is coming from and they would go:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Developer: &lt;em&gt;Oh yeah that's a special object we defined globaly.&lt;/em&gt;
&lt;/li&gt;
&lt;li&gt;Me: &lt;em&gt;Sigh.&lt;/em&gt; 🤦‍♂️&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Sure when you writing code you are lazy and global objects my seem like a viable solution, but on the long run they never are. If you use global objects your code most probably won't be thread safe so forget about multithreading. Oh and let's not forget that the code will be painful to read for any future developer.&lt;/p&gt;

&lt;h2&gt;
  
  
  Code organisation
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F2l8l5ai3z2wdati7hir4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F2l8l5ai3z2wdati7hir4.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Organise your program from top to bottom. Code that gets called last should be at the end of the file. There are few advantages of this. Code becomes readable like an article. You don't have to specify class/function definition before their implementation. Or in other words there's no need for forward declarations. &lt;/p&gt;

&lt;p&gt;As rule of thumb I try to follow these guidelines:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;code is split into self contained blocks,&lt;/li&gt;
&lt;li&gt;every code block can have multiple inputs, but only a signle output,&lt;/li&gt;
&lt;li&gt;don't use global object's ever,&lt;/li&gt;
&lt;li&gt;if global variable would be convinient use a class,&lt;/li&gt;
&lt;li&gt;don't hard code anything. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Hard coding is pain in the ass for mentainence and code reading. If data is needed in multiple places in the code pass it around. One more thought. Don't over use classes. There are a lot of cases where a function with multiple inputs and a single output will do just fine.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Ffxuwgomo8wxbf5oxkx0k.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Ffxuwgomo8wxbf5oxkx0k.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Global objects
&lt;/h2&gt;

&lt;p&gt;Don't do it. Maybe you think you are smart enough to keep all the global stuff in your head but once your codebase grows to few thousand lines of code (it does pretty fast ;) ) you'll loose track. Sure there maybe a one percent of cases where global stuff makes sense but unless you're doing the computing on scale of CERN or Google you most probably won't come across them.  &lt;/p&gt;

&lt;p&gt;Global objects never help with code readability. They just increase number of WTF per minute when another developer reads the code.&lt;/p&gt;

&lt;h2&gt;
  
  
  Localy/Class global
&lt;/h2&gt;

&lt;p&gt;It's true sometimes its handy to have objects/variables available in multiple functions without the need to pass them around every time. In that case you should write a &lt;code&gt;C++&lt;/code&gt; class. The use &lt;code&gt;private&lt;/code&gt; to make sure that variables needed in the class stays "global" only in the class. Other parts of the code shouldn't have access to those variables. &lt;/p&gt;

&lt;p&gt;For example let's create a  &lt;code&gt;C++&lt;/code&gt; class named &lt;code&gt;MyObject&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class MyObject{
private:
    unsigned int hidden_counter;
    double x;

public:
    void print_next(){ // public function
        ++hidden_counter;
        std::cout &amp;lt;&amp;lt; x*hidden_counter &amp;lt;&amp;lt; std::endl;
    }

    MyObject(double x){ // object constructor
        this-&amp;gt;hidden_counter = 0;
        this-&amp;gt;x = x;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now to work with the object you can initialize it with:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;MyObject  var(3.5);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To then use the public functions do:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var.print_next(); // prints to screen: 1*x = 3.5;
var.print_next(); // prints to screen: 2*x = 7.0;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Advantage of this approach is that we created an environment where &lt;code&gt;hidden_counter&lt;/code&gt; is global in scope of the class but isolated from the rest of the program that shouldn't modify it. &lt;/p&gt;

&lt;p&gt;If we now write  &lt;code&gt;var.hidden_counter = 3;&lt;/code&gt; the &lt;code&gt;C++&lt;/code&gt; compiler will complain that we are trying to modify a  private variable of class &lt;code&gt;MyObject&lt;/code&gt;. &lt;/p&gt;

&lt;h2&gt;
  
  
  Defensive programing
&lt;/h2&gt;

&lt;p&gt;Another concept worth mentioning. Idea of defensive programming is that our code also specifies how it shouldn't be used. For example by making &lt;code&gt;hidden_counter&lt;/code&gt; private inside class &lt;code&gt;MyObject&lt;/code&gt; we made sure that  &lt;code&gt;hidden_counter&lt;/code&gt;  can't be modified outside of the &lt;code&gt;MyObject&lt;/code&gt; methods. If we would have made  &lt;code&gt;hidden_counter&lt;/code&gt;  public we woldn't prevent the code user from missing the code of  &lt;code&gt;MyObject&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;To wrapp up. All the time invested into thinking how code should be structured/implemented is worth way more then you imagine. More readable code will decrease the likelihood of you and other coders pulling out your hair. Though don't get stuck in the code planing ;) &lt;/p&gt;

</description>
      <category>cpp</category>
      <category>codenewbie</category>
      <category>tutorial</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Analytics with vanilla JS: page view duration</title>
      <dc:creator>Ziga Brencic</dc:creator>
      <pubDate>Wed, 04 Dec 2019 19:22:45 +0000</pubDate>
      <link>https://dev.to/zigabrencic/analytics-with-vanilla-js-page-view-duration-2aph</link>
      <guid>https://dev.to/zigabrencic/analytics-with-vanilla-js-page-view-duration-2aph</guid>
      <description>&lt;p&gt;Third post in series: &lt;a href="http://zigabrencic.com/pages/analytics_series.html" rel="noopener noreferrer"&gt;&lt;strong&gt;Analytics with vanilla JS&lt;/strong&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Page view duration is essential in determining whether our users read the content of our article or not.&lt;/p&gt;

&lt;p&gt;To determine the time of user page visit, we need to detect two events:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;page view start time: &lt;code&gt;t_page_opened&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;page view end time: &lt;code&gt;t_page_closed&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Request page, close page
&lt;/h2&gt;

&lt;p&gt;We first cover the case of page view duration, which is the easiest to measure.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Frg4fvqebpgychjw00h04.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Frg4fvqebpgychjw00h04.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let's say the user clicks a link or types the address of our web page to the web browser. The user will land on our web page. The page files will be sent over from the server that hosts the web site.&lt;/p&gt;

&lt;p&gt;In this case, when the page is loaded, we can detect &lt;code&gt;onload&lt;/code&gt; Java Script event and determine that as the start of page visit with:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;window.onload = function () {
    t_page_opened = new Date();
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now let's say that the user leaves the web page by closing the browser tab or browser window. We can detect that via &lt;code&gt;beforeunload&lt;/code&gt; event by adding the event listener:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;window.addEventListener("beforeunload", leftWebSite);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;leftWebSite&lt;/code&gt; function then get's the time stamp when user left the page:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function leftWebSite() {
    const t_page_closed = new Date();

    const data = JSON.stringify({
        "page_opened": t_page_opened,
        "page_closed": t_page_closed
    });
    post_data(data, "define_URL");
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and sends the &lt;code&gt;t_page_opened&lt;/code&gt; and &lt;code&gt;t_page_closed&lt;/code&gt; to the a prediefined &lt;code&gt;URL&lt;/code&gt; with &lt;code&gt;post_data&lt;/code&gt; function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function post_data(data, url) {
    let xhr = new XMLHttpRequest();
    xhr.open("POST", url, true);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 &amp;amp;&amp;amp; xhr.status === 200) {
            console.log(xhr.responseText);
        }
    };
    xhr.send(data);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Job done, right? Far from it.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If we want to have a proper estimate of the read times, we need to be really careful about potential corner cases for page opening and page closing.&lt;/p&gt;

&lt;p&gt;Wait? Page view start and page view end should be determinable in a few lines of code. Not quite. &lt;/p&gt;

&lt;h2&gt;
  
  
  User leaves the web site
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fsfpg6rn6w481zrrgcrmj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fsfpg6rn6w481zrrgcrmj.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;What if the user left the page via a link, history forward or history back button, lost internet connection, refreshed the web page. In those cases, &lt;code&gt;beforeunload&lt;/code&gt; won't get consistently triggered (from browser to browser). &lt;/p&gt;

&lt;p&gt;Let's list the cases we need to cover. When the user leaves the page via:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Browser tab/window closing: detected via &lt;code&gt;beforeunload&lt;/code&gt;. Solved.&lt;/li&gt;
&lt;li&gt;internal or external link: detectable via &lt;code&gt;onclick&lt;/code&gt; event&lt;/li&gt;
&lt;li&gt;internet connection lost:

&lt;ul&gt;
&lt;li&gt;connection reestablished during page view: no issue&lt;/li&gt;
&lt;li&gt;user revisits a page in the future: fetch view data from user browser &lt;code&gt;localStorage&lt;/code&gt; if the user didn't clean it&lt;/li&gt;
&lt;li&gt;the user never comes back to our site: data lost&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;page refresh: can be detected with the help of &lt;code&gt;localStorage&lt;/code&gt;
&lt;/li&gt;

&lt;li&gt;page left via history back, forward button: using &lt;code&gt;pagehide&lt;/code&gt; event, since page &lt;code&gt;JS&lt;/code&gt; won't be re-loaded and &lt;code&gt;beforeunload&lt;/code&gt; event won't be triggered.&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;Keep in mind that the solutions that use &lt;code&gt;localStorage&lt;/code&gt; won't work if the user:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;disabled the use of local storage,&lt;/li&gt;
&lt;li&gt;uses incognito browser mode.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  User opens the web site
&lt;/h2&gt;

&lt;p&gt;To detect if the user opened the web site is slightly easier. There are just three cases to handle:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fwghqo78tuksa07t7wg45.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fwghqo78tuksa07t7wg45.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We already handled the first case with &lt;code&gt;onload&lt;/code&gt;. To handle the page left via history back, the forward button, we again use &lt;code&gt;pagehide&lt;/code&gt; event.&lt;/p&gt;

&lt;h2&gt;
  
  
  Tackling edge cases
&lt;/h2&gt;

&lt;p&gt;In the upcoming articles we'll cover the code needed for:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;em&gt;detecting: page refresh, history button clicks, internal-external links&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;detection of incognito mode&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;detection of internet connection loss&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;But even after we handle all of those cases, we won't ensure the correct estimate of reading time. What if the user opens the web page, leaves it open and goes to the toilet. Or scrolls through the article really fast. Well, we could monitor page scrolls. This way, we could eliminate a few more edge cases that could corrupt our read time estimates and analysis. Stay tuned.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>agile</category>
      <category>analytics</category>
    </item>
    <item>
      <title>JSON in C++</title>
      <dc:creator>Ziga Brencic</dc:creator>
      <pubDate>Mon, 02 Dec 2019 07:53:49 +0000</pubDate>
      <link>https://dev.to/zigabrencic/json-in-c-3mie</link>
      <guid>https://dev.to/zigabrencic/json-in-c-3mie</guid>
      <description>&lt;p&gt;&lt;strong&gt;Third article in series: Modern C++&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Modern C++ series:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="http://zigabrencic.com/posts/2019-11-05.html" rel="noopener noreferrer"&gt;Intro to Modern C++&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://zigabrencic.com/posts/2019-11-12.html" rel="noopener noreferrer"&gt;C++ the python way&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;One thing in &lt;code&gt;python&lt;/code&gt; that's super useful are dictionaries and &lt;code&gt;JSON&lt;/code&gt;. They allow flexible data structures. What about &lt;code&gt;JSON&lt;/code&gt; structures? They are not possible in a statically typed language like &lt;code&gt;C++&lt;/code&gt;. We'll modern &lt;code&gt;C++&lt;/code&gt; can handle &lt;code&gt;JSON&lt;/code&gt; believe it or not :)&lt;br&gt;
&lt;code&gt;C++&lt;/code&gt; itself doesn't provide &lt;code&gt;JSON&lt;/code&gt;, but there are a few options that bring &lt;code&gt;JSON&lt;/code&gt; type data structure to &lt;code&gt;C++&lt;/code&gt;.  &lt;/p&gt;

&lt;p&gt;I personally use &lt;a href="https://github.com/nlohmann/json" rel="noopener noreferrer"&gt;C++ JSON library nlohman&lt;/a&gt;. There are other libraries, though, so take your pick. I like &lt;code&gt;nlohman JSON&lt;/code&gt; lib because it's a single header file library (drop header file into the project). Or it can also be used as a dependency. It depends if you want to ship the &lt;code&gt;JSON&lt;/code&gt; lib with your software or allow the user to add it as a dependency.&lt;/p&gt;

&lt;p&gt;What can the &lt;code&gt;JSON&lt;/code&gt; library do? Well, quite a lot, but the syntax and usage can be quite confusing, so I'll provide a few examples to clear things out.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; I'm assuming ' &lt;code&gt;using nlohmann::json;&lt;/code&gt; to write less syntax. &lt;/p&gt;

&lt;p&gt;To create a &lt;code&gt;JSON&lt;/code&gt; object, we simply do:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

json data;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;and then add elements to it:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

// vector
data["M_final"] = std::vector&amp;lt;double&amp;gt;(N);

// a double
data["beta"] = 10.0;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;or any other structure from &lt;code&gt;STL&lt;/code&gt; library. Some &lt;code&gt;STL&lt;/code&gt; structures are not supported though most are. More on adding custom structures to &lt;code&gt;JSON&lt;/code&gt; later. &lt;/p&gt;

&lt;p&gt;There are a lot more options on how to construct the &lt;code&gt;json&lt;/code&gt; object. For example, we can actually write the &lt;code&gt;JSON&lt;/code&gt; format in the program, but I prefer to load &lt;code&gt;JSON&lt;/code&gt; data structures from an external file.  &lt;code&gt;json&lt;/code&gt; object creation inside the codebase:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

json data = R"(
    {
        "happy": true,
        "pi": 3.141
    }
)"_json;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;For more construction options, look into the docs. The library has a ton of other functionality &lt;code&gt;STL&lt;/code&gt; like access, for example, but really read the docs if you are interested in more.&lt;/p&gt;

&lt;h2&gt;
  
  
  Read &amp;amp; write JSON files
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fjoqihg87haqj76iymfeb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fjoqihg87haqj76iymfeb.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;How do we load &lt;code&gt;JSON&lt;/code&gt; file into the &lt;code&gt;JSON&lt;/code&gt; data object from &lt;code&gt;C++&lt;/code&gt;? We'll quite easyly. If we specify:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

std::string path = "path to json file";
std::string file_name = "json_file_name";


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;we then load the file with few lines of code:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

json data;
std::ifstream file(path + "/" + file_name + ".json");
file &amp;gt;&amp;gt; data;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Side note. You need to include &lt;code&gt;#include &amp;lt;iostream&amp;gt;&lt;/code&gt; and &lt;code&gt;#include &amp;lt;fstream&amp;gt;&lt;/code&gt; libraries. But they are in &lt;code&gt;STL&lt;/code&gt; so no need for messy installs.&lt;/p&gt;

&lt;p&gt;Then to store to the &lt;code&gt;JSON&lt;/code&gt; file:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

std::ofstream file(path + "/" + file_name + ".json");
file &amp;lt;&amp;lt; std::setw(4) &amp;lt;&amp;lt; data &amp;lt;&amp;lt; std::endl;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Custom JSON serializers
&lt;/h2&gt;

&lt;p&gt;So let's say we want to store a custom data structure to a &lt;code&gt;JSON&lt;/code&gt; file. For that, we need to define a serializer. JSON serializer tells our library how it should convert a &lt;code&gt;C++&lt;/code&gt; object into a format that can be written into a &lt;code&gt;JSON&lt;/code&gt; file. Or in other words, it tells the software how to load the &lt;code&gt;JSON&lt;/code&gt; file into appropriate &lt;code&gt;C++&lt;/code&gt; data structure.  &lt;/p&gt;

&lt;p&gt;For example, let's say we want to be able to store &lt;code&gt;std::complex&amp;lt;double&amp;gt;&lt;/code&gt; to JSON. Then we can expand the &lt;code&gt;std&lt;/code&gt; namespace with two methods &lt;code&gt;to_json&lt;/code&gt; and &lt;code&gt;from_json&lt;/code&gt;:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

namespace std {

    /// std::complex&amp;lt;double&amp;gt;
    void to_json(json &amp;amp;j, const std::complex&amp;lt;double&amp;gt; &amp;amp;complex_number) {
        j = json{{"re", complex_number.real()},
                 {"im", complex_number.imag()}};
    }

    void from_json(const json &amp;amp;j, std::complex&amp;lt;double&amp;gt; &amp;amp;complex_number) {
        complex_number.real(j.at("re").get&amp;lt;double&amp;gt;());
        complex_number.imag(j.at("im").get&amp;lt;double&amp;gt;());
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Or to add a structure of type &lt;code&gt;person&lt;/code&gt;:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

struct person_t {
    std::string name;
    std::string address;
    int age;
};

void to_json(json &amp;amp;j, const person_t &amp;amp;p) {
    j = json{{"name",  p.name},
             {"address", p.address},
             {"age",   p.age}};
}

void from_json(const json &amp;amp;j, person_t &amp;amp;p) {
    j.at("name").get_to(p.name);
    j.at("address").get_to(p.address);
    j.at("age").get_to(p.age);
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;By providing &lt;code&gt;to_json&lt;/code&gt; and &lt;code&gt;from_json&lt;/code&gt; we allow the program to automatically map our data structure to the &lt;code&gt;JSON&lt;/code&gt; format. Now we can store a &lt;code&gt;person&lt;/code&gt; structure to the &lt;code&gt;JSON&lt;/code&gt; file via:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

person_t p;
// define person: name, address, age
json data;
data["person"] = p;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;If we stored &lt;code&gt;json data&lt;/code&gt; now into a &lt;code&gt;JSON&lt;/code&gt; file, the content would be:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

"person": {
    "name": "John",
    "address": "web",
    "age": "31"
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;That's it. OK when reading back from &lt;code&gt;JSON&lt;/code&gt; file we actually need to provide the data structure type before we can get the &lt;code&gt;C++&lt;/code&gt; function. For example to retrieve our person object:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

json data; // contains person object but in string format
auto p = data.at("person").get&amp;lt;person_t&amp;gt;();


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;I know that's not as pretty as in &lt;code&gt;python&lt;/code&gt;, but if you store the type of the data structures when you create the &lt;code&gt;JSON&lt;/code&gt; file, you can use a little trick. You can write an extra wrapper around &lt;code&gt;json&lt;/code&gt; library that allows you to make calls of type:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

enhanced_json data;
person_p p = data.at("person");


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In the above case, you handle data loading based on the data type in the &lt;code&gt;JSON&lt;/code&gt; file inside the &lt;code&gt;enhanced_json&lt;/code&gt; object using the &lt;code&gt;at&lt;/code&gt; function. To get the &lt;code&gt;enhanced_json&lt;/code&gt; object, you need a few if statements and auto.&lt;/p&gt;

&lt;p&gt;Sure all the above software will add overhead and make your code slower. So if you need fast data storage for large amounts of data, this automatic serialization is probably not a good idea. I would argue that JSON is not a good idea if you need to read and store a lot of data. But if you need &lt;code&gt;C++&lt;/code&gt; to do a lot of data crunching and need a bit of storage. Then &lt;code&gt;JSON&lt;/code&gt; interface can tremendously speed up your workflow. &lt;/p&gt;

&lt;h2&gt;
  
  
  JSON doesn't make C++ totally python
&lt;/h2&gt;

&lt;p&gt;In the next article I'll dive into the use of C++ JSON data structures to speed up the analysis workflow. Until then, if you know any more tricks that make C++ more pythonic, let me know.&lt;/p&gt;

</description>
      <category>cpp</category>
      <category>codenewbie</category>
      <category>tutorial</category>
      <category>json</category>
    </item>
    <item>
      <title>Analytics with vanilla JS: page views</title>
      <dc:creator>Ziga Brencic</dc:creator>
      <pubDate>Fri, 29 Nov 2019 18:46:01 +0000</pubDate>
      <link>https://dev.to/zigabrencic/analytics-with-vanilla-js-page-views-47pb</link>
      <guid>https://dev.to/zigabrencic/analytics-with-vanilla-js-page-views-47pb</guid>
      <description>&lt;p&gt;&lt;strong&gt;How to get basic page view statistics?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Second article in the series Analytics with Vanilla JS. Motivation &lt;a href="http://zigabrencic.com/posts/2019-11-08.html" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Today we'll look into the impelentation of vanila JS analytics tool that analyses page views.&lt;/p&gt;

&lt;p&gt;For the sake of example we need some simple HTML code for our tracker (file &lt;code&gt;example_page.html&lt;/code&gt;). You can add anything you want to the HTML file:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
&amp;lt;head&amp;gt;
    &amp;lt;meta charset="UTF-8"&amp;gt;
    &amp;lt;script src="js/page_view_tracker.js"&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
    &amp;lt;a href="https://www.google.com" class="external"&amp;gt;Leave page by going to Google&amp;lt;/a&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The rest of the code will be in &lt;code&gt;page_view_tracker.js&lt;/code&gt;. First, let's define the function that will allow us to &lt;code&gt;POST&lt;/code&gt; all the gathered data as a string to a specific URL:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

function post_data(data, url) {
    let xhr = new XMLHttpRequest();
    xhr.open("POST", url, true);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 &amp;amp;&amp;amp; xhr.status === 200) {
            console.log(xhr.responseText);
        }
    };
    xhr.send(data);
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;data in the string is in JSON format. The server you'll be sending data to can be whatever you prefer: &lt;code&gt;node.js&lt;/code&gt;, &lt;code&gt;Django&lt;/code&gt;, &lt;code&gt;flask&lt;/code&gt;, ... There's even an option to post into Google Docs spreadsheets if you want to avoid the backend. &lt;/p&gt;

&lt;p&gt;Data is posted with the following command:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

post_data(JSON.stringify(data), "http://0.0.0.0:5000/analytics");


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;where we defined data object as:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

const data = {
    "current_page_name": current_page_name
};


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now let's add the rest of the data.&lt;/p&gt;

&lt;h2&gt;
  
  
  Tracking
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Number of views per page&lt;/strong&gt;: this one is easy. Every time a user visits our website, the &lt;code&gt;post_data&lt;/code&gt; function will be triggered, so we need to add &lt;code&gt;current_page_name&lt;/code&gt; to our data object. It's defined with:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

let current_page_name = window.location.href;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In principle, we could get the URL of the current page from the request on the backend by I prefer to have all the data in the &lt;code&gt;JSON&lt;/code&gt; object.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;User origin:&lt;/strong&gt; We want to know from what website the user came from. This information is important because it allows us to track sources of our web site traffic. Are we getting:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;direct traffic (users entering the URL to browser), &lt;/li&gt;
&lt;li&gt;traffic via referrals (links to our site),
or &lt;/li&gt;
&lt;li&gt;via organic search (user finds us via a Search engine like Google, Bing, Baidu ...). &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In all browsers except the Internet Explorer, the following will give us the source from which user came:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

let page_source = document.referrer;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;If traffic is dirrect or user used Internet Explorer &lt;code&gt;page_source&lt;/code&gt; will be empty so we set:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

if (page_source === "") {
    // could be direct traffic or Internet explorer
    page_source = "empty";
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now we can detect what web browser the user has with something like &lt;a href="https://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser" rel="noopener noreferrer"&gt;this&lt;/a&gt;, but that doesn't help us to determine the source from which the user came. If you know a workaround, please let me know how to get user origin in IE. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Device screen&lt;/strong&gt;: We want to know what devices the majority of our users are using. We get device screen size via:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

let screen_width = window.screen.width;
let screen_height = window.screen.height;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;and screen size that we can draw on with:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

let screen_available_width = window.screen.availWidth;
let screen_available_height = window.screen.availHeight;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Browser type, language, time zone&lt;/strong&gt;: To get the browser type we do:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

let browser_type = navigator.userAgent;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;the language:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

let language = navigator.language;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;and the time zone:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

let time_zone_offset = Intl.DateTimeFormat().resolvedOptions().timeZone;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Tracking parameters&lt;/strong&gt;: You can enhance your analytics if you publish URL-s with added parameters. For example, you can use the Urchin Tracking Module or UTM, a format used by Google to track your unique URLs:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

http://www.example.com/?utm_source=JohnDoe&amp;amp;utm_medium=mail


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;By adding parameters to links you share, you can segment the traffic way better during the analysis process. For example: What was published by you, what was shared by others, social media source, ...&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Page performance:&lt;/strong&gt; We want to know how long does it take for our web page to load. For that, we need to understand a bit about web browser events:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fq0rznsi9erg9rtr1qafp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fq0rznsi9erg9rtr1qafp.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;1.) First, the browser sends the request to the server to get page files.&lt;/li&gt;
&lt;li&gt;2.) Page files are sent to our device.&lt;/li&gt;
&lt;li&gt;3.) Then the browser needs to render the web page.&lt;/li&gt;
&lt;li&gt;4.) Once the web page is rendered, &lt;code&gt;onload&lt;/code&gt;/&lt;code&gt;load&lt;/code&gt; event is triggered.&lt;/li&gt;
&lt;li&gt;5.) The user views the page.&lt;/li&gt;
&lt;li&gt;6.) The &lt;code&gt;onload&lt;/code&gt;/&lt;code&gt;onunload&lt;/code&gt; event happens when the user closes the web page.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The page loading and rendering should happen in a matter of ms. If it doesn't, our user either has a really crapy internet, or we are sending over to many files. Either way, it's good to track that. According to &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Navigation_timing_API" rel="noopener noreferrer"&gt;Mozilla docs&lt;/a&gt; we can obtain the data about page loading from:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

let performance_data = window.performance.timing;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Then get:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

let page_load_time = performance_data.loadEventEnd - performance_data.navigationStart;
let request_response_time = performance_data.responseEnd - performance_data.requestStart;
let render_time = performance_data.domComplete - performance_data.domLoading;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We need to trigger page performance monitoring code after the page is loaded. Full code snipet for page perfromance:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

window.addEventListener("load", function () {
    let performance_data = window.performance.timing;

    // calculate request response time: network latency
    let request_response_time = ...

    // calculate page render time
    let render_time = ...


    // page load time: wait until load event is finished with setTimeout
    setTimeout(function () {
        let page_load_time = ...

        // Post data to the server
        ...
    }, 0);
});


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;code&gt;setTimeOut&lt;/code&gt; is needed because we need to wait for the &lt;code&gt;load&lt;/code&gt; event to finish before we can measure the page load time.&lt;/p&gt;

&lt;h2&gt;
  
  
  Stay tuned
&lt;/h2&gt;

&lt;p&gt;The &lt;strong&gt;full code&lt;/strong&gt; can be found on my blog at &lt;a href="//zigabrencic.com/examples/page_views/docs.html"&gt;page views&lt;/a&gt;. There you'll find the &lt;code&gt;HTML, JS, python&lt;/code&gt; files you need to run the whole thing.&lt;/p&gt;

&lt;p&gt;If you have any ideas what else we could track or how let me know in the comment section below.&lt;/p&gt;

&lt;p&gt;I'm not a very proficient &lt;code&gt;JavaScript&lt;/code&gt; developer, so there is probably a better way to do some of the parts. Any comments and solutions are welcome. Stay tuned for more. Next week we'll look into page view duration tracking. Why an entire article for that? Well, there are a few edge cases with web page closing that can complicate things.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>agile</category>
      <category>analytics</category>
    </item>
    <item>
      <title>C++ the python way</title>
      <dc:creator>Ziga Brencic</dc:creator>
      <pubDate>Thu, 28 Nov 2019 16:56:20 +0000</pubDate>
      <link>https://dev.to/zigabrencic/c-the-python-way-168p</link>
      <guid>https://dev.to/zigabrencic/c-the-python-way-168p</guid>
      <description>&lt;p&gt;&lt;strong&gt;Second article in series: Intro to Modern C++&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;First article from Intro to Modern C++ series: &lt;a href="http://zigabrencic.com/posts/2019-11-12.html"&gt;here&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I keep hearing. But &lt;code&gt;C++&lt;/code&gt; is so ugly to write. It's not like &lt;code&gt;python&lt;/code&gt;. Sure. But the &lt;code&gt;C++&lt;/code&gt; community adapted, and they introduced a few cool tricks that make &lt;code&gt;C++&lt;/code&gt; more pythonic. To make it clear, all of the syntax mentioned here won't work in older versions of &lt;code&gt;C++&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;You have element based &lt;code&gt;for&lt;/code&gt; loops in &lt;code&gt;C++&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;std::vector&amp;lt;double&amp;gt; x = {1, 2, 3};
for(auto &amp;amp;element: x){
    std::cout &amp;lt;&amp;lt; element &amp;lt;&amp;lt; std::endl;
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;code&gt;python&lt;/code&gt; version would be:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;x = [1, 2, 3]
for element in x:
    print(x)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Or for a map: key, value. In modern &lt;code&gt;C++&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;std::map&amp;lt;std::string, double&amp;gt; dict = {{"a", 2}, {"b", 4}};
for (auto const&amp;amp;[key, value] : dict)
    std::cout &amp;lt;&amp;lt; key &amp;lt;&amp;lt; " " &amp;lt;&amp;lt; value &amp;lt;&amp;lt; std::endl;

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;And in &lt;code&gt;python&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dict = {"a": 2, "b": 4}
for key, value in dict.items():
    print(key + " " + value)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;OK true there's nothing similar to &lt;code&gt;python&lt;/code&gt;'s &lt;code&gt;enumerate&lt;/code&gt; in &lt;code&gt;C++&lt;/code&gt; but you can always do:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;std::vector&amp;lt;double&amp;gt; x = {1, 2, 3};
unsigned int i = 0;
for(auto &amp;amp;element: x){
    std::cout &amp;lt;&amp;lt; i &amp;lt;&amp;lt; " " &amp;lt;&amp;lt; element &amp;lt;&amp;lt; std::endl;
    ++i;
}

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;For now that's the best implementation I came up with in &lt;code&gt;C++&lt;/code&gt; that is "similar" to &lt;code&gt;python&lt;/code&gt; &lt;code&gt;enumerate&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;x = [1, 2, 3]
for i, element in enumerate(x):
    print( i + " " + element)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h2&gt;
  
  
  So can C++ be completely pythonic?
&lt;/h2&gt;

&lt;p&gt;It’s quite interesting how the languages evolved over time. python was written with the aim to provide a simpler functionality than C++. But now python concepts are migrating into the C++ codebase. Though C++ can never replace python and python can never replace C++. But they can work really well hand in hand if we know how to leverage their strengths. Sure, in python we need to write less code then in C++. But honestly, if I have to type 10 more characters to get 15 times of code execution speed up, I’ll go with C++.&lt;/p&gt;

&lt;p&gt;Next week I’ll show you how to bring JSON into the C++ world.&lt;/p&gt;

</description>
      <category>cpp</category>
      <category>beginners</category>
      <category>codenewbie</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Intro to modern C++</title>
      <dc:creator>Ziga Brencic</dc:creator>
      <pubDate>Wed, 27 Nov 2019 16:25:49 +0000</pubDate>
      <link>https://dev.to/zigabrencic/intro-to-modern-c-j64</link>
      <guid>https://dev.to/zigabrencic/intro-to-modern-c-j64</guid>
      <description>&lt;p&gt;&lt;a href="https://www.ibiweb.org/regional-event-recap-paid-parental-leave-one-size-doesnt-fit-all/"&gt;Cover image source&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I turn to &lt;code&gt;C++&lt;/code&gt; when I have to do some sort of massive data crunching. In any other case I turn to &lt;code&gt;python&lt;/code&gt; since I can write numeric code in it faster. But there are cases where &lt;code&gt;C++&lt;/code&gt; is the only way to get out alive. We'll mention some advance concepts here but mostly to make you as a novice aware that they exist. Because you always don't know what you still don't know and I'll try to bridge this gap a bit.&lt;/p&gt;

&lt;h2&gt;
  
  
  C++ not the C way
&lt;/h2&gt;

&lt;p&gt;In natural sciences for some reason people practice and teach the young the &lt;code&gt;C++&lt;/code&gt; the &lt;code&gt;C&lt;/code&gt; way. Maybe they are stuck in the past or were just lazy to learn the cool features of modern &lt;code&gt;C++&lt;/code&gt; (&lt;code&gt;C++ 17&lt;/code&gt;).  But this &lt;code&gt;C&lt;/code&gt; is &lt;code&gt;C++&lt;/code&gt; mantra is producing an army of coders that are not leveraging modern tools.&lt;/p&gt;

&lt;p&gt;I keep seeing code that uses &lt;code&gt;double x[100];&lt;/code&gt; for arrays instead of &lt;code&gt;std::vector&amp;lt;double&amp;gt; x(100);&lt;/code&gt;. Or even worse: &lt;code&gt;double *x = new double[100];&lt;/code&gt;.  Hack when I started coding I was doing the same thing. Then someone told me. Hey there's this thing cold &lt;code&gt;STL&lt;/code&gt; (&lt;code&gt;C++&lt;/code&gt; Standard Template Library) that has vectors that are smart. If you try to access an element that doesn't exist it will raise a warning. Cool that's worth exploring.&lt;/p&gt;

&lt;p&gt;If you use &lt;code&gt;std::vector&amp;lt;double&amp;gt;&lt;/code&gt; instead of a &lt;code&gt;double&lt;/code&gt; array you have some pretty cool features at your disposal. You can enlarge the vector as the program gets executed, resize it, clean it up, ... To access elements you can use &lt;code&gt;x.at(i)&lt;/code&gt; instead of &lt;code&gt;x[i]&lt;/code&gt; sure the &lt;code&gt;[i]&lt;/code&gt; is faster but it doesn't check like &lt;code&gt;.at(i)&lt;/code&gt; if you are accessing elements that are not in the vector.&lt;/p&gt;

&lt;h2&gt;
  
  
  IDE is your friend
&lt;/h2&gt;

&lt;p&gt;Use something like &lt;code&gt;CLion&lt;/code&gt; it's the best Interactive Development Environment out there. It will tell you what you screwed up, remind you that you're maybe making some redundant copies of data, ... For the geeks. You can use &lt;code&gt;vim&lt;/code&gt; mode in it 😉&lt;/p&gt;

&lt;h2&gt;
  
  
  Don't use raw &lt;code&gt;*&lt;/code&gt; pointers. Ever !!
&lt;/h2&gt;

&lt;p&gt;But they are fast right. Yes sure raw pointers are the most efficient way to blow your head off 😀 General rule of thumb is that you don't use pointers at all. OK except for the reference &lt;code&gt;&amp;amp;&lt;/code&gt; which you use when you don't want unnecessary copying. For example when passing data to a function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;void my_calculator(const std::vector&amp;lt;double&amp;gt; &amp;amp;x){
// implementation
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;code&gt;const&lt;/code&gt; will make sure that the function can't modify &lt;code&gt;x&lt;/code&gt; that you passed in. If you wouldn't pass in &lt;code&gt;&amp;amp;x&lt;/code&gt; but just &lt;code&gt;x&lt;/code&gt; the data would be copied for no reason.&lt;/p&gt;

&lt;p&gt;If you really have to use pointers then smart pointers. &lt;code&gt;std::shared_ptr&lt;/code&gt; or &lt;code&gt;std::unique_ptr&lt;/code&gt; are the answer. Sure there might be some small percentage of cases where the library you are using forces you to use raw pointers (BTW that's bad library design). In that case keep in mind that smart pointer is just a smart envelope around the raw pointer so you can always get the raw pointer 'out'. Example of packaging an arbitrary &lt;code&gt;C++&lt;/code&gt; object into a smart pointer would be:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;std::shared_ptr variable_name = std::make_shared&amp;lt;Object&amp;gt;();
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Instead of the raw way that you shouldn't use ever:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;double *x = new double [100];
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Now why the hack is something like &lt;code&gt;double *&lt;/code&gt; so dangerous? Well if you delete the raw pointer to your data you will have pretty hard time getting back to it and cleaning it up. So before you realise your RAM is full and your PC can't perform any new calculations. In fancy words you cause a memory leak. By using smart pointers the smart pointers implementation sort of prevents you from doing that.&lt;/p&gt;

&lt;h2&gt;
  
  
  Code readability over performance
&lt;/h2&gt;

&lt;p&gt;I always recommend that you write code with readability in mind first. So other people (yes your future self in 2 years included) can understand, read and use the code afterwards. I propose that you:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;write your programs in English even if you don't have to. They become more readable.&lt;/li&gt;
&lt;li&gt;split larger sections of code into files: ~300 lines max per file&lt;/li&gt;
&lt;li&gt;don't use too much libraries per project&lt;/li&gt;
&lt;li&gt;use descriptive variables not something like &lt;code&gt;stRG2&lt;/code&gt; or &lt;code&gt;sss&lt;/code&gt;. The variable has to tell the reader descriptively what it represents. Good practice would be &lt;code&gt;num_of_simulation_steps&lt;/code&gt; for example.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;There a thousand more guidelines but  in general the above should give you the basis. For more you can check code style guides from google or someone else. But be careful at the end of the day you want to write code that produces good results so strike for healthy balance on spending time writing clean code and one that works. Your code readability will improve as you gain programming experience. In a sense programming is learning tricks and the person with most tricks is the 'best coder'.&lt;/p&gt;

&lt;h2&gt;
  
  
  Don't go down the optimisation rabbit hole
&lt;/h2&gt;

&lt;p&gt;Don't try to optimise the code for performance from the start. In most of cases that's usually a bad idea. Simply because before you write your whole program you don't know what the slow parts are. Maybe some function is slow but you don't really care because you run it once in your entire program. On the other had you might be executing specific line of code millions of times per program execution. That's the part that should be optimised. So general rule of thumb. Write your program. Then figure out where most of the program execution time is spent and optimise that part.&lt;/p&gt;

&lt;h2&gt;
  
  
  Key takeaways
&lt;/h2&gt;

&lt;p&gt;So what you should take from here:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;use &lt;code&gt;CLion&lt;/code&gt; editor (it's free for students and academics for non commercial use) and &lt;code&gt;cmake&lt;/code&gt; build system&lt;/li&gt;
&lt;li&gt;file that contains &lt;code&gt;int main(){}&lt;/code&gt; should be named &lt;code&gt;main.cpp&lt;/code&gt; that's usually good practice 😀&lt;/li&gt;
&lt;li&gt;use descriptive names for variables and objects&lt;/li&gt;
&lt;li&gt;don't do stuff globally, in 99% of the cases it's bad design&lt;/li&gt;
&lt;li&gt;use &lt;code&gt;STL&lt;/code&gt; (standard template library)&lt;/li&gt;
&lt;li&gt;don't optimize your code for performance from the get go. Compiler is usually smarter then you in most cases :) Let it do it's job.&lt;/li&gt;
&lt;li&gt;use &lt;code&gt;STL&lt;/code&gt; libraries for example: &lt;code&gt;#include&amp;lt;cmath&amp;gt;&lt;/code&gt; from &lt;code&gt;STL&lt;/code&gt; instead of &lt;code&gt;#include&amp;lt;math.h&amp;gt;&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Don't use global name spaces &lt;code&gt;using namespace std&lt;/code&gt; sure you write a bit more code but you keep the option open to introduce functions with same names&lt;/li&gt;
&lt;li&gt;strive for code readability over performance. At the end what costs you the most is the time that coders spent on your code base.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you find any bugs/mistakes shoot me a massage. Stay tuned for the upcoming articles. This is just the beginning of the series 😉&lt;/p&gt;

</description>
      <category>cpp</category>
      <category>beginners</category>
      <category>codenewbie</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Analytics with vanilla JS: motivation</title>
      <dc:creator>Ziga Brencic</dc:creator>
      <pubDate>Tue, 26 Nov 2019 21:41:16 +0000</pubDate>
      <link>https://dev.to/zigabrencic/analytics-with-vanilla-js-motivation-1p1b</link>
      <guid>https://dev.to/zigabrencic/analytics-with-vanilla-js-motivation-1p1b</guid>
      <description>&lt;p&gt;&lt;strong&gt;How to implement a feedback loop into the product?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A useful analytics tool will provide a direct feedback loop on how to improve our product. Every product (business/web page/blog, ...) want's to track different things. For example, user behavior, web site visits... For some of that, you can use Google Analytics or another commercial tool. But what if you want to track something extra? Or you don't like that Google charges you for data exports. Or you simply don't want to share user data with a 3rd party. All of a sudden, you end up with some hybrid custom solution. But why bother with tracking in the first place? &lt;/p&gt;

&lt;p&gt;Users are lazy. They won't take the time to tell you what's wrong with your product. They'll just leave and take their $$$ elsewhere. So how can you improve your product? By catching as much user data as possible and analyzing it without endangering the user's privacy. &lt;/p&gt;

&lt;p&gt;I had to start somewhere, so I decided to build my own web page analytics tool. If I used every tool on the market, I would end up with a blob of JavaScript:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--oDk0YyUD--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/sir3b9gjm90mo9r8xj8a.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--oDk0YyUD--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/sir3b9gjm90mo9r8xj8a.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;But I wanted something with a minimal amount of code and zero libraries. So pure JS, not 1000 libraries. Partially to reduce complexity but mostly to learn. &lt;/p&gt;

&lt;p&gt;When I headed out to build my own analytics tool, a quick search online didn't help much. Sadly most of the knowledge on analytics tool building is in the hands of big companies like Facebook, Amazone, Netflix, Google... Then at some point, I came across a simple example by accident. Then built forward from thereon. My process?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Google =&amp;gt; Implement =&amp;gt; Test =&amp;gt; Brainstorm =&amp;gt; Google =&amp;gt; Implement =&amp;gt; ...&lt;/strong&gt; &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;User privacy&lt;/strong&gt;: Depending on where you provide your web page (EU, for example), you have to notify the users about tracking and allow them to disable it. Track only the data you need for the development of your product. Don't track for advertising and selling data. Be better then Facebook ;) Encrypt the tracking data, so even if it gets stolen, it is a bit harder to decode.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Build products for the user benefit. Not to exploit and sell their privacy.&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Requirements
&lt;/h2&gt;

&lt;p&gt;I first though how the user interacts with our page: &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--avMm0m9o--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/ylt3459kh10apg89n8jp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--avMm0m9o--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/ylt3459kh10apg89n8jp.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Each user starts a user session when he/she requests the web page files from the server for the first time. Once the first request is processed user get's back the first web page view. Then the user clicks a link on the web page and gets back from the server another page view. On each page view, we want to track what the user does: mouse clicks, keypresses, ...&lt;/p&gt;

&lt;p&gt;With that in mind, I came up with a few requirements for the implementation:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;an alternative to third party tracking tools&lt;/li&gt;
&lt;li&gt;only pure/vanilla JS code (no external JS libraries)&lt;/li&gt;
&lt;li&gt;support for new web browsers&lt;/li&gt;
&lt;li&gt;track users that are not logged in&lt;/li&gt;
&lt;li&gt;be able to track:

&lt;ul&gt;
&lt;li&gt;number of views per page&lt;/li&gt;
&lt;li&gt;what web site user came from&lt;/li&gt;
&lt;li&gt;how long did the page take to load&lt;/li&gt;
&lt;li&gt;type of user device and screen size&lt;/li&gt;
&lt;li&gt;browser type&lt;/li&gt;
&lt;li&gt;user language&lt;/li&gt;
&lt;li&gt;time zone&lt;/li&gt;
&lt;li&gt;page view durations&lt;/li&gt;
&lt;li&gt;events during user page visit: clicks, keypresses, ...&lt;/li&gt;
&lt;li&gt;user sessions: what pages did the user visit sequentially&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;With the above list in mind, I started building things. &lt;/p&gt;

&lt;h2&gt;
  
  
  Stay tuned
&lt;/h2&gt;

&lt;p&gt;In the upcoming article, I'll focus on counting page visits and monitoring the necessary quantities. If you have any ideas, what else we could track let me know in the comment section below.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>agile</category>
      <category>analytics</category>
    </item>
  </channel>
</rss>
