teleren/devto huggingface dataset:
Can we pass variable in List
Published: 2021-05-02 13:09:21

Brief - created a List example - variable1 = ['one','two','three',1, 3, 5.6, True] Aim to view the type of each parameter passed in the list. My approach - print(type(variable1[0])) I have to repeat this couple of times to get each parameter type. This would not be efficient so I thought of using a for loop My Idea - use a for loop and pass a variable say x into the code print(type(variable1[x])) and increment it by 1 so the code can be simple. But when I tried it, the system gives an error. Question - can we pass a variable inside the list print(type(variable1[x])) like this, if not what is the efficient way to achieve the goal of viewing the type of each parameter inside a list
Focus vs Focus-Within vs Focus-Visible
Tags: ux, css, webdev, a11y
Published: 2021-05-07 07:46:18

---
title: Focus vs Focus-Within vs Focus-Visible
published: true
date: 2021-05-07 07:00:00 UTC
tags: #ux #css #webdevelopment #accessibility
canonical_url: https://bharathvaj.me/blog/focus-vs-within-vs-visible
---

Today, we will be discussing focusable pseudo-classes supported by modern browsers, but before we dive deeper, it’s worth understanding what _focusable_ and _tabbable_ means in the context of CSS.

### Focusable Element

The element will be focused by the script `(element.focus())` and possibly the mouse (or pointer), but not the keyboard.

### Tabbable Element

The element will be keyboard focusable (“tabbable”), as it is part of the document’s sequential focus navigation order. Also focusable by the script and possibly the mouse (or pointer).

These pseudo-classes are triggered when the user focuses on an element in different ways.

## :focus

Triggered when the user clicks or taps on an element or selects it with the keyboard’s `Tab` key.

```
/* Selects any <input> when focused */
input:focus {
  background: yellow;
  color: red;
}
```

This applies only to the focused element. Here, only the input tag will be highlighted

