teleren/devto huggingface dataset:
I need some help with layout and link (Portfolio in React)
Tags: react
Published: 2024-03-04 23:08:23

Hi everyone,

I'm currently learning React and Nextjs, and I've taken a tutorial on creating a portfolio.
The tutorial in question only focuses on the HomePage, and I'm having trouble creating the other pages.
As the "My projects" screen shows, I'd like to create 4 new pages ( project1.tsx/project2.tsx...) to present my 4 projects in detail. (screen 1)
I've created a link with the props id so that each project container can be clicked on and linked to the pages for each project (screen 2 & 3).
The pages in question (project1.tsx/project2.tsx..) are located in my app folder, which also contains my layout (layout.tsx) and my homepage (page.tsx)(screen 3 & 4)
The problem: When I click on each of the 4 containers, I'm redirected to the correct page address ( /project1 /project2...) but it doesn't load and the content doesn't appear (screen 5 & 6).
I don't know if it's a problem with my layout or the link.
Could you help me?

Thanks for taking the time to read me :)
Have a nice evening! 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u01ks446oh1djizrgph9.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v0ceuk6kjejtgsiw2ssn.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/enyt2abcs2adupe19bhx.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qpzavxgq8fhrhejm5fog.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0c2ous3mn22ljqre0lpu.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tnoomfa777b09dy5lr70.png)
10x API Start-up Boost
Tags: aws, lambda, api, performance
Published: 2024-03-04 22:55:18

I while ago I optimized my [Screen Saver Gallery](https://bliskavka.com/Screen-Saver-Gallery) API by loading a flat data file into lambda memory. A nightly job selects a random subset of the database and stores it in S3, and the API uses that file for the next 24 hours.

This simplified my code, reduced costs, and improved performance.

The average API calls took 50-100ms! ...but the start-up time was **5 seconds**!!!

I was using a lambda warmer, so most clients didn't hit the 5-second latency, but I wondered if I could reduce it.

## Before

1. A nightly process reads data from Dynamo DB and generates a zip file that looks like this:

   - cache.zip
     - tableA.json
     - tableB.json

2. The zip file is stored in S3
3. When the lambda starts, it loads the zip file from S3, and loads it into memory (Duration: 4-5 seconds)

   ```typescript
   let cache: Record<string, ITable>;
   ```

4. All future requests are served from the in-memory cache (50-100ms)

## Attempt 1

Instead of loading from S3, store the zip file in a lambda layer, and rebuild the layer every night.

Result: This reduced the start-up by 1 second.

## Attempt 2

The layer improved the load time, so it was a good start, but I felt like it should be faster.

I added some basic timers to my warmup function and discovered that almost 3 seconds were spent parsing the 217 files from the zip file.

I updated the code to parse the table files in parallel but it only shaved off 500ms.

## Attempt 3

Armed with the timing information, I understood that my load issue was computationally constrained - decompressing zip files requires CPU cycles.

I refactored my lambda layer cache to be a single `cache.json` file that looks like this

```json
{
  "tableA": [],
  "tableB": []
}
```

The lambda can load the data using `readFileSync('/opt/cache.json')` and parse it immediately.

Presto: Start-up load time is 500ms - a 10x improvement!

## Conclusion

If your data is relatively static you can cache it as a flat file in a Lambda layer to reduce app complexity, costs, and startup times. Use a Lambda to periodically query a new data set and publish a new Lambda Layer Version.

When using layers, your maximum package size is 250MB. By compressing your data files you can cache A LOT of data, but you will experience decompression latency.
Amazon Workspace problems with SSH Key
Tags: amazon, linux
Published: 2024-03-04 22:54:17

Sometimes the Amazon Workspace restarts, and if you already created the SSH Key, and after you restart the workspace you can't push any change to Gitlab, you can do it again with this command.

```bash
ssh-add KeyToAddSSH
```

Then you can push your changes without any problem.

Happy Coding!!!
HIRE A HACKER TO RECOVER LOST / STOLEN CRYPTO - GO TO OMEGA CRYPTO RECOVERY SPECIALIST HACKER
Tags: webdev, javascript, beginners, tutorial
Published: 2024-03-04 22:29:36


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rjq7djve2by5s4g6eris.jpg)OMEGA CRYPTO RECOVERY SPECIALIST is the best hacker to recover lost or stolen crypto because of their proven track record, reliable and efficient services, and prioritization of client satisfaction. The team has helped numerous clients recover their funds over the years and has a wealth of experience and expertise....... Furthermore, the team works quickly to recover funds, which is crucial in the fast-paced world of cryptocurrency.


