teleren/devto huggingface dataset:
🔥 Grouping array elements by a property
Tags: javascript
Published: 2020-12-20 18:06:00

If objects in an array are categorized by a property, we can group them by that property like this. We can then quickly get all objects with a certain value instead of having to filter all the time.

```js
// takes an array of objects and the name of a property of these objects
const groupBy = (array, property) => array.reduce((grouped, element) => ({
  ...grouped,
  [element[property]]: [...(grouped[element[property]] || []), element]
}), {})

// some elements in this array share the same value for their `type`
const team = [
  { name: 'Squirtle', type: 'Water'    },
  { name: 'Pikachu',  type: 'Electric' },
  { name: 'Arcanine', type: 'Fire'     },
  { name: 'Psyduck',  type: 'Water'    },
  { name: 'Vulpix',   type: 'Fire'     }
]

// `groupBy` groups an array into a dictionary based on the given property
const groupedByType = groupBy(team, 'type')
// ⇒ {
//     'Water': [
//       { name: 'Squirtle', type: 'Water' },
//       { name: 'Psyduck',  type: 'Water' }
//     ],
//     'Electric': [
//       { name: 'Pikachu',  type: 'Electric' }
//     ],
//     'Fire': [
//       { name: 'Arcanine', type: 'Fire' },
//       { name: 'Vulpix',   type: 'Fire' }
//     ]
//   }

// we can get a list of all values from the dictionary’s keys
Object.keys(groupedByType)
// ⇒ ['Water', 'Electric', 'Fire']

// we can then extract only the elements that share the same type
groupedByType['Fire']
// ⇒ [
//     { name: 'Arcanine', type: 'Fire' },
//     { name: 'Vulpix',   type: 'Fire' }
//   ]
```
My journey to becoming a Software Engineer
Published: 2020-12-20 18:00:45

For as long as I can remember, I've always been interested in all things technology. I was always in awe at what technology can do, starting from my first Gameboy advance. Playing these games used to always make me wonder how this was all possible. This was before I even knew what programming was. Back then, it wasn't something that was commonly talked about and so I unfortunately never thought to look deeper into it.

Fast forward years later, with the introduction of the iPhone and iPod Touch. It blew my mind, what Apple was trying to accomplish with these devices, and I knew that I just had to get my hands on one of them. I saved up all my money to buy the iPod Touch when I was able to afford it, and when I finally unboxed it, I was ecstatic! I started to play around with it with complete please, as I interacted with the device just with the touch of my fingers directly on the screen. While that whole experience was great, I soon realized that I couldn't do much with the iPod Touch without WiFi. As crazy as that may sound now WiFi wasn't a common thing at the time, and I sadly had to return the device.

Some years have passed, and due to the popularity of these Apple devices, WiFi was starting to become a common household need. Finally, I had WiFi! I was able to purchase the iPod touch again and use it to its full capabilities. The experience was pure bliss. I still couldn't comprehend how this device worked in the way that it did, but I was about to find out soon.

Every year since the release of the iPhone, Apple would hold two events: one for their new hardware, and one for their new software. Although I did enjoy their events, it was the developer's conferences that they held that really intrigued me. It really inspired me to see what these developers could do with software to make our lives easier. It always felt like the sky was the limit with what you could do with software. Most of my career has been in sales, but becoming a software engineer has always been my true passion. This is why I joined the Flatiron School program, and I'm excited to see what I can accomplish.
Solving day 20 of Advent of Code 2020 in JavaScript
Tags: challenge, adventofcode, javascript, video
Published: 2020-12-20 18:00:06

---
title: Solving day 20 of Advent of Code 2020 in JavaScript
published: true
description: JavaScript walkthrough of Advent of Code 2020 (day 20)
tags: challenge, AdventOfCode, javascript, video
series: Advent of Code 2020 in Javascript
---

Wow today was insane!! Here is only part 1, because I hit some bugs when trying to solve part 2.

{% youtube cR9jlJp_akM %}
How to display selected value of drop down list in HTML
Tags: html, webdev, programming
Published: 2020-12-20 17:57:43

