All About Target Encoding For Classification Tasks

Background

Recently I did a project wherein the target was multi-class. It was a simple prediction task and the dataset involved both categorical as well as numerical features.

For those of you who are wondering what multi-class classification is: If you want to answer in ‘0 vs 1’, ‘clicked vs not-clicked’ or ‘cat vs dog’, your classification problem is binary; if you want to answer in ‘red vs green vs blue vs yellow’ or ‘sedan vs hatch vs SUV’, then the problem is multi-class.

Therefore, I was researching suitable ways to encode the categorical features. No points for guessing, I was taken to medium articles enumerating benefits of mean target encoding and how it outperforms other methods and how you can use category_encoders library to do the task in just 2 lines of code. However, to my surprise, I found that no article demonstrated this on multi-class target. I went to the documentation of category_encoders and found that it does not say anything about supporting multi-class targets. I dug deeper, scouring through the source code and realized that the library only works for binary or continuous targets.

So I thought: “Inside of every problem lies an opportunity.” — Robert Kiposaki

Going deep, I went straight for the original paper by _Daniele Micci-Barreca _that introduced mean target encoding. Not only for regression problem, the paper gives the solution for both binary classification as well as multi-class classification. This is the same paper that category_encoders cites for target encoding as well.

While there are several articles explaining target encoding for regression and binary classification problems, my aim is to implement target encoding for multi-class variables. However, before that, we need to understand how it’s done for binary targets. In this article, I cover an overview of the paper that introduced target encoding, and show by example how target encoding works for binary problems.

#multiclass-classification #target-encoding #categorical-data #binary-classification #multi-class #data analytic

What is GEEK

Buddha Community

All About Target Encoding For Classification Tasks

All About Target Encoding For Classification Tasks

Background

Recently I did a project wherein the target was multi-class. It was a simple prediction task and the dataset involved both categorical as well as numerical features.

For those of you who are wondering what multi-class classification is: If you want to answer in ‘0 vs 1’, ‘clicked vs not-clicked’ or ‘cat vs dog’, your classification problem is binary; if you want to answer in ‘red vs green vs blue vs yellow’ or ‘sedan vs hatch vs SUV’, then the problem is multi-class.

Therefore, I was researching suitable ways to encode the categorical features. No points for guessing, I was taken to medium articles enumerating benefits of mean target encoding and how it outperforms other methods and how you can use category_encoders library to do the task in just 2 lines of code. However, to my surprise, I found that no article demonstrated this on multi-class target. I went to the documentation of category_encoders and found that it does not say anything about supporting multi-class targets. I dug deeper, scouring through the source code and realized that the library only works for binary or continuous targets.

So I thought: “Inside of every problem lies an opportunity.” — Robert Kiposaki

Going deep, I went straight for the original paper by _Daniele Micci-Barreca _that introduced mean target encoding. Not only for regression problem, the paper gives the solution for both binary classification as well as multi-class classification. This is the same paper that category_encoders cites for target encoding as well.

While there are several articles explaining target encoding for regression and binary classification problems, my aim is to implement target encoding for multi-class variables. However, before that, we need to understand how it’s done for binary targets. In this article, I cover an overview of the paper that introduced target encoding, and show by example how target encoding works for binary problems.

#multiclass-classification #target-encoding #categorical-data #binary-classification #multi-class #data analytic

Jupyter Notebook Kernel for Running ansible Tasks and Playbooks

Ansible Jupyter Kernel

Example Jupyter Usage

The Ansible Jupyter Kernel adds a kernel backend for Jupyter to interface directly with Ansible and construct plays and tasks and execute them on the fly.

Demo

Demo

Installation:

ansible-kernel is available to be installed from pypi but you can also install it locally. The setup package itself will register the kernel with Jupyter automatically.

From pypi

pip install ansible-kernel
python -m ansible_kernel.install

From a local checkout

pip install -e .
python -m ansible_kernel.install

For Anaconda/Miniconda

pip install ansible-kernel
python -m ansible_kernel.install --sys-prefix

Usage

Local install

    jupyter notebook
    # In the notebook interface, select Ansible from the 'New' menu

Container

docker run -p 8888:8888 benthomasson/ansible-jupyter-kernel

Then copy the URL from the output into your browser:
http://localhost:8888/?token=ABCD1234

Using the Cells

Normally Ansible brings together various components in different files and locations to launch a playbook and performs automation tasks. For this jupyter interface you need to provide this information in cells by denoting what the cell contains and then finally writing your tasks that will make use of them. There are Examples available to help you, in this section we'll go over the currently supported cell types.

