Shared posts

14 Jun 11:29

Building KNN from Scratch (Because import sklearn Feels Like Cheating)

by Darsh Ayde

Building K-Nearest Neighbors (KNN) From Scratch

Let's be real: in a production machine learning environment, we all just import scikit-learn and call it a day. But treating algorithms like black boxes can come back to bite you when those abstractions leak. Building K-Nearest Neighbors (KNN) from scratch is a fantastic exercise to actually understand the mechanics working under the hood.

At its core, KNN relies on a surprisingly simple geometric premise: a data point probably belongs to the same category as its closest spatial neighbors. Rebuilding this classifier from the ground up forces you to tackle some critical engineering challenges, such as:

  • Computing spatial geometry efficiently
  • Managing state during the voting process
  • Handling edge cases and algorithmic ties deterministically

In this post, we'll walk through the architectural decisions behind a pure Python implementation of KNN, translating textbook math into functional code.

1. The Distance Metric

import math

def _check_length(x, y):
    """Ensure both vectors have the same length."""
    if len(x) != len(y):
        raise ValueError("Vectors must be of same length")

def euclidean_distance(x, y):
    """Compute Euclidean distance between two vectors."""
    _check_length(x, y)

    sum_of_sq = sum(
        (i - j) ** 2
        for i, j in zip(x, y)
    )

    return math.sqrt(sum_of_sq)

The Goal

Calculate spatial similarity between vectors using Euclidean distance.

How It Works

KNN is fundamentally a geometry problem. The entire algorithm hinges on quantifying exactly how far apart points are in a given space.

If we're looking at a 2D plane, Euclidean distance comes straight from the Pythagorean theorem:

d=(x1​−x2​)2+(y1​−y2​)2​

In machine learning, however, we're rarely dealing with just two dimensions. Fortunately, the formula generalizes neatly to an arbitrary number of dimensions:

d(x,y)=i=1∑n​(xi​−yi​)2​

Where:

  • n is the total number of dimensions.
  • xi​ and yi​ are the coordinates of vectors x and y along dimension i .

In the euclidean_distance() function above, notice the generator expression inside sum(). It evaluates lazily, meaning we avoid constructing an intermediate list of squared differences in memory. This is a deliberate design choice that scales well when working with high-dimensional data.

Also, don't overlook the _check_length() guard—it is structurally critical. Comparing vectors of different dimensions is mathematically invalid. Since Python's zip() function silently truncates to the shortest iterable, omitting this check could allow the function to fail silently and return incorrect results.

2. The Voting Mechanism and Tie-Breakers

def _get_majority_vote(neighbors):
    # ... early-exit validation skipped ...

    vote_count = {}
    min_distance_per_label = {}

    for neighbor in neighbors:
        label = neighbor["label"]
        distance = neighbor["distance"]

        vote_count[label] = vote_count.get(label, 0) + 1

        min_distance_per_label[label] = min(
            distance,
            min_distance_per_label.get(label, float("inf"))
        )

    best_label = None
    best_vote = -1
    best_distance = float("inf")

    for label in vote_count:
        votes = vote_count[label]
        dist = min_distance_per_label[label]

        if votes > best_vote or (
            votes == best_vote and dist < best_distance
        ):
            best_label = label
            best_vote = votes
            best_distance = dist

    return best_label

The Goal

Tally the neighbors' labels to determine the final classification while using spatial proximity as a deterministic tie-breaker.

How It Works

Counting votes is straightforward with a hash map, but robust edge-case management is what separates a demo implementation from production-ready code.

Imagine a scenario where k=4 and your query point sits exactly halfway between two Class A neighbors and two Class B neighbors. A naive implementation might simply choose whichever label appears first. That makes the classifier non-deterministic and biased by data ordering.

To address this, the implementation maintains a secondary dictionary:

min_distance_per_label

As the algorithm iterates through the neighbors, it tracks the minimum distance observed for each class label. If a voting tie occurs,

votesA​=votesB​

the algorithm chooses the class whose nearest representative is closest to the query point.

Mathematically:

argcmin​(x∈cmin​d(x,q))

