teleren/devto huggingface dataset:
Mutable and Immutable in Python
Tags: python, programming, beginners, 100daysofcode
Published: 2022-10-20 23:41:07

In Python there are 2 types of objects. 

**_Mutable objects_ & _Immutable_ objects**

Every object that is created is given a number that uniquely identifies it. The type of the object is defined at runtime and cannot be changed afterwards unless if the object is mutable, then that means that the state can be modified even after it is defined. 

**Mutable Objects**
_A Mutable object can be altered._

- Lists
- Sets
- Dictionaries

**Immutable Objects**
_Immutable objects cannot be altered after its been initially defined._

- Numbers (int,float,bool,ect..)
- Strings
- Tuples
- Frozen sets

Lets see what happens when we try to alter an immutable object. 

Here's the scenario: A company hired a new employee and needs to add them to the employee database. 

```python
first_name = 'Jane'
last_name = 'Soe'
```
UH OH! It looks like in the process of adding this new employee there was a typo! Instead of "Jane Doe" they put "Jane Soe". Because strings are immutable we can't just change an individual character. But lets give it a try. 
```python
first_name = 'Jane'
last_name = 'Soe'
last_name[0] = 'D'
```
This is what we would get in the terminal
```
last_name[0] = 'D'
TypeError: 'str' object does not support item assignment
```
Now... there's a way around this. 
We can concatenate the string "D" with a slice of the `last_name` to fix this typo. 
```python
fix_typo = 'D' + last_name[1:]
```
What is Go?
Tags: go, devops, beginners
Published: 2022-10-20 23:38:46

Go is a general-purpose language designed with systems programming in mind. It was initially developed at Google in year 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. It is strongly and statically typed, provides inbuilt support for garbage collection and supports concurrent programming. Programs are constructed using packages, for efficient management of dependencies. Go programming implementations use a traditional compile and link model to generate executable binaries.

Go provides type safety, garbage collection, dynamic-typing capability, many advanced built-in types such as variable length arrays and key-value maps etc.

- Go is modern, fast and comes with a powerful standard library.
- Go has built-in concurrency.
- Go uses interfaces as the building blocks of code reusability.

```
package main  
import "fmt"  
func main() {  
   fmt.Println("Hello, World")  
}  

```

![https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oy0nfxqm8mzboi5m12q1.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oy0nfxqm8mzboi5m12q1.png)
Dot products, cosine similarity, text vectors
Published: 2022-10-20 22:39:51

Cosine similarity is a measure between two single dimensional vectors that gives us a value ranging 0-1 to inform of the similarity between the vectors. The formula is below:

```
Cosine Similarity = (A . B) / (||A||.||B||) 
```

Where (A . B) is the dot product between vector A and B. A dot product is the sum of the element-by-element product between A and B. For example,

```
A = [1, 2, 3]
B = [4, 5, 6]


A . B
>> 32
# (1 * 4) + (2 * 5) + (3 * 6) = 32
```

Meanwhile, `||A||` is the notation used to denote the L2 Norm of a vector. The L2 norm is a method to calculate the length of a vector in Euclidean space. Think of this as the length of a vector of length N as a "line" if the vector was drawn out on a N-dimensional graph. You sum the squares of the values in each dimension, and take the square root of the sum.

```
A = [1, 2, 3]

norm(A)

>> 3.7416573
# (1^2 + 2^2 + 3^2)^0.5 = 3.7416573
```

Numpy has a bunch of helpers so we don't need to run all of these calculations manually:

```
import numpy as np
from numpy.linalg import norm
 
# define two lists or array
A = np.array([1,2,3,4])
B = np.array([1,2,3,5])

# cosine similarity
cosine = np.dot(A, B) / (norm(A) * norm(B))
print("cosine similarity:", cosine)

>> 0.9939990885479664
```
A cosine similarity score near 1 means the vectors are very close to one another if they were projected. 0 means they are very dissimilar.
New Feature: Test Any Node in Steem API Node Status
Tags: steem, blockchain
Published: 2022-10-20 22:39:21

