teleren/devto huggingface dataset:
iOS: How to properly customize system controls like UINavigationBar, UITabBar and more
Tags: ios, swift
Published: 2020-04-26 07:12:27

In this blog post let’s look how to customize standard iOS UIKit controls in an easy way that will ensure your app looks consistent. Let’s use an `UINavigationBar` as an example. This is pretty common because the standard blue tint just does not look good.

Of course there are many many ways how to customize this control. You can select it in Interface Builder and with Attributes inspector set the properties like background color, tint color and more to your liking.

However this has one BIG drawback. You need to remember to change all navigations bar and make sure to select same properties otherwise your app won’t have consistent look. This  same problem happens when you modify the control inside `viewDidLoad` method.

Another possible way would be to create custom subclass and in its `init` change the properties to your liking. This is better but you once again have to bear in mind that you have to use this subclass in all places where you have `UINavigationBar`.

So those solutions aren’t ideal, let’s look how this kind of customization is done properly thanks to an API that Apple introduced in iOS 5.  It is called appearance proxy and we can access it by calling  method `appearance` on UIKit classes.

How it works? 🤔 Basically we get back “pseudo” instance that has the same properties as instances of current component but changes are then “forwarded” to all instances of this control.

There is one important caveat and that is that those changes will not apply to controls already in a view hierarchy meaning those already on the screen. If you want to apply changes to those you need to remove them from the hierarchy and add them again.

That is why those appearance proxies should be configured when the app launches. For once `AppDelegate` is perfect place to do this.

## `appearance()` usage

Let’s see how to use `appearance` to customize some controls.

```swift
UINavigationBar.appearance().tintColor = Theme.Colors.primary
UITextField.appearance().tintColor = Theme.Colors.primary
```

This is an example from one of my recent projects. The tint color of the `UITextField` will affect the color of the cursor and text selection indicator.

I also think it is a good idea to have your app colors in one place. Even if you are using something like `systemBlue` or any other built-in color. Having it in one place means you can easily experiment with other colors.

If you want to customize multiple properties of one control, you can just grab the reference to the appearance proxy and use that.

```swift
let navigationBar = UINavigationBar.appearance()
navigationBar.tintColor = Theme.Colors.primary
navigationBar.prefersLargeTitles = true
navigationBar.backgroundColor = Theme.Colors.complementary
```

Then don’t forget to call these customizations here:

```swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool
```

And you are good to go! 👍
Document APIs with Javadoc: from comments to README, in a nut!
Tags: readme, api, markdown
Published: 2020-04-26 06:20:42

Documenting code is usually needed for others to understand what we do.

