teleren/devto huggingface dataset:
How to Use Environment Variables (env) in ExpressJs
Tags: node, express, javascript
Published: 2021-10-21 13:49:28

Well, hello!
If you're coming from frontend development with Vue, or React, you know that environment variables (.env) are initialized behind the scenes i.e. You don't have to require and use `dotenv`. However, when writing backend with, Expressjs, for instance, you have to initialize it like so:-
```javascript
require('dotenv').config({path: './.env'});
```


## Problem: Env variable not found
A friend was building an API with Expressjs. He needed to connect to stripe for the payments. The response from stripe was `Authorization headers are missing`. He couldn't get why this was happening despite the fact that he had defined the Stripe Secret Key on the environment variables (.env), and used it when initializing "stripe" npm package. 

## Server.js

```javascript
..
const stripeRoute =  require("./routes/stripe")
..
require('dotenv').config({path: './.env'});
..
```

## routes/stripe.js

```javascript
const stripe = require("stripe")(process.env.STRIPE_KEY);
```

## .env
```
STRIPE_KEY=key_goes_here
```

# Soln: Define environment variables before using them

The error was as a result of defining the Stripe routes before requiring the `.env`. This solved his issue: 


```javascript
require('dotenv').config({path: './.env'});

const stripeRoute =  require("./routes/stripe")

```

Personally I like to define my environment variables at the start of the server file.
3-Ways Ghost Display Confirm Button
Tags: codepen, javascript, showdev, beginners
Published: 2021-10-21 13:46:33

<h1>3-Ways Ghost Display Confirm Button</h1>

<h2>Description</h2>

<p>I used lots of "3"s this time! 😅</p>

<p>I tried to render a 3D image using ThreeJS.</p>

<p>At first, I was intimidated by ThreeJS, because it is a 3D rendering engine! I mean, at first, I thought 3D was too complicated that it's impossible for me to understand the underlying concept about it.</p>

<p>Although it was actually complicated to understand (Yes, because I understood the concept of 3D in different way. I mostly created 3D rendering by using HTML and CSS), it is actaully really fun to learn! It makes me wonder of what others object I could create using modelling tool like Blender, or just use the default geometry provided by ThreeJS, and just add a texture on it.</p>

<p>I thought of using GSAP in animaton, because why not? I mean I already know the main concept in how to use this animation tool.</p>

<p>There are lots of commented-out codes here. I will not clear these comments for me to use those as my reference in the future.</p>

<h2>Other descriptions</h2>

<p>When you hover on the "confirm" button, there are minion of ghosts will appear, and march anywhre randomly. I created these animations using GSAP.</p>

<p>When you try to click the "cancel" button, a blocking ghost will get in your way. I created the model using just HTML and CSS.</p>

<h2>Next Steps</h2>

<p>My next goal I think is to create an animated GLTF file, then use ThreeJS to animate this.</p>

<p>Also maybe, I could be more ambitious, to actually create a 3D game.</p>

<p>I will also try to improve my skills in creating a 3D model using Blender.</p>

<p>And I'm also thinking to create an object using these primitive geometries provided by ThreeJS, also the textures.</p>

<h2>Resources</h2>

<ul>
<li>
<a href="https://www.blender.org/">Blender</a> - I used this as my 3D modelling tool to create the model of the large ghost.</li>
<li>
<a href="https://threejs.org/">ThreeJS</a> - I used this to render my 3D model into the webpage.</li>
<li>
<a href="https://greensock.com/">GSAP</a> - I used this to create an animation of the Ghoost, and also its minions.</li>
</ul>

<p>I created the model of this ghost by referencing that famous donut tutorial on the popular video streaming site.</p>

