teleren/devto huggingface dataset:
File upload issue in Chrome browser using exceljs with size more than 400kb
Tags: exceljs, nestjs, typescript, restapi
Published: 2023-12-19 18:35:00

Hello all,

I am facing few issues in Rest Service with file upload using **exceljs** and **@nestjs/common(UploadedFile)**.

An Excel file size of 6mb is giving issue in **Mozilla Firefox **and **Google Chrome**, it takes too long time to upload and gives below error (Issue)
**"502 Bad Gateway: Registered endpoint failed to handle the request"**

When I am uploading non Excel file(other than Excel file, ex: docx) of any size in **Mozilla Firefox**, no issues are coming, it giving me INVALID_FILE_FORMAT error, which is right (No issues)

But When i upload a docx of more than 400kb in **Google Chrome**, no error coming and code is coming out of execution, actually it should give INVALID_FILE_FORMAT error.(issue)

**Dependency versions:**
"@nestjs/common": "8.2.3"
"@nestjs/platform-express": "8.2.3",
"exceljs": "4.3.0",

**Code is below:**
//code 
@UseInterceptors(
FileInterceptor("file", {
storage: memoryStorage(),
fileFilter: excelFileFilter,
limits: {
fieldSize: 5 * 1024,
fileSize: 8000000,
},
})
)
@post("uploadFile")
@httpcode(200)
public async processExcelUpload(
@uploadedfile() file: Express.Multer.File
): Promise {

//this code dont have any issues
const workbook: Excel.Workbook = new Excel.Workbook();     
const wb: Excel.Workbook = await workbook.xlsx.load(file.buffer);
const worksheet: Excel.Worksheet = wb.worksheets[0];    
.....etc..
}

**Here is the excelFileFilter code:**

export const excelFileFilter = (
req: Request,
file: Express.Multer.File,
cb: (ex: HttpException, bool: boolean) => void
): void => {
if (!allowedMimeTypesExcel.includes(file.mimetype)) {
return cb(
new HttpException("INVALID_FILE_FORMAT", 400),
false
);
}
return cb(null, true);
};

Please let me know if anyone facing same issue and what is the solution for the same. Many thanks in advance ~Shoban.
ToneTrail
Tags: nextjs, music, react, webdev
Published: 2023-12-19 18:18:17

