teleren/devto huggingface dataset:
Adding Responsive Design to embedded YouTube videos with TailwindCSS
Tags: tailwindcss, nextjs
Published: 2022-04-02 09:36:56

YouTube does not offer a way to automatically resize and scale. Here is a list of steps to achieve this with Tailwind:

**1-** Install the plugin `@tailwindcss/aspect-ratio`
```
npm i @tailwindcss/aspect-ratio
``` 
**2-** Add the installed plugin to the Tailwind settings 
```
// tailwind.config.js 

plugins: [require("@tailwindcss/aspect-ratio")],
```
**3-** Add Responsive Design to your videos: 
```
<div class="aspect-w-16 aspect-h-9">
  <iframe src="https://youtu.be/NX_NW6bt6_s" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
```

**References** 

- [Sizing Images and Videos with Aspect Ratios with Tailwind CSS](https://youtu.be/NX_NW6bt6_s) (Link to YouTube)
- [@tailwindcss/aspect-ratio](https://www.npmjs.com/package/@tailwindcss/aspect-ratio) (Link to npm)
Upload file to Object Storage (S3) in Nest JS
Tags: nestjs, s3
Published: 2022-04-02 09:26:16

This is how to upload file to object storage like AWS S3, Minio, and another similarly in NestJS Framework.

I use package [nestjs-multer-extended](https://www.npmjs.com/package/nestjs-multer-extended)

Install package with yarn or npm

```
yarn add nestjs-multer-extended
```

In your module

```
import { MulterExtendedModule } from 'nestjs-multer-extended';
```

```
@Module({
    imports: [
        MulterExtendedModule.register({
    awsConfig: {
        accessKeyId: process.env.AWS_ACCESS_KEY_ID,
        secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
        region: process.env.AWS_DEFAULT_REGION,
    },
    bucket: process.env.AWS_BUCKET,
    basePath: 'public',
    fileSize: 1 * 1024 * 1024,
    endpoint: process.env.AWS_ENDPOINT,
});
    ],
})
```

In your controller

```
@UseInterceptors(AmazonS3FileInterceptor('path', { dynamicPath: 'folder_name_or_root', randomFilename: true }))
  @Post()
  async create(@UploadedFile() file, @Body() createProductGalleryDto: CreateProductGalleryDto) {
    if (file) {
      createProductGalleryDto.path = file.key;
    }
    return await this.productGalleryService.create(createProductGalleryDto);
  }
```

You can save file path into database with name "file.key:
Survey: Combining Modular Skills in Multitask Learning
Tags: deeplearning, datascience
Published: 2022-04-02 08:51:47

##　選定理由

MSR(Microsoft Research)の研究、あのYoshua Bengio氏も共著ということで注目した
paper: https://arxiv.org/pdf/2202.13914.pdf
Code: https://github.com/McGill-NLP/polytropon

##　概要
[課題] タスクやデータ分布の変化に対してロバストなMTLを行いたい
[従来] タスクに対し明示的スキルを組み合わせて解く方式(skill方式)とタスク間で表現学習された知識を共有する方式(sharing方式)がある。前者ではスキルに対するエキスパート知識が必要であり、後者ではタスク数が増えるに従ってモデルパラメータが増大したり新しいタスクに対する対応には再学習やドメイン適応等が必要となる欠点があった。
[提案] 各タスクは再利用可能な潜在的スキルの組み合わせによって解かれるという仮定のもと、スキルを組み合わせるMTLの枠組みを提案
[効果]タスクやデータ分布に対する汎化性能が高く、タスク数が増えてもモデルパラメータが増大しない。実験では強化学習とFew-shot Adapatationの実験でベースラインを超える性能を確認。

##　潜在的スキル組み合わせMTL

各タスクは再利用可能な潜在的スキルの組み合わせによって解かれると仮定する。スキルセットを組み合わせる行列Zを推定することで各タスクを解くのに必要なスキルの組み合わせ方を学習する

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/393alk6ifa001acanzxx.png)
 
再利用可能な潜在的スキルの組み合わせには以下のグラフィカルモデルを仮定。xは観測、yがラベル、τがタスク、Sがスキル、Zはタスクとスキルと結びつけるタスク数×スキル数のバイナリ行列、αはバイナリ行列に対する事前分布、φは特定スキルに関するモデルパラメータである。
 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h9vqd3sj45d4qq5vw857.png)

バイナリ行列のような離散的な分布は微分不可能であるため、End-to-Endの勾配降下法の枠組みで学習することはできない。そこで、バイナリ行列に近い信号を表現可能かつ微分可能なGumbel-sigmoidによる定式化をおこなっている(以下)

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

###　Inductive Bias
学習が失敗する典型的パターンとしてバイナリ行列Zが高エントロピー、つまりスパースに乏しい行列が学習されてしまうことが考えられる。これに対処するためにIndian Buffet Processによる Inductive Bias（問題が持つ固有の構造が解けるように制限をかけること） を導入し、バイナリ行列のスパース性を高める正則化として利用している。αはIBPにおけるハイパーパラメータである。

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ns6xqvbuovvukcqbu69c.png)
 
