teleren/devto huggingface dataset:
Javascript Ls/ss/cookies
Tags: engweb, aripovdev, javascript, localstorage
Published: 2024-06-28 02:50:53

**Browser Memory:**

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

- localStorage
- Session Storage
- Cookies

**Method**

SetItem();
GetItem();
RemoveItem();
Clear();

**Local Storage**
localStorage for long-term storage of data in the browser. 5-10 MB of memory is allocated for each origin domain by taking number.localStorage even after the cached data browser is closed. This amount may vary slightly depending on the browser and device.

Data storage(SetItem):

```
localStorage.setItem('key', 'value');

```

cancole:

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

Get information(GetItem):

```
let value = localStorage.getItem('key');
cansole.log(value)
```
cansole:

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


Delete data(removeItem):
```
localStorage.removeItem('key');

```


Delete all data(Clear):
```
localStorage.clear();

```

**Session Storage**
sessionStorage is also used to store data in the user's browser, but this data is only stored for the duration of the session. That is, the data is deleted when the browser window is closed. sessionStorage is also usually allocated 5-10 MB of memory for each originating domain. This amount may also vary by browser and device. sessionStorage only stores data for the duration of the session, and when the session ends (when the browser window is closed), the data is deleted.

Data storage:
```
sessionStorage.setItem('key', 'value');

```
Get information(GetItem):
```
let value = sessionStorage.getItem('key');

```
Delete data(removeItem):
```
sessionStorage.removeItem('key');

```

Delete all data(Clear):
```
sessionStorage.clear();

```
**Cookies**
Cookies are small pieces of information that are stored in the browser and can be read by websites. Cookies can be set with a specific term and can be deleted when the browser is closed or at a specific time interval.

Data storage:
```
document.cookie = "key=value; path=/; max-age=3600"; //it is kept for 1 hour

```

Get information
```
function getCookie(key) {
  let name = key + "=";
  let decodedCookie = decodeURIComponent(document.cookie);
  let ca = decodedCookie.split(';');
  for(let i = 0; i < ca.length; i++) {
    let c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

```

Delete data
```
document.cookie = "key=; path=/; max-age=0";

```

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


Memory size may vary slightly by browser and platform. An overview of the localStorage and sessionStorage sizes of some popular browsers:
- Google Chrome: About 10 MB.
- Mozilla Firefox: About 10 MB.
- Microsoft Edge: About 10 MB.
- Safari: About 5 MB.
- Opera: About 10 MB.
Declaração e Inicialização de Variáveis em Java
Tags: java
Published: 2024-06-28 02:43:21

**Declaração de Variáveis**
- Todas as variáveis devem ser declaradas antes de seu uso.
- Necessário para que o compilador saiba o tipo de dado da variável.
- Permite verificação rigorosa de tipos.

**Inicialização de Variáveis**
- É recomendável dar um valor à variável antes de usá-la.

**Pode ser feita por:**
- Instrução de atribuição.
- Valor inicial na declaração.

```
int count = 10;  // valor inicial
char ch = 'X';   // inicializa com 'X'
float f = 1.2F;  // inicializa com 1.2

```

- É possível inicializar variáveis do mesmo tipo em uma lista separada por vírgulas.

**Inicialização Dinâmica**

- Variáveis podem ser inicializadas dinamicamente usando expressões válidas.

```
double volume = 3.1416 * radius * radius * height;

```

**Escopo e Tempo de Vida das Variáveis**
- Variáveis podem ser declaradas dentro de qualquer bloco.

**Um bloco define um escopo:**
- Determina a visibilidade e o tempo de vida das variáveis.
- Variáveis dentro de um escopo não podem ser vistas fora dele.

**Escopos podem ser aninhados:**
- Variáveis em escopos externos são visíveis em escopos internos.
- Variáveis em escopos internos não são visíveis em escopos externos.

```
int x = 10;
if(x == 10) {
  int y = 20;
  System.out.println("x and y: " + x + " " + y);
  x = y * 2;
}
System.out.println("x is " + x);

```

**Regras e Peculiaridades de Escopo**
- Variáveis criadas ao entrar no escopo e destruídas ao sair dele.

- Variáveis são reinicializadas ao entrar novamente no bloco.

```
for(int x = 0; x < 3; x++) {
  int y = -1;
  System.out.println("y is: " + y);
  y = 100;
  System.out.println("y is now: " + y);
}

```

