teleren/devto huggingface dataset:
LeetCode 897. Increasing Order Search Tree (javascript solution)

Tags: algorithms, javascript
Published: 2021-05-24 04:32:52

###Description:
Given the root of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.

###Solution:
Time Complexity : O(n)
Space Complexity: O(n)

```javascript
var increasingBST = function(root) {
    // Create dummy head
    let ans = new TreeNode(0);
    // Pointer to the current node
    let cur = ans;
    // Add node to the right pointer of cur and remove the left pointer of cur then change cur to point to node
    function inorder(node) {
        if (node === null) return;
        inorder(node.left);
        node.left = null;
        cur.right = node;
        cur = node;
        inorder(node.right);
    }
    inorder(root);
    return ans.right;
}
```
Day 71 of 100 days of SwiftUI
Tags: swift, 100daysofcode
Published: 2021-05-24 04:02:02

I  just completed day 71 of 100 days of SwiftUI. Today, I continued working on the maps app. I added a feature to edit location pin names and I also added a nearby places feature. I got the list of nearby places by making an API request to wikipedia.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mwnu88u2rr2e7hke52xp.png)
Hackathon guide, tips, tricks, and resources for organisers
Tags: opensource, hacktoberfest, hackathon, github
Published: 2021-05-24 03:14:32

I'm really excited to finally :ship: something big. Before I started working at GitHub, I was running hackathons. Organising them, mentoring at them, judging entries, and even participating.

I became known as the Hackathon Queen and have been involved in over 100 hackathons to date. People are always asking for tips and tricks when organising their hackathons. Organisers are also wanting lists of resources and examples of other people's work.

Instead of saying the same thing to every hackathon organiser, I thought I'd put something together to share with the world. Not only is it here to share with the world, I also created it so everyone can contribute to it.

## Hackathon Tips, Tricks, and Resources