Where:

  • c is a class label.
  • q is the query point.
  • d(x,q) is the distance between a training sample and the query point.

This approach anchors tie-breaking in actual spatial proximity rather than arbitrary ordering or randomness.

3. The Orchestrator

import numpy as np

def knn_predict(training_data, labels, query_point, k):
    # ... input validation skipped ...

    distances = [
        euclidean_distance(sample, query_point)
        for sample in training_data
    ]

    nearest_idx = np.argsort(distances)[:k]

    neighbors = [
        {
            "distance": distances[i],
            "label": labels[i]
        }
        for i in nearest_idx
    ]

    return _get_majority_vote(neighbors)

The Goal

Create a controller function that computes distances, isolates the top k candidates, and delegates classification to the voting logic.

How It Works

Although a production implementation would include comprehensive validation and optimization, the core algorithm relies on one key operation:

np.argsort(distances)[:k]

Keeping multiple arrays synchronized during sorting can quickly become messy. Rather than zipping distances and labels together, sorting them, and then unpacking them again, we sort only the distance values and retrieve the corresponding indices.

numpy.argsort() returns the indices that would sort an array. This allows us to select the nearest neighbors without mutating the original data structures.

Mathematically, we're selecting:

argsort(D)1​

where D is the vector of computed distances.

This is a common scientific-computing pattern because it preserves the relationship between distances and labels while avoiding unnecessary data transformations.

After selecting the nearest indices, we package the neighbors into lightweight dictionaries and pass them directly to the voting mechanism.

Final Thoughts

K-Nearest Neighbors is a unique machine learning algorithm because it behaves less like a traditional parameter-learning model and more like a combination of geometric reasoning and voting heuristics.

Unlike algorithms such as linear regression or neural networks, KNN performs no explicit training. It simply stores the dataset and uses distance as a proxy for similarity during prediction.

Building algorithms from scratch is one of the fastest ways to demystify machine learning. You quickly discover that much of the perceived complexity comes from standard software engineering concerns:

  • Performance optimization
  • State management
  • Data validation
  • Numerical stability

The mathematics matters, but so does thoughtful implementation.

Further Reading

To explore more machine learning projects and software engineering content:

04 Jun 13:26

Article: Architectural Change Cases: a Practical Tool for Evolutionary Architectures

by Pierre Pureur, Kurt Bittner

Architectural change cases extend architecture decision record (ADR) thinking by evaluating how decisions may evolve over time. Change cases expose hidden assumptions and help teams estimate the reversibility and cost of change.

By Pierre Pureur, Kurt Bittner
30 Mar 20:20

Netflix har sabbat sin Apple TV-app

by Hugo Engström
Byter ut inbyggda mediaspelaren i tvOS



Netflix har rullat ut en uppdatering till sin Apple TV-app som verkar ha upprört en hel del användare, inklusive mig. Det man har gjort är att byta ut den inbyggda mediaspelaren i tvOS mot en egen, vilket bland annat innebär att det numera krävs två klick istället för ett för att spola fram eller tillbaka i en video. Tidigare hoppade ett enkelt klick på fjärrkontrollens hjul tio sekunder i tiden, men nu pausar det första trycket bara bilden och öppnar upp en tidslinje. För att faktiskt hoppa framåt eller bakåt krävs sedan ytterligare ett knapptryck.

Ändringen gör iallafall så att upplevelsen nu är densamma som på exempelvis Android TV, Fire TV och Roku, men för Apple TV-användare innebär det att åratal av muskelminne nu är rätt värdelöst i Netflix-appen. Tyvärr är ändringen permanent och går varken att ångra eller avinstallera.


Läs vidare och kommentera:
https://feber.se/internet/netflix-har-sabbat-sin-apple-tv-app/490172/

Läs mer om Apple TV-app, tvOS, Android TV, Fire TV, Roku, uppdatering, mediaspelare
23 Jan 12:35

Högre rörelsevinst än väntat för Ericsson

by Finwire
Telekomleverantören Ericsson överraskade med en omsättning som var lägre än väntat i Q4. Vd:n Börje Ekholm ser en fortsatt osäker marknad under 2024. Styrelsen föreslår oförändrad utdelning.
16 Dec 06:01

