teleren/devto huggingface dataset:
Electron Adventures: Episode 11: jQuery
Tags: electron, javascript, jquery
Published: 2021-08-04 00:47:19

So far I used bare browser APIs to manipulate the frontend. This is no way to write frontend code, so over the next few episodes I'll be using a lot of different frontend frameworks.

Starting with the much beloved classic [jQuery](https://jquery.com/). Rumors of jQuery's deaths have been vastly exaggerated, [it's still used by 80% of the website on the internet](https://trends.builtwith.com/javascript/jQuery), and it will surely outlive us all. [Unless we solve aging and live forever](https://www.sens.org/).

### Install jQuery

As I mentioned before, we do not want to use CDN to load jQuery, or anything else for that matter - all our resources should be bundled with our app if possible.

```shell
  $ npm install jquery
```

We can copy all assets from previous episodes except for the `app.js` script.

### Load jQuery

It works just like it did with D3, just one extra line before our `app.js` script:

```html
<script src="./node_modules/jquery/dist/jquery.js"></script>
```

### jQuely `app.js`

And now we can rewrite DOM manipulations in jQuery. It's both more concise, and more readable.

```javascript
function appendInput(command) {
  let e = $(
    `<div class='input-line'>
      <span class='prompt'>$</span>
      <span class='input'></span>
    </div>`)
  e.find('.input').text(command)
  $("#history").append(e)
}

function appendOutput(output) {
  let e = $(`<div class='output'></div>`)
  e.text(output)
  $("#history").append(e)
}

$("form").on("submit", function(e) {
  e.preventDefault()
  let command = $("input").val()
  let output = window.api.runCommand(command)
  appendInput(command)
  appendOutput(output)
  $("input").val("")
  $("input")[0].scrollIntoView()
})
```

### Security

Now it would be tempting to use direct string interpolation and just type `<span class='input'>${command}</span>`, but that's insecure, and the app would behave incorrectly if command or output contained special characters like `<` or `>` - which shells use all the time, even if for something different than HTML.

There are other ways to be even more expressive, and secure, without using bundlers - such as [tagged template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) and various template libraries like [handlebars](https://handlebarsjs.com/).

The choice is yours, even more so that with a normal web apps, as Electron really doesn't care what you use for the frontend part, and you know exactly which browser you'll be using as you're bundling it with the app.

### Result

It looks just like previous two episodes, but let's make some new screenshots anyway:

![Episode 11 screenshot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/elyqageg3df9qiyv972s.png)

In the next episode we'll get some fancy Google Fonts for our terminal app. Then we'll get to the bundlers.

As usual, [all the code for the episode is here](https://github.com/taw/electron-adventures/tree/master/episode-11-jquery).
6 CSS Selectors That You Will Use At Least One Of Them In Your Next Project
Tags: html, css, webdev, beginners
Published: 2021-08-04 00:37:35

Hello,
I'm [**Aya Bouchiha**](https://t.me/AyaBouchiha),
today, we're going to talk about **6 CSS Selectors That You Will Use At Least One Of Them In Your Next Project**.

## element1~element2

**element1~element2**: used to match occurrences of element2 that are preceded by element1.
Note: element1 and element2 should have the same parent.

{% codepen https://codepen.io/Aya_Bouchiha/pen/abWjgdR %}
 
## element1+element2

**element1 + element2**: means select the next sibling of element1.

{% codepen https://codepen.io/Aya_Bouchiha/pen/mdmjZOJ %}

## element1>element2

**element1 > element2**: means select element2 where element1 is its parent.

{% codepen https://codepen.io/Aya_Bouchiha/pen/GRmBbWp %}

## element1 \* 

**element1 \***: select all elements that are inside element1.

{% codepen https://codepen.io/Aya_Bouchiha/pen/wvdxLeg %}

## ::first-letter

**::first-letter**: used to select the first letter of the specified element.
The properties that  can be used with ::first-letter are:
+ font properties
+ color properties
+ background properties
+ margin properties
+ padding properties
+ border properties
+ text-decoration
+ vertical-align (only if float is 'none')
+ text-transform
+ line-height
+ float
+ clear

[more details](https://www.w3schools.com/cssref/sel_firstletter.asp)

{% codepen https://codepen.io/Aya_Bouchiha/pen/WNjKqZE %}


## ::selection
**::selection**: used to make styling to a piece of content that has been selected, highlighted, dragged using the mouse by the user.

The properties that  can be used with ::selection are:
+ color
+ background-color
+ text-decoration and its associated properties
+ text-shadow
+ stroke-color
+ fill-color
+ stroke-width

[more details](https://developer.mozilla.org/en-US/docs/Web/CSS/::selection)

{% codepen https://codepen.io/Aya_Bouchiha/pen/OJmweQW %}

### Summary

+ **element1~element2**:used to match occurrences of element2 that are preceded by element1.
+ **element1 + element2**:  selects the next sibling of element1.
+ **element1 > element2**:  selects element2 where element1 is its parent.

+ **element1 ***: selects all elements that are inside element1.
+ **::first-letter**: selects the first letter of the specified element.
+ **::selection**: makes styling to a piece of content that has been selected, highlighted, dragged using the mouse by the user.


### References

+ [www.developer.mozilla.org](https://developer.mozilla.org/)
+ [www.w3schools.com](https://www.w3schools.com/)

### Suggested Posts

+ [5 HTML Tags That Almost Nobody Knows](https://dev.to/ayabouchiha/part-2-5-html-tags-that-almost-nobody-knows-nj8)

+ [Youtube Courses, Projects To Learn Javascript](https://dev.to/ayabouchiha/youtube-courses-projects-to-master-javascript-3lhc)

+ [All JS String Methods In One Post!](https://dev.to/ayabouchiha/all-js-string-methods-in-one-post-4h23)

To Contact Me:

+ email: developer.aya.b@gmail.com
+ telegram: [Aya Bouchiha](https://t.me/AyaBouchiha)


Have an amazing day!
Installing Node 12 and higher on a Raspberry Pi Zero with nvm
Tags: raspberrypi, node, nvm, javascript
Published: 2021-08-04 00:15:54

---
title: Installing Node 12 and higher on a Raspberry Pi Zero with nvm
published: true
description: Instructions on how to use unofficial node.js builds for ARM V6 with nvm
 
tags: 
- raspberrypi
- nodejs
- nvm
- javascript
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/013ba8b2ne9f7hbdzp55.png

---

I usually use [nvm](https://github.com/nvm-sh/nvm) to manage node.js versions for projects, but there are not official binaries for the ARM V6 chip in a Raspberry Pi Zero for node versions 12 and higher. The source is still available, and so if you try `nvm install 14.17.4` nvm will attempt to compile from source, which on a Raspberry Pi zero will take a long, long, long time (and probably fail).

Fortunately node.js provides "unofficial builds" of newer node versions for ARM v6 at [unofficial-builds.nodejs.org](https://unofficial-builds.nodejs.org/).

You can use these binaries with nvm by providing a url to use instead of the default node.js binaries url:

## nodejs 14
```
NVM_NODEJS_ORG_MIRROR=https://unofficial-builds.nodejs.org/download/release nvm install 14
```

## nodejs 16
```
NVM_NODEJS_ORG_MIRROR=https://unofficial-builds.nodejs.org/download/release nvm install 16
```
7 Cara Mengatasi Hp Android Cepat Panas Dijamin 100% Work
Published: 2021-08-04 00:05:50

Saat ini handphone sudah menjadi sebuah kebutuhan yang tidak bisaditinggalkan. Karena itu bila tidak dapat berfungsi dengan baik bisa menghambat semua pekerjaan. Terutama bagi yang mempunyai usaha online. Atau yang berprofesi sebagai penulis. Ada berbagai hal yang dapat menyebabkan hp menjadi cepat panas. Selain karena pemakaian yang terus menerus ada juga sebab lain yang bisa membuatnya cepat panas. 

https://kuyakepo.blogspot.com/
How to add a Spotify playlist to your site
Tags: websites, spotify
Published: 2021-08-07 07:25:50

---
title: How to add a Spotify playlist to your site
published: true
date: 2021-08-04 00:00:00 UTC
tags: websites,spotify
canonical_url: https://driesdeboosere.dev/blog/how-to-add-a-spotify-playlist-to-your-site/
---

Adding a Spotify playlist to your website is realy easy. It's just getting some HTML code from Spotify that you can paste in your own HTML.

## Open Spotify

Open the Spotify application and go to your playlist that you want to share on your website.

## Get the HTML

1. Click on the three dots
2. Go to _Share_ and then _Embed playlist_

![Embed playlist](https://driesdeboosere.dev/blog/files/how-to-add-a-spotify-playlist-to-your-website/how-to-add-a-spotify-playlist-to-your-website-01.png)

Now you see the following screen: ![Embed playlist](https://driesdeboosere.dev/blog/files/how-to-add-a-spotify-playlist-to-your-website/how-to-add-a-spotify-playlist-to-your-website-02.png)

This is how your playlist is gonna look like when you paste the html code in your website.

Now click on the **Copy** button to copy the code. This should look like something to this:

`<iframe src="https://open.spotify.com/embed/playlist/5aXXutTCAQMAXHV7juYBR0" width="100%" height="380" frameBorder="0" allowtransparency="true" allow="encrypted-media"></iframe>`

If you paste this HTML code in your the HTML of your website then you'll see the (playable) Spotify playlist on your website. It will look exactly like the playlist you see in the preview:

![Embed playlist](https://driesdeboosere.dev/blog/files/how-to-add-a-spotify-playlist-to-your-website/how-to-add-a-spotify-playlist-to-your-website-02.png)
How to see the current date and time on the Linux terminal?
Tags: resource
Published: 2021-08-04 00:00:00

---
  title: How to see the current date and time on the Linux terminal?
  published: true
  tags: Resource
  date: Wed Aug 04 2021 05:30:00 GMT+0530 (India Standard Time)
  canonical_url: https://melvingeorge.me/blog/see-current-date-time-on-terminal-linux
  cover_image: https://melvingeorge.me/_next/static/images/main-bfdeef23195be38cb0909931a7eeb526.jpg
  ---
  [Originally posted here!](https://melvingeorge.me/blog/see-current-date-time-on-terminal-linux)
  
To see the current date and time, you can use the `date` command on the Linux terminal.

```bash
# See the current date and time
date

# OUTPUT
Sat Aug 04 21:23:25 UTC 2021
```

See the execution of the above command live in [repl.it](https://replit.com/@melvin2016/see-current-date-and-time-on-linux-terminal#main.sh)

That's all 😃!

### Feel free to share if you found this useful 😃.

---
Testing Authenticated Routes in Phoenix
Tags: phoenix, elixir, testing
Published: 2021-08-06 08:04:58

---
title: Testing Authenticated Routes in Phoenix
published: true
date: 2021-08-04 00:00:00 UTC
tags: [Phoenix, Elixir, Testing]
canonical_url: https://warrenwong.org/posts/testing-authenticated-routes-in-phoenix
---

This will be a quick one, but it was tough for me to find.

Just some background: I used [`phx_gen_auth`](https://github.com/aaronrenner/phx_gen_auth) for authentication in my app. This little tidbit is going to play an important role in my "no duh" moment.

After using `phx.gen.html` or `phx.gen.live` to do some heavy lifting, Phoenix is nice enough to write out some tests for me as well.

Only problem is when I require an authenticated user for a certain route or resource. My nicely passing out-of-the-box tests no longer pass.

Well, jumping into the code, I just started by fixing one test at a time. I looked in the `user_session_controller_test.exs` file generated from running `phx.gen.auth` and found how they created the user:

```elixir
import MyAwesomeProject.AccountsFixtures

setup do
  %{user: user_fixture()}
end

```

Okay, great! That means I can easily run `user_fixture()` to create a user and pass it into each test.

I then looked how the user was logged in in the test:

```elixir
test "redirects if already logged in", %{conn: conn, user: user} do
  conn = conn
  |> log_in_user(user)
  |> get(Routes.user_session_path(conn, :new))
  assert redirected_to(conn) == "/"
end

```

Okay, simple enough. There's nice conveniently named function called `log_in_user/2` that takes `conn` and `user` as parameters. Nice. I can do that on each of my tests too. But wait, that's not very [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) at all. Well, let's not even pass in the `user` to each test when I can just pass in an updated `conn` after logging in the user with `log_in_user/2`.

```elixir
defp log_in_user(%{conn: conn}) do
  %{conn: log_in_user(conn, user_fixture())}
end

...

describe "MyAwesomeTest" do
  setup [:log_in_user]
  ...

```

But wait, where did `log_in_user/2` come from. I had just made an assumption that it came from my import of `MyAwesomeProject.AccountsFixtures`. It actually came from `MyAwesomeProject.ConnCase`. It's that `phx.gen.auth` magic at work again!

And you know what I found when I just looked around in `conn_case.exs`?

```elixir
@doc """
Setup helper that registers and logs in users.

    setup :register_and_log_in_user

It stores an updated connection and a registered user in the
test context.
"""
def register_and_log_in_user(%{conn: conn}) do
  user = GrokTheGreeks.AccountsFixtures.user_fixture()
  %{conn: log_in_user(conn, user), user: user}
end

```

I've never been happier knowing I wasted my time writing throw-away code.
How to create server files with Flask
Tags: flask, backend, python, nelsoncode
Published: 2021-08-03 23:38:39

In this example I will show you how to upload, download, delete and obtain files with Flask

### Upload multiple files with Form Data

```python

from flask import Flask
import os

app = Flask(__name__)

@app.route("/upload", methods=['POST'])
def upload_image():
    if request.method == "POST":
        file = request.files['file']
        try:
            file.save(os.getcwd() + "/images/" + file.filename)
            return "Imagen saved"
        except FileNotFoundError:
            return "Folder not found"

if __name__ == '__main__':
    app.run(debug=True, port=8000, host="0.0.0.0")
```

### Download files

```python

from flask import Flask
import os

app = Flask(__name__)

@app.route('/download/file/<string:filename>')
def download_image(filename):
    return send_from_directory(os.getcwd() + "/images/", path=filename, as_attachment=True)

if __name__ == '__main__':
    app.run(debug=True, port=8000, host="0.0.0.0")
```


### Get files

```python

from flask import Flask
import os

app = Flask(__name__)

@app.route('/file/<string:filename>')
def get_image(filename):
    return send_from_directory(os.getcwd() + "/images/", path=filename, as_attachment=False)

if __name__ == '__main__':
    app.run(debug=True, port=8000, host="0.0.0.0")
```


### Delete files

```python

from flask import Flask
import os

app = Flask(__name__)

@app.route('/delete', methods=['POST'])
def remove_image():
    filename = request.form['filename']

    # CHECK IF EXISTS FILE
    if os.path.isfile(os.getcwd() + "/images/" + filename) == False:
        return "Esto no es un archivo"
    else:
        try:
            os.remove(os.getcwd() + "/images/" + filename)
        except OSError:
            return "Error :(("
        return "File deleted"

if __name__ == '__main__':
    app.run(debug=True, port=8000, host="0.0.0.0")
```
VS Code: Built-in Formatter for .js / .ts / .json / .html
Tags: vscode, formatter, text, manipulation
Published: 2021-08-03 23:30:24

As [Visual Studio Code says](https://code.visualstudio.com/docs/editor/codebasics#_formatting) in its website:

> VS Code has has default formatters for JavaScript, TypeScript, JSON, and HTML.

The keyboard shortcut:

__[Ctrl] + [Shift] + i__

brings formatted text. Like this :)

![vscode formatter](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rzh1p0fbeb7odqxb8675.gif)

It aims to format the whole text in file.
Well, there is also part formatter on selected text. The keyboard shortcut is:

__[Ctrl] + k__ then __[Ctrl] + f__

![vscode formatter](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ddzwb8ab9junhye7pyyk.gif)
C# Loops - Part 3: Do..While and While Loops
Tags: codenewbie, beginners, tutorial, csharp
Published: 2021-08-03 22:42:09

## Do...While loops 

Do while loops allow developers to repeat code execution as long as a condition is met. So whereas before we were instructing the code to run a number of times, or from beginning to end of an object. Now, we tailor it a little more and say only keep running this code "until" this condition is no longer valid. 

## How do they work then ?
```c# 
do{
   //Code goes here
}
while(condition)
```

Unlike the For and Foreach loop, the code is executed a minimum time of once. As the _do_ code is ran **before** the _while_ check. 

Example :

```c#

var counter =0;

do {
   Console.WriteLine("Keep Going");
   counter++;
}
while (counter < 10);
```

Here the code will run once, check if counter is less than 10, if it is it will keep going. Once the counter is >=10 the loop will exit and no longer execute the _do_ code. 

## While Loop

Ok so the while loop works on a very similar concept to the _do while_, however rather than running the code first then checking. The check is done first. Meaning the code will **only** run whilst the condition is met. 

### Syntax and Example:

```c#
var sum = 0;
var dartsThrown = 0;
while(sum < 180 && dartsThrown <3)
{
  var dartScore = new Random.Next(61);
  sum+= dartScore;
}
Console.WriteLine("Your score is " + sum);
```

## Summary 

There you go you've been introduced to the 4 ways of looping within C#. Each has there uses and are suited better for certain situations. 

After you've played around with them yourself , you'll see how easy they are to use, and which loop would suit your needs best.
C# Loops - Part 2 : For Each Loops
Tags: codenewbie, tutorial, beginners, csharp
Published: 2021-08-03 22:41:34

## For Each Loops

The _For Each Loop_ in concept works like any other loop in that it iterates over an object a number of times. However in a Foreach loop it will go from the first item all the way through to end in sequence. Unless, you manipulate the sequence by skipping items using the _continue_ keyword. 

## How does it work ?

The _foreach_ loop can iterate over any object that inherits from the IEnumerable class (e.g lists, collections). 

As already mentioned, it does this in order of the list, i.e order the items were loaded in / added to the list (or ordered). It does this because it iterates over the _instances_ of the list. An instance is a concrete occurrence of any object, existing usually during runtime, from memory. 

Example:

```c#
var names = new List<string>();
names.Add("Grant", "Barry", "Jenny”,"Shaun");

foreach(var name in names)
{
  Console.WriteLine(name);
}

//Output
Grant
Barry
Jenny
Shaun
```

I'll show you an example of a object with more properties. 

```c#

public class AddressBook {

public string Name {get;set;}
public string Address {get;set;}
public string Tel {get:set}

public AddressBook ()
{
}
}

var addresses = AddressBook();
addresses.Add(
     new Address{
       Name = "Grant"
       Address = "Developer Avenue, DevTown"
       Telephone = "019286661"
     },
     new Address{
       Name = "Terry"
       Address = "5 Developer Avenue, DevTown"
       Telephone = "019286662"
     });

foreach (var address in addressBook){
  Console.WriteLine(address.Name);
  Console.WriteLine(address.Tel);
}

//Output
Grant
019286661
Terry
019286662
```

That's how you can use the For Each loop. However there are some caveats. 

- You can't access instances within an object using indexing like the previous for loop. You know the _list[1]_ syntax. This is because the IEnumerable class doesn't expose this functionality.

- Thwre are some performance overheads with foreach loop, how it works behind the scenes. I won't get into it now but sometimes it can run slower than a for loop. But the pros can sometimes outweigh this.  

- Foreach loops make a copy od the object you're looping through. Therefore , amendments or assignments to the current item's properties is not feasible, i.e you cannot loop through a list and update all the values using a Foreach loop. You would need to use a _for loop_.  

Well that's all I've got for now on foreach loops. Next up.. do while and while loops
How to clean some disk space on a Linux instance ?
Tags: devops, linux, bash
Published: 2021-08-03 22:38:57

If you are lucky, the disk usage was already monitored and you have been warned on time. Otherwise it's already too late and some of your apps are simply not working anymore. To help you get back on track asap, here are some useful commands I found throughout the years to quickly and safely made room again on your instance / server.

First connect to it via SSH of course and become root with `sudo su -`

Then given your case, if you are using on it **Docker** to run containers :
* if your app is still running, clean Docker resources smoothly
```
docker images -q | xargs docker rmi
docker container prune -f
docker image prune -a -f
docker system prune -a -f
docker volume prune -f
```
* if you app is already down, clean all Docker resources in one shot
```
docker system prune
```
* if a container does not rotate its log, that may represent a huge file, go clean it
```
cd /var/lib/docker/containers/<container_id>/ # a file <container_id>-json.log is supposed to be there
truncate -s 0 <container_id>-json.log
```

If you are using a Linux distribution with **systemd**, you can clean its logs:
```
cd /var/log/journal # they are here
journalctl --disk-usage # have a look at how much you can reclaim
journalctl --vacuum-time=7d # reclaim it (7d = keep logs from last week only)
```

**Look elsewhere on the instance if you still need more space :**
```
du -sh * | grep "G" # travel around to find most imposant directories
```
* if it's a log file you can truncate it : `truncate -s 0 YOUR_LOGFILE.log`
* if you find a directory containing old files that are not needed anymore:
```
pwd # DOUBLE CHECK that you are inside the right directory to clean
find * -type f -mtime +100 -exec rm -rf {} \; # remove files not modified since 100 days for example
```

You should be good now and your apps should be back and running again, maybe you will need to redeploy / restart them for that.

Finally it's time now for continuous improvement :
* make sure the disk space on this instance is well monitored and the threshold in place does leave you enough time to intervene 
* your goal is to never do that again : find easy cleaning commands that you can put in the crontab of this instance for example

Please let us know if this article helped you in some ways, I would love to hear your stories regarding this usecase (never funny) and your personal tips and suggestions too.

I wish you a great day!
gRPC connection library in Go

Tags: go, grpc, concurrency, middleware
Published: 2021-08-03 22:15:51

Hello,

I have written a simple grpc-connection-library in Go.

Features:

1. The gRPC connection flow among server/client synchronized using the Ping/Pong services.

2. gRPC connection library supports connection pool reuse the gRPC client connection instance.

3. Concurrency Pipeline design pattern synchronizes the data flow among several stages while creating the connection pool.

4. The selection process of the gRPC connection instance from the pool is designed using the reflect.SelectCase that supports pseudo-random technique for choosing among different cases.

5. go-batch processing library implemented to divide the connection instances from the pool into batches.

6. The grpc-retry policy helps to retry the failure of gRPC connections with backoff strategy.

7. The grpclog will show the internal connection lifecycle that will be useful to debug the connection flow.

Github:

https://github.com/Deeptiman/grpc-connection-library

Wiki:

https://github.com/golang/go/wiki/gRPC-connection-library

Release: v1.0.0