teleren/devto huggingface dataset:
Exploring Javascript's Module Design Pattern
Tags: javascript, webdev, programming
Published: 2021-03-24 19:31:44

I remember that a few years back, I found it pretty hard to wrap my head around closures in Javascript. After months of struggling with them with readings, exercises, and tutorials, what helped me get a handle on them was using them in my day-to-day work. In my web and app development, I started writing immediately-invoking function expressions that used closures. My initial expressions simply had a getter and a setter, as in the function below:

<code>
var myFunc = (function() {
   let num = 0;
   return {
        get:function() {
          return num;
        },
        set:function(x) {
          num = x;
        }
   };
})();
</code>

And over time I ended up building out more complex expressions.

I later found out that I was routinely using what is known as the module design pattern. As I continued to built out variations of this pattern, I found that it became quite useful in compartmentalizing the numerous components in web interactives and in my Cordova app, which now has a fairly large codebase.

Last night I started thinking how I might teach the module design pattern to someone relatively new to Javascript. I wrote a quick tutorial on the pattern, which is now available in CodeX. Feel free to give it a read - I hope you find it helpful. 

https://medium.com/codex/put-the-javascript-module-design-pattern-to-work-41396c577084
Método includes - JavaScript
Tags: javascript, tutorial, webdev, beginners
Published: 2021-03-24 19:23:59

O método **includes()** determina se um array contém um determinado elemento, retornando **true** ou **false** apropriadamente.

## **Parâmetros**

**searchElement -** Elemento a buscar.

**fromIndex -** A posição no array de onde iniciará a busca pelo **searchElement**. por padrão, 0. (Opcional)

### Sintaxe

```jsx
nameArray.includes(searchElement);
```

## **Retorno**

O método **includes()** retorna **true** encontrar o elemento no array, caso contrário retorna **false**.

## Exemplos

Encontrar o valor 5 no array

```jsx
const numbers = [10, 6, 2, 85, 23, 1, 3];

const value = number.includes(5);
// value -> false
```

Encontrar o valor 10 no array

```jsx
const numbers = [10, 6, 2, 85, 23, 1, 3];

const value = number.includes(10);
// value -> true
```

<a href="https://www.notion.so/elianbecali/includes-f83086e004514416a339c2b545b7da68" target="_blank">Método includes | Notion
</a>
<a href="https://www.youtube.com/watch?v=Ko6TBX2jcB0" target="_blank">Método includes | Youtube
</a>
Math.random() in tests
Tags: javascript, testing
Published: 2021-03-24 19:22:37

Let's assume following source code generating random number with [Math.random()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) and [faker.random.number()](https://github.com/marak/Faker.js/):

```js
var faker = require('faker');

faker.seed(1);

console.log(
  "Faker goes:", 
  faker.random.number({ max: 100 })
);

console.log(
  "Math.random() goes:", 
  Math.random() * 100
);
```

And now let's try to run it several times in a row:

```sh
❯ node index.js
Faker goes: 42
Math.random() goes: 24.270154608840078

❯ node index.js
Faker goes: 42
Math.random() goes: 17.379030134115037

❯ node index.js
Faker goes: 42
Math.random() goes: 66.8433058100395
```

One quite common thing to do while writing tests is to write down what data got generated during the test run and assert against that value:

```js
let myRandomInt = faker.random.number({ max: 100 });
// let myRandomInt = Math.random() * 100;

assert.equals(myRandomInt, 42, 'Coincidence? I think not');
```

Now while there are better methods to write tests, this is a quick win and when done right can work quite well. As you can see from the values generated above when you use `Math.random()` you will get different result every time. While when using `faker` the results **seem** stable.

Faker will always give you _the same results_ when _all_ the calls to it are **exactly** the same till your call. The problem arises when you for some reason add another call to `faker` before your call:

```js
faker.random.number(); // Extra faker call

let myRandomInt = faker.random.number({ max: 100 });
assert.equals( // This will fail ☹️
  myRandomInt, 
  42, 
  'Coincidence? I think not'
);
```

