teleren/devto huggingface dataset:
100 Days of SwiftUI — Day 19
Tags: 100daysofswiftui
Published: 2020-06-09 20:11:30

---
title: 100 Days of SwiftUI — Day 19
published: true
date: 2020-06-09 20:10:20 UTC
tags: 100daysofswiftui
canonical_url: https://zeitschlag.net/100-days-of-swiftui-day-19/
---

Today, at [Day 19](https://www.hackingwithswift.com/100/swiftui/19) was the challenge day — and it was great! Basically, you had to build a unit conversion-app from scratch. Paul gave some examples on units and some tips and tricks — and then you were on your own.

As I enjoyed going to pubs in the UK in pre-corona-times from time to time, I decided to find out, how much I drank in liters (or litres?!) when I had four (imperial) [pints](https://en.wikipedia.org/wiki/Pint#Imperial_pint). It's 2.27l — that's quite a lot! 🍺🍺🍺🍺

And this is, what the app looks like. Not really pretty, but it get's the job done:

![](https://zeitschlag.net/content/images/2020/06/Simulator-Screen-Shot---iPhone-SE--2nd-generation----2020-06-09-at-21.37.27.png)

I learned, that there's a built-in unit conversion in Foundation called `(NS)Measurement`. I didn't expect that, but wow, that's great! So the code to convert pints into litres (or liters) is pretty straightforward:

<!--kg-card-begin: markdown-->
```swift
var convertedAmount: Double? {
  guard let amount = Double(amount) else { return nil }

  let input = Measurement(value: amount, unit: units[inputUnitIndex].unit)
  let output = input.converted(to: units[outputUnitIndex].unit)

  return output.value
}
```
<!--kg-card-end: markdown--><!--kg-card-begin: markdown-->

`units` are an array of type: `[(title: String, unit: UnitVolume)]` so that I can show a nicer text in the pickers instead of only the symbol:

```swift
private let units: [(title: String, unit: UnitVolume)] = [
  (title: "Milliliters", unit: .milliliters),
  (title:"Liters", unit: .liters),
  (title: "Cups", unit: .cups),
  (title: "Pints", unit: .imperialPints),
  (title: "Gallons", unit: .imperialGallons),
]
```

I learned, that I can't use the fancy string formatting in string interpolation in computed variables, unfortunately. The SwiftUI itself is a Form with some Sections, nothing special.

I enjoyed today's task and again: I'm looking forward to tomorrow. Obviously, Paul knows how to motivate people. Thank you for that! Solving the challenge didn't take as much time as writing this blogpost `¯\_(ツ)_/¯`

<!--kg-card-end: markdown-->
Explaining: Pure Functions
Tags: functional, beginners
Published: 2020-06-09 20:10:17

#Intro
Have you ever heard that your code is poorly written, or that I won't work under different circumstances. That it requires lots of special handling that isn't needed. Bad news: you're in a tough spot, good news: there's a way out. 

#Functional Programming, What Is It?
Functional Programming(FP) is programming that is composed of pure functions, absence of side affects, avoiding mutable data, and imperative like programming to build software.

>You lost me.

Basically, programming that avoids things like http calls and whatnot to make side affects avoidable and make useful, predictable code so it can be used over and over without concern or issues.

#Pure Functions
Pure Functions are basically the pinnacle and heart of functional programming. 

>What Does That Mean?

Pure Functions contain all the requirements for FP, this means that if you follow most of the guidelines for pure functions you'll be able to understand FP, but this post isn't about FP as much as it is about PF(I know I turned it around on you!).

#How Are They Used?
Pure Functions have many practical uses. Automation is one place where they are key. The idea of automation already involves some of the ideology of pure functions. Continuous use with no side effects, and output only being determined by the input.

>Uh... English please.

Simply, reusability, and the input being what determines the output. Here's an example, Drake hit it!
![](https://miro.medium.com/max/1024/1*mYbGgtrGqLuD-ZCABPbGrg.jpeg)

>Okay, I understand most of what you're saying but what's a sid effect?

Here's a more professional explanation: In computer science, an operation, function or expression is said to have a side effect if it modifies some state variable value(s) outside its local environment, that is to say has an observable effect besides returning a value (the main effect) to the invoker of the operation.

>I don't get it.

Go back to the Drake example. There you'll see that in the first example the actual list is mutated in the forEach method's parenthesis. The code uses the push method to change the contents of the list. That is kind of a side effect, because if I wanted the original list it would be lost. In the second example the map method is used to return a mutated version of the list, so the original isn't gone.

>So a side effect is manipulating the data?

No, manipulating data is fine, that is precisely what functions are for. The problem is when you make irreversible changes to the data, that's why we avoid *mutable data*, not *using* it.

>Okay, what's an example.

Most modules and libraries are a combination of pure functions made to be predictable and reusable. Not all are like that though.

#That's That
![](https://www.warpzoned.com/wp-content/uploads/2015/07/qwertee304-432x640.jpg)
<figcaption>Hope you learned something.</figcaption>
Domain specific web framework examples
Tags: discuss, webdev
Published: 2020-06-09 19:56:31

---
title: Domain specific web framework examples
published: true
description: 
tags: #discuss #webdev
---

I'm exploring web frameworks that are specific to a certain domain like Ecommerce, CRMs, or whatever. Things like Odoo, Prestashop, etc. 

Any modern frameworks/solutions you have in mind like Saleor or Forem.. ?
Performance measuring
Tags: javascript, webdev, webapi
Published: 2020-06-09 19:23:25

> Measure first and then optimize!
> -- <cite>Golden rule</cite>

> You can't optimize what you can't measure.
> -- <cite>Another golden rule</cite>

There are many articles on how to improve performance in JavaScript applications. Of course, it’s good to know all these tricks and tips, but it’s much better to know what I will tell in this article 😇.

### Three key performance features

1. Navigation speed
2. Resources loading speed
3. Code execution speed

In general, web application performance depends on these characteristics — navigation, resources, and scripting. And together they are part of the Performance Timeline. Thanks to the Performance Web API, we can easily measure and read Performance Timeline metrics. Let's do it.

### Navigation Timing

```javascript
function getNavigationMetric () {
  const [entry] = performance.getEntriesByType("navigation");
  console.table(entry.toJSON());
}
```

The `getEntriesByType` method returns a list of the `PerfomanceEntity` objects, each of which is a part of the Performance Timeline. In this case, we get an object of type “navigation”. This type will be contained in the `initiatorType` property of the object, which we will see in the console after calling our function in the  `body.onload` (or in the `componentDidMount` life cycle method in a React app).

Other interesting properties will be: `responseEnd` - time of the last byte received from the navigation request (`startTime`) and `duration` - equal to the difference between `responseEnd` and `startTime`, respectively.

### Resource Timing

```javascript
function getResourceMetric () {
  const entries = performance.getEntriesByType("resource");
  console.log(entries);
}
```

When we call this function in `body.onload`, we get PerfomanceEntity for all the resources that the page loads. If we filter these entries by `initiatorType`, we get metrics for images (`initiatorType === “img”`), scripts (`initiatorType === “script”`), etc.

### User Timing

```javascript
function getUserMetric () {
  performance.mark("do_something_start_mark");
  doSomething();
  performance.mark("do_something_end_mark");
  
  performance.measure("measure", "do_something_start_mark", "do_something_end_mark");
  
  const entries = performance.getEntriesByType("measure");
  console.log(entries);
}
```

In this case, we get the timeline metric from `startMark` to the `endMark` label. By the way, it’s good practice to delete the used metric using the `performance.clearMeasures` method.

### PerfomanceObserver

Well, we have metrics, and now we can send them to the server for analysis. The best way to do this is to use the Performance Observer API.

```javascript
const observer = new PerformanceObserver(list => {
  const res = list.getEntries().map(entry => ({
    name: entry.name,
    type: entry.entryType,
    start: entry.startTime,
    duration: entry.duration,
  }));
  
  sendMetrics(res);
});

observer.observe({entryTypes: ['resource', 'navigation', 'measure']});
```
[More about the Perfomance Timeline API] (https://developer.mozilla.org/en-US/docs/Web/API/Performance_Timeline)
Default values in nestjs
Tags: nestjs, node, typescript
Published: 2020-06-09 19:21:29

While passing query params in nestjs if you have come across a situation where you want the node to exist without an explicit value for it, then here is how I wasted a lot of time behind it.

```
import { IsNotEmpty, IsString } from "class-validator";

export class IssueSearch
{
	@IsString()
	search: string;

	@IsNotEmpty()
	length: number = 10;

	@IsNotEmpty()
	lastId: string = "0"
}
```

Above is my DTO which is applied on the validation params of a controller method as below.

```
@Get("issues/all")
@UsePipes(new ValidationPipe({transform: true}))
async fetchAllIssues(@Query() search: IssueSearch)
{
	...
```

Hence if you access this method like 
**http://baseurl/controller/issues/all** it will throw up an error saying it didn't find the **search** node. 

However, if you access it like this - 
**http://baseurl/controller/issues/all?search=**

Then it's fooled. 

Let me know if there is an easier way to do this.
Mini Project - Random Password generator tool (JavaScript) 
Tags: javascript, webdev, css, html
Published: 2020-06-09 19:05:47

Random #password generator tool. 
Simply build with math.random #function  From #javascript #Html #CSS.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/vvsq6g59u6yzemghw8u4.gif)

Live website link - https://random-password-generator.netlify.com

(I never store passwords 😂) 

Open Source on #Github

https://github.com/raghavkhanna30/Random-password-generator

#DEVCommunity #100DaysOfCode 
#webdevelopment
Kvell.js – Setup a production ready Node.js app with batteries included
Tags: showdev, javascript, node
Published: 2020-06-09 19:05:07


# What is Kvell ?

Kvell.js is a family of packages using which you can create Node.js applications with pre-defined configurations, a fixed application flow and a set of abstractions. It bootstraps the node application with a set of popularly used npm packages and provides a minimal setup environment so that the developer can focus directly on writing the essential parts of the application.

Please visit [kvelljs.now.sh](kvelljs.now.sh) for the docs and other guides.
The Github repository is available on [github.com/nsharma1396/kvell](github.com/nsharma1396/kvell).

# What does it do ?

- Maintains a proper code standard.
- Abstracts out server configurations.
- Abstracts out database related configurations.
- Maintains a consistent top-level folder structure.
- Provides support for writing and viewing API documentations without any setups.
- Provides auto-template creation for routes and models.
- Does automatic git initialization (if possible) on project setup.
- Provides a very simple and basic logging mechanism.

Kvell takes inspiration from [create-react-app](create-react-app.dev) in it's implementation and shares some similarity with it's methodology and internal flow when it comes to how it works under the hood.

This is my first attempt at building something for the community and I will be happy to know what you think about it!
Deploy Django or Flask in 3 easy steps (in production)
Tags: python, django, docker
Published: 2020-06-09 19:04:53

No intro, let's jump to the steps.

## 1. Write a Dockerfile 😐 (why not)

This is my directory structure -
```bash
├── app/
│     .....
├── requirements.txt
├── Dockerfile
└── gunicorn_starter.sh
```
This is the Dockerfile - 
```docker
FROM python:3.7.3-slim

WORKDIR /user/src

COPY ./requirements.txt ./
RUN pip3 install -r ./requirements.txt

COPY ./app ./app
COPY ./gunicorn_starter.sh ./

ENTRYPOINT ["./gunicorn_starter.sh"]
```
Things to remember - 
1. Use small docker images like `-slim` or `-alpine`. `-alpine` is the lightest but in my case `-alpine` haven't got the `gcc` so I used `-slim`. (I could've install gcc manually in alpine)
2. Import requirements and install them before importing codes. Why? If we change our code, we won't need to install requirements in every build. Simple and easy way to reduce build times 🤗


## 2. Gunicorn server

**Why Gunicorn?** 🧐 -> Django or Flask is a framework, not server. So we need a server to serve our application built with the framework. Gunicorn is a WSGI supported server that can communicate with other application that supports WSGI like Flask or Django. WSGI is a gateway interface that matches the URI defined in the python application.

Now install gunicorn and add to the requirements.txt
```bash
pip install gunicorn
pip freeze > requirements.txt
```

This is the `gunicorn_starter.sh` file we have seen earlier - 
```bash
gunicorn --chdir app wsgi:app -w 2 --threads 2 -b 0.0.0.0:8003
```
We show gunicorn our project directory with `--chdir app`. `wsgi:app` for Django apps and for Flask, we need the file name where we did `app = Flask()`, like this - `<file_contains_app>:app`. Change worker and thread as per your need. Too much workers actually makes a system slow, why? Because workers are processes, and they shares same CPU core. And we should know our threads right? 😅

## 3. Build & Deploy (Seek & Destroy ☠️)

Build the docker image - 
```bash
docker build -t <your_tag> .
```
This image is production ready! Beleive it or not 😐

Run it 🤘 - 
```bash
docker run --name <image_name> -p 8003:8003 -e DB_URI=<your_db_uri> <your_tag>
```
`-e DB_URI=<your_db_uri>` here `-e` sets the environment variable. I set my DB with URI, so I passed this environment variable `DB_URI` while running my image.

This is it! 🥳 If you have any questions or face any problem, comment below 👇
Writing Unit Test
Tags: testing, beginners, unit
Published: 2020-06-09 18:45:07

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/dioujm2o4ngx2riczvku.jpg)
Photo by Ferenc Almasi on Unsplash

## What is a unit test?
A unit test is a check to ensure that a function works as expected. It is written during the software development process.

## Why the unit test?
- Makes it easier to add a new feature or delete a feature.
- The developer refactors with more confidence.
- Bugs are found earlier during development.
- Makes debugging easier.
- It improves code quality.

## Tips to keep in mind when writing unit test
- The function/module should contain all input(s) needed as parameters.
- The function/module should return an output.
- Do not test any external module, library or function for example the database, an API etc.
GitUI v0.6
Tags: rust, git, terminal
Published: 2020-06-09 18:37:52

**GitUI** - the *fastest* terminal tool for git written in rust

In [v0.6](https://github.com/extrawurst/gitui/releases/tag/v0.6.0) you can open detail info on previous commits and inspect diffs in ⚡️speed: https://github.com/extrawurst/gitui/releases/tag/v0.6.0 

Please check it out and let me know what you think❤️
Lessons learned from my mentees
Tags: mentoring
Published: 2020-06-09 18:20:28

---
title: Lessons learned from my mentees
published: true
description: Valuable things I discovered while mentoring
tags: mentoring
---

Over the recent years, I got the chance to mentor some aspiring interns. Not only did I find great pleasure in mentoring others, it provided me with valuable insights as well. So, what did I learn?

## Spot onboarding hiccups
If you're getting familiar with how things work, things seem a lot more obvious than when you're new to them. If an intern is having trouble understanding a topic, have a look if it can be refactored or simplified. These small hiccups were often **starting points for improvements in the codebase**.

## Listen to their approach first
Interns don't have a lot of knowledge about the day-to-day workflow in the company yet. Listening to their thoughts and reasoning for a problem will leave them with more self confidence than directly providing them with a path to a solution. **Even coming up with a terrible solution helps in finding a better one the next time!**

Perhaps they thought of a technique you're not familiar with? Or maybe they spot restraints in the regular workflow? It's also a chance to look at things from a different perspective.

## Provide context
Giving them a chance to analyse a problem themselves first, doesn't mean sending them in blind. When starting out, you're **mostly training your analytical skills**: how can I get from A to B as efficiently as possible? Finding the best approach balancing technical requirements with different types of customers' (and businesses') needs requires a lot of experience. Thinking together about who the most important stakeholders are will help them a great deal choosing the right solution.

What have you learned from your mentee or mentor?
Tips to share on how to improve yourself as a mentor? 
I'd like to hear about them!
#004 Docker Architecture
Tags: docker, devops, tutorial
Published: 2020-06-09 17:03:16

# Introduction

this is part 4 from the journey it's a long journey(360 day) so go   please check previous parts , and if you need to walk in the journey with  me  please make sure to follow because I may post more than once in 1  Day  but surely I will post daily at least one 😍.

And I will cover lot of tools as we move on.

# Docker Engine

![dockerEngine](https://docs.docker.com/engine/images/engine-components-flow.png)

*Docker Engine* is a client-server application , he use an REST API to communicate between Server and client , same as back-end communicate with front-end , you send an API request to the server from the client and the server get back a response .

Since it's a server-client and REST API based it's mean you can have a docker daemon running on server , and client running on local machine . So you can remote control the server !

# A bigger picture

![Bigger-picture](https://dev-to-uploads.s3.amazonaws.com/i/0p5mpye5pkbcewcqbl0n.png)

### The Docker daemon

The Docker daemon (`dockerd`) listens for Docker API requests and manages Docker objects such as images, containers, networks, and volumes. A daemon can also communicate with other daemons to manage Docker services.

### The Docker client

The Docker client (`docker`) is the primary way that many Docker users interact with Docker. 

When you type a command the client send it to the API and then API interact with the server

### Docker registries

A Docker *registry* stores Docker images. Docker Hub is a public registry that anyone can use, and Docker is configured to look for images on Docker Hub by default. You can even run your own private registry. 

go to [Postgres Docker Hub](https://hub.docker.com/_/postgres)  , this is an example for postgres database you can run database with 1 command!

#### Images

An *image* is a read-only template with instructions for creating a Docker container. Often, an image is *based on* another image, with some additional customization. For example, you may build an image which is based on the `ubuntu` image, but installs the Apache web server and your application, as well as the configuration details needed to make your application run.

You might create your own images or you might only use those created by others and published in a registry. To build your own image, you create a *Dockerfile* with a simple syntax for defining the steps needed to create the image and run it. Each instruction in a Dockerfile creates a layer in the image. When you change the Dockerfile and rebuild the image, only those layers which have changed are rebuilt. This is part of what makes images so lightweight, small, and fast, when compared to other virtualization technologies.

[reference](https://docs.docker.com/get-started/overview/#docker-architecture)
Set cache-control to Azure blob storage items
Tags: azure, storageaccount, cloud, powershell
Published: 2020-06-09 18:13:23

---
title: Set cache-control to Azure blob storage items
published: true
description: You can set expiracy on your Azure blob storage items. Let's see how.
tags: azure, storageaccount, cloud, powershell
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/85gwtxtlfnn4siy2legn.jpg
---

In one of my customer's application, we are storing static content (such as icons, and logos) in an Azure Storage Account blob container.
We've also configured the Cache-Control property of the blob items when served up to reduce bandwidth consumption.
Today, I wanted to show you how we did that.

# the sample application
The sample application is very simple: it consists of an Azure App Service hosting a static HTML page that displays an image that is stored in an Azure Storage blob.

This looks like this:
![intial HTML page](https://dev-to-uploads.s3.amazonaws.com/i/8tl0ue1or1ynl29vlqpn.PNG)


# Setting the cache-control manually
In order to set the cache-control for the blob item manually through, you'll need to use Azure Storage Explorer (either from the standalone tool or from the Azure Portal):
![set blob properties 1]((https://dev-to-uploads.s3.amazonaws.com/i/an4yztmwod5m80oa2ylm.png)

Then set the value of the "CacheControl" property:
![set blob properties 2](https://dev-to-uploads.s3.amazonaws.com/i/6qkjleh8opm5xe50ld30.png)



# Automating the thing (with PowerShell)
If we have multiple items in our blob container, setting properties manually is probably not the best idea. 

Luckily, we can automate this thing!

In this example, I show you how to do it in PowerShell but you can do it with whatever Azure SDK you prefer: Azure CLI, .NET, Python and so on. It's your call!

{% gist https://gist.github.com/BelRarr/90e09fb0983b84f4f9efb048008db81c %}

# How to make sure that the Cache-control property is used?
The first time we access the HTML page, we see that the image has been downloaded:

![first page invocation](https://dev-to-uploads.s3.amazonaws.com/i/wffwbgadkr8ez9tfnvhy.PNG)

However, when we do a refresh, we see that the image has been served from the memory cache:
![page refresh](https://dev-to-uploads.s3.amazonaws.com/i/5i8o6jhjj212nrb77lfb.png)

Now, if the cache expires on the client-side (in our case, after 2 minutes), we'll see that the image will again be served from the server (i.e. downloaded again):
![after the cache expires](https://dev-to-uploads.s3.amazonaws.com/i/0j8ey701r872lm1l6ui3.PNG)


Without setting the "CacheControl" property, we would notice that, on every page refresh, the image is being downloaded again.


# As a conclusion...
Today, we've seen how we can set up cache-control on blob storage items, both manually and automatically using PowerShell.
This will help lower your application's latency as well as your Azure Bandwith costs.

I hope that you found it valuable. 

# Keep the discussion
You can reach me on [Twitter](https://twitter.com/tidjani_b) or [LinkedIn](https://ca.linkedin.com/in/tidjani-belmansour-ph-d-98460912).

See you soon!