- Em Java, variáveis em escopos internos não podem ter o mesmo nome que variáveis em escopos externos.

```
// Este programa não será compilado
int count;
for(count = 0; count < 10; count++) {
  int count;  // inválido
  for(count = 0; count < 2; count++)
    System.out.println("This program is in error!");
}

```

**Resumo dos Pontos-Chave**
- Variáveis devem ser declaradas antes de seu uso para permitir verificação de tipos.
- Inicialização pode ser feita na declaração ou dinamicamente.
- O escopo de uma variável determina onde ela pode ser acessada.
- Escopos podem ser aninhados e variáveis no escopo interno não podem ter o mesmo nome de variáveis no escopo externo.
- O tempo de vida de uma variável está confinado ao seu escopo.
State and Props In React
Published: 2024-06-09 09:15:07

**What is The State In React ?**

👉 State is a way to Keep Track of Data that can Change in your Application. State is a Plain JavaScript Object that holds information that may change during the components life cycle. this data directly Affects the Components behavior and appearance . When The state changes , React Re-renders the component with updated information , Ensuring the UI reflects the current State

**key Points :✍**

- **Internal :** State is local to it's Components and isn't modified outside the Components
- **Dynamic :** Sate Can be Modified Throughout the Component Lifecycle Allowing for interactive and responsive UI
- **Re-rendering :** whenever the state Changes , React Retender the Component and reflecting the updating information on the UI

**How State Works ? ✍**

- State is typically Initialized in the constructor of class components and using useState() hooks in Functional Components.
- You Can directly access the state value using this.state in class components and state variable in functional components.
- State Should never mutated Directly . instead of , use this.setState method for class components and state updater Function in Functional components.
- when Updating State , Never modify the existing state , instead of , create a new object with desire changes and make a shallow a comparison for Re-renders.

**👉 Props in React**

Props are short for "properties" and are used to pass data from one component to another. They are read-only, meaning they cannot be modified by the receiving component. Props are typically used to pass data from a parent component to a child component.

**key Points :✍**

- **Immutability:** Props are immutable. Once set by the parent component, the child component cannot change them.
- **Data Flow:** Props enable a unidirectional data flow, meaning data flows from parent to child components.
- **Function Arguments:** Props work similarly to function arguments. When you define a component, you can pass data to it through attributes, just like passing arguments to a function.
Diferença entre Strings e Literais de Caracteres
Tags: java
Published: 2024-06-28 02:36:48

**Um string composto por um único caractere é o mesmo que um literal de caractere? Por exemplo, "k" é o mesmo que 'k'?**

**Literal de Caractere:**
- Representa uma única letra.
- Tipo char.
- Exemplo: 'k'.

**String de um Único Caractere:**
- Contém apenas uma letra, mas ainda é uma string.
- Tipo String.

**Exemplo: "k".**
- Resumo
- 'k' (literal de caractere) e "k" (string de um único caractere) não são a mesma coisa.
- Um literal de caractere é de tipo char, enquanto uma string é de tipo String.
- Strings, mesmo quando contêm apenas um caractere, são diferentes de literais de caracteres.


Observe como a sequência de escape \n é usada para gerar uma nova linha. 
Você não precisa usar várias instruções println( ) para obter uma saída de várias linhas. Apenas incorpore \n a um string mais longo nos pontos onde deseja que a nova linha ocorra.
Literais em Java
Tags: java
Published: 2024-06-28 02:29:39

**Literais em Java**

**1. Definição de Literais:**
- Valores fixos representados em forma legível por humanos (e.g., número 100).
- Também chamados de constantes.
- Intuitivos e usados frequentemente.

**2. Tipos de Literais:**
- Tipos Primitivos: Podem ser de qualquer tipo de dado primitivo.
- Caracteres: Delimitados por aspas simples (e.g., 'a', '%').

**3. Literais Inteiros:**
- Números sem componentes fracionários (e.g., 10, -100).
- Representados como int por padrão.
- Podem ser especificados como long usando l ou L (e.g., 12L).

**4. Literais de Ponto Flutuante:**
- Incluem um ponto decimal e componente fracionário (e.g., 11.123).
- Representados como double por padrão.
- Podem ser especificados como float usando F ou f (e.g., 10.19F).
- Suportam notação científica.