7 Best Tools For Developers - They Can't Live Without It

by Dev Journal

 The best tools for developers are a priority for them to work. As a developer, he always works with code editors, browsers, terminals, etc. to improve his productivity. VS Code is one of the best editors, every developer would like to work with it. I've also listed the VS Code extensions for JS that are useful for a developer. And browser extensions are also a great way to improve productivity and I've also listed Chrome extensions for a developer.


If you are a junior programmer, this will give you an idea the improve your coding skills, and if you are a senior developer, you are still learn something new from it. Extensions are one the best tools for developers.
Let's see the best tools for developers.
Read More: 7 Best Tools For Developers - They Can't Live Without It
14 Dec 06:07

Integrating Azure Speech Service with LUIS(Language Understanding Service)

by /u/Ancient-Ad4966
05 Jul 19:02

5 EXACT alternatives of VSCode!

by Muhimen

At the end of the day, Visual Studio Code(or VSC) is a text editor just like notepad or atom or something else. But what makes VSCode special than others? Not sure about you, for me it is...

  • Extensibility
  • Lightweight
  • Customization
  • Debugger 🐛
  • Ease of use

makes the difference. Although I haven't used some different text editors other then Vim, I am pretty sure I will get somewhat disappointed if I use some other text editors other than VSCode. I know those text editors also have something great to offer, but for me, VSCode is the best. However, someone said

Varieties are the spice of life

So, if you wanna try something else but still want the flavor of good old(not too much old though) VSCode then here is a list of 5 EXACT alternatives for Visual Studio Code.

1. Visual Studio

Do you know that Visual Studio Code was inspired from Visual Studio?

Visual Studio

