teleren/devto huggingface dataset:
Vue.js Basics Part 4 | Lifecycle and Template Refs
Tags: vue, javascript, webdev, programming
Published: 2022-09-03 04:20:25

Today, I will be talking about `ref` attribute in Vue.js. 

_This is part 4 of my Vue.js Basics series, to read part 2, please click [here](https://dev.to/ahmetmeliksah/vuejs-basics-part-3-computed-property-3hmo) (spoiler! Part 3 is about computed property)_

We use `ref` attribute when we need to manually work with the DOM. Perhaps, the most common use case is forms, especially when we want to focus on input when the page is 'mounted' (loaded). 

'Mounted' is one the lifecycle hooks in Vue. What are lifecycle hooks? In short, each Vue component goes through a series of steps when it's created. Some of the most common ones are `updated` and `unmounted`. 

Why lifecycle hoooks? Because they give us opportunities to add our own code at specific stages (when page is loaded/rendered, updated, unmounted and e.g.).

What does `mounted` attribute do? `mounted` hook is used after the component has finished the initial rendering. That means whatever we put inside `mounted` will be run immediately after the component 'mounts' (after first render).

Let's get back to `ref`. So, how to use it? 
Like so:

```javascript
<template>
  <p ref="p">hello</p>
</template>
```
First of all, add `ref` attribute to element that you want to reference. `ref="p"`, 'ref=' indicates reference, and 'p' indicates how you refer to it. I will throw in the code below, so it will be more understandable

```javascript
<script>
export default {
  mounted() {
    this.$refs.p.innerHTML = "yooo"
  }
}
</script>
```
In `mounted` hook (and in any lifecycle hooks), we have access to objects using the `this` keyword, otherwise, Vue won't know what we're referring to. `this.$refs.p.innerHTML = "yooo"` with this line of code, we go to `ref` and choose `p` (remember ref="p") and change its innerHTML value to something else.

To sum it up, today we briefly talked about lifecycle hooks and template reference (ref) in Vue.js
Live reloading in Rust
Tags: rust, beginners
Published: 2022-09-03 04:13:20

I've been learning [Rust](https://www.rust-lang.org/) on and off since last fall. I'm still not proficient in the language as I haven't dedicated as much time to the language as I'd like to. Still, I find pockets of time, like tonight, to dive in a bit.

A quick Google of "rust hot reloading" introduced me to the rust crate, [cargo-watch](https://crates.io/crates/cargo-watch). I installed it as per their instructions `cargo install cargo-watch`.

From there, I went into a rust project I'm working on and ran the following from the project's root from the command line, `cargo watch -x 'run'`.

And that was it! I was able to start up my program, and with every change, it reran automatically!

```bash
[Finished running. Exit status: 101]
[Running 'cargo run']
   Compiling rusty v0.1.0
    Finished dev [unoptimized + debuginfo] target(s) in 0.12s
     Running `target/debug/rusty`
["tobey maguire", "andrew garfield", "tom holland"]
[Finished running. Exit status: 0]
[Running 'cargo run']
   Compiling rusty v0.1.0
    Finished dev [unoptimized + debuginfo] target(s) in 0.13s
     Running `target/debug/rusty`
["tobey maguire", "andrew garfield", "tom holland", ""]
[Finished running. Exit status: 0]
[Running 'cargo run']
   Compiling rusty v0.1.0
    Finished dev [unoptimized + debuginfo] target(s) in 0.12s
     Running `target/debug/rusty`
["tobey maguire", "andrew garfield", "tom holland", "pete davidson"]
[Finished running. Exit status: 0]
```

🦀

Photo by <a href="https://unsplash.com/@mackenziejcruz?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Mackenzie Cruz</a> on <a href="https://unsplash.com/s/photos/crabs?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
Diritto all'oblio
Tags: dirittoobliogdpr, gdpr
Published: 2022-09-03 04:07:48

The right to be forgotten, still under debate. Home » Blog » The right to be forgotten. The right to be forgotten is a concept linked to the world of the computer network and has gained popularity. Let's take a look at the topic.

Hypoconnectivity
The interest of the human being to be and feel connected in a globalized world has not reached limit.

The following data give an account of such a situation and offer us a more approximate idea, thanks to the figures. The amounts correspond to the day to day of shipments, views and starts, respectively:

These and other applications that millions of people use have permeated almost all areas of life. People are so associated with their social networks that they do not realize that they are generating information about themselves, with a monetary value.

In 2009, Google launched a new version of advertising based on the user's specific interests. In the same year, television advertising was reportedly overtaken in the UK. The information of individuals who use social networks indiscriminately has not been ignored by companies that, in this context, monetize it.

caught in the net
In 2012, the University of Worcester conducted a study and found that 70% of social networks leak private information. The ease with which such information is accessed shows the user's disadvantage in trying to protect their information [diritto all'oblio italia](https://dirittoobliogdpr.com/).

This month, Thirteen Bits reports that this practice has also reached Instagram on more than one occasion. And not only images of celebrities and influencers were leaked , but even phone numbers and emails.

Right to be forgotten
In this context, where personal data circulates freely on the internet, the right to be forgotten is born .

According to a note from the Excelsior in 2018, the right to be forgotten is an aspect of the right that is also known as habeas data.

The newspaper defines it as the right for any person to request the cancellation of their personal information by withdrawing digital media. This includes links located in search engines that affect the free development of your fundamental rights.

The so-called right to cancellation allows the citizen to request suppression of information if there is no historical memory or of public interest. This is stated in rule C 131/12 of the European Commission.

Much remains to be seen
Today, the issue is not closed, as Orlando Jorge Mera, of Forbes Mexico , points out :

“The right to be forgotten makes sense when we talk about people who are not public and about events that are clearly in the past. There is still no clear doctrine on how interpretations should operate. There is still much to see.”
Add Digits - I
Published: 2022-09-03 03:54:13

```js
const addDigits = function(num) {
 num = num.toString();
    let newNumber = 0;
    for (let i = 0; i < num.length; i++) {
        newNumber += Number(num[i]);
    }
    if (newNumber.toString().length === 1) return newNumber;
    return addDigits(newNumber);
};
```
Skill Up! - (Re)acting!
Tags: react, webdev, theoffice, javascript
Published: 2022-09-03 03:46:27

# Hi, 

To the new, Welcome; To the current, Thanks for coming back.
I've been learning React and it has actually been fun. 
The MERN stack now has an official spot in my inventory. 

There is one thing that I've picked up along the way, that has made everything SO MUCH EASIER.

## Perseverance 

I've been on and off coding since '05, and my issue was pushing through when I felt like I SHOULD HAVE known something, but I had just started. So my dreams grew faster than my skills, and my pride couldn't take it. So I stopped. 

But with React, I just kept going. Even if no one will look at that repo, finish the project. 

At a minimum, that's one more project. 
At maximum, you're now that much more competent at something.

Thanks for reading.
ECMAScript o JavaScript?
Tags: javascript, webdev, beginners, spanish
Published: 2022-09-03 03:39:55

Este no es un post ordinario, aquí voy a colocar notas de estudio de este tema tan basto que es JavaScript, o si tu vienes para saber que es ECMAScript puedes bajar unos cuantos párrafos, que hoy vamos empezar desde el inicio de los tiempos...

## Historia de JavaScript 

Antes de que se escribiera la primer linea de código de JS, en 1950 empezaba a nacer la computación moderna, la primeras computadoras eran enormes cajas de metal que solo podían ser adquiridas por grandes empresas, estas cajas que ahora son obsoletas se utilizaban para realizar enormes cantidades de cálculos, principalmente útiles para el sector militar. 

[ *Dato curioso = Un teléfono inteligente actual tiene mas poder de calculo y procesamiento que la computadora utilizada en el alunizaje ]


![El Apollo Guidance Computer fue un componente fundamental del programa Apolo. Proporcionaba la capacidad de cálculo necesaria para controlar la orientación y la navegación del módulo de mando y del módulo lunar.](https://upload.wikimedia.org/wikipedia/commons/e/e2/Dsky.jpg)
El Apollo Guidance Computer fue un componente fundamental del programa Apolo. Proporcionaba la capacidad de cálculo necesaria para controlar la orientación y la navegación del módulo de mando y del módulo lunar. Módulo de memoria volátil de 1024 bits del AGC del Apolo
![Image description](https://conceptodefinicion.de/wp-content/uploads/2014/08/smartphone.jpg)

Ahora en 1969 se creo la red ARPANET, este fue el primer protocolo para conectar dos computadoras. Este y otros protocolos se siguieron desarrollando entre 1970 - 1990, en 1990 Tim Berners-lee creo la world wide web, fue un forma nueva acceder a documentos, archivos o enlaces para navegar a otros lugares. 

En 1993 se creo Mosaic, fue el primer navegador de internet de fácil acceso. 

En 1995 Microsoft lanzo internet explorer, dando inicio a los browser wars, esta guerra inicia con internet explorer vs Netscape, en los siguientes anios luego se fueron agregando chrome, Firefox y safari. 

Dentro de Netscape nace JavaScript en 1995, por su lado Microsoft lanzo JScript, debido a esto en 1997 nace ECMA--->(European Computer manufacturer Association). ECMAScript es el estándar que se encarga de establecer como debe ser interpretado y debe funcionar JavaScript....

ECMAScript es el estándar ----> JavaScript es el lenguaje

## ECMAScript o JavaScript?

Si quieres aportar al lenguaje con ideas, implementaciones o nuevos métodos te puedes dirigir a la TC39 ----> Technical Committee No 39. Este comité se encarga de aceptar e implementar cambios al lenguaje.

Cuando hay cambios al lenguaje se creo un lanzamiento denominado ESxx, En 1997 se lanzo ES1 (primer ajuste), en el 2005 se lanzo ES5, en el 2018 se lanzo el ES9 ( ECMAScript 9)

La ultima version es ES2022
Automate Linting Python Scripts
Tags: python, github
Published: 2022-09-03 03:05:39

Create a Github Action to lint your Python scripts, simply copy & paste the following snippet and place it in your repository - `.github/workflows/lint.yml`.

**TLDR;**

```yaml
name: Lint
on: 
  - push
jobs:
  lint:
    name: Lint
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v2
      - name: autopep8
        id: autopep8
        uses: peter-evans/autopep8@v1
        with:
          args: --exit-code --recursive --in-place --aggressive --aggressive .
      - name: Commit autopep8 changes
        if: steps.autopep8.outputs.exit-code == 2
        run: |
          git config --global user.name '<your-name>'
          git config --global user.email '<your-email-address>'
          git commit -am "Automated autopep8 fixes"
          git push
```

Do update the `<your-name>` and <`your-email-address>` accordingly and you are good to go.
How I ported my discord rss bot to koyeb
Tags: koyeb, discord
Published: 2022-09-03 02:57:51


Read this post on my blog at https://friendlyuser.github.io/astro-tech-blog/posts/heroku_shutdown_migrate_to_koyeb/

Unfortunately, due to corporate greed, heroku is shutting down, the community has already rallied against this change. There are many other alternatives listed, for one of my personal projects I have chosen koyeb.

To track various light novel updates and manga updates, I use a discord rss bot. This bot is written in javascript and uses the monitorss library. The bot is hosted on heroku and uses a free dyno. The bot is also connected to a mongodb database which is external from mongodb free tier.

Having two instances run at once causing a few issues, but overall with some adapation you can move your stuff from heroku to koyeb. A lot of the koyeb build steps are similar to heroku, but there are some differences. For server side applications, I think koyeb is a great alternative to heroku. For bots, you may need to hack a server together along with the bot.

```js
const fs = require('fs')
const path = require('path')
const MonitoRSS = require('monitorss')
const schedulesPath = path.join(__dirname, 'settings', 'schedules.json')
const configPath = path.join(__dirname, 'settings', 'config.bot.json')
const config = fs.existsSync(configPath) ? JSON.parse(fs.readFileSync(configPath)) : {}
const schedules = fs.existsSync(schedulesPath) ? JSON.parse(fs.readFileSync(schedulesPath)) : {}

const clientManager = new MonitoRSS.ClientManager({
  setPresence: true,
  schedules,
  config
})

const http = require('http');

// Create an instance of the http server to handle HTTP requests

// Start the server on port 3000
// delay start by 5 seconds
setTimeout(() => {
  let app = http.createServer((req, res) => {
    // Set a response type of plain text for the response
    res.writeHead(200, {'Content-Type': 'text/plain'});

    // Send back a response and end the connection
    res.end('Hello World!\n');
});
  app.listen(8080, '0.0.0.0');
}, 5000)
clientManager.start()
```

Previously heroku, had a very way to run bots on their server, with koyeb, we need a port to listen to, and a way to keep the bot alive. I have chosen to use the standard http server, and that starts 5 seconds after monitorrss is initialized.

Alternatively a basic terraform setup can be made, koyeb was recently added to terraform.

```terraform {
  required_providers {
    koyeb = {
      source = "koyeb/koyeb"
    }
  }
}
provider "koyeb" {
  #
  # Use the KOYEB_TOKEN env variable to set your Koyeb API token.
  #
}

resource "koyeb_app" "my-app" {
  name = "my_tf_app"
}
```

Overall porting content from heroku can be done with koyeb or other listed alternatives.

## References
* https://github.com/synzen/MonitoRSS
* https://blog.heroku.com/next-chapter
Getting error in react
Tags: react, errors, beginners
Published: 2022-09-03 02:51:21

ERROR in [eslint] Plugin "react" was conflicted between "package.json » eslint-config-react-app » D:\web\nearassets\frontend\node_modules\eslint-config-react-app\base.js" and "BaseConfig » D:\Web\nearassets\frontend\node_modules\eslint-config-react-app\base.js".
get this error I am not able to figuring out why this happens


Not able to figuring out why this happens
Subset vs Substring
Tags: javascript, leetcode
Published: 2022-09-03 02:17:15

## SubString
 -extracts characters, between two indices (positions), from a string, and returns the substring.

```
var theString = "abc",
  allSubstrings = [];

getAllSubstrings(theString);

function getAllSubstrings(str) {
  for (let i = 0; i < str.length; i++) {
    for (let j = i + 1; j <= str.length; j++) {
      allSubstrings.push(str.substring(i, j));
    }
  }
}

console.log(allSubstrings);
```

[ 'a', 'ab', 'abc', 'b', 'bc', 'c' ] - Please note 'ac' is not a substring.

## Subset
 -A subset MAY NOT maintain relative ordering of elements and can or cannot be a contiguous part of an array. For a set of size n, we can have (2^n) sub-sets in total.

```
var subsets = function (str) {
  let index = 0;
  let subset = [];
  let current = "";
  findSubset(index, str, subset, current);
  return subset;
};

const findSubset = (index, str, subset, current) => {
  if (index === str?.length) {
    subset.push(current);
    return;
  }

  findSubset(index + 1, str, subset, current + str.charAt(index));
  findSubset(index + 1, str, subset, current);
};

console.log(subsets("abc"));

```
[ 'a', 'ab', 'abc', 'b', 'bc', 'c' ] - Please note 'ac' & '' is subset
Input streams buffer flag clearing and emptying
Published: 2022-09-03 02:04:23

The input streams works in such as a way that it holds some particular type of when undisturbed. Particularly with C++,when you try to extract a string and an integer continuously as in getting a name and age attributes of a person together for instance, the stream doesn't react to this sudden change of type data. To be able to adjust this change of memory, you have to employ the cin.ignore() object to be able to release the buffer of the integer and open a new room for the string to be extracted. And sometimes when you incorrectly place the wrong data type into the allocated buffer, flags are raised to tell you that you've committed error. Cin.clear() is used to clear the flags so that the buffer will ignore the error you committed. The buffer will now pretend that you entered the corrected data type and allow you carry on. You can cin.ignore() to remove the incorrect entry and manipulatively allow you re-enter the right value(data type) .
We will implement more on input streams
Learn Python #7 - List operations 💡!
Tags: python, programming, tutorial, build
Published: 2022-09-03 01:06:33

💡This is a continuation of what we had learnt in our last [post](https://dev.to/nitinreddy3/learn-python-6-lets-list-it-36ok). Let us learn more about some other operations that could be performed on the python lists.

📘So today we will be covering the following list of operations:-
- Combining list
- Removing list items
- Clearing out a list
- Counting how many times an item appeared in the list
- Finding a list item's index

### Combining list
In python, combining the two lists is bit easy. Let's learn through an example...
```
list1 = ['Roger', 'Stark', 'Banner'] //List 1
list2 = ['Steve', 'Tony', 'Bruce'] //List 2

list1.extend(list2)
//['Roger', 'Stark', 'Banner', 'Steve', 'Tony', 'Bruce']
```
In the above example, list1 is extended by including the list items of list2.

### Removing list items
There are different ways in which the item can be removed from the list. Let's look at them one by one
- `remove` method
```
list1 = ['Roger', 'Stark', 'Banner']
list1.remove('Roger')
```

- `pop` method
```
list1 = ['Roger', 'Stark', 'Banner', 'Steve', 'Tony', 'Bruce']
list1.pop(0) // 'Roger' is removed from the list since the index specified is 0
// Result - ['Stark', 'Banner', 'Steve', 'Tony', 'Bruce']

list1.pop() // 'Bruce' is removed from the list as it was the last item on the list.
// Result - ['Stark', 'Banner', 'Steve', 'Tony']
```

- `del` keyword
```
list1 =  ['Roger', 'Stark', 'Banner', 'Steve', 'Tony', 'Bruce']
del list1[2]
// Result -  ['Roger', 'Stark', 'Steve', 'Tony', 'Bruce']
```

### Clearing out the list
In case you want the delete the content of the lists but not the list, you can use the `clear` method on the list.
```
list1 =  ['Roger', 'Stark', 'Banner', 'Steve', 'Tony', 'Bruce']
list1.clear()
// Result - []
```
Easy peasy isn't it?

### Counting how many times an item appeared in the list
You can also find the number of appearances of a specific item in a list. This can be achieved by using the `count` method on a list that takes an item as an argument.
```
list1 =  ['Roger', 'Stark', 'Banner', 'Roger', 'Tony', 'Bruce']
list1.count('Roger')
// Result - 2
```

### Finding a list item's index
This operation would be pretty useful when you want to find and replace an item in the list with another item.
To find an index of an item in a list, we use the `index` method.
```
list1 =  ['Roger', 'Stark', 'Banner', 'Roger', 'Tony', 'Bruce']
list1.index('Roger')
```
The catch here is that this method will return the index of the first instance of an item from the list.


## Conclusion

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

Thanks in advance for reading this article...🚀

*I am 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)
Why I Write My LINQ Queries Tall, Not Wide
Tags: programming, webdev, dotnet, csharp
Published: 2023-08-23 14:03:22

---
title: Why I Write My LINQ Queries Tall, Not Wide
published: true
date: 2022-09-03 00:00:00 UTC
tags: programming,webdev,dotnet,csharp
canonical_url: https://www.milanjovanovic.tech/blog/why-i-write-tall-linq-queries
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mpj4pghspbb7qszsu6fz.png
---

## Wishing You a Warm Welcome

First, I want to welcome you to the first edition of **Milan's .NET Weekly** newsletter.

I hope that this newsletter can become a positive force in the .NET community. To bring many of us together so that we can all continue learning and improving.

With that out of the way, let's get into .NET!

## The Problem With Wide LINQ

Let's consider the following LINQ expression from a code style perspective.

I call this a wide LINQ expression, because it stretches horizontally across the entire screen.

```csharp
dbContext.Animals.Where(animal => animal.HasBigEars)
    .OrderBy(animal => animal.IsDangerous).Select(
        animal => (animal.Id, animal.Name)).ToList();
```

- It is difficult to read.
- It is difficult to reason about.
- It is difficult to extend or maintain.

To improve this, I created a simple rule that you can follow:

> When writing LINQ, try to go tall, not wide.

## How to Write Tall LINQ

So how do we write tall LINQ expressions?

I'm going to rewrite the previous expression, to improve it.

Try to follow the _one dot per line rule_:

```csharp
dbContext
    .Animals
    .Where(animal => animal.HasBigEars)
    .OrderBy(animal => animal.IsDangerous)
    .Select(animal => (animal.Id, animal.Name))
    .ToList();
```

Is the new version easier to read? **Yes** , very much so.

It is easier to understand what each expression does, and how it feeds into the next one in the chain.

If you are working in a team, try to propose this as a coding standard (if it isn't one already).  
You will see that over time this will make a noticeable difference.

* * *

**P.S. Whenever you're ready, there are 2 ways I can help you:**

1. [**Pragmatic Clean Architecture:**](https://www.milanjovanovic.tech/pragmatic-clean-architecture?utm_source=dev.to&utm_medium=website&utm_campaign=cross-posting) This comprehensive course will teach you the system I use to ship production-ready applications using Clean Architecture. Learn how to apply the best practices of modern software architecture. [**Join 950+ students here.**](https://www.milanjovanovic.tech/pragmatic-clean-architecture?utm_source=dev.to&utm_medium=website&utm_campaign=cross-posting)

2. [**Patreon Community:**](https://www.patreon.com/milanjovanovic) Think like a senior software engineer with **access to the source code** I use in my YouTube videos and **exclusive discounts** for my courses. [**Join 820+ engineers here.**](https://www.patreon.com/milanjovanovic)