teleren/devto huggingface dataset:
What's new in PreviewDevice 0.8.0
Tags: ios, swift, swiftui, preview
Published: 2021-09-18 15:32:12

[PreviewDevice](https://github.com/Toni77777/PreviewDevice) is a library with type-safe syntax sugar for preview device on SwiftUI. 
If you don't know what is the library, I recomment read this [article](https://tonidevblog.com/posts/meet-previewdevice/). 

## What's new in 0.8.0? Go-go-go

### Added support new Apple devices: 
iPhones: 
- iPhone 13 mini (``Device.iphone13Mini``)
- iPhone 13 (``Device.iphone13``)
- iPhone 13 Pro (``Device.iphone13Pro``)
- iPhone 13 Pro Max (``Device.iphone13ProMax``)

Apple Watch:
- Apple Watch Series 7 - 41mm (``Device.watchSeries7_41mm``)
- Apple Watch Series 7 - 45mm (``Device.watchSeries7_45mm``)

iPads:
- iPad 9th generation (``Device.ipad_9Gen``)
- iPad mini 6th generation (``Device.ipadMini6``)

### Preview on device with orientation and color schemes.

> Available iOS 15+ OSX 12+,  macCatalyst 15+, tvOS 15+, watchOS 8.0+

```swift
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
            .previewDevice(device: .iphone13,
                           orientation: .portrait,
                           colorSchemes: [.light, .dark])
    }
}
```
Do you like the library? Click the star on [GitHub](https://github.com/Toni77777/PreviewDevice).

Thanks for reading! See you soon. :wave:
Housing Flask App
Tags: python, flask, machinelearning, datascience
Published: 2021-09-18 14:59:40

This project was completed for my internship at Data Glacier.


Hello everyone!

This project included several new aspects I have never done before. It is my first time using Flask, APIs, and Heroku. It includes a simple Linear Regression model to predict housing prices in King County, Washington from 2014-2015. However, the model isn't the important part, I just used it since I am from that area and I needed to create a model for the assignment. My focus was on implementing a Flask app that could take API requests.

Flask app -

I had never created a Flask app before this project. In order to to learn how, I used information from my internship and lesson from CodeCademy.com. My focus is not on HTML and CSS, so that code is taken from a previous project I completed and edited for this app.

I wanted to make my app work with an API request and using the app UI. Unfortunately, I was unable to do so due to my lack of experience with Flask. My solution was to create a page for the app and a page for the API. I would love to hear how I could have accomplished this though.

Another feature that I had to remove was using flask_wtf to use the date from the app. Due to the deadline for the project I had to ditch this after not being able to make it work after some hours.

Heroku -

This was also my first time putting an app on Heroku. The biggest hurdle for me was getting the requirements.txt file working. I now understand the benefit of using a digital environment for this purpose, but before I used the command to create the file using all the dependencies on the machine. However, this added way too many libraries and they couldn't be found to upload them. I also tried using a Heroku python package, but for some reason none of them worked. I just ended up adding them manually which is what I should have done in the beginning since there are so few of them.

Conclusion -

Overall, this was a great experience with features I was not familiar with. The model building was really the only step I had familiarity with, but I was able to do what I needed to complete the project. I have linked the app and the repository below.

https://shrouded-meadow-77059.herokuapp.com/

https://github.com/TheHamhams/DG-Housing
Add new fields in Jquery
Tags: javascript, html
Published: 2021-09-18 15:16:53

#Here is the code Snapshot 
Simple Form with classes
![show](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ei2kwdnk6hvdmuxwznm7.png)
The div that copy on each time
![code-snapshot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bm8wlyfmi8jk8mrxxqur.png)
Matrizes ou Arrays Multidimensionais
Tags: javascript, algorithms
Published: 2021-09-18 14:56:59

## ⚠️ ALERTA!!!! ⚠️

Matrizes não são algo que vemos com frequência no JS. Coloquei aqui mais por conhecimento mesmo e porque elas existem.

As matrizes são vetores de duas ou mais dimensões (***arrays*** multidimensionais) que também guardam elementos do mesmo tipo. Essa funcionalidade não existe no JS, porém podemos criá-la da seguinte forma: fazendo um ***array*** principal e, dentro, colocar outros ***arrays***.

### Exemplo

```javascript
const numeros = [
	[1, 2, 3, 4, 5],
    [6, 7, 8, 9, 10]
];

console.log(numeros.join("\n\n"));
```

O resultado aparece assim:

```javascript
/*

"1,2,3,4,5

6,7,8,9,10"

*/
```

### E como eu faço para mostrar um determinado elemento dessa matriz?!

É só fazer assim:

```javascript
const numeros = [
	[1, 2, 3, 4, 5],
    [6, 7, 8, 9, 10]
];

console.log(numeros[0][0]); // 1
console.log(numeros[1][0]); // 2
```

É melhor explicar:

A matriz `numeros` consiste em dois vetores com cinco elementos cada. O primeiro índice entre colchetes refere-se ao **índice do vetor (linha)**, enquanto que o segundo índice refere-se ao **elemento que está dentro desse vetor (coluna)**. 

### Como faço para percorrer e mostrar todos os elementos da matriz?

Vamos usar o laço `for of.`

```javascript
for (let [d1, d2, d3] of numeros) {
  console.log(`${d1}, ${d2}, ${d3}`)
}
```

Ou podemos usar `for in`.

```javascript
for (let i of numeros) {
  for (let j of i) {
    console.log(j)
  }
}
```

E aí? Gostaram? Até a próxima anotação! 😊
Android ViewModel
Published: 2021-09-18 14:54:17

Uma das práticas básicas de desenvolvimento que temos que adotar assim que saímos do campo de estudos e entramos no campo de desenvolvimento profissional de aplicativos é separar a camada de negócios da camada de visualização. A camada de visualização possui um ciclo de vida próprio que muda de acordo com o estado do device (se a app está em primeiro ou segundo plano, se rotacionamos o aparelho, se o SO solicita memória, etc). Os dados de negócio não podem estar sujeitos a esses tipos de mudança. 
Para auxiliar essa implementação o Kotlin traz o ViewModel. O ViewModel permite realizar uma delegação e uma separação dos dados de negócio. Vamos à implantação:

O primeiro passo é a referencia à biblioteca no build.gradle.
`implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'`

A seguir no projeto crie uma classe herdando de ViewModel
```kotlin
public class PackageModel : ViewModel(){
}
```

Agora vem a parte importante da implementação. O Kotlin possui um recurso chamado **Property Delegate**. Basicamente ele permite que uma propriedade delegue o __getter__ e o __setter__ para uma classe externa. A sintaxe é essa:
```kotlin
var [nome] : [tipo] by [classe delegada]()
```

No nosso caso, vamos declarar a propriedade delegada do modelo dentro de uma Activity ou Fragment. Vai ficar assim:
```kotlin
private val model : PackageModel by viewModels()
```
No exemplo acima **viewModels()** é um property delegate que vem pronto do Kotlin.

Deste ponto em diante basta implementar as propriedades e métodos necessários
Persistence in the dev world
Published: 2021-09-18 14:47:24

Hi there,am actually a new member of the community.Writing this article means a lot to me since i am expressing my happiness by encouraging those of us who are beginners to the programming world.
One of the characteristics of a programmer,developer or any other IT person is PERSISTENCE,yes I said persistence.Having issues and problems in the dev world is inevitable but fixing them is rather accomplishable.Being able to see a problem(not necessarily a bug)and try fixing it over and over times not counting the failure turn outs is persistence in my dev dictionary.Recently,probably 2 days ago,i finally connected my web site to a database after several fails.I know some people who read this article would be like thats a small thing but it isnt for me because i failed over 10 times(very disappointing)but i never gave up,actually speaking am just a learner in the backend world but built a big website on the fronted,back end and the database management.What am i trying to say hear;that we are not limited to what we think we know but we could be persistent till we master what we didn't know.
With that i end this article on persitency in the dev world,thanks for reading.
TypeError: list indices must be integers or slices, not tuple
Tags: python, programming, codenewbie, tutorial
Published: 2021-09-19 13:00:06

---
title: TypeError: list indices must be integers or slices, not tuple
published: true
date: 2021-09-18 14:44:31 UTC
tags: #python #programming #codenewbie #tutorial
canonical_url: https://itsmycode.com/typeerror-list-indices-must-be-integers-or-slices-not-tuple/
---

ItsMyCode |

If you are accessing the list elements in Python, you need to access it using its index position. If you specify a tuple or a list as an index, Python will throw **typeerror: list indices must be integers or slices, not tuple.**

This article will look at what this error means and how to resolve the typeerror in your code.

## TypeError: list indices must be integers or slices, not tuple

**Example 1 – **

Let’s consider the below example to reproduce the error.

```python 
# Python Accessing List
numbers=[1,2,3,4]
print(numbers[0,3])

```

**Output**

```python 
Traceback (most recent call last):
  File "c:\Projects\Tryouts\main.py", line 3, in <module>
    print(numbers[0,3])
TypeError: list indices must be integers or slices, not tuple
```

In the above example, we are passing the [0,3] as the index value to access the list element. Python interpreter will get confused with the comma in between as it treats as a tuple and throws typeerror: list indices must be integers or slices, not tuple.

**Solution **

We cannot specify a tuple value to access the item from a list because the tuple doesn’t correspond to an index value in the list. To access a list, you need to use a proper index, and instead of **comma** use **colon :** as shown below.

```python 
# Python Accessing List
numbers=[1,2,3,4]
print(numbers[0:3])

```

**Output**

```python 
[1, 2, 3]
```

**Example 2 – **

Another common issue which developers make is while creating the list inside a list. If you look at the above code, there is no comma between the expressions for the items in the outer list, and the Python interpreter throws a TypeError here.

```python 
coin_args = [
  ["pennies", '2.5', '50.0', '.01']
  ["nickles", '5.0', '40.0', '.05']
]

print(coin_args[1])
```

**Output**

```python 
c:\Projects\Tryouts\main.py:2: SyntaxWarning: list indices must be integers or slices, not tuple; perhaps you missed a comma?
  ["pennies", '2.5', '50.0', '.01'] 
Traceback (most recent call last):
  File "c:\Projects\Tryouts\main.py", line 2, in <module>
    ["pennies", '2.5', '50.0', '.01']
TypeError: list indices must be integers or slices, not tuple
```

**Solution**

The problem again is that we have forgotten to add the comma between our list elements. To solve this problem, we must separate the lists in our list of lists using a comma, as shown below.

```python 
coin_args = [
  ["pennies", '2.5', '50.0', '.01'] ,
  ["nickles", '5.0', '40.0', '.05']
]

print(coin_args[1])
```

**Output**

```python 
['nickles', '5.0', '40.0', '.05']
```

The post [TypeError: list indices must be integers or slices, not tuple](https://itsmycode.com/typeerror-list-indices-must-be-integers-or-slices-not-tuple/) appeared first on [ItsMyCode](https://itsmycode.com).
0 downtime is hell, so prepare in advance
Tags: devops, postgres, 0downtime
Published: 2021-09-18 14:43:23

## TL;DR
Quick introduction to what is blue-green deployment with some useful links at the end

## Preamble
Some time ago my team lead told me to prepare a document about "0 downtime" deployment for developers usage. I knew something about it and thought that it would be easy task for me, but after some research I understood that it was about an endless rabbit hole. And if you want to implement "0 downtime" deployment you need to be very very cautious and better double-check everything. This post is just a warning for you my dear friend.

## Blue-green deployment
I will not lie to you. It is the only technique I know, so let's check its basic idea. [Martin Fowler article](https://martinfowler.com/bliki/BlueGreenDeployment.html)

> Blue-green deployment is an application release model that gradually transfers user traffic from a previous version of an app or microservice to a nearly identical new release—both of which are running in production.
>
> The old version can be called the blue environment while the new version can be known as the green environment. Once production traffic is fully transferred from blue to green, blue can standby in case of rollback.
> © [RedHat](https://www.redhat.com/en/topics/devops/what-is-blue-green-deployment)

Sounds pretty easy, but the hardest part of this it is making incompatible changes in compatible way (remember that you try to run previous and current version at the same time). So wherever you have separate layers you need to think about compatibility (client-server, server-database, etc.)

I will not give you any practical advice, because I have only theoretical knowledge about this topic yet. So check more experienced authors by the links below.

## Useful materials
- [Blue-green deployment @ Martin Fowler blog](https://martinfowler.com/bliki/BlueGreenDeployment.html)
- [What is blue green deployment? @ RedHat blog](https://www.redhat.com/en/topics/devops/what-is-blue-green-deployment)
- [Zero Downtime Deployment with a Database @ Spring Blog](https://spring.io/blog/2016/05/31/zero-downtime-deployment-with-a-database)
- [Zero downtime deployment with Kubernetes, Spring Boot and Flyway @ DevOps Days YouTube](https://www.youtube.com/watch?v=LQI19ngeLsA)
- [Safe Operations For High Volume PostgreSQL @ braintreepayments](https://www.braintreepayments.com/blog/safe-operations-for-high-volume-postgresql/)
- [Zero-downtime Postgres migrations - the hard parts @ gocardless](https://gocardless.com/blog/zero-downtime-postgres-migrations-the-hard-parts/)

## Afterword
Hope this post was useful for you guys. Feel free to share any feedback or thoughts.
Criando menu de contexto para apps Android
Tags: android, java
Published: 2021-09-18 14:30:31

Tutorial pá-pum pra você criar menus de contexto no Android, usando Java:

![Menu "opções" no navegador.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/franhbot4ctkwybx7dgh.png)

#### Crie o resource file menu.xml na pasta menu

``` xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@+id/refresh_page"
        android:title="Refresh"
        app:showAsAction="always" />

</menu>
```

#### Adicione o menu à activity

``` java
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }
```

#### Adicione ação aos botões do menu

``` java
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.refresh_page:
                refreshPage();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
```

### Referências
- [Documentação Android Developers](https://developer.android.com/guide/topics/ui/menus?hl=pt-br)
Debouncing / throttling
Tags: javascript, timers
Published: 2021-09-18 14:24:20

Photo by <a href="https://unsplash.com/@jpvalery?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Jp Valery</a> on <a href="https://unsplash.com/s/photos/throttle?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>

This short Q&A on `setTimeout()` hopes to lead you into writing your own debouncers & throttlers -- handy tools for treating repeated events that happen across short periods of time as a single event.

```
Debouncing:

       Time : -   - --> -   - --> -   - --> -
Key-presses :        X X X X   X X X X X
     Events :              O           O
```

```
Throttling:

       Time : -   - --> -   - --> -   - --> -
Key-presses :        X X X X X X X X X
     Events :        O     O     O
```

All code below assumes the following header:

```js
const seconds = n => n * 1000
const log = x => console.log(`hello, ${x}`)
```

So, the question is:

> "At the end of each run, what will be logged to the console?" 🤔

### 1. setTimeout / clearTimeout

```js
let id

function run() {
  id = setTimeout(log, seconds(1), 'world')
}

function clear() {
  clearTimeout(id)
}

// 1a)
run()
// What will be logged?

// 1b)
run()
clear()
// What will be logged?
```

### 2. runAfter

```js
function runAfter(ms, fn, ...args) {
  const id = setTimeout(fn, ms, ...args)
  return () => clearTimeout(id) 
}

// 2)
const clear = runAfter(
  seconds(1),
  () => log('world')
)

clear()
// What will be logged?
```

### 3. RunAfter

```js
function RunAfter(ms, fn) {
  let id
  const clear = () => clearTimeout(id)
  const run = (...args) => {
    id = setTimeout(fn, ms, ...args)
  }
  return [run, clear]
}

const [run, clear] = RunAfter(
  seconds(1),
  () => log('world')
)

// 3)
run()
// What will be logged?
```

### 4. makeDebouncer

```js
function makeDebouncer(ms, fn) {
  const [run, clear] = RunAfter(ms, fn)
  const debouncer = (...args) => (
    clear(), run(...args)
  )
  return [debouncer, clear]
}

const [run, clear] = makeDebouncer(
  seconds(1),
  () => log('world')
)

// 4)
run()
run()
run()
// What will be logged?
```

### 5. makeThrottler

```js
function makeThrottler(ms, fn) {
  let canRun = true
  const [run, clear] = RunAfter(ms, reset)
  return [throttler, reset]

  function throttler(...args) {
    if (!canRun) return
    canRun = false
    run()
    fn(...args)
  }

  function reset() {
    clear()
    canRun = true
  }
}

const [run, clear] = makeThrottler(
  seconds(1),
  () => log('world')
)

// 5)
run()
run()
run()
clear()
// What will be logged?
```

If you need a little help, I made a corresponding [interactive version](https://zansh.in/debouncing-throttling.html) of the article that offers some *very* basic visuals.

I'm not sure if they help intuit what's going on, but they give the answers at least! Did they meet your expectations?
How to perform calculations in CSS?
Tags: css, webdev, programming
Published: 2021-09-18 14:24:00

If the user wants to perform mathematical operations in CSS such as multiplication, addition, subtraction or division, they can use `calc()` function in CSS.

`calc()` is a function that performs calculation to be used as the value of property.


###Syntax
```
.class-name{
      property: calc(expression)
   }
```
where expression is mathematical expression with + - * / operators. It can be used anywhere angle, length, frequency, number, integer, time or percentage is required.


calc() can be used as an alternative to grid but it's not recommended to do the same.

###Points to remember before you use calc()
• Only + and - operators should be surrounded by whitespaces.
```
calc(50% - 80px)
```
• You can now use `calc()` with media query.
• `calc()` is mainly used when working with mixed units.
```
width: calc(50rem - 3px);
```
• You can nest `calc(calc())`
```
.class-name {
  width: calc(
    calc(20% / 5)
    +
    calc(4rem * 2)
  );
}
```

[![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hqmyq1twcon9ndguelyd.png)](https://www.buymeacoffee.com/hardiquedasore)

Follow us on [Instagram ](https://www.instagram.com/commitandpush/)
Released types for subroutines
Tags: perl, perl5
Published: 2021-09-18 14:14:25

---
title: Released types for subroutines
published: true
description: 
tags: perl,perl5
//cover_image: https://direct_url_to_image.jpg
---

It is useful to have a subroutine type, so I made one.

```perl
use Types::Sub -types;
use Types::Standard -types;

my $Sub = Sub[
    args    => [Int, Int],
    returns => Int,
];

warn $Sub->validate(sub {})
# =>
# Reference sub { "DUMMY" } did not pass type constraint "Sub[sub(Int, Int) => Int]"
#    Reason : invalid parameters: invalid args length. got: 0, expected: 2
#    Expected : sub(Int, Int) => Int
#    Got      : sub(*) => *
```

If you can find the meta-information from the subroutine, the test will pass as follows.

```perl
use Types::Sub -types;
use Types::Standard -types;

my $Sub = Sub[
    args => [Int, Int],
];

use Function::Parameters; 
fun add(Int $a, Int $b) { return $a + $b }
ok $Sub->check(\&add);

use Sub::WrapInType qw(wrap_sub);
ok $Sub->check(wrap_sub([Int,Int] => Int, sub {}));

use Sub::WrapInType::Attribute;
sub add2 :WrapSub([Int,Int] => Int) {
    my ($a, $b) = @_;
    return $a + $b
}
ok $Sub->check(\&add2);

sub add3 {}
my $meta = Sub::Meta->new(
    args    => [Int, Int],
    returns => Int,
);
Sub::Meta::Library->register(\&add3, $meta);
ok $Sub->check(\&add3);
```

Internally, `Sub[...]` coerces subroutines into Sub::Meta and compares Sub::Meta against each other.

Give it a try!
https://metacpan.org/release/KFLY/Sub-Meta-0.14/view/lib/Types/Sub.pm
5chan - The 4chan clone
Tags: nextjs, typescript, go, gofiber
Published: 2021-09-18 14:14:15

This weekend I want to make a clone of 4 chan. It won't be as big as 4chan lol.
But still I'll use this post to design and decide the stack to use.


## What is 4 chan
> 4chan is a simple image-based bulletin board where anyone can post comments and share images. There are boards dedicated to a variety of topics, from Japanese animation and culture to videogames, music, and photography. Users do not need to register an account before participating in the community.  ~ *4chan Homepage*

## What we want 5chan to be
 
 - Text based
 - Anonymous [ no registration ]
 - Posts
 - Replies to posts
 - Timeline of posts on homepage

## The tech stack :
- Backend
	- [Go-fiber](https://gofiber.io/)
	- [Air - live reload](https://github.com/cosmtrek/air)
	- [GORM](https://gorm.io/)
	- [PostgreSQL](https://www.postgresql.org/)
- Frontend 
	- [NextJs](https://nextjs.org/) 
	- [Chakra UI](https://chakra-ui.com/)
	- [SWR](https://swr.vercel.app/)
	- [Formik](https://formik.org/)
	- [Zustand](https://zustand.surge.sh/)
- Hosting
        - [Heroku](https://www.heroku.com/)


Hmmm. Thats something I can work out in a day or two for sure.

So ... LESGOOOO


![cat-ready.gif](https://media.giphy.com/media/CjmvTCZf2U3p09Cn0h/giphy.gif?cid=ecf05e47kq1h576i6japfzxpjvqixjrl4rihalyop04ipgsf&rid=giphy.gif&ct=g)
 
---
You can find me at:

Website : https://100lvlmaster.in 

Github : https://github.com/100lvlmaster
How To: Secure your Kubernetes Environment with RBAC User Management
Tags: kubernetes, management, user, rbac
Published: 2021-09-18 14:01:46

This webinar will compare and contrast how to create Kubernetes RBAC user management, with and without @portainerio. You will learn about -

- The 5 predefined roles within RBAC
- How to handle employee changes and leavers
- RBAC complexity
- Authentication
Virtual Bookcase - in progress
Tags: codepen, imersaodev, alura, learning
Published: 2021-09-18 13:23:00

Hello there!

I am making this very simple virtual bookcase for learning more about frontend development.

It is a challenge from ImersãoDEV event promoted by Alura. I used just HTML, CSS, and pure Javascript.

**The next steps:**
- I need to save the name of the book and show that name with its image book; [I'm thinking in a way to show the name when I put the mouse over the image];
- I need to remove the book by the name; 

{% codepen https://codepen.io/lucascunha/pen/powayVg %}