In order to denote what the cell contains you should prefix it with a pound/hash symbol (#) and the type as listed here as the first line as shown in the examples below.

#inventory

The inventory that your tasks will use

#inventory
[all]
ahost ansible_connection=local
anotherhost examplevar=val

#play

This represents the opening block of a typical Ansible play

#play
name: Hello World
hosts: all
gather_facts: false

#task

This is the default cell type if no type is given for the first line

#task
debug:
#task
shell: cat /tmp/afile
register: output

#host_vars

This takes an argument that represents the hostname. Variables defined in this file will be available in the tasks for that host.

#host_vars Host1
hostname: host1

#group_vars

This takes an argument that represents the group name. Variables defined in this file will be available in the tasks for hosts in that group.

#group_vars BranchOfficeX
gateway: 192.168.1.254

#vars

This takes an argument that represents the filename for use in later cells

#vars example_vars
message: hello vars
#play
name: hello world
hosts: localhost
gather_facts: false
vars_files:
    - example_vars

#template

This takes an argument in order to create a templated file that can be used in later cells

#template hello.j2
{{ message }}
#task
template:
    src: hello.j2
    dest: /tmp/hello

#ansible.cfg

Provides overrides typically found in ansible.cfg

#ansible.cfg
[defaults]
host_key_checking=False

Examples

You can find various example notebooks in the repository

Using the development environment

It's possible to use whatever python development process you feel comfortable with. The repository itself includes mechanisms for using pipenv

pipenv install
...
pipenv shell

Author: ansible
Source Code:  https://github.com/ansible/ansible-jupyter-kernel
License: Apache-2.0 License

#jupyter #python 

Target Encoding For Multi-Class Classification

This article is in continuation of my previous article that explained how target encoding actually works. The article explained the encoding method on a binary classification task through theory and an example, and how category-encoders library gives incorrect results for multi-class target. This article shows when _TargetEncoder of category_encoders fails, gives a snip of the theory behind encoding multi-class target, _and provides the correct code, along with an example.


When does the TargetEncoder fail?

Look at this data. Color is a feature, and Target is well… target. Our aim is to encode Color based on Target.

Image for post

Let’s do the usual target encoding on this.

import category_encoders as ce

ce.TargetEncoder(smoothing=0).fit_transform(df.Color,df.Target)

Image for post

Hmm, that doesn’t look right, does it? All the colors were replaced with 1. Why? Because TargetEncoder takes mean of all the Target values for each color, instead of probability.

#multi-class #categorical-variable #categorical-data #target-encoding #multiclass-classification #big data

Learn CRUD Operations in JavaScript by Building TODO APP

Today we're gonna learn how to do CRUD Operations in JavaScript by making a Todo App. Let's get started 🔥

This is the app we're making today:

App that we're making today

What is CRUD?

Image description

CRUD stands for -

  • C: Create
  • R: Read
  • U: Update
  • D: Delete

CRUD Fullform

CRUD is a type of mechanism that allows you to create data, read data, edit it, and delete those data. In our case, we're gonna make a Todo app, so we will have 4 options to create tasks, read tasks, update tasks, or delete tasks.

Understanding CRUD Principles

Before starting the tutorial, first, let's understand the CRUD principles. For that, let's create a very very simple Social Media Application.

Social Media App Project

Setup

Project Setup

For this project, we will be following these steps below:

  • Create 3 files named index.html, style.css, and main.js
  • Link the JavaScript and CSS file to index.html
  • Start your live server

HTML

Inside the body tag, create a div with a class name .container. There, we will have 2 sections, .left and .right 👇

<body>
  <h1>Social Media App</h1>
  <div class="container">

    <div class="left"></div>
    <div class="right"></div>

  </div>
</body>

On the left side, we will create our posts. On the right side, we can see, update, and delete our posts. Now, create a form inside the .left div tag 👇

<div class="left">
  <form id="form">
    <label for="post"> Write your post here</label>
    <br><br>
    <textarea name="post" id="input" cols="30" rows="10"></textarea>
    <br> <br>
    <div id="msg"></div>
    <button type="submit">Post</button>
  </form>
</div>

Write this code inside the HTML so that we can display our post on the right side 👇

<div class="right">
  <h3>Your posts here</h3>
  <div id="posts"></div>
</div>

Next, we'll insert the font-awesome CDN inside the head tag to use its fonts in our project 👇

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" />

Now, we're gonna make some sample posts with delete and edit icons. Write this code inside the div with the id #posts: 👇

<div id="posts">
  <div>
    <p>Hello world post 1</p>
    <span class="options">
      <i class="fas fa-edit"></i>
      <i class="fas fa-trash-alt"></i>
    </span>
  </div>

  <div >
    <p>Hello world post 2</p>
    <span class="options">
      <i class="fas fa-edit"></i>
      <i class="fas fa-trash-alt"></i>
    </span>
  </div>
</div>

The result so far looks like this:

HTML Markup result

CSS

Adding CSS for project 1

Let's keep it simple. Write these styles inside your stylesheet: 👇

body {
  font-family: sans-serif;
  margin: 0 50px;
}

.container {
  display: flex;
  gap: 50px;
}

#posts {
  width: 400px;
}

i {
  cursor: pointer;
}

Now, write these styles for the post div and option icons: 👇

#posts div {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.options {
  display: flex;
  gap: 25px;
}

#msg {
  color: red;
}

The results so far look like this:👇

The result after adding the css part project 1

JavaScript Part

Starting the javascript part

According to this flow chart, we will go forward with the project. Don't worry, I'll explain everything along the way. 👇

flow chart

Form Validation

First, let's target all the ID selectors from the HTML in JavaScript. Like this: 👇

let form = document.getElementById("form");
let input = document.getElementById("input");
let msg = document.getElementById("msg");
let posts = document.getElementById("posts");

Then, build a submit event listener for the form so that it can prevent the default behaviour of our App. At the same time, we will create a function named formValidation. 👇

form.addEventListener("submit", (e) => {
  e.preventDefault();
  console.log("button clicked");

  formValidation();
});

let formValidation = () => {};

Now, we're gonna make an if else statement inside our formValidation function. This will help us prevent users from submitting blank input fields. 👇

let formValidation = () => {
  if (input.value === "") {
    msg.innerHTML = "Post cannot be blank";
    console.log("failure");
  } else {
    console.log("successs");
    msg.innerHTML = "";
  }
};

Here's the result so far: 👇

7sb8faq21j5dzy9vlswj