{% codepen https://codepen.io/takaneichinose/pen/vYJGowE %}
Laravel Tip: Set a seeding seed
Tags: php, laravel
Published: 2021-10-25 09:30:59

---
title: Laravel Tip: Set a seeding seed
published: true
date: 2021-10-21 13:33:07 UTC
tags: php,laravel
canonical_url: 
---

![](https://cdn-images-1.medium.com/max/1024/0*g8ZGPRgxuogGpZtj)<figcaption>Photo by <a href="https://unsplash.com/@gallarotti?utm_source=medium&amp;utm_medium=referral">Francesco Gallarotti</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption>

Pretty much all apps will eventually have some quite complex seeding that occurs for local development. This is the best way to quickly apply a large amount of data to your database or other data stores.

Sometimes it can be really useful to have seeds to debug issues that you might not expect, especially with UI where it’s hard to make a test to catch out when a name is too long for a UI component.

The problem with that though is that seeding while using Faker is completely random and so reproducing that problem might actually be difficult to do.

Our seeding data doesn’t have to be completely random though, we can in fact apply a seed value which will make sure the data always generates the same data (as long as the code generating the data does not change).

A seed is essentially an initialising value for a random number generator. For the Faker library this allows you to use a string, number or some value that will be a starting point for all random values generated in sequence. This means, using the same seed produces the same result each time. This is until you change the code and generate another value from Faker. You can read more about this in the package’s [documentation](https://fakerphp.github.io/#seeding-the-generator).

We can apply this method across the board by adding a small snippet of code to the register method of a Service Provider class. In the example we simply used the AppServiceProvider.

{% gist https://gist.github.com/peterfox/7f7a35a8afb177c747196bc6aab6af4c %}

Now each time a seed runs, the data will be consistent until we change anything like the factory classes or the seeders themselves. As you can see in the example code we are using an environment variable to set the seed so that way each developer can use their own seed for seeding but can quickly try out someone else’s.

### Conclusion

This is all pretty simple stuff but could have a real impact to your team. Give it a go and see if it helps your team debug more issues before they hit production.

I’m Peter Fox, a software developer in the UK who works with Laravel among other things. Thank you for reading my article, I’ve got several more on both medium and dev.to. If you want to know more about me, head over to [https://www.peterfox.me](https://www.peterfox.me/). I’m also now also [Sponsorable on GitHub](https://github.com/sponsors/peterfox?frequency=one-time&sponsor=peterfox). If you’d like to encourage me to write more articles like this please do consider dropping a small one off donation.
How I made a URL shortener app -> From making To deployment
Tags: javascript, beginners, webdev, node
Published: 2021-10-21 13:30:13

![alt text](https://api-staging-shortio.herokuapp.com/accessstats)

## Shortbit
The name of the app we created is [**Shortbit**](https://shortbit.netlify.app/). This is pretty simple application that makes a long URL into a short URL and gives more in-depth insights of the link clicks and all other stuff such as the number of clicks, links shortened, from where the link is being clicked, which browser, referrer channel etc. These all things are visualized graphically.

## Tech used
All the tech used for this app is **MEAN** stack
**MongoDB** used for storing data of users, short URLs and some other stats.
**Redis** used for maintaining user sessions.
**Amazon SQS** helped in counting stats.
**Angular** for front-end and all other normal stuff.


## Behind scenes
All the implementation is pretty simple. Same as other URL shortener apps finds the long link with the given short link code and redirects the user to the long link.

But after redirecting how can we count the stats like country, referrer channel, browser, device and other stats ?

At first we made this as a simple project that doesn't counts any stats and it just redirects the user.

After then we implemented counting stats logic with some known modules of NodeJS for processing a request and storing the stats. All this logic went well but when there are a huge number of requests server stopped working and again we need to restart the app.

After then we tried to implement a message broker that holds the request data in a queue and then a micro service pick each item from the queue and consumes it and updates the related stats data.
We searched for a free service provider of Message Broker service. Unfortunately we didn't find any provider that goes with a free plan. 

Then [**Amazon SQS**](https://aws.amazon.com/sqs/) helped us to make the requests save in the queue and helped the consumer microservice to consume the requests in the queue and updated the stats.

## Deployment
As the idea of the app is completely free. We hosted the whole back-end part of the app in [Heroku](https://www.heroku.com/). And tried of serving front-end also from back-end heroku dyno, but it costed us more in consuming the free dynos. So for front-end used [Netlify](https://www.netlify.com/). For hosting a single page application we need to make necessary [changes](https://answers.netlify.com/t/page-not-found-after-deployment/2362) such that we won't face any issues after reloading a page.

## Conclusion
Please feel free to check the [app](https://shortbit.netlify.app/) we made. It's just a simple project that helps us to know and develop more deeper insights in creating any applicaiton.
Thanks for reading !!!
PWA or AMP: What is Better for a Business?
Tags: pwa, amp, webdev, frontend
Published: 2021-10-21 13:23:37

{% youtube wmERTvauYgk %}
Let's talk about PWA and AMP. How are they different and what should you choose?

🟣 What is AMP and PWA?
🟣 What is the difference in functionality? Why can’t we use PWA’s only? 
🟣 How to choose technology for your business?
🟣 AMP with functions of PWA: how does it work? 
🟣 Which technology do you prefer? 
🟣 If PWA development is much more difficult than AMP?

You can also read the article at [Frontend House](https://frontendhouse.com/experts-zone/pwa-or-amp:-what-is-better-for-your-business-experts-zone-talks-7)
[VIDEO] How to Deploy a Node.js App on Ubuntu with PM2, NGINX and Cloudflare
Tags: node, javascript, devops, ubuntu
Published: 2021-10-21 13:12:00

In this video you will learn how to deploy a Node.js application ready for production on an Ubuntu server using the following:

- A specific Node.js version
- PM2 to allow you to run and manage your Node application 24/7 
- Nginx setup as a reverse proxy so that your users could access your website via HTTP on port 80
- Cloudflare so that you could use a domain name and secure your website with a free SSL certificate 

<mark>**DigitalOcean free $100 credit:**</mark>
https://m.do.co/c/2a9bba940f39


{% youtube 9FvgyWDsViA %}

All commands used in the video can be found here:

https://www.digitalocean.com/community/tutorials/how-to-set-up-a-node-js-application-for-production-on-ubuntu-16-04


Follow me on [Twitter](https://twitter.com/bobbyiliev_)
DevBox Showcase: Fake Data Generator
Tags: productivity, tutorial, json, generator
Published: 2021-10-21 13:07:00

Hi 👋,

This is the third post in the series showcasing tools from [DevBox](https://www.dev-box.app) 🎉, a desktop application or browser extension packed with everything that every developer needs.

-------

DevBox has a **Fake Data generator tool**. Once DevBox is opened, click on its card: 

![Faker Card](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rv11jm3tru106va63y7l.png)

Now you can see the interface to generate fake data (annotated):

![Fake Data Generator Interface](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y59kx3l4bcfp4ywc689y.png)

Once you are happy with the generated values, you can copy it to the clipboard or download it as a JSON file.

-------

You can still buy DevBox [here](https://gdotdesign.gumroad.com/l/devbox/earlybird) for **a lifetime price of ~~$25~~ $20 💰**, get it while it's available!

More DevBox showcases are coming, so follow me here if you want to be notified!
CWE-77
Tags: applicationsecurity, softwarevulnerabilit, softwaresecurity, appsec
Published: 2021-10-26 21:20:05

---
title: CWE-77
published: True
date: 2021-10-21 13:03:14 UTC
tags: applicationsecurity,softwarevulnerabilit,softwaresecurity,appsec
canonical_url: https://blog.shiftleft.io/cwe-77-bf222588a521
---

#### Improper Neutralization of Special Elements used in a Command (‘Command Injection’)

![](https://cdn-images-1.medium.com/max/1024/1*ZIsvZXYMCVSXoqpmMSHerQ.jpeg)

CWE-77 refers to command injection, a vulnerability that allows malicious parties to control parts of the application by providing input that influences how the application behaves. In short, the attacker could control how the app behaves, compromising the app itself and potentially its data as well.

### Why command injection vulnerabilities are problematic

Command injection vulnerabilities allow attackers to perform actions they would otherwise not be able to perform. This potentially allows them to modify the behavior of the application, as well as gain access to sensitive data.

Variations, such as command-line injections or operating system (OS) injections, are commonly found, but there are additional ways that command injections can occur as well.

### How command injection attacks occur

Command injection attacks occur when user-provided input is accepted and used as part of a command executed by the application. For example, the user input might be used to find a file. The input is appended to a command that looks for a file and returns the content to the user. Without proper sanitization, users could modify this behavior (e.g., append a command to delete the folder contents).

This ability offers a malicious party the means to do something they would not otherwise be able to (either because they lack the proper authorization or ability to do so directly). Furthermore, the way that the programming language is structured may allow attackers to string together and execute multiple commands, all at once.

### Mitigating command injection vulnerabilities

Any instance where user input is accepted and used without proper sanitization could lead to a command injection vulnerability. As such, sanitization and allowlisting are simple strategies that can help.

However, it can be difficult to allowlist the accepted values properly; the best mitigation strategies include using libraries to implement the desired functionality. Additionally, limiting the scope of the command (e.g., set permissions so that users cannot access/modify/open privileged files) can help.

### TL;DR

Command injections are a general class of vulnerabilities primarily arising due to unsanitized user input that’s then used in a command executed by the application. Sanitization of user input, allowlist, implementing functions with libraries, and securing privileged files are all methods of mitigating the risk of command injections.

* * *
Deploy Elastic Beanstalk Application with Terraform
Published: 2021-10-21 12:54:18


AWS Elastic Beanstalk is a managed service for deploying and scaling web applications and services. It supports languages such as Java, .NET, PHP, Node.js, Python, Ruby, Go, and also Docker. You can deploy these applications on Apache, Nginx, Passenger, and IIS.

But Elastic Beanstalk has a lot of configurations. With Terraform we can automate this process. Later we can use the same Terraform script just changing variables.

With this Terraform configuration, we will create PHP 8.0 Elastic Beanstalk WebServer Environment on Amazon Linux 2 and Nginx. Also Application Load Balancer and SSL certificate for our domain. We will validate this certificate, create A record for our domain and it will be pointed to Elastic Beanstalk Environment. In the end, it will create Cloudwatch alarms for Elastic Beanstalk Environment Health, LoadBalancer 5xx requests, and network out the traffic of our instances.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/seo0mdc923n38a06n6ue.png)
>Structure of our Terraform Configurations


**Requirements**

[Create EC2 Key Pair ](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html)
Creating key pair in the EC2 console and using the name of that key pair in Terraform is a secure way than passing the public key pair file in Terraform.

[SNS Topic](https://docs.aws.amazon.com/sns/latest/dg/sns-create-topic.html)
When Cloudwatch alarms are triggered you will get notifications via SNS. You can add subscriptions like E-Mail, SMS, or HTTP-HTTPS endpoint like Opsgenie. You can use the same SNS Topic later in different alarms.

[Route53 Public Hosted Zone](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/CreatingHostedZone.html)
SSL Certification and DNS Records for your domain


**Deployment**

Clone the repository.
```
git@github.com:emreoztoprak/terraform-aws-elasticbeanstalk.git
```
Change the variables in the terraform.tfvars file

> I set up one subnet for EC2 Instance and two subnets for ALB. You can change this any number you want.

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

When everything is ready you can deploy with these 4 commands.

```
terraform init
terraform validate
terraform plan
terraform apply

```


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

[Github repo](https://github.com/emreoztoprak/terraform-aws-elasticbeanstalk)

I hope it was useful. Thank you for reading this article.
Product recommendation engine
Tags: machinelearning, aws
Published: 2021-10-21 12:53:24

Personalized product recommendation engine
Vue.ai’s product recommendation engine tracks website shoppers' behaviour based on their user behaviour. We tracked their historical and live data and based on that we provide product recommendations to them. Every shopper should delight in getting an individualized shopper experience. personalized recommendations that convert 120% better.

Drive growth with personalized product recommendations. Make every customer feel special with 1:1 curated & personalized recommendations that convert 120% better.A personalized experience at every touchpoint. Delight every shopper with truly individualized shopper experiences and grow your revenue.
Style Profiles
Build unique Style Profiles for each shopper based on their likes, affinities, and visual preferences.
Dynamic Personalization
Gauge shopper intent in real time with every click they make, to power relevant product discovery.
Recommendation Strategies
Deploy a variety of product recommendation engine  strategies to improve shopper engagement and conversion.
AI-Powered Search and Sorting
Leverage the power of Image Recognition to serve individualized search results to every shopper.

https://vue.ai/products/product-recommendations/
Using D3js, How to find the x,y coordinates after rotation respect to centre of rectangle in plan?
Published: 2021-10-21 12:32:07

I tried using this
 x` = (x-c1)*con(rotation)-(y-c2)*sin(rotation)+c1;
 y` = (x-c1)*sin(rotation)+(y-c2)*cos(rotation)+c2;
where c1,c2 is the centre points of object or rectangle.

Help me give me proper solution......
Day 13 of 100 Days of Code & Scrum: Product Backlog and Failing to Use Twitter
Tags: 100daysofcode, beginners, programming, webdev
Published: 2021-10-21 12:25:54

<small><cite>Image by <a href="http://jfbrett.github.io/">Jeremy Brett</a> from <a href="https://medium.com/@jfbrett/gobear-scotch-tape-and-sticky-notes-sprinting-singapore-style-b1f0c114a0fb">Medium</a></cite></small>

Hello there, everyone!

I made a lot of progress with Scrum today, and I think I'm probably mostly familiar with all of the concepts I need to learn for the Professional Scrum Master I (PSM I) certification. Not much GraphQL though.

Oh, and it was also my first time [using Twitter](https://twitter.com/RamminaR), and I 
had no idea what to do. :sweat: I haven't really used social media that much in my life. 

![Business Cat](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zdsve1a0tr5ku9m74ecj.gif)

## Yesterday

I finished the draft of the Scrum Master subsection and the Scrum Artifacts of my Scrum Guide for beginners, did some practice questions for Scrum.

## Today

### Scrum

- added a `Product Backlog` section for my Scrum Guide.
- added a `Sprint Backlog` section for my Scrum Guide.
- did a lot of practice quiz questions about Scrum (spent like a few hours on them).

### GraphQL

- continued learning about GraphQL server-side.
- read more about `resolver functions`.
- learned more about the `info` argument in GraphQL resolvers.
- review concepts I've learned last week.

I wish everyone a great Thursday! Thank you for reading!

![Good Luck](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1sqi2pecw4fq6dhghdkr.jpg)

### Resources/Recommended Readings

- [The 2020 Scrum Guide](https://scrumguides.org/scrum-guide.html)
- [Mikhail Lapshin's Scrum Quizzes](https://mlapshin.com/index.php/scrum-quizzes/)
- [GraphQL Basics: Demystifying the `info` Argument in GraphQL Resolvers](https://www.prisma.io/blog/graphql-server-basics-demystifying-the-info-argument-in-graphql-resolvers-6f26249f613a)
- [A Short Introduction to the Scrum Framework by Jim Medlock](https://medium.com/chingu/a-short-introduction-to-the-scrum-methodology-7a23431b9f17)

### DISCLAIMER

This post only expresses my thoughts and opinions (based on my limited knowledge) and is in no way a substitute for actual references. If I ever make a mistake or if you disagree, I would appreciate corrections in the comments!

### Other Media

Feel free to reach out to me in other media!

<span><a target="_blank" href="https://www.rammina.com/"><img src="https://res.cloudinary.com/rammina/image/upload/v1638444046/rammina-button-128_x9ginu.png" alt="Rammina Logo" width="128" height="50"/></a></span>

<span><a target="_blank" href="https://twitter.com/RamminaR"><img src="https://res.cloudinary.com/rammina/image/upload/v1636792959/twitter-logo_laoyfu_pdbagm.png" alt="Twitter logo" width="128" height="50"/></a></span>

<span><a target="_blank" href="https://github.com/Rammina"><img src="https://res.cloudinary.com/rammina/image/upload/v1636795051/GitHub-Emblem2_epcp8r.png" alt="Github logo" width="128" height="50"/></a></span>
Dynamic programming
Published: 2021-10-21 12:12:26

Dynamic Programming is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of subproblems, so that we do not have to re-compute them when needed later. This simple optimization reduces time complexities from exponential to polynomial. For example, if we write simple recursive solution for Fibonacci Numbers, we get exponential time complexity and if we optimize it by storing solutions of subproblems, time complexity reduces to linear.

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

Advantage of dynamic programming:
The advantage of dynamic programming is that it can obtain both local and total optimal solution. Also, practical knowledge can be used to gain the higher efficiency of dynamic programming. However, there is no unifiedstandard model for dynamic programming, multiple condition may appear during the solving process.

disadvantage of dynamic programming:
It takes a lot of memory to store the calculated result of every subproblem without ensuring if the stored value will be utilized or not. Many times, output value gets stored and never gets utilized in the next subproblems while execution.