teleren/devto huggingface dataset:
Reasons to prefer Map over Object in JavaScript
Published: 2020-12-11 03:59:17

A map is one of the most frequently used data structures. It keeps key-value pairs that can easily be accessed by their keys. 

```javascript
const map = {}; 
map['key1'] = 'value1'; 
map['key2'] = 'value2'; 
map['key3'] = 'value3'; 

// check if map contains key
if (map['key1']) {
    console.log('Map contains key'); 
}

// get value with specific key
console.log(['key1']); 
```

<hr>

# Reasons to prefer **map** over the object in JavaScript

### More key types
An object can only have symbols or strings. A map can have any type of value as a key: objects, functions, or primitives. 

### Direct iteration
An object must be iterated by getting the keys and iterating over them. 
A map can be iterated directly. 

```javascript
for (let [key, value] of map) {}
 // Map Iteration

for (let key of Object.keys(plainObjMap)) {
    const value = plainObjMap[key]; 
} // Object Iteration
```

### Key order 

Object keys are not guaranteed to be in a specific order before ECMAScript 2015. 
Map guarantees that keys appear in the order of insertion. 

### No key overriding
The object already contains some keys on creation because of its prototype. The map does not contain any keys on creation. 


```javascript
const map - new Map(); 
map.set('toString', 2); // No problem for Map

const plainObjMap = new Map(); 
plainObjMap['toString'] = 3; // Error
```

> Note: Since ECMAScript 2015, Accidental key overriding can be avoided by using `Object.create(null)` to create an object. 

### Better size determination
Object size has to be determined in a hard way and it takes 0(n) steps. 
The map can provide size property and it takes0(1) time. 

### Better performances
Maps are optimized for frequent addition and removal of entries. Moreover, the number of entries of a Map can be retrieved in constant time. 
It is not necessary to convert any key into a string, which can save a lot of time. 

<hr>

😎 Thanks For Reading | Happy Coding ⚡
Day: 0 - Starting A 100-day challenge to create Something.
Tags: vue, javascript, mongodb, php
Published: 2020-12-11 03:56:54

I heard a lot of people have been posting tweets and posts about their adventure about the 100-day challenge in programming.

So starting tomorrow I will start on a simple idea that I just planned it's a simple web app. My target will be on desktop and mobile devices.

I will be creating a task delegation app for a team of developers. It's a simple Idea but lets to make it.

The tools that I will be using for this project is Vue js with Buefy(Bulma). Also for the mobile, I will be using the PWA approach since it is easy to configure.

I will post my progress here in Dev.to and on my Twitter.

{% twitter 1337244787003465730 %}
Python basics
Tags: python, coding, programming, computer
Published: 2020-12-11 03:39:13

If you are also a newbie in python and struggling with any of the concepts of python, this post is for you. I have listed the basic and trending posts of pythonschool.xyz and you can go to any one of them to clear your doubts.


Importance of python-
https://beginnerspythonbysanatjha.blogspot.com/2020/08/beginners-python-1-introduction.html


Hello, world-
https://beginnerspythonbysanatjha.blogspot.com/2020/08/beginners-python-4-print-function.html


Variables-
https://beginnerspythonbysanatjha.blogspot.com/2020/08/beginners-python-5-variables.html


Arithmetic operators-
https://beginnerspythonbysanatjha.blogspot.com/2020/08/beginners-python-6-arithmetic-operators.html


Data types-
https://beginnerspythonbysanatjha.blogspot.com/2020/08/beginners-python-7-data-types.html


Input Function-
https://beginnerspythonbysanatjha.blogspot.com/2020/08/beginners-python-8-input-function.html


Basic calculator project -
https://beginnerspythonbysanatjha.blogspot.com/2020/08/beginners-python-9-calculator.html


String concatenation - 
https://beginnerspythonbysanatjha.blogspot.com/2020/08/beginners-python-10-string-concatenation.html