As you can see, a message will also show up if the user tries to submit the form blank.

How to accept data from input fields

Whatever data we get from the input fields, we will store them in an object. Let's create an object named data. And, create a function named acceptData: 👇

let data = {};

let acceptData = () => {};

The main idea is that, using the function, we collect data from the inputs and store them in our object named data. Now let's finish building our acceptData function.

let acceptData = () => {
  data["text"] = input.value;
  console.log(data);
};

Also, we need the acceptData function to work when the user clicks the submit button. For that, we will fire this function in the else statement of our formValidation function. 👇

let formValidation = () => {
  if (input.value === "") {
    // Other codes are here
  } else {
    // Other codes are here
    acceptData();
  }
};

When we input data and submit the form, on the console we can see an object holding our user's input values. Like this: 👇

result so far on the console

How to create posts using JavaScript template literals

In order to post our input data on the right side, we need to create a div element and append it to the posts div. First, let's create a function and write these lines: 👇

let createPost = () => {
  posts.innerHTML += ``;
};

The backticks are template literals. It will work as a template for us. Here, we need 3 things: a parent div, the input itself, and the options div which carries the edit and delete icons. Let's finish our function 👇

let createPost = () => {
  posts.innerHTML += `
  <div>
    <p>${data.text}</p>
    <span class="options">
      <i onClick="editPost(this)" class="fas fa-edit"></i>
      <i onClick="deletePost(this)" class="fas fa-trash-alt"></i>
    </span>
  </div>
  `;
  input.value = "";
};

In our acceptdata function, we will fire our createPost function. Like this: 👇

let acceptData = () => {
  // Other codes are here

  createPost();
};

The result so far: 👇

Result so far

So far so good guys, we're almost done with project 1.

so far so good

How to delete a post

In order to delete a post, first of all, let's create a function inside our javascript file:

let deletePost = (e) => {};

Next up, we fire this deletePost function inside all of our delete icons using an onClick attribute. You'll write these lines in HTML and on the template literal. 👇

<i onClick="deletePost(this)" class="fas fa-trash-alt"></i>

The this keyword will refer to the element that fired the event. in our case, the this refers to the delete button.

Look carefully, the parent of the delete button is the span with class name options. The parent of the span is the div. So, we write parentElement twice so that we can jump from the delete icon to the div and target it directly to remove it.

Let's finish our function. 👇

let deletePost = (e) => {
  e.parentElement.parentElement.remove();
};

The result so far: 👇

deleting a post result

How to edit a post

In order to edit a post, first of all, let's create a function inside our JavaScript file:

let editPost = (e) => {};

Next up, we fire this editPost function inside all of our edit icons using an onClick attribute. You'll write these lines in HTML and on the template literal. 👇

<i onClick="editPost(this)" class="fas fa-edit"></i>

The this keyword will refer to the element that fired the event. In our case, the this refers to the edit button.

Look carefully, the parent of the edit button is the span with class name options. The parent of the span is the div. So, we write parentElement twice so that we can jump from the edit icon to the div and target it directly to remove it.

Then, whatever data is inside the post, we bring it back on the input field to edit it.

Let's finish our function. 👇

let editPost = (e) => {
  input.value = e.parentElement.previousElementSibling.innerHTML;
  e.parentElement.parentElement.remove();
};

The result so far: 👇

Editing a post result

Take a Break!

Take a Break

Congratulations everyone for completing project 1. Now, take a small break!

How to Make a To-Do App using CRUD Operations

Let's make a todo app

Let's start making project 2, which is a To-Do App.

Project Setup

Project setup

For this project, we will be following these steps below:

  • Create 3 files named index.html, style.css, and main.js
  • Link the JavaScript and CSS files to index.html
  • Start our live server

HTML

Write this starter code inside the HTML file: 👇

<div class="app">
  <h4 class="mb-3">TODO App</h4>

  <div id="addNew" data-bs-toggle="modal" data-bs-target="#form">
    <span>Add New Task</span>
    <i class="fas fa-plus"></i>
  </div>
</div>

The div with an id addNew is the button that will open the modal. The span will be displayed on the button. The i is the icon from font-awesome.

We're going to use bootstrap to make our modal. We'll use the modal to add new tasks. For that, add the bootstrap CDN link inside the head tag. 👇

<link
  href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
  rel="stylesheet"
  integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
  crossorigin="anonymous"
/>

<script
  src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
  integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
  crossorigin="anonymous"
></script>

To see the created tasks, we'll use a div with an id tasks, inside the div with the classname app. 👇

<h5 class="text-center my-3">Tasks</h5>

<div id="tasks"></div>

Insert the font-awesome CDN inside the head tag to use fonts in our project 👇

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" />

Copy and paste the code below which are from the bootstrap modal. It carries a form with 3 input fields and a submit button. If you want then you can search Bootstrap's website by writing 'modal' in the search bar.

<!-- Modal -->
<form
  class="modal fade"
  id="form"
  tabindex="-1"
  aria-labelledby="exampleModalLabel"
  aria-hidden="true"
>
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Add New Task</h5>
        <button
          type="button"
          class="btn-close"
          data-bs-dismiss="modal"
          aria-label="Close"
        ></button>
      </div>
      <div class="modal-body">
        <p>Task Title</p>
        <input type="text" class="form-control" name="" id="textInput" />
        <div id="msg"></div>
        <br />
        <p>Due Date</p>
        <input type="date" class="form-control" name="" id="dateInput" />
        <br />
        <p>Description</p>
        <textarea
          name=""
          class="form-control"
          id="textarea"
          cols="30"
          rows="5"
        ></textarea>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
          Close
        </button>
        <button type="submit" id="add" class="btn btn-primary">Add</button>
      </div>
    </div>
  </div>
