teleren/devto huggingface dataset:
Replace Nested If Else Statement with Array
Tags: programming, php, array, webdev
Published: 2022-07-12 22:09:04

#Replace Nested If Else Statement with Array
The use of Early return and Array Approach will be considered

##Nested if else
I am very sure we have either written or seen such nested code.

It isn't pleasant to look at. 

```php
public function checkData($var){
    if (isset($var)){
          if ($var==1){
              return 'one';
          }
          elseif($var==2){
              return 'two';
          }
          elseif($var==3){
              return 'three';
          }
          elseif($var==4){
              return 'four';
          }    
    }
    else{
     return 'null';
    }
  
}

```
We can make it better 
##Early Return

```php
public function checkData($var){
    if (!isset($var)){
        return 'null';
    }
    if ($var==1){
        return 'one';
    }
    if($var==2){
        return 'two';
    }
    if($var==3){
        return 'three';
    }
    if($var==4){
        return 'four';
    }
}

```

##Array Approach

```php
public function checkData($var){
    $array = [
    '1'=>'one',
    '2'=>'two',
    '3'=>'three',
    '4'=>'four',
    ];
    return $array[$var] ?? 'null'; 
}
```

The array approach is easy to update and easier to understand as compared to the nested If Else.

The early return also works very fine!

The Array approach can also be used for methods.

##Early return Method calling

```php
public function checkData($var){
    if (!isset($var)){
        return $this->nullMethod($var);
    }
    if ($var==1){
        return $this->oneMethod($var);
    }
    if($var==2){
        return $this->twoMethod($var);
    }
    if($var==3){
        return $this->threeMethod($var);
    }
    if($var==4){
        return $this->fourMethod($var);
    }
}

```


##Array Approach Method calling

```php
public function checkData($var){
 $array_methods = [
    '1'=>'oneMethod',
    '2'=>'twoMethod',
    '3'=>'threeMethod',
    '4'=>'fourMethod',
    ];
    return $this->{$array_methods[$var]($var)};
    
    //to simplify, break it down
    $method=$array_methods[$var];
    return $this->{$method}($var);
}

```
Day 94: Firebase is actually good
Published: 2022-07-12 22:07:06

Hi!
I have been working with Firebase/Firestore for a month now and I have learned a lot about it and some of the benefits that it provides especially when to want to build something fast with out worrying about much configurations
I admit that for all this time I had some doubt about it being less powerful to having your own backend or using something like PostgreSQL as the database. well there is benefits and control that comes with building your own backend and also some things that are weird with Firebase but I know believe that they are both two different types of technologies with different use cases and I'm grateful to many times that I thought a task was going to be tiresome to implement just to find that it's already implemented and ready to use in Firebase utils. no context provided here but that how it is.

Tomorrow the focus will be to app routing and connection to some disorganized pages maybe also work on something else after that

see you there...
Signing off ...
Novedades javascript 2022 📢
Tags: javascript, webdev, programming, news
Published: 2022-07-12 19:32:07

 
Desde el año 2015, JavaScript ha estado realizando constantes actualizaciones anuales con nuevas características añadidas.

ECMAScript 2022 es un nuevo estándar de JavaScript que se ha aprobado este pasado 22 de junio.

Repasaremos en esta publicación alguna de las novedades de esta nueva versión🤗. 

**1. at()** 

¡Por fin! Se acabó el restar "x" número a la longitud de tu lista para acceder a un elemento concreto 🙄👎.
 
Este nuevo método nos permite seleccionar un índice concreto de un array de manera flexible. 

En lugar de esto:

```javascript
const list=[1,2,3,4];
list[list.length -2]; //return 3


const str = "1234"
str[str.length - 2] // return '3'
```

Podemos hacer esto:

```javascript
const list= [1,2,3,4];
list.at(2); //return 3 
list.at(-1); //return 4

const str = "1234"
str.at(-2) //return '3'
```

**2. Object.hasOwn()**

Este nuevo método nos permite comprobar si una propiedad esta incluida dentro del objeto.

```javascript
const myObject={
name:'Carmen',
description:'Aprende Javascript',
fecha:2022
}
Object.hasOwn(myObject,'name'); //return true
Object.hasOwn(myObject,'edad'); //return false

```
**3. Atributos y métodos privados en ES2022**