Homepage : omegarecoveryspecialist .c om
Django Framework is Dead 😵
Tags: webdev, python, django, programming
Published: 2024-03-04 22:26:22

Ladies and gentlemen, gather 'round, for I bring grave news from the world of Python web development. It is with a heavy heart that I declare the passing of our dear friend, Django framework.


![Django Web Framework](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8esmtwufptte8he6agx5.png)
But before you shed a tear or organize a funeral procession, let me assure you – Django is very much alive and kicking!

Yes, you read that correctly. Despite the ominous title, Django is far from dead. In fact, it's thriving more than ever, and here's why.

As we bid adieu to the era of monolithic frameworks and embrace the brave new world of micro services and serverless architecture, _some may have prematurely written off Django as a relic of the past_. But let me remind you of Django's timeless virtues – its elegance, **its simplicity, its "batteries-included" philosophy that has endeared it to developers for decades**.

While other frameworks may come and go, Django stands the test of time. Its robust ORM, its sleek admin interface, its powerful authentication system – these are not features of a dying framework, but the hallmarks of a mature, battle-tested tool-set that continues to evolve with the times.

So, why the provocative title, you ask? Well, dear reader, it's all about grabbing your attention and sparking a conversation. Sometimes a little irony is the best way to cut through the noise and make a point.

And the point is this – Django may not be the shiny new toy on the block, but it's the dependable workhorse that gets the job done. Whether you're building a simple blog or a complex enterprise application, **Django has your back**, providing a solid foundation upon which to build your dreams.

So, let's raise a toast to Django – not in mourning, but in celebration of its enduring legacy and the countless projects it has powered over the years. If you are a perfectionist with a deadline to meet, you should definitely try Django. Long live Django!
Example of a MongoDB Query that uses $elemMatch
Published: 2024-03-04 21:53:53

> Check out our Classroom API Postman Collection and subscribe to it on AWS Marketplace.

A simple example to illustrate MongoDB’s $elemMatch. In the code below, we fetch courses a teacher has access to.

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

There are 3 arguments to this method:

- user: A user object so we can return courses this particular user has access to.
- acl: What level of access should this teacher have?
- archived: Return archived or unarchived courses as dictated by this boolean.

## Could the query have looked like this instead?

Let’s try removing the use of $elemMatch and make the query simpler.

`where :_type.in => [PlanitApp::PrivateTeacherCourse, PlanitApp::SharedTeacherCourse],
          :archived => archived,
          :"authorization.users.id" => user.id,
          :"authorization.users.acl" => acl`

Will this work and return what we expect? **Not quite.**

Our intent is to return only those courses where the given user _(user.id)_ has a certain level of access _(acl)_ but authorization.users is a nested array of users with multiple attributes _(with ID and ACL being two of those)_. Though we want both those conditions to be applied within that nested array in the document, not using $elemMatch will not scope the results to only those courses as it will instead apply each of those conditions separately across different documents in that collection thereby returning incorrect results.

---

So, when you use nested arrays in a NoSQL document, be wary of this.

---
Lessons from opensource: Use Object.defineProperty to create an unwritable object’s property.
Tags: javascript, nextjs, node, react
Published: 2024-03-04 21:30:48

