teleren/devto huggingface dataset:
I've made a web component to easily implement and switch  two themes in a webpage.
Published: 2020-09-05 21:23:04

A lot of websites nowadays have this feature of having two color schemes for the user to choose, namely "dark" and "light", implementing this is a peace of cake with the help of CSS custom properties (variables) and a bit of ECMAscript. Today I present you a web component that abstracts the ECMAscript part and lets you switch between the themes dynamically.

Using the component is straightforward. The component adds and updates a data attribute "data-theme" to the body element which you can handle in CSS via attribute selectors, so depending on the theme you have you can update your theme variables. 

See a [live demo](https://diegosanchezp.github.io/theme-switcher-component) before using it.

## Usage example
To install it use your preferred package manager.

`npm install theme-switcher-component`

OR 

`yarn add theme-switcher-component`

In a .html file include and declare the component.

```html
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Theme switcher component demo</title> 
    <link rel="stylesheet" href="./styles.css">
    <!-- Include the component -->
    <script type="module" src="./node_modules/theme-switcher-component/switch.js" defer></script>
  </head>

  <body>
    
    <main>
      <section>
        <p>Components are not applications, they are just a part of the whole.</p>
        <!-- Declare the component -->
        <!-- The first element of the array themes defines the default theme -->
        <theme-switcher themes='["light", "dark"]' verbose></theme-switcher>
      </section>
    </main>

  </body>
</html>
```

Note: other names in the themes array rather than the typical "light" and "dark" can be defined, for example, "solarized" and "tango".

In a .css file declare in the root selector the css variables to use and change their values accordingly to the two themes defined selecting the body.

```css
/* Define a theme with variables */
:root {
  /* Light theme the default*/
  --border-color: black;
  --bg-color: white;
}

/* Change variables values accordingly*/

body[data-theme="dark"]{
  --border-color: white;
  --bg-color: black;
}

/* ... More CSS rules below ... */
```

After a theme is changed, it gets stored to `localStorage`, if you want to see values of the local store and the current theme set the `verbose` attribute to the <theme-switcher> custom element, like the example.

That's it ! Hope this helps you. 

If you want more in depth documentation check the github repository
{% github diegosanchezp/theme-switcher-component no-readme %}

And the [live demo code](https://github.com/diegosanchezp/theme-switcher-component/tree/master/demo).
Jumping on the Clouds Code Challenge Solved
Tags: codechallenge, hackerrank
Published: 2020-09-05 21:16:53

---
title: Jumping on the Clouds Code Challenge Solved
published: true
description: Complete the jumpingOnClouds function in the editor below. It should return the minimum number of jumps required, as an integer.
tags: codechallenge, hackerrank
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/e11ujwccltz3jteu0gzg.jpg
---
Emma is playing a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. She can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus **1** or **2**. She must avoid the thunderheads. Determine the minimum number of jumps it will take Emma to jump from her starting postion to the last cloud. It is always possible to win the game. 

For each game, Emma will get an array of clouds numbered **0** if they are safe or **1** if they must be avoided. For example, **c = [0, 1, 0, 0, 0, 1, 0]** indexed from **0...6**. The number on each cloud is its index in the list so she must avoid the clouds at indexes **1** and **5**. She could follow the following two paths: **0-2, 2-4, 4-6** or **0-2, 2-3, 3-4, 4-6**. The first path takes **3** jumps while the second takes **4**.

**Function Description**
Complete the jumpingOnClouds function in the editor below. It should return the minimum number of jumps required, as an integer.

jumpingOnClouds has the following parameter(s): 
- c: an array of binary integers 

## The solution:

```
function jumpingOnClouds($c) 
{
    $jumps = 0;
    $pos = 0;
    while ($pos < sizeof($c) - 1) {
        if ($c[$pos + 2] == 0) {
            $pos = $pos + 2;
            $jumps++;
         } else if ($c[$pos + 1] == 0) {
            $pos = $pos + 1;
            $jumps++;
        } else {
            break;
        }
    }
    return $jumps;
}
```
How I Applied to a Tech Job Using a POST Request
Tags: api, post, jobapplication
Published: 2020-09-05 21:14:46

I recently tweeted about a job application experience where I had to send my application using a POST request.
{% twitter 1302042477403279360 %}

It gained a lot of attention and bewilderment, so I'm going to use this post to ~demystify~ the process.

# The Job Posting
The job I applied to was for a [Technical Support Engineer position](https://plaid.com/job/?id=04afea9f-0859-4f1d-a439-e54e11658283) at [Plaid](https://plaid.com/). They provide two ways to apply: through a typical form or sending an API request. I chose to do the latter!

# How I Did It

### Gathering the Info
The job application provided a sample POST request body and the API endpoint, as shown below:

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

Now, all I had to do was gather my application information for the POST request and then send the request!

### Using Insomnia to Send the Request
There are numerous API tools out on the market. I chose to use [Insomnia](https://insomnia.rest/), an open-source API client application, to send my request. Luckily, Insomnia was easy-to-use and quickly walked me through the steps of creating an API request:

1. After opening Insomnia, click on `New Request`.

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

2. In the window that pops up:

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

    > - Type in a name for your request under `Name`.

    > - Click the drop-down menu and choose `POST`. A new drop-down list will appear next to `POST` that will ask you if there is a body to your request. Choose `JSON`, which was specified in the API instructions given in the job posting.

    > - Click the `Create` button.

3. Paste the raw JSON request body with your application information into the field under `POST`.

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

    > Make sure to remove the optional comments within the request body.

4. Paste the API endpoint that was provided in the job application next to `POST` in the top right corner.

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

5. Click the `Send` button!

# Results
After clicking `Send`, you should receive a HTTP response. If it all is well, you will see a 200 OK HTTP Response with a message saying "We got your application and we'll get back to you shortly!"

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



Tada! There you have it! 🎉 You should have been able to send a simple POST request to an API endpoint that contains your job application.
Sock Merchant Code Challenge Solved
Tags: codechallenge, hackerrank
Published: 2020-09-05 21:14:17

---
title: Sock Merchant Code Challenge Solved
published: true
description: Given the number of socks in the pile n and an array of colors of each sock, how many pairs do we have?
tags: codechallenge, hackerrank
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/icnnntdyxo4o5gqqtf8c.jpg
---
John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.

For example, there are n = 7 socks with colors ar = [1, 2, 1, 2, 1, 3, 2]. There is one pair of color 1 and one of color 2. There are three odd socks left, one of each color. The number of pairs is 2.

Given the number of socks in the pile n and an array of colors of each sock, how many pairs do we have?

## First solution:

```
static int sockMerchant(int n, int[] ar) {
    int pairs = 0;
    HashSet<int> set = new HashSet<int>();
    foreach (int i in ar)
    {
        if (set.Contains(i)) continue;
        int[] matchedItems = Array.FindAll(ar, x => i == x);
        int occurrencies = matchedItems.Length;
        if (occurrencies > 1)
            pairs += ((occurrencies - (occurrencies % 2)) / 2);
        set.Add(i);
    }
    return pairs;
}

```
## Second solution:
After showing the first solution to [Serhii Dyshko](https://www.linkedin.com/in/sergeydyshko/) at [this post on LinkedIn](https://www.linkedin.com/feed/update/urn:li:activity:6598274962220425216/) I optimized the first solution using LINQ and came up with this another solution:

```
static int sockMerchant(int[] ar)
{
    int pairs = 0;
    int[] colorsCount = ar.GroupBy(color => color).
                Select(color => color.Count()).
                ToArray();
    foreach (int count in colorsCount)
    {
        pairs += ((count - (count % 2)) / 2);
    }
    return pairs;
}
```
## Third solution:
As you can see, both solutions has a complexity of O(N^2) and this is not a good for performance. So, I have reasearched a little more on the web and asked for help on some Slack groups and received the solution bellow, proposed by [Higor Ramos](https://www.linkedin.com/in/higorcesar/) with a complexity of O(N):

```
static int SockMerchant(int[] ar)
{
	var socksPairs = new Dictionary<int, int>();
	int nSocks = 0;
	for (var i = 0; i < ar.Length; i++)	{
		var current = ar[i];
		if (socksPairs.ContainsKey(current)) {
			socksPairs[current]++;
			if (socksPairs[current] == 2) {
				nSocks++;
				socksPairs[current] = 0;
			}
		} else {
			socksPairs[current] = 1;
		}
	}
	return nSocks;
}
```
This Sock Merchant challenge is part of [HackerRank](https://www.hackerrank.com/)
Counting Valleys Code Challenge Solved
Tags: codechallenge
Published: 2020-09-05 21:11:56

---
title: Counting Valleys Code Challenge Solved
published: true
description: Print a single integer that denotes the number of valleys Gary walked through during his hike.
tags: codechallenge
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/umxck6n0altwqa94pykc.jpg
---
Gary is an avid hiker. He tracks his hikes meticulously, paying close attention to small details like topography. During his last hike, he took exactly **n** steps. 

For every step he took, he noted if it was an uphill, **U**, or a downhill, **D** step. Gary's hikes start and end at sea level and each step up or down represents a **1** unit change in altitude.

We define the following terms:
- A mountain is a sequence of consecutive steps above sea level, starting with a step up from sea level and ending with a step down to sea level.
- A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level.

Given Gary's sequence of up and down steps during his last hike, find and print the number of valleys he walked through.

For example, if Gary's path is **s = [DDUUUUDD]**, he first enters a valley **2** units deep. Then he climbs out an up onto a mountain **2** units high. Finally, he returns to sea level and ends his hike.

**Challenge:** _Print a single integer that denotes the number of valleys Gary walked through during his hike._

## Solution:
```
static int countingValleys(int n, string s)
{
    int altitude = 0;
    int valleys = 0;
    Array steps = s.ToArray();
    foreach (Char step in steps)
    {
        if (step == 'D') altitude--;
        if (step == 'U')
        {
            altitude++;
            if (altitude == 0) valleys++;
        }
    }
    return valleys;
}
```
The main thing about this solution is the fact that our algorithm must only increase the number of valleys when the current step is uphill. Otherwise, our algorithm will count not only valleys but also counts the moments when Gary has climbed a mountain and return to the sea level.
C# Tuples
Tags: csharp
Published: 2020-09-05 21:00:07

Beginning with C# 7.0, Tuples [can be expressed like this](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-tuples):

```
(double, int) t1 = (4.5, 3);
Console.WriteLine($"Tuple with elements {t1.Item1} and {t1.Item2}.");
// Output:
// Tuple with elements 4.5 and 3.

(double Sum, int Count) t2 = (4.5, 3);
Console.WriteLine($"Sum of {t2.Count} elements is {t2.Sum}.");
// Output:
// Sum of 3 elements is 4.5.
```

This way you don't have to write `new Tuple(item1, item2)`.

Tuples can be expressed succintly in method signatures. For example, this method returns an `IEnumerable` of tuples of generic type `T`:

```
public static IEnumerable<(T,T)> Pairs<T>(IEnumerable<T> ts)
{
    var skip = 1;
    T previous = default;
    foreach (var current in ts)
    {
        if (skip == 0)
        {
            yield return (previous, current);
        }
        else
        {
            skip--;
        }
        previous = current;
    }
}
```

This method enumerates through pairs of an `IEnumerable`.

For example, if you have `new [] { 1,2,3 }`, the following tuples will be enumerated (using the new syntax): `(1,2)`, `(2,3)`.
Looking forward to learning to develop like a pro.
Published: 2020-09-05 20:48:59

Been hoping to land a remote a job since I am an indie artist producing my own songs and so I need to save more time than ever if I wanna be a pro both at coding development and high quality music producer. Anyone who can show me how to better understand this whole coding stuff in a more simplistic manner and how I can integrate it perfectly for my music business I will greatly appreciate it. Hope everyone is doing well.
Serverless error-handling pipeline using Redis
Published: 2020-09-05 20:39:44

Errors are an essential part of an application. These are the thing that you don't want to occur, but if they do, then there should be some mechanism to detect them. These errors can be due to some service unavailability, bugs, or any other unforeseen issue. In this article, I am going to highlight how we used IBM Cloud Functions, a serverless offering by IBM, and Redis to log the errors in our Slack channel.

# Background
We have a Node.js application that interacts with Salesforce CRM offerings and performs certain operations. There are times when the application gets an error message. Whenever we get these messages, we want to detect and log these errors into our Slack channel so that appropriate actions can be taken.

# Technology used
We used [IBM Cloud Functions](https://cloud.ibm.com/functions/), which is a FaaS(Functions as a Service) platform based on Apache Openwhish. It allows us to run the application without worrying about the configurations. [Redis](https://redis.io/) cache was used to store the error logs within our system. It is an in-memory key-value data structure with in-build replication and LRU cache features.

# Working
Our Node.js application runs within our IBM Cloud Kubernetes cluster which interacts with Salesforce CRM systems. Whenever it sees an error, we trigger IBM Cloud Functions. At this point, the Node.js application continues its work in the Kubernetes cluster without worrying about the errors. The control for error handling is being transferred to IBM Cloud functions.
![Application Workflow](https://dev-to-uploads.s3.amazonaws.com/i/n1yu9sznl8dwx6suqb9v.png)
IBM Cloud functions try to establish a connection with the Redis cluster and stores the log over there. We categorize the type of error and then check if the error is eligible to be sent over to the Slack channel. If we have to send the message on Slack, we use Slack Webhooks. Once this message is sent, we remove the log from Redis.

We are using Redis to make sure that our logs have been processed. If we get an error next time, we will check if our Redis cluster contains any error messages that need to be processed. It will then retry sending these messages to Slack, thus helping us to ensure we don't miss any errors.
Angular on StackBlitz
Tags: angular, stackblitz
Published: 2020-09-05 20:27:57

[Angular](https://angular.io/docs) normally requires you to install [Node.js](https://nodejs.org/) and the [Angular command-line interface tool](https://cli.angular.io/) to [get started with an Angular project](https://angular.io/guide/setup-local).

Instead, to try out Angular, check out StackBlitz.

- Go to: https://stackblitz.com/

- Click the "Start a new app" button.

- Click "Angular". 
  - Stackblitz will create a "Hello, World" Angular application for you.

Example: https://stackblitz.com/edit/angular-ivy-nlem87
Programming Analogies
Published: 2020-09-05 20:20:31

When I first heard the Beatles on the Ed Sullivan show I immediately wanted to learn how to play the Guitar.

Throughout high school I practiced daily and continued for 30 years. I studied music theory, played in bands, did solo performances, played in church, and even had garage band practice on Friday evenings for years at a time.

I purchased custom guitars, amplifiers, effect pedals, Shure microphones, a nice PA system, Lexicon reverb units, compressors, a bass guitar and a top line bass amp and speaker cab. I had Amp modeling gear, guitar player magazine subscriptions for years.

I hung out on guitar forums and owned hundreds of CDs. I guess I just loved the guitar.

But despite all that I was never satisfied with my progress. I never sounded just like Eric Clapton, Eric Johnson or Tommy Emanuel. I did however sound like my own style. Something that was never pre-planned,rather it was just a mix of all I had learned and preferred to hear.

I was good enough to get paying solo performances for weekend work, but could never live off the pay.

Programming is similar in a lot of respects. It can be heavy on theory, is always creative and challenging, it's mostly enjoyable and there is always new 'songs' to hear.

Arriving to programming plateaus, just like guitar playing often leaves me thinking, 'What? That's all it's about?'. And on it goes, everyday a bit better off but never a Tommy Emanuel. 

[Michael Keller Guitars](https://www.youtube.com/watch?v=-ByDBiQtLAA)
Ridiculous new UX web-series pilot with Ivy and Derek
Tags: beginners, design, ux
Published: 2020-09-05 20:05:07

Naturally–as world renowned Experience User Experts–we had to come up with a really classy name for our new UX company.

## SUPER ULTRA EXPERIENCE USER EXPERTS DOT COM

{% youtube MHeGiNmL9G4 %}

Yes: This is real. Yes: reality is silly.

But hey - if you're one of those people out there who's about to go to a UX bootcamp to learn how to build graphic layouts for user-personas, maybe you should watch this - and get a feel for what web design is _really like_.

We also CHALLENGE YOU! To create a Golf Course website for your portfolio. _Tripple-dog-dare_

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/e59hlrcbw358fp826o51.png)
Day 51: Design World
Tags: 100daysofcode, design
Published: 2020-09-05 20:03:42

I dived into design today. I'm working on a one page progressive app. Here is the design.

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


I'd prefer to jump straight into the code but I'll end up spending a lot of time trying different variations. 

_Day 51_
OOP vs DB programming
Tags: oop, database
Published: 2020-09-05 19:30:49

Hello, as you can see this is my first post, I'll try to write about the programming languages that I know, and any other topic that I consider it's important for me to remember.

To begin with this blog, I want to talk about the difference between object oriented vs database programming, there's a lot to talk about, but I will focus on what has been my experience working with these two paradigms.

In the last six years I've been working mostly with database programming, the process to create a stored procedure could be very uncertain, if there isn't a clear process and specially a standard to follow, you could feel a dangerous freedom at the moment to write your code. I understand the advantages of using database programming for example, the speed to deploy changes in production and the easy to modifying the data, to name a few. But the fact that you don't have to compile all the project before deploying in production, it can bring many problems. For example, if a colleague adds a new parameter in a function, he don't need to modify every stored procedure/function/trigger where the function is called, and the function will compile successfully. Then when another colleague execute a stored procedure where that function is being used, he will see an error in execution time, 
which could be avoided. That kind of cases happens every day, because both the language and the programmer don't have the obligation to do so. Here comes the need to set rules and a standard that everybody must adopt.

By the other hand, when you develop with object oriented programming, it gives you a path to follow, I'm not saying that OOP resolves all the technical issues you encounter in the way, but makes the process a little bit neater and cleaner, and in mostly cases errors happens in compilation time, which is the right moment to correct it and make the adjustments necessary to a good deploying in production. Another advantage is the using of design patterns through interfaces and abstract classes which can be a quite clear path to walkthrough into a problem. It's nice to mention, that always you need to adopt a standard to get everybody in the right direction, in developing is quite easy to get a system into a completely mess, if you don't have people concerned for the correct applying of the company rules, and maybe the most important, for the language guidelines.

This is just a question about how many companies walks into a cloudy tunnel, when we talk about techniques of how to develop their systems, how to grow and how certain people choose these paths almost without thinking about the future.