Ahora podemos crear atributos y métodos privados utilizando la **#** delante del nombre de tu propiedad o método

```javascript
class Admin {
nombre='Carmen';
#apellido='Rendón';

#getYear(){
return '2022';
}
 }

const instancia = new Admin();

console.log(instancia.nombre); //return 'Carmen'
console.log(instancia.#apellido); 
//Property '#apellido' is not accessible outside class 'Admin' because it has a private identifier.
console.log(instancia.#getYear());
//Property '#getYear' is not accessible outside class 'Admin' because it has a private identifier.
```
**4.error.cause**

Nos permite especificar cual ha sido la causa del error.

```javascript
try {
 //...
} catch (error) {
  throw new Error('Ha ocurrido un error', { cause:  error })
}
```

**5.Await**

Ahora podemos declarar un await sin necesidad de que tenga que estar incluido en una función de tipo 'async'.

```javascript
const data = await fetch('get-alumnos');
const alumnos= await data.json();
```


Como vemos javascript sigue renovándose y mejorando con el paso del tiempo 💪. 
Hay otras novedades que han añadido pero para mí estas son las más relevantes. 

Puedes obtener más información de estas [aquí](https://github.com/tc39/proposals/blob/main/finished-proposals.md)

¡Un saludo! 😉
AWS CodePipeline Overview
Published: 2022-12-30 13:14:57

---
title: AWS CodePipeline Overview
published: true
date: 2022-07-12 21:46:52 UTC
tags: 
canonical_url: 
---
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sai0zwjeszgkhp61b4pg.png)

> This is the first series of my CI/CD with AWS CodePipeline and ECS.

Product feedback from customers is something any company doesn't want to joke with, which requires to be companies to be releasing software faster than ever. However, many of these companies struggle to deliver their software to their users. Delays happen when there are no feedback loops and a smooth delivery pipeline to roll out features with or without human intervention.

AWS CodePipeline is a fully managed continuous delivery service that helps teams automate the build, test, and deployment of their applications. It's a powerful tool that helps teams streamline their software delivery process and improve the speed and reliability of their deployments.

Features:

- Easy to use: CodePipeline is easy to set up and use, with a simple web-based interface that allows you to create, configure, and manage your pipelines with just a few clicks.

- Integration with other AWS services: CodePipeline integrates with a wide range of AWS services, including CodeBuild, CodeDeploy, and CodeCommit, allowing you to build, test, and deploy your code using a single, unified platform.

- Customizable pipeline stages: CodePipeline allows you to customize the stages in your pipeline to suit your specific needs. You can add custom actions to each stage, such as running additional tests or deploying to additional environments.

- Automated builds and tests: CodePipeline can automatically build and test your code as it moves through the pipeline, ensuring that the code is always in a deployable state.

- Declarative templates: AWS CodePipeline lets you define your pipeline structure using a JSON document that specifies your release workflow's stages and actions.

Components:

These are the terminologies you will come across when using AWS CodePipeline.

- Pipeline: A pipeline defines your release process workflow and describes how a new code change progresses through the release cycle of your software delivery.

- Actions: an action is part of the sequence in a pipeline stage.

- Stages: Stage is the logical division in your workflow. Each stage is made up of a sequence of actions. Your Pipeline has at least two stages, Source, which is required, and any other.

### Conclusion

AWS CodePipeline is a powerful tool for automating the build, test, and deployment of your applications. Its integration with other AWS services and ease of use make it an essential tool for any team looking to improve the speed and reliability of their software delivery process.

_The next post in this series will walk you through setting up a Pipeline to build a docker image and using GitHub as our Source._

_Kindly subscribe to my newsletter so you can be the first person to know when I release the next post._

Thanks for reading!
Day 93: the Lazy day
Published: 2022-07-12 21:14:01

Hi!

You know that song called the lazy song? the one that goes like "Today I don't feel like doing anything..." that exactly how I was feeling today and I actually didn't do anything well... at least anything code related but I filled some docs and travelled around which is not bad too
today also did a bit of research about relationship in firestore a firebase database and they are not natively available but there are some hacks around that that I will be focusing on tomorrow
I'm also planning to switch to a sleep early wake up early instead of the other way around to compare both differences and that's why I have to go now

signing off...
My Time with Moja Global for Google Season Of Documentation
Published: 2022-07-12 20:31:36