Solution: You can simply use JavaScript to display the selected value or text from a drop-down list. Let us follow this step

##STEP 1: Create a drop box list
```
<select id="country">
	<option value="None">-- Select --</option>
	<option value="ID001">China</option>
	<option value="ID002" selected>United State</option>
	<option value="ID003">Malaysia</option>
</select>
```

---
title: originally posted here 👇
canonical_url: https://kodlogs.com/blog/213/how-to-display-selected-value-of-drop-down-list-in-html
---

##STEP 2: Display option value
```
var e = document.getElementById("country");
var result = e.options[e.selectedIndex].value;
alert(result); //ID002
``` 

##STEP 3: Display option text
```
var e = document.getElementById("country");
var result = e.options[e.selectedIndex].text;
alert(result); //United State
``` 

##STEP 4: JavaScript drop-down code
```
<!DOCTYPE html>
<html>
	<head>
		<title>JavaScript - Get selected value from dropdown list</title>
	</head>

	<body>

		<h1>JavaScript - Get selected value from dropdown list</h1>

		<p id="result">United State</p>

		<select id="country">
			<option value="None">-- Select --</option>
			<option value="ID001">China</option>
			<option value="ID002" selected>United State</option>
			<option value="ID003">Malaysia</option>
		</select>

		<script>

			function GetSelectedValue(){
				var e = document.getElementById("country");
				var result = e.options[e.selectedIndex].value;

				document.getElementById("result").innerHTML = result;
			}

			function GetSelectedText(){
				var e = document.getElementById("country");
				var result = e.options[e.selectedIndex].text;

				document.getElementById("result").innerHTML = result;
			}

		</script>

		<br/>
		<br/>
		<button type="button" onclick="GetSelectedValue()">Get Selected Value</button>

		<button type="button" onclick="GetSelectedText()">Get Selected Text</button>
	</body>

</html>
```
[Read more in original post](https://kodlogs.com/blog/213/how-to-display-selected-value-of-drop-down-list-in-html)
Git Submodules vs Monorepos
Tags: git, discuss
Published: 2020-12-20 17:42:55

I am very interested in this topic and I want to know more about this. I have read about monorepos, and I understand the advantages, but I am more concerned about the disadvantages. More specifically, these four things:

1. In monorepos, how do you maintain a clean git history? For example, if you have backend + frontend in the monorepo, wouldn't the git history be a complete mess? Or you just don't mix these things?

2. Security. I have already seen that maybe this is impossible. If you want to restrict access to some "packages", then I believe this is imposibble with monorepos.

3. What happens when you have packages written in other programming languages other than Javascript? Can you still have them in the monorepo without conflicting with, for example, Yarn Workspaces or Lerna?

4. How do you run tests for only certain packages? How do you achieve CI/CD for certain packages?

Well, I find all of these things huge disadvantages of monorepos and I think these reasons are enough for not even trying them in real world projects. So trying to find a way to solve these problems, I thought about git submodules. To be honest I haven't worked too much with them (I barely know how to add them to a project and remove them).

Correct me if I am wrong, but with git submodules I think we do not have the capacity to generate "symlinks" like with monorepos. I was playing around with Yarn Workspaces, and when I make a change to one package, this change gets reflected in another package that uses it. This is cool! But I think this cannot be done with git submodules right?

I think that wit git submodules, we can say the following things about the points I just mentioned.

1. Independent repos have independent git histories, so I think this would get solved.

2. If I do not have access to one repo, then would running `git clone --recurse-submodules` just wouldn't give me those repos, or would it throw an error saying that the clone cannot be made because there are repos that I cannot access?

3. We can add submodules written in other languages. But I think they would be useful if, for example, I have some Flask app and the client in React, and if I make some change in the Flask app then I can test that change in the client immediately. Maybe this can be done with some kind of script that starts all the things inside each submodule? After 

4. I think this point gets solved with independent repos.

I really need someone to clarify all of these things to me. I appreciate your opinions!
How to generate pdf file from dynamic data coming from MySQL database in PHP
Tags: php, programming, webdev
Published: 2020-12-20 17:41:37

We can generate the pdf form MySQL database by using FPDF which allows generating the pdf files without using any library. We can generate by considering the following steps;

* Download the FPDF library from fpdf.org.
* Generate the database teacher in the MySQL database.
* Connect to the database by using the connection.php file.

###Connection.php
```
Class dbObj{

var $dbhost = "localhost";

var $username = "root";

var $password = "";

var $dbname = "test";

var $conn;

function getConnstring() {

$con = mysqli_connect($this->dbhost, $this->username, $this->password, $this->dbname) or die("Connection failed: " . mysqli_connect_error());

if (mysqli_connect_errno()) {

printf("Connect failed: %s\n", mysqli_connect_error());

exit();

} else {

$this->conn = $con;

}

return $this->conn;

}

}
```
###Index.php:
 Now generate the index.php file which will generate the invoice of that number.
```
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>PDF file</title>

</head>

<body>

<h2>Generate PDF</h2>

<form class="form-inline" method="post" action="generate_pdf.php">

<button type="submit" id="pdf" name="generate_pdf" class="btn btn-primary"><i class="fa fa-pdf"" aria-hidden="true"></i>

Generate PDF</button>

</form>


</body>

</html>
```
###Generate_pdf.php:
Now we will create the generate_pdf.php file
```
<?php
include_once("connection.php");

include_once('libs/fpdf.php');

class PDF extends FPDF

{

function Header()

{

    $this->Image('logo.png',10,-1,70);

    $this->SetFont('Arial','B',13);

    $this->Cell(80);

    $this->Cell(80,10,'Employee List',1,0,'C');

}
function Footer()

{
   $this->SetY(-15);

    $this->SetFont('Arial','I',8);
    $this->Cell(0,10,'Page '.$this->PageNo().'/{nb}',0,0,'C');

}

}

$db = new dbObj();

$connString =  $db->getConnstring();

$display_heading = array('id'=>'ID', 'employee_name'=> 'Name', 'employee_age'=> 'Age','employee_salary'=> 'Salary',);

$result = mysqli_query($connString, "SELECT id, employee_name, employee_age, employee_salary FROM employee") or die("database error:". mysqli_error($connString));

$header = mysqli_query($connString, "SHOW columns FROM employee");

$pdf = new PDF();
$pdf->AddPage();
$pdf->AliasNbPages();

$pdf->SetFont('Arial','B',12);

foreach($header as $heading) {

$pdf->Cell(40,12,$display_heading[$heading['Field']],1);

}

foreach($result as $row) {

$pdf->Ln();

foreach($row as $column)

$pdf->Cell(40,12,$column,1);

}

$pdf->Output();

?>
```
[Read more in original post](https://kodlogs.com/blog/130/generate-file-from-dynamic-data-coming-from-mysql-database)
PHP capitalize first letter of each word
Tags: php, programming, webdev
Published: 2020-12-20 17:38:14

In this topic, we will learn and explore how can we capitalize on the first letter of each word in PHP .PHP has a variety of inbuilt functions to make things easy and in a quick manner. PHP has a variety of inbuilt functions to deal with strings which help us to perform our desired task efficiently. Let’s discuss one of the best and a very helping method of PHP to capitalize on each first character of each word of a given string.

##Capitalizing the first letter of each word by using the ucwords() function.
PHP introduced the ucwords () function in its 4th version to process strings, and to assist the programmers in capitalizing the first letter of each word. Here we are going to discuss its syntax and how it works. We will check this method with examples.

---
title: originally posted here 👇
canonical_url: https://kodlogs.com/blog/2599/php-capitalize-first-letter-of-each-word
---

##Ucwords() function
This function is used to convert/ capitalize the first character of each word in strings.  It is supported by all versions of PHP starting from the 4th version.

###Syntax
```
ucwords(string, delimiters)
```

Ucwords function contains tow parameters, first parameter is “string” that is required and must be provided to get desired results. While the other one is an option and it is called delimiter, it will not affect the execution if you skip this parameter.

Ucwords () on strings and arrays

Here we will try this method on a string with a single parameter and with double parameters using a delimiter.

##Example:
```
<html>
<body>

<?php
echo ucwords("hello mr coder, enjoy coding php.");
echo '</br>';

 //using delimiter 

 echo ucwords("hello| coder", '|');
  
</body>
</html>
```
###How does the ucwords () function work on arrays?
This example will illustrate how can we use ucwords on arrays to capitalize on the first character of each word of string arrays.

 
```
<?php
$names =array(
  'john peter',
  'musa ahmad',
  'William parker',
  'yasir abbas',
  'brain larra'
);
foreach ($names as $name) {
print ucwords("{$name}\n").'</br>'; }

//PRINTS:
John Peter
Musa Ahmad
William Parker
Yasir Abbas
Brain Larra 
?>
</body>
</html>
```
[Read more in original post](https://kodlogs.com/blog/2599/php-capitalize-first-letter-of-each-word)
Mysqli_num_rows in PHP
Tags: php, webdev, programming
Published: 2020-12-20 17:31:56

PHP is an open-source programming language; it has built-in functions to communicate with the database and retrieve data. Mysqli_num_rows () function is used to check the number of rows in the query. This function is used after placing a query to check either database has any record or it is empty. This function has a return value. It returns the number of rows a table contains if the condition comes true and returns false for empty tables.

#How to use Mysqli_num_rows ()?
To use this function, you need to establish a database connection. this function returns true if the database has any record and returns false if the database has an empty recordset. This function is used to avoid errors in a web application because without checking the recordset if we perform further actions a program may have fatal errors and exceptions.

**Syntax of mysqli_num_rows function**
`
mysqli_num_rows(result)
`
To check either if a database contains any rows, we need to pass a parameter or variable, variable contains the result returned by mysql_query. It checks a database and if there is any record it will return true and if there is nothing it will return false or empty.

**Example:**   let’s explore and evaluate this with the help of an example.
```
<?php
$connection=mysqli_connect("localhost","username","password","database");
// Check connection
if (mysqli_connect_errno())
  {
  echo "database connection failed: " . mysqli_connect_error();
  }

$sql="SELECT Name,Lastname,Age,Class FROM students ORDER BY Lastname";

if ($result=mysqli_query($connection,$sql))
  {
  // Return the number of rows in result set
  $rowcount=mysqli_num_rows($result);//check if the database has any record
  printf("Result set has %d rows.\n",$rowcount);
  // Free result set
  mysqli_free_result($result);
  }

mysqli_close($connection);
?>
```

---
title: originally posted here 👇
canonical_url: https://kodlogs.com/blog/2538/mysqli_num_rows-in-php
---

##code explained:

1. first, we made a connection to the database and checked if the connection is valid 
2. note that PHP is case sensitive for database records field names so always use the same as in  tables
3. we used a variable $sql and assign a query to it 
4. we check if the query is valid and assigned it to the $result variable 
5. we used $rowscount and passed it the value of  mysqli_num_rows 
6. mysqli_num_rows will check the database and returns either try or false
[Read more in original post](https://kodlogs.com/blog/2538/mysqli_num_rows-in-php)
Given When Then
Tags: testing, csharp
Published: 2020-12-20 17:31:42

Today I'm happy to announce that I have released my first public Nuget package today! And in true Christmas fashion, I'd like to share it with you dear reader as a potential way to improve the quality of your testing code :)

[nuget](https://www.nuget.org/packages/GivenWhenThen/)
[Source](https://github.com/dotdashnotdot/GivenWhenThen)

## Motivation

Writing tests under the "Given When Then" approach is something I've come to appreciate these last few years for its ability to produce clear and easy to follow test cases. This style of test writing is covered extensively elsewhere, but speaking generally the base concept is:
- Given an initial state
- When something happens
- Then the result is/these things happen

Where I work there is a heavy focus on making test names as close to plain English as possible. The benefits of this are two fold:
1) Code is easier to maintain as a developer
2) Code is easier for less technical testers to evaluate whether there is sufficient coverage

But when writing tests however I noticed that I was starting to feel minor annoyances with the quality of code being produced. Naming could quickly get out of hand when trying to follow the given-when-then pattern:

```
public void Given_the_database_is_empty_when_searching_for_open_orders_then_it_returns_no_orders_found()
{
    ...
}
```

Spurred on by this problem, I did what any good Software Engineer should - apply some creative thinking. GivenWhenThen is the result and it aims to make writing tests in this style as simple as:

```
[TestCaseSource(nameof(TestCases))]
public void TestThat(
    GivenWhenThenTestCase toRun)
{
    toRun.RunTestCase();
}

public static IEnumerable<GivenWhenThenTestCaseData> TestCases
{
    get
    {
        yield return GivenWhenThen.Create(
            Given.UsernameValidationFails,
            When.FredTriesToLogOn,
            Then.LogOnFailsBecauseTheUserIsNotValid);
        yield return GivenWhenThen.Create(
            Given.NoUsersExist,
            When.FredTriesToLogOn,
            Then.LogOnFailsBecauseTheUserDidNotExist);
        yield return GivenWhenThen.Create(
            Given.FredExists,
            When.FredTriesToLogOn,
            Then.LogOnSucceeds);
    }
}
```

Which to my eyes reads beautifully and renders wonderfully in a test runner too:

![Runner Example](https://dev-to-uploads.s3.amazonaws.com/i/83th6a25mhbyno2jph33.png)

Thoughts?

[More detail](https://github.com/dotdashnotdot/GivenWhenThen)
Fatal error Maximum execution time of 30 seconds exceeded in xampp.
Tags: php, webdev, programming
Published: 2020-12-20 17:24:38

This problem usually occurs when your PHP code takes a too long time to run. The time limit is very important because it helps to prevent the abuse of the server.

#Why maximum execution time error occur?
This error mostly occurs in PHP Programming language. To protect the server from abuse there is the time limit to run the PHP script. The actual time is different according to hosting companies but mostly the maximum execution time is 30 to 60 seconds because this is enough time to run the PHP scripts.

When the PHP script reaches the maximum execution time then the error occurs to maximum execution time exceeded.

---
title: originally posted here 👇
canonical_url: https://kodlogs.com/blog/215/fatal-error-maximum-execution-time-seconds-exceeded-xampp
---

##Fixing maximum execution time exceeded error:
Without changing anything in the system configuration we can fix this problem by just following the simple steps;

* Open file “php.ini” in the editor. This file is located under the directory “xampp/PHP/folder”.
* Find the “max_executuion_time” line. You can also find it by using ctrl+F.
* Modify it in the php.ini file
`
max_executuion_time = 120 ;           // This is the maximum execution time of script is in seconds
`
* Modify the Excel Time Limit value in the file config.inc.php under the directory installdir/apps/phpmyadmin/htdocs/config.inc.php;
`
$cfg[‘ExecTimeLIMIt’] = 120;
`
* Save and stop the Apache server in the xampp control panel.
* Restart the Apache server.
In this way, the maximum execution time of local server Xampp can be increased.

**Note:**
To set the execution time-unlimited set the time limit 0 in both the above cases.
[Read more in original post](https://kodlogs.com/blog/215/fatal-error-maximum-execution-time-seconds-exceeded-xampp)
Remove first character from string C++
Tags: cpp, oop, programming, computerscience
Published: 2020-12-20 17:20:34

1.Declare a string
2.Declare an integer variable
3.Print String Statement
4.Input from user string any
5.integer variable call for string length
6.return erase() function

---
title: originally posted here 👇
canonical_url: https://kodlogs.com/blog/769/remove-first-character-from-string-c
---

```
#include<iostream>
#include<string>
using namespace std;
int main(){
    string s;
    int n;
    cout<<"String = ";
    cin>>s;
    n=s.length();
    s.erase(s.begin());
    cout<<s;
}
```
[Read more in original post](https://kodlogs.com/blog/769/remove-first-character-from-string-c)