teleren/devto huggingface dataset:
How to check battery status with javascript ( 2 simple steps )
Tags: javascript, webdev, tutorial, programming
Published: 2022-07-24 01:45:00

In this tutorial I am going to show you how easily you can **check battery status of system using javascript** battery API .

Using the battery API various information about the system battery can be extracted , thus increasing the user experience also , in case user needs urgent charging .

##Getting battery Information

The battery API is not working in all browser , so first of all before getting the battery status we need to check that if browser supports the battery API or not .

##Checking API working in browser

Now to check the working of API in browser we need to use `getBattery` method on navigator API , as shown in the example below .

```
if(navigator.getBattery){
    // if battery API is working
}
else{
    // if battery API is not working
}
```

##Check battery status

If the battery API is working then we can check the battery percentage with `getBattery()` API , this API returns a [promise ](https://bepractical.tech/how-to-use-promise-in-javascript-read-this-definitive-guide/).

```
navigator.getBattery()
    .then(function(battery) {

        // Get current battery level .
        var batteryLevel = battery.level * 100;
        console.log(batteryLevel);
    })
    .catch(function(e) {
        console.error(e);
    });
```

The `battery` object has the following properties we can use to extract more information about sytem battery .
    

- `battery.level` : to check the battery level 
- `battery.charging` : to check if the battery is currently charging or not (true/false)
- `battery.chargingTime` : to check the time remaining in full charge of battery 
- `battery.dischargingTime` : to check the time remaining in battery dead .

Now to detect changes in all these properties at real time javascript provide us some event listeners , as shown below .

- `battery.onlevelchange` : to detect change in battery level 
- `battery.onchargingchange` : to detect change in power plug in/out of battery 
- `battery.onchargingtimechange` : to detect change in battery level 
- `battery.onlevelchange` : to detect change in battery level 

In the below example as soon as the battery level goes below 15% an alert will popup recommending connecting system to charger .

Read full article here 👉 https://bepractical.tech/how-to-check-battery-status-with-javascript-2-simple-steps/
Learn Python #5 - Do with functions...
Tags: python, programming, webdev
Published: 2022-07-24 01:27:00

## What functions are?

Functions in [Python](python.org) are meant to isolate the different parts of the program in smaller chunks.

Functions shall be easy to read and understand.

![functions](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/84xs9jc0wgw2qd55j555.png)

## Let us look at an example

Let us say we want to find the volume of a cube so we write

```
def volume(side):
    return side*side*side

print(f"The volume of a cube is {volume(3)} cubic cm")
//The volume of a cube is 27 cubic cm
```

- Here we say that we want to define a function with the keyword `def` which stands for `define` in [python](python.org).
- `volume` is a name given to that function.
- In parenthesis `()` we are passing an argument which is of type number.
- And we end the `()` with `:` so that the indentation (4 spaces) will begin from the next line.
- return the result with the `return` keyword.
- We are calling this method inside a `print` statement where we interpolate the value returned by the function.

## Quick gotchas when you are defining a function

- Function name cannot start with numbers or any special characters.

## Conclusion

There are more posts on the way related to the functions...So keep reading.

Thanks in advance for reading this article...🚀

*More than happy to connect with you on*

- [@twitter](https://twitter.com/_nitinreddy3)
- [@LinkedIn](https://www.linkedin.com/in/nitinreddy3/)

*You can also find me on*

- [@Github](https://github.com/nitinreddy3)
- [@DEV](https://dev.to/nitinreddy3)
- [@Medium](https://medium.com/@nitinreddy3)
Reading List: How to Code HTML for Emails
Published: 2022-07-23 23:06:36

- [Responsive Email Templates](https://zurb.com/playground/responsive-email-templates)
- [The Most Common Email Coding Mistakes and How to Avoid Them](https://sendpulse.com/blog/email-coding-mistakes)
- [How to Code a Responsive Email from Scratch](https://litmus.com/community/learning/24-how-to-code-a-responsive-email-from-scratch)
- [HTML Email Development Best Practices: Rules to Code By](https://www.emailonacid.com/blog/article/email-development/email-development-best-practices-2/)
- [How To Code An Email Newsletter in 6 Simple Steps](https://www.crazyegg.com/blog/how-to-code-an-email-newsletter/)
- [HTML Email Basics](https://templates.mailchimp.com/getting-started/html-email-basics/)
- [A Complete Guide To HTML Email](https://www.smashingmagazine.com/2021/04/complete-guide-html-email-templates-tools/)
- [Coding html emails](https://www.campaignmonitor.com/dev-resources/guides/coding-html-emails/)
- [New to email coding? Here’s where to start](https://explore.reallygoodemails.com/new-to-email-coding-heres-where-to-start-2494422f0bd4)
- [The RIGHT WAY to create HTML emails | TUTORIAL [2021]](https://www.youtube.com/watch?v=sSNnixkKqcA)
- [How to HTML: Your Guide to Designing and Coding Emails That Deliver](https://customer.io/blog/how-to-html-your-guide-to-designing-and-coding-emails-that-deliver/)
- [Build an HTML Email Template From Scratch](https://webdesign.tutsplus.com/articles/build-an-html-email-template-from-scratch--webdesign-12770)
- [A Complete Guide To Create Your Own HTML Email](https://email.uplers.com/blog/step-step-guide-create-html-email/)
- [Email Coding vs Web Coding: It’s Not The Same](https://smaily.com/email-coding-vs-web-coding-its-not-the-same/)
- [Email Coding Guidelines](https://gist.github.com/janogarcia/4977a2346cbc7e52334b)
- [Free HTML Email Templates](https://github.com/designmodo/html-email-templates)
- [Responsive Email](https://github.com/derekpunsalan/responsive-email)
- [How to Code a Mobile-First Responsive Email Template [Tutorial]](https://designmodo.com/code-responsive-email-template/)
- [Unlayer. Create beautiful emails, easily.](unlayer.com)
- [Codepen Email Templates](https://codepen.io/collection/AyVBJr)
- [Really good email](https://reallygoodemails.com/)
- [Benchmarkemail. Email Marketing Templates](https://www.benchmarkemail.com/email-templates/)
- [An intuitive email builder for teams and individuals amps up email marketing ideas](https://designmodo.com/postcards/)
- [1210+ Free HTML Professional Email Templates](https://beefree.io/templates/)


## [Linkedin page of LLazyEmail](https://www.linkedin.com/company/llazyemail/)
GitHub Secret VSCode Web Editor
Tags: productivity, beginners, tutorial, programming
Published: 2022-07-23 23:47:49

Discover the secret VS Code web editor on GitHub. Press period "." on any GitHub repo and a VS Code web editor will open. You can also access the VS Code web editor by changing the GitHub Url from Github.com To Github.dev on any repository. 

This means you don't have to clone a repo just to view it in VS Code you can do it right in the browser. This is awesome for exploring and learning about new repos. You can do all the normal VS Code actions like split view, jump to file navigation with ctrl + P on windows or cmd  + P on mac and much more. The only thing you can't do is run your code. That's where codesphere comes in (https://codesphere.com/).

If you are a contributor on a repo you can even make changes and commit those changes from the editor.

Documentation for the github.dev web-based editor can be found here:
https://docs.github.com/en/codespaces/the-githubdev-web-based-editor

{% embed https://youtube.com/shorts/-sfsTh6od1k?feature=share %}
JS Anagrams with Big O Notation
Tags: javascript, tutorial, algorithms, programming
Published: 2022-07-23 23:45:00

We say that two strings are **anagrams** of each other if they have the **exact** same letters in same quantity of existance of each letter, regardless of non-alphabetic letters and case sensitivity.

Here's an **example**

```javascript
// 'hello', 'elloh' -> anagrams
// 'love', 'hate' -> not anagrams
// 'i'm 26 years old' -> 'myeald oirs o' -> anagrams
```

Well, the **Solution** is Simple

We just need to remove all non-alphabetic letters first, and turn all letters into lower case.

```javascript
// 'Hello World!@# ---30..' -> 'helloworld30'

const inputString = 'Hello World!@# ---30..'
inputString.toLowerCase().replace(/[\W_]+/g, ''); // returns 'helloworld30'
```

**\W leaves the underscore, A short equivalent for [^a-zA-Z0-9] would be [\W_]**

Then we need to convert string to array, sort the array alphabetically, and then turn it back into a string

```javascript
// 'hello' -> ['h', 'e', 'l', 'l', 'o'] -> ['e', 'h', 'l', 'l', 'o'] -> ehllo

const inputString = 'Hello World!@# ---30..'
inputString.toLowerCase().replace(/[\W_]+/g, '').split('').sort().join(''); // returns '03dehllloorw'
```

Here's the final code

```javascript
const anagrams = (firstInput, secondInput) => {
  return (
    firstInput
      .toLowerCase()
      .replace(/[\W_]+/g, '')
      .split('')
      .sort()
      .join('') ===
    secondInput
      .toLowerCase()
      .replace(/[\W_]+/g, '')
      .split('')
      .sort()
      .join('')
  );
}
```

![Big-O Complexity Chart](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nc24auo96tc1k3wc8sgk.png)

**Big O Notation**
Time Complexity: O(n * Log n) because we've used sort algorithm

However, a Better solutions do exist, We'll also write another solution

```javascript
const anagrams = (firstInput, secondInput) => {
  firstInput = firstInput.toLowerCase().replace(/[\W_]+/g, '');
  secondInput = secondInput.toLowerCase().replace(/[\W_]+/g, '');

  if (firstInput.length !== secondInput.length) {
    return false;
  }

  const inputLetterCount = {};

  for (let i = 0; i < firstInput.length; i++) {
    const currentLetter = firstInput[i];
    inputLetterCount[currentLetter] = inputLetterCount[currentLetter] + 1 || 1;
  }

  for (let i = 0; i < secondInput.length; i++) {
    const currentLetter = secondInput[i];
    if (!inputLetterCount[currentLetter]) return false;
    else inputLetterCount[currentLetter]--;
  }

  return true;
};
```
**Big O Notation**
Time Complexity: O(n)
Space Complexity: O(1)

Happy Coding ❤
Dotfiles Backup using `chezmoi` (MacOS)
Tags: dotfile, backup, github
Published: 2022-07-23 23:27:45

## Install `chezmoi`

* Brew

```
brew install chezmoi
```

* Curl

```
sh -c "$(curl -fsLS https://chezmoi.io/get)"
```

## Backup

* (First time) Create a new repo - `$ chezmoi init`
* (First time) Create a github (or gitlab, etc) - https://docs.github.com/en/get-started/quickstart/create-a-repo
* Add / Update dot files - `$ chezmoi add ~/.zshrc`, `$chezmoi add ~/.config/neovim`, etc
* CD into local repo - `$ chezmoi cd`
* Commit your changes - `$ git commit -am "Initial commit"`
* (First time) Add remote origin - `$ git remote add origin git@github.com:username/dotfiles.git`
* Push your changes to remote repo - `$ git push -u origin main`

## Restore

* (First time) Clone remote repo - `$ chezmoi init https://github.com/username/dotfiles.git`
* Pull and apply the latest changes - `$ chezmoi update -v`


Reference: https://www.chezmoi.io
From UI to Authentication - New Years Resolution - Dev Log 37
Tags: startup, webdev, beginners, programming
Published: 2022-07-23 23:23:12

As the title says I am moving on from the UI this coming week to creating an Authentication flow. I just finished the UI for the main page of the website. While there are still other pages to build out, I think it would be smart to implement the Authentication flow early in the process.

The Next JS documentation provides two authentication patterns as examples. One is for static content like my home page and the other is for server-side generated content. In order to use these, you need to have a way to authenticate users. For that, I am going to go with Auth0. The reason I am going with Auth0 is mainly that it is completely managed for me and there are ample tutorials online for integrating Auth0 with Next JS. If I were being honest, they also are killing it on the marketing. I can not even really think of other options that manage user authentication for developers besides AWS Cognito. Since I now have a full-time job, the time I get to spend coding on this New Year's Resolution is a lot less than the months prior. So instead of looking into a million options and fighting with some random API because it is cheaper, I am just gonna go with the big name. Security is not something I want to slack on anyway.

As per usual I would love to show off what I have been making, but I still love the idea and still have not gotten past the "someone will steal it" phase. I know it is dumb and cheesy but romanticizing the project you are working on is part of being a developer in my opinion.
Reading list: Demand Curve - Tested tactics for growing newsletters
Published: 2022-07-23 23:07:00


- [How to Send Newsletters On Demand](https://blog.feedly.com/how-to-send-newsletters-on-demand/)
- [Demand curve tested tactics for growing newsletters](https://techcrunch.com/2021/08/03/demand-curve-tested-tactics-for-growing-newsletters/) 
- [On demand newsletters](http://www.tlehs.com/on-demand-newsletters) 
- [Advanced marketing insights. By email](https://www.demandcurve.com/newsletter#oktgfxnrwma0uvcsjkaw)
- [Deliver 100% personalized news and targeted newsletters to your partners – based on their preferences](https://www.impartner.com/news-on-demand/) 
- [Top-Level Advice and Guidance from Experts in IT and Cyber Security—at no cost to you](https://www.it-on-demand.com/free-stuff/newsletters/) 
- [Top 10 Supply Chain Newsletters](https://supplychaindigital.com/top10/top-10-supply-chain-newsletters) 
- [Demand Curve: Email marketing tactics that convert subscribers into customers](https://techcrunch.com/2021/06/28/demand-curve-email-marketing-tactics-that-convert-subscribers-into-customers/) 
- [Creating Demand With Email Newsletters](https://ezinearticles.com/?Creating-Demand-With-Email-Newsletters&id=17354) 
- [Email newsletters: start, improve, reap](https://www.zembr.co/blog-archive/email-newsletters-start-improve-reap) 
- [94% Of Marketers Cite Email As Integral For Pandemic & Post-Pandemic Success](https://demandgenreport.com/features/news-briefs/94-of-marketers-cite-email-as-integral-for-pandemic-post-pandemic-success/) 
- [The Future of Email in 2020 and Beyond: The Email Marketing Trends That Will Really Matter](https://www.litmus.com/blog/infographic-5-email-marketing-trends-2020/)
- [Partnerdemand newsletters](https://www.partnerdemand.com/hpi/newsletters)
- [63% of Marketers to Use Email Newsletters to Enhance First-Party Data](https://komarketing.com/industry-news/63-of-marketers-to-use-email-newsletters-to-enhance-first-party-data-4420/) 


## [Linkedin page of LLazyEmail](https://www.linkedin.com/company/llazyemail/)
Day 105: Hello Figma!
Published: 2022-07-23 22:24:08

Hi!
So as planned yesterday today focus was about Figma level up I found a 10 hour course from the same guy that did yesterday material design course and he is actually good at explaining concept in an easier way. I considered myself as someone with a decent Figma skills but I noticed a lot of things that I didn't even know they existed and tools that I used without understand their basics, generally I learned new concepts and tricks to boost productivity with Figma. I want to work on my design skills so I plan to be active regularly on Dribble and Behance. 
Tomorrow I plan to finish the rest of the course 
Signing off...
Hi there!👋
Tags: beginners, programming, codenewbie
Published: 2022-07-23 22:02:00

**Hi there! I'm learning coding for me...**
My nickname is **Jeff** and I'm new here. I come from a remote area in Kenya where internet and electricity were inaccessible back in 2000s, I knew nothing about tech and my dream was never to be a developer. All I wanted was to join med school and pursue a career in medicine. 

Well I joined one of the local universities but I wasn't accepted in med school as I had hoped. I stepped into the computing class with no prior knowledge, and even worse, with no interest. Everything I did back then was for academic purposes, I could do projects and throw them away as soon as the semester was done.

I registered good grades but all these were theoretical, little did I know I'll need them. I'm now a graduate and I realize how important learning to understand is. I've joined ALX Africa as a post graduate program to harness my skills in software engineering and later venture into machine learning and AI.
I learnt about dev.to yesterday while updating my GitHub account. I hope to meet new peers, mentors and connections throughout this journey of providing impeccable solutions to modern day problems. 
I'll also appreciate following on [GitHub](.https://github.com/Namukuru254), [Twitter](https://twitter.com/JaphethNamukuru?t=W44mqUhZVjHKm5J6FnxqmA&s=09) and [LinkedIn](https://www.linkedin.com/in/japheth-namukuru-26a631194).
Run gists using npx
Tags: javascript, node
Published: 2022-07-23 21:33:00

---
canonical_url: https://faun.pub/run-gists-using-npx-99cf1799daf2
---
We can run gists using npx. I learned about that after reading this: [https://nodejs.dev/learn/the-npx-nodejs-package-runner](https://nodejs.dev/learn/the-npx-nodejs-package-runner).

## I want to run my gist

I created a gist that prints some text. I ran the command, but it didn't work. I figured I needed package.json, so I added it and ran it, but it still didn't work. I remembered I needed a shebang comment and bin property. After adding those and running it, it worked. Here is the full gist:

code.js

```js
#!/usr/bin/env node

console.log('Does that even work?');

// --------------------------------------------------
// To let npx run the gist we need
//
//   - package.json
//   - shebang comment at the top of file
//     - https://en.wikipedia.org/wiki/Shebang_(Unix)
//   - bin property in package.json
// --------------------------------------------------
```

package.json

```json
{
  "name": "npx-runs-gist",
  "description": "the gist to run it with npx command",
  "version": "0.1.0",
  "bin": "./code.js"
}
```

run-the-gist.bat

```bat
REM this is a comment in .bat files
REM runs the gist on Windows OS

npx https://gist.github.com/srele96/55260739ddef08389a2d992e132c843e
```

## Use library in the gist

Armed with knowledge, I wanted to use a library. It was straightforward. I copy pasted the example from https://www.npmjs.com/package/commander. Afterward, I ran it, and it worked. Much less effort this time. Here is the full gist:

split.js

```js
#!/usr/bin/env node

const { program } = require('commander');

program
  .option('--first')
  .option('-s, --separator <char>');

program.parse();

const options = program.opts();
const limit = options.first ? 1 : undefined;
console.log(program.args[0].split(options.separator, limit));
```

package.json

```json
{
  "name": "split",
  "version": "0.1.0",
  "description": "run split example from commander docs using gist and npx",
  "dependencies": {
    "commander": "9.4.0"
  },
  "bin": "./split.js"
}
```

run-the-gist.bat

```bat
REM intentionally misspeleld --fits
npx https://gist.github.com/srele96/c4e645abd50c0b3c2e543c8557c044c9 -s / --fits a/b/c

REM uses the correct flag --first
npx https://gist.github.com/srele96/c4e645abd50c0b3c2e543c8557c044c9 -s / --first a/b/c

REM no flag 
npx https://gist.github.com/srele96/c4e645abd50c0b3c2e543c8557c044c9 -s / a/b/c
```
Como criar um banco de dados MySQL
Published: 2022-07-23 21:08:58

Conectar ao servidor:

```
mysql -u root -p
```
Criar banco de dados:
```
CREATE DATABASE testdb;
```
Exibir bancos de dados:
```
SHOW DATABASES;
```

Fonte: [MySQLTUTORIAL](https://www.mysqltutorial.org/mysql-create-database/)
Commoditic Prices API
Published: 2022-07-23 20:32:20

Hi, dev community! My name is John Lucci and I am currently working as a project manager at the rising start-up financial service company Commoditic that specializes in the data accumulation and transfer of commodities prices. In other words, Commoditic is a data provider of spot and historical commodities prices that maintains up-to-date commodity databases accessible through API. According to the commodity class asset, there are four major APIs through which customers can get energy prices, metals prices, livestock commodities prices, and agricultural commodities prices. If you are interested in metals prices, then you can check out the Metals Prices API. Surely, you can pick the one of the rest APIs - Energy Prices API, Agricultural Commodities Prices API and Livestock Commodities Prices API. For further information: https://commoditic.com/
Paracetamol.js💊| #174: Explica este código JavaScript
Tags: spanish, webdev, programming, javascript
Published: 2022-07-23 20:25:07

## **<center>Explica este código JavaScript</center>**
#### <center>**Dificultad:** <mark>Intermedio</mark></center>

```js
const miFn = () =>{
  const x = 15;
  if(2 === Number(2)){
    if(true){
      var y = x;
    }
  }
  return y;
}

console.log(miFn())
```

A. `y`
B. `15`
C. `2`
D. `ReferenceError: y is not defined`

Respuesta en el primer comentario.

---
[Algorithms] 6 - My Solution for PrintTree Problem (DFS)
Published: 2022-07-23 20:23:00

- [Link for the problem description video](https://www.youtube.com/watch?v=V0xjK_6ZoEY)

```cpp

#include <iostream>
#include <vector>
#include <string>
#include <utility>      // std::pair, std::make_pair
#include <unordered_map>

using namespace std;

void DFS(int depth, string key, unordered_map<string, vector<string>> mp){
    if(!mp.count(key))// if key does not exist
        return;
    vector<string> values = mp[key];
    
    for (int i = 0; i < values.size(); i++){
        for (int j = 0; j < depth; j++)
            cout << "\t";
        cout << values[i] << endl;
        DFS(depth+1, values[i], mp);
    }
}

int main()
{
    vector<pair<string, string>> input;
    input.push_back(make_pair("animal", "mammal"));
    input.push_back(make_pair("animal", "bird"));
    input.push_back(make_pair("lifeform", "animal"));
    input.push_back(make_pair("cat", "lion"));
    input.push_back(make_pair("mammal", "cat"));
    input.push_back(make_pair("animal", "fish"));
    unordered_map<string, vector<string>> mp;
    unordered_map<string, bool> seen;
    
    for (auto p : input){
        
        string key = p.first;
        string val = p.second;
        seen[val] = true;
            
        
        if(mp.count(key)){
            mp[key].push_back(val);
        } else {
            vector<string> arr = {val};
            mp[key] = arr;
        }
    }
    
    // Finding the start point (root node)
    // 1. Brute force: Use DFS and count the height
    // 2. If the string ever appeared in the p.second (as a val) then remove from the candidate
    string root = "";
    for (auto m : mp){
        if(!seen.count(m.first)){
            root = m.first;
        }
    }
    cout << root << endl;
    DFS(1, root, mp);
    
    // Use DFS to print out every child
    // Need to add depth for every vector array

    return 0;
}


```