</form>

The result so far: 👇

Html file setup

We're done with the HTML file setup. Let's start the CSS.

CSS

Adding the css part

Add these styles in the body so that we can keep our app at the exact center of the screen.

body {
  font-family: sans-serif;
  margin: 0 50px;
  background-color: #e5e5e5;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

Let's style the div with the classname app. 👇

.app {
  background-color: #fff;
  width: 300px;
  height: 500px;
  border: 5px solid #abcea1;
  border-radius: 8px;
  padding: 15px;
}

The result so far: 👇

App styles

Now, let's style the button with the id addNew. 👇

#addNew {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: rgba(171, 206, 161, 0.35);
  padding: 5px 10px;
  border-radius: 5px;
  cursor: pointer;
}
.fa-plus {
  background-color: #abcea1;
  padding: 3px;
  border-radius: 3px;
}

The result so far: 👇

Add new task Button

If you click on the button, the modal pops up like this: 👇

Modal poping

Add the JS

Adding the JavaScript

In the JavaScript file, first of all, select all the selectors from the HTML that we need to use. 👇

let form = document.getElementById("form");
let textInput = document.getElementById("textInput");
let dateInput = document.getElementById("dateInput");
let textarea = document.getElementById("textarea");
let msg = document.getElementById("msg");
let tasks = document.getElementById("tasks");
let add = document.getElementById("add");

Form Validations

We cannot let a user submit blank input fields. So, we need to validate the input fields. 👇

form.addEventListener("submit", (e) => {
  e.preventDefault();
  formValidation();
});

let formValidation = () => {
  if (textInput.value === "") {
    console.log("failure");
    msg.innerHTML = "Task cannot be blank";
  } else {
    console.log("success");
    msg.innerHTML = "";
  }
};

Also, add this line inside the CSS:

#msg {
  color: red;
}

The result so far: 👇

Image description

As you can see, the validation is working. The JavaScript code doesn't let the user submit blank input fields, otherwise you're gonna see an error message.

How to collect data and use local storage

Whatever inputs the user writes, we need to collect them and store them in local storage.

First, we collect the data from the input fields, using the function named acceptData and an array named data. Then we push them inside the local storage like this: 👇

let data = [];

let acceptData = () => {
  data.push({
    text: textInput.value,
    date: dateInput.value,
    description: textarea.value,
  });

  localStorage.setItem("data", JSON.stringify(data));

  console.log(data);
};

Also note that this will never work unless you invoke the function acceptData inside the else statement of the form validation. Follow along here: 👇

let formValidation = () => {

  // Other codes are here
   else {

    // Other codes are here

    acceptData();
  }
};

You may have noticed that the modal doesn't close automatically. To solve this, write this small function inside the else statement of the form validation: 👇

let formValidation = () => {

  // Other codes are here
   else {

    // Other codes are here

    acceptData();
    add.setAttribute("data-bs-dismiss", "modal");
    add.click();

    (() => {
      add.setAttribute("data-bs-dismiss", "");
    })();
  }
};

If you open Chrome dev tools, go to the application and open the local storage. You can see this result: 👇

Local Storage Result

How to create new tasks

In order to create a new task, we need to create a function, use template literals to create the HTML elements, and use a map to push the data collected from the user inside the template. Follow along here: 👇

let createTasks = () => {
  tasks.innerHTML = "";
  data.map((x, y) => {
    return (tasks.innerHTML += `
    <div id=${y}>
          <span class="fw-bold">${x.text}</span>
          <span class="small text-secondary">${x.date}</span>
          <p>${x.description}</p>
  
          <span class="options">
            <i onClick= "editTask(this)" data-bs-toggle="modal" data-bs-target="#form" class="fas fa-edit"></i>
            <i onClick ="deleteTask(this);createTasks()" class="fas fa-trash-alt"></i>
          </span>
        </div>
    `);
  });

  resetForm();
};

Also note that the function will never run unless you invoke it inside the acceptData function, like this: 👇

let acceptData = () => {
  // Other codes are here

  createTasks();
};

Once we're done collecting and accepting data from the user, we need to clear the input fields. For that we create a function called resetForm. Follow along: 👇

let resetForm = () => {
  textInput.value = "";
  dateInput.value = "";
  textarea.value = "";
};

The result so far: 👇

Adding task cards

As you can see, there's no styles with the card. Let's add some styles: 👇

#tasks {
  display: grid;
  grid-template-columns: 1fr;
  gap: 14px;
}

#tasks div {
  border: 3px solid #abcea1;
  background-color: #e2eede;
  border-radius: 6px;
  padding: 5px;
  display: grid;
  gap: 4px;
}

Style the edit and delete buttons with this code: 👇

#tasks div .options {
  justify-self: center;
  display: flex;
  gap: 20px;
}

#tasks div .options i {
  cursor: pointer;
}

The result so far: 👇

Styles card templates

Function to delete a task

Look here carefully, I added 3 lines of code inside the function.

  • The first line will delete the HTML element from the screen,
  • the second line will remove the targetted Task from the data array,
  • and the third line will update the local storage with the new data.
let deleteTask = (e) => {
  e.parentElement.parentElement.remove();

  data.splice(e.parentElement.parentElement.id, 1);

  localStorage.setItem("data", JSON.stringify(data));

  console.log(data);
};

Now create a dummy task and try to delete it. The result so far looks like this: 👇

