teleren/devto huggingface dataset:
REDUCE for Array
Published: 2023-02-16 01:27:54

.reduce()

Reduce iterates over array elements. Reduce needs one additional argument. 

books.reduce((accumulator, otherParam) => {
   return accumulator; 

}, 0); the 0 here is the starting point or what gets iterated over.

If we wanted to count up the number of books sold from among our array, we would have the following...

const books = [
{title: The Great Gatsby, author: Fitzgerald, sales: 2},
{title: Odyssey, author: Homer, sales: 1889},
{title: Hyacinth, author: Julien Linde, sales: 275},
{title: Goldfinch, author: Tart, sales: 1089}
];

const bookSales = books.reduce((accumulator, book) => {



return accumulator + book.sales;

}, 0);

console.log(bookSales)
Building software for cattle farmers. Part 3. Active users
Tags: mobile, android, kotlin, tristan
Published: 2023-02-16 01:13:21

### Introduction
- In this series I take you along, week by week as I release my app and update you on all of the challenges I have faced from the previous week.
- The app I have built is an app that allows cattle farmers to track their calves during calving season

### My app on the Google play store
[HERE](https://play.google.com/store/apps/details?id=com.elliottsoftware.calftracker)

###GitHub code
- [HERE](https://github.com/thePlebDev/CalfTracker)

### Table of contents
1. [Active Users](#introduction)
2. [Code refactors](#paragraph1)
3. [What is next?](#next)

### Active Users <a name="introduction"></a>
- It is with great pleasure that I am able to announce my application now has 3 active users(and only one is my dad)!!! So what does this mean for the future of my application? First and foremost it is really exciting and motivating to know other farmers are finding value in my app. Now on a more realistic side of things I need to start thinking about a monetization plan, data storage is only free for so long. For monetization I am thinking about a basic SAS subscription model, which sounds easy, but implementing it will probably less so. 
- If anyone has any experience with implementing subscriptions on Android, please reach out to me.

### Code refactors <a name="paragraph1"></a>
- This past week was a big week for code refactoring. Specifically I used the [Twitter Jetpack Compose Rules](https://twitter.github.io/compose-rules/) to refactor a large chunk of my compose code base. I even made a little blog post about it, which can be found [HERE](https://dev.to/theplebdev/writing-cleaner-jetpack-compose-code-with-the-twitter-compose-ruleset-3cn3). I still have quite a lot of code to refactor but I am now able to write more flexible compose functions.

### What is next? <a name="next"></a>
- Looking forward into the next week I really have three main thing I need to get done to be able to consider it a successful week:

`1. New features:` I have one final basic feature to implement. This feature will allow farmers to track what medicine they have given their calves and when they have given it. Once this feature is implemented I will mark `version 1` of my application complete

`2. Code refactors:` I still have a lot of compose code to refactor and all of it needs to be done.

`3.Instrumented tests:` Once I have the compose code nicely refactored, I should be able to write instrumented tests. I would like to aim for a 80% test coverage on my UI tests. I will definitely be making tutorials on this subject.

###Conclusion
- Thank you for taking the time out of your day to read this blog post of mine. If you have any questions or concerns please comment below or reach out to me on [Twitter](https://twitter.com/AndroidTristan).
Using different PAM configuration
Tags: linux, bash, pam
Published: 2023-02-16 01:12:22

✨ **Tally2** maintains a count of failed login attempts for each user and can lock accounts if a threshold of failed attempts is reached. It provides a way for system administrators to enhance security by enforcing restrictions on user authentication attempts

✨ **Access** allows system administrators to define rules in the `/etc/security/access.conf` configuration file that specify which users and groups are allowed or denied access to specific services or files on the system

✨ **Pwquality** checks the strength of user passwords against a set of predefined criteria, such as length, complexity, and age, and can reject weak or easily guessable passwords

---

## `pam_tally2`

Locking your account if your password is wrong for more than nth number of times

```bash
vi /etc/pam.d/sshd

# Including this in the first line
auth       required     pam_tally2.so deny=3 unlock time=600
```

We can test the above by trying to login with a user (any other user than root)

If we enter a wrong password for more than 3 times, the account will be 'locked'. Even if we enter the correct password after 3 wrong attempts, we won't be able to access the user for 600 seconds

We can use the following command to see currently locked user

```bash
pam_tally2

Login        Failures    Latest   failure    From
user1           5       02/16/23   09:21:44    192.168.1.1
```

To reset the failures and unlock the account

```bash
pam_tally2 -u user1 --reset=0
```

---

## `pam_access`

Adding the following line just under all of the `auth` lines

```bash
account    required     pam_access.so
```

Now we can go to the `.conf` file for `access`

```bash
vi /etc/security/access.conf
```

We will be able to see different examples in this file to set access settings

I have added the following at the end

```bash
124 -:user1:ALL
```

This will deny `user1` to get access from all sources

So now if we try to login as the `user1` it should force kick us out and not let us login

---

## `pam_pwquality`

In the `system-auth` config file

```bash
vi /etc/pam.d/system-auth

# At line 15
     15 password    requisite     pam_pwquality.so try_first_pass local_users_only retry=3 authtok_type=
```

We can include `minlen=12` at the end and try to set the password for user2 to

`12#$qwER`

But the above is 8 letters not 12. That is true however as I have used a combination of numbers, upper and lower-case letters, and symbols, it added **points** per unique combination

There are 4 unique combinations in the above password so it will make,

8 + 4 = **12**

We can also use the following conditions as well

- **ucredit:** The minimum credit requirement for uppercase letters in user passwords
- **lcredit:** The minimum credit requirement for lowercase letters in user passwords
- **dcredit:** The minimum credit requirement for digits (numbers) in user passwords
- **ocredit:**The minimum credit requirement for other (non-alphanumeric) characters in user passwords
Publishing A Package To NPM
Tags: npm, javascript, node, beginners
Published: 2023-02-16 00:50:41

Npm is a popular package manager for Node.js, which provides a vast range of libraries and packages that can be installed and used to enhance your projects. Creating and publishing a package on Npm is a straightforward process, and this guide will walk you through the steps to successfully publish your package on Npm.

## Step 1: Create your package

To begin, create your package using your preferred programming language. Your package should include a package.json file, which contains essential information about your package, such as its name, version, and dependencies. To create a package.json file, run the following command in your terminal:

```
npm init
```

This command will prompt you to provide all the necessary details about your package. It's essential to ensure that the package name is unique and descriptive to help users find your package.

## Step 2: Add your files to Git

The next step is to add your files to Git. Ensure that your package files are in a Git repository, and you have committed all the changes.

## Step 3: Create an Npm account

To publish your package, you must first create an Npm account. If you already have an account, skip this step. You can create an account by running the following command:

```
npm adduser
```

## Step 4: Publish your package

Once you've created an Npm account, it's time to publish your package. Use the following command to publish your package:

```
npm publish
```

Npm will then prompt you to log in with your Npm credentials. Once you've logged in, Npm will publish your package to the registry. If everything is successful, you should see a success message, indicating that your package has been published.

## Step 5: Manage your package

Congratulations, your package is now published on Npm. You can view your package and manage its details by visiting the Npm registry. You can also update your package by making changes to your package.json file and re-publishing your package using the npm publish command.

## Conclusion

Publishing a package on Npm is a simple and straightforward process that anyone can do. By following the steps outlined in this guide, you can publish your package and share it with the community. Remember to keep your package up-to-date and always respond to issues and queries from your users. Good luck and happy publishing! Please leave a comment below and give me your npm account so I can use your packages. Consider stopping by our [discord server](https://discord.gg/KpGXAEnVnv) and getting to know the team I work with
TexCreate v3 Betas!!!
Published: 2023-02-16 00:49:35

I would like to announce that a few days ago I had published the first beta of TexCreate version 3. I had written a guide on getting started in the [TexCreate Github repo](https://github.com/MKProj/texcreate) and instead I will dedicate this post to cover what's been implemented and what needs to be worked on before v3.0.0 is considered stable for me. 

To view the other projects that are related to TexCreate v3, take a view at the [`texc_v3_sources` repo](https://github.com/MKProj/texc_v3_sources)

## What's been implemented 
- TexCreate repo template system 
  - Storing latest repos in the `$HOME/.texcreate` directory 
- Custom template support 
- Proper project structure creation 
  - An issue with version 2 was input paths that would cause compile errors 

## What needs to be worked on 
- TexCreate.com proper front end to show latest and older releases 
- Documentation for ...
  - `texcreate` 
  - `texcore` 
  - `texcreate_gen` 
- Figuring out how to compile LaTeX asynchronously 


## Features to be implemented 
- `extra` feature: 
   - `make` command 
      - Would add `makefile` option to config 
   - `compile` command 
      - Would add `compiler` option to config
- Considerations 
  - `web` command for local web interface 
  - `generate` command for interaction with `texc_gen` 

## Templates to be added from v2
> Note currently v0 only contains the `basic` template 

- `code` 
- `dictionary` 
- `lachaise` 
- `lachaise_modified` 
- `news` 
- `novel` 
- `theatre`
The GPT-3 Prompt Generator V-3.0
Tags: chatgpt, gpt3
Published: 2023-02-16 00:44:06

Hello everyone!

I'm excited to announce my new project, the GPT-3 Prompt Generator V-3.0. This project uses the OpenAI API to generate responses to prompts based on different options that you choose. The options include simulating an expert, challenging conventional narratives, using unconventional prompts, ultra-brainstorming, adding in human-written techniques, writing from different perspectives, and writing in different styles or tones such as satire or irony.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6wxguweu3zgfq7tjou21.jpeg)

To use the GPT-3 Prompt Generator V-3.0, simply choose an option and enter the prompt you want the program to respond to. You can also specify the role you want the AI to act as and provide any additional context or information. The program will then generate a response using the OpenAI text-davinci-003 engine.

I'm always looking to improve this project, so I welcome any feedback or suggestions. If you want to check out the code or contribute to the project, please visit my [Github](https://github.com/felipeOliveira-1/gpt3_prompt_generator). Thank you for reading and I hope you enjoy using the GPT-3 Prompt Generator V-3.0!
Networking on AWS - Part 4
Published: 2023-02-14 19:52:14

In the previous parts, we discussed the basics of networking on AWS, setting up and configuring a VPC on AWS, and advanced networking concepts on AWS. In this part, we will take a closer look at some best practices for networking on AWS.

Use a Well-Planned IP Address Scheme

When creating a VPC, you need to plan your IP address scheme carefully. It is essential to allocate IP address ranges that are appropriate for the size and complexity of your deployment. You should also consider the potential growth of your deployment and ensure that you have enough IP addresses to accommodate future growth.

Use Multiple Availability Zones

To ensure high availability, you should spread your instances across multiple availability zones. This will ensure that your application remains available in the event of an outage in one availability zone.

Use Security Groups to Control Traffic

Security groups allow you to control inbound and outbound traffic to and from your instances. You should use security groups to restrict traffic to only the necessary ports and protocols. You should also ensure that security groups are configured correctly for each instance type.

Use Network Access Control Lists (ACLs) to Control Traffic

Network ACLs are a stateless firewall that can be used to control traffic at the subnet level. You should use network ACLs to restrict traffic to only the necessary ports and protocols. You should also ensure that network ACLs are configured correctly for each subnet.

Use VPC Flow Logs

VPC Flow Logs allow you to capture information about the traffic flowing in and out of your VPC. This information can be used for troubleshooting, security analysis, and performance analysis. You should enable VPC Flow Logs for all your VPCs.

Conclusion

In conclusion, networking on AWS requires careful planning and execution. By following best practices such as using a well-planned IP address scheme, using multiple availability zones, using security groups to control traffic, using network ACLs to control traffic, and using VPC Flow Logs, you can ensure that your deployment is secure, reliable, and performant.

It is also essential to keep up-to-date with the latest features and best practices on AWS to ensure that your deployment remains secure and compliant with industry standards. By following these best practices, you can create a highly available and secure architecture for your applications on AWS.
Code Smell 196 - Javascript Array Constructors
Tags: webdev, javascript, beginners, programming
Published: 2023-02-16 00:43:40

*Array creation is homogenous and predictable, or is it a hack?*

> TL;DR: Be very careful with Javascript Arrays.

# Problems

- The Least surprise principle violation

# Solutions

1. Be as declarative as possible

2. Avoid creating Arrays with one argument.

# Context

Javascript has a lot of magic tricks.

Knowing them makes some developers proud and a sense of belonging to juniors.

A language should be intuitive, homogeneous, predictable, simple, and pure.

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/5d0644c120630d637c9649d7c92805c7)
```javascript
const arrayWithFixedLength = new Array(3);

console.log(arrayWithFixedLength); // [ <5 empty items> ]
console.log(arrayWithFixedLength[0]); // Undefined
console.log(arrayWithFixedLength[1]); // Undefined
console.log(arrayWithFixedLength[3]); // Undefined
console.log(arrayWithFixedLength[4]); // Undefined
console.log(arrayWithFixedLength.length); // 3
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/a7f4c59210257cb279efc6747b4e3122)
```javascript
const arrayWithTwoElements = new Array(3, 1);

console.log(arrayWithTwoElements); // [ 3, 1 ]
console.log(arrayWithTwoElements[0]); // 3
console.log(arrayWithTwoElements[1]); // 1
console.log(arrayWithTwoElements[2]); // Undefined
console.log(arrayWithTwoElements[5]); // Undefined
console.log(arrayWithTwoElements.length); // 2

const arrayWithTwoElementsLiteral = [3,1];

console.log(arrayWithTwoElementsLiteral); // [ 3, 1 ]
console.log(arrayWithTwoElementsLiteral[0]); // 3
console.log(arrayWithTwoElementsLiteral[1]); // 1
console.log(arrayWithTwoElementsLiteral[2]); // Undefined
console.log(arrayWithTwoElementsLiteral[5]); // Undefined
console.log(arrayWithTwoElementsLiteral.length); // 2
```

# Detection

[X] Automatic 

We can check for the notation with one argument and flag it as a warning.

# Tags

- Smart

# Conclusion

Many "modern" languages are full of hacks to make life easier for programmers but are a source of potential undiscovered bugs.

# Relations

{% post https://dev.to/mcsee/code-smell-06-too-clever-programmer-37lb %}

{% post https://dev.to/mcsee/code-smell-69-big-bang-javascript-ridiculous-castings-49ij %}

{% post https://dev.to/mcsee/code-smell-93-send-me-anything-16m3 %}

# Disclaimer

Code Smells are just my [opinion](https://dev.to/mcsee/i-wrote-more-than-90-articles-on-2021-here-is-what-i-learned-1n3a).

# Credits

Photo by [Ryan Quintal](https://unsplash.com/@ryanquintal) on [Unsplash](https://unsplash.com/photos/US9Tc9pKNBU)
  
Originally on this tweet:

{% twitter 1621103384731287554 %}
  
* * *

> When someone says, "I want a programming language in which I need only say what I want done," give him a lollipop.

_Alan J. Perlis_
 
{% post https://dev.to/mcsee/software-engineering-great-quotes-26ci %}

* * *

This article is part of the CodeSmell Series.

{% post https://dev.to/mcsee/how-to-find-the-stinky-parts-of-your-code-1dbc %}
Building a RESTful API with Node.js and Express: A Step-by-Step Guide
Published: 2023-02-16 00:38:39


In today's web development world, RESTful APIs are essential in building modern web applications. In this blog post, we will explore how to create a RESTful API using Node.js and Express.

**Prerequisites**
Before we begin, you should have the following installed on your machine:

Node.js
NPM (Node Package Manager)

Step 1: Create a new Node.js project
First, create a new directory for your project and navigate to it in your terminal. Then, run the following command to create a new Node.js project:

```
npm init -y
```
This will create a new package.json file in your project directory.

**Step 2: Install required dependencies**
Next, we need to install the necessary dependencies for our project. Run the following command to install express, body-parser, and cors:

```javascript
npm install express body-parser cors
```
**Step 3: Create a server using Express**
Now that we have the necessary dependencies installed, we can create a server using Express. Create a new file called index.js in your project directory and add the following code:

```javascript
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();

app.use(bodyParser.json());
app.use(cors());

const port = 5000;

app.listen(port, () => {
  console.log(`Server is running on port: ${port}`);
});
```
This will create a new Express server with CORS support and JSON body parsing middleware.

**Step 4: Add routes to your server**
Next, we need to add some routes to our server. Add the following code to your index.js file:

```javascript
app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.post('/api/users', (req, res) => {
  const { name, email } = req.body;

  res.json({ message: `User ${name} with email ${email} was created.` });
});
```
This will create two routes - one for a simple "Hello World" message, and another for creating a new user.

**Step 5: Test your API**
To test your API, run the following command in your terminal:

```javascript
node index.js
```
This will start your server on port 5000. You can then use a tool like curl or Postman to make requests to your API.

For example, to create a new user, you can send a POST request to http://localhost:5000/api/users with a JSON body like this:

```javascript
{
  "name": "John Doe",
  "email": "john.doe@example.com"
}
```
This will return a JSON response with a message indicating that the user was created.

**Conclusion**
In this blog post, we explored how to create a RESTful API using Node.js and Express. We covered the necessary dependencies, creating a server using Express, adding routes to the server, and testing the API. With this knowledge, you can start building your own RESTful APIs and take your web development skills to the next level.

[![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4e8rf68auayri7e1nrnq.png)](https://www.buymeacoffee.com/bhavikgevariya)

Small support comes a long way!
MAP, MAP, MAP
Published: 2023-02-16 00:32:35

.map

Let's Goooooooooo

Map can transform the array. It doesn't change or mutate the old one, it creates a new one.  

you can do this really neat thing with arrays where you can utilize the .map feature to add only to those nested objects where a certain criteria is met, the ones that don't meet the criteria don't have any value added, not even to say that it is false. 

say you have an array of books. Each book has a objects that have its title, author, and number of sales. from number of sales you know that if the total sales exceeded 100 (sales in thousands), it was a best seller. 

here's the code that would allow you to add in the value if the object should have the best seller line added. 

const books = [
{title: The Great Gatsby, author: Fitzgerald, sales: 2},
{title: Odyssey, author: Homer, sales: 1889},
{title: Hyacinth, author: Julien Linde, sales: 275},
{title: Goldfinch, author: Tart, sales: 1089}
];

const updatedBooks = books.map(book=> book.sales > 100 ? {...book, bestSeller: true} : book);cons

console.log(updatedBooks)

btws... you will have to add in quotes around the author and title values 

.forEach() 

This is powerful and lets us work off the arrays we have built. 

Using the array we created above with the bestSeller value included, we can alert the user if the book was a best seller. We will demonstrate chaining here. 

books.map(book=> book.sales > 100 ? {...book, bestSeller: true} : book).forEach(book => {
if (book.bestSeller) {
  console.log(`${book.title} written by ${book.author} was a best seller!!`
   }

})
static website forms
Tags: hugo, webdev, html
Published: 2023-02-16 00:19:35


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

If you are using a static website generator (SSG) like Hugo, Jekyll, eleventy or many of the others, to create static websites (only plain HTML, CSS, Javascript) you may we wondering how can you can create a contact form and collect all the form submissions if there is not website backend.

This is were the use of a forms back-end comes into play.

I will be showing you in this quick tutorial a very good [static website forms](https://fabform.io) backed called Fabform.



First create a free account at https://fabform.io

From there, click on Create Endpoint and give it any name you like.

Make a note of the form_id for your newly created endpoint.

In your website, you create your HTML contact form in the usual way.

The only difference will be you point the forms action method to your newly created endpoint on fabform

```
<form action="https://fabform.io/f/{form_id}" method="post">
  <label for="email">Your Email</label>
  <input name="Email" id="email" type="email">
  <button type="submit">Submit</button>
</form>

```

Voila! That's it folks. You have a fully working static website contact form that will collect all your contact form submissions.