又、φよりもZに対する学習率を高めることでもInductive Biasの効果が得られる。(Two-speed Learning Rateと呼んでいる)

##　実験

１６０個のNLPタスクを内包するCrossFitでのFew-shot AdaptationにおいてSkilled方式は従来のMTLで主流であったShared方式やタスク別での学習(Private方式)より大幅な性能改善を示した。なお、Shared方式の場合はZは1×1の単位行列となる。

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

###　学習されたスキルに関する分析

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/22k0f0m48ncdfobmhdnz.png)

DiscreteはZのエントロピー、SparsityはZのゼロ要素率、Usageは特定スキルへの偏りを示すエントロピーである。スキル数が多いほどSparsityは下がるのはスキルに多様性があるほど小さいスキルセットで学習しようとすることを示す。
This week’s newsletter is out! (02-04-2022) - Hypothermia and then sunshine, and then starvation & thirst
Tags: javascript, tech, webdev, discuss
Published: 2022-04-02 08:46:43

---
title: This week’s newsletter is out! (02-04-2022) - Hypothermia and then sunshine, and then starvation & thirst
published: true
description: Another week of great javascript, tech and web development links.
tags: javascript, tech, webdev, discuss
---

Hypothermia and then sunshine, and then starvation & thirst

https://markjgsmith.substack.com/p/mark-smiths-newsletter-02-04-2022?s=w

Would love to hear any comments and feedback you have.