These lessons are picked from [next.js](https://github.com/vercel/next.js/tree/canary/packages/next) open source code. In this article, you will learn how to create an unwritable property using Object.defineProperty.

## Object.defineProperty

[Object.defineProperty()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty) is used to add a new property directly to an object.

If you are looking to practice next.js, checkout my website: https://tthroo.com/

Execute the following in your browser’s console.

```
const object1 = {};

Object.defineProperty(object1, 'property1', {
  value: 42,
  writable: false,
});
```

Try to make the following modification using the same console:

```
object1.property1 = 11
```

![Object.defineProperty()](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g2tw4z01darrh928gb7w.png)

Because writable is set to false, you are not able to modify the property1 value. [MDN docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty) has awesome documentation about this.

Object.defineProperty has **data descriptor** like shown in the above image and **accessor descriptor** (this is what is used in next.js source code explained below)

### Where is Object.defineProperty used in nextjs codebase?

You can find Object.defineProperty used in next.js code here.

![https://github.com/vercel/next.js/blob/canary/packages/next/src/client/router.ts#L89](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1i3m5bxd3nkq11m6awxz.png)

## Conclusion:
You do not have the flexibility to make a property unwritable when you create an object using const obj = {}. In case, if you ever need to have an unwritable property in an object, use Object.defineProperty with unwritable set to false.
Conditionally Add CSS Classes to Your Views and Components
Tags: rails, quicktip
Published: 2024-03-04 20:00:00

[_This article was originally published at Rails Designer_](https://railsdesigner.com/conditional-css-classes-in-rails/)

With the release of Rails 6.1, the `class_names` view helpers [was introduced](https://github.com/rails/rails/pull/37918). It is one of those helpers I use _a lot_.

Before you had to write some hard to read code:

```erb
<div class="<⁠%= item.for_sale? ? 'active' : '' %>">
```

But with the `class_names` helper, you can do:

```erb
<div class="<⁠%= class_names(active: item.for_sale?) %>">
```

Both output the following HTML (assuming `item.for_sale?` returns true):

```html
<div class="active">
```

More advanced is the following:

```ruby
class_names("item", { active: item.for_sale?, "out-of-stock": item.out_of_stock? })
```

Here `item` is applied in _all cases_. And `active` / `out-of-stock` only when the respective conditionals are met.

The `class_names` helper is also supported in tag-helpers. So this works just the same:

```ruby
<⁠%= tag.div class: class_names(active: item.for_sale?) %>
```

Or even shorter, like this:

```ruby
<⁠%= tag.div class: [active: item.for_sale?] %>
```

It's one of those little, unknown features in Rails that helps you write better views and components. No wonder it is used in almost all [Rails Designer's components](https://railsdesigner.com/).
GroupBy and Join in Spark
Tags: spark, sql, dataengineering
Published: 2024-03-04 21:25:26

In the next three videos for the [Data Engineering Zoomcamp](https://github.com/datatalksclub/data-engineering-zoomcamp), we learned about Spark internals and the SQL commands GROUP BY and JOIN. 

Spark uses partitioned data. Each executor takes one partition and works on it until it's done, then takes another partition, until all the partitions are done being processed. In the case of a GROUP BY, the first pass can only group whatever is in one partition. The executors do this and store the results in temporary intermediate files. That means that if you are grouping by day, for example, there may be all the days in each parquet file. Each executor groups all the days in one partition, but there are many such groups across all the partitions.

So the output of this first step is a set of temporary files, each belonging to one partition, that has the grouped data in it. The next step is called "reshuffling", where the data from all partitions is combined for the final result.

Here's an example of a GROUP BY command, where we're grouping by the hour and the zone, counting the number of records and adding the revenue for that day and zone:

```python
df_green_revenue = spark.sql("""
SELECT 
    date_trunc('hour', lpep_pickup_datetime) AS hour, 
    PULocationID AS zone,

    SUM(total_amount) AS amount,
    COUNT(1) AS number_records
FROM
    green
WHERE
    lpep_pickup_datetime >= '2020-01-01 00:00:00'
GROUP BY
    1, 2
""")
```
Here's a visualization from Spark, showing the two stages of the GROUP BY command.

![Spark visualization of GROUP BY](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/42lp8uabihc14zfjphsc.png)

JOIN works similarly when the files being joined are large and approximately the same size. We made another set of files from yellow taxi data, similar to the above, and then joined them with the Spark command `df_join = df_green_revenue_tmp.join(df_yellow_revenue_tmp, on=['hour', 'zone'], how='outer')`. This is an outer join, meaning that if the first dataframe doesn't have any data for the hour and zone, but the second one does, we'll keep the record and put Null for the first dataframe. We'll do the same if the second dataframe doesn't have any data for the hour and zone, but the first dataframe does.

Here's the visualization from the Spark UI:

![Spark visualization of complex JOIN](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rpdtf2sla5r5k0s38bdj.png)

When one file is considerably smaller than the other, Spark can accomplish the join in one pass. It copies the smaller file into each executor along with the partition and does the join completely within the executor.

Here we're joining the zone and borough data from the zones file, which only has 250 or so records.

```
df_result = df_join.join(df_zones, df_join.zone == df_zones.LocationID)
```
And here's the Spark UI visualization:

![Spark visualization of simple JOIN](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vokc29e20b97atkuqime.png)
Dewy Agency - UI UX Design
Published: 2024-03-04 21:13:14

I'm happy to share with you my last UI design project I've made, which is website for space flights with many magnificent features called" Dewy Agency"🪐🔥

I hope by the following future taht will  be possible in our world 🥳🚀

Tha work link in behance👇
[(https://www.behance.net/gallery/193083573/Dewy-Agency-Space-Flight-Website)]
Strengthening Your Node.js Applications: Essential Secure Coding Practices
Tags: node, security, programming, tutorial
Published: 2024-03-04 21:06:32


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tt53kuabymi0ens8ua3l.jpeg)
In today's digital landscape, where cybersecurity threats lurk around every corner, ensuring the security of your Node.js applications is paramount. With the ever-evolving nature of cyber threats, mastering secure coding practices is not just a good idea—it's a necessity. Whether you're a seasoned developer or just starting your journey with Node.js, adopting robust security measures can safeguard your applications and protect sensitive data from falling into the wrong hands.

This article [Secure Coding in Node.js](https://techscriptlab.com/secure-coding-nodejs-best-practices/) offers invaluable insights into enhancing the security of your Node.js applications. Authored by experts in the field, this comprehensive guide delves deep into the intricacies of secure coding practices tailored specifically for Node.js environments. From implementing encryption algorithms to mitigating common vulnerabilities such as injection attacks and cross-site scripting (XSS), this resource equips developers with the knowledge and techniques needed to build resilient and secure applications.

By incorporating the principles outlined in "Fortifying Node.js Applications: Mastering Secure Coding Practices," developers can bolster their defenses against a myriad of threats, ensuring that their applications remain resilient in the face of evolving cyber risks. Whether you're developing a small-scale project or a mission-critical enterprise application, prioritizing security from the outset is key to safeguarding your assets and maintaining the trust of your users.

In conclusion, the importance of secure coding practices cannot be overstated in today's cybersecurity landscape. With Node.js becoming increasingly popular for building web applications, it's imperative for developers to stay abreast of the latest security protocols and best practices. "Fortifying Node.js Applications: Mastering Secure Coding Practices" serves as an indispensable resource for developers looking to fortify their applications and navigate the complex terrain of cybersecurity with confidence.
Conditionally Add CSS Classes in Your Stimulus Controllers
Tags: javascript, rails, hotwire, stimulus
Published: 2024-03-04 20:00:00

[_This article was originally published at Rails Designer_](https://railsdesigner.com/conditional-css-classes-in-stimulus/)

When you need to create a bit more advanced UI's in your Rails application, [Stimulus](http://railsdesigner.com/what-is-hotwire/) is a great, little framework to easily add sprinkles of JavaScript.

Whenever I have some functionality that is reused in multiple Stimulus controllers, I extract them into “helper” functions. I put these (related) functions in their own file in the `app/javascript/controllers/helpers/` folder.

A common thing I do, similar to [Rails views and components](https://dev.to/railsdesigner/conditionally-add-css-classes-to-your-views-and-components-133p), is conditionally add CSS classes to an element.

For that I use a really simple JavaScript function:

```javascript
// app/javascript/controllers/helpers/class_names.js

export function classNames(options) {
  return Object.keys(options).filter(key => options[key]).join(" ");
}
```

And then in your Stimulus controller:

```javascript
import { Controller } from "@hotwired/stimulus";
import { classNames } from "helpers/class_names";

export default class extends Controller {
  // …

  get tooltipTemplate() {
    return `
      <span
        role="tooltip"
        class="${classNames({"tooltip": true, "tooltip--dark": this.isDarkTheme})}"
      />
    `;
  }
}
```

The tooltip-span will have the `tooltip` class by default, and the `tooltip--dark` only when `this.isDarkTheme` returns true. Getting started is very easy, much like using [Rails’ `class_names`](https://dev.to/railsdesigner/conditionally-add-css-classes-to-your-views-and-components-133p).
func init() {}
Tags: 100daystooffload, go, programming
Published: 2024-03-04 20:46:40

If you are coming from other languages that are OOP based like C#, then you might wonder what tool you can use in Go to do something similar as the constructor in a class.

The solution to this is the [init function](https://go.dev/doc/effective_go#init). This is a function that can be defined in each source file.

```golang
func init() {
   // initialization code
}
```

The function signature tells us that it neither takes any parameters or returns any result, which hints us that it is supposed to produce some kind of side effect. It's is not uncommon to see the expression, **importing a side effect**, which refers to this. From the [The Go Programming Language Specification](https://go.dev/ref/spec#Import_declarations):

> To import a package solely for its side-effects (initialization), use the blank identifier as explicit package name:
> ```golang
>import _ "lib/math"
>```

So this function is the home for initializing variables to get a program to its correct state before everything is starting to run.

Lets do some examples.

```golang
package main

import "fmt"

var message = "Hello, init"

func init() {
	fmt.Println(message)
}

func main() {
	fmt.Println("main")
}
```

This program will produce the following output:

![output from first example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/17ekp1kw2zfu44yjoar3.png)

That's pretty straightforward. First the variable `message` will be declared and then the `init` function will be called, and finally the `main` function.

It is also possible to define several init functions in the same source file.

```golang
package main

import "fmt"

var first = "Hello, init"
var second = "Hello, again init"

func main() {
	fmt.Println("main")
}

func init() {
	fmt.Println(first)
}

func init() {
	fmt.Println(second)
}
```

Which product the following output:

![output from second example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fkd18egvh405ysznutwb.png)

The `init` functions will be executed in the order they are defined in the source file. Note that I moved both init functions after the main function to just show that they still will be executed before the main function.

So what happens if you have several source files in the same package that is using an init function?

```golang
// first.go
package main

import "fmt"

func init() {
	fmt.Println("first.go")
}

// main.go
package main

import "fmt"

func init() {
	fmt.Println("main.go")
}

func main() {
	fmt.Println("main")
}

// z.go
package main

import "fmt"

func init() {
	fmt.Println("z.go")
}
```

The it will execute the init functions based on lexical order of the filenames. Therefore the init in `first.go` will be executed first, then the one in `main.go` and finally the one in `z.go`.

![output last example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x2d9iunvwycuplppk16q.png)

If you browse through the code in the standard packages you will find many cases where the init function has been used. However be careful, side effects can make things harder to understand when reading the code.

Happy hacking!