Though Visual Studio is not as light-weight(because it's an IDE, not a code editor) as VSC, you still have the major features like Extensibility, Debugging, Ease of use. And if you are up to the following stuff, Visual Studio is just for you.

  • Game development
  • Mobile app development with unity
  • Desktop app development with C++
  • .NET development
  • Linux development with C++
  • ...

In a nutshell, if you are up to any kind of development with C++, you must try out Visual Studio.

Ow, I forgot the mention, you can use almost all the extensions that you use with VSCode!!

2. Visual Studio Code Insiders

VSC-Insiders

If you like to stay up to date all the time then Visual Studio Code Insiders is just for you. VSC Insiders and VSC are almost the same. But the insiders version is updated quite frequently(I generally receive 5 updates per week). If you want to try out all the latest features of Visual Studio Code, then don't forget to try out Visual Studio Code Insiders.

Benefits

And, don't even worry about the instability issue. I am using insiders daily never faced any issue with it. It feels EXACTLY like VSCode.

FYI: I am writing this blog in VSC Insiders

3 Visual Studio Codium

Open source version of VSCode.

VSCodium

Wait! Isn't VSCode open source itself? Here is what folks from Microsoft have to say.

When we [Microsoft] build Visual Studio Code, we do exactly this. We clone the vscode repository, we lay down a customized product.json that has Microsoft specific functionality (telemetry, gallery, logo, etc.), and then produce a build that we release under our license. When you clone and build from the vscode repo, none of these endpoints are configured in the default product.json. Therefore, you generate a “clean” build, without the Microsoft customizations, which is by default licensed under the MIT license

That means the Visual Studio Code you use isn't baked from the official GitHub repo although, technically it's the same repo with some small changes.

VSCodium does all the things for you to turn the main VSCode repo into binary so that you can use it without any problem.

If you don't want people to track your data

Visual Studio Code collects telemetry data, which is used to help understand how to improve the product. For example, this usage data helps to debug issues, such as slow start-up times, and to prioritize new features.

Consider using Visual Studio Codium

The VSCodium project exists so that you don’t have to download+build from the source. This project includes special build scripts that clone Microsoft’s vscode repo, run the build commands, and upload the resulting binaries for you to GitHub releases. These binaries are licensed under the MIT license. Telemetry is disabled.

That means you are getting the original Visual Studio Code in your machine. So, if you want the real experience of open source Visual Studio Code then this is for you.

4 Visual Studio Codespaces(PAID)

Codespaces
Can you run VSCode on your mobile phone? Certainly not. However, if you want to keep coding even when you are on the run, you will prefer something lightweight. Most of the time, it's a laptop. But in the worst-case scenario, you will need something lighter than a laptop. And you guessed it right. It's a mobile phone.

Visual Studio Codespaces is an online version of VSCode. Alternatively, it's a web app of VSCode. But why should you use VSCodespaces instead of VSCode? There is no strong reason behind it. 😅

Here are a few reasons that might change your mind to use VSCodespaces.

  • Cross-platform(shall I say cross-device? 😅) development
  • Remote workflow
  • Collaborative development

However, there is a catch. You will need to pay for this.

Here is how it works

You host an environment on the cloud and then access it via Codespaces. Let's say, you will use Azure for hosting the app. And you will host a standard environment that will have the following specs.

  • 4 Cores CPU
  • RAM of 8GB
  • 64 GB SSD storage

It will cost you about $0.169 per hour. Not that expensive.

5 Eclipse Theia

Theia

If you like the idea of VSCode as a web app but don't have the money to spare, then you should consider trying out Eclipse Theia.

Eclipse Theia follows the same concept as Codespaces, a web app. The main difference is the company(and the money). Here is what Eclipse has to say.

We believe VS Code is an excellent product. That is why Theia embraces many of the design decisions and even directly supports VS Code extensions.

Theia versus VS Code

  • Theia's architecture is more modular and allows for way more customizations,
  • Theia is designed from the ground to run on Desktop and Cloud, and
  • Theia is developed under a vendor-neutral Open-Source Foundation.

This is it. I use the VSCode Insiders version in my day to day operation. It has never disappointed me. Let me know in the comment section which one you liked the most.

Until next time, happy coding for you. 😀

24 Jun 05:03

Becoming a Technical Fellow at Headspring, and New Beginnings

My journey at Headspring started for me at a local developer meetup, the "Austin Agile Lunch" group, way back in 2007. I had started blogging and getting involved in the community, attending the local .NET user group, code camp, and most influentially, the first ALT.NET open space conference. At
23 Jun 19:25

How do you abstract business logic?

by /u/randomrabo
15 Jun 05:05

Problem with Winforms timer

by /u/Phantonia

Hey :3

I'm currently writing a playbar control for music or videos, and in the background it is using a System.Windows.Forms.Timer which ticks every interval (default is 50 milliseconds) to redraw the control. When the current position is greater or equals the total duration that is set for the control, it should finish (and raise the Finished event). The duration and current position are represented by System.TimeSpan. But there is a problem: Somehow when setting the duration to 20 seconds, as an example, the playbar is finished after around 25 seconds (as determined by a System.Diagnostics.Stopwatch). I feel like it's a performance problem because it becomes better the higher the interval is.

This is my timer.Tick event handler:

private void OnTimerTick(object sender, EventArgs e) { CurrentPosition = CurrentPosition + TimeSpan.FromMilliseconds(timer.Interval); if (CurrentPosition >= Duration) { timer.Enabled = false; Finished?.Invoke(this, EventArgs.Empty); Running = false; return; } Invalidate(); } 

I don't know if this code snippet is enough to answer the question. If you need more information, feel free to ask. This is the whole code: https://pastebin.com/C6NMATw6

Thanks in advance.

submitted by /u/Phantonia
[link] [comments]
14 Jun 18:26

The Case for Comma-Leading Lists

by Lewis Lloyd

Introduction

Comma-leading lists are an objectively better presentation style.

They make logical sense; the next value on the list is dependant on the comma, and so, they should be kept together.

The style may look alien at first, but give it a test drive and you'll be surprised at how quickly it starts to look normal.

For now, let's have a look at the benefits.

Justification

1. No Merge Conflicts

When adding a new value to a list with trailing commas, you're making 2 additions and 1 deletion.

Comma-Trailing List Diff

This will give you a merge conflict just because someone else adds a value on a different branch.

By using the comma-leading style, you make 1 addition and 0 deletions.

Comma-Leading List Diff

These commits play ball with each other, without needing any conflict resolution.

"Ah, but I've used a dangling comma," you say? Allow me to continue.

2. Dangling Commas Bad

It's true that using a trailing comma after the final value will prevent conflicts, but it's dumb for two reasons.

1. Language Inconsistency

SQL doesn't support them.

Comma-Leading JSON

The JSON standard and Pre-ES5 JavaScript don't support them.

Comma-Leading JSON

It's better to stick to a style that works across more languages, especially for a multi-lingual codebase.

2. Redundant Logic

There's not a second element. It's unnecessary context, so why justify it?

And, if an interpreter ever decides to stick a None in there, good luck.

3. Better Presentation

Separating Context

With the comma-leading style, the logic stays on the left, and the data stays on the right.

This makes it quicker and easier to scan when looking through code.

Better Presentation

It will also allow you to quickly identify logic errors, such as missing commas.

Leaking Globals

Saving Whitespace

When you indent after the opening bracket, you're adding extra columns of whitespace on the left-hand side.

Placing the commas on the left keeps the code neat and narrow. Neat!

Summary

Comma-leading lists are easier for source control, more compatible across languages, and much faster to read since they keep data separate from the list's logic.

Do the world a favour and switch to a better standard of data structure.

animals = [ "ant"
          , "bat"
          , "cat"
          , "dog"
          ]

What's not to love? 😉

Hey, guys! Thank you for reading. I hope that you enjoyed this.

Keep up to date with me:

Catch you around!

07 Jun 14:49

Vendors Update Controls for .NET Core 3.1, Blazor

This week saw two third-party vendors of dev tools -- UX and UI toolkits and controls -- release new offerings that include support for two of Microsoft's main open source frameworks, the cross-platform .NET Core 3.1 and Blazor, which allows for creating browser-based web applications with C# instead of JavaScript.
28 May 17:06

ASP.NET Core in .NET 5 – sending a request

by Michał Białecki

Sending a request in ASP.NET Core in .NET 5 is a standard operation that can be achieved pretty easily. However, details matter in this case and I’ll show you the best practice available. We will also take a look at some advanced features to get the full scope.

Using a real available API

In this article, I will be using 3rd party free service for fetching weather forecasts – http://weatherstack.com. To be able to use it, just register on their website and you can use it as well. 1000 requests in a month are available for a free account and that should be more than enough to fulfill our needs.

First, let’s have a look at the requests we are going to make. To test the API, I’m using a Postman app, which is very powerful, yet intuitive. I strongly encourage you to read my article about it here: Postman the right way

Here is how a request to fetch current weather in Poznań looks like:

This is a GET request to http://api.weatherstack.com/current with two parameters:

  • access_key which you get when registering on the website
  • query that can be a city name

The response that we got is a 200 OK with JSON content.

 To make this request, I’ll create a WeatherStackClient class.

using Microsoft.Extensions.Logging;
using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;

namespace PrimeHotel.Web.Clients
{
    public class WeatherStackClient : IWeatherStackClient
    {
        private const string AccessKey = "3a1223ae4a4e14277e657f6729cfbdef";
        private const string WeatherStackUrl = "http://api.weatherstack.com/current";

        private HttpClient _client;
        private readonly ILogger<WeatherStackClient> _logger;

        public WeatherStackClient(HttpClient client, ILogger<WeatherStackClient> logger)
        {
            _client = client;
            _logger = logger;
        }
    }
}

There are a few things to notice here:

  • AccessKey which is hardcoded for now, but in a real-life API should be moved to configuration
  • IWeatherStackClient interface that is introduced for Dependency Injection support
  • HttpClient class is passed in a constructor. It will be automatically created and maintained by the framework

Now let’s create the logic.

public async Task<WeatherStackResponse> GetCurrentWeather(string city)
    {
        try
        {
            using var responseStream = await _client.GetStreamAsync(GetWeatherStackUrl(city));
            var currentForecast = await JsonSerializer.DeserializeAsync<WeatherStackResponse>(responseStream);
            
            return currentForecast;
        }
        catch (Exception e)
        {
            _logger.LogError(e, $"Something went wrong when calling WeatherStack.com");
            return null;
        }
    }

    private string GetWeatherStackUrl(string city)
    {
        return WeatherStackUrl + "?"
                + "access_key=" + AccessKey
                + "&query=" + city;
    }

Let’s go through this code and explain what’s going on:

  • _client.GetStreamAsync is an asynchronous method that takes a URL an returns a stream. There are more methods, like: GetAsync, PostAsync, PutAsync, PatchAsync, DeleteAsync for all CRUD operations. There is also GetStringAsync that serializes a response content to string – just like GetStreamAsync does
  • GetWeatherStackUrl is merging a service URL with query parameters, returning a full URL address
  • JsonSerializer.DeserializeAsync<WeatherStackResponse>(responseStream) deserializes a stream and format output as a WeatherStackResponse class

The WeatherStackResponse class looks like this:

using System.Text.Json.Serialization;

namespace PrimeHotel.Web.Clients
{
    public class WeatherStackResponse
    {
        [JsonPropertyName("current")]
        public Current CurrentWeather { get; set; }

        public class Current
        {
            [JsonPropertyName("temperature")]
            public int Temperature { get; set; }

            [JsonPropertyName("weather_descriptions")]
            public string[] WeatherDescriptions { get; set; }

            [JsonPropertyName("wind_speed")]
            public int WindSpeed { get; set; }

            [JsonPropertyName("pressure")]
            public int Pressure { get; set; }

            [JsonPropertyName("humidity")]
            public int Humidity { get; set; }

            [JsonPropertyName("feelslike")]
            public int FeelsLike { get; set; }
        }
    }
}

Notice that I used JsonPropertyName attribute to identify what JSON property is each property matching. Here is the structure that we are going to map.

One last thing – we need to register our WeatherStackClient in a Dependency Injection container. In order to do so, we need to go to Startup class and add the following line in ConfigureServices method.

services.AddHttpClient<IWeatherStackClient, WeatherStackClient>();

We are using a dedicated method for registering classes using HttpClient. Underneath it’s using IHttpClientFactory that helps to maintain the pooling and lifetime of clients. You have a limited number of HTTP connections that you can maintain on your machine and if you create too much clients each blocking a connection, you will end up failing some of your requests. It also adds a configurable logging experience (via ILogger) for all requests sent through. All in all, it makes a developer’s life easier and allows you to do some smart stuff too.

Does it work? Yes it does! The response was correctly mapped into my class and I can return it.

Do you wonder what was logged when making this request? Let’s have a quick look.

As I mentioned earlier IHttpClientFactory also provides a logging mechanism, so that every request is logged. Here you can see that not only address was logged, but also HTTP method and time of execution. This can be pretty useful for debugging.

Adding a retry mechanism

In a micro-services world, every micro-service can have a bad day once in a while. Therefore, we need to have a retry mechanism for services we call and we know that they fail from time to time. In ASP.NET Core for .NET 5 there is a third-party library integrated just that purpose – it’s Polly. Polly is a comprehensive resilience and transient fault-handling library for .NET. It allows developers to express policies such as Retry, Circuit Breaker, Timeout, Bulkhead Isolation, and Fallback in a fluent and thread-safe manner.

For our scenario let’s add a retry mechanism, that will call WeatherStack service and retry 3 times after an initial failure. With Polly, a number of retries and delays between then can be easily set. Let’s have a look at the example – it’s in the Startup method where we configure DI container.

services.AddHttpClient<IWeatherStackClient, WeatherStackClient>()
        .AddTransientHttpErrorPolicy(
            p => p.WaitAndRetryAsync(new[]
            {
                TimeSpan.FromSeconds(1),
                TimeSpan.FromSeconds(5),
                TimeSpan.FromSeconds(10)
            }));

With this code we will retry the same request after 1, 5, and 10 seconds delay. There is no additional code needed. Polly will do everything for us. We will see logs that something failed, only after all retries will fail, we will get the exception.

Adding a cancellation token

A cancellation token is a mechanism that can stop the execution of an async call. Let’s say that our request shouldn’t take more than 3 seconds, because if it does, we know that something isn’t right and there is no point to wait.

To implement that we need to create a cancellation token and provide that when making a call with an HTTP client.

public async Task<WeatherStackResponse> GetCurrentWeatherWithAuth(string city)
    {
        try
        {
            using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(3));

            using var responseStream = await _client.GetStreamAsync(GetWeatherStackUrl(city), cancellationTokenSource.Token);
            var currentForecast = await JsonSerializer.DeserializeAsync<WeatherStackResponse>(responseStream);

            return currentForecast;
        }
        catch (TaskCanceledException ec)
        {
            _logger.LogError(ec, $"Call to WeatherStack.com took longer then 3 seconds and had timed out ");
            return null;
        }
        catch (Exception e)
        {
            _logger.LogError(e, $"Something went wrong when calling WeatherStack.com");
            return null;
        }
    }

