teleren/devto huggingface dataset:
Hacktoberfest Progress
Tags: github, opensource, hacktoberfest, javascript
Published: 2023-10-31 16:50:24

As Hactoberfest comes to a close, I have a few irons in the fire which I'm hoping to bring some closure to. The issue in progress that is most likely to be wrapped up neatly is a code contribution to [regex-pro](https://github.com/hammadsaedi/regex-pro). It is a simple Javascript site that offers some tools and templates for processing regular expressions.  

[Issue-6](https://github.com/hammadsaedi/regex-pro/issues/6) was my initial attempt to contribute to the project.  It asked to provide support for the entry and extraction of phone numbers via regex.  While not a massive undertaking, it did require some back and forth to make sure the regex I was providing met the expectations of the project.

Extracting phone numbers via regex proved to be an interesting task as there can be a variety of formats received as input and the regex needs to do some work in determining the input formating and imposing some constraints on the output options.  In this case I initially wasn't clear on which of the various options was prefered for the project.  
Initially I provided the following solution:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vqvidk8azfq4f2ifsycm.png)
With some feedback from the owner I realized I needed to use the `+` symbol as a qualifier to whether the input should be looking for 12-13 subsequent digits (international number) as opposed to 10 digits (local).  
I implemented these changes to make that qualification:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l6069oe32i3dy4e7jjnr.png)

This proved a good opportunity to make add some code and submit a draft Pull Request to get some feedback.  I was able to get some feedback from the owners and in turn update my changes and push them to the same PR for review.  This was a first and was helpful to see my options in terms of pushing either new commits or amending the exisiting commit with updates.

