teleren/devto huggingface dataset:
Iterator Pattern
Published: 2020-03-12 07:19:57

# Iterator Design Pattern 
### *Also known as Cursor*

GitHub link: https://github.com/FrancescoXX/Design-Patterns-Iterator-Javascript
___

## Behavioral Design Pattern

## ⚡️Recognize 

We want to separate the logic of how to access data from data itself
___

## 💡Intent

Provide a way to access the elements of an aggregate object sequentially, without exposing its representation
___


## 🔧 Apply when

We want give a way to access elements in such a way that it does not expose its internal structure;
The Iterator takes the responsibility for access and manipulation of the data structure
___

## ✅Pro

- We can define different iterators for different ways of manipulating a data structure
- Clients can use an iterator to access data without knowing the representation

___

## 🏆 Great for

Decoupling algorithms from containers

___

```javascript
/** Iterator Design Pattern
 *  Behavioral Pattern
 */

/**
 * @function hasNext returns true/false, depending 
 *                   if the iterator has other elements in the collection
 * @function next returns the next available element in the collection
 */
class Iterator {
  constructor(items) {
    this.items = items; //The collection to iterate to
    this.index = 0; //Starting index
  }

  hasNext = () => this.index < this.items.length; //Returns TRUE if there's another element, FALSE otherwise
  next = () => this.items[this.index++]; //Rule for next element
}

// MAIN

//Define a collection
const animals = ["dog", "cat", "bird", "tiger", "lion"];

//Define an Iterator
const iterator = new Iterator(animals);

//Iterate over each Element
while (iterator.hasNext()) {
  console.log("[", iterator.index, "] :", iterator.next());
}

// [ 0 ] : dog
// [ 1 ] : cat
// [ 2 ] : bird
// [ 3 ] : tiger
// [ 4 ] : lion



```


GitHub link: https://github.com/FrancescoXX/Design-Patterns-Iterator-Javascript
Explain RBAC vs ACL Like I'm Five
Tags: explainlikeimfive
Published: 2020-03-12 07:02:25

---
title: Explain RBAC vs ACL Like I'm Five
published: true
tags: explainlikeimfive
---
HeyHo DEVs, 

I want to implement a permission system for my small flat file cms [Typemill](https://typemill.net) and I am not super sure, if I should follow RBAC or ACL. What the heck is the difference? I want to create roles like this: 

* "reader" (public access), 
* "member" with auth and access to "member" content
* "customer" with auth and access to "paid" content
* "author" with auth and access to his own articles
* "editor" with auth and access to all articles, but no rights like publishing
* "publisher" with publishing rights.
* "admin" with access to admin settings.

Everything with enough flexibility.

So what should I use?
React Mobile App Consult
Tags: react, reactnative, ios, android
Published: 2020-03-12 07:00:36

to all mobile experts

once our Android developed via React Native is about to finish,
what should be the next "mobile" project using the same database & backends?
between
1) React Native on iOS
or 2) React web on mobile
in terms of resources worth returns (ROI)

ps. the mobile app has special backends of video call (webRTC) and chat (Pulsar)
Wrote a new article on Medium!
Tags: coding, coder, selfhelp, motivation
Published: 2020-03-12 04:43:27

The article is about 5 key things that a Junior Developer needs to hear from a Senior Developer at the earliest.

Do check it out and let me know your views 