If the request takes too long, we will receive a TaskCancelledException, which we can catch and react to it differently, that when getting unexpected exception.

Provide authorization

Basic authorization is definitely the simplest and one of the most popular ones used. The idea is that every request to the specific service needs to be authorized, so that along with our content, we need to send authorization info. With basic authorization, we need to pass a user and password encoded as base64 string and put in a request header. Let’s see how that can be accomplished. 

private const string ApiKey = "3a1223ae4a4e14277e657f6729cfbdef";
    private const string Username = "Mik";
    private const string Password = "****";

    public WeatherStackClient(HttpClient client, ILogger<WeatherStackClient> logger)
    {
        _client = client;
        _logger = logger;

        var authToken = Encoding.ASCII.GetBytes($"{Username}:{Password}");
        _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
            "Basic",
            Convert.ToBase64String(authToken));
    }

In this way every call from WeatherStackClient will have authorization info and we do not need to add anything when we make requests. The only place we need to put additional code is a constructor.

Note that authorization is not needed to call weatherstack.com and is added only to show how it can be done.

This article did not cover all of the possibilities of IHttpClientFactory so if you want to know more, just go to this Microsoft article.

Hope you like this post, all code posted in this article is available at my GitHub account:

https://github.com/mikuam/PrimeHotel

 