How to solve this? Using [seed](https://github.com/marak/Faker.js/#setting-a-randomness-seed), which will reset the pseudo-random sequence:

```js
faker.random.number(); // Extra faker call

faker.seed(1);
let myRandomInt = faker.random.number({ max: 100 });
assert.equals( // It works again ✨
  myRandomInt, 
  42, 
  'Coincidence? I think not'
);
```

## Conclusion

If you want to hard-code assert expected values in your test, you should make sure that you:

1. In your tests use stable random generator like `faker` instead `Math.random()`.
1. Pin `faker.seed(x)` to a constant value before generating data for each test.

-----

Photo by <a href="https://unsplash.com/@rihok?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Riho Kroll</a> on <a href="https://unsplash.com/s/photos/dice?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
Use SSL to develop Rails projects using Puma-dev
Tags: rails, puma, ssl
Published: 2021-03-24 17:21:21

---
title: Use SSL to develop Rails projects using Puma-dev
published: true
description: https for the win
tags: rails, puma, ssl
//cover_image: https://direct_url_to_image.jpg
---

When developing Rails apps we use http://[localhost](http://localhost):3000 as a default URL to access. It would be nice to use custom domains like `awesome-rails-app.test` . Even better if we can use https so it could be accessed using [https://awesome-rails-app.test](https://awesome-app.tesst) . in this case **puma-dev** can help you.

## Installation

I will describe the installation for macOS, for Linux you can use [https://github.com/puma/puma-dev#linux-support](https://github.com/puma/puma-dev#linux-support).

Add puma in the Gemfile.

```ruby
# Gemfile
gem 'puma'
```

Install Puma-dev using Homebrew.

```bash
brew install puma/puma/puma-dev
```

## Setup

Next we need to configure some DNS settings and Configure puma-dev to run in the background. By default it uses the domain `.test`

```bash
sudo puma-dev -setup
puma-dev -install
```

## Usage

Symlink you app's folder into `~/.puma-dev` .

Also you can use `puma-dev link`.

```ruby
cd awesome-rails-app
puma-dev link -n awesome-rails-app .
```

Now access to the URL: [https://awesome-rails-app.test](https://awesome-rails-app.test) 

That's it!

### Restart

Just `touch tmp/restart` inside your Rails project.

### Stop

These will stop all the apps added into `~/.puma-dev`

```ruby
puma-dev -stop
```

## Bonus - Debugging using Rubymine

If you use Rubymine as your IDE you can debug your app simply by pressing `Option + Shift + F5` to attach to the puma-dev process. (See References below)

## References

[https://github.com/puma/puma-dev](https://github.com/puma/puma-dev)

[https://www.jetbrains.com/help/ruby/attaching-to-process.html](https://www.jetbrains.com/help/ruby/attaching-to-process.html)
O que é Human Interface Guidelines?
Tags: ios, apple, swift, developer
Published: 2021-03-24 19:14:58

<i> O Human Interface Guidelines ou HIG</i> um documento feito pela Apple que descreve os princípios e as diretrizes para ajudar você a fazer o seu app, de uma forma intuitiva e boa para o usuário. Existe três princípios:

<b>Claridade</b>
O texto e seu tamanho deve ser elegível para todos os tamanhos de telas e os ícones também. O conteúdo importante deve ser destacado e ser interativo.

<b>Deferência</b>
A interface(View), deve ser apresentada respeitosamente. Ela não deve competir com os outros conteúdos que estão nela.

<b>Profundidade</b>
Hierarquia entre os elementos que possuem na tela com camadas visuais e movimentos realistas. Através dos movimentos com o toque, a experiência trás vitalidade e facilita a compreensão.

<b>Princípios de Design</b>
Cada app tem um identidade própria e ela deve ser seguida em todas as telas.Se você usou o background vermelho na sua LaunchScreen, após a abertura dele tem que ter vermelho em outros componentes. Seja na <i>TabBar, Button, Text Fields…</i>

<b>Integridade Estética</b>
A representação da aparência e o comportamento do aplicativo deve se integrar com a sua função. Se você vai fazer um app que te ajuda a contabilizar as calorias inseridas no dia, deve ter componentes claros e diretos.

<b>Consistência</b>
O mesmo formato que for utilizado no botão da View principal, deve ser usado nas outras Views. Deve possuir um padrão no estilo dos elementos existentes do aplicativo.

<b>Manipulação direta</b>
O aplicativo deve envolver o usuário através da manipulação do Device. Ao girar ele horizontalmente ou verticalmente, os gestos e a tela devem ser adaptados de acordo com o movimento feito.

<b>Feedback</b>
Manter o usuário informado de todas as ações que ele realizará. Com animações ou elementos interativos.

<b>Metáforas</b>
Usar objetos do mundo real no seu aplicativo, permitirá que ele aprenda a e navegar rapidamente. Como por exemplo, nós temos o app do Kindle, que ao passar de página imita o movimento do mundo real e ainda tem som.

<b>Controle do Usuário</b>
Permitir sempre que o usuário tenha o domínio do aplicativo, ele deve ser o agente principal tomando as decisões e definindo suas preferências. Cancelando algumas operações antes de serem concluídas.
Skills for Hacking
Published: 2021-03-24 19:01:05

Hacking is broad… To be a hacker you have to be creative, if you learn a hacking technique  from someone or somewhere try to add something to it or change it and make it your own.

NOTE: You can’t become a hacker in a day, it takes time and dedication and you have to be someone who loves research and let google be your friend simple. Aha... Just ask google all the questions you have in mind I tell you someone has already asked that question and someone has already answered that person so that’s it.

Below are listed skills you need to have:
1.Good knowledge in networking (This will help you to understand how the  internet works).

2.Good knowledge in Operating systems.(This will help you to know how to use  any OS and also help you in troubleshooting problems).

3.Programming(This is not needed all the time but frankly speaking it really helps).

4.Good PC.(This shouldn’t be a problem you can start with any specs).

5.Your smartness.
With programming you can start with any language but I recommend you start  with something not too difficult like c++, just learn the fundamentals to give you  the base knowledge then you can look at other languages maybe python, because  it’s easy to understand and has a good documentation for it library to help you. The  concepts in programming are similar just that they are written in different languages.
Information Sharing And Transparency In Government
Tags: it
Published: 2021-03-24 19:46:36

---
title: Information Sharing And Transparency In Government
published: true
date: 2021-03-24 18:57:35 UTC
tags: IT
canonical_url: https://blog.nisankhacharjya.in/information-sharing-and-transparency-in-government
---

A particular fact or circumstance which could be knowledge communicated received or learned about something or someone is information. There is a difference between the information already present in the public domain and the accessibility of information held by public bodies.

Every piece of information can’t be available to every member of the general public. However, a particular piece of information can be critical to a specific stakeholder among the general public, where this information determines the freedom of information and the person’s right to access it.

Since information is a fact, the truth is evident in it. The truth shows whether what has happened had sincerity, honesty or genuineness. This lets us know real intent. Once we know the intent, we can identify the happening with either dishonest or honest conduct.

No one has the freedom to unnecessarily invade privacy and be detrimental to security. However, whatever pieces of information the government and its institutions hold are in principle public where the fundamental premise on which this information sharing is based encourages them to be transparent and accountable.
Random Wikipedia Article Reader | Rookie Week of Python Day 05
Tags: python, beginners, programming, wikipedia
Published: 2021-03-24 18:46:40

Every person that has ever been bored on the internet and read Wikipedia articles to rid themselves of boredom has probably used their random article generator link:

`https://en.wikipedia.org/wiki/Special:Random`

Today we will use this link to write a python script that searches Wikipedia for random articles and gives you a y/n prompt to choose if you'd like to read the article or pick another random article. Since the link can not be refreshed to again search for a different article we will need to use loops.

# Random Wiki Article Generator

First we will need to pip install two prerequisites, easily done as follows:

`pip install beautifulsoup4`
`pip install requests`

Now to import the above installs and an additional `webbrowser` module

```python
import requests
from bs4 import BeautifulSoup
import webbrowser
```

We will declare a `while` loop and three variable.
* url - contains the random wiki link
* soup - used to parse html content
* title - fetch `firstheading` value from parsed data

```python
while True:
    url = requests.get("https://en.wikipedia.org/wiki/Special:Random")
    soup = BeautifulSoup(url.content, "html.parser")
    title = soup.find(class_="firstHeading").text
```

A `print` statement to prompt the user for a y/n option and an `input()` statement. Append the statement with the `.lower()` function to convert any uppercase inputs to lowercase as to avoid any incorrect inputs.
```python
while True:
    url = requests.get("https://en.wikipedia.org/wiki/Special:Random")
    soup = BeautifulSoup(url.content, "html.parser")
    title = soup.find(class_="firstHeading").text
    
    print(f"{title} \nDo you want to read this article? (Y/N)")
    ans = input("").lower()
```

Write a conditional statement to perform different functionality based on user input. Execute `webbrowser.open()` to open a browser windows with the selected link (program will use the default browser for this purpose).
```python
if ans == "y":
        url = "https://en.wikipedia.org/wiki/%s" % title
        webbrowser.open(url)
        break
    elif ans == "n":
        print("Don't worry. Fetching a new article for you!")
        continue
    else:
        print("Invalid Command!")
        break
```

### Output

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

Thank you for reading. You can get the code [here](https://github.com/thehannankhan/random-wiki-article-generator) from it's GitHub repo.
Creating VR games by learning from step 1 with Noble Ackerson
Tags: vr, ar, privacy
Published: 2021-03-24 18:44:55

---
title: Creating VR games by learning from step 1 with Noble Ackerson
published: true
description: We talk VR/AR, Data Privacy & Trust, Continuing education and more 
tags: vr, ar, privacy
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o9sf2dorwm03niaw1qp1.jpg
---

In in episode 30 of the Friends That Code podcast, Mike and I talk VR/AR, Data Privacy & Trust, Continuing education and more [Listen here](https://anchor.fm/friendsthatcode/episodes/30---Creating-VR-games-by-learning-from-step-1-with-Noble-Ackerson-esaie7/a-a51cipm)
Automatically upload on ftp with VsCode after git pull or external change: any good extension?
Tags: help, vscode, ftp
Published: 2021-03-24 18:31:32

I'm searching an extension for VsCode that can upload automatically all the fil changed after a git pull, or any modification with other external editor.
I've seen PHPStorm have this, and can upload either pull make when is running than when is closed, at the startup moment. 
I've tried to replicate this on VsCode with SFTP, but this not worked. The file where uploaded only when I save them.

Someone have an extension (or SFTP configuration) to suggest me?

Or some method external from VsCode that can work the same? i'm using MacOs Catalina.

Thanks to all who will reply :)
A11yship is multi-dimensional — with Crystal Preston Watson and Marcy Sutton
Tags: discuss, podcast, a11y
Published: 2021-03-24 18:14:10

---
title: A11yship is multi-dimensional — with Crystal Preston Watson and Marcy Sutton
published: true
description: Listen to S4E7 of DevDiscuss!
tags: discuss, podcast, a11y
series: DevDiscuss Season 4
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z3c2a9gu11oy2m718lt1.png
---

Another week, another episode of DevDiscuss that I couldn't wait to share with you all. This week, I was joined by guest host @s_aitchison — a software engineer here on team Forem who focuses on all things front end. 

{% podcast https://dev.to/devdiscuss/s4-e7-what-you-need-to-know-about-accessibility %}

We decided to focus on the topic of accessibility for a handful of reasons. First off, making the Internet work for _everyone_ is one of the most important jobs web developers have today. Additionally, in recent years, accessibility has thankfully come into the forefront of many software teams' minds — but we can't stop the drumbeat now. As more people pursue programming every day, accessibility needs to be a core tenet of everyone's curriculum, self-taught or otherwise. 

Finally, accessibility-focused projects give way to some of the most fulfilling and fun challenges for any developer. We hope that this episode touches on all of this, sparks discussion, and gets you all the more curious about the a11y work to be done on each and every team. 

### In this episode, we were joined by special guests...
- [Crystal Preston-Watson](https://www.twitter.com/ScopicEngineer), Quality and Accessibility Engineer at Salesforce
- [Marcy Sutton](https://dev.to/marcysutton), Web Developer and Accessibility Specialist — who has also consulted at Forem!
  

---

_You can [follow DevDiscuss](dev.to/devdiscuss) to get episode notifications and listen right in your feed_ — or subscribe on your platform of choice! Plus, if you leave us a review, we'll send you a free pack of thank-you stickers. Details [here](https://airtable.com/shr8oKAIMZgdYnBxx). 

## Quick Listening Links
- [Apple Podcasts](https://podcasts.apple.com/us/podcast/devdiscuss/id1513053883)
- [Spotify](https://open.spotify.com/episode/7pOib7KYa6zAF4mNf1Gcou)
- [Google](https://podcasts.google.com/feed/aHR0cHM6Ly9mZWVkcy5kZXZwb2RzLmRldi9kZXZkaXNjdXNzX3BvZGNhc3QueG1s/episode/aHR0cHM6Ly9kZXZwb2RzLmRldi9wb2RjYXN0cy9kZXZkaXNjdXNzLzMy?sa=X&ved=0CAQQkfYCahcKEwjogNbhwsnvAhUAAAAAHQAAAAAQAg)
- [Listen Notes](https://www.listennotes.com/podcasts/devdiscuss-dev-xtQvoDylAUg/)
- [TuneIn](https://tunein.com/podcasts/Technology-Podcasts/DevDiscuss-p1324596/?topicId=161778343)
- [RSS Feed](http://feeds.codenewbie.org/devnews_podcast.xml)
- [Pocket Casts](https://pca.st/vvo2unz9)
- [DEV Pods Site](https://devpods.herokuapp.com/podcasts/devdiscuss/episodes/155)

---
_Acknowledgements_ 
- _@levisharpe for producing & mixing the show_
- _Our season four sponsors: DataStax, New Relic, Educative, and Ambassador Labs!_

# 🗣️🗣️🗣️
Dev life is easy with node-mssql
Tags: beginners, node, sql, azure
Published: 2021-03-24 18:06:16

As mentioned already in a [previous posts](https://dev.to/azure/promises-node-tedious-azure-sql-oh-my-ho1), I've just started learning Node in the last months. At first I had a rough start as the totally asynchronous nature of Node, and the many ways it can be leveraged, wasn't something I was used to. I battled a bit with that, learned a lot, and also figured out how to properly use [Tedious](https://tediousjs.github.io/tedious/) to take advantage of Azure SQL in my projects.

But using Tedious is...~~tedious~~ verbose. Also the way it manages all asynchronous calls is quite different than the modern async/await pattern.

So I looked for something different and more modern and I found the [node-mssql](https://www.npmjs.com/package/mssql) package that does exactly what I needed.

Taking advantage of Azure SQL is really a breeze now. Exposing a stored procedure as a REST endpoint is now as easy as writing something like (the stored procedure returns data a JSON):

```javascript
const sql = require('mssql')

const AZURE_CONN_STRING = process.env["AzureSQLConnectionString"];

module.exports = async function (context, req) {    
    const pool = await sql.connect(AZURE_CONN_STRING);    

    const busData = await pool.request()
        .input("routeId", sql.Int, parseInt(req.query.rid))
        .input("geofenceId", sql.Int, parseInt(req.query.gid))
        .execute("web.GetMonitoredBusData");        

    context.res = {        
        body: JSON.parse(busData.recordset[0]["locationData"])
    };
}
```

The above code is literally all you need, for example, if you are using Azure Functions to host your node code. 

I prefer to use the async/await pattern when I can as it is so easy to use, but if for some reason you cannot use it, our you prefer the old Promise approach, or even the Callback one, you'll be happy to know that they are supported too.

Definitely recommended. 

# Warning Note

Make sure that you import the `mssql` package:

```
npm install mssql
```

even if the official name is *node-mssql*. Unfortunately if you try to import "node-mssql" package you'll end up with something [ different](https://www.npmjs.com/package/node-mssql) and not really working :( Keep that in mind, I've lost a good hour just trying to figure out why my code was not working, and then I discovered I imported the wrong package :/

---

Photo by [Jonathan Borba](https://www.pexels.com/@jonathanborba?utm_content=attributionCopyText&utm_medium=referral&utm_source=pexels) from [Pexels](https://www.pexels.com/photo/red-hammock-between-wall-3255245/?utm_content=attributionCopyText&utm_medium=referral&utm_source=pexels)
JavaScript & API's?
Tags: beginners, javascript, codenewbie
Published: 2021-03-24 18:01:33

I'm currently in a front end web development program from General Assembly and I'm interested in using an API with my final project.

The issue is, they don't cover API's until the very end of our course right before we present our projects.

Where can I go to learn about API's and how to use them?
Address Validation
Tags: jquery, jqueryvalidatejs, addressvalidate, regx
Published: 2021-03-24 17:52:57

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6lw5osmtypgl8437d3mf.png)

Accepts at least one number and no special characters in the jquery validate plugin.

you can find code [here](https://tiny.one/fan7twkj)
Python Tricks for beginners
Tags: python, beginners, tutorial
Published: 2021-03-24 17:43:59

1. print(array, end=" ")
Everytime you print something in python it automatically creates a new line. It is very useful unless you want to print something in the same line for that you use end=" " . print("whatever you want to", end="")

2. set()
This is very helpful in removing duplicate items, it is used especially when comparing values. Let's say you want to get the lowest and highest scores from a class usually you want to just make a list and sort it and you will have scores in ascending order, now set() is really helpful when you have to find things like second highest or second lowest since more than one person can have same highest/lowest score So, second_highest = print(sorted(set(list(score)))[-2]) Second_lowest = print(set(sorted(list(score)))[1]) Here [1] is basically index 1 of score since in python the counting start from 0 so index 1 will give the second position value from an ascending order of scores

While reading a list backwards (i.e., from right to left) index starts at -1 so [-2] will give the value of second highest

list(score), will make the list of scores

set(list(score)), will remove the duplicates of scores

sorted(set(list(score))), it will give the scores without duplicates in ascending order