**5. Atribuição a Variáveis:**
- Literais inteiros podem ser atribuídos a char, byte, short se o valor couber.
- Literais inteiros podem ser atribuídos a long.

**6. Sublinhados em Literais (JDK 7+):**
- Facilita a leitura de valores grandes (e.g., 123_45_1234).

**7. Literais Hexadecimais, Octais e Binários:**
- Hexadecimais: Começam com 0x ou 0X (e.g., 0xFF).
- Octais: Começam com zero (e.g., 011).
- Binários (JDK 7+): Começam com 0b ou 0B (e.g., 0b1100).

**8. Sequências de Escape de Caracteres:**
- Usadas para representar caracteres especiais (e.g., \n para nova linha, \t para tabulação).
- Exemplos: ch = '\t';, ch = '\'';.

**9. Literais de Strings:**
- Conjunto de caracteres entre aspas duplas (e.g., "this is a test").
- Podem conter sequências de escape (e.g., \n, \t).

**Exemplo de uso em System.out.println:**

```
System.out.println("First line\nSecond line");
System.out.println("A\tB\tC");

```

**10. Tabela de Sequências de Escape:**
- \': Aspas simples
- \": Aspas duplas
- \\: Barra invertida
- \r: Retorno de carro
- \n: Nova linha
- \f: Avanço de página
- \t: Tabulação horizontal
- \b: Retrocesso
- \ddd: Constante octal
- \uxxxx: Constante hexadecimal
I made a Course
Published: 2024-06-21 07:21:25

---
title: I made a Course
published: true
date: 2024-06-20 19:08:36 UTC
tags: 
canonical_url: 
---