22 May 05:45

Nhibernate QuerySyntaxException is not mapped from

by Benjamin Perkins
An important step which is often overlooked when beginning the process of mapping your database is to set the Build Action to Embedded Resource. (Buildvorgang – Eingebettete Resource). If you forget to do this you may receive a QuerySynataxException stating that the … is not mapped [from …]. It is also possible to store the […]
06 May 17:57

Article: Understanding Classic Java Garbage Collection

by Ben Evans

Java Garbage Collection remains a topic of major interest even after 25 years. Many developers are still confused about the fundamentals of the topic, even of the most widely-used implementation (Parallel on Java 8).

By Ben Evans
04 May 18:23

How JavaScript Works: Web APIs, Callback Queue, and Event Loop

by Bipin Rajbhar

Hello everyone 👋, I hope you are doing great.

So, In the previous article, we learned about Google's V8 Engine, Heap Memory, and Call Stack.

In this article, we will learn about Web APIs, Callback Queue, and Event Loop.

🌐 Web APIs

The Web APIs are provided by the web browser that gives additional functionality to the V8 engine.

The Web API calls are added to the Web API Container from the Call Stack. These Web API calls remain inside the Web API Container until an action is triggered. The action could be a click event or HTTP request, or a timer finishes its set time. Once an action is triggered, a callback function is added to the Callback Queue.

🧑‍🤝‍🧑 Callback Queue

The Callback Queue is a FIFO data structure.

The Callback Queue stores all the callback functions in the order in which they are added.

♻️ Event Loop

What happens when you have function calls that take a large amount of time to execute in the Call Stack?

For example

  • Executing a for loop from 1 to 10B
  • Making a network request
  • Doing image processing

Let's take an example.

Synchronous Code Visualization
blocking

You may ask why this is a problem? The problem is when the Call Stack has a function to execute, the browser cannot do anything else because it is blocked.

The solution is an asynchronous callback, promises, and async / await.

Let's take an example.

Asynchronous Code Visualization
blocking

The Event Loop has only one simple job to do. It looks at the Call Stack and Callback Queue, if the Call Stack is empty, it pushes the first callback function of the Callback Queue to the Call Stack..

I hope now you have a good understanding of how JavaScript works.

In the next article, we will learn how V8 compiles our JavaScript code.

📚 Resources

What the heck is the event loop anyway? | Philip Roberts | JSConf EU

Thanks for reading! My name is Bipin Rajbhar; I love helping people to learn new skills 😊. You can follow me on Twitter if you’d like to be notified about new articles and resources.

24 Apr 18:42

Rust 1.43 stabilizes six APIs and adds minor changes

Rust 1.43 has been released according to schedule. The latest version of the multi-paradigm programming language is a minor release, but that doesn’t mean nothing has happened. Let’s take a look at the stabilized APIs and language changes that this version has on board.