Those updates to [PR32](https://github.com/hammadsaedi/regex-pro/pull/32) are now in review and I hope to see some further feedback or a merge shortly.  

This project seems to be in a fairly early stage but looks to be an actively growing project with some additional issues that appeal to me.  I have requested to contribute to some additional issues that provides a bit more challenge in terms of the contribution.
Maximizing Efficiency with Cloudflare's AI Gateway
Tags: ai, workers, cloudflare
Published: 2023-10-31 16:33:01

---
title: Maximizing Efficiency with Cloudflare's AI Gateway
published: true
description: Preventing Abuse and Saving Bucks: The Dual Advantage of Cloudflare AI Gateway
tags: ai, workers, cloudflare
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kg5fd2yzv04fua6hb0uo.jpg
# published_at: 2023-10-31 14:23 +0000
---

In the contemporary realm of AI applications, efficiency and control are paramount. [Cloudflare's AI Gateway](https://developers.cloudflare.com/ai-gateway/) emerges as a game-changer, offering remarkable advantages: observability, caching and rate-limiting.

The cost-saving aspect is excellent, serving requests directly from Cloudflare's cache rather than the original model provider (if cached). Additionally, the in-built rate limiting feature is a robust measure against potential abuse, ensuring your application scales gracefully without being overwhelmed by excessive requests ​and burning your wallet.

I use it to interact with OpenAI API, but this Gateway also supports [Cloudflare Workers AI](https://ai.cloudflare.com/), Azure OpenAI, HuggingFace and [Replicate](https://replicate.com/). In addition, there is a [Universal Endpoint](https://developers.cloudflare.com/ai-gateway/providers/universal/) that helps you set up a fallback provider when a request fails.

## The Power of Caching

![Dashboard of cost and caching](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/07g281z1qcl7waynnlf1.jpg)

Caching can be set from one minute to one year, and in my case, it caches from `text-embeddings` to `gpt-3.5`. In the above screenshot of a non-production app, the savings were 50% instead of calling OpenAI directly, plus faster response speeds.

## Rate-limit your Wallet

Every time you release your App into production, you question if some bad actor will run you to the ground. The Rate-limit feature will enable you to control the frequency and volume of requests made to your app, thereby avoiding any unnecessary charges or misuse of resources. Rate-limit from 1 minute to 1 hour period, fixed or sliding.

## Observability

In the case of OpenAI API, observability is very limited. The Real-time logs feature on the Gateway is bliss. You can turn it on or off as you like.

## Getting Started

Visit [Cloudflare's AI Gateway Docs](https://developers.cloudflare.com/ai-gateway/) and if you use [OpenAI NPM Package](https://www.npmjs.com/package/openai) is a easy as setting up `baseURL`.


```javascript
import OpenAI from 'openai';

const openai = new OpenAI({
	apiKey: 'my api key', // defaults to process.env["OPENAI_API_KEY"]
	baseURL: "https://gateway.ai.cloudflare.com/v1/ACCOUNT_TAG/GATEWAY/openai"
});
```
Promise APIs with Example🤝
Tags: javascript, promise, webdev, beginners
Published: 2023-10-31 16:32:38

_We know that promise is a special JavaScript object. It is a placeholder for a value which can be either fulfilled or rejected._

In this we will discuss how we can handle multiple promises.

**1.** **Promises.all**  - It is used to handle multiple promises together. It takes array of promises as an input.

_NOTE : You can take any iterable as input but as of now we are considering only array._

Example: _promises.all([p1,p2,p3])_ , where p1,p2,p3 are three different promises.
Suppose p1 takes 3sec , p2 takes 1sec and p3 takes 2sec time to complete.

case 1 :  If all of three promises are fulfilled/success/resolve then output will be array of resolve value of all the three individual promises.

output : [val1,val2,val3]
          where (val1,val2,val3 are object)

When the code executed, all the three promises will run parallelly but wait for all to finish. In our example , after 3sec output will be generated as p1 takes maximum time(3sec).

Case 2 : If any or all of the promises get rejected.

When code is executed and all promises run parallelly and as soon as any of promises get rejected, error will be thrown. The error will be same as error of that particular promise.

Suppose p2 get rejected while p1, p3 get resolved in the above example, then error will be thrown immediately after p2 is executed i.e. after 1sec.

**2. Promise.allSettled** 

We have seen that if any of the promises get rejected then error is thrown, if we want result of other two promises whichever are resolved then we can use promise.allSettled

Example: _promise.allSettled([p1,p2,p3])_ , where p1,p2,p3 are three different promises.
Suppose p1 takes 3sec , p2 takes 1sec and p3 takes 2sec time to complete.

case 1 : If all promises get resolve then output will be array of resolve value of promise.

case2 : If any of promise get rejected.

Suppose p2 fails/rejected and p1, p3 get resolved then output will be array of return value of each promises. It doesn't matter if return value is error or success and it will wait for all the promises to settle.

_NOTE : Promise.all is like fast failing and Promise.allSettled wait for settling promise then give result accordingly._

**3. Promise.race**

In this whichever promise get settled first, whether it is resolved or rejected, output is given accordingly. It doesn't wait for other promises to settle.

**4. Promise.any**

It is same as promise.race but the difference is that it will wait for first fullfilled/resolved/success promise result and then output is produced.

If all of the promises fails/rejected then output will be aggregate error.
Calling all developers! AML Watcher Launch Update!!!
Published: 2023-10-31 16:24:55

I'm thrilled to introduce AML Watcher, your ultimate solution for seamless AML compliance. Designed with developers in mind, AML Watcher offers effortless API integration and on-premises capabilities, streamlining your compliance processes. 

I would love it if you could take a moment to explore AML Watcher, show your support, and share your valuable insights by leaving a review.
[https://www.producthunt.com/posts/aml-watcher 
]
Encrypting Sensitive Information using Laravel Database Encryption Package
Tags: laravel, database, encryption
Published: 2023-10-31 16:15:42

**Introduction**

In this guide, we are going to learn how to encrypt our databases in our Laravel application to protect data. Developers sometimes consider encryption an afterthought but it is essential that encryption techniques are considered in the early stage of development especially when dealing with sensitive user data.

**Requirements**

Laravel: Laravel is a web application framework with expressive, elegant syntax. Supported versions > 5.x.x. The version used in this guide is Laravel 8.

Laravel Database Encryption Package: This is a package from Elgiborsolution for encrypting and decrypting model attributes for Laravel using OpenSSL. The package is simple and easy to use. All you need to to specify the fields/attributes you want to encrypt and "voila" the work is done.  The package uses the encryption key in your .env.

**Tutorial**

1. 
Install the package via composer using the command line

`$ composer require elgibor-solution/laravel-database-encryption
`

2. 
To encrypt a field of data use the EncryptedAttribute trait in the model where you want to apply the encryption. For example, if you want to encrypt the name_of_spouse, address_of_spouse and occupation_of_spouse attributes  in the Family model, you do the following:

```
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use ESolution\DBEncryption\Traits\EncryptedAttribute;

class Family extends Model
{

    use EncryptedAttribute;

    protected $encryptable = [
        'name_of_spouse','maiden_name_of_spouse','address_of_spouse'
    ];

}

```
This tells the package which properties are to be encrypted.

3. 
If you have an empty database and have not run migrations, you can run your database migrations and the columns are automatically encrypted.

4. 
If you already have data in your database you can encrypt it with the following artisan command. 

`php artisan encryptable:encryptModel 'App\Models\Family'
`
And that's how you protect user data by working with Laravel database encryption. 

**Other features **

To decrypt your database you use the following artisan command:

`php artisan encryptable:decryptModel 'App\Models\Family'
`
To decrypt a record in your controller you can use Encrypter method

```
use ESolution\DBEncryption\Encrypter;

class RecordsController extends Controller{

 public function index(){

            'name_of_spouse'=>Encrypter::decrypt($family->name_of_spouse),

}

}

```
To learn more about the package read the documentation and give them a star on GitHub

https://github.com/elgiborsolution/laravel-database-encryption#laravel-database-encryption-package
Hacktoberfest 2023!!
Tags: hack23contributor, hacktoberfest23
Published: 2023-10-31 16:12:03

<!-- ✨This template is only meant to get your ideas going, so please feel free to write your own title, structure, and words! ✨ -->

### Intro
<!-- Share a bit about yourself as a contributor. Is this your first Hacktoberfest, or have you contributed to others? Feel free to embed your GitHub account by using {% embed LINK %} -->
Hello, this is my 4th hacktoberfest, I followed hacktoberfest from 2020 and from year to year it becomes more exciting to follow it.

### Highs and Lows
<!-- What were some of your biggest accomplishments or light-bulb moments this month? Did any problems come up that seemed impossible to fix? How did you adapt in those cases?  -->
By participating in hacktoberfest I learned how to contribute to open source projects and learned many new things about the project 

### Growth
<!-- What was your skillset before Hacktoberfest 2023 and how did it improve? Have your learning or career goals changed since working on these new projects? -->
Previously I didn't know about DDD architecture and at Hacktoberfest this time I contributed to the DDD Generator project for Laravel([Diamond Console](https://github.com/KoalaFacade/diamond-console)) and this added to my knowledge about architecture.
What are HTTP headers in a REST API?
Tags: javascript, webdev, beginners, node
Published: 2023-10-31 15:58:18


In a REST API, HTTP headers are often used to provide information about the request or response, such as the format of the data being sent or received and the type of authentication being used.

A request header is a key-value pair that provides information about the request context so that the server can tailor the response. 

***Some commonly used request headers are:***

**Content-Type**: This header specifies the format of the request or response body, such as application/json for JSON data or application/xml for XML data.

**Accept**: This header specifies the format of the data that the client is willing to receive in the response.

**Authorization**: This header is used to provide authentication credentials, such as an API key or a token. The specific format of the credentials will depend on the authentication scheme being used.

**Cache-Control**: This header is used to specify caching behavior for the response, such as whether the response can be cached and for how long.

**Content-Length**: This header indicates the number of bytes contained in the request or body.

So, one full example of request headers while sending the request looks like this:
``` bash
Content-Type: application/json
Accept application/json, application/xml
Authorization: Bearer YourAccessToken123
Cache-Control: max-age=86400
```

The above request headers tell the server that it's sending JSON data prefers JSON but can also accept XML, uses an access token for authorization, and allows caching the response for up to one day.

I hope you like this article and have understood the use of HTTP headers. If you enjoyed it, please like, comment, and follow for more cool stuff.

If you are on Twitter can you follow me there as well, I keep posted these kinds of stuff there as well => {% twitter 1718621312867016831 %}
From Idea to SaaS in 30 days, building Qiu
Tags: ruby, rails, saas
Published: 2023-10-31 15:56:48

Having been a Ruby developer for a decade, Rails was my go-to for building Qiu. It just made sense. Rails provided a treasure trove of tools right at my fingertips. No reinventing the wheel and allowed me to build [Qiu](https://qiu.so) from a concept to a live product in 30 days.

### Sensible Defaults

Rails comes with great feature from the start, like ActiveJob for background processing, has_secure_password for authentication, mailers for email handling, and ActiveStorage, were invaluable. This blog engine is written using ActionText! 🤯

> Convention over configuration is the way

### Ruby Gems

Ruby gems was what allowed us to stay productive when building Qiu. Here are some I consider great defaults.

- pay-rails - rapid integration of Stripe and other payment types
- good_job - what powers our background job, from queuing to sending
- nanoid, hashid - URL obsfucuration, allows us to create URLs with nicer slugs than incremental IDs
- discard - soft deletion, why code one when you could install one!
- bool_at - personal favorite (I made it), DSL for boolean statuses
- name_of_person - Easy first name, last name
- liquid - templating engine for dynamic data (we use this for our email parser)
- ahoy_matey, ahoy_captain - built-in Rails analytics


### Analytics

Special mention to Ahoy + Ahoy Captain. It allowed us to add custom tracking without any external requirement, and it is GDPR compliant.

![Ahoy Captain!](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/06nlo5578f3om2cke8j7.png)

And includes a beautiful UI for analytics tracking.

### Coding Convention

I did not follow the skinny model, nor service models very closely.

![Qiu API code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vufyvuu3j24q6mb0fx9w.png)

We deploy a mix of Rails callbacks and model methods to perform tasks.Instead of fighting Rails, we embrace class and instance methods than going immediately for a service class whenever we want to implement something. This allows us to avoid early code bloat and Service class hell early on while keeping code maintainable.

### Hosting

Using Render with Docker allowed Qiu to iterate quickly, changing code and deployment only takes 3 minutes.

![3 minute deploys](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tgo80l4v8lylbziq930a.png)

It allows us to quickly iterate, fix bugs or add features without worrying about deployment times.

### And with that

Is what allowed us to build Qiu from idea to MVP in 30 days using Ruby + Rails. Hope you enjoyed this article!

Also, if you want an easier way to send emails, try [Qiu](https://qiu.so).

[This article was originally posted in Qiu](https://qiu.so/blog/QkaUwN/from-idea-to-code-the-one-month-journey-of-qiu)
Job Opportunityt
Tags: programming, csharp, hdrp, nativegpuacceleration
Published: 2023-10-31 15:55:47

TAD, Technology Architecture Design, is a design consultancy with offices in NYC and London.

We are currently seeking a programmer to join us on a real-time generative content installation 
for an exciting ongoing project.  This work will be 40 hours per week, last for 2 months, starting December 1, 2023 and ending January 31, 2024.

If you have experience and work examples that demonstrate the below skills and are up for the challenge, please drop us a line at hr@TechnologyArchitectureDesign.com.

Fluency
1.	Unity HD Render Pipeline (HDRP)
2.	Native GPU acceleration (scripting experience) 
3.	CPU offloading & management 
4.	Experience with 3D textures
5.	Water mesh generation
6.	Understanding of DOP & OOP 
7.	C# chops
8.	Experience with entity component systems
9.	Experience in leveraging Network Manager (LAN mode)
10.	Experience with Git

Tasks
1.	Expand existing solution to enable a single machine deployment to a multi-machine coordinated display
2.	Optimize hardware utilization to load balance game performance 
3.	Improve GPU memory management to increase framerate
4.	Improve photorealism of environment
5.	Coordination of rendered elements across multiple devices
6.	Incorporate support for external API interaction (weather.com/ open weather)
Annotate Gem
Published: 2023-10-31 15:33:38

`db/schema.rb` 
- Contains the record of the database. 
- NEVER edit this file
- It is auto-generated from running 

`rake db:migrate`

Instead of constantly referencing `db/schema.rb`, install the `annotate` gem. 

Add the gem to the `:development` group of the `Gemfile`.

`bundle install`

`annotate --models`

This creates a rake task file `lib/tasks/auto_annotate_models.rake` 

`rake db:migrate` runs the annotation automatically.

Now at the top of `app/models/like.rb`, see the annotations.
C# - Parallel Asynchronous Operations with Task.WhenAny
Tags: csharp, programming, tutorial, opensource
Published: 2023-10-31 15:30:00

C# provides the `Task.WhenAny` method, which allows you to efficiently await the completion of the first task among a collection of tasks. This is particularly useful when you want to parallelize multiple asynchronous operations and process the result of the first one that completes.

Here's an example:

```csharp
using System;
using System.Threading.Tasks;

public class Program
{
    public static async Task Main()
    {
        var task1 = SimulateAsyncOperation("Task 1", 2000);
        var task2 = SimulateAsyncOperation("Task 2", 3000);
        var task3 = SimulateAsyncOperation("Task 3", 1500);

        // Wait for the first completed task
        var completedTask = await Task.WhenAny(task1, task2, task3);

        // Handle the result of the completed task
        if (completedTask == task1)
        {
            Console.WriteLine("Task 1 completed first.");
        }
        else if (completedTask == task2)
        {
            Console.WriteLine("Task 2 completed first.");
        }
        else if (completedTask == task3)
        {
            Console.WriteLine("Task 3 completed first.");
        }
    }

    public static async Task SimulateAsyncOperation(string taskName, int delayMilliseconds)
    {
        await Task.Delay(delayMilliseconds);
        Console.WriteLine($"{taskName} completed after {delayMilliseconds} ms.");
    }
}
```

In this example, we create three asynchronous tasks using `SimulateAsyncOperation`, each with a different delay. We then use `Task.WhenAny` to await the first completed task and process the result.

This technique is valuable in scenarios where you want to perform multiple asynchronous operations concurrently and act on the result of the first operation that finishes, which can help improve the overall responsiveness and efficiency of your code.
Ansible
Tags: devops, linux, ansible
Published: 2023-10-31 15:29:54

## Ansible Installation

- Ansible Installation steps on Ubuntu machine
```
sudo apt update
sudo apt-add-repository ppa:ansible/ansible
sudo apt update
apt install ansible -y
sudo apt install ansible -y
ansible --version
```
**If not able to get the ansible version follow the below steps**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rgycd5leawl9kj6we6ji.png)

- Virtual Machine setup 

Download and install kvm and install ubuntu 22.04 server edition and centos 7 minimal server with 1GB RAM.

`https://ubuntu.com/download/server#downloads
http://isoredirect.centos.org/centos/7/isos/x86_64/`

1. create a new virtual machine

2. Select Local install media and select the downloaded ISO Package.

3. set memory as "1024" CPU as "1" 

4. set Disk image as "25" modify the name and Click Finish to complete the process. 

5.  Once done select the "Network&Hostname" Enable the Ethernet port.create the user account and set the root password.
**Follow the below cmds to assign different IP when clone**
 

```
echo -n > /etc/machine-id
rm /var/lib/dbus/machine-id
ln -s /etc/machine-id /var/lib/dbus/machine-id
```
**Ansible Config for target machine**

- Enter the inventory and hosts entry on the ansible machine.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qb02unh7loo9khsbuuq9.png)
 

- Get the ssh keygen (.ssh) and find the target machine IP using (hostname -I)

- Copy the source machine ssh public key to the target machine

```
ssh-copy-id -i id_rsa.pub kannan@192.168.122.133
```

- If you want to change the hostname of the target machine go with the below cmd

```
sudo hostnamectl set-hostname ubuntu-node-1
exec bash
```

- Ping the target machine from ansible machine

```
ansible all -m ping
```

- Find the OS version of the target machine from ansible machine

```
ansible all -a "cat /etc/os-release"
```

- To provide root privileges for the users

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e7jf7fsuryz4u2w4vq3b.png)
```
# Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL
```

```
sudo su-
usermod -aG sudo kannan
sudo su - kannan
```

- Let install Apache server(httpd) using adhoc cmds

```
ansible ubuntu -i hosts -m apt -a "name=apache2 state=present" --sudo
ansible all --list-hosts

ansible all -m package -a "name=httpd state=present"
```

```
ansible centos -m package -a "name=httpd state=present" -b

 ansible centos -m ansible.builtin.service -a "name=httpd state=started" -b

ansible ubuntu -m file -a "path=/home/kannan/test mode=755 state=directory" -b

```

- Once Apache is installed on the Target machine bydefault its not active we need to enable,start and find the staus from ansible machine.

```
systemctl enable httpd
systemctl start httpd
systemctl status https
```
Now apache is running on the target machine.
We have done these all from ansible machine and get the output on target machine via ansible.