Image description

Function to edit tasks

Look here carefully, I added 5 lines of code inside the function.

  • Line 1 is targetting the task that we selected to edit
  • Lines 2, 3, and 4, are targetting the values [task, date, description] of the task that we selected to edit
  • line 5 is running the delete function to remove the selected data both from the local storage, HTML element, and data array.
let editTask = (e) => {
  let selectedTask = e.parentElement.parentElement;

  textInput.value = selectedTask.children[0].innerHTML;
  dateInput.value = selectedTask.children[1].innerHTML;
  textarea.value = selectedTask.children[2].innerHTML;

  deleteTask(e);
};

Now, try to create a dummy task and edit it. The result so far: 👇

Editing a Task

How to get data from local storage

If you refresh the page, you'll note that all of your data is gone. In order to solve that issue, we run a IIFE (Immediately invoked function expression) to retrieve the data from local storage. Follow along: 👇

(() => {
  data = JSON.parse(localStorage.getItem("data")) || [];
  console.log(data);
  createTasks();
})();

Now the data will show up even if you refresh the page.

Conclusion

Congratulations

Congratulations for successfully completing this tutorial. You've learned how to create a todo list application using CRUD operations. Now, you can create your own CRUD application using this tutorial.

Here's your medal for reading until the end. ❤️

Source: https://www.freecodecamp.org/news/learn-crud-operations-in-javascript-by-building-todo-app/

#javascript #crud #operator #todoapp 

Cómo Hacer Operaciones CRUD En JavaScript Creando Una Aplicación Todo

Hoy vamos a aprender cómo hacer operaciones CRUD en JavaScript creando una aplicación Todo. Empecemos 🔥

Esta es la aplicación que estamos haciendo hoy:

Aplicación que estamos haciendo hoy

¿Qué es CRUD?

descripción de la imagen

CRUD significa -

  • c: crear
  • R: Leer
  • U: Actualizar
  • D: Eliminar

CRUD de forma completa

CRUD es un tipo de mecanismo que le permite crear datos, leer datos, editarlos y eliminar esos datos. En nuestro caso, vamos a crear una aplicación Todo, por lo que tendremos 4 opciones para crear tareas, leer tareas, actualizar tareas o eliminar tareas.

Comprender los principios CRUD

Antes de comenzar el tutorial, primero, comprendamos los principios CRUD. Para eso, creemos una aplicación de redes sociales muy, muy simple.

Proyecto de aplicación de redes sociales

Configuración

Configuración del proyecto

Para este proyecto, seguiremos los siguientes pasos:

  • Cree 3 archivos llamados index.html, style.css y main.js
  • Vincule el archivo JavaScript y CSS a index.html
  • Inicie su servidor en vivo

HTML

Dentro de la etiqueta del cuerpo, crea un div con un nombre de clase .container. Ahí tendremos 2 secciones, .lefty .right👇

<body>
  <h1>Social Media App</h1>
  <div class="container">

    <div class="left"></div>
    <div class="right"></div>

  </div>
</body>

En el lado izquierdo, crearemos nuestras publicaciones. En el lado derecho, podemos ver, actualizar y eliminar nuestras publicaciones. Ahora, crea un formulario dentro de la etiqueta div .left 👇

<div class="left">
  <form id="form">
    <label for="post"> Write your post here</label>
    <br><br>
    <textarea name="post" id="input" cols="30" rows="10"></textarea>
    <br> <br>
    <div id="msg"></div>
    <button type="submit">Post</button>
  </form>
</div>

Escribe este código dentro del HTML para que podamos mostrar nuestra publicación en el lado derecho 👇

<div class="right">
  <h3>Your posts here</h3>
  <div id="posts"></div>
</div>

A continuación, insertaremos el CDN font-awesome dentro de la etiqueta de encabezado para usar sus fuentes en nuestro proyecto 👇

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" />

Ahora, vamos a hacer algunas publicaciones de muestra con íconos de eliminar y editar. Escribe este código dentro del div con el id #posts: 👇

<div id="posts">
  <div>
    <p>Hello world post 1</p>
    <span class="options">
      <i class="fas fa-edit"></i>
      <i class="fas fa-trash-alt"></i>
    </span>
  </div>

  <div >
    <p>Hello world post 2</p>
    <span class="options">
      <i class="fas fa-edit"></i>
      <i class="fas fa-trash-alt"></i>
    </span>
  </div>
</div>

El resultado hasta ahora se ve así:

Resultado de marcado HTML

CSS

Agregar CSS para el proyecto 1

Mantengámoslo simple. Escribe estos estilos dentro de tu hoja de estilo: 👇

body {
  font-family: sans-serif;
  margin: 0 50px;
}

.container {
  display: flex;
  gap: 50px;
}

#posts {
  width: 400px;
}

i {
  cursor: pointer;
}

Ahora, escribe estos estilos para los íconos de opción y div posteriores: 👇

#posts div {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.options {
  display: flex;
  gap: 25px;
}

#msg {
  color: red;
}

Los resultados hasta ahora se ven así: 👇

El resultado después de agregar el proyecto de parte css 1

Parte de JavaScript

Comenzando la parte de javascript

De acuerdo con este diagrama de flujo, seguiremos adelante con el proyecto. No te preocupes, te explicaré todo en el camino. 👇

diagrama de flujo

Validación de formulario

Primero, apuntemos a todos los selectores de ID del HTML en JavaScript. Así: 👇

let form = document.getElementById("form");
let input = document.getElementById("input");
let msg = document.getElementById("msg");
let posts = document.getElementById("posts");