I present to you: [Hackathon Tips, Tricks, and Resources](https://github.com/github/hackathons).

{% github github/hackathons %}

This is an open source repository containing lots of information for organisers. This is a curated list based on my own experiences in running multiple hackathons. The repo is set up to take contributions from others. It also has [Discussions](https://github.com/github/hackathons/discussions) enabled, meaning organisers can come together and discuss issues, ask questions, find more resources, and share their own experiences.

I really wanted this resource to be available to everyone, but also welcoming of other people's feedback, thoughts, advice, and ideas. There are a lot of people out there with lots more experience so please feel free to share it around, make a pull request, or open a Discussion.

This is for the community and I encourage you to join the repo, star it, head into the Discussions, and download the resources for your use. If you have any questions, thoughts, or feedback, drop them below or feel free to open a Discussion!
Code Smell 71 - Magic Floats Disguised as Decimals
Tags: webdev, javascript, programming, codenewbie
Published: 2021-05-24 03:04:57

TL;DR Don't trust numbers on immature languages like JavaScript.

# Problems

- [Principle of Least Surprise](https://en.wikipedia.org/wiki/Principle_of_least_astonishment) Violation

- [Accidental Complexity](https://dev.to/mcsee/coupling-the-one-and-only-software-design-problem-2pd7)

- Wrong decimal representations.

# Solutions

1. Choose Mature Languages.

2. Represent [Decimals with Decimals](https://dev.to/mcsee/the-one-and-only-software-design-principle-3086).

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/46a81f9ff84ac7c32b2f482e0625efce)

```javascript
console.log(0.2 + 0.1) 
// 0.30000000000000004

//We are adding two decimal numbers
// 2/10  +  1/10 
// Result should be 3/10 as we learnt at school
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/f57afd489e3f65c44e4e92fc1ff74fb8)
```javascript
class Decimal {
  constructor(numerator) {
    this.numerator = numerator;    
  }
   plus(anotherDecimal) {
      return new Decimal(this.numerator + anotherDecimal.numerator);
  }
   toString() {
      return "0." + this.numerator;
   }}     
  
console.log((new Decimal(2).plus(new Decimal(1))).toString());
// 0.3

//We can represent the numbers with a Decimal class (storing only the numerator)
//or with a generic Fraction class (storing both the numerator and denominator)
```
# Detection

Since this is a language feature, it is difficult to detect. We can ask our linters to prevent us from manipulating numbers this way.

# Tags

- JavaScript

- Premature Optimization

# Conclusion

My first programming language was [Commodore 64](https://en.wikipedia.org/wiki/Commodore_64)'s basic back in 1985.

I was very surprised to discover that 1+1+1 was not always 3. Then they introduced integer types. 

JavaScript is 30 years younger, and it has the same immaturity problems.

# Relations

{% post https://dev.to/mcsee/code-smell-69-big-bang-javascript-ridiculous-castings-49ij %}

# More info

[Here](https://blog.pankajtanwar.in/do-you-know-01-02-03-in-javascript-here-is-why) is the technical (and accidental) explanation.

Please, don't argue telling this is fine and expected since this is the binary representation. 

These numbers are decimal, we should represent them as decimals. 

If you think representing them as floats is a great performance improvement, you are wrong. 

Premature optimization is the root of all evil.

# Credits

Photo by <a href="https://unsplash.com/@steve228uk">Stephen Radford</a> on <a href="https://unsplash.com/s/photos/explosion">Unsplash</a>  

* * *

> The purpose of computing is insight, not numbers.

_Richard Hamming_
 
* * *
 
{% post https://dev.to/mcsee/software-engineering-great-quotes-26ci %}

* * *

This article is part of the CodeSmell Series.

{% post https://dev.to/mcsee/how-to-find-the-stinky-parts-of-your-code-1dbc %}
All About Analog Clocks
Tags: javascript
Published: 2021-05-24 03:01:53

I create an animated Analog Clock when at the beginning of my JavaScript journey. I was excited to get started and I knew that I could add my own personal style. 

The first step was to set up the HTML code in different class attributes from 1 to 12.

```html
     <div class="clock">
                <div class="hand hour" data-hour></div>
                <div class="hand minute" data-minute></div>
                <div class="hand second" data-second></div>
                <div class="number number1">1</div>
                <div class="number number2">2</div>
                <div class="number number3">3</div>
                <div class="number number4">4</div>
                <div class="number number5">5</div>
                <div class="number number6">6</div>
                <div class="number number7">7</div>
                <div class="number number8">8</div>
                <div class="number number9">9</div>
                <div class="number number10">10</div>
                <div class="number number11">11</div>
                <div class="number number12">12</div>
            </div>

            <script src="clock.js"></script>     
        </body>
```

## JavaScript

I created an array with a variety of colors, then implemented that array in the `randomColor() function` to change the color on each second, as shown below
.
```javascript
let colorArray = ["#71b8bd", "#6ebcbe", "#6cc1be", "#6bc5be", "#6ac9bd", "#6bcdbb", "#6dd1b9", "#71d5b6", "#75d8b2", "#7bdcae", "#82dfa9", "#8ae2a4", "#93e59f", "#9de899", "#a7ea93", "#b2ed8d", "#beef87", "#caf082", "#d6f27c", "#e3f377"]

function changeColor() {
  let randomColor = colorArray[Math.floor(Math.random() * colorArray.length)];
    document.getElementById('bg-color').style.backgroundColor = randomColor;
}
```
## And here it is!
{% codepen https://codepen.io/soulchick25/pen/vYxmLVx %}
Firefox and Chrome resolve any localhost domain (*.localhost) to loopback address
Tags: firefox, http, dns
Published: 2021-05-24 03:01:43

I was reading this [reddit's thread](https://old.reddit.com/r/programming/comments/nj1all/how_to_get_https_working_on_localhost/gz5qvxm/) and this comment caught my interest:-

>Chrome and Firefox also consider "*.localhost" as secure so you can develop multiple websites with different service workers. They automatically resolve to "localhost" so it's very handy.

I didn't know this and after trying myself on Firefox, that's turn out to be true. I checked my `/etc/hosts` to make sure I didn't have the name defined that and also checked via `host` command and `dig` as well. Both returned domain not found result.

```
host web01.localhost
Host web01.localhost not found: 3(NXDOMAIN)
```

So it pretty sure coming from Firefox itself. Firefox also has this pretty handy dns lookup tools (accessible via `about:networking#dns`):-

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

I can't find much information about this so why not just look directly in the source code? After some googling, I guess the networking portion for Firefox is under the directory called `netwerk` and made my educated guess that the code could be in  `nsHostResolver.cpp`. Then using browser's Find on page for "localhost", voila! The code looks like this:-

```
// Check if we have a localhost domain, if so hardcode to loopback
    if (IS_ADDR_TYPE(type) && IsLoopbackHostname(host)) {
      nsresult rv;
      RefPtr<nsHostRecord> result = InitLoopbackRecord(key, &rv);
      if (NS_WARN_IF(NS_FAILED(rv))) {
        return rv;
      }
      MOZ_ASSERT(result);
      aCallback->OnResolveHostComplete(this, result, NS_OK);
      return NS_OK;
    }
```

https://github.com/mozilla/gecko-dev/blob/master/netwerk/dns/nsHostResolver.cpp#L1031
Laravel One to One Eloquent Relationship Example Tutorial

Tags: laravel, php, programming, tutorial
Published: 2021-05-24 02:31:08

https://codingtracker.blogspot.com/2021/05/laravel-one-to-one-eloquent.html

Hey Artisan,

In this tutorial, I Will explicate how to engender laravel one to one eloquent relationship.We will show one to one model relationship in laravel. you will learn how we can engender migration with peregrine key schema, retrieve records, insert incipient records, update records etc. we will show laravel hasone relationship example.

In this example , we will engender "employee" and "salary" table.both table are connected with each other, i will engender one to one relationship with each other by utilizing laravel Eloquent Model, We will first engender database migration, then model retrieve records and then how to engender records too.One to One Relationship will utilize "hasOne()" and "belongsTo()" for cognation.

Here the example of laravel one to one eloquent relationship.

if you want to see full example follow this link..
Project 1 Complete: DogSweeper!
Tags: gamedev, javascript, css, html
Published: 2021-05-24 02:14:15

Our first project is officially finished! We were tasked with three requirements: first, to fetch data from a public API, second, to run the app on one page only, and lastly, to use 3 separate event listeners. Since Minesweeper involves a lot of clicking, and I personally want to focus on game design and development as a career, I thought that this idea would suit wonderfully.

Making the actual game was easier than I thought. I created a bunch of cells using loops to create the x and y-axis of the board. As each cell was created, attributes are distributed so that the cells can have mines, a number of mines adjacent to them, or 0. After that was some grueling math in order to randomize the mines, and it was off to the event listeners!

In order to start the game and create the board, I created a simple start button to fill one of the 3 required event listeners. The second was using onclick() in order to play the actual game, reveal mines, etc. The third I used as both a test for the API, to make sure the images would come in perfectly, and that is my "I deserve a dog" button. Clicking this button will fetch the data from the dog image API I chose to use, so anyone needing a picture of a good dog could easily get one. The game will also fetch a dog for us when we win, but it's nice to have dogs on command!

This project, though poorly timed due to some family emergencies, was a blast to get through. It also reaffirmed myself that a career in game development is very possible, so I am thankful for the opportunity that FlatIron has given me. 

If you need me, I'm going to go decompress from this week with some classic Dogsweeper.

Also, here is my dog. I have put her in the API as well. <3 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6jiiy2ukhxrccl8qxdq7.png)
Live Q&A on DevOps, GitHub and Azure DevOps
Tags: devops, github, azuredevops, live
Published: 2021-05-24 01:24:14

Got any questions about __DevOps__, __GitHub__ and/or __Azure DevOps__?

Join me for this live Q&A and I will try and answer all your questions!

{% youtube ICP3hHCEcUI %}

To celebrate the 2,000 subscribers on my YouTube channel [CoderDave](https://youtube.com/CoderDave) I will host a live Q&A/AMA next Tuesday (_see below the time schedule_)

Prepare your questions, and I hope to see y'all live! And if you can't make it, post your questions either here or in the comments of the video so I can address them during the live!

Thanks so very much again for your support!

TIME OF THE LIVE:

- Tuesday 25, 9.30 pm UTC+8
- Tuesday 25, 7.00 pm IST
- Tuesday 25, 1.30 pm UTC
- Tuesday 25, 9.30 am ET
- Tuesday 25, 6.30 am PT

__Like, share and follow me__ 🚀 for more content:

📽 [YouTube](https://www.youtube.com/CoderDave)
☕ [Buy me a coffee](https://buymeacoffee.com/CoderDave)
💖 [Patreon](https://patreon.com/CoderDave)
👕 [Merch](https://geni.us/cdmerch)
👦🏻 [Facebook page](https://www.facebook.com/CoderDaveYT)
🐱‍💻 [GitHub](https://github.com/n3wt0n)
👲🏻 [Twitter](https://www.twitter.com/davide.benvegnu)
👴🏻 [LinkedIn](https://www.linkedin.com/in/davidebenvegnu/)
🔉 [Podcast](https://geni.us/cdpodcast)
Book recommendation: Team Topologies
Tags: team, book, recommendation
Published: 2021-05-26 07:04:24

---
title: Book recommendation: Team Topologies
published: true
date: 2021-05-24 00:00:00 UTC
tags: team,book,recommendation
canonical_url: https://jhall.io/archive/2021/05/24/book-recommendation-team-topologies/
---

About a year ago I was helping an early-stage startup grow their software engineering staff. Around the same time, the book [_Team Topologies_](https://amzn.to/3vgzx4C) by Matthew Skelton and Manuel Pais, was published. I read most of it on a flight from Amsterdam to Madrid, and was able to immediately begin to put it to use.

The book offers four fundamental team types, which roughly map to the [three types of dependencies](https://jhall.io/archive/2021/05/22/three-ways-to-manage-dependencies/) I talked about on Saturday:

- **Stream-Aligned Team:** this team type is perhaps the most numerous, is usually cross-functional in nature.
- **Platform team:** this team type is perhaps most commonly seen in operations roles (often mislabeled a “DevOps team”), and develops and maintains the platforms that allow the stream-aligned teams to work unhindered.
- **Enabling team:** this team type doesn’t always exist, but when it does it is generally at the beck and call of the stream-aligned teams, as needed. Some organiations put QA in teams like this.
- **Complicated-Subsystem Team:** the least common type of team, this is designed to reduce the cognitive load on other stream-aligned or platform teams, when there some especially complicated piece of technology that must be maintained.

If your company is struggling with how to organize its teams, this book will give you some priceless food for thought. And it’s non-dogmatic approach is very refreshing!

* * *
_If you enjoyed this message, [subscribe](https://jhall.io/daily) to <u>The Daily Commit</u> to get future messages to your inbox._
Observer Pattern
Tags: designpattern, observerpattern, python
Published: 2021-05-23 17:21:02

Last week we learned about Strategy pattern, today we are going to see about Observer pattern.

The Observer pattern is a behavioral design pattern in which an object can have multiple dependents(can be called observers) which will get notified when the state of the object changes.

Some of the terms we need to know are

- Observer - Dependents which should get notified
- Observable - Object which will notify its observers

A real-world example of this pattern is magazine company subscription service. Let's say we are subscribing to a magazine. Here the magazine company is the object they will have the list of dependents (people who are subscribed to their magazine). Whenever a new magazine is published, it will be sent to all the subscribers.

 Some of the technical examples of Observer pattern are

- Model View Controller Pattern (Here View represents  **Observer** and Model represents **Observable**)
- **LiveData** in Android
- In Social media platforms like Facebook/Twitter, a person can post or update his status and their followers will get a notification.

Lets see how we can implement this pattern in Python

```python
class Subject(object):
    def __init__(self):
        self.observers = []

    def subscribe(self, observer):
        self.observers.append(observer)

    def unsubscribe(self, observer):
        self.observers.remove(observer)

    def notify(self, *args, **kwargs):
        for observer in self.observers:
            observer.notify(*args, **kwargs)

class EmailSender(Subject):
    pass
```

In the above code, we have a `Subject` which has methods for subscribing/unsubscribing observers. Also, we have a method called `notify`, whenever the user wants to send emails to his subscribers he can call this method.

> Note that we have written the common code for observer pattern in a separate class called `Subject` . This is for reusability and for cleaner code.

```python
class EmailObserver(object):
    def __init__(self, email):
        self.to_address = email

    def notify(self):
        self.send_email()

    def send_email(self):
        print(f"Sending email to {self.to_address}")

if __name__ == '__main__':
    email_sender = EmailSender()
    subscriber1 = EmailObserver("abc@gmail.com")
    subscriber2 = EmailObserver("efg@gmail.com")

    email_sender.subscribe(subscriber1)
    email_sender.subscribe(subscriber2)
    email_sender.notify()

    print("Unsubscribing subscriber1")
    email_sender.unsubscribe(subscriber1)
    email_sender.notify()
```

In the above code we have defined `Observer` and subscribed it to `EmailSender`

The above code will output the following

```python
Sending email to abc@gmail.com
Sending email to efg@gmail.com
Unsubscribing subscriber1
Sending email to efg@gmail.com
```
Microsoft Azure Services and Concepts
Tags: webdev, azure, tutorial, az900
Published: 2022-02-01 23:24:58

---
title: Microsoft Azure Services and Concepts
published: true
date: 2021-05-24 00:00:00 UTC
tags: webdev,azure,tutorial,az900
canonical_url: https://www.rupeshtiwari.com/microsoft-azure-services-and-concepts/
---

> Learn everything you should know about Azure Services and their concepts as a beginner.

## Azure Infrastructure and Management

1. Azure Data Center
2. Azure Regions and Availability Zones
3. Azure Resource Group
4. Azure Resource Manager (ARM)
5. Infrastructure as Code Using ARM Templates
6. Azure Service Health & Azure Monitor
7. Azure Mobile App
8. Azure Advisory for optimizing your Azure resources.

## Azure Core Products

1. Virtual Machines
2. Containers
3. Azure App Service
4. Serverless Compute in Azure
5. Core Networking Products in Azure
6. Windows Virtual Desktop
7. Azure Content Delivery Network (CDN)

## Azure Data Storage

1. Managed Databases
2. Azure Cosmos DB
3. Azure Storage Accounts
4. Azure Blob Storage
5. Data Migration Options

## DevOps Solutions in Azure

1. Pipelines
2. Azure DevTest Labs

### Azure Service Health

![](https://imgur.com/Nc5EvmZ.png)

[Azure Status](https://status.azure.com/en-us/status) generates all global Azure service status. Azure Service Health broadly check 4 different kind of health categories like:[Planned Maintenance](#planned-maintenance), [Health Advisories](#health-advisories), [Security Advisories](#security-advisories), [Service Issues](#service-issues). Azure Health also allows you to configure health alerts based on above categories events. You can also add action groups to either email or SMS or phone call on desired health events.

🏆 **ProTip**   
  
Azure Service Health is: **Planned, Health & Security, Service**.

graph TD;     A(Azure Service Health)-->P(Planned Maintenance); A-->H(Health Advisories); A-->S2(Security Advisories);     A-->S(Service Issues);

#### Planned Maintenance

You can find planned maintenance in Azure and notify your clients of an up coming events or reschedule an up coming release.

#### Health Advisories

Changes in Azure Service that require your attention. For example, if features in a service that you use are being deprecated or you need to upgrade your web application because a framework version in Azure App Service is updated.

#### Security Advisories

Notifications or violations that may affect availability of your Azure services.

#### Service Issues

In the Azure portal Azure Service Health list down all the service issues that may impact you based on your resources in use.

### Azure Monitor

Azure Monitor is a solution within Azure for collecting and analyzing telemetry from your Azure or on-premises resources.

graph TD;     A(Azure Monitor)-->M(Metrics); A-->L(Logs); A-->W(Workbooks);     A-->I(Insights);

### Azure Mobile App

Azure Mobile App gives an easy and secure way to manage your Azure resources, even when you are out of the office and not near computer.
HowTo: Create a billing alarm
Tags: aws, cloudpractitioner, notes
Published: 2021-05-23 23:32:36

# Why?

Setting up this alarm will monitor your billing charges. It allows you to set a treshold value (e.g. $20.00). When your bill goes over $20.00, you get an email from AWS.

## Steps

1. Log in to the AWS Console

2. Go to the CloudWatch service > Billing

3. Click Create Alarm

4. Select Metric > Billing > Total estimated charge > USD > Select Metric > Static > Enter a Threshold value ($10) > Next 

5. Create new topic > enter email address > Create Topic > Next

6. Verify your email address by logging into your email account. Look for the email, click verify. Go back to AWS console.

7. Alarm name > Alarm Description > Next

8. Create Alarm
Lo que construyes es un MVP o una primera versión?
Published: 2021-05-23 23:17:07

Cuando recién se inicia varios proyectos de software o algunos concursos, se usa rápidamente la abreviatura de MVP. 
Si es una empresa o startup que recién probará su sistemas o proyectos de software, entiendo que sería correcto ese uso, pero si la idea es construir una versión inicial que poco a poco se le agregará más características, será correcto llamarlo MVP?

A mi parecer, lo más adecuado es llamarlo "versión beta" o "versión gamma" y con numeraciones que inician con "0.X", por ejemplo versión "0.1, 0.2, 0.2.1" y así. Hasta cuando sea la versión estable llamarla "1.0". La diferencia aquí, es que, se está usando el mismo proyecto de software, es decir, la misma base, misma tecnología y repositorio. Desde un versión inicial, es lo que el cliente quiere, solo que poco a poco estás complementando o agregando características. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/00on8hun84vxz8vfikfz.png)

A diferencia de un MVP, significa que tu MVP 1, podría ser usado con una tecnología X, luego tu MVP 2, es con una tecnología Y, y así, retirando el producto trabajando anterior para acercarte más a lo que el cliente quiere.