Now, we can test any Steem API Node in [Steem RPC Node Testing Tool](https://steemyy.com/node-status.php)

![image.png](https://cdn.steemitimages.com/DQmQtiQW4YgBLcX5CBGmuyiA3gqMNtYbv7YHawBeAAm9xSG/image.png)

The ping speed is measured from your browser. Some node may show some problems/errors and here are some common reasons:
1. HTTPS certificates expired/invalid.
2. CORS
3. Jussi configure error.
4. Unable to Connect (5xx errors)

If you see Version and Latest Jussi Number, it usually means the node is good.

![steem](https://justyy.com/png/whale.png)

<hr/>

Follow me at [https://steemyy.com](https://steemyy.com)
And, don't forget, you can swap your STEEM to USDT (TRC-20) via [Super Easy/Handy Service to Convert your STEEM or SBD to USDT (TRC-20)](https://steemyy.com/steem2usdt.php)
Quotes App
Tags: angular, rxjs, typescript, showdev
Published: 2022-10-20 22:18:22

I developed a Quotes application using Angular, RxJS, TypeScript, and the Quotable API. Feel free to learn from it and/or provide feedback. Thanks!

## Features

- Random quote on home page which can be refreshed to get another.
- Search quotes by author and tag.
- Clicking an author or tag will search for quotes with that author or tag.
- View more information about an author.

## Getting Started

1. Clone the repo:
  `git clone https://github.com/nightwolfdev/quotes.git`
2. Navigate to the project folder:  
  `cd quotes`
3. Install dependencies:  
  `npm install`
4. Run the app:  
  `ng serve`
5. Visit the app in a browser:  
  `http://localhost:4200`

## Links

* [Demo](https://nightwolf.dev/demos/quotes)
* [GitHub Repo](https://github.com/nightwolfdev/quotes)
* [Angular](https://angular.io)
* [RxJS](https://rxjs.dev)
* [TypeScript](https://www.typescriptlang.org)
* [Quotable API](https://github.com/lukePeavey/quotable)
Friendly IDs for Ruby on Rails
Tags: rails
Published: 2022-10-20 22:08:15

Do you have URLs like `/books/1` or `/secret_things/10` and wish that they were friendlier? Also, wish the IDs were sequential and guessable?

I like Stripe's URLs, such as `https://dashboard.stripe.com/test/products/prod_MG5m4q7sKvGto8`. If I see the ID value `prod_MG5m4q7sKvGto8` anywhere I know it belongs to a Stripe Product. `cus_MG5sTiccdSlpjw`? A Stripe Customer ID. Very friendly.

And the IDs are not sequential. Friendly and random. I want this.

I'm going to show you the project I use for friendly IDs, and how I add them to my Rails scaffolding generators so they are automatically enabled for every model.

```
rails generate scaffold Book title description:text
```

And my URLs automatically pop out looking like `/books/book_qYlVPJvDprRabHa0wy1xz3n9`.

A quick tweak of the generated class and they might become even nicer, `/books/bk_qYlVPJvDprRabHa0wy1xz3n9`.

Yeah, you want this too.

## prefixed_ids gem

The magic is provided by Chris Oliver's [prefixed_ids](https://github.com/excid3/prefixed_ids) rubygem.

The only requirement is that your models' `id` column is `bigint` or some other integer. I was not successful using the gem with `uuid` columns. But you won't need UUID IDs because you'll have publicly friendly, random IDs, and internally sequential IDs.

```
bundle add prefixed_ids
```

## Trying it out

Before we go and edit your scaffold generators, let's try it out on an existing model.

Add `has_prefix_id :thing` to one of your models, and go and view it in your app.

```ruby
class Book
  has_prefix_id :bk
```

Your boring IDs now look gloriously friendly, `/books/bk_x912t423`.

The gem hijacks the `find` and `to_param` methods. Everything just works.

## Adding it to your model generator

You definitely want friendly IDs for all your future models. That is, when you run either:

```
rails g model Book title
rails g scaffold Book title
```

You want the resulting `app/models/book.rb` to include the `has_prefix_id :bk` link from above.

First, copy the current Rails [`model.rb.tt` template](https://github.com/rails/rails/blob/main/activerecord/lib/rails/generators/active_record/model/templates/model.rb.tt) into your app.

If you're using Jumpstart Pro, you can skip this step.

```
mkdir -p lib/templates/active_record/model
curl https://raw.githubusercontent.com/rails/rails/main/activerecord/lib/rails/generators/active_record/model/templates/model.rb.tt \
  -o lib/templates/active_record/model/model.rb.tt
```

This file will be used to generate all your future model class files.

In the newly created `model.rb.tt` file, add the 3rd line:

```
<% module_namespacing do -%>
class <%= class_name %> < <%= parent_class_name.classify %>
  has_prefix_id :<%= singular_name %>
```

If you were to generate a `Book` model, it would look like:

```ruby
class Book
  has_prefix_id :book
end
```

You can edit `:book` to `:bk`. Pick an abbreviation that resonates with your URL-appreciating customers.

Show them you care.
Day 640 : Risk
Tags: hiphop, code, coding, lifelongdev
Published: 2022-10-20 21:47:12

_liner notes_:
- Professional : 6 hours of back to back meetings, a brown bag session and holding a workshop. I'm tired. Just got to record this talk and I'm done. I'm thinking I have too many slides and will need to cut it down. Since I gave a workshop for the same event, I can probably cut out the stuff from the talk that I covered in the workshop. Which means I'll need to edit the script I wrote. Wish me luck. I knew the risk when I took the job. haha

- Personal : Only thing I remember from last night was finishing up the script for my talk. I think I also played around with the layout for my new side project.

![Looking out for a cave in Ilhéu De Baixo, Portugal in to the ocean with a large rock formation coming out of the ocean at sunset](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o0qqlu30fdaaz1d9rbzu.png)

Going to record this video because this is the last chance I can do it, haha. Then I'm going to watch some anime, maybe check out some tracks for the radio show and go to bed.

Have a great night!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube uBGsBxHPW78 %}
Cookies and Sessions
Published: 2022-10-20 21:20:31

Since cookies are such an important part of most web applications, Rails has excellent support for cookies and sessions baked in. Unfortunately for us, when you create a new application in API mode with rails new appname --api, the code needed for working with sessions and cookies in the controller is excluded by default.

To add session and cookie support back in, we need to update our application's configuration in the config/application.rb file:

```
# config/application.rb
module MyApp
  class Application < Rails::Application
    config.load_defaults 6.1
    # This is set in apps generated with the --api flag, and removes session/cookie middleware
    config.api_only = true

    # Must add these lines!
    # Adding back cookies and session middleware
    config.middleware.use ActionDispatch::Cookies
    config.middleware.use ActionDispatch::Session::CookieStore

    # Use SameSite=Strict for all cookies to help protect against CSRF
    config.action_dispatch.cookies_same_site_protection = :strict
  end
end
```
This will add in the necessary middlewareLinks to an external site. for working with sessions and cookies in our application.

To access the cookies hash in our controllers, we also need to include the ActionController::Cookies module in our ApplicationController:

```
# app/controllers/application_controller.rb
class ApplicationController < ActionController::API
  include ActionController::Cookies
end
```
tão rápido quanto um celeron 🐌
Tags: braziliandevs, newsletter, news, writing
Published: 2022-10-20 21:18:22

Fala, Dev!

Estamos de volta com mais uma edição da **EZ._pills_** 💊, uma newsletter em cápsulas de conteúdos para devs.

Você sabia que o primeiro microprocessador do mundo foi criado a mais de 50 anos atrás? 🤔

---

### ANPD quer criar concurso para 213 servidores
Após a Autoridade Nacional de Proteção de Dados ser transformada em autarquia independente pelo Congresso Nacional, houve uma necessidade maior de força de trabalho. A equipe atual conta com 99 pessoas (sendo 19 terceirizados), porém Waldemar Gonçalves, presidente da autoridade, afirma que a extensão do país e quantidade de indivíduos faz necessária um aumento de mão de obra. A notícia pode ser lida no [Convergência Digital🔗](https://www.convergenciadigital.com.br/Governo/Transformada-em-autarquia%2C-ANPD-quer-concurso-para-213-servidores-61745.html).

### Microsoft melhora experiência do Windows Update no Windows 11
A última build de preview melhora o gerenciamento de atualizações por parte dos administradores de TI e corrige diversos problemas que levavam a aplicativos "crashando". A maioria das mudanças foi feita no Update Stack Orchestrator, deixando inclusive com que administradores escolham manualmente os dias e horários para as atualizações. A notícia pode ser lida no [Bleeping Computer🔗](https://www.bleepingcomputer.com/news/microsoft/microsoft-improves-the-windows-update-experience-in-windows-11/).

### Pesquisa indica que geração Z não se importa tanto com cybersegurança no trabalho
A empresa EY entrevistou aproximadamente 1000 funcionários para a pesquisa, onde 83% dos entrevistados informaram estarem cientes dos protocolos de segurança. Apesar disso, os funcionários da geração Z se mostraram mais propensos a reciclar senhas, aceitar quaisquer cookies e outras práticas consideradas inseguras, talvez por estarem mais confortáveis com tecnologia. A notícia pode ser lida no [Tech Radar🔗](https://www.techradar.com/news/younger-workers-dont-care-about-workplace-cybersecurity).

### Firefox 106 dá grande salto em seu visualizador de PDFs
O gerenciador de PDFs do Firefox é baseado em JavaScript e já tem recebido muita atenção desde 2021, quando começou a abrir PDFs de preenchimento de formulário de forma nativa. As mudanças agora trarão mais features, como anotações, desenhos e assinaturas diretamente no browser, trazendo o Firefox como um "concorrente" mais próximo do Adobe Acrobat. As implementações podem ser lidas nas [release notes do Firefox🔗](https://www.mozilla.org/en-US/firefox/106.0/releasenotes/).

### FreeBSD chega ao Hypervisor lightweight da AWS
O "herói da comunidade AWS" Colin Percival foi o responsável pelo suporte ao SO no Amazon EC². Agora, ele anunciou que o FreeBSD também suportará outra plataforma: o Amazon Firecracker hypervisor, tendo elementos derivados do crosvm baseado em Rust do Google ChromeOS. A notícia pode ser lida no [The Register🔗](https://www.theregister.com/2022/10/19/freebsd_comes_to_amazons_lightweight/).

---

E assim nós finalizamos mais uma edição da sua dose semanal de pílulas de conteúdo! 💙
SparrowCI Pipelines - super fun and flexible CICD pipelines
Tags: cicd, raku, python, ruby
Published: 2022-10-20 20:54:12

---
title: SparrowCI Pipelines - super fun and flexible CICD pipelines
published: true
description: How to create build pipelines using SparrowCI pipelines
tags: cicd, raku, python, ruby
cover_image: https://raw.githubusercontent.com/melezhik/images/master/Screen%20Shot%202022-10-20%20at%203.52.19%20PM.png
# Use a ratio of 100:42 for best results.
# published_at: 2022-10-20 20:26 +0000
---

---

# Simple and fun

[SparrowCI](https://ci.sparrowhub.io) is super fun and flexible free service allow to build CICD pipelines.

SparrowCI exposes YAML DSL that allow to build projects for different languages including Raku, Python, Ruby, GoLang or just a make based projects.

The killer feature of SparrowCI pipelines is that they could be extended by many languages with the idea of repeatable executable tasks in the core:


```yaml
- 
  tasks:
    -
      name: main-task
      language: Python
      default: true
      code: |
        print("hello from Python")
      depends:
        - 
          name: install-python
    -
      name: install-python
      language: Bash
      code: |
       sudo apk apk add --no-cache python3 py3-pip          
```

In this simple example task "main-task” would execute some Python, to make it sure we have a Python in runtime, dependency task "install-python" is executed. That's simple!

This example illustrates the core idea behind SparrowCI pipeline - to have a **collection of dependent tasks** (DAG) that executed in **particular order**.
 
---

## More

Or course SparrowCI allows more than this simple example, follow the [documentation](https://github.com/melezhik/SparrowCI) to know more.


---

## Popular languages support

The service is still on progress, however many typical build scenarios for [popular programming languages](https://github.com/melezhik/SparrowCI/tree/main/examples) are already tested and work.

---


## Docker environments

Build scenarios are executed in ephemeral docker containers under Alpine OS.

---

## Plugins

SparrowCI pipeline could take a benefits in using a numerous plugins from [SparrowHub](https://sparrwhub.io). Typical plugins would install MySQL/PgSQL database or setup Python/Raku environment. New plugins are easily created by using many modern languages, using [Sparrow plugins API](https://github.com/melezhik/Sparrow6/blob/master/documentation/development.md).

---

## Conclusion

I'd appreciate a feedback and ideas on how people could use such a service.
Do commit dates on GitHub matter for job applications?
Tags: anonymous, discuss, github
Published: 2022-10-20 20:50:44

_This is an anonymous post sent in by a member who does not want their name disclosed. Please be thoughtful with your responses, as these are usually tough posts to write. Email sloan@dev.to if you'd like to leave an anonymous comment or if you want to ask your own anonymous question._ 

***

I've recently decided to get back on the job hunt after a 2 year personal absence. In that time, I did a lot of fooling around on Github and contributed to a bunch of projects, both my own and on other's projects. I haven't gotten around to completing much, just little additions here and there. So as I'm applying to new jobs, I'm just wondering how much headhunters and hiring staff will look at commit dates as big factors on my resume.
(Array Methods Part 1) What are Mutator Methods?
Tags: javascript, beginners, programming
Published: 2022-10-20 20:36:04

When we started to learn javascript anytime we will meet the famous array methods. Array methods can be separated in three types:

- Mutator Methods
- Accessor Methods
- Iteration Methods

I will create one post for each array type methods, but today I will explain about the first type.

**Mutator Methods**

Mutator methods besides return a value, they also change original array, such as:

**.sort()** - sort method organize array in alphabetical order.

The return of this method is the array itself with the changes.

```javascript
const animals = ['dog', 'cat', 'turtle', 'bird'];
animals.sort();
console.log(animals) // output: ['bird', 'cat', 'dog', 'turtle']
```

**Some others examples:**

**.push()** - push method insert elements into the end of an array

This method change the original array and return the new length, so we can classify as mutator method.

```javascript
const animals = ['dog', 'cat', 'turtle'];
const count = animals.push('bird');
console.log(count); // output: 4
console.log(animals); // output: ['dog', 'cat', 'turtle', 'bird']
```

There are a lot of types of mutator methods and if I explain about all methods I think this post will be very big, but that's not my intention, so I will list some important mutator methods that I think you should be study:

- `.unshift()`
- `.shift()`
- `.pop()`
- `.reverse()`
- `.splice()`
- `.fill()`

See you soon!!!


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m2zph17qht7aywz16vge.gif)
What's So Great About Virtual Dom in React?
Published: 2022-10-20 20:19:01

Nowadays, React is popular among Front-end developers. There are tons of reasons why they prefer React. One of those is the concept of Virtual Dom. I learned what is the virtual DOM so I am going to write it.
 Before React appears, web documents like HTML are loaded in web browsers to show users. They have tree-like structures.

![alt text](https://raw.githubusercontent.com/yuki-o1o5/dev.to/main/VirtualDominReact/IMG_4364AE9E5405-1.jpeg "Text 1")

When we would like to update something different, DOM (Document Object Model) works. This word is a little bit difficult for me so I think that Dom is an office to access each tag like `head`, `title`, `body`, `header`, `nav`, `main`, `p`, and `div`. 
 In JavaScript, If we want to change an element of `div` tag, we get `div` DOM and give it something different, and then the page has to re-render. In this way, DOM is changed directly and processed in the web browser. This process leads to being overloaded and the cost of re-rendering is high. 
 However, React can solve these problems because it uses the concept of a virtual DOM. React creates a virtual DOM to keep in memory whenever we render the user interface. If the next update occurs in the render, it compares the new version with the previous version and figures out the difference and the real DOM only changed the different points. It is called reconciliation. The updating is processed in the JavaScript engine and this process is implemented efficiently. The cost of re-rendering is low. Users also can see web pages more quickly than before.

![alt text](https://raw.githubusercontent.com/yuki-o1o5/dev.to/main/VirtualDominReact/IMG_FC1479FF53B4-1.jpeg "Text 2")

According to [this link](https://www.codecademy.com/article/react-virtual-dom), we can understand how virtual DOM works easily.

>In summary, here’s what happens when you try to update the DOM in React:

>1. The entire virtual DOM gets updated.
>2. The virtual DOM gets compared to what it looked like before you updated it. React figures out which objects have changed.
>3. The changed objects, and the changed objects only, get updated on the real DOM.
>4. Changes on the real DOM cause the screen to change.

The Virtual DOM enables pages to re-render productively. That's why React becomes more and more mainstream among Front-end web developers.

+ [reference link 1](https://blog.logrocket.com/what-virtual-dom-react/)
+ [reference link 2](https://www.youtube.com/watch?v=XKSYF2aZnkQ&list=PLX8Rsrpnn3IWPoM7-1YPDksRRkamRY25k&index=2)