teleren/devto huggingface dataset:
Converting Binary Strings to English Sentences using JavaScript
Tags: codenewbie, javascript, webdev, algorithms
Published: 2023-05-19 12:00:34

### Introduction:

In this article, we'll explore a JavaScript solution that takes a binary string with each binary number separated by a space and transforms it into its corresponding sentence. 

We'll
1. discuss the problem,
2. outline an approach,
3. present a step-by-step solution, and provide example code.

### Understanding the Problem:

The task at hand is to convert a binary string, where each binary number is separated by a space, into its corresponding English sentence. For example, the binary string "01000001 01110010 01100101" should be transformed into the sentence "Are".

### My approach for solving this problem:

> 1- Define the `binaryAgent` function, which takes the binary string as an argument.

> 2- Split the binary string into an array of binary numbers using the `split` method with a space as the separator. This gives us an array of binary numbers.

> 3- Use `map` method and inside the map function, convert each binary number to its corresponding character using `String.fromCharCode()` and `parseInt(binary, 2)`. The parseInt function converts the binary string to its decimal representation.

> 4- Finally, join the resulting array of characters using the `join `method to form the sentence.

### My solution:

```js
function binaryAgent(str) {
  const binaryArray = str.split(" ");

  const sentence = binaryArray
    .map((binary) => String.fromCharCode(parseInt(binary, 2)))
    .join("");

  return sentence;
}

const binaryString = "01000001 01110010 01100101 01101110 
01110100 00100000 01100010 01101111 01101110 01100110 
01101001 01110010 01100101 01110011 00100000 01100110 
01110101 01101110 00100001 00111111";
const result = binaryAgent(binaryString);

console.log(result); // Output: "Are you bonfires fun!?"
```

>  If you have any questions or feedback, please feel free to share them in the comments. Thanks for being here!

### About the Author:

