teleren/devto huggingface dataset:
Nuxt3 x MySQL (& Drizzle ORM)
Tags: nuxt, database, mysql, drizzle
Published: 2024-05-09 08:11:33

The Nuxt ecosystem is very promising but also very badly documented.

Not sure that is the best way to do it but it's the simplest and working I found.

If you have a better way please share with us.

## mysql2 and raw SQL

### Install mysql2

```sh
npm i mysql2
```

### Setup Nuxt3 app

```ts
// /.env.dev

DB_HOSTNAME="localhost"
DB_PORT=3306
DB_USERNAME=""
DB_PASSWORD=""
DB_DATABASE=""
```

```ts
// /nuxt.config.ts

runtimeConfig: {
	db: {
		hostname: process.env.DB_HOSTNAME,
		port: process.env.DB_PORT,
		username: process.env.DB_USERNAME,
		password: process.env.DB_PASSWORD,
		database: process.env.DB_DATABASE
	}
},
```

```ts
// /server/plugins/db.ts

import mysql from 'mysql2'

export default defineNitroPlugin(async nitroApp => {
	const cfg = useRuntimeConfig()
	const pool = mysql
		.createPool({
			host: cfg.db.hostname,
			user: cfg.db.username,
			port: cfg.db.port,
			password: cfg.db.password,
			database: cfg.db.database,
			timezone: '+01:00',
			supportBigNumbers: true,
			bigNumberStrings: true
		})
		.promise()

	nitroApp.db = pool
})
```

### Usage

```ts
// /server/api/dbtest.ts

export default defineEventHandler(async event => {
	const [r] = await useNitroApp().db.query(`SELECT * FROM user`)
	return r
})
```

```ts
// /pages/tests/dbtest.vue

<script setup lang="ts">
const r = await $fetch('/api/dbtest')
</script>

<template></template>
```

## With Drizzle ORM

Next to previous steps

### Install Drizzle ORM

```sh
npm i drizzle-orm
npm i -D drizzle-kit
```

### Define DB schema

```ts
// /server/utils/dbschema.vue

import { mysqlTable, int, text, varchar } from 'drizzle-orm/mysql-core'

export const Post = mysqlTable('post', {
	id: int('id').primaryKey(),
	title: varchar('title', { length: 255 }).notNull(),
	text: text('text').notNull(),
	user: int('user_id').references(() => User.id),
})

export type PostSelect = typeof Post.$inferSelect
export type PostInsert = typeof Post.$inferInsert

export const User = mysqlTable('user', {
	id: int('id').primaryKey(),
	email: varchar('email', { length: 255 }).notNull().unique()
})

export type UserSelect = typeof User.$inferSelect
export type UserInsert = typeof User.$inferInsert
```

### Usage

```ts
// /server/api/dbtest.ts

export default defineEventHandler(async event => {
	const r = await useNitroApp().drizzle.select().from(Post).where(eq(Post.id, 1)).limit(1)
	return r[0] ?? null
})
```
Terraform = Peace of Mind
Tags: devops, terraform, cloud, aws
Published: 2023-02-13 21:54:56