[@markjgsmith](https://twitter.com/markjgsmith)
Today's Fun Joke For Developers - Daily Developer Jokes
Tags: jokes, dailydeveloperjokes
Published: 2022-04-02 08:00:04

---
title: "Today's Fun Joke For Developers - Daily Developer Jokes"
description: "Check out today's daily developer joke! (a project by Fred Adams at xtrp.io)"
series: "Daily Developer Jokes"
published: true
tags: #jokes, #dailydeveloperjokes
---

Hi there! Here's today's Daily Developer Joke. We hope you enjoy it; it's a good one.

![Joke Image](https://private.xtrp.io/projects/DailyDeveloperJokes/public_image_server/images/5e1258ab6087f.png)

---

For more jokes, and to submit your own joke to get featured, check out the [Daily Developer Jokes Website](https://dailydeveloperjokes.github.io/). We're also open sourced, so feel free to view [our GitHub Profile](https://github.com/dailydeveloperjokes).

### Leave this post a ❤️ if you liked today's joke, and stay tuned for tomorrow's joke too!

_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:___ Where did the parallel function wash its hands?

___A:___ Async
 -->
MediaClasses
Tags: css, mediaquery, javascript, beginners
Published: 2022-04-02 07:49:36

Wouldn't it be nice to be able to do without those ugly media-queries in CSS?
Just a class for the respective width and that's it?

**No problem with a little Javascript!**

First, we define the desired screen widths and the corresponding class names in an object:

```js
const breakpoints = [
  { width: "36em", class: "small" },
  { width: "64em", class: "medium" },
  { width: "99em", class: "large" }
];
```
With the following query, we find out the appropriate width of the screen:

```js
if (window.matchMedia(`(max-width: ${breakpoint.width})`).matches)
```

Now just add the class (don't forget to delete the old one first) to the body tag:

```js
document.body.removeAttribute("class");
document.body.classList.add(breakpoint.class);
```
Put all this into a small function and call it at the beginning and at every change of the viewport:

```js
window.addEventListener("DOMContentLoaded", mediaClasses);
window.addEventListener("resize", mediaClasses);
```

A small example here in this [codepen](https://codepen.io/koljal/pen/xxPNZdB).
A somewhat larger one in this [template on GitHub](https://github.com/KoljaL/ProgressiveResponsiveLayout).
Principal Component Analysis (PCA) Theory
Tags: machinelearning, datascience, python, ai
Published: 2022-04-02 06:58:11


[![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tga5pmubzmna6hs2z10m.png)](https://laid-back-scientist.com/en/pca-theory)

Principal component analysis is a method of summarizing the information in multidimensional data observed for features that are correlated with each other into new features expressed as a linear combination of the original features, with as little loss of information as possible.

The data to be classified by machine learning is often highly dimensional, well beyond three dimensions. This makes data visualization difficult and computationally expensive.

Even in such cases, principal component analysis can be used to compress dimensions and project the data into a 1D line, 2D plane, or 3D space to visually grasp the data structure.

This article describes the basic theory behind principal component analysis.

👇
https://laid-back-scientist.com/en/pca-theory
June1-2: Free Virtual IoT OS Tech Conference
Published: 2022-04-02 06:02:55

The most inspired event for developers! You’re invited to talk, to share, to express, to discover, to explore the most cutting-edge advancements in IoT&Embedded with the others!

The 2021 RT-Thread IoT OS Tech Conference has 1500+ developers registered for the conference, over 20 topics were shared, featured on the open-source RT-Thread OS projects and the new development RT-Smart Micro-Kernel OS, RISC-V ecosystems and associated manufacturers introduced, STM32 ecosystems, embedded projects showcase, IoT security, trending technical knowledge such as AI, ROS, Rust, Micropython, and more!

The 2022 RT-Thread IoT OS Global Tech Conference will continue kicking off with unique insights, exciting innovative technologies, inspiring projects showcases.


So join us to experience the next generation of IoT innovation.

**Register Now:** https://bit.ly/3GNujSQ

**Call for Proposal:** https://forms.gle/VytZsuTstebyqkA4A

## About RT-Thread IoT OS:
RT-Thread is an open-source embedded real-time operating system, with its rich middle-tier components and extensive hardware and software ecosystem delivering robust support for the Internet of Things (IoT) industry. Since its inception in 2006, RT-Thread has powered 1 billion devices, which includes applications for wearable devices, smart home appliances, energy, automotive electronics, medical electronics, consumer electronics, and many other industries.

Go to RT-Thread Github: https://github.com/RT-Thread/rt-thread
Brief Summary : Dart Variable
Published: 2022-04-02 05:29:28


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e1d6gguvk6i05l7j49o1.png)
This post may helpful for those who need quick remind of Dart grammar, or a programmer from a different language learning Dart.

# Basic

> Variables store references.
> 

# var

```dart
var language = 'dart';
```

- Mutable variable keyword

# By Type

```dart
String language = 'dart';
```

- You can specify the type in order to declare variable.

# final & const

```dart
final fruits = {
	1: 'apple',
	2: 'orange'
};
const animals = {
	1: 'dog',
	2: 'cat'
};

fruits[1] = 'banana'; // NO ERROR
animals[1] = 'monkey'; // ERROR
```

- There’re similar in sense that they can’t be changed once you assign a value to them.

## The Difference Between “final” and “const” keyword

- `final` can’t be changed once you assign a value.
- `const` is also like that, but in advance, they require more rules
    - The value that you’re going to assign should be a `compile-time constant`
        - `compile-time constant` means a constant value that is already fixed by the time when dart compile process.
        - For example, String literals that dose not contain interpolated expression and expression must be one of these(null, numeric, string, or boolean)
- Also, after assigning a value, variables annotated with `final` can’t be reassigned, but it’s fields can.
- Unlike `final`, variables annotated with `const` can’t be reassigned, both itself ant it’s sub fields.

# late

```dart
late String onlyKnowAfterInitialization;

onlyKnowAfterInitialization = 'hello world';
```

- Keyword that’s used in below cases.
    - You need to assign a value after you declare it.
    - You want to use lazy assignment.
        - For example, when you need to access `this` in order to assign a value.
- If the value of a variable annotated with `late` keyword needs to be computed, the computation will not happen unless the variable is actually used in somewhere.

Cheers!

<a href="https://www.buymeacoffee.com/swimmingkiim" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/arial-yellow.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>
100 Days of Code: The Complete Python Pro Bootcamp for 2022 - Day 1 (Band Name Generator
Published: 2022-04-02 04:18:05

Exercise 1 - Printing
````python
#Write your code below this line 👇
print("Day 1 - Python Print Function") 
print("The function is declared like this:")
print("print('what to print')") 
```
Exercise 2 - Debugging Practice
````python
#Fix the code below 👇
print("Day 1 - String Manipulation") 
print('String Concatenation is done with the "+" sign.')
print('e.g. print("Hello " + "world")')
print("New lines can be created with a backslash and n.")
```
Exercise 3 - Input Function
````python
#Write your code below this line 👇
print(len(input("What is your name?")))
```
Exercise 4 - Variables
````python
#🚨 Don't change the code below 👇
a = input("a: ")
b = input("b: ")
#🚨 Don't change the code above 👆

####################################
#Write your code below this line 👇

a,b = b,a

#Write your code above this line 👆
####################################

#🚨 Don't change the code below 👇
print("a: " + a)
print("b: " + b)
```
Project 1 - Band name generator
````python
#1. Create a greeting for your program.
print("Welcome to the Band Name Generator \n")
#2. Ask the user for the city that they grew up in.
city = input("Whats the name of the city where you grew up? \n ")
#3. Ask the user for the name of a pet.
pet_name = input("Name of pet? \n ")
#4. Combine the name of their city and pet and show them their #band name.
print("Your band name could be " + city + " " + pet_name +"")
#5. Make sure the input cursor shows on a new line, see the #example at:
#https://replit.com/@appbrewery/band-name-generator-end
```
How to handle duplicate lambda function invocations
Published: 2022-04-02 04:07:03

AWS Lambda is an event-driven, serverless computing platform. It helps to run code without controlling or managing a server. We can focus on code only. Lambda is an event-driven service it requires some trigger to run the function. If there is any failure in the lambda function, then lambda retries again and runs the code. But sometimes, it is not easy to find the code error. For example, we use nodejs in the AWS lambda function, and on each trigger, the nodejs function runs and is executed successfully. If you look into metric, it shows it as an error. It is an AWS lambda property that if there is an error then it keeps retrying. So even if the function is executed successfully, it is marked as an error lambda keep retry. 

![screenshot of lambda metric](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6oy9wkg7fymxi2a7oelz.png)

There are many ways to handle this. I am adding two ways that I have tried and worked for us.
* AWS Lambda has an option to set the retry attempt. It uses to decide how many times lambda will retry to run the code on error. Go to Lambda, Functions, and then click on the lambda function for that you want to set the retry attempts. In the configuration, open asynchronous invocation and click on edit to set the retry attempts. Set the retry attempts to zero so that it will not run the lambda function multiple times. The disadvantage of this approach is that if there is an error then also lambda will not retry.

![screenshot of lambda configuration](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ncqzdjib5c68mnq5s5ml.png)
* When AWS Lambda runs the function, it passes a context object to the handler.
`module.exports.handler = (event, context, callback)`.
One of the properties of the [context](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-context.html) object is awsRequestId. awsRequestId is used to identify the invocation request and is unique for each invocation. We can save the requestId in the database before the function execution finish. On the next invocation, we can check and verify requestId is the same or not. If the requestId is the same then we can skip it. For example, we save the requestId in the SQL table that has auto-increment id. In the next invocation, we fetch the requestId from the table that has the highest id and check if it is the same as the requestId of the current invocation.

There is one more better way to handle it. I will add that too next time. I am still trying and testing it.
Update: If we add return in the handler function then it will exit process and stop the lambda function too. We are doing async task in the lambda and we use promise to handle that.

```
module.exports.handler = async (event) => {
  const promise = new Promise((resolve, reject) => {
/*
do the async task here. if error use reject and if success then use the resolve
*/
});
return promise;
```
Once promise is resolved or rejected, node process will exit with success or failure. If it is success then there will be no duplicate invocation.
Automatically deploy your react site with GitHub and Netlify
Tags: automation, react, github, netlify
Published: 2022-04-02 03:48:44

Hi guys, this is my first article on [Dev.to](dev.to) platform
Today I am going to show you how you can automate your ReactJS deployments on Netlify.

## Prerequisites:

- NPM and NodeJS installed.
- Understanding of React.
- Understanding of git and GitHub.
- Free Netlify and GitHub accounts.

## Step 1: Setup ReactJS app

`npx create-react-app my-portfolio`

### NPX

> npx is a CLI tool whose purpose is to make it easy to install and manage dependencies hosted in the NPM registry. This is awesome because sometimes you just want to use some CLI tools but you don’t want to install them globally just to test them out. This means you can save some disk space and simply run them only when you need them. 

## Step 2: Set up GitHub repository

Login to your GitHub account and create a new repository, in the **Initialize this repository with** section leave everything unchecked

## Step 3: Link your local code to GitHub repository

Go to the my-portfolio folder created earlier and do the following:
Rename local master branch to main:
`git branch -M main`
Add remote repository:
`git remote add origin YourGithubRepoUrlHere`
Push local code to GitHub:
`git push -u origin main`

## Step 4: Link Netlify to GitHub repository

- Login to your Netlify account.
- Go to the Sites tab and click on Add New Site button.
- Select Import existing project.
- Select GitHub in **Connect to Git Providers**.
- Pick the newly created repository.
- Make sure that the branch to deploy is main
- Click deploy site
Your site will be deployed and now whenever there is any change main branch of GitHub, Netlify will automatically build and deploy your site with latest changes.

## Bonus: Set up dev branch so you can create merge requests and get preview before deploying on the url

We can create a development branch in the repository where we can do all the changes and when we are confident with our code, we can create a merge request from development branch to main branch, before merging, Netlify will provide us with a deploy preview, on a separate URL, we can test it to see if our website functions as required and then can merge our code into main.

That's all for this article, Goodbye :)
Neo4j basics
Tags: feynmantechnique, todayilearned, neo4j, beginners
Published: 2022-04-02 02:32:35

## What is a graph?

A **graph** is a set of objects in which some pairs of the objects are connected. The objects are known as **nodes** and the connections are known as **relationships**. With these two elements, we can solve real-world problems by creating or inferring connections between objects. We can also create predictions given the strength of the connections.


![A set of connected circles](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tsmnz6356og96gri7tc2.png)

## How are graphs structured?

In an **undirected graph**, the relationships are bi-directional or symmetric; in a **directed graph**, the relationships have one direction.


![Undirected graph vs directed graph](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qeipleynitaoi4lcn3r2.png)

In a **weighted graph**, the relationships carry measurable values such as cost, time, distance or priority.


![Weighted graph](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hulgqkaaw30wqn7r8vwd.png)


The structure of a graph enables **traversal**. The process consists of following the relationships. With Neo4j's Cypher query language, relationships are not be followed multiple times.

## Some common use-cases for graphs

- **E-commerce and real-time recommendations**:
Recommendations like "People who bought {Product X} also bought…" can be generated by having a proportion of the graph be traversed. In this example, you traverse from one Product node to the Persons nodes who have purchased that product and then to the subsequent Products nodes that they have bought.

- **Investigative journalism**:
The graph known as **Panana Papers** was created to identify possible corruption based upon the relationships between people, companies, and most importantly financial institutions.

- **Network and IT operations**:
A typical graph would describe how information flows through a system and how components of a network are related

- **Transportation and logistics**:
A typical graph would describe how locations are related and the distances between them
¿Cómo hacer un pull request a Github? 🤔
Tags: git, github, webdev, opensource
Published: 2022-04-02 01:23:55

## ¿Cómo hacer un pull request a Github?
Vamos directo al grano. Para hacer un pull request a Github sigue los siguientes pasos:

1. Hacer un fork del repositorio original con el cual se quiere colaborar.

2. Clonar el repositorio.

3. Crear una rama nueva (acá sera donde haremos la colaboración)

4. Realizar el aporte.

5. Comitear los cambios.

6. Subir la rama al repositorio: `git push origin [nombre-rama]`

7. Ir a la rama que acabamos de subir a Github y crear el pull request. 

Eso es todo. 

Este video me ayudó mucho, se los recomiendo. 

{% youtube Zqft6yNRuNs %}
🤨 What is N+1 problem?
Tags: sql, beginners, database, mysql
Published: 2022-04-01 23:35:54

## 💎 What is it?
Simply put, a lot of SQL query executes in loop

## 💎 For example
There are two tables in database

▼ country table

| id | name |
| --------- | --------- |
|1|Japan|
|2|Poland|

▼ food table

| id | country_id | name |
| --------- |:---------:| -------:|
|1| 1 | sushi |
|2| 1 | ramen |
|3| 1 | udon |
|4| 2 | pierogi |
|5| 2 | kotlet |
|6| 2 | ziemniaki |

### Get country name
(I'm going to use ruby code)
```ruby
# SELECT * FROM country;
Country.all.each do |country|
  put country.name
    # Japan
    # Poland
end
```

### Call another table in loop
```ruby
# SELECT * FROM country;
Country.all.each do |country|
  put country.name
    # Japan
    # Poland

  # SELECT * FROM food WHERE country_id=1;
  # SELECT * FROM food WHERE country_id=2;
  # 😫 😭 if country table had 200 records, 200 query would be executed!!! OMG
  country.foods.each do |food|
    put food.name
      # sushi
      # ramen
      # udon
      # pierogi
      # kotlet
      # ziemniaki
  end
end
```

## 💎 How to solve it?
- **JOIN**
- **Eager Load**

#### JOIN
Integrate tables !
```ruby
# SELECT * FROM country INNER JOIN food ON country.id=food.country_id
# 😀 😀 only 1 query !
Country.join(:food).all.each do |country|
  country.foods.each do |food|
  end
end
```

#### Eager Load
Not integrate tables completely like JOIN, but executes SELECT at first !
```ruby
# SELECT * FROM country;
# SELECT * FROM food WHERE country_id IN(1,2)
# 😀 😀 only 2 queries !
Country.includes(:food).all.each do |country|
  country.foods.each do |food|
  end
end
```
⭐ if you want to use eager load in Ruby, just use **includes**

## 💎 Disadvantage
**Memory leak** because Join/Eager load need to execute huge SELECT at first

---
{% link https://dev.to/kaziusan/how-to-resolve-n1-problem-on-rails-fl2 %}