teleren/devto huggingface dataset:
cURL basics
Tags: curl
Published: 2023-08-11 18:48:55

---
title: cURL basics
published: true
tags: ['curl']
canonical_url: https://sevic.dev/notes/curl-basics/
---

cURL is a command line tool for interacting with servers, it can be used in bash scripts to automate some workflows. This post covers primary usage with examples.

- Send an HTTP GET request to the server

```bash
curl ipv4.icanhazip.com
```

- Get only the response headers

```bash
curl -I ipv4.icanhazip.com
```

- Send POST requests with the request body and headers

```bash
curl -X POST https://api.gumroad.com/v2/licenses/verify \
  -d "product_id=product-id" \
  -d "license_key=license-key"

curl https://api.openai.com/v1/chat/completions \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-3.5-turbo",
    "messages": [{"role": "user", "content": "What is cURL?"}]
  }'
```

- Use the `i` option to include the headers in the response

```bash
curl -i -X POST https://api.gumroad.com/v2/licenses/verify \
  -d "product_id=product-id" \
  -d "license_key=license-key"
```

- Use the `s` option to hide all the logs during the request

```bash
curl -s -X POST https://api.gumroad.com/v2/licenses/verify \
  -d "product_id=product-id" \
  -d "license_key=license-key"
```

- Use the `v` option for verbose logs during the request

```bash
curl -v -X POST https://api.gumroad.com/v2/licenses/verify \
  -d "product_id=product-id" \
  -d "license_key=license-key"
```

- Retrieve bash script and run it locally

```bash
curl https://raw.githubusercontent.com/creationix/nvm/master/install.sh | bash
```

- Trigger specific endpoint inside Kubernetes cronjob

```yml
# ...
containers:
  - name: cleanup
    # ...
    command:
      - /bin/sh
      - -ec
      - 'curl "https://some-service.com/cleanup"'
```
Efficiently Using Environment Variables in FastAPI!
Tags: fastapi, python, environmentvariables, bestpractices
Published: 2023-08-11 18:46:00



---
title: "Efficiently Using Environment Variables in FastAPI!"
published: true
description: "Discover the best practices to leverage environment variables in your FastAPI projects."
tags: fastapi, python, environmentvariables, bestpractices
---

FastAPI offers a flexible and efficient way to build web applications. One of its strengths is the ease with which it integrates with external tools and libraries. In this article, we'll delve into how you can effectively use environment variables within your FastAPI applications. This is crucial for safely managing configurations, secrets, and other sensitive data. Dive in to learn the steps and grab some sample code!

## Table of Contents
1. Installing Necessary Libraries
2. Setting Up Environment Variables
3. Using Environment Variables in FastAPI

---

## 1. Installing Necessary Libraries

First and foremost, we'll need to install the `python-dotenv` library to effortlessly handle environment variables.

```bash
pip install python-dotenv
```

## 2. Setting Up Environment Variables

Next, create a `.env` file in the root directory of your project. Set your environment variables within this file. For example:

```plaintext
DATABASE_URL=postgresql://user:password@localhost:5432/mydatabase
SECRET_KEY=mysecretkey
```

Before launching your FastAPI application, add the following code to ensure the `.env` file's environment variables are loaded:

```python
import os
from dotenv import load_dotenv

load_dotenv()  # Loads environment variables from .env file
```

## 3. Using Environment Variables in FastAPI

Once the environment variables are loaded, they can be accessed and used within the FastAPI application. Use `os.environ.get()` to retrieve the values of these variables:

```python
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    secret_key = os.environ.get("SECRET_KEY")
    return {"Hello": "World", "Key": secret_key}
```

By following these steps, you can seamlessly and securely use environment variables in your FastAPI applications.

---

That's it! By using environment variables in FastAPI, you ensure the security of configurations, secrets, and other sensitive data. Give it a try in your next project!

If you have questions or feedback, don't hesitate to drop a comment or give a thumbs up! 🚀🌟
Beautiful pipelines in Elixir
Tags: elixir
Published: 2023-08-11 18:45:35

Even though I have used Elixir for several years now it still 
 amazes me how much you can achieve with a single pipeline in Elixir language. The other day I had to find the total size of the files in a given dir. I thought of just parsing the output of the `ls -l` command and then adding up all the file sizes to get the total. Here is what I ended up with.