String Slicing - 
https://beginnerspythonbysanatjha.blogspot.com/2020/08/beginners-python-11-string-slicing.html


Booleans -
https://beginnerspythonbysanatjha.blogspot.com/2020/08/beginners-python-12-booleans.html


Conditional Statements - 
https://beginnerspythonbysanatjha.blogspot.com/2020/08/beginners-python-13-conditional.html


User-defined functions - 
https://beginnerspythonbysanatjha.blogspot.com/2020/09/beginners-python-14-user-defined.html


Lists - 
https://beginnerspythonbysanatjha.blogspot.com/2020/09/list.html


Tuples - 
https://beginnerspythonbysanatjha.blogspot.com/2020/10/beginners-python-16-tuples.html


Dictionaries - 
https://beginnerspythonbysanatjha.blogspot.com/2020/10/beginners-python-17-dictionaries.html



Happy Learning!😊
Happy Coding!🤗
|HTML| HTML: Creating Dynamic HTML with Templating
Tags: javascript, html, css, webdev
Published: 2020-12-11 03:26:37

---
title: |HTML| HTML: Creating Dynamic HTML with Templating 
published: true
description: 
tags: javascript, html, css, webdev
//cover_image: https://direct_url_to_image.jpg
---



              -What is Templating
              -Setting the Views Directory
              -Conditionals in EJS 
              -Loops in EJS 
     
   



###What is Templating
Templating allows us to define a preset "pattern" for a webpage, that we can dynamically modify. 
It is possible to define a single "search" template that displays all the results for a given search term. We don't know what the term is or how many results there are ahead of time. The webpage is created on the fly. 

EJS is embedded JavaScript templating engine that is used with node JS. 
<%= EJS %> 

https://ejs.co/



```

{% extends "base.html" %}
{% block header %} 
<h1>{{ title }}</h1> 
{% endblock %}

{% block content %} 
<ul> 
{% for name, item in items %} 
<li>{{ name }}: {{ item }}</li> 
{% endfor %} 
</ul>
{% endblock %}

```


###EJS Interpolation Syntax
These are taken from the website. 

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


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

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






###Conditionals in EJS 


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


###Loops in EJS 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/hndkeb3ehopan5iks5uu.png)
|Express| Express: Creating Servers with Express
Tags: javascript, html, css, webdev
Published: 2020-12-11 03:23:52

---
title: |Express| Express: Creating Servers with Express 
published: true
description: 
tags: javascript, html, css, webdev
//cover_image: https://direct_url_to_image.jpg
---

The focus of this post was to include new information from Colt Steele Web Developer Bootcamp Updated Version.  
HTML: The Essentials
           

              -Introducing Express
              -The Request and Response Objects  

              



      
    
            
            
         


###Introducing Express
Express is a fast minimalist web framework for Node.js. It helps us build web apps. 
It is NPM package which comes with a bunch of methods and optional plugins that we can use to build web apps and API's. 

Express helps us start up servers to listen for request, parse incoming requests, match those requests to particular routes, and craft our http response and associated content. 

Libraries vs. Frameworks 

Library is when you control the flow of the application code, and you decide when to use the library. 

Framework is in control of the flow of the application code, frameworks tells you where to plug in the code.
Code Smell 49 - Caches
Tags: oop, webdev, codenewbie, caching
Published: 2020-12-11 03:21:38

*Caches are sexy. They are a one-night stand. We need to avoid them in a long-term relationship.*

# Problems

- Coupling

- Testability

- Cache invalidation.

- Maintainability

- Premature Optimization

- Erratic Behavior

- Lack of transparency

- Non-Deterministic behavior

# Solutions

1. If you have a conclusive benchmark and are willing to pay for some coupling: Put an object in the middle.

2. Unit test all your invalidation scenarios. Experience shows we face them in an incremental way.

3. Look for a real world cache metaphor and model it.

# Sample Code

## Wrong

