teleren/devto huggingface dataset:
Callbacks
Tags: javascript, beginners, discuss, tutorial
Published: 2022-04-21 17:26:29

## Callbacks

Functions are first class objects in JS. Meaning, you can pass a function as an argument into another function and
execute as per the need.
Asynchronous callbacks are often used as a continuation of the program after an async operation.
Callbacks are by far the most common way that asynchrony in JS programs (Before ES6 promises).

Imagine you have an ajax utility to fetch a resource and based upon the result you need to make further request

```js
// Nested callbacks
listen("click", function (event) {
  ajax("http://example.com/first", function (respone1) {
    if (response1) {
      ajax("http://example.com" + response1, function (response2) {
        console.log("Response", response1 + response2)
      })
    }
  })
})
```

One of the problem with Callbacks, easily we end up in nested callbacks, or sometimes it is referred to as
Callback hell. But there is more to Callback hell than just nested callbacks. It is difficult to imagine sequential way
of flow using callbacks, it is always jumpy when you have more async callbacks

```js
doA(function () {
  doC();

  doD(function () {
    doF();
  });

  doE();

});

doB();
```

*Outputs*: A -> B -> C -> D -> E -> F  (if all the above functions are async)

what if doA() or doD() aren't async. The output would be A -> C -> D -> F -> E

### Handling Failures

There is no norm how to handle error handling in Callbacks. Few libraries (NodeJs API) follow `err` first argument
approach followed by actual response.

```js
function response(err, data) {
  if (err) {
    console.error(err);
  } else {
    console.log(data);
  }
}
```

- Each team or library follows different conventions of handling callbacks and how they do error handling.
- `err` and `data` needs to be checked for all callbacks which adds more redundant code. Imagine you have to do for
  sequence of async callbacks A -> B -> C.
- Nesting along with error handling and redundant checks are the ones which make Callbacks Hell

### Trust issues with Callbacks

Imagine you have a third party utility to do certain async action and post that your callback executes some important
stuff.

```js
    thridParty.doAction(function () {
  // Important stuff for your app goes here which needs to be executed  
})

```

What if there is a bug in third party utility, and probably you must think of different possibilities

- If the callback is never called
- If the callback is called more than once
- How errors/exceptions are handled? Are they swallowed or propagated to the callback

Above trust issues with callback hell and more boilerplate code for error handling are bottleneck for scaling
applications. That lead us to next asynchronous way of handling `Promises`
Optionally control state from parent component in React
Tags: react, javascript, reacthooks, reactutils
Published: 2022-04-21 17:23:15


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

useFallbackState is almost same as useState, but it takes 3 props instead of 1.

1st prop is the same -> default value.

2nd prop is the state from the parent. It's optional if parent doesn't send a prop then local useState's value will be used.

3rd prop is the setState from the parent. This callback will be called every time state changes.


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

In above code state's have been managed inside component.

Lets say this component is used in 10 places and you get a scenario where you need to manage the state from parent in just 1 place.

Now instead of adding if…else… condition in 100s of places you could simple replace useState to useFallbackState. Please see the example below.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hhxt9ppl5z5ertf0ppzh.png)
New NFT Landing Page Template
Tags: nextjs, javascript, opensource, web3
Published: 2022-04-21 17:21:11

