teleren/devto huggingface dataset:
Programming Exercise: Frequency Sort
Tags: java, programming, leetcode
Published: 2020-06-12 23:34:10

---
title: Programming Exercise: Frequency Sort
published: true
description: Frequency Sort
tags: java, programming, leetcode
series: programming-exercises
//cover_image: https://direct_url_to_image.jpg
---

## Background
Recently, I decided to solve some of the problems in leetcode.com for fun and practicing my java which I have not used in a while. I decided to document my thought process as I solve these problems. You can find some of the other solutions in the series table above this section.

## Problem
[Frequency Sort](https://leetcode.com/problems/sort-characters-by-frequency)
Given a string, return another string where the characters are sorted by the frequency of their appearance with the most repeating at the beginning. 
Eg:
```
Input: tree
Output: eert
Input: aabbbc
Output: bbbaac
```

## Solution
Whenever I see a problem like this, where the output depends on the how each item in a list relate to another item in the list (here for e.g. how many times each element appears in the list) my mind immediately jumps to a two pass approach with a hashmap. 

This is not because hashmaps are my favorite data structure (I don't have a favorite data structure), but rather the ease of lookup of hashmaps. So usually my mind thinks how I can store the data in a hashmap in the first pass, so that I can look it up in the second pass thereby avoiding a nested loop. 

This problem was no different and I started out the same way. But when I started to write down what the hashmap I needed I realized I might need two hashmaps. One to represent how many counts of a characters there are, and another to represent the different counts itself. (There might be a better way of doing it, but this is what I came up with in the first try)

So my two hashmaps for the second example above looked like this at the end of the first pass: 

```javascript
// For each character a string with their frequency
{
  a: aa,
  b: bbb,
  c: c
}
// For each count a list of characters with the count
{
  1: [a, b, c],
  2: [a, b],
  3: [b],
}
```
Now there is some repetition in the second map, but that was ok since I didn't want to add additional complexity of lookup in the first pass.

From here it was a matter of sorting the counts and then forming a string from the other map.

This yielded the following code: 
{% gist https://gist.github.com/deepakvenkat/a1db4426c1b6dc1adcc69f7d4c671f90 file=FrequencySort.java %}

### Complexity
Since there are a few different steps involved in here lets see the complexity of each step:
1. First pass - constructing the hashmap - `O(n)` where n is the length of the string.
2. Sorting the counts - `O(k.log k)` where k is the number of unique counts.
3. Second pass - constructing the result - 
  3.1 `O(n)` - if each character appeared only once.
  3.2 `O(k + n)` - if there are `k` counts each with more than one item. But since k < n, that is really `O(n)` 

So the most expensive operation here is the sort.
Show Dev: tutorial for ScrapingBee thanks to Dev! 🥳 🥳 🥳
Tags: showdev, ruby, tutorial, codenewbie
Published: 2020-06-18 17:40:48

**Tech writing is my passion.** I love it. Since I started blogging, I was quickly approached by different companies and devs who needed help with either writing a readme, tutorials or other docs. Usually, I can't share this work because it either exists in private repos or was ghostwritten. Recently, however, I noticed a wonderful opportunity in [the Dev listings](https://dev.to/listings) where [ScrapingBee](https://www.scrapingbee.com/) looked for tech writers. Long story short, the collaboration was dream-like and [my blog on web scraping with Ruby](https://www.scrapingbee.com/blog/web-scraping-ruby/) was just published:

![Scrolling through my blog post](https://dev-to-uploads.s3.amazonaws.com/i/585pg0up5v1ty86hm5nq.gif)

In the blog post, **I explain the basics of web scraping with Ruby but also create an automated job tracker** because I see many of my friends now go through the pain of remembering where to apply and by when! 

Let me know what you think about the blog post — and remember to check Dev's listings!

***
**cover photo**: ScrapingBee's header for my blog post
Material Dialog in 10 minutes
Published: 2020-06-18 17:40:33

A Minimal example to get started with [Material Dialog](https://material.angular.io/components/dialog/overview) using Angular.

```typescript
 import { MatDialog, MatDialogConfig } from "@angular/material/dialog";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"],
})
export class AppComponent {
  constructor( private dialog: MatDialog) {}
 // The HTML button click handler
 onButtonClicked($event) {
    let httpClient: HttpClient = new HttpClient(this.httpHandler);
// Causes a CORS error 
httpClient.get("http://www.google.com").subscribe(
      (response) => {
        console.log(response);
      },
      (error) => {
        let dc = new MatDialogConfig();
        dc.autoFocus = true;
        // Important part
        dc.data = error;
        this.dialog.open(ErrorHandlerComponent, dc);
      }
    );
  }

```

This statement is the call to open but uses the injected component as the display.

```typescript
this.dialog.open(ErrorHandlerComponent, dc);
```
**The Injected Component**
```typescript
export class ErrorHandlerComponent implements OnInit, AfterViewInit {
  error: HttpErrorResponse;
  constructor(
    // Must inject MAT_DIALOG_DATA
    @Inject(MAT_DIALOG_DATA) public data: any,
    private ref: ElementRef,
    private HtmlElementService: HtmlElementService
  ) {
    // Html binds to this.error
    this.error = data;
  }
```

**The Injected Component's HTML**
```html
<h1 mat-dialog-title>{{ error.statusText }}</h1>
<div mat-dialog-content>
  <p>Message</p>
  {{ error.message }}
</div>
<div mat-dialog-actions>
  <button class="mat-raised-button" mat-dialog-close>Close</button>
  <button class="mat-raised-button mat-primary" (click)="save()">Copy</button>
</div>
```

✔️ **The Result**

 ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/0xzfd7k8jny3k0muna6e.png)

**Observations**

Many examples show this being done in app.component, that's the only reason this example does the same. 

A timer can be placed on the Injected Component to auto-close. This makes is more of an notification or toaster item.

The configuration contains [many properties](https://material.angular.io/components/dialog/api#MatDialogConfig) which are nice features.

I don't care for the data being passed in the configuration.  Wouldn't this make more sense?

```typescript
this.dialog.data = this.data;
let dc = new MatDialogConfig();
dc.autoFocus = true;
this.dialog.open(ErrorHandlerComponent,dc);
```
Creating a To-do App with Auth {react-redux-firebase v3}
Tags: react, redux, javascript, beginners
Published: 2020-06-18 17:24:38

Hey guys, I recently completed a playlist on my YouTube Channel where we are creating a complete To-do app with auth using react, redux and firebase.

I have listed all the 13 videos in the playlist below.

**Please support my content** (*Stay Awesome!*)
1. Subscribe to my YouTube channel [here] (https://www.youtube.com/channel/UCe8uN9zoKksCb1hfw61myRw?sub_confirmation=10)
2. Donate to my PayPal [here](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NZCBMP9V54G9J&source=url)

The following is the table of content:
* [Introduction](#introduction)
* [Installing Bootstrap](#bootstrap)
* [Adding React Router](#react-router)
* [The Nav-Bar Component](#nav-bar)
* [The SignIn and SignUp Components](#SignIn-SingUp)
* [Bootstrap Tables](#bootstrap-tables)
* [Why Redux?](#why-redux)
* [Adding Redux?](#redux)
* [Adding Redux-thunk](#redux-thunk)
* [Creating Firebase Project](#fbProject)
* [Adding react-redux-firebase Version 3](#react-redux-firebase)
* [CRUD Operations](#crud-operations)
* [AUTH](#auth)

For these videos to be more productive to you, take your time and learn by doing. Get your hands dirty and you'll get it better.

Here is the link to the playlist: [playlist](https://www.youtube.com/playlist?list=PL63c_Ws9ecIT-3xsPL_9wsUC7hTptBCUQ)

Or you can use the videos below.

**Introduction #0** <a name="introduction"></a>
{% youtube 7ibFgnUvzVY %}
**Installing Bootstrap #1** <a name="bootstrap"></a>
{% youtube YOmzyc1ArrE %}
**Adding React Router #2** <a name="react-router"></a>
{% youtube xMuKMihI-ac %}
**The Nav-Bar Component #3** <a name="nav-bar"></a>
{% youtube v2Grz2MHAnw %}
**The SignIn and SignUp Components #4** <a name="SignIn-SingUp"></a>
{% youtube gwyTGjrxQwo %}
**Bootstrap Tables #5** <a name="bootstrap-tables"></a>
{% youtube _z0GYAJf6Ug %}
**Why Redux? #6** <a name="why-redux"></a>
{% youtube QbCncZlZYgQ %}
**Adding Redux #7** <a name="redux"></a>
{% youtube S0ehjKlPcLA %}
**Adding Redux-thunk #8** <a name="redux-thunk"></a>
{% youtube UuYEdxjFu3o %}
**Creating Firebase Project#9** <a name="fbProject"></a>
{% youtube FwQQDxHGB8c %}
**Adding react-redux-firebase Version 3 #10** <a name="react-redux-firebase"></a>
{% youtube C804gQ7YVxA %}
**CRUD Operations #11** <a name="crud-operations"></a>
{% youtube PmzcByhVg1M %}
**AUTH #12** <a name="auth"></a>
{% youtube 1pWsm4pBjkI %}

Thank you for passing by.
Happy coding 💙
SEO tips for Hugo blog 
Tags: help, showdev
Published: 2020-06-18 17:22:07

I just started [blogging](https://tckb.tgrthi.me) (this time for real) a week ago, I am interested in configuring it for SEO.

I appreciate any suggestions or improvements from anyone with SEO experience :pray: It is based on Hugo and I tried to tune it based on some online tutorials. Unfortunately, it gets pretty bad rating and needs improvements.
CSS Index Generator?
Tags: css, discuss
Published: 2020-06-18 17:17:55

I've sometimes seen lengthy stylesheets that include an index at the top something like: 

```
1: Headings: line 255
2: Cards: line 380

...

255: /*----------Headings-------*/

...

380: /*---------Cards----------*/
```

This makes it super easy to navigate big stylesheets.  Is this done by hand? I imagine it's super tedious to go in and update the index even if your just making a few line changes or the project is in active development.  

Is there any sort of gulp tool that would do this for you based on some formatting in the css?
We are looking for a mobile phone developer for Neonflight
Published: 2020-06-18 17:07:19






We would like to further develop our game "NeonFlight".  Therefore we are looking for a team/person to program our game for the mobile version.  If you want to see the PC version watch the trailer: https://youtu.be/7XtrcNlrYbs. If you are interested please write us a mail: mika.borg@online.de



Best regards, 
 
Borg Entertainment, Mika
Manage subscriptions in your Gatsby Blog by connecting a custom React form to Hubspot
Tags: react, gatsby, marketing, hubspot
Published: 2020-06-18 17:00:15

Hubspot is a great tool that offers a full platform of marketing, sales, customer service, and CRM software --- plus the methodology, resources, and support --- to help businesses grow and engage with their customers.

Learn how to manage subscriptions in your Gatsby Blog by connecting a custom React form to Hubspot.

[View the blog post for this video](https://juliapottinger.com/manage-subscription-in-gatsby-blog-with-custom-react-form-connected-to-hubspot/)

[View the repository](https://github.com/jpott77/connect-custom-react-form-to-hubspot/)

{% youtube FCZAO33fRKg %}

#react #gatsby #hubspot
What are some of the coolest things you've made using *just* HTML or CSS?
Tags: discuss, podcast
Published: 2020-06-18 16:45:27

---
title: What are some of the coolest things you've made using *just* HTML or CSS?
published: true
description: Answer this question for a chance to be featured in the next episode of DevDiscuss!
tags: discuss, podcasts
---

The format of DEV's first official podcast, [DevDiscuss](https://dev.to/devdiscuss), begins with an interview and ends with commentary from the community.

For this week’s episode, we want to know...

**What are some of the coolest things you’ve made using just HTML or CSS?**

If you'd like a chance to be featured in the episode, please send us a voice memo or leave a comment below by Wednesday, June 24th. 

### Details on how to participate:

* Call our Google Voice at +1 (929)500-1513 and leave a message 📞
* Send a voice memo to pod@dev.to 🎙

OR, if you don't want your voice recorded...just leave a comment here and we'll read your response aloud for you 🗣

### Our most recent episode:

{% podcast https://dev.to/devdiscuss/s1-e6-little-known-productivity-tools-big-productivity-gains %}
Mocking API calls in Laravel TDD
Published: 2020-06-18 16:44:28

---
title: Mocking API calls in Laravel TDD
published: true
description: If you are used to TDD, you will definitely come across this at some point. 
tags: 
//cover_image: https://direct_url_to_image.jpg
---
If you are used to TDD, you will definitely come across this at some point. Mocking an API client like Guzzle is a piece of cake in Laravel.
As a test case, I want to mock a Guzzle call to get data from a certain endpoint.
I will simply do the following 
- Import the following classes into your test class.

   use Mockery;

   use GuzzleHttp\Client;

   use GuzzleHttp\Psr7\Response; 


- Create a mockery object.

   $mock = Mockery::mock(Client::class);

NOTE:- the Client class is Guzzle Class.
- Create a response variable.

   $response = json_encode(['data'=>'ok']);

NOTE:- The array should contain the expected response you want.
- Now define what the mock object should do.

  $mock->shouldReceive('get')->once()->andReturn(new Response(200,[],$response));
- Finally, bind the mock object to an instance of the Guzzle client class.

  $this->app->instance('GuzzleHttp\Client', $mock);

After following these steps, anywhere you instantiate Guzzle class in your code will automatically call the mock object instead.

Do you have other ideas about mocking API calls ?, feel free to comment.
Ciao !
World Wide Creators Conference this weekend and there are still FREE tickets available
Tags: eventsinyourcity, news
Published: 2020-06-18 16:30:50

[https://hopin.to/events/world-wide-creators-conference-by-visionaryislife](https://hopin.to/events/world-wide-creators-conference-by-visionaryislife) A lot of interesting talks coming.

I'm going to have a presentation about tools that help you become more organized and that way more efficient. I explain how to use Notion, Google Calendar, and how to make gradual improvement every week using certain kind of framework.

I recommend to get the free ticket as soon as possible because they are running out. There is also an option to pay something as donation. Justin, who is organizing this, is really good person and puts the money back to the community so it's for good cause.
Introducing functional programming in Javascript - Part 2 Pure functions and Side Effects
Tags: javascript, functional, react
Published: 2020-06-18 16:27:54

In the first part of our series about functional programming we talked about Immutability, now we will talk about pure functions and side effects and how these concepts can improve the quality of your code ✅

👉🏻 Check the post here: https://devinda.house/2020-06-18

Liked this post? 💬 Comment 🤝 Share on your stories and mark us 💙 Like and 👉🏻 Follow us to daily content of #programming, #javascript, #reactjs and more 🙏🏻⁣⁣⁣
⠀⠀⠀⠀⠀⠀⠀⠀⠀⁣⁣⁣
📨 Send us your feedback, if you want to make a partnership or have something to talk, please send us an email to talk@devindahouse.com⁣⁣⁣
how to learn something
Tags: beginners
Published: 2020-06-18 16:27:06

If you are reading this article now, be calm don't give up!
Throughout our lives, it is common for us to experience difficulties mainly in technology, but everything that is new, ends up causing us strangeness even, don't worry, at that moment it means that you need to open your mind, humble yourself and be patient, difficulties will always arise and when at the end of persistence we overcome a little bit the limits of our capacity we can feel the taste of having overcome ourselves through a quality that we acquire either in a personal way or in work/study.
it's just one pill of good words that you can take.
Thanks for reading! ;)
Code is clean if it can be understood easily by everyone on the team. 😇
Tags: github, codequality, firstpost, cleancode
Published: 2020-06-18 16:25:46

Hey, hey! 👋
Check this repository 👉 [clean-code](https://github.com/julkwel/clean-code) 👈
_______

# 🤔 What is this ?
I created this repository to share how to write a clean code ✍ for all programming langage.

Thanks for reading !
Reset Postgres ID sequence in Rails
Tags: todayilearned, rails, postgres, webdev
Published: 2020-06-18 16:22:19

Today I had to restore backup data from one of our SQL dumps to my local development database.  For one reason or another the table id sequences didn't reset after the restore. So I was getting errors in my terminal like this:

```
PG::UniqueViolation: ERROR:  duplicate key value violates unique constraint "track_events_pkey"
DETAIL:  Key (id)=(3673) already exists.
: INSERT INTO "track_events" ("track_session_id", "action", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" excluded from capture: DSN not set
```

Manually resetting it is actually quite easy.

Hop into your `rails console` and run:

```ruby
ActiveRecord::Base.connection.tables.each do |t|
  ActiveRecord::Base.connection.reset_pk_sequence!(t)
end
```

I hope this helps someone else who runs into a similar issue!
Making the first ever web scraper
Tags: python, beginners, tutorial
Published: 2020-06-18 16:13:37

This is a comprehensive on point tutorial to get you started on web scraping. Before getting on our project we have to install some mandatory libraries. 

Let's get started.


*Beautiful Soup*
So, [beautiful soup](https://www.crummy.com/software/BeautifulSoup/bs4/doc/) package is the essence of web scraping and all we are about to do. Short intro- It's a python package to parse HTML and XML documents.
{% gist https://gist.github.com/saswat01/ee979a3ce2bec515bf618be7ab918b7a %}

*Requests*
[Requests](https://requests.readthedocs.io/en/master/) is a python HTTP library to make HTTP and XML requests simple and convenient.
{% gist https://gist.github.com/saswat01/24104251c384faeb03c91dd2aa7de55e %}

Now, we are done with installing all the ingredients that we need to cook our first web scraper. We will be using the [newegg](https://www.newegg.com/) website to scrape the costs of graphics card that are available on the website.

**Step 1**
Hop on to your favourite editor and follow my lead.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/4ekgcpggcjydm4ziu0qq.gif)

Let's first import our libraries that we just pip-installed. 
{% gist https://gist.github.com/saswat01/dd828d9a076eb89f2718a794a40d2e87 %}

**Step 2**
After importing the libraries, we have to make an HTTP request to the newegg website to scrape through. We will be using the requests library to make the request. When the request is approved we will parse the website using our beautiful soup library.
{% gist https://gist.github.com/saswat01/bbb1c3def86f308ea265e92d67cd1c57 %}

**Step 3**
Pheww, we are halfway down the road.

Okay, now we have to do bit of an excercise. Navigate to this [link](https://www.newegg.com/global/in-en/p/pl?d=graphics+card) and explore for real on this page. Let the information sink in. 

Now, open the developer tools of your browser(for chrome: [follow](https://developers.google.com/web/tools/chrome-devtools/open)
for firefox: [follow](https://developer.mozilla.org/en-US/docs/Tools#:~:text=You%20can%20open%20the%20Firefox,%2B%20Opt%20%2B%20I%20on%20macOS.)) and watch the code even if you don't understand and try finding where the prices would be hidden amongst these layers of code. Sorry, for sounding gloomy but as web scraper you have to develop this intuition.

******************************************************************

After you are done experimenting and playing around let's dig the website and do what we're supposed to do. So, we will use the beautiful soup library to find the price from our parsed website. And we wil repeat this step to extract the prices of all the graphics cards on the page.
{% gist https://gist.github.com/saswat01/70f6e825c6f04bc55cc27ba471329c8a %}

Congratulations! You just made your first ever web scraper.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ssae5kbksknr9gko6avo.gif)

Here is the full code:

{% gist https://gist.github.com/saswat01/c750b1ed16a42fe7ba8bae2ea90d2eb6 %}


######Note: Maybe your output was not clean but you got the prices. Try cleaning them and remove the unnecessarily spaces. Good Luck!
I need problem slides!
Tags: presentation, slides, codeland, discuss
Published: 2020-06-18 16:11:37

Hi, everyone! I'm presenting a workshop, Presentation Skills for Brainiacs, at [Codeland 2020](https://codelandconf.com/). I'm looking for some slides that I can redesign to show the students how it's done. The purpose is not to say, "Ha-ha, this slide is ugly!" Instead, I'll be breaking down the issues the slide has and redesigning it to address them. The slides will be totally anonymized. I will send you the redesigned slide so that you can use it in your own presentations. 

##**Can you help me by sending me your problem slide?**

I need your slide no later than June 25. **Thank you!**
Routing to EC2 without EIP
Tags: terraform, aws
Published: 2020-06-18 16:08:52

# TL;DR
Explicitly define that the `aws_instance` associates a public IP address and then create a Route 53 `A` record that points to the instance's public IP:
```lang=terraform

resource "aws_route53_record" "www" {
  zone_id = "..." # PlaceHosted zone ID here

  name    = "foo_subdomain"
  type    = "A"
  ttl     = "300"
  records = ["${aws_instance.foo.public_ip}"]
}

resource "aws_instance" "foo" {
  ...
  associate_public_ip_address = true
  ...
}
...
```

## Where's the load balancer?
Ideally, you want to have a scalable setup where every service is containerised, put them in a private VPC, setup load balancer to handle public requests, and then setup routing for the requests to the services. Unfortunately, I had a setup where I was forced to create a [pet server instead of cattle](https://medium.com/@Joachim8675309/devops-concepts-pets-vs-cattle-2380b5aab313) in a herd.

I needed to host a network management tool that required old-school ways of setting up and heavily relying on the state of the disk. To make my life harder it only worked for Ubuntu and it even required me to do a few custom configuration to make it work on the latest distro. :shrug: Luckily, the instance is unlikely to have insane traffic so I am not forced to setup a load balancer to handle scaling issues.

Since the software itself made it hard to containerise it, I needed to do some compromises. I made sure to harden the instance such as setting up the security group to restrict access to our office IP, and I only allowed shell access through AWS Session Manager. To improve fault-tolerance we setup Data Lifecycle Manager to take snapshots of the instance's EBS volume in regular intervals. 


## Why not use Elastic IPs (EIPs)?
To differentiate public IPs from EIPs:
> Public IP addresses are dynamic - i.e. if you stop/start your instance you get reassigned a new public IP.

> Elastic IPs get allocated to your account, and stay the same - it's up to you to attach them to an instance or not. You could say they are static public IP addresses.

EIPs are great for keeping a consistent public IP address. It works for use cases where you need to change the instances behind the IP.

For my use case, I don't really care if the public IP changed since I don't intend to change the instance every time. If it does change, I'll simply run terraform again to update the Route53 record with the new public IP of the instance.

Fin. :fish: