teleren/devto huggingface dataset:
How to preload images for canvas in JavaScript
Tags: tutorial, beginners, javascript, canvas
Published: 2023-01-17 11:26:51

<!--
Title: How to preload images for canvas in JavaScrypt
Tags: tutorial, beginners, javascript, canvas, image
-->

## Introduction

This past week, I was toying around with the HTML5 canvas element, trying to join two images together.
At first, it seemed fine, but when I tried to reload the website, it was a mess. One image would load, but the other wouldn't.

Investigating, I found out that the images were being loaded asynchronously.
But the JavaScript code was running anyway, without waiting for the images, ending up with a messed up canvas.

That is why I decided to write this tutorial, to help you **preload images for canvas in modern JavaScript**.

---

## Preload images

With the help of the `Promise.all()` function, we can devise a solution to preload images.

```javascript
/**
 * @param {string[]} urls - Array of Image URLs
 * @returns {Promise<HTMLImageElement[]>} - Promise that resolves when all images are loaded, or rejects if any image fails to load
 */
function preloadImages(urls) {
  const promises = urls.map((url) => {
    return new Promise((resolve, reject) => {
      const image = new Image();

      image.src = url;

      image.onload = () => resolve(image);
      image.onerror = () => reject(`Image failed to load: ${url}`);
    });
  });

  return Promise.all(promises);
}
```

You can then use it like this:

```javascript
const urls = [
  'https://example.com/image1.png',
  'https://example.com/image2.png',
];

// Important to use `await` here
const images = await preloadImages(urls);

// Can also be destructured
const [image1, image2] = await preloadImages(urls);

// For example:
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');

context.drawImage(images[0], 0, 0);
context.drawImage(images[1], 0, 0);
```

---

## End

That was it.
It's a small one-time setup on your project, that works like a charm.

<!-- INCLUDE -->

### Self-promotion

If you have found this useful, then you should follow me, I will be posting more interesting content! 🥰