Working with Moja Global for Google Season of Documentation 2022 has been and continues to be an exciting ride. Creating documentation for moja global gave me a new perspective on important concepts like climate change, the effects of climate change on our environment, and, more importantly, how we as a society can mitigate those effects. Although understanding, breaking down, and relaying these concepts have not been the most straightforward tasks, it certainly has been informative and fun.

I was offered the role of "Technical Writer 2", which meant that I was tasked with creating the Full Lands INtegration Tool (FLINT) handbook and credible case studies on both FLINT and the Generic Carbon Budget Model (GCBM). I am also tasked with creating documentation for the "Understanding FLINT" section of the official moja global documentation.

During the first week of settling down, I had an onboarding call with my mentor Harsh Mishra who gave me insights on how to curate content for the moja global documentation. Breaking my tasks into smaller tasks, Harsh advised me on how to approach these tasks not to feel overwhelmed. This hack motivated me greatly to start creating technical content. Unfortunately, I fell ill and was asked to take a break.

For the next two weeks, week two and week three, I studied FLINT and GCBM resources. I used these resources' knowledge to create a FLINT handbook structure. This structure creation process started with a high-level understanding of what the FLINT handbook should cover and ended with creating the FLINT handbook table of contents. Next, I completed a case study describing the natural and anthropogenic effects of disturbances on our forests and how we can use the GCBM tool to assess and report these disturbance effects accurately.

I worked on creating chapters 2 and 3 of the FLINT handbook through weeks 4 and 5. Chapter 2 discussed what FLINT is and, more importantly, the different modules FLINT uses to describe processes that drive carbon changes in a landscape. Chapter 3 discusses GCBM, the data required for the GCBM to simulate carbon flows, and, more importantly, how to conclude from the output that the GCBM gifts us.

Next, I worked on chapter one of the FLINT handbook. This chapter handles fundamental concepts like stocks, flows, states and transitions. This chapter also introduces the reader to organizations that significantly impact global decisions on the war against climate change. It aims to ease the reader into understanding the FLINT handbook.

In the coming months, I will work on finishing the FLINT handbook, creating credible documentation for the understanding FLINT section of the moja global official documentation, and finally, case studies on climate change mitigation.

Finally, I want to thank moja global for this life-changing opportunity to learn and grow as a professional.
Problem with req. query;
Tags: help, mongodb, react, nextjs
Published: 2022-07-12 20:18:22

I'm trying to pull data from a document containing a logged-in user from the MongoDB database. However, req. query doesn't seem to pass.



API:


```
export default async function handler(req, res) {
  const client = await clientPromise;
  const db = client.db("USERS");
  const { userName } = req.query;
  switch (req.method) {
  case "POST": {
    const bodyObject = JSON.parse(req.body);
    const query = {
      user: bodyObject.user,
      avatar: bodyObject.avatar,
      level: bodyObject.level,
    };
    const update = { $set: { score: bodyObject.score } };
    const options = { upsert: true };

    const newScore = await db
      .collection("USERS")
      .findOneAndUpdate(query, update, options);

    res.json(newScore);
    break;
  }
  case "GET": {
    const users = await db
      .collection("USERS")
      .find({ user: { $in: [userName] } })
      .toArray();
    res.json(users);
    break;
  }

  default: {
    // do nothing
  }
  }
}
```

COMPONENT:
 

```
import styles from '../styles/Elements.module.css';
import clientPromise from '../lib/mongodb';
 

export default function ScoreHeader({ users }) {
  console.log(users)
  
  return (
    <div className={styles.containerIndex}>
     fadsfds
    </div>
  );
}

export async function getServerSideProps({}) {
  const client = await clientPromise;
 const db = client.db('USERS');
 
  const res = await fetch(`http://localhost:3000/api/usersAPI`, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
    },
  });
  const users = await res.json();

  return {
    props: { users },
  };
}
```
Validator Function in Haskell
Tags: haskell, programming
Published: 2022-07-12 20:16:32

```haskell
{-# LANGUAGE TypeApplications #-}

module Main where

import Data.Char (isAlphaNum, isSpace)

maxLength :: String -> Maybe String
maxLength "" = Nothing
maxLength xs =
  case (length xs > 20) of
    True -> Nothing
    False -> Just xs

allAlpha :: String -> Maybe String
allAlpha "" = Nothing
allAlpha xs =
  case (all isAlphaNum xs) of
    False -> Nothing
    True -> Just xs

stripSpace :: String -> Maybe String
stripSpace "" = Nothing
stripSpace (x : xs) =
  case (isSpace x) of
    True -> stripSpace xs
    False -> Just (x : xs)

validatePassword :: String -> Maybe String
validatePassword password =
  stripSpace password >>= allAlpha >>= maxLength

main :: IO ()
main = do
  putStrLn "Please enter a password"
  password <- getLine
  print (validatePassword password)
```
Open Source backend in just 1 File
Tags: go, webdev, productivity, opensource
Published: 2022-07-12 20:13:12

Hi, I'm Muneeb, Freelance Front-end Developer. I will keep the post short and to the point.
So I came accross an Amazing Open Source Project called [PocketBase](https://pocketbase.io/) developed in GOLang. I was blown away with the capabilities of this project. Read more on their [repo](https://github.com/pocketbase/pocketbase).

There's no need to manage 100's of file for your backend. you just have a single executable file and that's it. Feels untrue right? I thought that too but when I tried it, I was speechless.

Here are the features mentioned on their website



- Realtime database
- Authentication
- File storage
- Admin dashboard

Just one file. Damn. Here's how to get it
Go to this [link](https://pocketbase.io/docs/) and download the file for your specific OS.

Then you need to unzip the archieve. In my case on Linux I used following commands

Head over to downloads folder where you saved it.

```
cd Downloads
```

Then you need to extract the archieve

```
unzip pocketbase_0.2.4_linux_amd64.zip
```

Then you need to open the extracted folder

```
cd pocketbase_0.2.4_linux_amd64
```

and final step

```
./pocketbase serve
```

Hurrayy!! Your Self-Hosted Real Time Server is rolling on 

```
http://localhost:8090
```
The admin panel UI is hosted on 
```
http://localhost:8090/_/
```
and the REST API is hosted on
```
http://localhost:8090/api/
```
Now go to `http://localhost:8090/_/`

Pretty simple HUH? So here's the first time signup page 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/15ubkbc33ecb5vy1t84d.png)
 
and here's the ADMIN Panel for you. Congragulations, You have your own self-hosted backend in just 5 minutes.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r0bqgqewodjlzpfsg435.png)
 
Thanks for reading my post ❤️ Leave a comment!

[@muneebbug](https://twitter.com/muneebbug)
10 things you should do to become a Project manager
Tags: projectmanager, sofwareengineer
Published: 2022-07-12 20:03:58

---
title: 10 things you should do to become a Project manager
published: true
description: 10 things let you transfer from software engineer to project manager
tags: projectmanager, sofwareengineer
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
---

## 1. Learn as much as you can about product management
you should learn as much as you can about product management white you are still a software engineer.

## 2. Stick to your domain expertise
You should stick to the domain expertise at the beginning.

## 3. Keep and strengthen your SQL knowledge
As a product manager, you constantly need to validate your assumptions with qualitative and quantitative data.

## 4. Skills to use UMLs and User flows
Be a professional for UMLs and user flows. It will help you understand both development and business well.

## 5. Keep open-source mindset
Keep on sharing knowledge generously.

## 6. Make side-project
Prioritising learning above programming.

## 7. Hackathons
Given the time constraint hackathons often just focus on feasibilities test, not desirability test.

## 8. Become a good writer
A skill to master is to learn to write good notes and documentation. Convert notes into action items is the next stage.

## 9. Keep away from solution discussions
To be a PM, you should learn to give the authority about the solution to the developers. The duty of PM is to describe the "why" and "What".

## 10. Get out of GitHub
starting the focus on identifying the user needs and business requirements and learning how to write great user story. GitHub will distract your focus and will ultimately harm the trust as PM among the developers.

This is a summary of this nice talk by Product People. You can check this video on https://www.youtube.com/watch?v=4hnu4FM6qYY
Created a scrollbar plugin for neovim: nvim-scrlbkun
Tags: showdev, neovim
Published: 2022-07-12 19:22:18

![scrlbkun_preview1](https://user-images.githubusercontent.com/9912146/177551550-b4f8c112-1dc5-4fa5-b9eb-1b6fcfd8bf51.gif)

## Introduction

I am using Neovim for programming.
I was initially already using a certain scrollbar plugin, but it was very simple and could not display git, diagnostic or search results.
I had never made a Neovim plugin before, but when I read the source of the plugin, I decided to make my first neovim plugin [nvim-scrlbkun](https://github.com/kensyo/nvim-scrlbkun), because it was not too big and I thought I could implement my own plugin based on it.

nvim-scrlbkun displays the cursor position, the results of git, search, diagnostics in addition to a scrollbar itself, with the auto-hiding feature.

I would be happy if you used it.

## Implementation

nvim-scrlbkun is written in lua.

I had very little experience with lua, but it was very easy to use and I had no trouble understanding the functional aspects of the language. I was used to a language with classes, so the lack of class functionality was a bit painful for me.
Personally, I find it very similar to JavaScript.

nvim-scrilbkun displays a floating window at the right edge of each window, and draws elements such as search, git, diagnostics, on the floating window as virtual text.

I thought about using only virtual text without floating windows, but gave up because the display collapses if there are long lines that are wrapped.

I had a bit of trouble implementing the display of the search results, since the `v:hlsearch`, an internal variable of Neovim, does not change at the moment of search, so I decided to delay rendering the results. It is a simple idea now, but it seemed like a very good idea when I first came up with it(I had to remove some resulting bugs, though).

## Impressions after implementation

Through this experience, I realized again that the best way to improve coding skills is to read codes excellent people write.
I think it is a waste of time if you are struggling on your own, so there is no way you can avoid using github, where you can immediately see codes written by excellent people.
Writing custom middleware functions in NodeJS
Tags: javascript, webdev, beginners
Published: 2022-07-12 19:19:03

Middleware is any code that runs on the server between getting a request and a response. Middleware functions in NodeJS have access to the request object, the response object and the next function. 

```
function middleFunc(req,res,next){
    req.message:'Hello'
    next()
}
```
In the example above, the function middleFunc is a middleware function that takes three parameters: req,res,and next. The function sets a req.message to 'Hello'.

Middleware functions do not end the request-response cycle but they have to call `next()` to either pass execution to the next middleware function or the request handler itself. If `next()` function is not called, the request will hang.

A middleware function can be run by passing it between the path and callback function of the request handler.

```
app.get('/',middleFunc,(req,res)=>{
    res.json(req.message)
})
```
Here, middleFunc will run first then when next() is called, the execution is passed to the request handler which prints the message.

It is also possible to rewrite the middleware function as an Application-level middleware like this,

```
app.use((req,res,next)=>{
    req.message = 'Hello'
    next()
})
```
Disabling installation notifications for Packagist
Tags: cli, webdev, tutorial
Published: 2022-07-12 19:15:51

If you use workflow to run tests along with installing dependencies via composer, you may find it useful to disable sending install statistics to Packagist.

Just add this line of code to the beginning of the script.
```
composer config notify-on-install false
```
As it says in the composer documentation:

> notify-on-install: This allows composer to send notification to a URL whenever a package is installed. This by default is true.
How to add PHP CS Fixer to your project?
Tags: php, programming, tutorial, codequality
Published: 2022-07-12 19:12:34

First of all, add PHP CS Fixer to your project:

```
composer require --dev friendsofphp/php-cs-fixer
```

A configuration file called **.php-cs-fixer.dist.php** needs to be in the root directory of your project if you want to avoid command-line options.

There are many rules that can be set, I usually use these. It follows the **PSR12** code standards and checks both the _src_ and _tests_ directories.

{% embed https://gist.github.com/richardDobron/111144957880e3623a4566efa27cab94 %}

You can find more rules in the [PHP CS Fixer docs](https://github.com/FriendsOfPHP/PHP-CS-Fixer/blob/master/doc/rules/index.rst).

Let’s add a some scripts to **composer.json** file:

{% embed https://gist.github.com/richardDobron/2037ea7e4d875ab49a2288c424922d45 %}

Now, just run composer run fix-style and all your code style errors will be fixed.

The _--dry-run_ flag will run the fixer without making changes to your files.

If you are using Git, add **.php-cs-fixer.cache** (this is the cache file created by php-cs-fixer) to .gitignore:

```
.php-cs-fixer.cache
```