teleren/devto huggingface dataset:
How test your listener events on Symfony with phpunit
Published: 2021-10-03 11:51:23

Test a listener using the Symfony's events, is easy.

The listener is listening an event for example, when an exception has happened.
When the **onKernelException**  event has happened, you can intercept the request and catch the data of request
thanks to the **ExceptionEvent** Object.

In fact, you can transform the response as follows:

```php
class JsonExceptionResponseTransformerListener
{
    public function onKernelException(ExceptionEvent $event): void
    {
        $exception = $event->getThrowable();

        if ($exception instanceof HttpExceptionInterface) {
            $data = [
                'class' => \get_class($exception),
                'code' => $exception->getStatusCode(),
                'message' => $exception->getMessage(),
            ];

            $response = $this->prepareResponse($data, $data['code']);

            $event->setResponse($response);
        }
    }

    private function prepareResponse(array $data, int $statusCode): JsonResponse
    {
        $response = new JsonResponse($data, $statusCode);
        $response->headers->set('Server-Time', \time());
        $response->headers->set('X-Error-Code', $statusCode);

        return $response;
    }
}
```

On **onKernelException** you can catch the **Exception** and prepare a response. You can modify the status of the response and the type of the response for example.
This is useful when you want response with a json response like in an api-app.

But.. how test this with php-unit ??

In a first instance, only need the **EventDispatcher**. The idea is use an instance of **EventDispatcher**, and trigger the event with the 
**ListenerObject** that you has created. ( see up )
You don't need Mocks for the ExceptionEvent o dependencies of other classes.

Only, need trigger the event inside phpunit, and catch the event. Then you can use the asserts of php-unit for get the response and the type of the response expected.

Like this:

```php
class JsonExceptionResponseTransformerListener extends TestCase
{

    /** @var EventDispatcher **/
    private $dispatcher;
    
    public function setUp(){
        $this->dispatcher = new EventDispatcher();
    }

    public function test_should_get_a_json_response() : void
    {
        // instance our own listener
        $listener = new JsonExceptionResponseTransformerListener();
        $this->dispatcher->addListener('onKernelException', [$listener, 'onKernelException']);
        
        // dispatch your event here
        $event = new ExceptionEvent();
        $dispatcher->dispatch($event, 'onKernelException');
        $this->assertInstanceOf(JsonResponse::class,$event->getResponse());
    }
    
}
```

You can , of course, add more assert to the response, like the status code, the params of the header response, etc etc....


**fdo:roberto manchado**
{Insert Hacktoberfest 2021-Related Title Here}
Tags: hacktoberfest
Published: 2021-10-03 11:46:05

<!-- ✨This template is only meant to get your ideas going, so please feel free to write your own title, structure, and words! ✨ -->


### [Intro Heading]
<!-- If you are new to the DEV community, introduce yourself and share a bit about why you joined DEV and decided to participate in Hacktoberfest this year.  --> 

### Background

<!-- Are you brand new to open source? What about coding in general? Tell us about how you got here →

### Progress

<!-- Share a bit about where you’re at in your Hacktoberfest journey. What stage are you at? How has the process been?  -->

### Contributions

<!-- This is where you can list the contributions you made and explain why you chose the projects you did. Don’t forget to add links!  -->


### Reflections
<!-- Overall, how has your Hacktoberfest 2021 experience been? If you’re a first-timer, will you participate again? What have you learned? Have you made any interesting connections? What is your next step in open source?  -->
How can you embed a simple CODE EDITOR.
Tags: javascript, html, webdev, beginners
Published: 2021-10-03 11:25:57

Today we're going to embed an code editor in website.
I found a code editor called codemirror. which is lighter than monaco.