- [GitHub](https://redirect.akbal.dev/github)
- [Twitter](https://redirect.akbal.dev/twitter)
- [Dev.to](https://redirect.akbal.dev/dev.to)

<!-- /INCLUDE -->

### Conclusion

Congratulations, today you have learned how to preload images for canvas in modern JavaScript. Without needing to complicate your code or use libraries.

**Let me know if the tutorial was useful to you in the comments!**
Array methods in JavaScript, some of the most commonly used ones include:
Published: 2023-01-17 11:04:29


.**push**(): adds one or more elements to the end of an array and returns the new length of the array.
.**pop**(): removes the last element of an array and returns that element.
.**shift**(): removes the first element of an array and returns that element.
.**unshift**(): adds one or more elements to the beginning of an array and returns the new length of the array.
.**slice**(): returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included) where begin and end represent the index of items in that array.
.**splice**(): changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
.**sort**(): sorts the elements of an array in place and returns the array.
.**reverse**(): reverses the order of the elements in an array in place and returns the array.
.**concat**(): returns a new array that is the result of concatenating the given arrays or values.
.**forEach**(): executes a provided function once for each array element.
Many other functions are available in JS like Map, Filter, Reduce, etc.
Developers, Start Paying For Stuff, Will You?
Published: 2023-01-17 11:03:45

I can sense your contempt. But hear me out here.

There are some counter-intuitive advantages to taming that inner instinct and natural pride a developer has, which makes him/her want to always develop stuff instead of paying for it. Here is a couple…

1. You will be able to relate: Till I started paying for stuff, I had a hard time relating to people who pay for stuff. That’s not a helpful mindset to have when you are developing products yourself that you expect people to pay. If you have to create high quality, you will need to experience high quality. Most of them cost some money.

2. You will see that it’s not just about the code: A right product means care, attention to detail, handling weird edge cases, proper documentation, UX, excellent onboarding, follow-up, support, and sound design. Signing up and paying for products like Intercom or Basecamp exposed me to the other aspects of product making and showed me first-hand what it ‘feels’ like to be a part of a pleasant experience.

3. Your app/project inherits the qualities of high quality paid products: Contrary to popular belief, open-source products aren’t that efficient at getting jobs done. It is because a random set of developers builds it from different parts of the world with different agendas. There is almost no research, no prioritization, and because developers use it, there is not much need for great onboarding, great UI, and support. Using Slack or Base camp makes your projects better. They allow you to consider more things, think broader and more organized get better consensus, and overall make for a better whatever-you-are-making. It is a little known secret that a product maker cannot make a great product without having experienced several great products themselves. Conversely, an excellent maker builds his creation by the combined influence of the ethos of all the products he/she has experienced until then. If you want to make great products, experience great products

I am the maker of Proxies API, a rotating proxy service that you will need to pay for if you want a reliable way to bypass IP blocks when web scraping.
Webinar- Code & Context: Debugging running code faster with intelligent observability
Tags: webinar, observability, productivity, programming
Published: 2023-01-17 10:48:04

Date & Time: 21st February 2023, 11:00 am (ET)

As digital transformation continues to accelerate and customer demands increase, traditional approaches of debugging are limited and reactive troubleshooting is insufficient. During incidents, developers need to quickly understand the relationships between user sessions, topology, and end-to-end transactions. In addition, they must have the tools to triage and debug what the code is doing in order to resolve issues and minimize user impact.

To help with this need, Dynatrace brings together high fidelity distributed tracing, code-level visibility, and advanced diagnostics across the most advanced cloud-native serverless and service mesh architectures. Dynatrace uses a sophisticated AI causation engine, called Davis®, to automatically tell you when there is a problem, the business impact, and the root cause. With these answers, Rookout’s Developer-First tooling and observability solution enables developers to capture live debugging data across your tech stack without stopping and redeploying the running application.

Rob Jahn, Sr. Technical Partner Manager from Dynatrace will be presenting the webinar, along with myself, Rookout Co-Founder & CTO.

## We'll discuss and demo 👨‍💻:

- Common observability challenges of cloud-native architectures.

- How to capture and analyze timing and code-level context for distributed traces end-to-end and across the full stack.

- How to collect metrics, log lines and debug snapshots from a running application, troubleshoot faster, and get instant insight into your app.

- How easy it is to get started with the Dynatrace-Rookout integration.

⏩ Register Here: https://www.rookout.com/webinar-debugging-running-code-faster-with-intelligent-observability/
Making react vite and storybook play nice
Tags: react, storybook, vite
Published: 2023-01-17 10:38:13

---
title: Making react vite and storybook play nice
published: true
description: Bit of a quicky for how to get react, vite and storybook, playing nice.
tags: react,storybook,vite
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2023-01-17 10:31 +0000
---

Another one of those reminder posts. I wanted to add storybook to a react app that I had created with vite. I was getting the following error
```shell
ERR! Error [ERR_REQUIRE_ESM]: require() of ES Module /home/bart/src/enra_v3/frontend/.storybook/main.js from /home/bart/src/enra_v3/frontend/node_modules/@storybook/core-common/dist/cjs/utils/interpret-require.js not supported.
ERR! main.js is treated as an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which declares all .js files in that package scope as ES modules.
ERR! Instead rename main.js to end in .cjs, change the requiring code to use dynamic import() which is available in all CommonJS modules, or change "type": "module" to "type": "commonjs" in /home/bart/src/enra_v3/frontend/package.json to treat all .js files as CommonJS (using .mjs for all ES modules instead).
ERR! 
```
There is a whole thread of different ways of fixing this but this is the one that helped me most [Issues Link](https://github.com/storybookjs/storybook/issues/11587#issuecomment-813079314)

Basically Add a `package.json` file to the `.storybook` folder

```json
{
  "type": "commonjs"
}
```

Boooom!!!!
234. Palindrome Linked List
Tags: java, algorithms, leetcode, 100daysofcode
Published: 2023-01-17 10:29:16

**Problem Statement:**

Given the head of a singly linked list, return true if it is a 
palindrome or false otherwise.

**Example 1:**


**Input:** head = [1,2,2,1]
**Output:** true

**Example 2:**


**Input:** head = [1,2]
**Output:** false
 

**Constraints:**
- The number of nodes in the list is in the range [1, 105].
- 0 <= Node.val <= 9

**Solution:**


**Code:**
```
public class Solution {
    public boolean isPalindrome(ListNode head) {
        ListNode slow = head, fast = head, prev, temp;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        prev = slow;
        slow = slow.next;
        prev.next = null;
        while (slow != null) {
            temp = slow.next;
            slow.next = prev;
            prev = slow;
            slow = temp;
        }
        fast = head;
        slow = prev;
        while (slow != null) {
            if (fast.val != slow.val)
                return false;
            fast = fast.next;
            slow = slow.next;
        }
        return true;
    }
    
}
```
Mounted check in a stateless widget
Tags: flutter, dart, mobile, extension
Published: 2023-01-17 10:27:54

If you want to use mounted check in a stateless widget its possible by making an extension on BuildContext

```
extension ContextExtensions on BuildContext {
  bool get mounted {
    try {
      widget;
      return true;
    } catch (e) {
      return false;
    }
  }
}
```
and then you can use it like this

```
if (context.mounted)

```


https://stackoverflow.com/a/74575955/14745090
Ways to achieve SEO in Next.js
Tags: seo, nextjs, ssr, react
Published: 2023-01-17 10:17:37

There are several ways to achieve SEO in Next.js:

1. Server-side rendering: Next.js uses server-side rendering by default, which allows search engines to easily index the content of your pages.

2. Static site generation: Next.js also allows you to export your pages as static HTML, which can be easily crawled by search engines.

3. Proper use of meta tags: Use next/head component to add meta tags such as the title and description to your pages, which can help search engines understand the content of your pages.

4. Sitemap and robots.txt: Next.js allows you to generate a sitemap and robots.txt file for your pages, which can help search engines discover and index your pages.

5. Redirects and rewrites: Next.js allows you to define redirects and rewrites for your pages, which can help search engines understand the structure of your site and avoid indexing duplicate content.

6. Performance optimization: Optimizing the load time of your pages can improve the crawl-ability and indexing of your pages by search engines.

_Note that SEO is a complex and evolving field, and implementing these techniques alone may not be enough to achieve high visibility in search engines. It's recommended to work with an SEO expert to optimize your site for search engines._
Listing first elements of a huge directory using Python
Tags: python, programming, beginners, devops
Published: 2023-01-17 10:09:57

---
title: Listing first elements of a huge directory using Python
published: true
description: It is possible to read the files of a directory one-by-one even in Python. It is not even difficult.
tags: python, programming, beginners, devops
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2023-01-17 10:07 +0000
canonical_url: https://code-maven.com/listing-first-elements-of-huge-directory-using-python
series: python
---

At a client we have a huge directory of files. I wanted to list the first few files. `ls -l | head` took ages as it first lists all the files and only then cuts it down.
After my first attempts in Python failed I wrote a [Perl one-liner to list the first elements of a huge directory](https://dev.to/szabgab/one-liner-read-first-elements-of-a-huge-directory-2h8c). However I wanted to see if I can do it with Python in some other way.


## using iterdir of pathlib

The original attempt in Python was using the [iterdir](https://docs.python.org/3/library/pathlib.html#pathlib.Path.iterdir) method of [pathlib](https://docs.python.org/3/library/pathlib.html).

```python
import pathlib

path = pathlib.Path("/home/gabor/work/code-maven.com/sites/en/pages/")
count = 0

for thing in path.iterdir():
    count += 1
    print(thing)
    if count > 3:
        break

```

On the real data it took 47 minutes to run.

## using walk of os

The second attempt was to use the [walk](https://docs.python.org/3/library/os.html#os.walk) method of [os](https://docs.python.org/3/library/os.html#os.walk).

```python
import os

path = "/home/gabor/work/code-maven.com/sites/en/pages/"
count = 0

for dirname, dirs, files in os.walk(path):
    for filename in files:
        print(os.path.join(dirname, filename))
        count += 1
        if count > 3:
            exit()


```

I don't know how long this would take. I stopped it after a minute.

## using scandir of os

Finally I found the [scandir](https://docs.python.org/3/library/os.html#os.scandir) method of [os](https://docs.python.org/3/library/os.html#os.walk). That did the trick:

```python
import os

path = "/home/gabor/work/code-maven.com/sites/en/pages/"
count = 0

with os.scandir(path) as it:
    for entry in it:
        print(entry.name)
        count += 1
        if count > 3:
            exit()

```
Affiliate Tracking System for Networks — Part 2
Tags: buildingpubli, webdev, javascript, html
Published: 2023-01-17 10:05:18

Quick changes on the plan, In the beginning I found that creative-tim's softUI is eyecatching, but now I want to continue with another theme called Sneat. This is also a powerful theme with good amount of components, and it also free. So I am going to use this for the project.

I started by creating the dashboard. For now I already created the Admin and Publisher dashboard. 

Take a look 😁

Admin Dash:

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

This is basic look, I will add more components when I am going further. 

Publisher Dash:


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


Thats it for today, Thanks for your time on reading this.
If you have any comments let me know, that is so much for me.
How to pick the best hosting option if you are in Europe?
Tags: hosting
Published: 2023-01-17 10:04:28

When it comes to choosing region specific hosting, there are a few key factors to consider. One important factor is location. Hosting your website in a server located in the same region as your target audience will ensure your website performs well and your visitors are up to date.

Another important factor to consider is the hosting company's infrastructure and network. Make sure to choose a company with a robust network and good uptime records.

If you are targeting countries in Europe, lets say the Netherlands specifically, there are a few hosting companies that are considered to be the best. These include:

TransIP: This company is based in the Netherlands and offers a wide range of hosting solutions, including shared hosting, VPS hosting, and dedicated servers. They also have a good reputation for their customer service and features oriented hosting options.

LeaseWeb: This company is another popular choice for hosting your website in Europe. They offer a wide range of services, including cloud hosting, dedicated servers, and managed hosting. They also have a strong network of servers spread globally and a uptime speed of 99.5%.

Cloudways: This US-based company has a data center in the Netherlands, They offer a wide range of hosting options including managed hosting, WordPress hosting, Magento Hosting, and more. They are known for providing affordable hosting plans with high-performance features.

When looking for the [best web hosting in the Netherlands](https://www.cloudways.com/en/netherlands-hosting.php), it's important to do your research and compare different options to find the one that best suits your need. Consider factors like location, infrastructure, and uptime records when making your decision.
Which is better C++ or Java or Python?
Tags: cpp, python, java, programming
Published: 2023-01-17 10:04:09

C++ is a powerful, high-performance programming language that is widely used for systems programming, creating operating systems, device drivers, embedded systems, and gaming. It is also commonly used in applications that need to be optimized for speed and performance, such as video editing and image processing software.

Java is a popular, general-purpose programming language that is used for developing enterprise applications, mobile apps, video games, and other types of software. Java is known for its write-once-run-anywhere (WORA) principle, which means that once a program is written, it can run on any platform that has a Java Virtual Machine (JVM) installed.


Python is a high-level, interpreted language that is well-suited for scripting, automation, data analysis, and machine learning. Python has a large community, and a lot of libraries and frameworks, it is user-friendly and easy to learn.

In general, C++ is best for performance-critical applications that need to be optimized for speed, Java is best for enterprise applications and cross-platform development, and Python is best for rapid development, prototyping, and applications that don't require the highest level of performance.

It is recommended to consider the specific requirements and constraints of the project and choose the language that is most suitable for the task at hand.
Which is a good software to run Python codes?
Tags: python, programming, productivity, beginners
Published: 2023-01-17 10:01:24

There are several software options available for running Python code, some popular ones are:

**IDLE:** IDLE is the default Python IDE that comes pre-installed with the Python programming language. It is simple and easy to use, and it's a good option for beginners.

**PyCharm: **PyCharm is a popular, full-featured IDE that is widely used by Python developers. It has a user-friendly interface, advanced debugging capabilities, and support for various frameworks and libraries.

**Visual Studio Code:** Visual Studio Code (VS Code) is a popular, lightweight code editor that has built-in support for Python. It is highly customizable and has a large number of extensions available for various languages and frameworks.

**Jupyter Notebook: **Jupyter Notebook is a web-based interactive development environment (IDE) that is commonly used for data science and machine learning projects. It allows you to write and run Python code, as well as add text and visualizations to explain the code.

**Anaconda:** Anaconda is a free, open-source distribution of Python that comes with over 1,500 packages and is designed for scientific computing and data science. It also comes with a package manager (conda) and an environment manager that makes it easy to install and manage packages and environments.
It is recommended to choose the software that best fits your needs and experience level.
Weekly 0043
Tags: weeklyretro
Published: 2023-01-17 09:57:50

### Monday
In the morning I had a meeting with Marta (my Brandplane cofounder) about the new pricing strategy and the strategy for the next 2-3 weeks for the product.

After that in the morning I helped one of my colleague with a PowerShell script.
For me it's not really hard to write PowerShell, but I totally understand it's not easy for a non developer.

In the afternoon I had a meeting about Red Origin and how we will proceed with the product internally.

I did another annoying task for Red Origin: create the products manually on Stripe for development and live environments.

In the meantime I have created a demo project for Blazor WASM and Stripe.

I also created a new session for my next events called “Accepting payment with Stripe in your Blazor applications”. I sent it to two or three events in the coming months.

**Mood:** 

### Tuesday

I started the morning creating a new project on GitHub called “ShopWest”.
I will be a new demo application based on Blazor, Stripe and Auth0. I think I will use this demo for my next events in the future.
This is the link of the repo: [https://github.com/kasuken/ShopWest](https://github.com/kasuken/ShopWest)

**Mood**: 😩

### Wednesday
In the morning I worked on the Brandplane's Stripe flow for payments.

I also found a kind of bug in the Stripe portal. It's not possible to use an email like hotmail or outlook.com because I never receive the confirmation email or the email to retrieve the forgot password.
You need a "commercial" domain.

In the afternoon I received an email from Sessione. I was recognized with one of the most active speaker on Sessionize.

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

I have also a badge on my public profile.

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

[https://sessionize.com/emanuelebartolesi](https://sessionize.com/emanuelebartolesi)

**Mood: 🤪**

### Thursday

In the morning I spent one hour to update one of the most viewed post on my blog about PowerShell and Visual Studio Code.

![https://res.cloudinary.com/practicaldev/image/fetch/s--7EiXMiS4--/c_imagga_scale,f_auto,fl_progressive,h_420,q_auto,w_1000/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5zycjj4g1szdnsljj5hq.png](https://res.cloudinary.com/practicaldev/image/fetch/s--7EiXMiS4--/c_imagga_scale,f_auto,fl_progressive,h_420,q_auto,w_1000/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5zycjj4g1szdnsljj5hq.png)

This is the link of the post: [https://dev.to/kasuken/how-to-use-powershell-with-visual-studio-code-like-a-pro-475b](https://dev.to/kasuken/how-to-use-powershell-with-visual-studio-code-like-a-pro-475b)

Worked on Brandplane

**Mood: ⭐**

---

Thanks for reading this post, I hope you found it interesting!

Feel free to follow me to get notified when new articles are out 🙂

{% embed https://dev.to/kasuken %}