[ToneTrail](https://tonetrail.vercel.app) is a website I've built which helps users learn music theory from scratch!

Today I'm pulling back the curtain and giving you a sneak peek into our tech wonderland!

### Tech Stack Harmony 🚀
ToneTrail is grooving to the beats of a powerful tech stack: Next.js, React, MongoDB, and Tailwind CSS. Picture this stack as a band— Next.js leading the melody, React jamming on the guitar, MongoDB holding down the rhythm, and Tailwind CSS bringing in the stylish harmonies.

## How It All Comes Together 🎶
So, what's the secret sauce? ToneTrail serves up lessons and exercises seamlessly, allowing you to groove through music theory effortlessly. Lessons are your backstage pass to music theory insights, delivered with the crispness of Next.js and the interactivity of React.

But wait, there's more! Tailwind CSS steps in to make everything look sleek and modern, turning the learning journey into a visually pleasing experience.

## Jamming with Lessons and Exercises 🎸
ToneTrail isn't just a spectator sport; it's your interactive jam session. Dive into lessons to grasp the fundamentals, and then jump into exercises to practice what you've learned. It's like playing your favorite riff over and over until it becomes second nature!

## Tracking Your Musical Odyssey 🎵
Now, here's the real kicker—tracking your progress. ToneTrail doesn't just leave you in the audience; it pulls you onstage with progress tracking. MongoDB is the backstage manager, keeping tabs on your journey and ensuring you hit every high note.

## More Than Just a Lesson Plan 🌟
ToneTrail is not just a platform; it's your musical mentor. I'm all about demystifying music theory, making it accessible, and turning learning into a symphony of fun. Explore major and minor scales, dance with key signatures, and conquer intervals — ToneTrail's got your back.

--- 

So, what are you waiting for? Dive into the world of ToneTrail, where tech meets music, and let the learning riff begin! 🎹

Ready to start your musical journey? Check out [ToneTrail](https://tonetrail.vercel.app) now!

PS. I'm launching on ProductHunt for the first time, and I'd really appreciate it if you could support [my launch](https://www.producthunt.com/posts/tonetrail)!
LAB 10, Releasing the app
Published: 2023-12-19 17:59:25

I took a step forward to simplify the process and make it accessible for everyone. Armed with npm and GitHub, I embarked on an exciting journey that transformed the vision into reality.

**Championing npm for Package Management**

I chose npm as our trusty sidekick for package management. Its simplicity and widespread usage in the Node.js ecosystem made it a natural fit. With a nod to semantic versioning, I marked our initial release with the tag v1.0.0.

**Tagging, Pushing, and a Seamless Release**

GitHub played a pivotal role in the version control strategy. I embraced tagging with `git tag -a v1.0.0 -m "Initial release"` and pushed tags with `git push --follow-tags`. A seamless release followed, thanks to npm. The command `npm publish` catapulted our package onto the npm registry.

**Update Your Docs: README.md Takes the Spotlight**

Documentation is the unsung hero. I updated README.md to reflect the npm installation process. The README now serves as a compass, guiding users through the installation steps and providing a direct link to our npm package.

**User Testing: A Crucial Chapter**

User testing became our compass for documentation updates. Insights gained from user interactions influenced tweaks and improvements, ensuring our documentation resonated with users.

**The Grand Finale: Sharing the Experience**

As I unveil our creation to the world, anyone can explore the magic at [npm](https://www.npmjs.com/package/osdproject) and dive into the source code on [GitHub](https://github.com/sshah135/Converter-txtToHtml).

**Closing Thoughts**

Our journey was not just about lines of code; it was about simplifying a process, making it user-friendly, and sharing the joy with the community. Join us in this adventure, and let's simplify document conversion together!
How to Solve Vercel Server Less function Crushed 500 Error for Express Server.
Tags: programming, react, javascript, serverless
Published: 2023-12-19 17:29:50

## **Introduction**
Working with serverless functions on platforms like Vercel can be a seamless experience, but occasionally, challenges may arise. Recently, I encountered a serverless function crash on Vercel, and I'm here to share how I resolved it.


![Vercel Error Image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/exfzsdgbhosvgmxsnfid.png)

## **The Problem**
The issue manifested as a 500 Internal Server Error, and the logs pointed towards a missing module: Cannot find module 'express'. This error message was puzzling as express was part of the project dependencies. The Error code looks like this,

`Cannot find module 'express'
Require stack:
- /var/task/index.js
- /var/task/___now_launcher.js
- /var/runtime/index.mjs
Did you forget to add it to "dependencies" in `package.json`?
INIT_REPORT Init Duration: 202.73 ms	Phase: invoke	Status: error	Error Type: Runtime.ExitError
Error: Runtime exited with error: exit status 1
Runtime.ExitError`


## **Troubleshooting Steps**

1. Dependency Check
First, I double-checked my `package.json` file to ensure that express was listed as a dependency. Surprisingly, everything seemed fine.

`"dependencies": {
    "express": "^4.18.2"
  },`

2. Vercel Configuration
Next, I revisited the `vercel.json` file. The configuration for serverless functions is crucial here. Previous `config ` was 

```
{
  "version": 2,
  "builds": [
    {
      "src": "index.js",
      "use": "@now/node"
    }
  ],
  "routes": [
    {
      "src": "/(.*)",
      "dest": "index.js"
    }
  ]
}
```


## **The Solution**



```
{
    "version": 2,
    "builds": [
        {
            "src": "index.js",
            "use": "@vercel/node"
        }
    ],
    "routes": [
        {
            "src": "/(.*)",
            "dest": "/",
            "methods": [
                "GET",
                "POST",
                "PUT",
                "PATCH",
                "DELETE",
                "OPTIONS"
            ]
        }
    ]
}

```
I am trying to build and deploy next js applicaiton but it will give me error as dynamic routes error generatestaticParams().
Published: 2023-12-19 17:28:57

Build error occurred
Error: Page "/checklist/[checklistid]" is missing "generateStaticParams()" so it cannot be used with "output: export" config.      
    at C:\Deploy PTass\PTaas\frontend\node_modules\next\dist\build\index.js:1012:59
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Span.traceAsyncFn (C:\Deploy PTass\PTaas\frontend\node_modules\next\dist\trace\trace.js:140:20)
    at async Promise.all (index 6)
    at async C:\Deploy PTass\PTaas\frontend\node_modules\next\dist\build\index.js:892:17
    at async Span.traceAsyncFn (C:\Deploy PTass\PTaas\frontend\node_modules\next\dist\trace\trace.js:140:20)
    at async C:\Deploy PTass\PTaas\frontend\node_modules\next\dist\build\index.js:829:124
    at async Span.traceAsyncFn (C:\Deploy PTass\PTaas\frontend\node_modules\next\dist\trace\trace.js:140:20)
    at async build (C:\Deploy PTass\PTaas\frontend\node_modules\next\dist\build\index.js:187:29)
    at async main (C:\Deploy PTass\PTaas\frontend\node_modules\next\dist\bin\next:150:5)
   Collecting page data  .
Task - 2 (Test Case Design Techniques)
Published: 2023-12-19 17:20:12

Q1. You are testing a form that allows users to schedule appointments with a doctor. The form has the following fields: first name, last name, email, phone number, and appointment date/time. Some more inputs:

- In Name field (first name or last name) if numbers or special 
  characters used it should display as "Please enter Alphabets only"
- In Phone number field if alphabets used it should display as "Please enter Numbers only"
- In Email field if more number of domains used it should display as "Enter a valid email id"

Q2.Suppose you are a software tester and you are assigned to test a new mobile app that has just been developed. The app has three different user roles: basic user, premium user, and admin user. You have been given the following three test scenarios to execute:

1. 

- Verifying Basic users can access limited features.
- Verifying Premium users can access all features.
- Verifying Admin users have access to advanced settings and all actions. 
Expected Results:
- Basic users can only access limited features of the app.
- While premium users can access all features.
- Admin users have access to advanced settings and can perform all actions.

2. 

- Verify that users can successfully delete their accounts when authorized to do so.
- Verify that Passwords meet the required complexity standards.
- Verify that user received a confirmation email upon successful account creation.
Expected Results:

- Users should be able to create and delete their accounts successfully.
- Passwords must meet the required complexity standards.
- Users should receive a confirmation email upon successful account creation.

3.

- Navigate through the app using different user roles.
- Verify that the app doesn’t crash during normal usage.
- Test all major functions and features of the app.
- Test the app performance under various conditions
- Verify that appropriate error messages are displayed.
- Attempt actions that are not authorized for the current user role.
Expected Results:

- Users should be able to navigate through the app without crashes or performance issues.
- Appropriate error messages should be displayed when users attempt unauthorized actions.
Custom BOM Editor
Tags: cadsoftware, cadcustomization, medicaldevicedesgin
Published: 2023-12-19 17:17:47

About the BOM:
BOM is an important feature available in CAD software by default. Even though every CAD software has given the flexibility to the user to configure the BOM according to their requirement, most users want some additional options to be available in BOM. One of our clients was looking for a more powerful BOM feature which will save time and hence increase productivity.

Challenges Faced
There were a range of challenges faced during the course of the project. Few of them are listed below

Sorting capabilities were not available directly in ‘CAD API’ provided UI controls
Only selected columns will be ‘Editable’, which should be configurable. To set certain columns as editable based on user preference was a challenge.
Since the primary key like the part number can also editable, maintaining the map from the BOM row to the part was a challenge
Providing a dynamic highlight of the component(s) in the graphic area when the row(s) is selected was a challenge
Another challenge was excluding the non-topological entities like Dimension, Annotations, etc. while computing the bounding box.
Solutions
After careful consideration of the client need and analysis of the API provided by the CAD system, we decided to develop an ADD-ON inside the CAD system named as “BOM List Editor”. It was also decided to develop the COM component using .Net technology after considering the UI flexibility expected by the client.

Some of the features we included are:

Using the default BOM settings on the first usage of “BOM List Editor”

The list of columns to be displayed can be configured in “BOM Settings”
Shortcut to show “BOM Settings” is provided in “BOM List Editor” UI.
context menu options on in the BOM list for Zoom and Hide Entities
Option to change BOM Hierarchy Level (0, 1, 2… n, ‘All’ and ‘Leaf’)
Option to make certain columns Editable is also provided inside the Settings dialog.
Performance is high even for complex assemblies as the assembly is scanned and the data is cached to avoid repeated scans and hence lags were avoided when the user makes modifications
Exporting to excel along with the column headers information is provided. The checkbox columns are exported as True/False
Properties displayed as checkbox are named with a suffix _BOOL
Automatic size calculation was also displayed as a column in BOM List Editor . Read more about the **[case study](https://cadvisionengineers.com/resources/case-studies/custom-bom-editor/)**
Aplicando Arquitectura Limpia en Desarrollo de Software con Golang
Tags: go, programming, beginners, softwaredevelopment
Published: 2023-12-19 17:17:37

En el mundo del desarrollo de software, la Arquitectura Limpia, propuesta por Uncle Bob, ofrece un enfoque sólido para construir sistemas mantenibles y escalables. Veamos cómo aplicar estos principios en el contexto del lenguaje de programación Go (Golang).

##1. Separación de Capas:
En Golang, organiza tu código en capas bien definidas: dominio, uso de casos, interfaces y controladores. Mantén la lógica empresarial en el dominio, utiliza casos de uso para las interacciones y separa las interfaces de las implementaciones concretas.

##2. Dependencias Unidireccionales:
La arquitectura limpia promueve la dependencia unidireccional, donde las capas internas no conocen nada sobre las externas. En Golang, esto se traduce en importar solo lo necesario. Asegúrate de que las capas internas no dependan de las externas para evitar acoplamientos innecesarios.

##3. Implementación de Interfaz:
Utiliza interfaces en Golang para definir contratos claros entre las capas. Esto facilita las pruebas unitarias y permite la sustitución de componentes sin afectar otras partes del sistema.

##4. Testing:
Golang tiene un sólido soporte para pruebas. Aprovecha esto creando pruebas unitarias y de integración para cada capa. Garantiza que las pruebas reflejen la lógica de negocio y la integridad del sistema.

##5. Inyección de Dependencias:
Aplica la inyección de dependencias para facilitar las pruebas y mejorar la flexibilidad. Golang permite la inyección de dependencias de manera sencilla, lo que facilita la creación de código mantenible y testeable.

##6. Manejo de Errores:
Golang utiliza la gestión explícita de errores. Aprovecha este enfoque para manejar errores de manera clara y consistente en todas las capas. Evita el uso excesivo de errores genéricos y proporciona información significativa sobre la causa de los problemas.

###Conclusión:
Al aplicar la arquitectura limpia en Golang, estás construyendo un sistema modular, fácil de mantener y escalable. La combinación de las características del lenguaje y los principios de la arquitectura limpia te permitirá desarrollar software robusto y eficiente.

Espero que encuentres útiles estos principios al aplicar la arquitectura limpia en tus proyectos de desarrollo de software con Golang. ¡Happy coding!
Advent of Code 2023 - December 18th
Tags: advent, adventofcode, python, december
Published: 2023-12-19 17:15:39

---
title: Advent of Code 2023 - December 18th
published: true
description: My progress with the 2023 version of Advent of Code
tags: advent, adventofcode, python, december
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/36qayk14ewje7rvykeg5.jpg
series: Advent of Code 2023
# published_at: 2023-12-01 17:41 +0000
---

In this series, I'll share my progress with the 2023 version of [Advent of Code](https://adventofcode.com/2023).

Check the first post for a short intro to this series.

You can also follow my progress [on GitHub](https://github.com/robvanderleek/adventofcode).

## December 18th

[The puzzle of day 18](https://adventofcode.com/2023/day/18) was all about using the right algorithm. I must admit I find these puzzles less exciting since I don't know these algorithms by heart and need to look them up (I do write the code implementation myself.)

__My pitfall for this puzzle:__ I forgot the name of the algorithm, a few Googles were needed for that.

{% spoiler Solution here, do not click if you want to solve the puzzle first yourself %}

```python
#!/usr/bin/env python3

with open('input.txt') as infile:
    lines = infile.readlines()
    plan = []
    for line in lines:
        parts = line.strip().split(' ')
        hex = parts[2][2:-1]
        dir = 'R' if hex[-1] == '0' else 'D' if hex[-1] == '1' else 'L' \
            if hex[-1] == '2' else 'U'
        plan.append((dir, int(hex[:-1], 16)))

def shoelace(verts):
    totalX = 0
    totalY = 0
    for idx, v in enumerate(verts[:-1]):
        totalX += v[0] * verts[idx + 1][1] 
        totalY += v[1] * verts[idx + 1][0] 
    totalX += verts[-1][0] * verts[0][1] 
    totalY += verts[-1][1] * verts[0][0] 
    return abs(totalX - totalY) / 2

def to_verts(plan):
    pos = [0, 0]
    verts = [(0, 0)]
    for d in plan:
        if d[0] == 'R':
            pos[0] += d[1]
            verts.append((pos[0], pos[1]))
        if d[0] == 'D':
            pos[1] += d[1]
            verts.append((pos[0], pos[1]))
        if d[0] == 'L':
            pos[0] -= d[1]
            verts.append((pos[0], pos[1]))
        if d[0] == 'U':
            pos[1] -= d[1]
            verts.append((pos[0], pos[1]))
    return verts

verts = to_verts(plan)
trench = sum([d[1] for d in plan])
print((shoelace(verts[:-1]) + (trench / 2)) + 1)
```

{% endspoiler %}

That's it! See you again tomorrow!
📱Solving React Native Challenges: A Recent Android App Issue & Its Resolution 🛠️
Published: 2023-12-19 17:06:49

I wanted to share a recent challenge I encountered while working on a mobile app for Android devices, specifically something that popped up with the OnePlus 10 Pro NE2213 and other models.

🔍 **The Issue**: After releasing a new app version, I noticed multiple exceptions on Android devices. The error message was quite specific: "TypeError: undefined is not a function at getRandomBase64 at getRandomValues". This was intriguing, as it pointed towards a deeper compatibility issue.

🧩 **Root Cause**: Upon delving into the problem, I realized it was linked to the Web Crypto API. This API, which includes the `getRandomValues` function, is a standard in modern browsers and environments. However, it turns out that it's not universally available or fully compatible across all JavaScript environments, particularly in certain mobile contexts.

📲 **OnePlus 10 Pro NE2213**: This device, among others, was one of the primary affected models. The lack of or partial support for the Web Crypto API in its environment led to the mentioned errors.

💡 **The Solution**: To address this, I opted for installing a polyfill, `react-native-get-random-values` for the `getRandomValues` function. Polyfills are a great way to plug the gaps in functionality across different environments, ensuring a more uniform performance and experience.

👨‍💻 **For Fellow React Native Engineers**: This experience underlines the importance of thoroughly testing across different devices and being aware of the variances in JavaScript environment support. Also, the use of polyfills can be a lifesaver in ensuring compatibility and smoothing out these bumps.

If you're a React Native developer, I'd love to hear your thoughts and experiences on similar challenges!

#ReactNative #MobileDevelopment #AndroidDev #JavaScript #ExpoDev #AppDevelopment #EngineeringChallenges
Microsoft PHI-2 + Huggine Face + Langchain = Super Tiny Chatbot
Tags: datascience, ai, machinelearning, deeplearning
Published: 2023-12-19 16:35:33

Microsoft Research today released the latest version of the small language model (SLM) Phi-2, which has only 2.7 billion sets of parameters.

So, In this Post, we will learn what is Microsoft Phi-2, Why Phi-2 is so small, and how to use Microsoft PHI-2, Huggine Face, and Langchain to create a super Chatbot

The full article can be found [Here](https://quickaitutorial.com/microsoft-phi-2-huggine-face-langchain-super-tiny-chatbot/)
Yoshi Pixel Art - Generated w/ JS
Tags: codepen, javascript, css, html
Published: 2023-12-19 16:30:28

I used JavaScript to create a [Yoshi pixel art](https://codepen.io/jakekbuckner/pen/vYborVx) (best viewed in browser). You can change the color of Yoshi, add a grid to it, view the numbers of each created div, and scale the image up and down. 

The way I did it was I used a for loop to generate 900 divs in a grid (30x30). Then I created arrays with the corresponding number (references i in the loop) which colors the div based on the number found in the array. 

I was really excited to create this, as it really helped me continue develop my skills in JavaScript. 

{% codepen https://codepen.io/jakekbuckner/pen/vYborVx %}