{% medium https://medium.com/@gurkeeratsingh_5281/things-no-one-tells-a-developer-who-is-just-starting-out-2bcafd4b60c7 %}
【WordPress】ページネーションがあるページのnoindex,canonical対応
Tags: php, wordpress, seo
Published: 2020-03-12 04:41:46

```
<?php
$url = $_SERVER['REQUEST_URI'];
if(strstr($url,'/page/')==true):
?>
<meta name="robots" content="noindex,follow">
 <?php
      $cat = get_the_category();
      $cat_id = $cat[0]->cat_ID;
      $link = get_category_link($cat_id);
    ?>	
<link rel="canonical" href="<?php echo $link; ?>">
	
<?php else: ?>
<link rel="canonical" href="<?=home_url().$_SERVER["REQUEST_URI"]; ?>">
<?php endif; ?>	
```
Day 1 [D&D Character Sheets]
Tags: 100daysofcode
Published: 2020-03-12 04:21:40

# Report
Today was the first day of my 100 days of code challenge, I mostly worked on the initial setup. I worked for about an hour just getting everything installed, setting up the file structure and etc. When I finished I copied the code to a boilerplate repo that should make starting express projects easier in the future. At least I have a pretty good express boilerplate now!
{% github ApproachingApathy/express-boilerplate %}

# Project
{% github ApproachingApathy/100days-dnd-character-sheets %}

The First project will be an app to keep D&D character sheets.

## Stack

I'll be using Node.js and building a full-stack Express app with MongoDB.
### Requirements
#### Minimum Viable 
- [ ] Present a D&D Character Sheet
    - [ ] The sheet should display all the same info as the first page of the 5e Official sheet.
- [ ] Users should be able to log in and create player-characters.
- [ ] Users should be able to edit character sheets.
- [ ] Users should be able to organize character sheets into groups (parties/tables)
- [ ] Sheets should auto calculate basic stats like ability modifiers.
    - [ ] Support Proficiency Bonuses 

### Cake
- [ ] Extend character creation to allow the user to use any of the three common stat gen methods.
    - [ ] Point Buy
    - [ ] Standard Array
    - [ ] Roll
- [ ] Extend the character sheet to all the info in the 5e official sheet.
- [ ] Allow for image uploads for character portraits.
- [ ] Allow for extended descriptions/backstories.
    - [ ] Characters should have nice full page backstories.
    - [ ] Preferably use a markdown editor.
Let's do the accessibility audit on the live product
Tags: a11y, webdeveloper, product
Published: 2020-03-12 04:06:51

---
title: Let's do the accessibility audit on the live product
published: true
description: accessibility, accessibility testing, accessibility audit
tags: accessibility, web developer, product
---

In India, unfortunately very few people are aware of the 'accessibility'. Tech folks who should be advocating and shipping accessible products they themselves are not aware of it much. As a result, we have non-accessible products in the real world.  The blame should be shared by the PMs and product owners as well as for not supporting accessibility.

In India, [Swiggy](https://swiggy.com) is the most famous food ordering app. They are almost 5 years old startup doing pretty good. I myself is the biggest user of the Swiggy. They basically connect all the small to big food vendors and deliver the food at your doorstep with nominal fee charges. This was a big revolution in India as before Swiggy we have to order at least a minimum amount of food and then only we can get home delivery.

I did the accessibility review of their desktop site and my main aim was keyboard support.

Overall the desktop site is not accessible by keyboard. I am not able to:

- Access login or signup link
- Not able to change the location
- Not able to access 'locate me' from the search bar
- Not able to again access 'signup' from an internal page
- Not able to add the product to the cart

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

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

I did the most basic keyboard testing in that it failed so badly. So, far I haven't done the color contrast, structure, and screen reading testing.

Lighthouse scores look good BUT in real-time testing, it failed.
NLP code search and annotation
Published: 2020-03-12 04:06:15

Hey!

I'm a 19-year old engineer and I've done software development at various Big 5 companies, and realized how annoying and frustrating searching for code can be.

I'm working on a new tool to help software engineers and want to hear what would be useful for you -- when you navigate your codebase, what are you looking for?

If you want to keep updated on my current progress, sign up online or check it out on Product Hunt:

Product Hunt: https://www.producthunt.com/posts/expressiv

Website: https://expressiv.ai/

Feedback Form: https://expressiv.typeform.com/to/K4O4C5

Thanks so much!
JavaScript - Abbreviate Numbers 
Tags: javascript, snippet, utils
Published: 2020-03-12 03:55:36

# Case

 I am working into a website in which I handle with a lot of data and by this, the end user (client) shall see the results and values. So, I was caught into a problem... The overall display of the values.
 While in some cases for the user, it will be interesting to see the raw value (like, 13.640.333.000)... in another, just the abbreviation of the  value will be acceptable (13.64 B).
 So I went to look forward a way to solve this problem of mine — looking around the community. But, the scripts that I have found either is "heavy" for this purpose or it is very fancy for this.
 Then... I end up creating my own, tiny solution... 

# Warning

 As I'm pretty busy with my works recently, I'll not be able to share my codes with the community (I'll share some 'react hooks' and snippets that I use often).
However, since I feel that this can be very useful... I'll share here xD

# Code

```js
/**
 * Abrreviete the number by unit
 * @param {Number|String} number
 * @param {Object} config
 * @param {Boolean} config.absolute if it will replace the 'x.yyy', '.yyy', for
 * empty space. Like, '13.4' to '13'
 * @param {Number} config.factor the factor on 'toFixed'
 * @param {Array} config.unit
 * @param {Boolean} config.numeric if the final value will be the type 'number'
 * or 'string'
 */

function abbreviate (number, config = {}) {
    if (typeof config !== 'object') config = {}
    if (!config.hasOwnProperty('factor')) config.factor = 2
    if (!config.hasOwnProperty('absolute')) config.absolute = true
    if (!config.hasOwnProperty('unit'))
        config.unit = ['', 'K', 'M', 'B', 'T', 'Q']
    if (!config.hasOwnProperty('numeric')) config.numeric = false
    let value = String(number).replace(/(\.|\)|\(|\,)/g, '')
    let length = value.length - 1
    const unit_index = ~~(length / 3)
    value = eval(
        `parseFloat(${value} / 1e${unit_index * 3}).toFixed(${config.factor})`
    )
    //console.log(config)

    if (!!config.absolute) value = value.replace(/\.(\d+)$/, '')
    return !!config.numeric ? +value : `${value} ${config.unit[unit_index]}`
}

```

# How to Use
  Copy the code on the DevTools of your Browser and let's test it xD

## Default
 You can use the standard way...
 Like:

```js
abbreviate("123458886")
// "123 M"
```

or to control decimal places

```js
abbreviate("123458886", {absolute: false, factor: 3})
// "123.459 M"
```

# Bye

 Well, that is it... If it helps you or if you have some feedback/suggestion, let me know :)... Any doubt, please, comment as well
What topics are you interested in?
Tags: webdev, html, css, discuss
Published: 2020-03-12 02:02:42

I want to make more content for design and development, but I want your help.

[**What are the topics or ideas you want me to cover?**](https://twitter.com/adrian_twarog/status/1237914713834418179)

Here are some already on my list. But if you have ideas for things more specific, please leave them in the comments below!

- UI 📘
- UX 👦
- CSS 👓
- SASS 💅
- HTML 👨‍💻️
- Animation ➡️
- React ⚛️
- React Native 📱
- NodeJs 💻
- State 💾
- JavaScript 📲
- API's 🔰
- Webhooks 🔱
- Databases 🔘
- Frameworks ⏹
- IE compatibility 😨

If you don't know of me, I am [Adrian Twarog](https://twitter.com/adrian_twarog), and am trying to work provide fun and interesting topics on designing websites and developing apps. 

[![Adrian Twarog Youtube](https://adriantwarog.com/wp-content/uploads/2020/03/p-1.png)](https://www.youtube.com/adriantwarog?sub_confirmation=1)
<center><strong>[Youtube: Adrian Twarog](https://www.youtube.com/adriantwarog?sub_confirmation=1)</strong></center>

Love to hear your feedback!

Thanks
HTML Demo: Whitespaces and Newlines
Tags: codepen
Published: 2020-03-12 02:24:20

{% codepen https://codepen.io/minae/pen/QzYpLj %}

This is a project I did on codepen. I was wondering if there's a better way to format the poem at the bottom this way than to just add a ton of $nbsp; tags where they need to be?

#beginners #html #css
Cloud in a budget: Preemptible instances to the rescue  
Tags: cloud, infrastructure, gcp
Published: 2020-03-12 02:22:24

---
title: Cloud in a budget: Preemptible instances to the rescue  
published: true
description: 
tags: #cloud #infrastructure #gcp
---

# Saving costs on cloud
For those on a tight budget, 
Google Cloud [Preemtible VMs](https://cloud.google.com/preemptible-vms) is one of my favorite offerings.

Preemptible VMs are restarted (recycled) every 24 hours which make them a great fit for stateless workloads. The benefit of those VMs comes in pricing. Prices for a 24/7 VM running on us-central1: 

| Configuration | Regular | Preemptible |
| ------------- |:-------------:| -----:|
| E2 4vCPUs 16GB RAM     | $97.84 | $29.35 |

As you can see, there's a huge cost saving in leveraging them. Consider the cost savings for your testing enviroments alone.

# Wait what about serverless?

A lot of people may point out that you should use serverless for stateless workloads, since it's a managed offering.

And while that is indeed true for most cases, there are still several workloads that would not make sense on a serverless environment.
 
One of the main shortcomings of serverless offerings is the fact that you can't run long running processes.

Another issue is the fact that many serverless offerings would not allow you to customize the sandbox environment ([Google Cloud run](https://cloud.google.com/run) fixes this by letting you bring your own container with your pre packaged libraries, and lambda layers also help in that front).

# Quasi-stateful machines

Ok, so preemtible VMs can't really run stateful workloads, but it doesn't mean you can't have state. That is possible by attaching a persistent disk to your instance.

The data on the boot disk gets discarded on every restart, but not the persistent disk.

GCE instances can run scripts during the startup and you can attach one or more disks to it. The script bellow would mount and format (if not already) any disk on /dev/sdb

```bash
#!/bin/bash

if sudo blkid /dev/sdb;then 
   exit
else 
   sudo mkfs.ext4 -m 0 -F -E lazy_itable_init=0,lazy_journal_init=0,discard /dev/sdb; \
   sudo mkdir -p /mnt/data
   sudo mount -o discard,defaults /dev/sdb /mnt/data
fi
```

* Please be advised that a machine stop can lead to data corruption so be careful when using this approach *

# Our cheap batch workload agent

Where I found this to be very useful was running some long running (2~3 hours a day jobs) where I could use some beefier machines for video encoding tasks.

As video encoding requires a good chunk of CPU and a bunch of libraries installed on the OS. Preemptible VMs were an easy choice. To give you an idea, running a node 4 hours would cost:

| Configuration | Regular | Preemptible |
| ------------- |:-------------:| -----:|
| E2 16vCPUs 64GB RAM     | $65.22 | $19.57 |

Not too bad right? We start and stop the VMs via cloud functions and cloud scheduler (there's a place for serverless too).

So if you are in a budget, consider using preemptible VMs if your architecture requires batching or stateless workloads.

Happy coding.
CSS animation with mix-blend-mode
Tags: codepen, css, animation, mixblendmode
Published: 2020-03-12 02:21:20

<p>Spawning fruit labels from different images of fruits, using a mix of beautiful and confident animations; Experimenting with mix-blend-mode CSS animations.</p>

{% codepen https://codepen.io/knekk/pen/KKpvdwP %}
New Startup Idea 
Tags: startup, discuss, javascript, python
Published: 2020-03-12 02:15:34

So, my friend (who shall remain unnamed), has an idea and has asked me and some other high schoolers if they want to help out on it. I wanted to get some advice/opinions on what everyone else thinks of it.

I won't go too deep into the details of the startup idea but think of it as if it's an Airbnb for processing power. The idea is to open up your computer for others near you to connect to it via a P2P network and run any heavy processes they needed to run on your computer, allowing them to do other things without their computer crashing. Let me know what you think of this idea.

So, to build it he was thinking of either building it in Python, Javascript, or C++. We're probably not going to go with C++ because most of us in the group do not know C++, but let me know what you think we should build it in.

Honestly, it's not an idea I'm too crazy about, but something I'd be willing to set aside some time to work on.
Oh My Glob: alias expansion in zsh
Tags: zsh
Published: 2020-03-12 01:58:11

I'm just getting on the zsh train, and while a lot of my personal customisation work has been around getting zsh to look like my [old bashrc setup](https://opensource.com/article/20/1/bash-scripts-aliases), I just learnt of one new feature that I never used in bashrc that is going to make my zsh experience much more friendly, especially to those looking on when I'm coding. 

---

Alias Expansion is a concept where when you declare an alias

```shell
alias serveme="python -m http.server 1337"
```

Instead of just typing the alias, you hit a key sequence and it expands for you



By using the [`globalias`](https://github.com/ohmyzsh/ohmyzsh/tree/master/plugins/globalias) ohmyzsh plugin, this automatically happens when you hit <kbd>space</kbd>.

```
$ serveme▊
```

```
$ python -m http.server 1337 ▊
```

Which is really nifty because there's _no extra key presses required_, *and* it helps you remember the full command (extra points!). 

But not only that, it means that you can _greatly improve your demos_ especially when you have super long commands to run all the time.  

For example: 

```
$ tail ~/.zshrc 
alias ka="kubectl apply -f"

$ ka▊
```
```
$ kubectl apply -f ▊
```


Shout-out to [Mark](https://twitter.com/Neurotic) for the tip!
How to prevent flickering in Live Markdown Editor
Tags: webdev, javascript, incrementaldom
Published: 2020-03-12 01:48:56

Especially, for items that shouldn't load too often, like `<iframe>`.

In short, [incremental-dom](https://github.com/google/incremental-dom)

You can replace the entire HTML output with incremental DOM tree. (Much of the code comes from [here](https://github.com/yhatt/markdown-it-incremental-dom/blob/master/src/mixins/renderer.js).)

```ts
import { Parser } from 'htmlparser2'
import { elementOpen, elementClose, text } from 'incremental-dom'
import { Serialize } from 'any-serialize'

const ser = new Serialize()

export function makeIncremental (s: string): () => void {
  const open = (name: string, attr: Record<string, string> = {}) => {
    elementOpen(name, name + '-' + ser.hash(attr), Object.values(attr).flat())
  }

  const close = (name: string) => {
    elementClose(name)
  }

  const iDOMParser = new Parser(
    {
      onopentag: open,
      ontext: text,
      onclosetag: close
    },
    {
      decodeEntities: true,
      lowerCaseAttributeNames: false,
      lowerCaseTags: false,
      recognizeSelfClosing: true
    }
  )

  return () => {
    iDOMParser.write(s)
  }
}
```

About [htmlparser2](https://www.npmjs.com/package/htmlparser2), it does work in web browser, but I need to install `@types/node` (in devDependencies)...

The real project is here -- https://github.com/patarapolw/blogdown-cms/tree/heroku and it is 

- Markdown editor that supports
  - `<style>` tags that do not leak outside the scope (thanks to [stylis](https://github.com/thysultan/stylis.js))
  - Embedded PDF
  - Embedded Presentation (via [reveal-md](https://github.com/patarapolw/reveal-md))
- Presentation (reveal-md) editor
  - Via same-origin `iframe.contentWindow`

Well, [reveal.js](https://revealjs.com/) sometimes create problem for me as well. Might create my own someday.
Dark blue Login Page
Tags: codepen, javascript, typescript, showdev
Published: 2020-03-12 01:27:00

<p>Dark blue color professional login page contains username and password as input, created using HTML, CSS, gradients, font awesome, bootstrap and tsParticles(for background effect). Easy to integrate into any project.</p>

{% codepen https://codepen.io/matteobruni/pen/xxGXELa %}
tsParticles 1.9.1
Tags: javascript, typescript, showdev, npm
Published: 2020-03-12 01:19:00

# New tsParticles version released, 1.9.1.

Checkout the demo here: <https://particles.matteobruni.it>

Do you want to replace the old, outdated and abandoned particles.js?
You're in the right place!

---

Here are some demos!

## Characters as particles

[![Particles chars demo](https://media.giphy.com/media/JsssOXz72bM6jGEZ0s/giphy.gif)](https://particles.matteobruni.it/#chars)

---

## Mouse hover connections


[![Particles mouse connections demo](https://media.giphy.com/media/XzvZThpVbxHxMYz5xt/giphy.gif)](https://particles.matteobruni.it/#connect)

---

## Polygon mask

[![tsParticles Polygon Mask demo](https://media.giphy.com/media/lNRfiSgaMFbL4FMhW6/giphy.gif)](https://particles.matteobruni.it/#mask)

---

#### Background Mask particles

[![tsParticles Background Mask demo](https://media.giphy.com/media/dWraWgqInWFGWiOyRu/giphy.gif)](https://particles.matteobruni.it/#background)

---

#### COVID-19 SARS-CoV-2 particles

[![tsParticles COVID-19 demo](https://media.giphy.com/media/fsVN1ZHksgBIXNIbr1/giphy.gif)](https://particles.matteobruni.it/#virus)

**Don't click! DON'T CLICK! OH NO IT'S SPREADING!!!!**

*COVID-19 is not funny. It's a serious world problem and we should prevent its spreading. If you are in a risky area please STAY AT HOME*

--

## GitHub repo
<https://github.com/matteobruni/tsparticles>

##npm
<https://www.npmjs.com/package/tsparticles>

##jsDelivr
<https://www.jsdelivr.com/package/npm/tsparticles>

---

Feel free to contribute to the project!
Study with me #1 | Azure Durable Functions
Tags: azure, serverless
Published: 2020-03-12 01:02:31

Study with me is a series where I pick a subject I want to learn about, and I film myself figuring it out. This video covers my first attempts to learn Azure Durable Functions. Expect lots of rambling, incorrect statements, frustration, Googling, imposter syndrome, and self-doubt. Welcome to the world of engineering. 


{% youtube 4q2Q4ha0f60 %}

I plan on creating more content around Azure; it's great to share what I've been learning.


If you have ANY feedback at all, please let me know in the comments below or reach out to me on socials.

Thanks for reading and possibly watching!