I created, time ago, [`javadoc`](https://www.npmjs.com/package/javadoc), an `npm` module to fastly generate `json/markdown` from any source code file, from a comfortable command line interface.

Personally, I document all my projects with it, and you can do it as well.

This is how I exploit this tool.

# 1. Install

```sh
$ npm i -g javadoc
```

# 2. Comment your code

This can be done with any programming language.

```js
/**
 * 
 * #### `myFunction(variable:Type):TypeReturned`
 * 
 * @name myFunction
 * @parameter
 * @parameter - `variable:Type` Description
 * @return `TypeReturned`
 * @description Description
 * 
 */
```

This comment will become fresh Markdown code that we can insert in the `README.md` file of our project, directly.

# 3. Generate documentation

To generate a markdown file with all our comments, we run in the console:

```sh
$ javadoc
  --include filesOne/**/*.js
  --format markdown
  --output README.md
```

Gotcha!!!

Your project was documented successfully.

Happy documenting!!!
Create your programming language, online and for free!
Tags: language, create
Published: 2020-04-26 06:50:45

Hi, folks.

Have you ever wanted to create your programming language?

LET'S DO IT IN 3 MINUTES.

# 1. Open the languages creator app

Go here:

[https://allnulled.github.io/language-generator-online/](https://allnulled.github.io/language-generator-online/)

# 2. Know PEGjs syntax

We are using PEGjs under the hood, a parser generator tool for JavaScript. Here the docs:

[https://pegjs.org/documentation](https://pegjs.org/documentation)

You will need to understand its syntax to create complex languages. But it is worthy.

# 3. Create project, syntax and example

The application will bring you, step by step, to create your language.

It is a good tool to use offline and from mobile phones.

This means that you can create programming languages while you are walking on the streets.

Is not that awesome???

Happy language creation!!!
Code Review: Prereview checklist. No important tasks are forgotten.
Tags: checklist, codereview, markdown, templates
Published: 2020-04-26 06:26:36

Here's my rephrase on [preflight checklist](https://en.wikipedia.org/wiki/Preflight_checklist),

> a **prereview checklist** is a list of tasks that should be performed by developer or team prior to raise an Merge Request 

Everytime we discussing changes in code review, we might found ourself talking about same things over and over again. For example, asking in comments to add testing instructions or adding pivotal story number for reference. 

To prevent that we need a little reminder to ourselves, or list of things we should check before raising an attention to your changes.

In our team we have checklists built-in in our [Merge Request templates](https://docs.gitlab.com/ee/user/project/description_templates.html).

Here an example of one of our [templates](https://gitlab.com/mycf.sg/ui-employer/-/tree/master/.gitlab/merge_request_templates
), 

```
<!-- Make sure Merge Request title following "<type>: <subject> [#<pivotal_story_id>]" -->

<!-- Brief description. Examples are, screenshots, steps to reproduce, links to dependent MRs -->

### General Checklist:

- [ ] Exact versions in package.json
- [ ] Testing instructions?
- [ ] Docs? Examples are, update `README.md` file, or add ADR in `doc/adr`
- [ ] Tests?
- [ ] Put in copy at least two potential reviewers

/cc

/label ~"Review Me"
```

Structure of this template are self-explanatory, one thing I want to point out is last line: `/label ~"Review Me"` on which I already wrote an [article](https://dev.to/mcf/code-review-review-labels-in-gitlab-1ola).

And don't forget to treat checklists as living documentation, new items can be added, or removed throughout time.

It's purpose is to improve code review safety by ensuring that no important tasks are forgotten.
Too good to miss ⭐
Tags: offers
Published: 2020-04-26 06:13:42


# ⭐ If you don't already know about it www.zapier.com are giving free<sup>*</sup> 3 months of credits to initiatives fighting COVID19 ⭐

https://zapier.com/blog/covid-19-assistance-program

<sup>*</sup>You need to be eligible. So I've snipped that part and listed it below.

> COVID-19 is creating challenges for all of us. Small businesses are being hit especially hard. With this assistance program, we want to lend what help we can to our most impacted customers.

> We're offering our small business assistance program to heavily impacted people who meet some combination of these criteria:

> - You work in a business with 10 employees or fewer, or you're a solo entrepreneur.
- Your business is privately owned.
- Your business is impacted by "social distancing" in an outsized way.
- The tourism, food service, hospitality, salon and spa, fitness, and education industries are some examples.
- You're a paying Zapier customer as of 3/20/2020.
Git & Branches
Published: 2020-04-26 05:58:08

I for one seem to always get carried away with my work.  By noon a project will be working fine & come evening for some reason a change I've made will cause enough errors that I have to backtrack to find the bug.  For far too long this entailed looking through directories of different saved files named with timestamps.  Then my life turned around...

...then I discovered Git.

Git is a wonderful tool for working on a project and saving your progress at different times.  Once it is installed on your system, just navigate into the project you'd like Git to work with and invoke a simple command.
```
git init
```
This will make the directory a working Git repository.  What this means is that Git will keep track of changes you make to files, and when you're ready, take a "snapshot" of the differences.  While Git has many MANY commands available to help in this task, my favorite is branches.

Git branches allow you to create a mirror of what you're working on.  This way you can make any number of changes without worrying about breaking your project.  It is if a parallel universe is created for your project for you to tinker in.  Then, when you're satisfied with your changes you can "merge" them into your main branch.

All Git repositories start on a branch called "master".  A new branch is created with the command:
```
git branch name-of-new-branch
```
By then typing "git branch" alone you can see a list of branches your repository has.  To switch to the new branch one would type:
```
git checkout name-of-new-branch
```
Now you are actively working on the different branch.  Make all the changes you like!  None of these will affect the "master" branch.  Once you are done with your modifications the changes can be "merged" into the master branch!
Hash Table - Data Structures in JavaScript: Part #4
Tags: javascript
Published: 2020-04-26 05:27:15

Hash table is a data structure that implements an associative array. An associative array is a structure that can map keys to values. In JavaScript, an object can act as an associative array. 

ECMAScript 2015 introduced a new data structure Map to map keys to values. 

To add a key-value pair into a hash table, we take a key and pass it through a hash function, which will output a number that corresponds to an index in an array of buckets. This is what we call **hashing**.

![hash table](https://raw.githubusercontent.com/Urfan196/MyFIles/master/implementing-own-hash-table.png?token=AMQWY7BS6RFSXSC6EUZPDDC6UUNJ6)

**Buckets/slots** are placeholders in a hash table where we will store values. They are often set with an initial max capacity.

Hash functions are:
- Irreversible - you cannot take the output of a hash function put into the same hash function and get the original data (input) back. 
- Consistent - if you put an input in a hash function over and over again, you should expect the same result each time.

To retrieve an item from a hash we take a key, run it through that same exact hash function and then directly access that bucket in the array where the value is stored. 

It is possible to have two or more different inputs return the same output. This is called a **collision**. To handle collisions we just store the key-value pairs at that same index using other collections like an array or linked list. 

```javascript
//hash function
const hash = (key, size) => {
 let hashedKey = 0
 for (let i = 0; i < key.length; i++) {
   hashedKey += key.charCodeAt(i)
 }
 return hashedKey % size
}


//hash table
class HashTable {
 constructor() {
   this.size = 10
   this.buckets = Array(this.size)
 
 // populate each bucket with a Map()
   for (let i = 0; this.buckets.length; i++) {
     this.buckets[i] = new Map()
   }
 }
 
 insert(key, value) {
   let idx = hash(key, this.size)
   this.buckets[idx].set(key, value)
 }
 
 
 remove(key) {
   let idx = hash(key, this.size)
   let deleted = this.buckets[idx].get(key)
   this.buckets[idx].delete(key)
   return deleted
 }
 
 
 search(key) {
   let idx = hash(key, this.size)
   return this.buckets[idx].get(key)
 }
}


```
Optimistic UI Trick Revealed!
Tags: webdev, graphql, react
Published: 2020-04-26 05:12:41

> Fake it, 'til you make it.

Suddenly I remember that quote when I'm talking about Optimistic UI. Before I understand what Optimistic UI is, I just wondering that how a response could be that fast. 😳 For example, look at Instagram like UI.

![optimistic-ui-apollo-graphql-instagram](https://2.bp.blogspot.com/-rLTyD50vcbw/XqUWRoEv2gI/AAAAAAAAQJc/EQNW26arS8MOljAzpgEGc_3w7iSZ6_k5ACLcBGAsYHQ/s1600/optimistic-response-instagram.gif)

There is no boring loading icon. When we press the like button, it will immediately liked the post. That's awesome right? 😲
> When a Magician 🎩 performs a trick, we could be easily amazed until someone revealed the trick.

# So, How Optimistic UI works?
Let's reveal the secret behind the Optimistic UI trick.

> Optimistic UI is a pattern that you can use to simulate the results of a mutation and update the UI even before receiving a response from the server. Once the response is received from the server, the optimistic result is thrown away and replaced with the actual result. -- Apollo GraphQL

"Simulate the results" means that we need to fake the response first, before we receive the real one. That's it. 💁‍♂️

## Example
We could implement this pattern easily using Apollo Client. This is one of the benefits of using GraphQL because the request and response are defined earlier in the Query and Mutation schema, we could easily fake the response while ensuring that the data becomes consistent with the actual response when it arrives.

```javascript
const LIKE_POST = gql`
  mutation LikePost($postID: ID!) {
    likePost(postID: $postID) {
      id
      __typename
      likers
    }
  }
`

const Posts = () => {
  const username = useSelector(state => state.auth.username)
  const [mutate] = useMutation(LIKE_POST)
  return (
    <Comment
      updateComment={({ id, likers }) =>
        mutate({
          variables: { postID: id },
          optimisticResponse: {
            __typename: "Mutation",
            likePost: {
              id,
              __typename: "Post",
              likers: [...likers, username]
            }
          }
        })
      }
    />
  )
}
```
Now, this trick couldn't amazed us anymore. 😅
I Made an NPM Package to Render text on HTML5 Canvas
Tags: npm, javascript, html
Published: 2020-04-26 05:09:25

Rendering text onto HTML5 Canvases has always been a hassle for me.

## The Problem

There was no proper way to align text, to wrap words if it overflows and even to properly position text without knowing the contents of the text.

Larger packages had this feature but I didn't wanna import a whole canvas library just to render some text.

![](https://i.imgur.com/TvGaHZu.png)

## Enter Canvas-Txt

I made a library called **Canvas-Txt**, which will let you render textboxes to html canvases and has all sorts of aligning and multi-line features

I created this for myself and it grew with some community help. This package was released to NPM and has some weekly downloads now.

I added some major changes and just released V2 of this.

**Features**

- Multiline text
- Auto line breaks
- Horizontal Align
- Vertical Align
- Easy Debugging

![](https://i.imgur.com/qV2x2zV.jpg)

## URLs

**Github:**  https://github.com/geongeorge/canvas-txt


**Demo:**  http://canvas-txt.geongeorge.com/
Unit Test vs Integration Test
Tags: testing, beginners
Published: 2020-04-26 04:31:04

### Why do you need testing?
Testing is very important. Many if not all companies test their code before shipping out, or at least they should. Testing helps prevent users from finding bugs that could have been caught before the release of a new feature/product. Automated testing by using a testing library like Jest can help cut down on repetitive manual testing. Automated testing saves a lot of time.

### What is unit testing?
Unit testing is like how it sounds. Unit testing is testing part of a program/codebase. Developers usually test a function to make sure it works as intended. The developer might test multiple functions or modules to see if they are working correctly. Theses tests are usually pretty quick and not very costly.

### What is integration testing?
Integration tests check to see if all the components that make up the whole product are working correctly. The last thing you would want is to add a new feature that would break other features. These tests are usually performed by a tester but there are testing libraries like react-testing-library that helps with integration tests. These tests are more costly because they they take a long time to run compared to unit tests.

Thank You for reading!

Resources
[Unit test versus Integration test](https://www.geeksforgeeks.org/difference-between-unit-testing-and-integration-testing/)
Keeping up in a Pandemic
Tags: career, mentalhealth, productivity, remote
Published: 2020-04-26 04:25:16

**_It is ok not to be ok._**

What does it mean to __keep up__ during a pandemic? What are we supposed to do? Are we supposed to use this time to learn a new skill? Or do our best to survive, keeping ourselves and others safe?

### If you are having trouble doing the basics, you are not alone.

Throughout this time, I have felt I should be doing more. I see posts of people learning new skills, running live coding streams, and online workshops. They are using the lockdown to their advantage. Meanwhile, I struggle with the day-to-day.

I had big plans for this year. I created a [website](https://melissahoughton.dev), started a blog and applied to speak at conferences. I had goals to post once a month and complete ten public speaking events this year. I joined the organising committee for [DDD Melbourne](https://www.dddmelbourne.com/) and another group that was brainstorming the future of the .NET community. I was eager to get involved and be proactive in the tech community. I finished one blog post and was accepted to speak at [Full Stack Day, New Zealand](https://www.fullstackday.com/2020/) in March.

Then the pandemic hit.

Company-wide travel restrictions and self-quarantine for international travellers meant the conference in New Zealand could not happen.

Working from home became mandatory. We all had to adjust to a new way of doing things, with no end in sight.

I hoped that working from home would mean more time to get things done. I would have more time to write blog posts, conference talks and learn new technologies.


### I was wrong.

We've been working from home now for six weeks. Some days are better than others. One week I was very productive, accomplished all my tasks and was positive about my work. The next, I had trouble concentrating, was not able to focus, felt down and angry at myself for not achieving as much as I thought I should be.

My big plans fell to the waste side as I tried to figure out how to make this all work.

Many people are worse off than I am, having to look after kids while trying to work, or not able to work at all. I am grateful I am still able to work, but that does not mean it is unchallenging. This pandemic has impacted us all in different ways.

The purpose of this post is not to be all doom and gloom but instead to tell you that it is ok and you are not alone. Not everyone can accomplish more or learn a new skill. It is ok to have a glass of wine, to have good days and bad, to struggle to keep on top of routine tasks. The conference talks and new skills can wait. Take care of yourself and do what is best for you. **We will get through this.**
Chain of responsibility
Tags: oop, designpatterns
Published: 2020-04-26 04:18:37

How could I explain the Chain of Responsibility pattern to myself?

# What is the Chain of Responsibility?

A series of classes or functions that are capable of handing certain requests.These handlers are connected in a linked list where each handler is aware of the next handler in the list, or chain. If a handler is not capable of handling the request then it calls the next providing the request.
The chain may be implemented such that multiple handlers can contribute to the completion of a single request. In this the request will need to be updated before being passed to the next handler.

# Why is that a good idea?
* It allows handers to be added or removed with minimal change to existing code.
* It allows handlers to be re-ordered without editing the handlers or making large code changes.
* Allows handling logic to be decoupled from other handling logic and tested independently.

# Where would you use it?
* At times where the execution order is likely to be changed often or dynamically.
* At times when methods of processing a request need to be added or removed with minimal code changes or dynamically 
* To simplify complex if, else logic chains and decouple them into testable components.

# ATM example. 
The canonical example for explaining how the Chain of Responsibility works is using an ATM. Each denomination of money is provided as a handler. Ordered from largest to smallest.
 
To return $125
The $50 note handler run first scheduling 2 $50 notes to be given to the user and passes the request to the next handler. 
The $20 note handler runs second scheduling 1 $20 note to be given to the user and passes the request on again. 
The $10 note handler is not able to process the request and passes the request on.
The $5 note handler schedules 1 $5 note.
With nothing left to return the recursion completes and the scheduled money is given to the user.

# What could go wrong?

* No fall back handler. 
If no handler is specified to handle a command that is is unknown or not capable of being processed then there is a chance that the system will throw a null reference exception or complete without having finished processing the request.

* Can be implemented in a way that tightly couples the order of the strategies
Each handler should not be hard coded to know what is next in the chain. This creates unnecessary and undesirable coupling between the handlers. The next handler in the chain should be passed in as part of the constructor or be set by a higher order class.  
In the above example if the machine is out of $20 notes it should be able to dynamically remove the $20 handler without having to be re-coded.
Designing from scratch
Published: 2020-04-26 04:01:59

One thing I started to wonder, and challenge myself with, is to design work from scratch. What I mean by this is if I'm curious on figuring out how to make something with a similar style, how can I design something so close to it?

I started to do this with CSS. I wanted to create layouts from scratch, design them in a way that will resemble something I look at every day. I didn't want to get any templates and build off that, but more just start coding. 

Boy was I in for a world of wonder. So much guess work goes into this style. Not saying this is something we should all do, I'm sure some have done it or do it now? Maybe just me? 

Basically what I learned so far is that I constantly sit and nitpick it all and try to "fine tune it". However, that just leads to frustration and a "meh oh well" outlook. 

But what I do learn about it is patience and to get comfy and that Google is really burned into my browser history. hah. 

Does anyone else ever take this approach? Does anyone have any tips or strategies?
How to delete file from aws s3 bucket
Tags: aws
Published: 2020-04-26 03:38:45

```js
const s3 = new AWS.S3({
  accessKeyId: process.env.AWS_ID,
  secretAccessKey: process.env.AWS_SECRET,
});

const params = {
    Bucket: process.env.AWS_BUCKET_NAME,
    Key: `folder/subfolder/filename.fileExtension`
};

s3.deleteObject(params, (error, data) => {
  if (error) {
    res.status(500).send(error);
  }
  res.status(200).send("File has been deleted successfully");
});
```