teleren/devto huggingface dataset:
Rails Environment Variables Using Credentials
Tags: rails, ruby
Published: 2022-02-01 13:34:54

In your Rails app, do you use `ENV` or `Rails.application.credentials`? Is there an easy way to use both? Lets find out.

I've been a long time fan of [Figaro](https://github.com/laserlemon/figaro), a great gem that lets your store your environment variables in `/config/application.yml`. I've used it in most of my Rails apps for two reasons. _One_, it lets you easily define variables for your for `development`, `staging`, `production` environments. _Two_, it works well with Heroku since they also use `ENV` for storing and accessing environment variables, so things work the same locally while developing as well as after it's been deployed. However the downside with [Figaro](https://github.com/laserlemon/figaro) is that all your environment variables are exposed to the outside world, which is problematic if your repo is open source. 

[Rails.application.credentials](https://edgeguides.rubyonrails.org/security.html#environmental-security) helps solve this problem by encrypting your environment variables in `config/credentials.yml.enc` so they are only readable with the key providing a secure way to store them. However the downside, is your environment variables are now stored and accessed in two different ways, using `Rails.application.credentials` and `ENV` if you are also using Heroku.

It would be a lot more convenient, if you could define your variables in `Rails.application.credentials` so they are encrypted and secure, yet still access them using `ENV` so both local and remote environment variables are consistent.

You can do this easily by adding the following into `/config/application.rb`.

```ruby
credentials.config.each do |key, value|
  if key.to_s == Rails.env
    value.each do |env_key, env_value|
      ENV[env_key.to_s.upcase] = env_value.to_s if ENV[env_key.to_s.upcase].blank?
      ENV[env_key.to_s.downcase] = env_value.to_s if ENV[env_key.to_s.downcase].blank?
    end
  elsif ['development', 'staging', 'test', 'production'].include?(key.to_s) == false
    ENV[key.to_s.upcase] = value.to_s if ENV[key.to_s.upcase].blank?
    ENV[key.to_s.downcase] = value.to_s if ENV[key.to_s.downcase].blank?
  end
end
```

Now you have the best of both worlds, security plus accessibility. You can now access all your environment variables via `ENV` whether they are defined in Heroku or in `Rails.application.credentials`.

```ruby
ENV['HEROKU_APP_NAME'] # access Heroku defined variables
ENV['GITHUB_API_KEY'] # access variables from your credentials
ENV['git_api_key'] # also access variables in lowercase
ENV['rails_env_key'] # access environment specific variables
```

The snippet only sets the `ENV` if it's not already defined. It also handles global or environment specific variables in your `Rails.application.credentials`. 

You can copy and paste the initializer above, or you can run the following [template](https://railsbytes.com/templates/Vp7s90) to add it to your project.

```zsh
rails app:template LOCATION="https://railsbytes.com/script/Vp7s90"
```
Disabling the Tailwind input ring
Tags: tailwindcss, css, html, webdev
Published: 2022-02-01 13:30:57

If you’ve ever worked with [Tailwind](https://tailwindcss.com) components or [TailwindUI](https://tailwindui.com), you’ve probably come across the “focus ring”. On inputs (checkboxes, fields, etc.), this ring is shown when you’ve clicked or tabbed onto a component, indicating that you have selected it. Here’s an example:

![Enabled ring on checkbox](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zb2uzz25u9jv9qg202zl.png)

## Disabling the ring

I’ve seen myself and others try to disable this by simply calling the `focus:ring-0` utility. This sort of works, but gives us this weird shadowing effect on the corners of our input:

![Disabled ring, but persistent offset](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gjeaawinckw0gjgioary.png)

By default, Tailwind will include this ring and an offset on certain input elements like checkboxes. If you’d rather not have this ring on all interactions, **you can easily disable it:**

```html
<input type="checkbox" className="focus:ring-0 focus:ring-offset-0" />
```

With this, we’re able to get a nice looking checkbox, without the “ugly” looking ring:

![Fully disabled ring on a checked checkbox](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dmlq0jtzyhdrv5znsfzk.png)

### Keeping things clean

To reduce redundancy across my project, I created a class that I can globally apply:

```css
.without-ring {
  @apply focus:ring-0 focus:ring-offset-0;
}
```

Now, instead of re-defining these utilities on all of my inputs, I can use the `without-ring` class to achieve the desired output:

```html
<input type="checkbox" className="without-ring" />
```

## Keeping it accessible

Accessibility is important, but to keep it short, I won’t cover it here. Instead, [this post by David Gilbertson](https://medium.com/hackernoon/removing-that-ugly-focus-ring-and-keeping-it-too-6c8727fefcd2) provides a simple, framework-agnostic solution to showing the focus ring only when a user is tabbing and making it hidden otherwise.

Keeping it within Tailwind, we can use both our pre-defined without-ring class and native CSS selectors to show the ring for keyboard users, but hide it when using a mouse:

```css
.without-ring:focus:not(:focus-visible) {
  @apply focus:ring-0 focus:ring-offset-0;
}

.without-ring:focus-visible {
  @apply ring-2 ring-offset-2;
}

// If we wanted to apply this globally, we could use native type selectors

[type="checkbox"]:focus:not(:focus-visible) {
  @apply focus:ring-0 focus:ring-offset-0;
}

[type="checkbox"]:focus-visible {
  @apply ring-2 ring-offset-2;
}
```
How To Install Maven Plugin? | Jenkins Tutorial | Part III
Tags: javascript, beginners, jenkins, tutorial
Published: 2022-02-01 13:21:02

{% youtube hmqJpU_7gis %}

In this part of Jenkins tutorial Series, Moss(@tech_with_moss), an experienced DevOps engineer, will take you to the next step after setting up Jenkins and explain How to install Maven Plugin in Jenkins Server? and How to build and configure the Jenkins Maven project? 

By the end of this video, you will learn 🎫 -:
🔸 What are Maven plugins?
🔸 How do you download Maven plugins?
🔸 How do you run a Maven command in Jenkins pipeline?
🔸 Where is Maven installed in Jenkins?
Find all Headings with BeautifulSoup
Tags: python, webdev
Published: 2022-02-01 13:16:36

---
canonical_url: https://waylonwalker.com/til/bs4-findall-headings/
published: true
tags:
- python
- webdev
series: til
title: Find all Headings with BeautifulSoup
---

BeautifulSoup is a DOM like library for python.  It's quite useful to manipulate html.  Here is an example to find_all html headings.  I stole the regex from stack overflow, but who doesn't.

## Make an example
_sample.html_

Lets make a sample.html file with the following contents.  It mainly has some headings, `<h1>` and `<h2>` tags that I want to be able to find.

```html
<!DOCTYPE html>
<html lang="en">
  <body>
    <h1>hello</h1>
    <p>this is a paragraph</p>
    <h2>second heading</h2>
    <p>this is also a paragraph</p>
    <h2>third heading</h2>
    <p>this is the last paragraph</p>

  </body>
</html>
```

## Get the headings with BeautifulSoup

Lets import our packages, read in our `sample.html` using pathlib and find all headings using BeautifulSoup.

```python
from bs4 import BeautifulSoup from pathlib import Path

soup = BeautifulSoup(Path('sample.html').read_text(), features="lxml") headings = soup.find_all(re.compile("^h[1-6]$"))
```

And what we get is a list of `bs4.element.Tag`'s.

```python
>> print(headings)
[<h1>hello</h1>, <h2>second heading</h2>, <h2>third heading</h2>]
```

I recently added a heading_link plugin to markata, you might notice the
🔗's next to each heading on this page, that is powered by this exact
technique.
Working of JS Engine
Tags: javascript, webdev, beginners, programming
Published: 2022-02-01 13:07:33

JavaScript runs through the code it needs to execute, twice. This results in two phase execution of code

The two phases are popularly referred as 
1) Creation Phase
2) Execution Phase

###Creation Phase
In the creation phase, the JavaScript Engine goes through the code to
* Create a special object called activation object. This object is used to hold all the variables and functions
* Create a scope chain, which is an array of lexical environments.(Will be discussed in detail in later blogs)
* Determine the value of 'this', which is a special keyword in JavaScript which refers to the object calling the function

###Execution Phase
In this phase, the JavaScript Engine goes through the code line by line(in the order dictated by the thread of execution) and executes each line of code, and updates the values of variables as needed

###Advantages of 2 Phase Execution Process
1. As we can see, during the creation phase, JavaScript has access to all the variables and functions, we can get access to those functions. Hence we can now call a function before its definition.

```
// Function call before, definition is valid
dev()
function dev() {
// Some Code
}
```

Hence call before definition is now possible in JavaScript Engine

2. JavaScript now also knows all your variables and sets a initial value 'undefined' to it. This way if some identifier is not declared, the error message would give 'not defined' instead of 'undefined'

```
console.log(x)  // This gives undefined
let x = "dev"
console.log(x) // This gives "dev", as it is updated on the line above
```
```
console.log(y) // This is not defined as 'y' is not a valid identifier that JavaScript knows about
let x = "dev"
```

To get a video tutorial on the concept
https://www.youtube.com/watch?v=wtBbanu-kUY 

References:
https://medium.com/@happymishra66/execution-context-in-javascript-319dd72e8e2c
 
https://medium.com/@sudhakarsp06/creation-phase-and-execution-phase-in-javascript-32fcdbef60f4
Paracetamol.js💊| #39: Explica este código JavaScript
Tags: javascript, beginners, spanish, webdev
Published: 2022-02-01 12:58:06

## **Explica este código JavaScript**

```js
async function getData() {
  return await Promise.resolve("I made it!");
}

const data = getData();
console.log(data);
```

-     A: `"I made it!"`
-     B: `Promise {<resolved>: "I made it!"}`
-     C: `Promise {<pending>}`
-     D: `undefined`

Respuesta en el primer comentario.

---
April 2022 Calendar Printable
Published: 2022-02-01 12:54:21

According to today's needs as scheduling and planning for any meetings, events, holidays, appointments, etc., The [April 2022 Calendar Printable](https://acalendarprintable.com/april-calendar/) is an ideal solution for all folks. Via it, we can plan and schedule easily. It facilitates that you just can look it everywhere as in an office, home. The format of the calendar has met in simple that you simply can easily print and April enter any important notes or information into day after day and not have it obscured by irrelevant information. you need to download the printable calendar from the web that will be the format of PDF and TEXT. Every calendar is meant to print in landscape format and might print in any size as your wish.
How to Transfer Tokens To  The Owner Address and Not stuck In Contract Address In Solidity.
Tags: nft, webdev, blockchain, web3
Published: 2022-02-01 12:52:16

I recently faced a bug when I was building a web dapp with react.js and smart contract(solidity). The project was an NFT minting Dapp where customers can mint NFTs and own them. 

I was sure everything was working very fine until I tested and noticed that the money customers were using to mint is not going to the owner's wallet but going to the contract address. 

That is so strange! What is the point of selling NFTs and you aren't getting the money in your or where you can access it. 

This is a very strange bug that we might not take note of until we see the effect. I learnt that CrytoPunk also faced the same issue which was why they launched version 2 of their NFTs.

So how do you solve this problem? 

Money being stuck in the contract address can be removed if there is a withdrawal function that allows the owner to withdraw from the contract. See the code below.

```
//only owner
function withdraw() public payable onlyOwner {
    payable(msg.sender).transfer(address(this).balance);
  }
```

This function allows the owner to withdraw from the contract address by going to the scan address of the blockchain used like [polygonscan](https://polygonscan.com/) for Polygon and [etherscan](https://etherscan.io/) for Ethereum.

Noticed the only owner in the code, it means it is only the owner that can withdraw. If the withdraw function is not restricted with only the owner, anybody will be able to withdraw.

Also note that, to withdraw from the contract, you must have more than the amount you want to withdraw in your wallet.

But how do we make it so that when customers mint NFTs, it goes straight to the owner's address while the transactions still show on the contract?

Inside your mint function in your contract, add the following line of code;

`payable(owner()).transfer(msg.value);`

owner() is a function in Ownable on the smart contract that stores the address that is used to deploy the contract as the owner's address.

The full mint function looks like this;

```
function mint(address _to, uint256 _mintAmount) public payable {
    uint256 supply = totalSupply();
    require(!paused);
    require(_mintAmount > 0);
    require(_mintAmount <= maxMintAmount);
    require(supply + _mintAmount <= maxSupply);

    if (msg.sender != owner()) {
        if(whitelisted[msg.sender] != true) {
          require(msg.value >= cost * _mintAmount);
        }
    }

    for (uint256 i = 1; i <= _mintAmount; i++) {
      _safeMint(_to, supply + i);
    }
    payable(owner()).transfer(msg.value);
  }
```

So when customers mint their NFTs to acquire them and they are being charged the amount to mint from Metamask, the last line of code in the mint function transfers the funds used to mint to the owner's address i.e the owner of the contract.

These two functions have solved the issue of tokens getting stuck in the contract address and not being able to access or withdraw it.

I hope you find this article helpful. Follow me on [twitter](twitter.com/GraceOmole3) for more tips on Frontend and Blockchain
learn JSON from head to toe
Tags: javascript, webdev, json, tutorial
Published: 2022-02-01 12:49:32

## what is JSON ?

• JSON - JavaScript Object Notation

• JSON is a lightweight format for storing and transporting data.

• JSON is often used when data is sent from a server to web page

• JSON is language independent

####The JSON format is almost identical to JavaScript objects.

• In json keys MUST be in strings, written with double quotes

• In JavaScript object, keys can be strings, numbers, or identifier names

![json](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6p6pd90hnhbgh17abgwu.png)
 
###In JSON, values must be one of the following data types:

- string
- number
- object (JSON object)
- array
- boolean
- null

###In javaScript object , valuse must be one of the following data types:

- string
- number
- object (JSON object)
- array
- boolean
- null
- function
- date
- undefined
![js object](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0fxb469ysh8zuc4912ub.png)

###🚥JSON.stringify(  )

When sending data to a web server, the data has to be a string.

So thats why while before sending data we need to Convert it from a JavaScript object to a JSON

To make this happen we need JSON.stringify(  ).
![stringify](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ce7zifu6yd6l16oc4uew.png)
 
###🚥JSON.parse(  )

Likewise while we receiving data from a web server, the data is always a string.

So we need to Parse the data into javascript object to use the data in out applications.

And for this action we need to use JSON.parse()
![parse](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q47xxe0tjdiqomqqgzx4.png)

-----------------------------------------------
######That's it for now , if you have any doubt let me know on comments and let's connected on [Twitter](https://twitter.com/Sahilsaif2002)
Como liberar acesso remoto do MySql server no Ubuntu
Tags: mysql, ubuntu
Published: 2022-02-01 12:41:58

Config file changes are required to enable connections via localhost.

To connect through remote IPs, Login as a "root" user and run the below queries in mysql.
```

CREATE USER 'username'@'localhost' IDENTIFIED BY 'password';

GRANT ALL PRIVILEGES ON *.* TO 'username'@'localhost' WITH GRANT OPTION;

CREATE USER 'username'@'%' IDENTIFIED BY 'password';

GRANT ALL PRIVILEGES ON *.* TO 'username'@'%' WITH GRANT OPTION;

FLUSH PRIVILEGES;
```

This will create a new user that is accessible on localhost as well as from remote IPs.

Also comment the below line from your my.cnf file located in /etc/mysql/my.cnf
```
bind-address = 127.0.0.1
```

Restart your mysql using
```
sudo service mysql restart
```

Now you should be able to connect remotely to your mysql.

[Solution found on stackoverflow and written by harishannam](https://stackoverflow.com/questions/8348506/grant-remote-access-of-mysql-database-from-any-ip-address/8348560)
Guía rápida de Babel
Tags: webdev, spanish, babel, javascript
Published: 2022-02-01 12:37:44

Babel es un software que permite transpilar código, con el principal objetivo de aumentar la compatibilidad del programa para el despliegue del mismo en distintos navegadores.
ES6 a incluido nuevas características que en un principio no eran soportadas por todos los navegadores, generando de esta manera problemas de compatibilidad y por consiguiente un funcionamiento incorrecto del programa escrito con esta versión del lenguaje. Babel permite realizar la conversión de código escrito con la sintaxis permitida por el estándar ES6 a versiones anteriores.

## Instalación de Babel
Babel es un modulo de Node.js, el cual puede ser instalado a través de su gestor de paquetes conocido como npm (node package manager), haciendo uso de la terminal del sistema.

Generar un archivo llamado package.json con el cual se puedan manejar los módulos del proyecto, en este caso Babel.
```
$ npm init
```
Instalar Babel como un modulo de desarrollo.
```
$ npm i babel-cli -D
$ npm i babel-preset-env -D
```
Crear un archivo llamado .babelrc.
```
$ touch .babelrc
```
Incluir el siguiente objeto como código del archivo anterior, por medio del cual se indica que el código se transpilara a versiones de ES5 y anteriores.
```
{
  "presets":["env"]
}
```
Dentro del archivo package.json incluir el script de ejecución de Babel.
```
"scripts": {
   "build": "babel src -d lib"
}
```
El código del script anterior instruye lo siguiente:
* Transpilar el código mediante Babel.
* El código a transpilar será aquel localizado en el directorio src.
* Crear un nuevo directorio llamado lib.
* El código transpilado se localizará en este último directorio mencionado.

Por último el proceso de transpilación se podrá iniciar con el  siguiente comando.
```
$ npm run build
```
C program for beginner
Tags: c
Published: 2022-02-01 12:02:15

C, computer programming language developed in the early 1970s by American computer scientist Dennis M. Ritchie

It is widely used for developing desktop applications and software application,  It can be used to develop software like operating systems, databases, compilers, and so on
When you begin to learn c program, you will observed most of the collage start programming with hello world
[hello world](https://www.studyfame.com/c-program/hello-word-program-in-c)

`#include<stdio.h>
  void main() {
  // printf() displays hello worl on your screen
  printf("Hello World!");
  }`

[c program](https://www.studyfame.com/c-program/) for beginner are:

[addition of two number](https://www.studyfame.com/c-program/c-program-to-add-two-numbers)
[swapping of two number](https://www.studyfame.com/c-program/swapping-in-c)

[check even odd](https://www.studyfame.com/c-program/c-program-to-check-whether-a-number-is-even-or-odd)

[check positive, negative and zero in c](https://www.studyfame.com/c-program/find-number-is-positive-negative-or-zero)
[Convert Uppercase to Lowercase in C](https://www.studyfame.com/c-program/convert-uppercase-to-lowercase-in-c)

[Prime number program in C](https://www.studyfame.com/c-program/prime-number-program-in-c)

CPU scheduling program in C like first come first serve

[FCFS(First Come First Serve) scheduling program in c
](https://www.studyfame.com/c-program/fcfs-in-c)
Ultra High Frequency HAT for Raspberry Pi - Kickstarter
Tags: uhf, raspberrypi, pi, kickstarter
Published: 2022-02-01 11:59:15

**[UHF HAT for Raspberry Pi](https://www.kickstarter.com/projects/127134527/uhf-hat-for-raspberry-pi/)**
RAIN RFID technology | Supports EPC Gen2V2 | ISO 18000-63 standard | M6E-Nano | Up to 200 Tags/Sec | ARM based Cortex-M4 architecture
https://bit.ly/3Lc93dd
Checklist to Hire Flutter App Development Company
Published: 2022-02-01 11:50:09

Hiring a flutter developer is beneficial to businesses as they satisfy the need for developing an android & iOS app in one go. Flutter is the technology acquired by Google to make the work of the developer easy in maintenance and make the mobile app development cost-effective for businesses. 

**Checklist for hiring a dedicated flutter developer:**
1. Developers experience 
2. Past Industry Work Performance 
3. Suggestions of the developer for the Project 
4. Skills on Latest Technology 
5. Cross-platform development and launch expertise 
6. Maintenance supports after launch 
7. Regular updates on the work 
8. Communication skills 
9. Design Capabilities 
10. Cost of the developer per hour

Every point given in the above checklist should be analyzed and examined carefully before hiring a flutter developer.  

To be successful as a specialist, Flutter app developers should be a combination of both hard and soft skills.
 
Hard skills are quite essential for the job. The app developers require extensive framework knowledge to build complex and challenging applications using the Flutter framework. 

In order to co-operate and work with the team efficiently, flutter app developers should have soft skills such as teamwork, creativity, communication skills, work management, dedication, conflict management, etc. 

Now that you’re convinced to hire flutter app developers, the market offers you the three best alternatives to identify and hire the best resources.
- Freelancers 
- In-house development team 
- Outsourcing companies 

**What about the flutter developer’s hourly rates?**
The rates to hire flutter app developers in 2022 vary countrywide. Generally, developers prefer to work over hourly rates. However, that can vary based on the below factors. 
- Hiring options (freelance, in-house, outsource) 
- Qualifications (junior, mid-level, senior) 
- Regions

In India, companies like **WebCLues Infotech** offer their developers on hire at $10-$25. Check out their services and expertise from the given link below.