Luego, cree un detector de eventos de envío para el formulario para que pueda evitar el comportamiento predeterminado de nuestra aplicación. Al mismo tiempo, crearemos una función llamada formValidation. 👇

form.addEventListener("submit", (e) => {
  e.preventDefault();
  console.log("button clicked");

  formValidation();
});

let formValidation = () => {};

Ahora, vamos a hacer una declaración if else dentro de nuestra formValidationfunción. Esto nos ayudará a evitar que los usuarios envíen campos de entrada en blanco. 👇

let formValidation = () => {
  if (input.value === "") {
    msg.innerHTML = "Post cannot be blank";
    console.log("failure");
  } else {
    console.log("successs");
    msg.innerHTML = "";
  }
};

Aquí está el resultado hasta ahora: 👇

7sb8faq21j5dzy9vlswj

Como puede ver, también aparecerá un mensaje si el usuario intenta enviar el formulario en blanco.

Cómo aceptar datos de campos de entrada

Cualesquiera que sean los datos que obtengamos de los campos de entrada, los almacenaremos en un objeto. Vamos a crear un objeto llamado data. Y crea una función llamada acceptData: 👇

let data = {};

let acceptData = () => {};

La idea principal es que, usando la función, recopilamos datos de las entradas y los almacenamos en nuestro objeto llamado data. Ahora terminemos de construir nuestra acceptDatafunción.

let acceptData = () => {
  data["text"] = input.value;
  console.log(data);
};

Además, necesitamos que la acceptDatafunción funcione cuando el usuario haga clic en el botón Enviar. Para eso, activaremos esta función en la instrucción else de nuestra formValidationfunción. 👇

let formValidation = () => {
  if (input.value === "") {
    // Other codes are here
  } else {
    // Other codes are here
    acceptData();
  }
};

Cuando ingresamos datos y enviamos el formulario, en la consola podemos ver un objeto que contiene los valores de entrada de nuestro usuario. Así: 👇

resultado hasta ahora en la consola

Cómo crear publicaciones usando literales de plantilla de JavaScript

Para publicar nuestros datos de entrada en el lado derecho, necesitamos crear un elemento div y agregarlo al div de publicaciones. Primero, creemos una función y escribamos estas líneas: 👇

let createPost = () => {
  posts.innerHTML += ``;
};

Los acentos graves son literales de plantilla. Funcionará como una plantilla para nosotros. Aquí, necesitamos 3 cosas: un div principal, la entrada en sí y el div de opciones que lleva los íconos de edición y eliminación. Terminemos nuestra función 👇

let createPost = () => {
  posts.innerHTML += `
  <div>
    <p>${data.text}</p>
    <span class="options">
      <i onClick="editPost(this)" class="fas fa-edit"></i>
      <i onClick="deletePost(this)" class="fas fa-trash-alt"></i>
    </span>
  </div>
  `;
  input.value = "";
};

En nuestra acceptdatafunción, activaremos nuestra createPostfunción. Así: 👇

let acceptData = () => {
  // Other codes are here

  createPost();
};

El resultado hasta ahora: 👇

resultado hasta ahora

Hasta ahora todo bien chicos, casi hemos terminado con el proyecto 1.

Hasta ahora, todo bien

Cómo eliminar una publicación

Para eliminar una publicación, en primer lugar, creemos una función dentro de nuestro archivo javascript:

let deletePost = (e) => {};

A continuación, activamos esta deletePostfunción dentro de todos nuestros íconos de eliminación usando un atributo onClick. Escribirá estas líneas en HTML y en el literal de la plantilla. 👇

<i onClick="deletePost(this)" class="fas fa-trash-alt"></i>

La thispalabra clave se referirá al elemento que disparó el evento. en nuestro caso, el thisse refiere al botón eliminar.

Mire con cuidado, el padre del botón Eliminar es el tramo con opciones de nombre de clase. El padre del lapso es el div. Entonces, escribimos parentElementdos veces para que podamos saltar del ícono de eliminar al div y apuntarlo directamente para eliminarlo.

Terminemos nuestra función. 👇

let deletePost = (e) => {
  e.parentElement.parentElement.remove();
};

El resultado hasta ahora: 👇

eliminar el resultado de una publicación

Cómo editar una publicación

Para editar una publicación, en primer lugar, creemos una función dentro de nuestro archivo JavaScript:

let editPost = (e) => {};

A continuación, activamos esta editPostfunción dentro de todos nuestros íconos de edición usando un atributo onClick. Escribirá estas líneas en HTML y en el literal de la plantilla. 👇

<i onClick="editPost(this)" class="fas fa-edit"></i>

La thispalabra clave se referirá al elemento que disparó el evento. En nuestro caso, el thisse refiere al botón editar.

Mire con cuidado, el padre del botón de edición es el tramo con opciones de nombre de clase. El padre del lapso es el div. Entonces, escribimos parentElementdos veces para que podamos saltar del ícono de edición al div y apuntarlo directamente para eliminarlo.

Luego, cualquier dato que esté dentro de la publicación, lo traemos de vuelta al campo de entrada para editarlo.

Terminemos nuestra función. 👇

let editPost = (e) => {
  input.value = e.parentElement.previousElementSibling.innerHTML;
  e.parentElement.parentElement.remove();
};

El resultado hasta ahora: 👇

Editar el resultado de una publicación

¡Tomar un descanso!

Tomar un descanso

Felicitaciones a todos por completar el proyecto 1. Ahora, ¡tómense un pequeño descanso!

