teleren/devto huggingface dataset:
5 Useful Array Methods in Javascript
Tags: javascript, typescript, webdev, tutorial
Published: 2021-07-20 23:46:07

Hi, I'm [Aya Bouchiha](https://t.me/AyaBouchiha) today, I'm going to talk about useful Array methods in Javascript.

## every

**every(_callbackFunction_)**: returns _true_ if all elements in an array pass a specific test, otherwise, returns _false_

```javascript
const allProductsPrices = [21, 30, 55, 16, 46];
// false because of 16 < 20
const areLargerThanTwenty = allProductsPrices.every(
	(productPrice) => productPrice > 20
);
// true because allProductsPrices < 60
const areLessThanSixty = allProductsPrices.every(
	(productPrice) => productPrice < 60
);
```

## some

**some(_callbackFunction_)**: returns _true_ if at least one element in the array passes a giving test, otherwise, it returns _false_.

```javascript
const allProductsPrices = [10, 0, 25, 0, 40];
const isThereAFreeProduct = allProductsPrices.some(
	(productPrice) => productPrice === 0
);
const isThereAPreciousProduct = allProductsPrices.some(
	(productPrice) => productPrice > 100
);
console.log(isThereAFreeProduct); // true
console.log(isThereAPreciousProduct); // false
```

## fill

**fill(_value, startIndex = 0, endIndex = Array.length_)** : fills specific elements in an array with a one giving value.

```javascript
const numbers = [20, 254, 30, 7, 12];
console.log(numbers.fill(0, 2, numbers.length)); // [ 20, 254, 0, 0, 0 ]

// real example
const emailAddress = "developer.aya.b@gmail.com";
const hiddenEmailAddress = emailAddress.split("").fill("*", 2, 15).join("");
console.log(hiddenEmailAddress); // de*************@gmail.com
```

## reverse

**reverse()**: this method reverses the order of the elements in an array.

```javascript
const descendingOrder = [5, 4, 3, 2, 1];
// ascendingOrder
console.log(descendingOrder.reverse()); // [ 1, 2, 3, 4, 5 ]
```

## includes

**includes(_value, startIndex = 0_)**: is an array method that returns true if a specific value exists in a giving array, otherwise, it returns false (_the specified element is not found_).

```javascript
const webApps = ["coursera", "dev", "treehouse"];
console.log(webApps.includes("dev")); // true
console.log(webApps.includes("medium")); // false
```

## Summary

-   **every(_callbackFunction_)**: returns true if all elements in an array passed a giving test.
-   **some(_callbackFunction_)**: returns true if at least one element passed a giving test.
-   **fill(_value, startIdx = 0, endIdx = arr.length_)**: fills specified array elements with a giving value.
-   **reverse()**: reverses the order of the elements in an array.
-   **includes(_value, startIdx = 0_)**: check if a giving value exist in an specific array

## References