```elixir
"ls -l /Users/parth/temp/github_events/2015/"
|> to_charlist()
|> :os.cmd()
|> to_string()
|> String.split("\n")
|> Enum.reject(&String.starts_with?(&1, "total"))
|> Enum.map(&String.split(&1, ~r/\s+/))
|> Enum.map(&Enum.at(&1, 4))
|> Enum.reject(&(is_nil &1))
|> Enum.map(&(String.to_integer &1))
|> Enum.sum()
|> then(&(&1/:math.pow(10, 9)))
|> Float.round(2)
|> IO.inspect(label: "Size in GBs => ")
```

P.S In practise this code might be shortened by using the standard library functions associated with file handling. But it was fun coming up with this!
reverse only the alphabetical ones
Tags: javascript, programming, tutorial, interview
Published: 2023-08-11 18:30:59

You are given a string that contains alphabetical characters (a - z, A - Z) and some other characters ($, !, etc.). For example, one input may be: 

```
input: 'sea!$hells3'
```

Can you reverse only the alphabetical ones?

```
reverseOnlyAlphabetical('sea!$hells3')
```

```
output: 'sll!$ehaes3'
```

**Solution**

```
function reverse(str) {
  const alphas = [];
  for (let i = 0; i < str.length; i++) {
    if (/[a-z]/gi.test(str[i])) {
      alphas.push(str[i]);
    }
  }
  let output = "";
  for (const char of str) {
    if (/[a-z]/gi.test(char)) {
      output += alphas.pop();
    } else {
      output += char;
    }
  }
  return output;
}

console.log(reverse("sea!$hells3")); // "sll!$ehaes3"

```
Clear and honest code
Tags: programming, adt, kotlin, design
Published: 2023-08-12 22:05:15

---
title: Clear and honest code
published: true
date: 2023-08-11 18:30:00 UTC
tags: #programming #adt #kotlin #design
canonical_url: https://amolrv.github.io/posts/clear-and-honest/
---

When working with a huge code base, it's common to forget how a specific code block (function, method, or class) is implemented. However, the IDE suggests using a signature. Sometimes calling a code block can come with unpleasant shocks. By creating honest and clear code blocks, this can be prevented.

For example:

```kotlin
// (account: Account, amount : BigDecimal) -> Account
fun credit(account: Account, amount : BigDecimal): Account {
  if(amount < ZERO) throw NegativeAmountError(amount)
  return account.copy(balance = account.balance + amount)
}
```

By looking at the signature, caller simply does't know that it's going to blow up. This kind of code blocks affect engineer in 2 ways
1. Increase cognitive overload of reading and understanding each branch of the code block before calling it
2. hampers trust of code block.

Honest signature could have been something like
```kotlin
(account: Account, amount : NonNegativeCurrency) -> Account
// or
(account: Account, amount : BigDecimal) -> Either<NegativeAmountError, Account>
```

These 2 signatures appear quite straightforward, yet they use 2 different techniques.

- The first signature prevents entry into an incorrect state by forbidding negative input.
- While allowing erroneous input, the second signature communicates output more precisely. It informs the caller that it may provide an error or credit to their account.