[Muhammad Awd](https://www.linkedin.com/in/muhmmadawd) is a passionate JavaScript developer with expertise in problem-solving and web development. He has a strong track record of delivering high-quality projects and enjoys tackling challenging coding puzzles. You can explore more of Muhammad's work and connect with him on his [LinkedIn](https://www.linkedin.com/in/muhmmadawd) and [GitHub](https://github.com/MuhmmadAwd).

### Get in Touch:
If you have any JavaScript development opportunities, project collaborations, or would like to discuss any tech-related topics, feel free to reach out at [muhmmad.awd@gmail.com](mailto:muhmmad.awd@gmail.com). looks forward to hearing from you and exploring potential collaborations.
How to Solve CORS Origin Issue in Asp.Net Core Web API
Tags: webdev, programming, aspnetcore, javascript
Published: 2023-05-19 11:42:00

To solve the CORS (Cross-Origin Resource Sharing) issue in ASP.NET Core Web API, you can follow these steps:

### Step 1: Install the required NuGet packages
Make sure you have the following NuGet packages installed in your ASP.NET Core Web API project:

**Microsoft.AspNetCore.Cors**: This package provides CORS middleware to enable Cross-Origin Resource Sharing.

You can install the package using the Package Manager Console or NuGet Package Manager in Visual Studio.

### Step 2: Configure CORS in your ASP.NET Core Web API project

In the `Startup.cs` file, locate the `ConfigureServices` method and add the following code to enable CORS:

```
public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("CorsPolicy", builder =>
        {
            builder.AllowAnyOrigin()
                   .AllowAnyMethod()
                   .AllowAnyHeader();
        });
    });
    
    // Other service configurations
}

```
In the code above, `AddCors` adds CORS services to the dependency injection container, and `AddPolicy` defines a CORS policy named "CorsPolicy". The policy is configured to allow any origin, method, and header. You can modify these settings to meet your specific requirements.

### Step 3: Enable CORS in the request pipeline
In the `Configure` method of the `Startup.cs` file, add the following code to enable CORS in the request pipeline:

```
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // Other configuration settings
    
    app.UseCors("CorsPolicy");
    
    // Other middleware configurations
}

```
The `UseCors` method configures the CORS middleware to use the policy named "CorsPolicy" defined earlier.

### Step 4: Testing CORS
Now you should be able to make cross-origin requests to your ASP.NET Core Web API. The API should include the appropriate CORS headers in the response, allowing requests from different origins.

It's important to note that allowing any origin (`AllowAnyOrigin()`) may not be suitable for production environments. You should consider limiting the origins, methods, and headers based on your specific requirements.

By Following these steps you can solve the CORS Origin Issue
My 2 most frequently used SVG features
Tags: webdev, svg
Published: 2023-05-19 11:29:44

I use editors like Figma or Sketch to edit and export SVG. But there are two SVG features I find myself adding to the exported SVG markup quite often.

## 1. Stretch SVG with `preserveAspectRatio="none"`

Unlike rasterized images (like PNG or JPG) SVG graphics won’t be stretched when setting height and width in HTML or CSS. Instead the graphic will be resized to fit inside the set dimensions while keeping its original aspect ratio.

This behavior can be changed however by setting `preserveAspectRatio` like so:  

```xml
<svg preserveAspectRatio="none" viewBox="0 0 42 42" …>
```

> Note: The `viewBox` attribute must be defined in order for this to work. When exporting from an editor this is usually done for you. Without a view box the contents of a SVG graphic will always render in the same size on your screen. 

<figure>
  <img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h9649a51qbvqklxe8ntb.png">
  <figcaption>Default behavior</figcaption>
</figure>

---

<figure>
  <img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2ckk19rouz3bbimz50e6.png">
  <figcaption>With `preserveAspectRatio="none"`</figcaption>
</figure>

While `none` is the only value I ever needed, there are more options available:
https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/preserveAspectRatio

## 2. Consistent stroke width with <br>`non-scaling-stroke`

This feature can be very useful if you need a consistent line width between multiple images and/or CSS borders for example.

Just add the value `non-scaling-stroke` to the `vector-effect` attribute of an SVG element and the stroke will always render with the same stroke width, no matter how you scale it.

```xml
<svg …>
<path vector-effect="non-scaling-stroke" stroke-width="2" …/>
<circle vector-effect="non-scaling-stroke" stroke-width="2" …/>
</svg>
```
&nbsp;

<figure>
  <img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fr17ibegxal1sdaw8h8o.png">
  <figcaption>Default behavior</figcaption>
</figure>

---

<figure>
  <img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h1p9immg7cjtgxnw2onu.png">
  <figcaption>`vector-effect="non-scaling-stroke"`</figcaption>
</figure>

More about the `vector-effect` attribute: https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/vector-effect

## Do you want more?

Here is another article of mine about using `currentColor` to set the SVG's color in CSS: [Import SVGs as React component and set color in CSS with currentColor](https://dev.to/receter/so-easy-svg-with-currentcolor-in-create-react-app-1aid)

---
I hope this was worth reading for you. Did you ever use one of these features? Is there some other SVG feature that you find particularly useful?
What is Circular Dependency in Microsoft Asp.net Core Web API
Tags: azure, webdev, aspnet, javascript
Published: 2023-05-19 11:28:03

When two or more components in your application are dependent on each other either directly or indirectly, ASP.NET Core Web API refers to this as a circular dependency. This results in a cycle of dependencies. When two classes or components share references, it might result in a circular chain of dependencies.

_**Circular dependencies can cause several problems, including:**_

### Compilation errors:
A circular dependency causes the compiler to be unable to resolve the references, leading to compilation failures.

### Runtime errors:
Circular dependencies can result in runtime issues like stack overflows and infinite loops even if the code correctly compiles, which will make your application unstable or unusable.

### Code maintenance difficulties: 
Circular dependencies make it more challenging to comprehend and manage the source. It becomes difficult to pinpoint the cause of problems, and altering one component accidentally can have unintended effects on other components.

_**To avoid circular dependencies in your ASP.NET Core Web API application, it is important to follow good architectural practices and design principles. Here are some tips to help you prevent circular dependencies:**_

### Dependency Inversion Principle (DIP): 
Utilize the Dependency Inversion Principle, which contends that high-level modules ought to rely on abstractions rather than low-level modules directly. By reducing the likelihood of circular dependencies, this notion aids in the decoupling of components.

### Dependency Injection (DI): 
Component dependencies can be managed with dependency injection. You can prevent tight coupling and circular dependencies by injecting dependencies into a class rather than explicitly constructing them.

### Modularization: 
Divide your application into more manageable, modular parts. Each component should have a distinct role to play and shouldn't rely on other unrelated components. This lessens the possibility of circular dependencies.

### Analyze and refactor: 
Check your codebase for circular dependencies on a regular basis. Use programs or IDE plugins that can assist you in automatically identifying circular dependencies. Refactor your code to stop the cycle when you find a circular dependency. This could entail removing interfaces, adding intermediary layers, or reevaluating the architecture.

You can reduce the incidence of circular dependencies in your ASP.NET Core Web API application by putting these strategies into practice and upholding a distinct separation of concerns, leading to a more robust and manageable codebase.
Level Up Your Coding Skill: Join PhishGuard, the Revolutionary Open-Source Game!
Tags: phishguard, opensource, cybersecurity, github
Published: 2023-05-19 11:24:26

🎮 Calling all Cyber Coding enthusiasts! Join PhishGuard! 🔒

PhishGuard is an open-source cyber awareness game designed to educate users about phishing attacks and online security threats. As a contributor to PhishGuard, you can make a real impact in the fight against cybercrime while enhancing your skills and collaborating with a passionate community.

Join us now! 🌟

🔧 Developers: Contribute code, implement new features, and optimize performance using HTML, CSS, and JavaScript.

🎨 Designers: Create engaging game assets and UI designs to enhance the player experience.

💡 Content Creators: Craft educational dialogues and design realistic phishing scenarios to provide an authentic learning experience.

📢 Marketers and Community Managers: Help us spread the word and grow our community on social media.

Ready to make a difference? Visit our GitHub - https://github.com/iammuhammedfuhad/PhishGuard 🌐

Let's level up cyber awareness with PhishGuard! 🎮🔒
Ultimate Guide to Cloud Cost Optimisation for VM Services
Tags: virtualmachine, cloudcost, cloudoptimisation, cloud
Published: 2023-05-19 11:18:47

In today’s cloud-driven landscape, businesses across various industries use virtual machine (VM) services from major cloud providers like **AWS EC2, Azure VM, and GCP Compute Engine** to leverage their power and flexibility. These services provide the foundational infrastructure for running diverse workloads and applications in the cloud. However, to get the most out of these services, organisations must prioritise cost optimisation.

This blog post will provide you with a comprehensive checklist to ensure maximum cost savings on VM services. This guide will equip you with the essential knowledge to optimise your VM costs effectively.


**1. Identifying Underutilised VMs**
Utilise AWS CloudWatch, Azure Monitor and GCP Compute Engine Monitor to analyse performance metrics and usage patterns, enabling cost optimisation through downsizing or terminating underutilised VMs.

**2. Deleting Unused VMs - Eliminating Wasteful Expenses**
Regularly assess and decommission unnecessary VMs to minimise wasteful expenses and optimise cost efficiency.

**3. Leveraging Reservations - Cost Savings for Long-Term Workloads**
Maximise cost savings by identifying suitable workloads and implementing effective reservation strategies for long-term usage.

**4. Spot Instances**
Explore Spot Instances (AWS), Spot VMs (Azure), and Preemptible VMs (GCP) to identify non-critical workloads and strategically leverage them for optimised cost savings.

**5. Optimising Storage Costs - Tackling Unattached Volumes**
Unattached volumes can significantly impact costs. Efficiently review and manage storage volumes, removing or detaching unattached ones to reduce expenses.

**6. Minimising Idle Costs - Maximising IP Address Efficiency**
Understanding the cost implications of unattached IP addresses and actively managing their allocation to optimise costs. Regularly reviewing and releasing unattached IPs ensures efficient utilisation of resources.

**7. Opting for Burstable VMs - Efficiently Handling Workload Spikes**
Introducing burstable instances like AWS T3 and Azure B-series for optimised performance and cost balance during workload fluctuations.

**8. Scheduling Dev/Non-Prod Instances - Optimising Usage and Costs**
Maximise efficiency in dev/non-production environments by scheduling instances during active periods and reducing costs by pausing or shutting down instances during idle periods.

**9. Rightsizing Your VMs - Matching Workloads, Saving Costs**
Evaluate resource requirements, identify over provisioned instances, and optimise VM sizes to align with workload demands, resulting in cost savings.

**10. Auto Scaling**
Maximise resource utilisation and cost efficiency by leveraging AWS Auto Scaling Groups for automated, demand-based scaling.


By implementing these strategies, organisations can achieve substantial cost savings and optimise their cloud investments. Start implementing these best practices today and take control of your VM costs for a more efficient and cost-effective.
Continious Delivery Bootcamp: Continuous Integration
Tags: programming, productivity, devops, development
Published: 2023-05-19 10:58:42

# Context

Welcome to our Continuous Delivery Bootcamp! We'll teach you the skills you need to get your projects out the door fast, without sacrificing quality. By the end of this program, you'll be a pro at transforming code into working software. Sign up today and start transforming your workflow! 

This chapter we will do an example on how to build and validate our project in github actions.

# Video

<iframe width="100%" height="444" src="https://www.youtube.com/embed/QMwXxezykHc" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

{% embed https://youtu.be/QMwXxezykHc %}

[﻿Watch the video on Youtube](https://youtu.be/QMwXxezykHc)
Automate VM Creation Using Vagrant
Tags: vagrant, devops, vm
Published: 2023-05-19 10:35:26

Creating and Managing VMs manually on platforms such as Virtual box and Vmware workstation can be time consuming, especially when handling multiple VMs at the same time where speed and consistency is required. Automating VM creations using tools like Vagrant makes this process easier and seamless.
In this tutorial, I will be showing you how to set up and create a CentOS7 operating system in your Windows machine with Virtual box and vagrant in minutes!

First, the Prerequisites:

- Ensure you have chocolatey installed on your windows machine. You can install [here](https://chocolatey.org/install)
- Also, install Virtual Box software on your windows system.
- Install git bash. This will allow us to run Linux commands on our windows system.

Step 1: With Chocolatey installed, we can easily download Vagrant into our system. Open up powershell with administrative privilege, and run the following command:

![Vagrant download command](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/54pfwye0klfrpjtg7ifr.png)

Step 2: Once Vagrant is installed, Create a directory where your VM will be setup in git bash. Vagrant cloud provides a list of different vagrant boxes. Each box includes an operating system at its base to set up a working environment, while other specialised boxes will have configurations like Laravel, Lamp stacks, Ruby etc already provided. Search for “CentOS7” and select a box with that name. Ensure that the box supports the provider (Virtual box, vmware, hyperv, etc)  you are using.

Step 3: In git bash, we will initialise the box

![Vagrant Box Initialisation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/csi76cydzibmx8u0v0xz.png)

Step 4: Once the box has been initialised, a Vagrantfile that contains the configuration of the centos 7 operating system will be added to our directory. You can also modify the configurations as needed.

![Vagrantfile configuration](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6p50wa4jzj8zj18vyqbw.png)

Step 5: Once the configurations are good to go, bring up the operating system with vagrant using “vagrant up” command

![Vagrant creation command](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gjzriw0p6k1zgs4jwh3r.png)
Here, your Vm is up and running as can be seen on Virtual box:

![Virtual Box](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6g10c6fjytp3qr9g7i0f.png)
Step 6: Using “Vagrant ssh”, we will be able to access and interact with the centos 7 machine

![Vagrant SSH](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tlef8ibb4zqwe6unxxde.png)

You can also use “Vagrant halt” to pause the CentOS VM when not in use and “vagrant destroy” to delete the VM completely.

So there you have it, Techies😎. You can create VMs automatically in minutes with Vagrant🎊.
Thanks for reading! Please leave a comment.
Copy SSH key to Clipboard
Tags: ssh
Published: 2023-05-19 10:28:54

This is a short guide on how to copy your ssh key to the clipboard.

Mac
```
pbcopy < ~/.ssh/id_rsa.pub
```
Linux (Ubuntu, Debian)
```
cat ~/.ssh/id_rsa.pub
```
Windows (Git Bash)
```
clip < ~/.ssh/id_rsa.pub
```
Revise or learn basic programming in few minutes
Tags: beginners, productivity, codenewbie, development
Published: 2023-05-19 10:16:04

It happens so much times as a lazy developer , you stop coding for a while and when you come back and you have to revise the basics because you don't believe in yourself. I am with you on that one and then you end up reading documentation which is too much or watch a Youtube video which does nothing but overwhelm you. 

So I recently stumbled around a website that helps user revise or get familiar with any coding languages basics in just several minutes. This website also helps you to get a good understanding on documentation and covers almost everything you should know before you can jump on building projects. 

[learnxinyminutes](https://learnxinyminutes.com/)
🔍 Azure CLI. How to Simplify Output.
Tags: azure, azurecli, devops, bash
Published: 2023-05-19 09:38:43

---
title: 🔍 Azure CLI. How to Simplify Output.
published: true
description: 
tags: #Azure #AzureCLI #DevOps #bash
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2023-05-19 09:28 +0000
---


If you need to extract specific information from the output of an Azure CLI command you can use the `--query` that will do it for you.

Let's say you want to save a `deployement key` of the Azure Static Web App in a Bash variable for later use in your CI/CD pipeline. When you run the command:

```bash
az staticwebappsecrets list -g rg-name -n static-web-app-name --query
```

The output will be in JSON format:

```json
{
  "id": "some id",
  "kind": null,
  "location": "West Europe",
  "name": "secrets",
  "properties": {
    "apiKey": "cool key"
  },
  "resourceGroup": "rg-name",
  "type": "Microsoft.Web/staticSites/secrets"
}
```

But you only need the `apiKey` value. That's where the `--query` parameter comes in play. Simply add it to your command:

```bash
az staticwebappsecrets list -g rg-name -n static-web-app-name --query 'properties.apiKey'
```

Now, you can save only the key in a Bash variable:

```bash
DEPLOYMENT_TOKEN=$(az staticwebappsecrets list -g rg-name -n static-web-app-name --query 'properties.apiKey')
```

To remove the surrounding quotes, use the following step:

```bash
DEPLOYMENT_TOKEN=${DEPLOYMENT_TOKEN//\"/}
```

And here you go! You have extracted the key and it is ready to use in your CI/CD pipeline.

Full documentation is here: https://learn.microsoft.com/en-us/cli/azure/query-azure-cli
Is this how you test Node cron jobs?
Tags: node, jest, javascript
Published: 2023-05-19 09:14:57

I have a node cron job in my application that looks something like this:

```

const taskOne = (time) => {
   const loadData = schedule(time , ()=>{

}
loadData.start();

}

taskOne("23 04 * * 0-6")
```

**The way I wrote it this was because the same logic runs two times in a day so did not want to write the logic again.
**

**The way I am trying to test is:**

```
describe("cron jobs", () => {
    let year, month, day;
    beforeAll(() => {
      const date = new Date();
      year = date.getFullYear();
      month = String(date.getMonth()).padStart(2, "0");
      day = String(date.getDate()).padStart(2, "0");
    });

    it("run taskOne node cron job", async () => {
      const currentHour = new Date().getHours();
      let currentMinutes = String(new Date().getMinutes()).padStart(2, "0");
      if (currentMinutes == `60`) currentMinutes = `01`;
      taskOne(`${currentMinutes} ${currentHour} * * 0-6`);
      setTimeout(() => {
        //expect statements
        done();
      }, 300000);
    });
```

The above test passes but these cron jobs take a long time to finish (could be 30 -60 minutes) so it is getting difficult to decide when should I do the assertions using expect statement. Currently I am doing it after a wait for 5 minutes to verify some of the tasks that usually completes within that time. 

Another issue is how to stop these cron jobs after I do my assertions otherwise jest throws below warnings:Jest did not exit one second after the test run has completed.

'This usually means that there are asynchronous operations that weren't stopped in your tests.'