teleren/devto huggingface dataset:
How to create a new Thread in java ?
Tags: java, learning, tutorial, thread
Published: 2021-08-03 15:02:23

We are going to explore different ways to start a thread & execute parallel tasks.

This is very useful, in particular when dealing with the long or recurring operations that can't run on the main thread or where the UI interaction can't be put on hold while waiting for results or response.

**Running a Thread**

1. **By Extending the Thread class**

Define the task class which will perform a task on different thread. The class should **extends** Thread class & override the **run method** to define the task to execute on a separate thread.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lajoyvdbe1siknboiuy6.png)

And now we write a second class to initialize and start our thread:

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/936aep6c1xveersdeapj.png)

We should call the start() method on threads in the NEW state (the equivalent of not started). Otherwise, Java will throw an instance of IllegalThreadStateException exception. 

The output will be :
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5aqjwi55dju1fxkzftnc.png)

Now, let us assume you want to start multiple threads:

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7plgz5xrr3z5yga66k2i.png)

The output will be :
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xgtf6x0v2pnjjguhmw8t.png)

2. **Implementing the Runnable Interface**

Define a class which will implements the Runnable Interface. The Runnable interface is also a functional interface, which has only 1 method i.e run.


![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9w5hjhk8ojdu8vigdk7e.png)

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j1alp9ef4il45syx5vb3.png)

The output will be:
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rkrq018bxdd0veyf2iuv.png)  

If you are not extending the Thread class,your class object would not be treated as a thread object.So you need to explicitely create Thread class object.We are passing the object of your class that implements Runnable so that your class run() method may execute.

Thanks :)


keep-learning :)
How fast can one learn JavaScript?
Tags: javascript
Published: 2021-08-03 14:45:12