Hey guys I have just added new Template to [DEV.UI](https://dev-ui.vercel.app/)
Check out this [NFT landing Page](https://dev-ui.vercel.app/templates/nftlandingpage)

[Github Link](https://github.com/kumard3/dev-ui-templates/tree/main/template-9) [Deployed Link](https://dev-ui-templates.pages.dev/)
Getting started with contributing to open source – Real world example
Tags: opensource, beginners, tutorial
Published: 2022-04-21 17:19:53

Hey awesome people,


This is your step-by-step detailed with images guide on getting started contributing to opensource using real world package on github.

## How to find something to contribute on

Community make it super easy to get started with opensource you can even start by fix typos on `Readme` files in any repo.

### When you're a complete beginner

Although I encourage you to get involved in opensource community as soon as possible, I recommend starting a project with your favorite tech stack or language.

Get better understanding of what is going on inside these projects first before contributing.

👉 Visit [good first issue](https://goodfirstissue.dev/) and pic your favorite **language or framework**.

![Good first issue](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vct3ajamdse8qvk0dzfw.png)

👉 Click on the project you like.

👉 Open `Issues` tap on the project's github page.

👉 In the search field enter this phrase `is:issue is:open #good label:"good first issue"`.

[Continue reading](https://ahmednagi.com/getting-started-with-opensource/) ... 👇

[![Ahmednagi.com](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mquqqqv6e5zb9wa4hgib.png)](https://ahmednagi.com/getting-started-with-opensource/)
introduction to python
Published: 2022-04-21 17:12:04

## python
python is a high level programming language meaning it can be easily understood by humans.
python extension is .py
**python environment** is a space where you write your python code.examples visual studio,google colab.
_features of python_ include
easy to learn
simple
**fuctions**:keywords that perform specific tasks example;
1)print function`print("welcome")`-this displays the text in quotes that is welcome.other examples of functons are ;input
**identifiers**: names used to name 

##variables;RULES-
must not be keywords, 
digits cannot be used, they are case sensitive,
special characters cannot be used.
**data structures**-ways of organising or describing pieces of data example lists:`todo=list["cow","goat"]`,turple,sets
**data types**:integer-print(123),
float-numbers with decimal points,
boolean-true or false,
**commenting **in python by use of # and """,""":comments do not a[ppear on the code they just give instructions
給 PHP 開發者的 Docker 文件（六）
Published: 2022-04-21 16:57:19

（本文譯自〈[Docker for PHP Developers](https://www.newmediacampaigns.com/blog/docker-for-php-developers)〉）

## Nginx Docker容器（Container）

我們在實例化（instantiate）Nginx Docker 容器之前，需要先傳好虛擬主機的組態檔，在你的專案目錄下建立下面檔案 src/vhost.conf：

```conf
server {
  listen 80;
  index index.html;
  server_name docker.dev;
  error_log /var/log/nginx/error.log;
  access_log /var/log/nginx/access.log;
  root /var/www/public;
}
```

這是個基本（rudimentary）的 Nginx 虛擬主機，它會監聽 HTTP 80 埠的連入要求；它會回應對於主機名稱 docker.dev 的所有的 HTTP 要求；它把錯誤與存取紀錄輸出到指定的路徑檔案（並且這些檔案也符號連接（symlink）到容器的標準輸出與表準錯誤描述子（descriptor））；它定義了網站根目錄在 /var/www/public。我們在實例化時會把這份虛擬主機組態檔案拷貝到我們的 Docker 容器內。

在你的專案根目錄內執行下面的 Bash 指令，實例化並且跑一個基於我們訂製的 tutorial/nginx Docker 映像的新的 Nginx Docker 容器。

```sh
docker run \
  -d \
  -p 8080:80 \
  -v $(pwd)/src/vhost.conf:/etc/nginx/sites-enabled/vhost.conf \
  -v $(pwd)/src:/var/www \
  tutorial/nginx;
```

![docker run](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8sb9r563cbagvhzb4yfd.png)

我們使用旗標 `-d` 讓我們新的 Docker 容器在背景執行。

我們使用旗標 `-p` 來對映 Docker 母機（host）埠到容器埠，在本例中，我們叫 Docker 讓 Docker 母機（8080 埠）對映到 Docker 容器（80 埠）。

（待續…）
How the TypeScript Omit Type Works
Tags: typescript, javascript, webdev, tutorial
Published: 2022-04-21 16:47:34

TypeScript provides a number of utility types which are used to solve a particular problem that using types in Javascript creates. One very useful utility type used in TypeScript is the Omit type, which lets us customize an already existing type. Let's look at how it works.

### Custom Types
This article assumes you know how to create custom types in TypeScript. If you don't, [read my article on custom types here.](https://fjolt.com/article/typescript-creating-custom-types)

## TypeScript Omit Type
In TypeScript we often create custom types which let us ensure data conforms to a specific format. For example, if we wanted to create a custom User type which has four fields - `firstName`, `lastName`, `age` and `lastActive`, we could do something like this:

```javascript
type User = {
  firstName: string;
  lastName: string;
  age: number;
  lastActive: number;
}
```

Sadly, coding is not always straight foward. Sometimes, we want to use our type again, but remove certain elements from it, thus creating a new type. To do this, we can use `Omit<Type, Omissions>`. Omit accepts two values:

- The Type to base our new type on
- A Union Type listing all the fields to remove.
For example, if we want to take our User type, and remove age and lastActive, we could do the following:

```javascript
type User = {
  firstName: string;
  lastName: string;
  age: number;
  lastActive: number;
}
 
type UserNameOnly = Omit<User, "age" | "lastActive">
```

Now we have two types - `User`, which is our core user type, and `UserNameOnly`, which is our User type minus `age` and `lastActive`. Similarly, if we only wanted to remove `age`, this would suffice:

```javascript
type UserNameAndActive = Omit<User, "age">
```

Now we can use our new types anywhere in our code. This gives us flexibility to use a type, and transform it for specific circumstances. Here is an example of using both our new types:

```javascript
type User = {
  firstName: string;
  lastName: string;
  age: number;
  lastActive: number;
}
 
type UserNameOnly = Omit<User, "age" | "lastActive">
type UserNameAndActive = Omit<User, "age">

const userByName:UserNameOnly = {
    firstName: "John",
    lastName: "Doe",
};
const userWithoutAge:UserNameAndActive = {
    firstName: "John",
    lastName: "Doe",
    lastActive: -16302124725
}
```
Solving "Index for table 'user' is corrupt; try to repair it"
Tags: phpmyadmin, mysql
Published: 2022-04-21 16:47:06

---
title: Solving "Index for table 'user' is corrupt; try to repair it"
published: true
description: How to solve the table is corrupt error while using phpmyadmin
tags: phpmyadmin, mysql
//cover_image: https://direct_url_to_image.jpg
---

I was trying to assign access to a database to the default `root` user in my MariaDB database hosted via phpmyadmin and I was getting the following error.

```Can't open and lock privilege tables: Index for table 'user' is corrupt; try to repair it```

Although not the exact same error but I got similar errors to the above one when trying to perform similar functions like setting password for the user tables or adding privileges to a user. 

Let's see how to resolve issues like this:

* First we need to check the tables that have errors or issues.
* For this select the database where you need to repair the tables or find issues. Or select the database where you get errors similar to above.
* Select all the tables in the database at the bottom left corner and choose the option `Check table`. This will show the exact tables where the issue is.
![Checking the tables in phpmyadmin](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/09udsthmhw0y4ewy4nzq.png)
* Next the tables with the issue can be selected and repaired as shown in the image below. Alternatively, all the tables in the database can be selected and the option `Repair table` can be selected to repair the tables if possible.
![Repairing the tables in phpmyadmin](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ahhdk7bcfzna1xrsoqhe.png)

References: 
1. [Repair xampp mysql user table](https://stackoverflow.com/questions/57128891/how-repair-corrupt-xampp-mysql-user-table/66576509#66576509)
3. [Repair mysql db with phpmyadmin](https://www.thoughtco.com/repairing-mysql-database-with-phpmyadmin-2693966)
Ultimate Python Tutorial For Beginners
Published: 2022-04-21 16:34:56

Before we start knowing what Python is, Let's first know what a programing Language is. 

#**WHAT IS A PROGRAMMING LANGUAGE** 
A programming language is the passing of information to a computer to be able to perform various tasks such as playing games and so on. 
 
_**Note**_ Python is a HIGH level programming language. This means that it is closer to the human language since it is simple to understand and simple to manipulate. 

*For a Beginner one must grasp the following if at all you want to be good at Python as your first language if it's the case. 

- Variables 
- Operators
- Data Types 
- Conditions 
- Loops 
- Exception Handling 
- List 
- Dictionary
- String operators 
- File operators  

**Variables**
A variable is a name in reference to something. 
It's classified in 4 types 

  *Integer `int` - it is simply a whole number. For Example `1`
Paice, Abell y Daimler acuerdan licenciar la tecnología patentada
Published: 2022-04-21 16:04:41

Paice y Daimler han llegado a un acuerdo para licenciar la tecnología híbrida patentada.

Paice fue uno de los primeros líderes de los vehículos electrificados. La empresa obtuvo su primera patente de vehículo híbrido en 1994, mucho antes de que la mayoría de los fabricantes de automóviles comenzaran a centrarse seriamente en las formas de mejorar la eficiencia del combustible y reducir las emisiones. La tecnología de Paice demostró ser valiosa y ayudó a acelerar el crecimiento de la industria de los vehículos híbridos. Un análisis independiente concluyó que Paice es propietaria de las patentes de vehículos híbridos más dominantes en el mundo. 

"Hemos llegado a varios acuerdos de licencia en los últimos dos años sin necesidad de litigar. Estos acuerdos tienen un impacto duradero en nuestra comunidad al apoyar las buenas obras de la Abell Foundation", dijo el Presidente Ejecutivo de Paice, Frances Keenan.

Durante los primeros años de la compañía, Severinsky trabajó estrechamente con dos veteranos de la industria automotriz: Bob Templin, un miembro de la junta de Paice que había servido como ingeniero jefe de Cadillac y director técnico del Laboratorio de Investigación de GM; y Ted Louckes, un veterano de 40 años de General Motors que sirvió como Director de Operaciones de Paice y fue instrumental en el desarrollo de la tecnología híbrida de Paice junto con el Dr. Severinsky.

[Leer Mas...](https://estartit.tv)
GESAB y Fountainhead Control Rooms modernizan ocho centros de control de la NASA
Published: 2022-04-21 16:03:52

Los puestos de trabajo de más de 220 operadores han sido renovados con consolas de control 100% personalizadas a sus requerimientos técnicos y ergonómicos.

La Administración Nacional de Aeronáutica y el Espacio de Estados Unidos, NASA por sus siglas en inglés, ha completado ocho centros de control con un total de más de 220 operadores utilizando las soluciones de consolas de control de GESAB mediante su partner en Estados Unidos Fountainhead Control Rooms, Inc. Desde el año 2016 hasta 2020, GESAB ha instalado su mobiliario técnico en los centros NASA Launch Vehicle Data Center’s y NASA Mission Director’s Center’s situados de costa a costa de los Estados Unidos, en Cabo Cañaveral (Florida) y en la base aérea Vandenberg (California).

Estas salas, en colaboración con la NASA, han sido utilizadas también por el sector privado en lanzamientos de United Launch Alliance, proveedor de servicios de lanzamientos espaciales formada por Martin Space Systems y Boeing Defense, Space & Security y la mediática empresa creada por Elon Musk, SpaceX, primera empresa privada en alcanzar el hito de lanzar el primer vuelo tripulado desde suelo estadounidense.

La amplia experiencia del equipo de diseñadores e ingenieros de GESAB junto con el conocimiento de Fountainhead Control Rooms, Inc. del mercado americano de los centros de control, consiguió cumplir con las complejas características de la industria aeroespacial al proporcionar un modelo 100% personalizado tecnológicamente muy avanzado y con unas características ergonómicas específicas. Este proyecto ha permitido a la asociación entre GESAB y Fountainhead Control Rooms, Inc. aumentar su presencia en el sector y desarrollar proyectos para otras empresas.

Desde que la NASA comenzó a operar en 1958 se ha convertido en un líder mundial en investigación aeronáutica y aeroespacial, promoviendo la innovación y la aplicación de los últimos avances técnicos para lograr un conocimiento científico y éxitos tecnológicos. Su minucioso trabajo de investigación ha permitido a la sociedad comprender el sistema solar y así cambiar radicalmente la comprensión del universo. El desarrollo de la actividad de la NASA requiere equipos de vanguardia de alto rendimiento capaces de adaptarse a sus necesidades específicas lo que le llevó al cambio tecnológico y la modernización de las instalaciones de sus centros de control.

En palabras de Pere Sabaté, director ejecutivo y fundador de GESAB: "hemos tenido éxito en cumplir con los requisitos técnicos específicos establecidos por la NASA, así como proporcionar más espacio para el operador con la creación de una zona de conexión personalizada mejorando la ergonomía visual. Sin duda un excelente trabajo de todo nuestro equipo".

[Leer Mas...](https://estartit.tv)
Settling your priorities back on track...
Published: 2022-04-21 15:17:36

It feels weird to blog again after a couple of months away from the coding world. Actually, it feels weird being back in the coding world in general. The reason why I say this is because I, unintentionally, got caught up preparing for university that I did not leave too much time in my day to continue coding. Now that I am back, it feels as though I need to revisit the things I had learnt before I can proceed onto learning newer and more advanced things.

My time away has also allowed me to take things in and put things into perspective a little more. As I am more artistically inclined, I have found Three.js to be a fascinating realm of JavaScript as it involves both coding and 3D environments. In school, we have recently gotten to grips with C# and so far I can say that it has a lot of similarities with JavaScript.

Now that I am a student, in a completely foreign country, my ambition and determination to be the best coder I can be has been magnified because nothing is going to be given to me so I need to at least give 101% in order to achieve my short-term goals and ,eventually, the long term ones as well.
A magic hand using DXL and servo motors
Tags: opensource, tutorial, devjournal, luos
Published: 2022-04-21 15:30:35

Vik1501 (on Luos Discord) developed a quick demo to show the power of Luos, connecting different types of hardware.

{% embed https://www.youtube.com/embed/WU8Rqw-W0iY %}

Using topology detection, she prepared two applications: One using her hand to control the movement of the motors and another by copying the movement of the DXL motor.
i created rattle_wiki 🐍🌎🐍
Tags: showdev, python, programming, productivity
Published: 2022-04-21 15:04:12

Hello i created rattle_wiki it is working as a common as wikipedia but the speciality is it can read the results shown by the rattle_wiki.You can download it through our github now!

github account-https://github.com/rattleofficial/rattle_wiki
Run and attach to a Docker container with a tiny command
Tags: docker, bash, zsh, productivity
Published: 2022-04-21 15:01:36

---
title: Run and attach to a Docker container with a tiny command
published: true
description: 
tags: docker, bash, zsh, productivity
//cover_image: https://direct_url_to_image.jpg
---

> For more information, see [the Docker reference](https://docs.docker.com/engine/reference/run/#foreground)

This command runs an interactive (`-i`) container from the given image with an allocated tty (`-t`)

```bash
$ docker run -it image-name
```

You can make a convenience function to execute this with a short command and the image name as an argument by adding the following to your `.bashrc` or `.zshrc`:

```bash
# run detached container, start interactive session
dat() {
  image=${1}
  if [ -z "$image" ]; then
    echo Please provide an image name
    return
  fi

  docker run -it $image
}
```

To use:

```bash
dat image:tho
```

You'll need to reload your shell or run `source ~/.zshrc` (or `~/.bashrc`) for the file changes to take effect. 

Look you saved like 10 characters!

## So what?

Ok so it's a little more reasonable when you start adding more options to the command...

For example, I found myself needing to build and run a container with an explicit platform set because I'm on an M1 chip and they're just fun like that.

```bash
# ~/.zshrc
datp() {
  image=${1}
  if [ -z "$image" ]; then
    echo Please provide an image name
    return
  fi
  docker run -it --platform linux/x86_64 $image
}

dim() {
  image=${1}
  if [ -z "$image" ]; then
    echo Please provide an image name
    return
  fi

  docker build -t $image -f Dockerfile .
}

dimp() {
  image=${1}
  if [ -z "$image" ]; then
    echo Please provide an image name
    return
  fi

  docker build -t $image -f Dockerfile --platform linux/x86_64 .
}
```

Bam! With a `dimp` and a `datp`, I'm off to the races. The really slow races because I'm building for amd64 on an M1.

```bash
dimp myimage

datp myimage
```
Progressive Web Application: Statistics- Infographic
Tags: webdev, beginners, tutorial
Published: 2022-04-21 14:39:19



We love PWAs and seems like so do you 😉 That’s why you are here. In our previous blogs, [Testing a Progressive web app with LambdaTes](https://www.lambdatest.com/blog/testing-a-progressive-web-application-with-lambdatest/?utm_source=devto&utm_medium=organic&utm_campaign=apr21_sd&utm_term=sd&utm_content=blog)t and [Planning to move your app to a PWA: All you need to know](https://www.lambdatest.com/blog/planning-to-move-your-app-to-a-pwa-all-you-need-to-know/?utm_source=devto&utm_medium=organic&utm_campaign=apr21_sd&utm_term=sd&utm_content=blog), we have already gone through a lot on PWAs so we decided to cut is short and make it easier for you to memorize by making an Infographic, all in one place. Hope you like it.

Note: [Session history management](https://www.lambdatest.com/web-technologies/history?utm_source=devto&utm_medium=organic&utm_campaign=apr21_sd&utm_term=sd&utm_content=web_technologies) - The pushstate() and replaceState() methods of the history object are used to manipulate the browser’s session history.

![](https://cdn-images-1.medium.com/max/2800/0*3cwzwPWN1YCE7y8Z.jpg)

Note: [seamless attribute for iframes](https://www.lambdatest.com/web-technologies/iframe-seamless?utm_source=devto&utm_medium=organic&utm_campaign=apr21_sd&utm_term=sd&utm_content=web_technologies) - The seamless attribute allows the contents of iframe elements to flow into regular ancestor elements. Since the content is rendered by the browser, it is subject to all of the usual browser quirks and CSS styles that affect resolution or layout.

## Share this Image On Your Site

**Please include attribution to [www.lambdatest.com](https://www.lambdatest.com/?utm_source=devto&utm_medium=organic&utm_campaign=apr21_sd&utm_term=sd&utm_content=webpage) with this graphic.**

Note: [naturalWidth & naturalHeight image properties](https://www.lambdatest.com/web-technologies/img-naturalwidth-naturalheight?utm_source=devto&utm_medium=organic&utm_campaign=apr21_sd&utm_term=sd&utm_content=web_technologies) - The img-naturalwidth and img-naturalheight properties describe the intrinsic width and height of an image, as determined by its media type.

    <a target="_blank" href='https://www.lambdatest.com/blog/progressive-web-application-statistics-infographic/'>
      <img src='https://www.lambdatest.com/blog/wp-content/uploads/2018/04/PWA-1.jpg' alt='Progressive Web Application: 
       Statistics' 540px border='0' />
    </a>