{% codepen https://codepen.io/bharathvaj1995/pen/eYvmzWV default-tab=html,result %}


## :focus-within

Triggered when the user clicks or taps on any of its child element or itself

```
/* Selects a <div> when one of its descendants is focused */
div:focus-within {
  background: cyan;
}
```

Here if any of that div’s children receive focus that this selector will get applied.

{% codepen https://codepen.io/bharathvaj1995/pen/LYWEZOa default-tab=html,result %}

## :focus-visible

Triggered by User-Agent on elements having `:focus` selector based on some heuristics that determine which one of the active elements should receive focus.

This selector is mostly useful to provide a different focus indicator based on the user’s input modality (mouse vs. keyboard).

For instance, let’s say you have `<a>` tag, you want to remove the focus outline when user focuses it via mouse but want to retain an outline that goes in with the site theme when user focuses via keyboard.

 ![](https://i1.wp.com/css-tricks.com/wp-content/uploads/2019/01/unwanted-outline.png?ssl=1)

```
.next-image-button:focus {
  outline: none;
}
.next-image-button:focus-visible {
  outline: 3px solid currentColor; /* That'll show 'em */
}
```

 ![](https://i1.wp.com/css-tricks.com/wp-content/uploads/2019/01/focus-visible-outline.png?ssl=1)

So, when we use mouse there won’t be any visual outline but with keyboard, there will be a nice visual focus indication that goes along with the site theme.

These CSS pseudo-classes will definitely improve site accessibility when used correctly.

 
<div style="text-align:center"><img width="240px"  height="240px" src="https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif"></div>

Happy Hacking!!!
Pushing Large Files to GitHub(CMD-V)
Tags: github
Published: 2021-05-02 11:17:10

Hello everyone in todays article we will see how you can upload large files i.e, Files>25MB to you Git Repositories. So Lets get started.

Before getting started make sure that the following things are ready
1. _Make you have a [GitHub](https://github.com/) account_
2. _Download and install [GITBASH](https://git-scm.com/downloads)_
3. _Configure [GITBASH](https://git-scm.com/downloads) i.e, connect it with you GitHub account_

Now I hope everything is ready so lets begin.

* Open the command line ("Terminal" on the Mac, "Git Bash" on Windows) and change into your project's base directory. There, you can create a new Git repository:

```
$ cd projects/my-project
$ cd projects/my-project/git init
```

 * As a first step, you can add all of your current files to the 
 repository and then bundle these in a commit:
```
$ git add .
$ git commit -m "Initial commit"
```
* Now, you are ready to push your code to GitHub!

####How to Push to GitHub
Before you can upload your code to GitHub, you need to create a remote repository in your GitHub account.

####Using Git on the Command Line
* If you're working with Git on the Command Line, you'll have to open the GitHub.com interface in your browser. Right on the "Dashboard" view, you can see a button to create a new repository:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nfrruldwtl7husml7g1g.jpeg)

* Then, on the project's main page, you can use the green "Code" button to reveal the repository's remote URL and copy it to your clipboard:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5pxx3li45e9cbqt1t2x4.jpeg)
* You can then connect this remote repository to your local Git repository with the following command:
```
$ git remote add origin <remote repository URL>
```
* The final step is to push your changes from your local repository to your new remote repository:
```
$ git push origin master
```

`NOTE:
The maximum size of GitHub is 100 MB per file, 1 GB per repo`

So that's it guys!
If you like this article hit that button, if you have any doubt's you can comment down below.
Help me understand this code, please
Tags: javascript, closure
Published: 2021-05-02 12:38:47

I'm working through 'Eloquent Javascript' (www.eloquentjavascript.net) and I'm not grasping how this works.

```
function multiplier(factor) {
  return number => number * factor;
}
let twice = multiplier(2);
console.log(twice(5));
// → 10
```

I guess where I'm getting lost is how does this line worK:
`let twice = multiplier(2)`

In trying to understand, I did some other console.log commands to see what they would return:

```
console.log(multiplier(2));
// → x => x * factor
console.log(twice);
// → x => x * factor
```

Can someone help me get over this mental block that I'm having?  How does 'twice' have a parameter?  Is 'twice' a reference to the multiplier function?
Sock merchant problem - Hackerrank
Tags: kotlin
Published: 2021-05-02 12:20:19

Problem definition is available [here](https://www.hackerrank.com/challenges/sock-merchant/problem)

This is a classification problem where the element can repeat multiple times in the given array. 


Like any other problem, this can be solved in multiple ways in kotlin.


### 1. Elegant - yet non performant solution

```kotlin
fun sockMerchant(n: Int, ar: Array<Int>): Int {
  return ar.groupBy { it }
      .map { it.value.size/2 } // it is Map<Int, List<Int>>
      .sum()
}
```

This is a straightforward solution

1. Read each value and create a map `Map<Int, List<Int>>`
2. Convert each key-value-entry into integer by computing the size of value array
3. Sum all elements in the integer list obtained from previous step


Though this looks elegant and **kotlin**ish, we shouldn't ignore the fact that it creates a Map with value list of identical elements. While what needed is just a counter mapped against each element.


### 2. Old school - manual computation

For this classification problem, `Map` is the ideal datastructure for grouping.

```kotlin
fun sockMerchant(n: Int, ar: Array<Int>): Int {
    val map = mutableMapOf<Int, Int>()
  	for (s in ar) {
        map[s] = (map[s] ?: 0) + 1
    }
  	return map.values.fold(0) { 
        acc, v ->
        acc + v/2
        }
}
```



Here, we create a map `Map<Int, Int>` & increase the counter for each bucket. Then fold it. So, there is no value `List<Int>` created. Moreover, based on the unique values, the Map size constrained. At the end, the map values iterated through and folded into count.



**Wait.. There is still room for improvement** 



We need a consolidated count, **not** the per element pair count. That means, the fold function can be avoided by adding another line to the first loop.

```kotlin
val map = mutableMapOf<Int, Int>()
var pairCount = 0
for (s in ar) {
    var count = (map[s] ?: 0) + 1
    map[s] = count
    if (count % 2 == 0) { 
      // For every second encounter, increase pairCount by one
        pairCount++
    }
}
return pairCount
```



> Be kind to GC, few more lines of code won't hurt
Deploy an Easy Apple CareKit iOS App for Healthcare with a HIPAA-ready back end
Tags: cloud, healthcare, ios, techtalks
Published: 2021-05-02 12:17:57

Recently, Elton de Souza (Chief Architect, IBM) and I (Developer Advocate, IBM) conducted a webinar on Deploying an Easy Apple CareKit iOS App for Healthcare with a HIPAA-ready back end.

We covered a lot of points in this presentation, which includes the topic of confidential computing, what is overall security and how do policies play a major role when it comes to the topic of security where we majorly focused on Health Insurance Portability and Accountability Act (HIPAA) and its implications on healthcare.

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

The application Elton demonstrated was an iOS application which has been created on top of Apple CareKit and to further extend the functionality and connectivity there is an Hyper Protect SDK for CareKit which allows us to connect to Hyper Protect Services on IBM Cloud

Wondering what is Hyper Protect?
It is basically IBM's confidential computing services which are provided and are focused mainly on security and efficiency.

There is a variety of Hyper Protect services which are available on IBM Cloud which you can sign up and login by clicking [here](https://ibm.biz/HyperProtectHIPAA)

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

It was a very interesting webinar and I being new to the topic of confidential computing really enjoyed presenting the tech-talk with Elton.

In case you are wondering where you can get started:
### Find the recording of the webinar here: https://www.crowdcast.io/e/healthcare-app

### Slides: https://fawazsiddiqi.github.io/carekit-hyperprotect-lab

### Sign up for IBM Cloud at: https://ibm.biz/HyperProtectHIPAA

Looking to use #TechforGood? Join a community of problem solvers to fight back some of the world’s most pressing challenges and win up to $200K!
 
Answer the call on → http://callforcode.org
 
Follow us on [Meetup](https://www.meetup.com/IBMDeveloper-Dubai/) to join us in the upcoming relevant workshops and webinars.
Day 49 of 100 Days of SwiftUI
Tags: swift, 100daysofcode
Published: 2021-05-02 12:04:45

I just completed day 49 of 100 Days of Swift. Today I learnt a lot about Codables, making  API requests with URLSession, and validate and disable form data. 

Making API requests using a URLSession is actually pretty simple. To do so you first have to create a URL object and then defined the networking task. Here's an example showing you how to do so
```swift
struct Response: Codable {
    var results: [Result]
}

struct Result: Codable {
    var trackId: Int
    var trackName: String
    var collectionName: String
}

guard let url = URL(string: "https://itunes.apple.com/search?term=taylor+swift&entity=song") else {
    print("Invalid URL")
    return
}

let request = URLRequest(url: URL)

URLSession.shared.dataTask(with: request) { data, response, error in
   if let data = data {
    if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {
        DispatchQueue.main.async {
            self.results = decodedResponse.results
        }
        return
    }
}
}.resume()
```
The code above fetches a list of songs by Taylor swift from the internet. The first thing this code does is to define struct models that represent the JSON being received from the internet. It then creates a `URLRquest` using the URL specified. 
This `URLRequest` is then passed into `URLSession.shared.dataTask` in order to make the actual network request. Network requests done by `URLSession` are done in a background thread so we need to find a way to send the decoded response from the background thread to the main thread. This is where the `DispatchQueue.main.async` comes in. `DispatchQueue.main.async` is used to perform a piece of work and send it to the main thread. 

Like everything, I've seen so far in SwiftUI validating form is also pretty simple. All you need to do is add a `disabled() ` modifier. For example, this is how you validate a form in SwiftUI

```swift
struct ContentView: View {
    @State private var username = ""
    @State private var email = ""

    var disableForm: Bool {
       username.count < 5 || email.count < 5
    }

    var body: some View {
        Form {
            Section {
                TextField("Username", text: $username)
                TextField("Email", text: $email)
            }

            Section {
                Button("Create account") {
                    print("Creating account…")
                }
            }.disabled(disableForm)

        }
    }
}
```
The code above defines a SwiftUI view that takes the username and email of a user. Using the disabled modifier on the button's section. That section will be disabled until the both the username and email have more than 5 characters.
Daily Developer Jokes - Sunday, May 2, 2021
Tags: jokes, dailydeveloperjokes
Published: 2021-05-02 12:00:21

---
title: "Daily Developer Jokes - Sunday, May 2, 2021"
description: "Check out today's daily developer joke! (a project by Fred Adams at xtrp.io)"
series: "Daily Developer Jokes"
cover_image: "https://private.xtrp.io/projects/DailyDeveloperJokes/thumbnail_generator/?date=Sunday%2C%20May%202%2C%202021"
published: true
tags: #jokes, #dailydeveloperjokes
---

Generated by Daily Developer Jokes, a project by [Fred Adams](https://xtrp.io/) ([@xtrp](https://dev.to/xtrp) on DEV)

___Read about Daily Developer Jokes on [this blog post](https://xtrp.io/blog/2020/01/12/daily-jokes-bot-release/), and check out the [Daily Developer Jokes Website](https://dailydeveloperjokes.github.io/).___
### Today's Joke is...
![Joke Image](https://private.xtrp.io/projects/DailyDeveloperJokes/public_image_server/images/5e1258f70cd7f.png)

---
*Have a joke idea for a future post? Email ___[xtrp@xtrp.io](mailto:xtrp@xtrp.io)___ with your suggestions!*

*This joke comes from [Dad-Jokes GitHub Repo by Wes Bos](https://github.com/wesbos/dad-jokes) (thank you!), whose owner has given me permission to use this joke with credit.*

<!-- 
Joke text:
___Q:___ Are computers dangerous?

___A:___ Nah, they don't byte. They just nibble a bit.
 -->
Go: เปลี่ยนสีรูปเป็น Gray scale
Tags: go
Published: 2021-05-02 10:02:29

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/20z9ni035j5vrt2oyc81.png)

มีงานที่ต้อง process รูปก่อนไปทำ OCR เพื่อให้ program ทำ OCR นั้นแยกแยะตัวอักษรได้ง่ายๆ เลยต้องทำการเปลี่ยนสีรูปให้อยู่ในแบบ Gray Scale ก่อน

ซึ่งสำหรับ Go นั้นทำได้ง่ายๆด้วย Standard library 

* `image`
* `image/jpeg` (เนื่องจาก source เป็น JPEG)
* `image/png` (output ออกเป็น PNG)

นี่คือโค้ดที่ทำการแปลง โดย gopher.jpg คือไฟล์รูปที่จะแปลง และ gray_gopher.png คือไฟล์ที่แปลงเรียบร้อยแล้ว

```go
package main

import (
	"image"
	_ "image/jpeg"
	"image/png"
	"log"
	"os"
)

func main() {
	f, err := os.Open("gopher.jpg")
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()
	m, _, err := image.Decode(f)
	if err != nil {
		log.Fatal(err)
	}
	bounds := m.Bounds()
	grayImg := image.NewGray(bounds)
	for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
		for x := bounds.Min.X; x < bounds.Max.X; x++ {
			grayImg.Set(x, y, m.At(x, y))
		}
	}
	grayFile, err := os.Create("gray_gopher.png")
	if err != nil {
		log.Fatal(err)
	}
	defer grayFile.Close()
	if err := png.Encode(grayFile, grayImg); err != nil {
		log.Fatal(err)
	}
}
```

โค้ดที่ทำมี 3 steps คือ

1) โหลด source ไฟล์แล้วก็ decode ให้มาเป็น `image.Image` type

```go
	f, err := os.Open("gopher.jpg")
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()
	m, _, err := image.Decode(f)
	if err != nil {
		log.Fatal(err)
	}
```

2) สร้าง Image ใหม่ให้เป็นแบบ gray scale ด้วย `Image.NewGray` โดยใช้ขนาดรูปจากรูปต้นฉบับ จากนั้นวนลูปเพื่อดึงค่าสีตามแกน x, y ทีละค่าไปกำหนดให้รูปที่เป็น gray scale เดี๋ยวมันจะแปลงสีให้เอง

```go
	bounds := m.Bounds()
	grayImg := image.NewGray(bounds)
	for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
		for x := bounds.Min.X; x < bounds.Max.X; x++ {
			grayImg.Set(x, y, m.At(x, y))
		}
	}

```

3) สุดท้ายเราก็เขียนไฟล์รูป `grayImg` ลงไปโดยใช้ `png.Encode` เพื่อให้แปลงจาก `image.Image` เป็นไฟล์ png

```go
	grayFile, err := os.Create("gray_gopher.png")
	if err != nil {
		log.Fatal(err)
	}
	defer grayFile.Close()
	if err := png.Encode(grayFile, grayImg); err != nil {
		log.Fatal(err)
	}
```

เพียงเท่านี้ก็ได้แล้ว ลองเอาไปประยุกต์ใช้กันดูครับ


## ขอฝาก Buy Me a Coffee
สำหรับท่านใดที่อ่านแล้วชอบโพสต์ต่างๆของผมที่นี่ ต้องการสนับสนุนค่ากาแฟเล็กๆน้อยๆ สามารถสนับสนุนผมได้ผ่านทาง Buy Me a Coffee คลิ๊กที่รูปด้านล่างนี้ได้เลยครับ

<a href="https://www.buymeacoffee.com/weerasak" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>

ส่วนท่านใดไม่สะดวกใช้บัตรเครดิต หรือ Paypal สามารถสนับสนุนผมได้ผ่านทาง PromptPay โดยดู QR Code ได้จากโพสต์ที่พินเอาไว้ได้ที่ Page DevDose ครับ https://web.facebook.com/devdoseth
Improve Your Java Code Using Streams
Tags: java, webdev, programming, tutorial
Published: 2021-05-02 11:37:18


## **What are streams?** 🌊

Streams were introduced in Java 8. According to Oracle docs, it’s:

> Classes to support functional-style operations on streams of elements, such as map-reduce transformations on collections

Let’s put it in more practical terms, a  **stream consists of a data source, followed by zero or more intermediate operations and then a terminal operation**.

### **What data sources?** 🗃

-   Collections, Lists, Sets, ints, longs, doubles, arrays, lines of a file.

### **what intermediate operations?**🪓

-   filter, map, sort, etc.
-   Those operations return a stream, so they can be chained with other operations.

### **What terminal operations?**⚒

-   forEach, collect, reduce, findFirst, etc.
-   They return a void or non-stream result.
-   If a stream doesn’t have a terminal operation, the intermediate ones aren’t going to get called.


## **Let’s convert a function from imperative to a declarative style using Streams**

### The imperative function (No Streams) 🦨

```java
private int getResult_imperative(List<String> strings) {  
    int result = 0;  
    for (String string : strings){  
        if(isDigit(string.charAt(0))) continue;  
        if (string.contains("_")) continue;  
        result += string.length();  
    }  
    return result;  
}
```
We notice that we manually have to do a couple of things 😤

-   Declare a result variable to keep track of the result
-   Loop through the Strings
-   Write two if statements (which could be much more complex than this case)
-   Add the length of each one to the result


### Let’s check the declarative style (Streams) 🤩

```java
private int getResult_Declarative(List<String> strings){  
    return strings.  
            stream().  
            filter(s -> !isDigit(s.charAt(0))).  
            filter(s -> !s.contains("_")).  
            mapToInt(String::length).  
            sum();  
}
```

**So, what is different?** 👀

-   we get a Stream object by calling the  **_stream()_**  function
-   **(Intermediate operation)**  we apply to the filter function twice, for each time we specify a condition that only the elements we want to proceed to the next phase should meet.
-   **(Intermediate operation)** we map each String object to an int by calling the length method (using method reference style)
-   **(terminal operation)** we sum all the previous int values

## **Observations**🧠

Didn’t the second approach feel more straightforward? We specified  **what we wanted and not how we want to do it**. That is the spirit of declarative programming and the purpose of the Stream API in modern Java applications.

### **Here is an excellent [source](https://www.youtube.com/watch?v=1OpAgZvYXLQ&ab_channel=Devoxx) to get more in-depth regarding streams in Java.**
How to add Supabase to Nuxt.js
Tags: supabase, nuxt, firebase
Published: 2021-05-02 11:36:34

Yesterday, I tried Supabase for the first time. Within about 30 minutes, I had social login and password-based authentication set up. There was almost zero friction during the whole process and I was super impressed, especially after my horrible developer experience with AWS Cognito and Amplify Auth.

This is a quick guide on how you can add Supabase to a Nuxt.js application.

## Prerequisites
(1) You have a Nuxt.js application created using *npx create-nuxt-app* or through another method
(2) You have created a Supabase project and the Supabase key, Supabase URL

## How to add Supabase to Nuxt

**(1) Install Supabase**
```yarn add @supabase/supabase-js```

**(2) Add Supabase to plugins**
In the plugins folder
- Create a file ```supabase.client.js```
- Add the following code snippet (replace the key, url with your own)

```js
import { createClient } from '@supabase/supabase-js'
const SUPABASE_KEY = '<YOUR-KEY>'
export default ({ app }, inject) => {
  const supabaseUrl = '<YOUR-URL>'
  const supabaseKey = SUPABASE_KEY
  const supabase = createClient(supabaseUrl, supabaseKey)

  inject('supabase', supabase)
}
```
This will inject Supabase to our Nuxt project, and will be available as *this.$supabase* for us to use

**(3) Add the plugins file to nuxt.config.js**
In nuxt.config.js, add the following to plugins

```js
// ...
  plugins: [
    '@/plugins/supabase.client.js'
  ],
// ...
```

You can also use the alternative syntax
```js
// ...
  plugins: [
    { src: '@/plugins/supabase.client.js', ssr: false }
  ],
// ...
```
**(4) Use Supabase on any page**
```js
//...
methods: {
  signIn(){
    const { user, error } = await this.$supabase.auth.signIn({
        email: this.email,
        password: this.password
      })
      console.log(user, error)
  }
}
//...
```
That's it!

* * *

I'm really excited to see where @supabase_io goes in the coming weeks and months! I hope it keeps growing and adding more useful features.