The post Rust 1.43 stabilizes six APIs and adds minor changes appeared first on JAXenter.

05 Apr 06:32

Object Destructuring In JavaScript

by Shivangi Rajde
Object destructuring in JavaScript is an expression that lets us extract values objects and arrays. Learn how to use object destructuring in JavaScript.
05 Nov 14:39

Migrationen splittrar Texas

by Frida Wallnor
Precis som i det svenska valet har migrationsfrågan spelat en viktig roll i upptakten till tisdagens mellanårsval i USA. I Texas, vid den mexikanska gränsen, är frågan extra känslig och bidrar till att fler går och röstar.  Di har i valspurten besökt jättestaden Houston. 
19 Aug 00:29

100 kvinnor undsatta på bordell i Mexiko

14 Aug 18:19

"Fortnite"-stjärnan ratar kvinnliga spelare

06 Jul 15:57

Beskow lämnar Swedbank – går till DNB

by Nyhetsbyrån Direkt
Elisabeth Beskow lämnar Swedbank för chefsbefattningar på DNB. Hon blir ny chef för DNB i Nordeuropa och chef för den svenska rörelsen med cirka 400 anställda. Det framgår av ett pressmeddelande.
13 Apr 17:51

Misstänkt mord i Järfälla – en gripen

11 Sep 03:02

Därför vinner den alternativa högern

by widarnord
07 Jul 19:15

NVIDIA GeForce GTX 1060 6GB Video Card Coming For $249 on July 19th

by Nathan Kirsch

The NVIDIA GeForce GTX 1060 will be coming on July 19th for as little as $249 from board partners and will feature GeForce GTX 980-level performance! NVIDIA will also be releasing a special limited GeForce GTX 1060 Founders Edition, basically the reference model, that will be available only directly from NVIDIA for $299. The NVIDIA ...more

The post NVIDIA GeForce GTX 1060 6GB Video Card Coming For $249 on July 19th appeared first on Legit Reviews.

21 Jun 16:22

Hela VW-ledningen anmäld för att ha manipulerat aktiekursen


VW-härvan utvidgar sig. På måndagen stod det klart att en förundersökning inletts mot förre koncernchefen Martin Winterkorn och ytterligare en medlem i den tidigare koncernledningen. På tisdagen kom avslöjandet att den tyska finansinspektionen anmält hela koncernledningen för att ha manipulerat kursen i samband med avgasskandalen.
28 Sep 07:18

Why does the state exist?

What does a state do? For instance, in the Philippines, before they were to host the executive committee meeting of the Asian Development Bank, to keep the visiting foreigners from seeing the country’s poverty, erected a temporary wall to hide the slums on the road from the airport to the city
24 Apr 15:35

Man avrättade sin dator med åtta skott - "Jag ångrar ingenting"


Efter en blåskärm för mycket fick Lucas Hinch nog och sköt inte mindre än åtta skott i sin Dell.
11 Dec 00:16

Hamas in Turkey on alert after Israeli complaint

by Adnan Abu Amer
Hamas officials in Turkey are taking precautions after Israel’s complaint to NATO against Ankara for hosting the Palestinian Islamist group, fearing that Israel might resume assassinating its leaders abroad.
06 Oct 06:56

Uzbeker tvingas åter plocka bomull

I sedvanlig ordning tvingas delar av Uzbekistans 30 miljoner invånare ut på landets bomullsfält för att - ofta oavlönat - hjälpa till med höstskörden.