I’ve created a course with Newline called “Fullstack Typescript with TailwindCSS and tRPC Using Modern Features of PostgreSQL”. It basically teaches what is currently my favourite stack, from top to bottom. I am honestly quite happy with it and I feel that it gives a good introduction to how I like to use [Kanel](https://github.com/kristiandupont/kanel) to generate types that permeate the system.

If you are interested, take a look: [https://www.newline.co/courses/fullstack-typescript-with-tailwindcss-and-trpc-using-modern-features-of-postgresql](https://www.newline.co/courses/fullstack-typescript-with-tailwindcss-and-trpc-using-modern-features-of-postgresql)

![](https://cdn-images-1.medium.com/max/1024/0*BczW_oS58IoZ2ejf)

The course consists of several hours of video where I not only show the concepts but also little tricks and tips about how I work day-to-day.
Protect Your Website from XSS Attacks
Tags: xss, attacks, cybersecurity
Published: 2024-06-28 02:16:41

## What are XSS Attacks?

💻 Cross-site scripting (XSS) is a type of security vulnerability that allows an
attacker to inject malicious code into a web page. This malicious code can then
steal cookies, session tokens, or other sensitive information, hijack accounts,
deface websites, or redirect users to malicious websites.

## Types of XSS Attacks

There are two main types of XSS attacks:

- 💣 **Reflected XSS attacks.** In a reflected XSS attack, the malicious code is
  injected into the response to a user-supplied request. For example, if a user
  enters their name into a form on a website, the attacker could inject
  malicious code into the response that would then be executed by the user&#x27;s
  browser.
- 💻 **Stored XSS attacks.** In a stored XSS attack, the malicious code is
  stored on the website itself. This can happen if a website accepts
  user-submitted content that is not properly sanitized before being displayed
  on the website.

## Best Practices for Preventing XSS Attacks

🔒 To prevent XSS attacks, follow these best practices:

- 🧼 Sanitize all user-supplied input before it is displayed on the website by
  using a HTML parser or escaping special characters.
- 🛡️ Use a web application firewall (WAF) to filter out malicious traffic.
- 💻 Keep web applications up to date with the latest security patches.
- 📚 Educate users about the dangers of XSS attacks and how to protect
  themselves.

## Additional Tips for Preventing XSS Attacks

Here are some additional tips for preventing XSS attacks:

- 💻 Use a content management system (CMS) with built-in XSS protection.
- 📊 Use a web development framework with built-in XSS protection.
- 🛡️ Use a secure coding standard when developing web applications.
- 🔍 Conduct regular security audits of your web applications.
- 🕵️ Monitor your web applications for signs of XSS attacks.

## Conclusion

💻 XSS attacks are a serious security threat, but they can be prevented by
following best practices and additional tips. By taking steps to protect your
website from XSS attacks, you can help keep your users safe and secure. 🔒
Protect Your Website from DDoS Attacks
Tags: ddos, cybersecurity
Published: 2024-06-28 02:06:27

## What is a DDoS Attack?

💻 A distributed denial-of-service (DDoS) attack is a cyber attack in which a
large number of computers are used to flood a website or server with so much
traffic that it becomes unavailable to its intended users. DDoS attacks can be
used to disrupt businesses, governments, and other organizations.

## How Common are DDoS Attacks?

💥 DDoS attacks are becoming increasingly common. In 2022, there were over 10
million DDoS attacks recorded worldwide and the average cost of a DDoS attack is
now over $2 million.

## How to Prevent DDoS Attacks

🛡️ To protect your website or server from DDoS attacks, you can take several
steps, including:

- 🔥 **Using a web application firewall (WAF).** A WAF is a security device that
  filters out malicious traffic before it reaches your website or server.
- 🌍 **Using a content delivery network (CDN).** A CDN is a network of servers
  that deliver content to users based on their geographic location, which can
  help reduce the amount of traffic that reaches your website or server.
- 💻 **Upgrading your network infrastructure.** Having a fast and reliable
  network infrastructure can help mitigate the effects of a DDoS attack.
- 📈 **Having a disaster recovery plan in place.** A disaster recovery plan is a
  set of procedures that you can follow in the event of a DDoS attack, including
  steps for restoring your website or server to operation.

## Additional Tips for Preventing DDoS Attacks

Here are some additional tips for preventing DDoS attacks:

- 🔄 Keep your software up to date.
- 🔒 Use strong passwords and security measures.
- 🕵️ Monitor your website or server for signs of a DDoS attack.
- 📚 Have a plan in place to respond to a DDoS attack.

## Conclusion

💻 DDoS attacks are a serious threat to businesses and organizations of all
sizes. By taking steps to prevent DDoS attacks and following best practices for
website security, you can help protect your website or server from being taken
offline. Stay vigilant and stay protected! 🛡️
Be Safe and Secure with Credit Card Scanners
Tags: creditcard, scanners, cybersecurity, fraudprevention
Published: 2024-06-28 02:01:19

## What are Credit Card Scanners?

💳 Credit card scanners are devices that can read the magnetic stripe or chip on
a credit or debit card. They are often used by merchants to process payments,
but they can also be used by criminals to steal card information.

## Types of Credit Card Scanners

There are two main types of credit card scanners:

- 💳 **Magnetic stripe readers.** These readers read the magnetic stripe on the
  back of a credit or debit card, which contains the cardholder&#x27;s name, credit
  card number, expiration date, and CVV code.
- 💻 **Chip readers.** These readers read the chip on the front of a credit or
  debit card, which contains the same information as the magnetic stripe but is
  more secure.

## Places Where Credit Card Scanners Can be Found

Credit card scanners can be found in a variety of places, including:

- 🛍️ **Merchants.** Merchants use credit card scanners to process payments.
- 🏧 **ATMs.** ATMs use credit card scanners to dispense cash and make
  withdrawals.
- 🚗 **Gas stations.** Gas stations use credit card scanners to accept payments
  for gas and other items.
- 🏨 **Hotels.** Hotels use credit card scanners to process room charges.
- 🚗 **Car rental agencies.** Car rental agencies use credit card scanners to
  process rental car payments.

## Protecting Yourself from Credit Card Scanner Fraud

🔒 Credit card scanners are a convenient way to make payments, but they can also
be a security risk. To protect yourself from credit card scanner fraud, follow
these tips:

- 🔍 **Be aware of your surroundings.** If you are using a credit card scanner
  at a merchant, be sure to check that the scanner is properly secured and not
  accessible to the public.
- 💰 **Be careful about using ATMs.** If you are unsure about the safety of an
  ATM, do not use it. Instead, go to a bank or credit union where you can use a
  secure ATM.
- 🌐 **Be careful about entering credit card information online.** Only enter
  your credit card information on websites that you trust.
- 💳 **Use a credit card with a chip.** Credit cards with chips are more secure
  than credit cards with magnetic stripes.
- 🔒 **Keep your credit card information safe.** Do not carry your credit card
  information in your wallet or purse. Instead, store it in a secure place.

## Conclusion

💳 Credit card scanners are a convenient way to make payments, but they can also
be a security risk. By following these tips, you can help protect yourself from
credit card scanner fraud. Stay safe and secure when using credit card scanners!
🔒
Building Trust The Importance of Past Performance in Government Sales
Tags: government, sales, trust, contracting
Published: 2024-06-28 01:56:11

## Why Past Performance Matters 🎖️🏛️

When it comes to government contracts, agencies want assurance. They seek vendors with a proven track record of delivering quality products or services on time and within budget.

## Benefits of a Strong Track Record

💥 A stellar past performance can be your business&#x27;s strongest asset:

- 🔥 **Increased Credibility:** Agencies perceive you as a reliable vendor.
- 🌍 **Competitive Edge:** In competitive bids, a strong track record can tip the scales in your favor.
- 💻 **Referrals:** Satisfied agencies can recommend you to other departments or units.

## Building and Leveraging Your Track Record

🛡️ Here&#x27;s how you can establish and use your past performance:

- 🔄 **Document Everything:** Maintain comprehensive records of all contracts, deliverables, and feedback.
- 🔒 **Seek Feedback:** Proactively request performance evaluations from agency contacts after contract completion.
- 🕵️ **Showcase Your Successes:** Use your track record as a key selling point in your proposals and pitches.

## Conclusion

💻 In government sales, your reputation precedes you. A robust past performance not only builds trust but can also be a deciding factor in contract awards. Invest in building and maintaining a stellar track record, and let your work speak for itself. 🎖️🏛️
Chapter 1
Tags: nextjs, junior, react, learning
Published: 2024-06-19 08:25:19

## Introduction

Hello, fellow developers and enthusiasts! I'm thrilled to share with you the journey of my most ambitious portfolio project to date – Zušflix. As a junior developer, I wanted to push myself beyond my comfort zone and create something that would not only challenge my existing skills but also help me grow and learn new ones. Thus, the idea of Zušflix, a video catalog for local music school concerts, was born. 

## Why Zušflix?

The inspiration behind Zušflix is twofold. Firstly, as a music enthusiast myself, I recognized the need for an easily accessible platform to watch and enjoy local music school concerts. Teachers, students, and parents often face challenges in accessing these performances, and I wanted to simplify this process. Secondly, as a junior developer, I sought to enhance my full-stack development skills and gain experience in building a real-world application. 

## Project Overview

Zušflix is designed to be a sleek and modern platform, reminiscent of the popular streaming service Netflix. It aims to provide a user-friendly interface for browsing and watching music school concert videos. With a robust backend and intuitive features, it offers an engaging and seamless experience for users. 

## Key Features

- **Modern User Interface:** We've paid close attention to aesthetics and usability, creating an interface that is both visually appealing and intuitive. The Netflix-inspired design provides a familiar and engaging experience for users. 

  - Comprehensive Video Catalog: Zušflix offers a vast library of concert videos, neatly organized and easily searchable, ensuring users can conveniently access and enjoy performances. 

- **Secure Auth Page:** We've implemented a secure authentication system to protect user privacy. This ensures that only authorized individuals can access the video content, adding a layer of security to the platform. 

- **Admin Capabilities:** The admin panel empowers administrators to manage the video catalog effectively. They can easily add, edit, or delete video entries, keeping the content fresh and well-organized.

- **Google Driven:** Videos are uploaded on Google Drive, providing reliable and secure hosting, efficient video streaming, and storage.

## Technologies Used

- NextJS: Lightning-fast server-side rendering and static site generation.
- SQL PostgreSQL: Flexible database for video metadata management.
- React: Reusable components for a consistent and responsive UI.

## The Journey Begins

In this first blog post, I've outlined the project's inception, goals, and key features. Join me in the next part as I delve into the initial project setup, my experience with NextJS, and getting Zušflix up on GitHub. 

Chapter's 1 blueprint:

**Goals:** 
- Basic project setup.
- Familiarize myself with NextJS.
- Upload the project to GitHub.

**Next Steps:** 
- Find a Tailwind UI kit for components without dependencies.
- Create a responsive layout and sticky menu.
- Start implementing the UI with dummy data.

Let's embark on this exciting adventure together! 

Happy coding!