Anyone that have had the pain of setting up infrastructure, specially the same infra multiple times (shout out to all software agencies out there), knows how much of a lifesaver [Terraform](https://developer.hashicorp.com/terraform/tutorials/aws-get-started/infrastructure-as-code) actually is.

As the go-to infra-as-code solution, Terraform brings peace to an arena filled with stress, worry and doubt. **Stop taking hours to set up the same thing over and over**, no infra team member having all the company's infra knowledge only on their head, no new colleague having no idea what's the company's infra like.

**No more infra being something hard to describe.**

Here's how Terraform accomplishes all of this (all screenshots are from their [AWS "Get Started"](https://developer.hashicorp.com/terraform/tutorials/aws-get-started/infrastructure-as-code)):

# 1. Resources' Description File

Every infra resource is described as a "resource" block. This one is an [EC2 instance](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/instance) resource:

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

It could be an [S3 bucket](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/s3_bucket), or an [RDS instance](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/db_instance), or all of them together at the same time!

You could create one resource instance for each deployment stage with a [for loop](https://developer.hashicorp.com/terraform/language/meta-arguments/for_each)!

And of course, once you have the resource set up correctly, you could have it live in a few seconds/minutes with a single [`terraform apply`](https://developer.hashicorp.com/terraform/cli/commands/apply) command!

Once live, the description file becomes a snapshot for the resource configuration params.

And just like that, your infra code becomes documentation. We can use it as a reference to set up new infrastructure on a new environment!

# 2. Resources' History

Of course, once something becomes code, it becomes trackable through the use of Git! Just create a repo with all of your resources and start tracking all the changes done to your infra!
TW Elements - Rounded corners / border radius. Free UI/UX design course
Tags: webdev, javascript, beginners, tailwindcss
Published: 2024-05-09 08:00:00

## Shadows
In this lesson we will take some time to learn the theory behind the shadows.

As in Material Design, shadows play a big role in Material Minimal (TW Elements design system). However, they are definitely more subtle here - they have brighter colors and are often more extensive.

Unlike Material Design, Material Minimal is not afraid to use colored shadows, which can be seen in the example of our buttons. However, these are always delicate accents, as Material Minimal values subtlety and avoids exaggeration.

The shadows are undoubtedly one of the most distinctive features of Material Minimal and give it a special flavor.

## Default shadows in Tailwind CSS
Tailwind CSS provides utilities for adding box-shadows to elements. They create the illusion of depth and are useful for adding subtle visual distinction between different elements on the screen.

The syntax for applying shadows in Tailwind CSS is very straightforward. You simply apply the shadow utility at its various strengths to an HTML element.

Note: .shadow-none removes shadows.

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

HTML

```
<div class="... shadow-none"></div>
<div class="... shadow-sm"></div>
<div class="... shadow"></div>
<div class="... shadow-md"></div>
<div class="... shadow-lg"></div>
<div class="... shadow-xl"></div>
<div class="... shadow-2xl"></div>
```

## Add shadows to the carousel images
Just like the class for rounded corners, we also need to add a class for shadows to the Carousel items part.

So let's add .shadow-2xl class:

HTML

```
<!--Carousel items-->
<div
  class="relative w-full overflow-hidden rounded-2xl shadow-2xl after:clear-both after:block after:content-['']">
  [...]
</div>
```

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


After saving the file and refreshing the browser you should see the shadow added to the carousel.

However, because the graphics in the carousel are quite dark, the shadow is hardly visible. We can increase its intensity by adding the .shadow-black/50 class.

How exactly does it work? It's simple:

shadow-black: This part of the class is setting the shadow color to black
/50: This part of the class is setting the opacity of the shadow to 50%.
This combination allows you to have a very diffused (because of .shadow-2xl) black shadow with 50% opacity. This would give a soft, semi-transparent black shadow.

So let's add this to the carousel:

HTML

```
<!--Carousel items-->
<div
  class="relative w-full overflow-hidden rounded-2xl shadow-2xl shadow-black/50 after:clear-both after:block after:content-['']">
  [...]
</div>
```

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

Now the shadow is much more visible.

**[DEMO AND SOURCE CODE FOR THIS LESSON](https://tw-elements.com/snippets/tailwind/ascensus/5343603)**
TOPTRADE WebTrading: Empowering Institutional Traders with Customized Solutions
Published: 2024-05-09 07:55:35

In today's fast-paced financial landscape, where adaptability and decisive action are paramount, TOPTRADE WebTrading recognizes the diverse environment in which institutional traders operate. Our trading platform is meticulously crafted to equip institutional traders with the essential tools they need to excel in this dynamic setting.

A Comprehensive Range of Assets
Institutional traders often traverse various markets and asset classes, necessitating a platform that offers versatility and agility. With TOPTRADE WebTrading, traders gain access to a diverse array of instruments including Forex, stocks, CFDs, futures, ETFs, commodities, and indices through a single trading account. This extensive range of assets empowers traders to diversify their portfolios and capitalize on opportunities across diverse markets.

Addressing Platform Challenges
Over the past three years, TOPTRADE WebTrading has emerged as a compelling alternative to established platforms such as MetaTrader 4 and 5. We have proactively addressed limitations inherent in these platforms, enhancing the appeal of TOPTRADE WebTrading for institutional traders.

Unique Features and Benefits

Flexible Functionality: Our platform caters to both novice and experienced traders, offering a wide array of functions to meet diverse needs. From one-click or double-click trading modes to advanced trading alert systems and comprehensive charting capabilities, TOPTRADE WebTrading equips traders with the tools they need to succeed.

Diverse Account Options: TOPTRADE WebTrading offers a range of account types to accommodate traders' preferences and strategies. Whether traders seek real-time trading with spot exchange accounts or leverage positions with margin operations accounts, our platform provides flexibility to align with different trading approaches.

Swift Execution and Reliability: We understand the critical importance of rapid and reliable trade execution. TOPTRADE WebTrading ensures swift and dependable execution, particularly with our one-click trading feature. This feature is especially beneficial for scalpers and day traders who require prompt entry and exit from positions.

Client Applications: Our platform provides a suite of client applications tailored for various environments, ensuring consistent execution speed across different devices. Whether traders prefer our desktop app for advanced functionality or our web app for convenient access from any location, they can trade confidently with TOPTRADE WebTrading.

In Conclusion
At TOPTRADE WebTrading, our commitment is to provide institutional traders with a robust trading platform equipped with advanced features and reliable performance. With our extensive range of assets, unique functionalities, and dedication to addressing traders' needs, we empower institutional traders to navigate the intricate financial landscape with confidence and achieve success.
Netlify image CDN
Tags: netlifychallenge, devchallenge, webdev, javascript
Published: 2024-05-09 07:52:51

*This is a submission for the [Netlify Dynamic Site Challenge](https://dev.to/challenges/netlify): Visual Feast.*


## What I Built
<!-- Share an overview about your project. -->
I used the Netlify image CDN to transform image properties, type, and quality of an image. We have custom images and you can also upload your own images to transform(remote and relative path).
## Demo
<!-- Share a link to your Netlify app and include some screenshots here. -->
Check the web app [here](https://peppy-profiterole-58b1ee.netlify.app/)

![before transform](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3jo2uxp1oewagvuv5ciw.png)

![After transform](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3mqhse87odnvviggd6ym.png)


## Platform Primitives
<!-- Tell us how you leveraged the Netlify Image CDN. -->
By using Netlify Image CDN you can enhance and server images efficiently. And not bad for transforming basic properties of an image. But after transforming an image we see a decrease in the image quality. 

<!-- Did you implement additional platform primitives like Netlify Blobs or Cache Control? Tell us about that too! You may qualify for more than one prompt. -->

<!-- Team Submissions: Please pick one member to publish the submission and credit teammates by listing their DEV usernames directly in the body of the post. -->
It was individual.

<!-- Don't forget to add a cover image (if you want). -->


<!-- Thanks for participating! -->
Day 8 of 30 of JavaScript
Tags: webdev, javascript, beginners, tutorial
Published: 2024-05-09 07:50:55

Hey reader :) I hope you are doing well. In the last post we have learnt about functions and how they are used in JavaScript. In this post we are going to learn about arrow functions and function invokation. 
So let's get started...

## Arrow Functions
**Arrow functions are concise form to define functions in JavaScript.** They are introduced in ECMAScript 2015. 
They provide a more concise syntax compared to traditional function expressions and offer some additional benefits.

Syntax -:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rksmb7pyw12j7yzbg3il.png)
Arrow functions are defined using a shorthand syntax, using the `=>` arrow syntax.

**Benefits of using Arrow function ->**
1. They provide a concise format to define functions in JavaScript.

2. Implicit Return -: If the function body consists of a single expression, you can omit the curly braces `{}` and the return keyword. The expression's result will be automatically returned. This makes arrow functions particularly useful for concise one-liners.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wpo7akqb07ytgqea5uic.png)

There are more benefits of using arrow function but we will see them in upcoming blogs as we need to learn more prior to these.

## Function Invocation
The code inside the function will execute when "something" invokes (calls) the function:

- When an event occurs (when a user clicks a button)

- When it is invoked (called) from JavaScript code

- Automatically (self invoked)

Let's see example of each -:
1. When an event occurs (when a user clicks a button)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kw3nq8c46ltf6z0yy7p6.png)
So here when button is clicked `fun` function is invoked.

2. When it is invoked (called) from JavaScript code
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0hfyrue4f0wnip0awvx6.png)
So here when `fun` is called then the function is executed.

3. Automatically (self invoked)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7grcv26odxqwrm9wdtzc.png)
In this example, the arrow function is immediately invoked after its definition using the parentheses `()` surrounding it. This pattern is known as an Immediately Invoked Function Expression (IIFE). The function is invoked automatically as soon as the JavaScript interpreter encounters it, without needing to be explicitly called elsewhere in the code.

So this was all about this post. I hope you liked it. In the next post we are going to learn about arrays and its methods. Till then stay connected. Don't forget to follow me :)
#3075. Maximize Happiness of Selected Children
Published: 2024-05-09 07:47:30

https://leetcode.com/problems/maximize-happiness-of-selected-children/?envType=daily-question&envId=2024-05-09

```javascript
/**
 * @param {number[]} happiness
 * @param {number} k
 * @return {number}
 */
var maximumHappinessSum = function (happiness, k) {
    let res = 0
    happiness.sort((a, b) => b - a)

    for (let i = 0; i < k; i++) {
        res += Math.max(happiness[i] - i, 0)
    }
    
    return res
};

```

One tip from this question is: 

```javascript
Math.max(happiness[i] - i, 0)
```

Subtracting the value from it's index and making the results that are less than 0 to be 0 just solves the question.

Still feels like magic to me.
Empowering Businesses: Markytics Consulting Redefining Artificial Intelligence Solutions in India
Tags: ai, aicompanies, dubai, india
Published: 2024-05-09 07:45:10

In the dynamic landscape of **_[artificial intelligence (AI) companies in India](https://www.markytics.com/artificial_intelligence/
)_**, Markytics Consulting stands tall as a beacon of innovation and excellence. With a strong presence in Pune and Mumbai, Markytics has been revolutionizing the industry with its bespoke AI solutions for over 15 years. Despite its roots in Maharashtra, Markytics caters to clients across India, offering unparalleled AI consulting services that drive business growth and transformation.

Markytics Consulting's commitment to delivering cutting-edge AI solutions is evident in its diverse portfolio of services. From Mumbai to Dubai, Markytics has earned a reputation for excellence, offering top-notch AI consulting tailored to the unique needs of each client. Whether it's implementing AI-powered analytics solutions or developing machine learning algorithms, Markytics Consulting excels in delivering tangible results that propel businesses forward.

As one of the top **_[AI consulting firms in India](https://www.markytics.com/artificial_intelligence/
)_**, Markytics Consulting is dedicated to staying ahead of the curve and embracing emerging technologies. With a team of seasoned experts and a relentless focus on innovation, Markytics is well-positioned to continue leading the charge in the ever-evolving field of artificial intelligence.

Join us as we explore how Markytics Consulting is reshaping the [AI landscape in India](https://www.markytics.com/artificial_intelligence/
) and beyond, empowering businesses to thrive in the age of digital transformation.
ESP32 WiFiManager and ArduinoJson 7
Tags: esp32, cpp
Published: 2024-05-09 07:40:22

```
#include <WiFi.h>
#include <WiFiManager.h>
#include <ArduinoJson.h>

// ตั้งค่า WiFiManager
WiFiManager wm;

// ตั้งค่า JSON document
StaticJsonDocument<200> doc;

void setup() {
  Serial.begin(115200);

  // รีเซ็ตการตั้งค่า WiFi เมื่อกดปุ่มรีเซ็ตนาน 3 วินาที
  wm.resetSettings();

  bool res = wm.autoConnect("ESP32-AP");

  if (!res) {
    Serial.println("Failed to connect");
    // ไม่สามารถเชื่อมต่อ WiFi ให้เข้าสู่โหมด Deep Sleep
  } else {
    Serial.println("Connected to WiFi");
  }

  // เพิ่มข้อมูลลงใน JSON document
  doc["sensor"] = "BME280";
  doc["data"][0] = 24.5;
  doc["data"][1] = 65.2;

  // สร้าง JSON string จาก JSON document
  String output;
  serializeJson(doc, output);
  Serial.println(output);
}

void loop() {
  // ไม่มีการทำงานอื่นในลูป
}
```
#506. Relative Ranks
Published: 2024-05-09 07:38:46

https://leetcode.com/problems/relative-ranks/?envType=daily-question&envId=2024-05-08

```javascript

/**
 * @param {number[]} score
 * @return {string[]}
 */
var findRelativeRanks = function (score) {
    const copy = [...score].sort((a, b) => b - a)
    const ranks = ["Gold Medal", "Silver Medal", "Bronze Medal"]
    const result = new Array(score.length)

    for (let i in score) {
       let index = copy.indexOf(score[i]) 

       if (index < 3) {
        result[i] = ranks[index]
       } else {
        result[i] = (index + 1).toString()
       }
    }

    return result
};

```
What are the common mistakes learners make while learning to code?
Tags: coding, programming, softwaredevelopment, learningtocode
Published: 2024-05-09 07:31:29

Learners often make several common mistakes while picking up coding skills:

**1. Skipping the Basics:** Many rush into complex topics without a solid grasp of fundamentals like loops, variables, and basic logic, which are crucial for understanding more advanced concepts.
**2. Lack of Practice:** Simply watching tutorials or reading books isn’t enough. Coding requires hands-on practice to build and reinforce skills.
**3. Not Debugging Effectively:** Beginners sometimes avoid debugging their code, missing a critical learning opportunity to understand their mistakes and how to fix them.
**4. Isolated Learning:** Trying to learn everything alone without seeking help or engaging with other learners can slow progress and limit exposure to different problem-solving approaches.
**5. Overwhelm from Resources:** With countless resources available, it's easy to jump between different learning materials without making meaningful progress in any.
Recognizing and addressing these pitfalls early can significantly enhance the learning experience and development of coding skills.
[Get access to our coding course](https://tinyurl.com/m5pb4zk6) if you need one.  
You can also check the [5 Mistakes I made while learning to code](https://softwaredevelopmentinsights.com/top-5-mistakes-i-made-while-learning-to-code-and-how-you-can-avoid-them/).
Guess What? Your JavaScript Array is an Object! 🤔
Tags: webdev, javascript, beginners, programming
Published: 2024-05-09 07:30:28

In the quirky world of JavaScript, where the unexpected often becomes the rule, arrays are actually objects. If you're new to programming or coming from other languages, this might seem a bit odd. So, let's dive into why JavaScript treats arrays this way and what it means for you as a developer.

**What's in a Type?**

JavaScript is known for its loose typing system. Unlike more rigid languages that require explicit declarations, JavaScript uses dynamic typing. This flexibility is part of what makes JavaScript both powerful and perplexing.

When you use the `typeof` operator on an array, JavaScript returns `object`. Here's a quick example:

```js
let fruits = ["apple", "banana", "cherry"];
console.log(typeof fruits); // Output: "object"
```
**Arrays are Special Objects**

The reason arrays are considered objects in JavaScript is due to how the language is designed. In JavaScript, arrays are essentially objects with extra capabilities and a special internal property known as `length`. This `length` property automatically updates as the array grows or shrinks, something typical objects don't do.

**What Does This Mean for You?**

Understanding that arrays are objects clarifies several JavaScript behaviors:

- **Property Access**: Like objects, you can access array elements using bracket notation `(array[index])`.

- **Flexibility**: Arrays can have properties added to them, just like objects. However, it's best practice to use arrays for numerically indexed data and objects for named properties.

- **Methods and Prototypes**: Arrays inherit from `Array.prototype`, allowing them to use methods like `.push()`, `.pop()`, and `.map()` which are not available in ordinary objects unless explicitly added.

**Conclusion**

The classification of arrays as objects in JavaScript might seem like a small detail, but it has significant implications on how you write and understand code. By embracing JavaScript's flexibility and understanding its nature, you can write more effective and efficient code.

Next time you declare an array, remember, you're technically working with a specialized object!
Unlocking Success with IT Consulting: Your Friendly Neighborhood CPA at SAI CPA SERVICES.
Tags: accounting, bookkeeping, fbar
Published: 2024-05-09 07:25:59

Sai CPA Services has gained a vast array of experience in Financial and Consulting Services. We offer a wide range of services to our individual and business clients. Being a relatively small firm, we can offer our clients personalized and quality service. We deliver our services in an efficient and cost-effective manner. SAI CPA Services is dedicated in helping its clients to make intelligent financial decisions and ethically minimize Tax Liabilities. We ensure that every client is treated with high regards. Mr. Ajay Kumar, CPA MBA, has sound knowledge and over 20 years’ experience in accounting, internal control, financial statement analysis, review and audit of financial statements Certified Public Accountant from State of New Jersey. Member, New Jersey Society of Certified Public Accountants (NJSCPA) as well as Member of American Institute of Certified Public Accountants (AICPA). Our organizations are designed to be effective & efficient. Collaborative decision boards & tailored decision processes.
[](https://www.saicpaservices.com)

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