Hi, Coders!
How much time did it take to learn JS? I know a little Python, HTML, CSS, and just starting to learn JS.
Also, is the pro plan at [Codecademy Learn JavaScript](https://www.codecademy.com/learn/introduction-to-javascript) to gain the "Mobile Practice" worth it?
API timeout when accessToken expire and passport.js fetch new access token
Tags: node, proxy, expressrequestproxy, passportjs
Published: 2021-08-03 14:43:08

I have a implementation where express-request-proxy is within  adapter.authenticate('main', { session: true }, function(err, user) {//here I have express-request-proxy}
Access_token_expiry is set to 5 mins and sso_Idle_max is set to 30 mins in IDP.
Once you login all call get proxy via authenticate('main') method. this works fine between 1-4 mins of session as during this time authenticate method approve the requst using cache but the moment the time reaches to 5 mins or 5+ the autheticate('main') method goes to IDP to get a new access_token. the token is received but express-request-proxy gets timeout error.

Any recomendation on this ? Is there any issues with using express-request-proxy inside authenticate('main') ?

Appreciate your help in advance
O que é View Composer?
Tags: laravel, php, backend, codequality
Published: 2021-08-03 14:33:22

View Composer é uma solução elegante para um problema muito específico! Todo desenvolvedor provavelmente já se deparou com uma Exceção de variável indefinida ao chamar uma view. Isso é simples de resolver, foi você que esqueceu de buscar essa informação no seu controller para enviar. 
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/92z2lo6heckaeijdm5nu.png)
 
Usando o View Composer, não há mais essa necessidade de ficar se preocupando com os dados do seu arquivo de visualização, pois esse recurso irá garantir que todas as informações estarão lá sempre que a sua view seja renderizada.

## View Composer na Prática

Primeiro começo organizando o diretório de onde ficarão os arquivos que é em `app/Http/View/Composers` é o que recomenda a [documentação do Laravel](https://laravel.com/docs/8.x/views#view-composers) mas você pode ficar a vontade para modificar. 
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/spppn1livetstsbslhpn.png)
 
### Classe de View Composer
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gc057mthd9b101p1f0eg.png)
Dentro dessa classe você pode usar quaquer dependência que precise. Nesse exemplo estou dizendo para o framework que a variável `users` irá receber o valor dessa consulta `User::with('role')->withTrashed()->paginate(10)` . Todas as definições de variáveis ficarão nessa função `compose`. 

### Criando um Service Provider

Para registrar os seus View Composers, iremos precisar [criar um Service Providers](https://laravel.com/docs/8.x/providers)
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f6i0dycy4wavvaa2cie3.png)
Esse é um exemplo do meu `ViewServiceProvider`. Observe que no método `register`eu especifico o diretório de onde os meus arquivos de visualização estão localizados. Não esqueça de registrar o seu Service Provider no array de `'providers'` em   `config/app.php`.

Veja que no `registerComposers` é onde defino exatamente os arquivos que aquele View Composer que acabamos de criar irá aparecer.
```
View::composer([
            'users.index',
            'users.create',
            'users.edit',
        ], UserViewComposer::class);
```
Nesse trecho estou informando que toda as variáveis definidas no `UserViewComposer` irão aparecer sempre que forem renderizadas as views de `index`,`create` e `edit` do usuário. 

### Vantagens
<ol>
<li> O primeiro ponto que destaco é organização, pois todas as variáveis e dados serão tratados em um arquivo específico do seu projeto.  </li>
<li> Outro benefício é a "limpeza" que você irá causar nos seus controllers, pois não há necessidade de ficar passando dados por ele</li>
<li>Gatantia que sempre uma view for renderizada, todos os dados que ela precisa estarão disponíveis</li>
</ol>

## Conclusão
É isso galera, espero que tenham gostado desse recurso  que ajuda muito a organizar o seu projeto e também melhorar a manutenção do código. Gostou? deixa um comentário ai :smiley: .
What can you do while your car drives itself?
Tags: autonomousdriving, automotive, adas, ads
Published: 2021-08-03 14:27:16

Autonomous driving is still not widely accepted. It is plausible, however, due to the increasing complexity of [software development](https://arobs.com). Autonomy will make mobility safer and will fundamentally change the way we drive and engineer cars. This technology will allow drivers to have stress-free, focused, and valuable time. What would people do with all that time?
Modern society seems to be lacking something- time. Time is glorified as money. We imagine all the things that we could do if we had more time. Autonomous driving will provide some extra time for the driver as we are getting closer to the future of [automotive engineering](https://arobs.com/automotive-engineering/).
What to do with it?

**Levels of autonomy**
The majority of modern cars currently on the roads are autonomous to some degree. We are not yet ready to fully autonomous vehicles, which correspond to the fifth level of autonomy.
Here is a quick summary of the fifth level of autonomy:
•	Level 0 - there is no automation in the car, and the human is totally responsible for the driving.
•	Level 1 - An advanced driver assistance (ADAS) system can operate steering or brake/acceleration.
•	Level 2 - the ADAS in the car can control the steering, the brake, and the acceleration.
•	Level 3 - The vehicle's ADS can perform all aspects, but only in certain circumstances. It is necessary that the human monitors the driving process and is available to take control at any time. Modern vehicles already have this level of driver assistance.
•	Level 4 - The ADS can drive and monitor all aspects of driving under certain conditions. This level is highly autonomous, and the driver doesn't have to pay attention to driving or the surrounding circumstances.
•	Level 5 - The ADS can handle all aspects of driving regardless of the conditions. This level allows the human driver to travel while sleeping.
According to [**NHTSA**](https://www.nhtsa.gov/technology-innovation/automated-vehicles-safety), we have now reached level 3 autonomy. This fact means that the vehicle can have Partially Automated Safety features, Lane-keeping Assist, Traffic jam assistance, Lane-keeping aid, and even Self-parking.
What would people do with the free time enabled by fully automated vehicles?
 
Recent research by **GenPop/Ipsos** shows that most people will continue to pay attention to the road. The majority of European car owners were surveyed and said they would pay the most attention to the road and communicate with others. Only a small percentage of respondents said they would either take a break, relax or work during this plus time.
The results are similar in North America and Asia. These results show that drivers still don't trust the idea of fully autonomous driving.
Even if the widespread adoption of completely autonomous driving is yet to come, certain automated aspects are already facilitating driving for millions of drivers.
tmux attach
Tags: cli, linux, tmux
Published: 2021-08-03 14:27:15

---
tags: ['cli', 'linux', 'tmux',]
series: tmux
title: tmux attach
canonical_url: https://waylonwalker.com/tmux-attach/
published: true
---

attach is one of the most useful features of tmux. If you have no interest in tmux for pane and window management, you should use tmux for this. It can be a life saver if you ever get disconnected from the host machine or accidently close your terminal you can connect right back into the session you were just in using attach.

## attach

```
tmux attach
```

this command will simply attach back to tmux if you are ever disconnected

If you ever run long running tasks on a remote machine by sshing into this you should be doing it inside tmux, or something like tmux so that you do not loose your work.

## attach to a specific session

If you have multiple sessions running you can select the session that you want to attach to by passing -t <name-of-session> .

``` bash
tmux attach -t scratch
```

Be sure to check out the full YouTube playlist and subscribe if you like it.

[![tmux playlist on youtub](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v4cgo76y53s1hwykajo1.png)](https://www.youtube.com/playlist?list=PLTRNG6WIHETB4reAxbWza3CZeP9KL6Bkr)

{% post https://dev.to/waylonwalker/how-i-navigate-tmux-in-2021-2ina %}

> Also check out this long form post for more about how I use tmux.
Types of Machine Learning: Time Series Analysis
Tags: article
Published: 2021-08-03 19:05:13

---
title: Types of Machine Learning: Time Series Analysis
published: true
date: 2021-08-03 14:10:54 UTC
tags: Article
canonical_url: https://reinforcement-learning4.fun/2021/08/03/types-of-machine-learning-time-series-analysis/
---

The typical regression task predicts the value of a target variable based on the values of one or more feature variables.

For example, to predict the price of a house based on its characteristics like size, number of rooms, etc. But in some cases, we want to predict the value of a variable based on … [Continue reading Types of Machine Learning: Time Series Analysis →](https://reinforcement-learning4.fun/2021/08/03/types-of-machine-learning-time-series-analysis/)
Accessing dictionaries in python for beginners
Tags: python, beginners, programming, functional
Published: 2021-08-03 13:53:50

>Parameter Details

>key = The desired key to lookup
>value = The value to set or return

------




###What exactly is a dictionary?
>A real-life dictionary holds words and their meanings. As you can imagine, likewise, a Python dictionary holds key-value pairs. Also to be noted that they are Unordered and mutable.

***


####How to create one ?
```python
mydict = {}                #Empty dictionary
mydict = {'key' : 'value'} #Initialized dictionary
person = {'name':'xyz', 'age':23}
```


####Built in Function for creating a dictionary: dict()
```python

myperson = dict() #empty dictionary
myperson = dict(name="xyz", age=23) #here we have given value to dict function

# while using dict function we dont need quotes or colons. 
```

####Modifying a dictionary 
```python
myperson = dict(name="xyz", age=23) #creating a dict

myperson["email"] = "xyz@gmail.com" #adding email as key and its value to dict

```

#####Adding list to a dictionary
```python
myperson['new_list'] = [1, 2, 3] #adding new_list as key and [1,2,3] as value
```
#####Adding Dictionary to a dictionary
```python
myperson['new_dict'] = {'nested_dict': 1} #new_dict is the key and {'nested_dict': 1} is the value
```

#####To delete an item, delete the key from the dictionary
```python
del myperson['email'] #here key is deleted
```

____

####Iterating Over a Dictionary
>Yes, we can iterate over dictionary. Such structures on which we can iterate are called ITERABLE and things which iterates, like 'i' in for loop, that 'i' is called ITERATOR(abstract explanation).

```python
myperson = {'name':'xyz', 'age':23}

for key in myperson:
    print(key, myperson[key],sep=" : ")

# key is iterated , so key is iterator here

```

#####The items() method can be used to loop over both the key and value simultaneously
```python
myperson = {'name':'xyz', 'age':23}

for key,values in myperson.items():
    print(key,values)
    
```

#####While the values() method can be used to iterate over only the values

```python
myperson = {'name':'xyz', 'age':23}

for values in myperson.values():
    print(values)
    
```


####Soon.
I created a SpaceX tracker with React
Tags: javascript
Published: 2021-08-03 13:49:03

Hey fellow React dev/spaceX fan,

https://tsensei.github.io/spaceXtale/

This webapp contains a countdown timer for latest launch, all info about past and upcoming launches and detailed info about rockets and starlink satellites.

No external librarys were used except for react-router-dom, everything is coded from the ground up. Any review or constructive criticism would be appreciated.
🧩 A Complete Guide to Lombok
Tags: lombok, java, programming
Published: 2021-08-03 13:39:23

#### 📚 Let’s see everything you should know to start using Project #Lombok. We will have a look at how to integrate it into your #IDE and use it to avoid boilerplate code.

### <br>
Java is a great but verbose language. You may be ending up writing many lines of code even to achieve the most common goals. Plus, it definitely involves repetitive code, like getters and setters. This leads to a huge amount of boilerplate and avoidable code. Not only does this add nothing to the business logic of your application, but writing it is an unnecessarily boring and time-consuming process. This is why you should start employing tools and libraries to make you more productive by avoiding this. That’s where Lombok comes into play!

This Java library provides you with several annotations aimed at avoiding writing Java code known to be repetitive and/or boilerplate. Project Lombok works by plugging into your build process. Then, it will auto-generate the Java bytecode into your *.class* files required to implement the desired behavior, based on the annotations you used. Thus, each annotation offered by Project Lombok allows you to skip writing methods and logic you would like to avoid, like constructors, equals, and hash code functions. This will save you a lot of time and let you focus on the business logic of your project. Plus, you will be able to keep your codebase smaller, cleaner, and easier to be read and maintained.

First, we will see what Project Lombok is and how it works. Then, we will study the most common and relevant Lombok’s annotations, understanding what the most important ones are, where, and how to use them. Next, it will be time to see how to integrate it in your IDE ([Integrated Development Environment](https://en.wikipedia.org/wiki/Integrated_development_environment)) and why you should not be afraid of using it.

## Prerequisites

This is the list of all the prerequisites to replicate the examples that will be shown next:

* Java >= 1.8
* Gradle >= 4.x or Maven 3.6.x
* Project Lombok >= 1.18.20

## What is Lombok

[Project Lombok](https://projectlombok.org/) (from now on, *Lombok*) is an annotation-based Java library that allows you to reduce boilerplate code. Lombok offers various annotations aimed at replacing Java code that is well known for being boilerplate, repetitive, or tedious to write. For example, by using Lombok, you can avoid writing constructors with no arguments, `toString()`, `equals()`, and `hashCode()` methods by simply adding a few annotations. The magic happens during the compile-time when the library injects the bytecode representing the desired and boilerplate code into your *.class* files. Plus, as we will see, the library can be plugged into your IDE, letting you have the same experience as if you had written all the boilerplate code yourself.


[Read more...](https://auth0.com/blog/a-complete-guide-to-lombok/?utm_source=content_synd&utm_medium=sc&utm_campaign=java)
Fart.js- The end of the world
Tags: javascript, adventofcode, discuss, webdev
Published: 2021-08-03 13:37:10

We all know there are hundreds of thousands of javascript frameworks and they are never going to stop releasing. But I found something interesting but at the same I want to ask:

![Why](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bttcf0304ljb2c2jcu9i.gif)

I came across this library few days ago. It make so easy to add fart noises to your website (but who wants to do that). I thought due to lock down many peoples are at home creating this type of thing and I found this:

![JS fart github](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2jaxsqpzd3ljgo572ctz.png)

I was actually released 7 years ago, and last commit was 4 years ago(they kicked out jQuery from their dependencies). Currently it has 51 Star and 13 Forks on [Github](https://github.com/74656c/fart.js/).

![JSFart home page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e0l46ntrqm4xgp2i3av1.png)

You can get more detailed documentation on [jsfart.com](http://jsfart.com).

Here are some examples available to fart 😂.
![Examples of jsfart](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0cgtfpveimllm4tuwpl0.png)

Overall, I'm not spreading hate against this. But I want to ask again:

![Why](https://i.giphy.com/media/UnRIwArJhtZUfindRs/giphy.webp)
In what order does Jest execute tests anyway? (And how to change it!)
Tags: javascript, node, testing
Published: 2021-08-03 12:34:18

Jest will execute different test files potentially in parallel, potentially in a different order from run to run. Per file, [it will run all describe blocks first and then run tests in sequence, in the order it encountered them while executing the describe blocks](https://jestjs.io/docs/setup-teardown#order-of-execution-of-describe-and-test-blocks).

Here's an illustration of that per file behavior, copied straight out of the doc link above:

```javascript
describe('outer', () => {
  console.log('describe outer-a');

  describe('describe inner 1', () => {
    console.log('describe inner 1');
    test('test 1', () => {
      console.log('test for describe inner 1');
      expect(true).toEqual(true);
    });
  });

  console.log('describe outer-b');

  test('test 1', () => {
    console.log('test for describe outer');
    expect(true).toEqual(true);
  });

  describe('describe inner 2', () => {
    console.log('describe inner 2');
    test('test for describe inner 2', () => {
      console.log('test for describe inner 2');
      expect(false).toEqual(false);
    });
  });

  console.log('describe outer-c');
});

// describe outer-a
// describe inner 1
// describe outer-b
// describe inner 2
// describe outer-c
// test for describe inner 1
// test for describe outer
// test for describe inner 2
```

If you want to run files in sequence as well, run Jest with the `--runInBand` command line flag. (`-i` does the same thing.) Doing this, the scheduler might still run them in a different _order_ from run to run. To prevent this as well, [you will need to define your own test sequencer](https://jestjs.io/docs/configuration#testsequencer-string). 

To sort test files alphabetically for example, create a file with the following contents:

```javascript
// testSequencer.js
const Sequencer = require('@jest/test-sequencer').default;

class CustomSequencer extends Sequencer {
  sort(tests) {
    // Test structure information
    // https://github.com/facebook/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21
    const copyTests = Array.from(tests);
    return copyTests.sort((testA, testB) => (testA.path > testB.path ? 1 : -1));
  }
}

module.exports = CustomSequencer;
```

Then, set the following in your Jest config:

```
// jest.config.js
{
  "testSequencer": "path/to/testSequencer.js"
}
```
Octopod Episode 2 -- Open Source: It's Everywhere with Chris Aniszczyk
Tags: opensource, podcast, beginners, cloudnative
Published: 2021-08-03 13:20:03


[Octopod Episode 2: Open Source -- It's Everywhere with Chris Aniszczcyk](https://www.buzzsprout.com/1819621/episodes/8940785)

{% spotify spotify:episode:6NcfRJX6TfS6aEShSzosm6 %}



These days, open source has become pervasive across every aspect of our lives. From your refrigerator to your TV to your phone, almost everything you’re using incorporates some aspect of open source software. 

In episode two, we welcome Chris Aniszczyk to the show. Chris is an open source technologist with a passion for building a better world through open collaboration. He's currently a CTO at the Linux Foundation where he focuses on developer relations and running the Open Container Initiative and the Cloud Native Computing Foundation. He’s also a partner at Capital Factory, where he focuses on mentoring, advising, and investing in open source and infrastructure-focused startups. Chris’s CV also includes creating Twitter’s open source program and serving on the Eclipse Foundation Board. Today we discuss how open source became as pervasive as it is today and how it has changed over time. We talk about which types of companies or areas open source has not yet permeated and why, as well as the vast benefits of open source program offices. 



To hear more about the value of open source and the importance of keeping the ‘open’ in ‘open source’, tune in today!



Please subscribe and tell your friends. You can find the OCTOpod on all the major podcast platforms!



##Listen to The OCTOpod: Conversations with SUSE's office of the CTO.##


Listen to the OCTOpod here or subscribe on your favorite podcast platform! And please share it with your friends! Learn more at [community.suse.com](https://community.suse.com).