-   [www.w3schools.com](https://www.w3schools.com/)
-   [www.developer.mozilla.org](https://developer.mozilla.org/en-US/)

Have a nice day!
How to handle form Validation in React ?
Tags: react, javascript, html, reactnative
Published: 2021-07-20 23:06:14

Today I bring you the ultimate way to handle form validation in a react application with a library called formik.

  Formik makes form validation as easy as ......
lets get straight to the point....

npm install formik and thats it, we will also be making use of yup which may be used with Formik but it ain't mandatory if you feel comfortable writing your own form validation


import { useFormik } from "formik"
import * as Yup from "yup"
const FormValidation =()=>{

const signup =(e)=>{
  const formik = useFormik({
   initialValues:{
     name:"",
     email:"",
     password:""
    },
    

   validationSchema:Yup.object({
    name:Yup.string().required('this field is 
    required'),
    email:Yup.string().email('invalid email 
    type').required('this field is required'),
    password:Yup.string().max(16,"password must 
    not be more than 16 characters").required('required')
   }),

    onSubmit =() =>{
      alert(JSON.stringify(values))
    }
  })
}

return (
    <form onSubmit={formik.handleSubmit}>

      <input id="name" name="name" type="text"
       onBlur={formik.handleBlur} onChange= 
      {formik.handleChange}/>
       {formik.errors.name && formik.touched.name 
      ? <div>{formik.errors.name} </div> : ""}


      <input id="email" name="email" type="text" 
      onBlur={formik.handleBlur}
      onChange= 
      {formik.handleChange}/>
       {formik.errors.email && 
            formik.touched.email ? <div> 
        {formik.errors.email} </div> : ""}

      <input id="password" name="password" type="text" onBlur={formik.handleBlur}
      onChange= 
      {formik.handleChange}/>
       
       {formik.errors.password && formik.touched.password ? <div>{formik.errors.password} </div> : ""}
   </form>
);
}
This is pretty much all you need to get started using formik and yup....

for detailed information checkout www.formik.org/docs/tutorial
Day 412 : Trouble Shooter
Tags: hiphop, code, coding, lifelongdev
Published: 2021-07-20 22:05:47

_liner notes_:
- Professional : Pretty productive day. Reviewed some pull requests. Updated some documentation and made my own PR. Got to demo the changes I made to sample application a coworker and I have been building. Basically I added a dashboard that would show the current conversations of an agent and have any new ones show up in a different section of the dashboard. The agent can then click on them to join the conversations. Came out pretty good. My coworker liked it. Just tweaked a couple of things and made it even better. Had another meeting with another coworker about another project I'll be helping with. Then I ended the day playing the role of trouble shooter with helping a community member an issue they are running into.

- Personal : Last night, I watche "Rick and Morty", "Fire Force" and worked a little on my side project. I heard back from the API support with my question. Looks like my endpoint is returning a 403 Unauthorized response to their servers. I'll have to look into that.

![View from a lake in Moraine Lake, AB, Canada looking up at a huge mountain range with a forest in front of it.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w8jb1p90frz4uzhlodc0.jpg)

So one of the devices I'm looking to use lift the van container I'll be building came in yesterday. After dinner and watching "Fire Force", I'm going to put it together and test it out. After that, I'll probably work on my side project and see why my endpoints are returning 403.

Have a great night!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube oYDt37vm2YQ %}
JavaScript Variables!
Tags: javascript, tutorial, beginners, 100daysofcode
Published: 2021-07-20 21:44:48

Let's review how to declare them the right way🤔

There are a few general rules for naming variables:⁣⁣

⁣▪️Variable names cannot start with numbers.⁣⁣

⁣⁣▪️Variable names are case sensitive, so myName and myname would be different variables. It is bad practice to create two variables that have the same name using different cases.⁣⁣

⁣⁣▪️Variable names cannot be the same as keywords. For a comprehensive list of keywords check out MDN’s keyword documentation.⁣⁣

⁣⁣I leave you this infographics slides, with code snippets 👇

![slide1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6qwr6afhb3yghxwij6jr.png)

![slide2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dvr92tqu2mi9v2spp2vr.png)

![slide3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ej1s26xq1gxp2v4pswlu.png)

There you go! If you have questions or you find it useful, please let me know in the comments!

Find me on:

[🔗 Instagram](https://www.instagram.com/carlosginer_webdev) | [🔗 Twitter](https://twitter.com/Carlosginer_dev) | [🔗Github](https://github.com/CARLOSGINER) | [🔗linkedIn](www.linkedin.com/in/carlosginerdev)
Don't Hold Back!
Tags: inspiration
Published: 2021-07-29 00:57:26

---
title: Don't Hold Back!
published: true
date: 2021-07-20 21:38:53 UTC
tags: inspiration
canonical_url: https://dils.blog/dont-hold-back/
cover_image: https://images.unsplash.com/photo-1516556878440-129be5a6c538?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MnwxMTc3M3wwfDF8c2VhcmNofDF8fHJvYWQlMjBhaGVhZHxlbnwwfHx8fDE2MjY3MzEzODM&ixlib=rb-1.2.1&q=80&w=2000
---
Sometimes we are our own blockers to progress. We doubt ourselves and play it safe and wish our time will come. We don't try because we don't want to fail.

{% twitter 1417163346646913034 %}

Failure is learning. If you don't try you will probably regret it. Even if you fail, you will have a good story to tell. So give it a go, there is nothing to loose.

You can't sustain motivation by doing the same thing everyday. Business as usual rarely leads to innovation. Be creative. Get inspired and to try new things.

{% spotify spotify:track:5V6AuJcYN3RbwS3NJBC3qK %}

Don't hold back. Give it everything you have and then some more.

Don't keep that reserve [fuel in the tank](https://www.urbandictionary.com/define.php?term=Fuel%20in%20the%20Tank). Where we are going we don't need fuel ... or a tank.

{% youtube G3AfIvJBcGo %}
Higher-order functions in Python and C#
Tags: csharp, python, functional, programming
Published: 2021-07-20 20:59:35

In this article I will explain what is higher order function and how to implement it in programming languages like c# and python.

#What is Higher Order Function(HOF):
so HOF is a function that either takes a function as an argument or returns a function. This type of function has implementations in many programming languages like javascript, python, Go, etc.

#Some examples:
let's build very simple function called `doOperation()` which take a function as a first parameter and two numbers and will return a function that takes two numbers as an arguments, 
we have also a function called `sum()` that returns summation of two numbers.

###Python:
```python
def doOperation(operation, num1, num2):
    return operation(num1, num2)

def sum(number1, number2):
    return number1 + number2

doOperation(sum, 2, 3)

-----------
Output: 5
-----------
```

###Csharp
```cs
public int DoSomthing(Func<int,int,int> sum, int num1,int num2) =>
    sum(num1, num2);

	
public int sum(int number1, int number2) =>
    number1 + number2;


DoSomthing(sum, 2, 3)

-----------
Output: 5
-----------
```

in cshap example we use a built in delegate `Func<int,int,int>` which take 2 integer numbers and return integer to assign a `sum` function to it.

So with this implementation we already apply higher order function.

##Another example
we want to create `filter()` function to filter an array based on function we can pass it for this `filter()` function.

###Python:
```python
def filter(arr, action):
   result= []
   for num in arr:
      if(action(num)):
         result.append(num)
   return result

def isOddNumber(num):
   return num % 2 != 0


filter([1, 2, 3, 4, 5], isOddNumber)

-----------
Output: [1,3,5]
-----------

```

###Csharp
```cs
 public static int[] Filter(int[] arr, Func<int, bool> func) =>
    arr.Where(func).OrderBy(n => n).ToArray();

public static bool isOddNumber(int number) =>
   number % 2 != 0;


Filter([1,2,3,4,5], isOddNumber)

-------------
Output: [1,3,5]
-------------

```

Hope it to be useful and thanks for reading!
Visualizing Artificial Ant Problem using pygame
Tags: python, pygame, geneticprogramming
Published: 2021-07-20 20:49:15

## DEAP

I recently started learning about genetic algorithms and programming. I came across several easy to start tools, libraries and tutorials.There are many cool visualizations available online to showcase how the algorithm improves the population generation over generation. Seems like a nice way to grasp the concept and build intuition. 

Since I mainly code in Python, I ended up using [DEAP](https://deap.readthedocs.io/en/master/) for prototyping and learning. Documentations are very clear and with lots of examples to study from. 

## Artificial Ant Problem

One particular example was, [Artificial Ant Problem](https://deap.readthedocs.io/en/master/examples/gp_ant.html). The goal is to evolve an individual that can control an ant and eat as many food items from the environment as possible given a limited amount and types of moves.

The code runs seamlessly and you could see the output in the console that generation over generation the population is actually able to increase the amount of food items eaten. 

## Code Changes

That’s all well and good, but I wanted to visualise the solution to see for myself and get a better understanding. First step was to actually read the best individual attributes `hall of fame`. 

[Original Base Code for Reference](https://github.com/DEAP/deap/blob/f4b77759897d0322ab5a6551106b28f6f4401a4e/examples/gp/ant.py)
I captured the best individual after running the program and recompiled the attribute for that individual.

```python
from deap import gp
hof_promitive_tree = gp.PrimitiveTree(hof[0])
routine = gp.compile(hof_promitive_tree , pset)
```

Modified the `AntSimulator` class a little bit to record every move for later use.

```python
class AntSimulator(object):
def __init__(self, max_moves):
...
self.recorded_moves = []
        ...
    def record_move(self):
        self.recorded_moves.append(self.position)
```

Next step was to run the routine again on modified `AntSimulator` and get the recorder moves for simulation

```python
ant.run(routine)
# contains the initial food item and ant location
grid = ant.matrix
# recorder moves of best individual
moves = ant.recorded_moves
```

## Pygame

Given this much information, initialisation involved placing ant and food items on the pygame screen. The main loop consists of playing each move one by one and removing food items once eaten. Complete modified code can be found [here](https://gist.github.com/ranuzz/89ee8a84274cb7d0634b94c84f317547)

And here is the end result. Shows the individual controlling the first 600 moves of our artificial ant.

## one generation

{% youtube rlXWhgnjqhk %}

## Ten Generations

{% youtube uz8Kt738kkA %}

## Forty Generations

{% youtube RxEwl5rGGkY %}
Introduction to software testing in .NET
Tags: dotnet, test, tutorial
Published: 2021-07-20 20:26:07

---
title: Introduction to software testing in .NET
published: true
description: Learn what types of software testing exist
tags: dotnet, test, tutorial
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/auxj635j3cwgevf83vae.png
---


Testing is crucial part of software development. We want to make sure the software we ship is as tested as much as possible. However, there are many ways to test, and the scenario and the application is usually what determines what the best approach is. Upskill your testing knowledge and get a good high-level view of all types of testing that exist, so you are better informed how to approach testing for your next program - cause you do test right?



## This module covers:

- Evaluate if testing is right for your scenarios.
- Describe how different types of testing, the testing - pyramid, and different testing schools of thought answer the demands of modern development.


Check it out: [.NET testing](https://docs.microsoft.com/en-us/learn/modules/visual-studio-test-concepts/)
How to set up Terraform on GitLab
Tags: terraform, gitlab
Published: 2021-07-20 20:25:36

If you use the GitLab platform, you can be tempted to move pretty much all aspects of your development to them - since you already pay for it because of the feature X, why not use Y & Z that comes in the plan. One of the features I was recently investigating is infrastructure-as-code with Terraform.

# Terraform

[Terraform](https://www.terraform.io/) is a tool that allows us to describe in a file what infrastructure we want. So, for example, we have `main.tf`:
```tf
provider "aws" {
  region = "eu-west-1"
}

resource "aws_instance" "example" {
  ami           = "ami-0f89681a05a3a9de7"
  instance_type = "t2.micro"
  subnet_id       = "subnet-1234"

  tags = {
    Name = "terraform-example"
  }
}
```

This file, we manage in the same way as we would manage any source code - by putting it under a version control system (most likely git). Then, when we have changes to the environment description, Terraform figures out what to remove/add/update apply the changes to the infrastructure. In this way, we can do our DevOps in git - the so-called GitOps. I'm new to this, but I definitively want to keep all the important information in a repository.

# Terraform on GitLab

So far, we have talked about changes & existing infrastructure. There is one important piece missing - the current, expected state. Terraform, on its own, will not remember what severs are already started by it, and we need a backend to store this information.  When we use the backend provided by GitLab, we will additionally get an overview of our infrastructure in the GitLab UI. 

The best resource on this topic is one of the articles on [GitLab documentation](https://docs.gitlab.com/ee/user/infrastructure/terraform_state.html). In short, you should be able to do:

1. make some changes from the localhost, and save their result on GitLab, so they appear in the Terraform tab
2. get the same thing up & running, so you have a deployment task in your repo CI - if you trigger the deployment once, it should create the infrastructure & update the Terraform tab. If you trigger after that, it should fail because it recognizes the changes were already applied.

# Documenation caveat

If you tried following some Terraform documentation from GitLab and got very frustrated - you are not alone. Two articles cover this topic, and the one I linked above is doing a pretty good job. Make sure you check out this article:

![Screenshot 2021-07-20 at 22-13-06 GitLab managed Terraform State GitLab](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xvgmm8is77918d39941h.png)

Before you give up on setting up Terraform. 

# Summary

Terraform looks like an exciting approach to managing the infrastructure, and I'll definitively keep on investigating it. The GitLab integration can be nice if you use their platform, and after all, they do have good documentation about it - but you have to look out not to fall into the trap of a not-so-helpful guide.
Design and development
Tags: design, development, product, experience
Published: 2021-07-20 20:17:56

---
canonical_url: https://carlmultimedia.com/diseno-y-desarrollo
---

![design and development](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wu4ynv2ahzb6207v9jp7.jpg)

## Designers

Most of the time in previous years, designers work alone, that is (only designers) within their studios, agencies, or houses, and as a result of this, the look and feel of a digital product were not the best, viable or achievable. , many of the great ideas that they embodied much later were discarded by other areas due to the lack of foundation.

## Developers

On the other hand, the developers thought believed or imagined that they did not need a design, because they had the belief that if "I can use it, anyone can do it" this was one of the reasons, however, the developers did not understand what the designers wanted, it was difficult to imagine, develop and above all because of simple ignorance and thinking that they can do everything.

## Real case

According to the Spotify design team, in one of their articles called <a target = "_ blank" rel = "noopener noreferrer" href = "https://spotify.design/article/the-paradox-of-design-systems" > "The Paradox of Design Systems" </a> they denote the importance of working on a digital product as a whole, in which everyone is involved in each of the product definitions. They understood that there are no deliverables between one team or another, but that everyone works for the same goal, and that ideas and possible new creations are defined from the beginning between all and also know what can and what not in order not to create false expectations.

## Experience

To finish and from what I have seen in the different projects I have worked on during the last 10 years is that all the roles involved are beginning to understand the creation of digital products as a whole. Now, there is still much to do, there are many gaps between the parties for which the companies internally are beginning to create workshops so that everyone is on the same page. We will talk about the role of user experience within the life cycle of a digital product.
BackEnd Development checklist to ensure application performance and maintainable code.
Tags: backenddev
Published: 2021-07-20 20:00:27

Few notes for backend developer which will help to write better production code.

1.Always check any possibility of a null pointer exception.

2.Remove redundant/extra DB or network call. (Query in a loop, N+1 query)
3.In case of database connection, properly use connection pool, pool size, idle size, queue size, monitor pool resource.

4.When querying/searching, think about table size and param index or any performance impact at high load.

5.Measure and profile Database query latency.

6.Handle DB TimeOut(Connection, Read) properly.

7.When network call (REST, in-memory DB, Message Queue), use proper connection pool configuration. (Pool Size, Queue Size, Rejection or exhaustion policy).

8.When third party call, handle Time out(connection & read), try to implement circuit breaker and bulkhead pattern.

9.Always think about the asynchronous process.

10.Be careful about shared resources and critical sections.

11.Try to avoid member variable at spring singleton bean.
Class Name, class size, method name, method size, and variable name should follow clean code rules.

12.Ask yourself, is my method unit testable?

13.Meaningful tag after each release.

14.Every git commit will be an independent feature.

15.Use cache as much as possible.

16.Think about Spring Bean Scope(Singleton, Request & prototype).

17.Try as much automation(Testing, CI & CD)

18.Try to retrieve data from pre-calculated data using the scheduled job.

19.Avoid redundant or any extra variable assignment.

20.Should maintain a proper log with the appropriate level.
 
21.Follow logging and tracing standard rules.

22.Try as much documentation or note so that QA & System team and another stakeholder do not ask the Developer. Mostly when developers change the config, DB structure, migration script, framework version, library, runtime environment(JDK, python), dependency, new technology.

23.Isolate scheduled jobs from the main application and use standard tools(Jenkins).

24.While writing complex queries, check raw queries and analyze the query using DB tools(like MySQL explain command).