References
1. Treat Type as set Read [here](https://blog.ploeh.dk/2021/11/15/types-as-sets/) and [here](https://guide.elm-lang.org/appendix/types_as_sets.html)
2. [Algebraic data type](https://en.wikipedia.org/wiki/Algebraic_data_type)
Exploring PostgreSQL Connectivity with Node.js: A Powerful Duo - CRUD Operations
Tags: postgres, node, crud
Published: 2023-08-11 18:24:53

In my previous blog, we took a deep look at establishing connection between NodeJS and PostgreSQL, and now we move forward! Welcome to the realm of data manipulation! In this section, we'll dive into the exciting world of performing CRUD (Create, Read, Update, Delete) operations within your Node.js application using PostgreSQL. Buckle up, as we explore how to seamlessly interact with your database, creating, fetching, updating, and deleting records with ease.

## Creating Records
To insert new data into your PostgreSQL database, you'll be utilizing the `INSERT` statement. Here's how to insert a new user into a hypothetical `users` table:

```
const newUser = {
  username: 'john_doe',
  email: 'john@example.com',
};

const insertQuery = 'INSERT INTO users (username, email) VALUES ($1, $2)';

client.query(insertQuery, [newUser.username, newUser.email])
  .then(() => {
    console.log('New user inserted successfully');
  })
  .catch((err) => {
    console.error('Error inserting user:', err);
  });

```

## Reading Records
Retrieving data from the database involves the `SELECT` statement. Let's fetch all users from our users table:

```
const selectQuery = 'SELECT * FROM users';

client.query(selectQuery)
  .then((result) => {
    const users = result.rows;
    console.log('All users:', users);
  })
  .catch((err) => {
    console.error('Error fetching users:', err);
  });

```
You can change the query to alter the selection. 

## Updating Records
Modifying existing records is done with the UPDATE statement. Suppose we want to change the email of a user:

```
const userIdToUpdate = 1;
const newEmail = 'updated@example.com';

const updateQuery = 'UPDATE users SET email = $1 WHERE id = $2';

client.query(updateQuery, [newEmail, userIdToUpdate])
  .then(() => {
    console.log('User updated successfully');
  })
  .catch((err) => {
    console.error('Error updating user:', err);
  });

```

## Deleting Records
To remove records from the database, use the DELETE statement. For instance, let's delete a user with a specific ID:

```
const userIdToDelete = 2;

const deleteQuery = 'DELETE FROM users WHERE id = $1';

client.query(deleteQuery, [userIdToDelete])
  .then(() => {
    console.log('User deleted successfully');
  })
  .catch((err) => {
    console.error('Error deleting user:', err);
  });

```

## Conclusion
With the power of PostgreSQL and the flexibility of Node.js, you now possess the tools to masterfully manipulate your database. Whether you're adding new data, fetching insights, updating records, or removing entries, your Node.js application and PostgreSQL database are seamlessly connected, allowing you to mold your data with precision and finesse.
fizzbuzz
Tags: javascript, programming, beginners, interview
Published: 2023-08-11 18:14:04

## Write a function that returns the string representation of all numbers from 1 to n based on the following rules:

**• If it's a multiple of 3, represent it as "fizz".
• If it's a multiple of 5, represent it as "buzz".
• If it's a multiple of both 3 and 5, represent it as "fizzbuzz".
• If it's neither, just return the number itself.**

**Example**

```
function fizzBuzz(num){

}

input:15

output:'12fizz4buzzfizz78fizzbuzz11fizz1314fizzbuzz'.
```

**Solution**

```
function fizzBuzz(num) {
  let i = 1;
  let result = "";
  while (i <= num) {
    if (i % 15 === 0) {
      result += "fizzbuzz";
    } else if (i % 3 === 0) {
      result += "fizz";
    } else if (i % 5 === 0) {
      result += "buzz";
    } else {
      result += i;
    }
    i++;
  }
  return result;
}

const result = fizzBuzz(15)
console.log(result); // '12fizz4buzzfizz78fizzbuzz11fizz1314fizzbuzz'
```
Array intersection
Tags: javascript, beginners, programming, interview
Published: 2023-08-11 18:02:29

## Can you write a function that takes two arrays as inputs and returns to us their intersection? Let's return the intersection in the form of an array.

```
function intersection(arr1, arr2) {
  
}

const nums1 = [4, 9, 5];
const nums2 = [9, 4, 9, 8, 4];

console.log(intersection(nums1, nums2)); // [9,4] or [4,9]
```

**Solution 1**

```
function intersection(arr1, arr2) {
  const set = new Set(arr1);
  return [...new Set(arr2.filter((num) => set.has(num)))];
}

const nums1 = [4, 9, 5];
const nums2 = [9, 4, 9, 8, 4];

console.log(intersection(nums1, nums2)); // [9,4]
```

**Solution 2**

```
function intersection(arr1, arr2) {
  const set = new Set();
  for (const num of arr1) {
    set.add(num);
  }
  const result = [];
  for (const num of arr2) {
    if (set.has(num)) {
      result.push(num);
      set.delete(num);
    }
  }
  return result;
}

const nums1 = [4, 9, 5];
const nums2 = [9, 4, 9, 8, 4];

console.log(intersection(nums1, nums2)); // [9,4]
```
Day2-#100DaysOfCoding Challenge Update
Tags: 100daysofcode, programming, cpp
Published: 2023-08-11 18:01:52

Today, I began my coding session by tackling some basic-level questions from Geeks for Geeks. To be honest, my motivation wasn't at its peak today. I did make an effort to push myself, although I feel I might not have made the most of my time. On the positive side, I did manage to code, which I consider a small victory. Admittedly, I had hoped to dive into more substantial coding challenges today, but I also recognize that achieving significant progress takes time. Rushing through the process wouldn't benefit anyone.

To sum it up, today marked just the second day of this journey, and I faced a moment where quitting crossed my mind. While that's not a desirable thought, I'm determined to fight it. The fact that I'm pushing through despite challenges is a victory in itself.

Onward to day 3, where I aim to make more strides and keep the momentum alive. Let's keep the positivity flowing and continue to learn and grow together.

Stay resilient,
Sivaraghavi U.R.
How to Select a Domain Extension for a company?
Published: 2023-08-11 17:43:07

Your website might have to face a lot of challenges. Therefore you need to select a domain extension for your company that suits your requirements. [Navicosoft](https://www.navicosoft.com/) offers multiple domain extensions for your online company which includes .com, .org, .info, .tel .biz, .net, etc. 
Here are some of the options that you might want to consider closer to jump into the world of top-level domains (TLDs). 
**When to Use a .org Extension**
.org stands for ‘organization.’ Non-profit websites prefer using a .org extension. It was found in 1985 for only non-profit existences. But eventually, even the profitable companies opt for it now. Many users consider it reliable and trustworthy.
Using other TLDs can be useful in some situations, but the .org extension is a well-known and trustable extension. However, most users believe that companies should use .com extension. Tying .org domain extension for your brand raises the possibility of people visiting other websites by chance. Moreover, search engine ranking works well but is not as efficient as that of .com.
**When to Use a .net Extension**
A .net stands for ‘network.’ People can select a [domain extension](https://www.navicosoft.com/domain-name/) if a .com domain is unavailable. In general, people recognize a .net extension as more authoritative and reliable since people can easily recall it.
It is a great option from an SEO point, but people might confuse it with other extensions such as .org or .com, and you definitely do not want that! Hence if a .com domain is unavailable, then .net is a good second choice.
**A .com extension is a Preferable one**
[A .com domain is the most notable](https://www.navicosoft.com/domain-name/) and suitable domain extension for any business. That is because most users will automatically assume that your website has a .com extension. Search engines, especially Google, prefer the .com extension. The reason is very obvious that users are most likely to click on a .com extension. Hence before you select a domain extension, think carefully. In addition to this, the .com extension is a suitable extension since it is convenient to remember, and the user will most probably type the correct URL to land on the correct website.
Navicosoft provides domains at very low prices. We offer much more than just a platform to build a blog or a website by creating the best web presence.
This content is taken on given link:
[https://www.riteanswers.com/domain-and-hosting/details/how-to-select-a-domain-extension-for-a-company](https://www.riteanswers.com/domain-and-hosting/details/how-to-select-a-domain-extension-for-a-company)
How to restrict AWS access from office Ips only
Published: 2023-08-11 17:24:10

Use Source IP condition in IAM policy.

```
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Statement1",
            "Effect": "Allow",
            "Action": [
                "*"
            ],
            "Resource": [
                "*"
            ],
            "Condition": {
                "IpAddress": {
                    "aws:SourceIp": [
                        "202.74.246.XXX/32"
                    ]
                }
            }
        }
    ]
}
```
AWS Resource Explorer
Tags: aws, cloud, devops, learning
Published: 2023-08-11 17:13:41

![Day22](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u99g4pmwgzoaeky008e9.png)

[22/30] #30DaysOfAWS Today, **AWS Resource Explorer & Hands-On**.

**AWS Resource Explorer** is a managed capability that simplifies the search and discovery of your AWS resources across AWS Regions. You can use Resource Explorer to explore your resources using an internet search engine like experience. Examples of resources include Amazon Relational Database Service (Amazon RDS) instances, Amazon Simple Storage Service (Amazon S3) buckets, or Amazon DynamoDB tables.

**Here are some of the things you can do with AWS Resource Explorer**

- Search for your resources using resource metadata like names, 
  tags, and IDs.
- Search across all of the AWS Regions in your account in which 
  you turn on Resource Explorer.
- See the relationships between your resources.
- Get information about your resources, such as their status, 
  configuration, and usage.
- Take actions on your resources, such as deleting them or 
  modifying their configuration.
- You can access Resource Explorer from the AWS Management 
  Console, the AWS Command Line Interface (CLI), or the AWS SDKs.

**Here are the steps on how to use AWS Resource Explorer**

- Sign in to the AWS Management Console.
- In the navigation pane, choose Services, then select Resource 
  Explorer.
- In the Search bar, enter a search term.
- The results will be displayed in a table. You can filter the 
  results by using tags, services, and other metadata.
- To learn more about a resource, click on it in the table.
- To take action on a resource, click on the Actions button.

**Step-by-step tutorial** for how to setup **AWS Resource Explorer**. You can download it using this [URL](https://lasantha-fileshare-s3-932747549174-v1.s3.us-east-2.amazonaws.com/AWSResourceExplorer.pdf).

Learn More - https://docs.aws.amazon.com/resource-explorer/latest/userguide/welcome.html

Thanks for reading the Article.
A beginner-friendly design patterns masterclass
Tags: java, designpatterns
Published: 2023-08-11 17:10:58

Are you ready to supercharge your Java programming skills? Join me on this enlightening journey where we unravel the world of creational design patterns and discover how to create powerful, efficient software architectures.

🔍 Course Highlights:

🧩 Master all creational design patterns: Factory Method, Abstract Factory, Builder, Singleton, and Prototype.

💡 Practical solutions for real-world software engineering challenges.

🌟 Acquire problem-solving skills that'll turbocharge your software development career.

🖋️ Write cleaner, scalable Java code with confidence.

Enroll now: https://www.udemy.com/course/creational-design-patterns-in-java-demystified/?couponCode=LI_CREATE_JAVA_0823

Don't miss out on this opportunity to enhance your Java programming prowess and become a pro in building robust software architectures.

Let's level up our Java game together! 🚀 Enroll today and let's delve into the world of creational design patterns.
How to Manage Your Time Effectively as a Software Engineer
Tags: softskills, softwareengineering, time
Published: 2023-08-11 17:06:48



> "Your greatest asset is your earning ability. Your greatest resource is your time." - **Brian Tracy**

In the dynamic realm of technology, software engineers are the architects of innovation, meticulously crafting the digital landscapes that define modern existence. The role they play is pivotal, as they conceptualize, construct, and maintain software applications that resonate with millions. Amidst this intricate tapestry of responsibilities, the art of time management emerges as a linchpin for success.

_Time management, akin to an adept ally, empowers software engineers to navigate their professional voyage with precision._

**Here's why it's pivotal:**

1. With a deft command of time, software engineers can channel their energies into vital tasks, culminating in heightened productivity and bolstering corporate outcomes.
2. Strategic time management serves as a potent antidote to the stressors that often pervade intricate projects. The equilibrium it establishes nurtures a harmonious work-life coexistence, underpinning job contentment.
3. Time-conscious engineers are better poised to make judicious decisions, guided by a lucid comprehension of priorities and deadlines. This strategic acumen augments project efficacy and individual career trajectories.
4. Proficient time management fosters seamless collaboration, enabling engineers to engage seamlessly with team members and stakeholders. This cohesion cultivates efficient workflows and successful project outcomes.

**Explore these effective time management techniques crafted for software engineers:**

1. Initiate with clear, goal-driven objectives and well-defined timelines.
2. Fragment sizeable tasks into manageable components.
3. Discern the zenith tasks from the periphery. Prioritize judiciously to concentrate efforts on pivotal endeavors.
4. Accurate time estimation for each task is paramount. Precise assessments preclude delays and pave a smooth trajectory.
5. In the quest for excellence, pause for rejuvenation. Brief interludes augment focus and sustain enduring productivity.
6. Harness the potency of delegation, if viable. Entrusting ancillary tasks amplifies the focus on the crux of responsibilities.
7. Establish a sanctuary of concentration by muting external disruptions.

**In tandem with these strategies, leverage an array of time management tools to fortify your pursuit:**

1. Tools such as Asana or Trello provide a digital arena for task management, ensuring coherence amidst complexity.
2. Enlist Pomodoro timers, like Focus Booster, to delineate work intervals, optimizing efficiency.
3. Engage digital reminders through apps or calendars.
**BEST PYTHON'S TURTLE CHEAT SHEET EVER**
Published: 2023-08-11 17:06:32

Hi guys, checkout my new own made cheat sheet. I looked through lot of cheat sheet and came up to this. You can download it and use it, no Copyright

[](https://docs.google.com/document/d/1rKgdIwjNdOxBqZc7C8EuAhvB2qN4lwyV-_qH_Swfm7I/edit?usp=sharing)