{% gist https://gist.github.com/mcsee/c429e71f6b0239b83e7e307feb5927fe %}

## Right

{% gist https://gist.github.com/mcsee/7b6a2b5eb49cbb4dc690a2657d6837d0 %}

# Detection

This is a design smell.

It will be difficult to enforce by policy.

# Tags

- Premature Optimization

# Conclusion

Caches should be functional and intelligent

In this way we can manage invalidation.

General purpose caches are suitable only for low level objects like operating systems, files and streams. 

We shouldn't cache domain objects.

*This page is hosted on a cached website.*

# Relations

{% post https://dev.to/mcsee/code-smell-20-premature-optimization-4moe %}
 
# More Info

[Common Cache Usages](https://dev.vamsirao.com/what-is-cache-and-common-ways-of-using-it)

[Caching Patterns](https://frankel.hashnode.dev/a-hitchhikers-guide-to-caching-patterns)

# Credits

Photo by <a href="https://unsplash.com/@vogelina">Aimee Vogelsang</a> on <a href="https://unsplash.com/">Unsplash</a>

* * *

There are only two hard things in Computer Science: cache invalidation and naming things.

_Phil Karlton_
|NODE| NODE: Exploring Modules and the NPM Universe
Tags: javascript, html, css, webdev
Published: 2020-12-11 03:21:07

---
title: |NODE| NODE: Exploring Modules and the NPM Universe
published: true
description: 
tags: javascript, html, css, webdev
//cover_image: https://direct_url_to_image.jpg
---





              -Introducing Node JS
              -What is Node Used For
              -Introducing NPM 

     

###Introducing Node JS
What is node? Node is a JavaScript runtime. 
Node is JavaScript outside of the browser. 
Node makes it possible to write server-side code with JavaScript. 



###What is Node Used For
Node can be used for web servers, command line tools, native apps, video games, and more. 
Express is a framework for node. 



###Introducing NPM 
NPM is node package manger which is a library of thousands of packages published by other developers that we can use for free. 
NPM is also a command line tool to easily install and manage those packages in the node project.
|AJAX| AJAX: AJAX and API's
Tags: javascript, html, css, webdev
Published: 2020-12-11 03:19:42

---
title: |AJAX| AJAX: AJAX and API's 
published: true
description: 
tags: javascript, html, css, webdev
//cover_image: https://direct_url_to_image.jpg
---



              -Intro to AJAX
              -Intro to API's
              -Using Postman
              -Query Strings 
              -Making XHR's 
              -The Fetch API




###Intro to AJAX
AJAX stands for asynchronous JavaScript and XML. The process is a concept of making requests to load information or to send information to save something behind the scenes on a given website or on a given application, seamlessly. 


###Intro to API's
API is application programming interface. API is more about one piece of software to another piece of software that doesn't have to be separate computers. API do not even need to be involved with the web in general. 

Web Apps are interfaces that are web based, HTTP based. 
Web APIs are like a portal into a different application or database somewhere or a data set or just some start up information. 

Web API occurs over HTTP. 

URLs are sometimes called endpoints. 

Interfaces are for applications to read not humans. 



###Using Postman
Postman is used to make a bunch of requests to different apps and learn more about how HTTP requests are structured, different status codes, headers in a request with a query string.
 
https://www.postman.com/


###Query Strings 
q= is known as the query string. It is used to provide additional information to the request within a URL. 



###Making XHR's 
XMLHttpRequest is the original way of sending request via JS. 
Does not support promises. 

```javascript 

const myReq = new XMLHttpRequest(); 

myReq.onload = function() {
 const data = JSON.parse(this.responseText); 
 console.log(data); 
};

myReq.onerror = function(err) {
 console.log('Error!', err); 
}; 

myReq.open('get', 'https://icanhazdadjoke.com/',true);
myReq.setRequestHeader('Accept', 'application/json');
myReq.send(); 

```




###The Fetch API
This is the new way of making HTTP request using javascript. It has replaced XMLHttpRequest. Fetch API supports promises. 

```javascript 

fetch('https://api.cryptonator.com/api/ticker/btc-usd')
 .then(res => {
   console.log("Response, waiting to parse...", res) 
     return res.json()
  })
  .then(data => {
    console.log("Data parsed...") 
    console.log(data.ticker.price)
  })
  .catch(e => {
   console.log("Oh no! Error!", e) 
  }) 

```
Started Python 100
Published: 2020-12-11 03:18:17

Day 1 - Band Name Generator:


print("Welcome to band name generator")

user_city = input("What city did you grew up in?\n")
user_pet_name = input("What is your pet's name?\n")
band_name = user_city + " " + user_pet_name
print("Your band name will be", band_name)


Day 2 - Tipping Calculator:

print("Welcome to the tip calculator")
total_bill = float(input("What was the total bill? "))
tip_percent = int(input("What percentage tip would you like to give? 10, 12, or 15? "))
split_bill = int(input("How many people to split the bill? "))

tip_amount = total_bill * tip_percent / 100
result = (total_bill + tip_amount) / split_bill
print(f"Each person should pay {result}")

Day 3 - Treasure Island:

print("Welcome to Treasure Island.")
print("Your mission is to find the treasure.") 
choice1 = input("You are at a crossroad, where do you want to go? Type left or right").lower()

if choice1 == "left":
  #Continue in the game
  choice2 = input("You have come to a lake. There is an island in the middle of the lake. Type wait to wait for a boat. Type swim to swim across.").lower()
  if choice2 == "wait":
    #Continue in the game
    choice3 = input("You arrive at the island unharmed. There is a house with 3 doors. One red, one yellow and one blue. Which colors would you choose?").lower()
    if choice3 == "red":
      print("You die. Game over!")
    elif choice3 == "yellow":
      print("You found the treasure. You win!")
    else:
      print("You die. Game over!")
  else:
    print("You got attacked by an angry trout. Game over!")
else:
  print("You fell into a hole. Game over!")
How to empty an array in JavaScript
Tags: javascript, node, tutorial, tricks
Published: 2020-12-11 03:17:55

The simple way to empty an array in JavaScript is through assigning **0** to the property **length** of the array affected. For Example

```
let numbers = [1,3,5,7,9];

numbers.length = 0;

console.log(numbers);
// []

```

This is possible because the **length** property is read/write property in an array. Therefore, you can assign zero and the array will be clear.
The AWS Well-Architected Framework and it's 5 Pillars - Part 5
Tags: aws, architecture
Published: 2020-12-11 03:13:11

The continuation of the **The AWS Well-Architected Framework and it's 5 Pillars Series**.

For the others who haven't yet read the initial part of this series, please read the previous parts above or below this article.

Let's continue on diving deep and this time let's venture the **Security** realm to gain knowledge on what are the key areas, what questions you must conquer and what are the key phases involve in this pillar for us to satisfy it's standards.

## **Security**
*... the ability to protect information, systems, and assets while delivering business value through risk assessments and mitigation strategies...*

Simply saying, *We need to ensure that our workload will ONLY work as intended*

To satisfy this pillar, your architecture needs to **apply the best security practices** by being aware on these key areas:
- Identities have the least privileges required
- Know who did what? When?
- Security is woven into the fabric of the system
- Automate security tasks
- Encrypt data in transit and at rest
- Prepare for the worst

### Phases
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/bkcrbutgh2cve465vyvl.PNG)

#### **Identity Access Management (IAM)**
Only authorized and authenticated users can take action:
- Who is allowed to do what? when?
- Are you applying least privileges
- Deny root and full access
- Regularly review access and privileges

#### **Detective Controls**
Look for abnormal behavior in your workload:
- Capture and analyze logs
- Regularly audit controls and configurations
- Look for unauthorized or unexpected changes
- Monitor workload behavior for abnormalities

#### **Infrastructure Protection**
Defense in depth:
- Establish trust boundaries
- Protect network in/out
- Protect all hosts
- Configure services to meet security posture needs
- Enforce service level protection

#### **Data Protection**
Classify and protect your data:
- How sensitive is the data
- Who should have access? when?
- Encryption in transit
- Encryption at rest
- Back and test backups of data

#### **Incident Response**
Contain and recover from *unplanned* events:
- Do you have a plan to tag affected resources?
- Can you adjust permissions to allow for containment?
- Can you redeploy to recover quickly?
- Did you learn from the incident and adjust?

The key takeaways in this pillar is *Built-In, Not Bolt-On - Security is a critical part of the fabric of your workload*. Whatever you built you need to ensure that it is doing what you want it to do, and only that.

Overall, the Well-Architected Framework and together with its pillars are the guiding lights on achieving value to you business.
 
Remember, it's all about balance, finding the right balance at the same time making trade-offs that depends on your workload.

__Follow or Connect with me__:

[Dev.to](https://dev.to/edwardmercado)
[Twitter](https://twitter.com/edwardmercado_)
[LinkedIn](https://www.linkedin.com/in/edwardallenmercado-677b69139)
Setting up your Linux Environment for Competitive Coding(with Geany, in C++)
Tags: programming, productivity, discuss, ubuntu
Published: 2020-12-11 03:00:08

In this article, we will learn how to setup an all-in-one Competitive Programming Environment.

<h1>Operating System</h1>
As mentioned above, we are gonna be using an OS, which comes under the Linux Distro. There are many popular distro out there, but for starters, <b>Ubuntu</b> is recommended, Kali and Arch Linux are for advance user.
If you are a Windows lover, then stick to Windows 7 or above versions.
<h1>Text Editor</h1>
There are many text editors out there, and you are open to choose from any one of it.
Since this post mainly focuses on the Linux Environment setup, I would prefer a text editor which is maintained by the open source community:- <b>Geany</b>. Its not the most convenient, but perfect for competitive programming.
There are other options as well:-
<ol>
   <li>VScode</li>
   <li>Sublime(is lightweight, and minimally aesthetic </li>
   <li>Notepad++</li>
   <li>Atom</li>
</ol>
<h1>Lets set up Geany</h1>
<h2>Installation</h2>
First thing first, we need to install it. You are open to install it either from <b>Ubuntu Software</b> or from the <a href="https://www.geany.org/"> Official Geany Website</a>.
You can also install using the terminal, copy the commands in your terminal:
For Ubuntu/ Debian:-
<i>sudo apt-get install geany</i>
For Fedora:
<i>sudo dnf install geany</i>
For CentOS:
<mark>sudo snap install geany-gtk --edge</mark>
<a href ="https://plugins.geany.org/">You can also install plugins</a>
<h2>Configure</h2>
Once you are done with installation, you can find Geany, using the search bar. 
<h3>KeyBindings</h3>
<ol>
<li>Edit->Preferences->Keybindings</li>
<li>Head to focus.<li>
Now change the following:
<ol>
<li><b>Switch to Editor-></b> F1</li>
<li><b>Switch to VTE-></b> F2</li>
</ol>
</ol>
<h3>Terminal</h3>
<ol>
<li> Head to terminal, and select the check box Follow path of the current file. </li>
</ol>
<h3>Build and Compile</h3>
<ol>
<li> First create any C++ file by typing anything in the text editor, and save it by cntrl+s, with a .cpp extension</li>
<li> Head to Build->Set Build Commands</li>
<li> Copy the following flags with the corresponding commands:-</li>
<ol>
<li>
Compile (F8): g++ -std=c++17 -Wshadow -Wall -o "%e" "%f" -O2 -Wno-unused-result  
</li>
<li>
Build (F9): g++ -std=c++17 -Wshadow -Wall -o "%e" "%f" -g -fsanitize=address -fsanitize=undefined -D_GLIBCXX_DEBUG
</li>
</ol>
You may get compilation error, if so, then try changing from C++17 to C++14, or remove the two sanitizers.
</ol>

<p>
This is the basic set up for Competitive Programming in a Linux Environment, you can obviously set up another text editor like Sublime, with the other settings as well. I will make a post on that very soon.
<p>
<b>Credits:<b> The flags that I have used here, has been provided by Errichto, <a href="https://github.com/Errichto">Link to GitHub</a>
Thank You!
After complete setup, the environment should look like this:![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/r7mprwfvst8f5acuw4ba.png)
DAY 10 - Advent of Code 2020 w/ GoLang
Tags: go, adventofcode
Published: 2020-12-11 02:57:50

---
title: DAY 10 - Advent of Code 2020 w/ GoLang
published: true
description: AoC 2020 Day10 solutions in GoLang
tags: golang, AdventOfCode
series: Advent of Code 2020
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/gb6jnhz1didpnth3pbsw.jpeg
---

**DAY10:**
Woof. Be warned, part one is *DECIEVINGLY* simple. Part two had me thinking about implementing a binary tree, which in Go gets terribly verbose. Half-ish way through that approach, I dumped it and started over. Then attempted to recurse while removing indexes after they'd been evaluated. That eventually evolved into implementing a *sliding window* recursion approach. I slid and evaluated on if the index landed within the acceptable joltage range. ALSO, don't forget the built-ins.


```golang
package days

import (
	"fmt"
	"sort"

	inputs "../inputs"
)

// https://adventofcode.com/2020/day/10
// Ten : advent of code, day ten part1 and 2
func Ten() {
	inputSlice := inputs.Day10

	// Adding in built-ins and sorting
	inputSlice = append(inputSlice, 0)
	sort.Ints(inputSlice)
	inputSlice = append(inputSlice, inputSlice[len(inputSlice)-1]+3)

	fmt.Print("(Part1) - result from multipling the 1 and 3 jolt jumps in the total adapter path: ")
	fmt.Println(numberOfOneAndThreeJoltJumpsInAdapterPath(inputSlice))

	fmt.Print("(Part2) - Number of adapter paths that result in the max joltage of is : ")
	fmt.Println(evaluateAdapterPath(inputSlice, 0))
}

func numberOfOneAndThreeJoltJumpsInAdapterPath(adapterSlice []int) int {
	ones := 0
	threes := 0

	for joltage := 0; joltage < len(adapterSlice)-1; joltage++ {
		if adapterSlice[joltage+1]-adapterSlice[joltage] == 1 {
			ones++
		} else if adapterSlice[joltage+1]-adapterSlice[joltage] == 3 {
			threes++
		}
	}
	return ones * threes
}

var adapterPathsTried = make(map[int]int)

func evaluateAdapterPath(adaptersTocheck []int, startAdapter int) int {
	workingAdapterPaths := 0
	nextAdapter := startAdapter + 1
	furthestPossibleAdapter := startAdapter + 3

	if furthestPossibleAdapter >= len(adaptersTocheck) {
		return 1
	} else if _, ok := adapterPathsTried[adaptersTocheck[startAdapter]]; ok {
		return adapterPathsTried[adaptersTocheck[startAdapter]]
	}

	for i := nextAdapter; i <= furthestPossibleAdapter; i++ {
		lower := adaptersTocheck[startAdapter]
		upper := adaptersTocheck[i]

		if (upper-lower) >= 1 && (upper-lower) <= 3 {
			workingAdapterPaths += evaluateAdapterPath(adaptersTocheck, i)
		}
	}

	adapterPathsTried[adaptersTocheck[startAdapter]] = workingAdapterPaths
	return workingAdapterPaths
}

```

[Link to Github source file](https://github.com/dizveloper/AdventOfCode/blob/main/2020/days/day10.go)