Cómo hacer una aplicación de tareas pendientes usando operaciones CRUD

Hagamos una aplicación de tareas

Comencemos a hacer el proyecto 2, que es una aplicación To-Do.

Configuración del proyecto

configuración del proyecto

Para este proyecto, seguiremos los siguientes pasos:

  • Cree 3 archivos llamados index.html, style.css y main.js
  • Vincule los archivos JavaScript y CSS a index.html
  • Inicie nuestro servidor en vivo

HTML

Escribe este código de inicio dentro del archivo HTML: 👇

<div class="app">
  <h4 class="mb-3">TODO App</h4>

  <div id="addNew" data-bs-toggle="modal" data-bs-target="#form">
    <span>Add New Task</span>
    <i class="fas fa-plus"></i>
  </div>
</div>

El div con una identificación addNewes el botón que abrirá el modal. El intervalo se mostrará en el botón. El ies el ícono de font-awesome.

Vamos a usar bootstrap para hacer nuestro modal. Usaremos el modal para agregar nuevas tareas. Para eso, agregue el enlace CDN de arranque dentro de la etiqueta principal. 👇

<link
  href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
  rel="stylesheet"
  integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
  crossorigin="anonymous"
/>

<script
  src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
  integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
  crossorigin="anonymous"
></script>

Para ver las tareas creadas, usaremos un div con una tarea de identificación, dentro del div con la aplicación de nombre de clase. 👇

<h5 class="text-center my-3">Tasks</h5>

<div id="tasks"></div>

Inserte el CDN font-awesome dentro de la etiqueta principal para usar fuentes en nuestro proyecto 👇

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" />

Copie y pegue el código a continuación que proviene del modal de arranque. Lleva un formulario con 3 campos de entrada y un botón de envío. Si lo desea, puede buscar en el sitio web de Bootstrap escribiendo 'modal' en la barra de búsqueda.

<!-- Modal -->
<form
  class="modal fade"
  id="form"
  tabindex="-1"
  aria-labelledby="exampleModalLabel"
  aria-hidden="true"
>
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Add New Task</h5>
        <button
          type="button"
          class="btn-close"
          data-bs-dismiss="modal"
          aria-label="Close"
        ></button>
      </div>
      <div class="modal-body">
        <p>Task Title</p>
        <input type="text" class="form-control" name="" id="textInput" />
        <div id="msg"></div>
        <br />
        <p>Due Date</p>
        <input type="date" class="form-control" name="" id="dateInput" />
        <br />
        <p>Description</p>
        <textarea
          name=""
          class="form-control"
          id="textarea"
          cols="30"
          rows="5"
        ></textarea>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
          Close
        </button>
        <button type="submit" id="add" class="btn btn-primary">Add</button>
      </div>
    </div>
  </div>
</form>

El resultado hasta ahora: 👇

Configuración del archivo HTML

Hemos terminado con la configuración del archivo HTML. Comencemos el CSS.

CSS

Agregar la parte css

Agregue estos estilos en el cuerpo para que podamos mantener nuestra aplicación en el centro exacto de la pantalla.

body {
  font-family: sans-serif;
  margin: 0 50px;
  background-color: #e5e5e5;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

Apliquemos estilo al div con la aplicación classname. 👇

.app {
  background-color: #fff;
  width: 300px;
  height: 500px;
  border: 5px solid #abcea1;
  border-radius: 8px;
  padding: 15px;
}

El resultado hasta ahora: 👇

Estilos de aplicaciones

Ahora, diseñemos el botón con el id addNew. 👇

#addNew {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: rgba(171, 206, 161, 0.35);
  padding: 5px 10px;
  border-radius: 5px;
  cursor: pointer;
}
.fa-plus {
  background-color: #abcea1;
  padding: 3px;
  border-radius: 3px;
}

El resultado hasta ahora: 👇

Agregar nueva tarea Botón

Si hace clic en el botón, el modal aparece así: 👇

Estallidos modales

Agregar el JS

Agregar el JavaScript

En el archivo JavaScript, en primer lugar, seleccione todos los selectores del HTML que necesitamos usar. 👇

let form = document.getElementById("form");
let textInput = document.getElementById("textInput");
let dateInput = document.getElementById("dateInput");
let textarea = document.getElementById("textarea");
let msg = document.getElementById("msg");
let tasks = document.getElementById("tasks");
let add = document.getElementById("add");

Validaciones de formulario

No podemos permitir que un usuario envíe campos de entrada en blanco. Entonces, necesitamos validar los campos de entrada. 👇

form.addEventListener("submit", (e) => {
  e.preventDefault();
  formValidation();
});

let formValidation = () => {
  if (textInput.value === "") {
    console.log("failure");
    msg.innerHTML = "Task cannot be blank";
  } else {
    console.log("success");
    msg.innerHTML = "";
  }
};

Además, agregue esta línea dentro del CSS:

#msg {
  color: red;
}

El resultado hasta ahora: 👇

descripción de la imagen

Como puede ver, la validación está funcionando. El código JavaScript no permite que el usuario envíe campos de entrada en blanco; de lo contrario, verá un mensaje de error.

Cómo recopilar datos y utilizar el almacenamiento local

Independientemente de las entradas que escriba el usuario, debemos recopilarlas y almacenarlas en el almacenamiento local.

Primero, recopilamos los datos de los campos de entrada, usando la función named acceptDatay una matriz llamada data. Luego los empujamos dentro del almacenamiento local así: 👇

let data = [];