<blockquote> See my last article -  
{%post https://dev.to/ksengine/embed-vscode-single-file-editor-in-your-website-176j%}
</blockquote>

<blockquote> **CodeMirror** is a versatile text editor implemented in JavaScript for the browser. It is specialized for editing code, and comes with a number of language modes and addons that implement more advanced editing functionality.</blockquote>

<img src="https://github.com/codemirror/CodeMirror/raw/master/doc/logo.png" alt="Codemirror Logo" width="250px" height="auto"/>

For features visit [CodeMirror WebSite](https://codemirror.net/#features)

## Example

{% codepen https://codepen.io/ksenginew/pen/gORJpQv %}

## Example Explained

The easiest way to use CodeMirror is to simply load the script and style sheet , plus a mode script (Here I'm using Javascript mode script). For example:
```html
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.1/codemirror.min.css" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.1/codemirror.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.1/mode/javascript/javascript.min.js"></script>
```
Then Create a dummy text box for your Editor

```html
<textarea id="editor">
  your code here...
</textarea>
```
Having done this, an editor instance can be created like this:
```js
let editor = CodeMirror.fromTextArea(document.getElementById('editor'), {
  mode:  "javascript"
});
```

Then enjoy it.
I hope to write more articles with advanced use cases of embedded editor. 
Follow 🏃‍♂️ me for more articles.
Ask🙏 any question on comments section.
Star⭐ me if you love this article.

<sup>cover image by [Unsplash](https://unsplash.com/photos/oXlXu2qukGE?utm_source=unsplash&utm_medium=referral&utm_content=creditShareLink)</sup>

Happy Coding 👩‍💻👩‍💻👩‍💻...
Thanks. :heart::heart::heart:
Golang 101: Döngü (For)
Tags: go, for
Published: 2021-10-03 08:25:21

Golang döngüler için sadece `for` kullanır. Örnek üzerinden inceleyelim.

```golang
package main

import "fmt"

func main() {

	// Basit koşul
	x := 1
	for x <= 4 {
		fmt.Println(x)
		x = x + 1
	}

	// Klasik döngü
	for i := 7; i <= 10; i++ {
		fmt.Println(i)
	}

	// Sonsuz döngü
	for {
		fmt.Println("sonsuz döngü")
		break
	}

	// Kontrollü döngü (tek sayılar)
	for y := 0; y <= 9; y++ {
		if y%2 == 0 {
			continue
		}
		fmt.Println(y)
	}

	// Koşulsuz Sonsuz Döngü
	for i := 0; ; i++ {
		fmt.Println(i)
		if i == 4 {
			break
		}
	}
}
```
```
1
2
3
4
7
8
9
10
sonsuz döngü
1
3
5
7
9
0
1
2
3
4
```
[çalıştır!](https://go.dev/play/p/G3XgMuUnQgj)



## Basit Koşul
```golang
	x := 1
	for x <= 4 {
		fmt.Println(x)
		x = x + 1
	}
```
Döngüden önce tanımlanan `i` değişkeni `for` içerisinde değeri arttırılarak diğer dillerdeki `while` benzeri bir yöntemle kullanılıyor. Burada atanan değer eşitliği (`x <= 4`) sağladığında döngümüz sonlanıyor.

## Klasik Döngü
```golang
	for i := 7; i <= 10; i++ {
		fmt.Println(i)
	}
```
Klasik döngü de diğer dillerden alışık olduğumuz değişken atama, eşitlik kontrolü ve değişkenin arttırılması işlemleri for ile birlikte tanımlanıyor. For içerisindeki işlemler bu kontröle göre devam ediyor.

## Sonsuz Döngü
```golang
	for {
		fmt.Println("sonsuz döngü")
		break
	}
```
Sonsuz döngü herhangi bir koşul belirtilmeden `for` ile oluşturulabilir. İşlevi tamamladığında döngünün sonlandırılması için `break` kullanılmalıdır.

## Kontrollü Döngü
```golang
	for y := 0; y <= 9; y++ {
		if y%2 == 0 {
			continue
		}
		fmt.Println(y)
	}
```
Döngü belirli bir koşulu sağladığında (örnekte `y%2` ile değişkenin mod'u alınıyor) döngü `continue` ile bir sonraki adıma atlatılıyor. Yani döngü sonlanmıyor ve başa dönüp işlemlere devam ediyor.

## Koşulsuz Sonsuz Döngü
```golang
	for i := 0; ; i++ {
		fmt.Println(i)
		if i == 4 {
			break;
		}
	}
```
Son anda koşulsuz döngüden bahsetmediğimi fark ettim. Bu örnekte değişken tanımlama ve değişkenin arttırımı belirtiliyor fakat herhangi bir koşul tanımlama sırasında belirtilmiyor. Aslında sonsuz döngü oluşturuyoruz ve `break` ile döngüden çıkış işlemini önceki örnekteki gibi unutmamalıyız. Örnekte `1, 2, 3, 4` ekrana yazılıp uygulama sonlandırılıyor.

**NOT:** `range` ile de bir dizi (`array`), kesit (`slice`) veya haritadan (`map`) veriyi `for` ile çekebilirsiniz. Bu konuya ileri ki yazılarda dizi çeşitlerini gördükten sonra detaylıca değineceğiz.
simple search filter array of objects in javascrit (React js)
Tags: javascript, vscode, programming, beginners
Published: 2021-10-03 10:37:37

we are going to see how to filter the array of object when user type something in input field

first we take some mock data 

```
  const  data = [
  {name:'karthi'},
  {name:'mani'},
  {name:'siva'},
  {name:'raj'}];
```
add map the data first 
```
{data.map((e)=>(
        <li>{e.name}</li>
      )
```
after that we need to add filter function 
```
{data.filter((e)=>e.name.toLowerCase().includes(searchtext.toLowerCase())).map((e)=>(
        <li>{e.name}</li>
      )
```
so we have filter function now after that we need to get the user input text so we can use either usestate or useref here i am using usestate
```
 const handleinput = (e) => {
    console.log(e.target.value)
    setsearchtext(e.target.value)
  }
```
thats all you got it

Full code : 
```
import { useState } from "react";
import "./styles.css";

export default function App() {
    const  data = [
    {name:'karthi'},
    {name:'mani'},
    {name:'siva'},
    {name:'raj'}];
  const [searchtext, setsearchtext] = useState('');
  const handleinput = (e) => {
    console.log(e.target.value)
    setsearchtext(e.target.value)
  }
  return (
    <div className="App">
      <input
      placeholder="enter"
      onChange={handleinput}
      />
      {data.filter((e)=>e.name.toLowerCase().includes(searchtext.toLowerCase())).map((e)=>(
        <li>{e.name}</li>
      )
        )}
    </div>
  );
}

```
Week Five as a TaskForce
Published: 2021-10-03 10:28:07

As we are coming to the end of week 5 and also clause to the end of the bootcamp, I have acquired so much knowledge from the ups and downs of the bootcamp😂, from soft skills that I did not even know that I needed, to technical skills which made me improve my design skills.

There were two main highlights in this week. One was the session with Thomas about the Business simulation game using agile methodology. The aim of this session was to teach us the role of each team member, their responsibilities and how to communicate effectively within the team. And more importantly that no one in the team has to feel superior to the other. This session helped me put myself in a real life situation so that when I start working with clients, I will know what I have to do in order for the project to be implemented smoothly.

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

The second was, we were told that during week 6, we shall be working on our own, on the project that we came up with, that will solve real life problems in our community. The first brainstorm took place on Friday, where I got to collaborate with my teammates and set a plan of how we are going to work on our project and deliver it on time. This will be an occasion for us to showcase all the knowledge and skills that we have acquired during these past weeks of the bootcamp and will help us to push ourselves to our full potential.

All in all, this week was very insightful, we learned a lot, mostly about real life working conditions as designers and developers.

Week 6, let's roll 😉
5th week as a taskforce 3.0 member
Tags: taskforce, bootcamp
Published: 2021-10-03 10:25:41

Hi! Today I would like to talk about my 5th week as taskforce member. The week has been full of productive and fun sessions.

On Wednesday we had a really great and fun session with Thomas, The session was about [Agile](https://www.atlassian.com/agile) Project Management. In case you don't know what Agile is, Agile is an iterative approach to project management and software development that helps teams deliver value to their customers faster and with fewer headaches.

We played a very cool Business Simulation Game, it was so fun! I acted as a scrum master. It was my first time to work or act as a scrum master, by acting such role I gained a little bit of experience. I found out that as a scrum mater you really need to push the team and make sure things' re always set.

During the session, I also found out that before starting any project; the team of developers, scrum master, project owner, and every one who involves in the project should sit together to plan for sprints. Before having this session, I used to think that there is no need for the product owner to be there during the sprint planning, but now I know how import it is for the P.O present during the sprint planning.

This week we did not only do soft kill sessions we also had to integrate the [LoT](https://lot-dashboard.vercel.app/) dashboard with backend.

In the start of Business Simulation Game, I had a little challenge to act as a scrum master as this was my first time to be a scrum master, but then I realized that this session was for me to learn and then I calmed down myself, took a deep breathe and every thing started to go well during the whole game.

I have a lot to say about this week, but let me stop by here.

Thanks for reading.
How does HTTP work?
Published: 2021-10-03 07:00:04

When browsing the internet you are using the HTTP/HTTPS protocol. Whenever you are clicking a button, calling an address in the browser, download a file on the internet, you are making an HTTP request. As simple as they may seem, there are process behind the curtain that make it all work. Have you ever wondered how it works behind the curtain? In this article I’ll explain to you how HTTP works.

HTTP is a so called request response protocol. Meaning the client sends the request and the Server replies with a response. Request and response are both carefully formatted messages that the other can understand. Both messages are different message types. They are exchanged in a single HTTP transaction. These messages are in ASCII text and formatted according to the HTTP standard so client and server know how to interpret the content correctly.

Any application that is able to open a network connection to a server machine and is able send data over the network can make an HTTP request. Even you can try this. Just type in manually the HTTP request by using Telnet from the command line. Heads up: A normal telnet session connects over port 23. As it was mentioned before, in order to connect to a server via HTTP we have to use port 80.

In the following example we will use Telnet in order to
- connect to a server
- make an HTTP request
- receive an HTTP response

telnet www.google.com 80

This command tells the computer to connect to a server with the host name “www.google.com” on port 80. After the connection is established you can write the HTTP request message:

GET / HTTP/1.1

The “GET” part tells the server we want to retrieve a resource.
The “/” tells the server that the resource we want to retrieve is located at the root resource of the home page.
“HTTP/1.1” tells the server we are using the HTTP 1.1 protocol to speak to him.

Next you type this line:

host: www.google.com

That line specifies the requested resource on the server, because one server could host multiple websites.

After you type in this and pressed ENTER twice, you should see the HTTP response. The response is plain and simple HTML code. If the code would send to a browser then he would take the code render it into a website.

Do you have any questions? Please leave a comment and I’ll get back to you as soon as possible.

This article was first published in my blog
 https://link.medium.com/1hsIYpyZ2jb
Taskforce [ fifth week ]
Tags: programming, react, javascript, webdev
Published: 2021-10-03 10:16:18

Hello mates!

And yet again i’ve come to the end of the second last week of the awesomity lab / code of africa taskforce.

This week was more of techinal, we had a very fruitful session game called The business simulation game with one of the geniuses in tech Thomas. Where we played different roles in real scenerios and projects and the roles included Product owner, scrum master, architect, Developers and more more.

As i said this week was more technical where we were working on intergrating API endpoints to our LOT dashboard.

The friday session we had a brainstorming session where we presented our ideas of our graduation project throughout next week that solves real life scenerios.


All in all, this week was very fun and educative. See you next week after graduation😎🔥
Week 5 in Taskforce 3.0
Tags: javascript, agile, frontend
Published: 2021-10-03 10:00:49

The week was kinda interesting because we dive into deep on some skills i already know , but this time i understood them well. 

Agile methodology.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qn8rsmgeau4dn0lerzf2.jpg)

In this week with help of our facilitators who tried to explain in a simple possible way of how agile works and also it's unique importance compared to other methodology, after a good explanation of agile with real world problem, we played a game which related to agile where each member had a role to play, so i was software developer and other team mates had different roles such as project owner, project consultant, software architecture and a scrum master.

so what i really liked and learned in the game, was the impact of agile to a software developer in a daily life of developing solution of the client's problems, i found how agile can help to brain storm's best solution  for the client project, because also the client has role play in developing solution. and also it takes less time to figure out what is going wrong during the development. There are many things i learned from the session, but this was a cool and educative session during the whole week.

Lastly on Friday with my teammates we come up with an idea of what we are going to develop as the final project in the next week.

See y'all next week when we have developed our interesting project.
Task-Force week five experience
Tags: agilemethodology, brainstorming, codeofafrica, awesomitylab
Published: 2021-10-03 09:59:22

As today marks the end of the fifth week in Task-Force, I'm going to share with you the experience so far.

This week involved a lot of activities and there were many things to learn. 

The session on Thursday was the most amazing as I got to learn about Agile Methodology deeply.

I was not my first time using/knowing about Agile methodology but I found out that there is more to Agile Methodology than what I knew before.

![Agile Methodology](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9hijxdpb2kzn59kbfxl1.jpeg)


We played short games to help us understand Agile Methodology better, where some teammates were acting as SCRUM Masters, Developers, Product Owner, Client and so..on.

This helped me to understand how each party plays a role in Agile Methodology and also understand its best practices.

This was a long day but fruitful. I enjoyed every moment of the Thursday session.

During this week, we also worked on some coding challenges. 
Coding challenges can be fun and also helpful as you are learning and developing your problem-solving skills.

In programming, there are many alternatives to a solution but optimization of your solution also matters.
Coding challenges help you on this. It's good if you start a week with coding challenges to refresh your mind :)

Coming to Friday, we had to brainstorm and come up with an idea for our final project. The idea had to be solving a real problem and had to be unique. 

![Brainstorming](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i3stl4xe5k84v4y5sssb.jpg)

After a brief discussion, we came up with ideas for our project and chose the best one to work on. 

Generally, this week was amazing but Thursday was another thing. It was super amazing. I can't wait to see how next week is going to be like :)
Who Else Wants To Learn About 938 Area Code
Published: 2021-10-03 09:45:23

No matter where you are in the country, you can get a virtual (938) Area Code business phone number using our fast, simple business phone service. Never miss a customer call again. We offer a full business phone service plan with unlimited minutes, call screening, call forwarding, customized voicemail, call history logs, and more. No matter where you live and work, we've got your number.

For Complete Details You May Read>> https://eightyreviews.com/
Primary Website: https://eightyreviews.com/938-area-code/

We offer one plan that includes every feature for $20 a month. We don't believe in locking features that you need behind a higher tier plan. We believe everyone should always receive every feature we offer at one affordable price.

Get a second phone number on your cell phone for your business. No additional hardware is required.
5 HTML tags that make the text italic
Tags: html, javascript, webdev, beginners
Published: 2021-10-03 08:52:21

As I was reading the documentation of HTML, I saw the var tag. Initially, I thought it was related to variables. However, I had seen that it was making the text Italic. So I asked myself, how many HTML tags make text Italic.

I began researching how many HTML tags make the text italic and found 5 tags that do so.

# `<i>` tag
It is a common and well-known tag.
Display style- Inline
`<i>` elements are used to differentiate words from the surrounding text by styling italicized text without adding any emphasis to italicized text.

# `<em>` tag
Display Style - Inline.
The `<em>` element is used to indicate text that should receive more emphasis than the surrounding text.

# `<cite>` tag
Display style - Inline
Use the cite element to identify the source of a quotation or creative work, rather than the author or creator.

# `<dfn>` tag
Display style- Inline
When a term is enclosed in a `<dfn>` tag, browsers and web crawlers will understand that nearby text contains a definition of the term.

# `<var>` tag
Display style - Inline
Most browsers display text marked with <var> tags in italics. This element indicates a variable in a mathematical equation or computer program.

My Blog:- [Beginner Developer Blog](https://beginners-developer.blogspot.com)
Website:- https://ejaazrkhan.github.io/portfolio
Google Test - missing feature
Tags: showdev, cpp, python, tdd
Published: 2021-10-03 08:48:53

**Test-Driven Development**. **Red-Green-Refactor**.
Let's start. You are working on an awesome project in C++ and for TDD you are using the Google testing framework. 

A typical scenario when using TDD:
* The new behavior is introduced and described by a falling test. **We have RED**. 
* Logic is implemented, the test is PASSING. **We have GREEN**.
* The last step, **REFACTOR** test and implementation if possible. 

After that, we run all the tests and we notice that **we have 17 falling tests**. 
What about re-running only failing tests?
What about re-running the first and last failing tests?

This is something that kept popping up to me.
Google Test does not support anything like this, so I decided to write my solution. [Github link](https://github.com/elvisoric/gtester)

## What is it?
Wrapper around Google tests


## What it solves?
It allows you to re-run failed tests as well as to filter those failed tests by using numeric tags 

### How to use it?

* Set which executable file will be executed:
```
./gtester.py --exe exe_name
```
* Run all tests:
```
./gtester.py
```
* Run just failing tests:
```
./gtester.py --run_failing
```
* Run several failing tests using tags:
```
./gtester.py --run_failing 1 3
```

##Example

![Demo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4o7215cxq3nq9w0zodgn.gif)