let acceptData = () => {
  data.push({
    text: textInput.value,
    date: dateInput.value,
    description: textarea.value,
  });

  localStorage.setItem("data", JSON.stringify(data));

  console.log(data);
};

También tenga en cuenta que esto nunca funcionará a menos que invoque la función acceptDatadentro de la declaración else de la validación del formulario. Síguenos aquí: 👇

let formValidation = () => {

  // Other codes are here
   else {

    // Other codes are here

    acceptData();
  }
};

Es posible que haya notado que el modal no se cierra automáticamente. Para resolver esto, escribe esta pequeña función dentro de la instrucción else de la validación del formulario: 👇

let formValidation = () => {

  // Other codes are here
   else {

    // Other codes are here

    acceptData();
    add.setAttribute("data-bs-dismiss", "modal");
    add.click();

    (() => {
      add.setAttribute("data-bs-dismiss", "");
    })();
  }
};

Si abre las herramientas de desarrollo de Chrome, vaya a la aplicación y abra el almacenamiento local. Puedes ver este resultado: 👇

Resultado de almacenamiento local

Cómo crear nuevas tareas

Para crear una nueva tarea, necesitamos crear una función, usar literales de plantilla para crear los elementos HTML y usar un mapa para insertar los datos recopilados del usuario dentro de la plantilla. Síguenos aquí: 👇

let createTasks = () => {
  tasks.innerHTML = "";
  data.map((x, y) => {
    return (tasks.innerHTML += `
    <div id=${y}>
          <span class="fw-bold">${x.text}</span>
          <span class="small text-secondary">${x.date}</span>
          <p>${x.description}</p>
  
          <span class="options">
            <i onClick= "editTask(this)" data-bs-toggle="modal" data-bs-target="#form" class="fas fa-edit"></i>
            <i onClick ="deleteTask(this);createTasks()" class="fas fa-trash-alt"></i>
          </span>
        </div>
    `);
  });

  resetForm();
};

También tenga en cuenta que la función nunca se ejecutará a menos que la invoque dentro de la acceptDatafunción, así: 👇

let acceptData = () => {
  // Other codes are here

  createTasks();
};

Una vez que hayamos terminado de recopilar y aceptar datos del usuario, debemos borrar los campos de entrada. Para eso creamos una función llamada resetForm. Síguenos: 👇

let resetForm = () => {
  textInput.value = "";
  dateInput.value = "";
  textarea.value = "";
};

El resultado hasta ahora: 👇

Adición de tarjetas de tareas

Como puede ver, no hay estilos con la tarjeta. Agreguemos algunos estilos: 👇

#tasks {
  display: grid;
  grid-template-columns: 1fr;
  gap: 14px;
}

#tasks div {
  border: 3px solid #abcea1;
  background-color: #e2eede;
  border-radius: 6px;
  padding: 5px;
  display: grid;
  gap: 4px;
}

Dale estilo a los botones de editar y eliminar con este código: 👇

#tasks div .options {
  justify-self: center;
  display: flex;
  gap: 20px;
}

#tasks div .options i {
  cursor: pointer;
}

El resultado hasta ahora: 👇

Plantillas de tarjetas de estilos

Función para eliminar una tarea

Mire aquí cuidadosamente, agregué 3 líneas de código dentro de la función.

  • La primera línea eliminará el elemento HTML de la pantalla,
  • la segunda línea eliminará la tarea objetivo de la matriz de datos,
  • y la tercera línea actualizará el almacenamiento local con los nuevos datos.
let deleteTask = (e) => {
  e.parentElement.parentElement.remove();

  data.splice(e.parentElement.parentElement.id, 1);

  localStorage.setItem("data", JSON.stringify(data));

  console.log(data);
};

Ahora cree una tarea ficticia e intente eliminarla. El resultado hasta ahora se ve así: 👇

descripción de la imagen

Función para editar tareas

Mire aquí cuidadosamente, agregué 5 líneas de código dentro de la función.

  • La línea 1 apunta a la tarea que seleccionamos para editar
  • Las líneas 2, 3 y 4 apuntan a los valores [tarea, fecha, descripción] de la tarea que seleccionamos para editar
  • la línea 5 está ejecutando la función de eliminación para eliminar los datos seleccionados tanto del almacenamiento local, el elemento HTML y la matriz de datos.
let editTask = (e) => {
  let selectedTask = e.parentElement.parentElement;

  textInput.value = selectedTask.children[0].innerHTML;
  dateInput.value = selectedTask.children[1].innerHTML;
  textarea.value = selectedTask.children[2].innerHTML;

  deleteTask(e);
};

Ahora, intente crear una tarea ficticia y edítela. El resultado hasta ahora: 👇

Edición de una tarea

Cómo obtener datos del almacenamiento local

Si actualiza la página, notará que todos sus datos han desaparecido. Para resolver ese problema, ejecutamos un IIFE (expresión de función invocada inmediatamente) para recuperar los datos del almacenamiento local. Síguenos: 👇

(() => {
  data = JSON.parse(localStorage.getItem("data")) || [];
  console.log(data);
  createTasks();
})();

Ahora los datos aparecerán incluso si actualiza la página.

Conclusión

Felicidades

Felicitaciones por completar con éxito este tutorial. Ha aprendido a crear una aplicación de lista de tareas mediante operaciones CRUD. Ahora, puede crear su propia aplicación CRUD usando este tutorial.

Aquí está tu medalla por leer hasta el final. ❤️

Fuente: https://www.freecodecamp.org/news/learn-crud-operations-in-javascript-by-building-todo-app/ 

#javascript #crud #operator #todoapp