teleren/devto huggingface dataset:
How to calculate execution time in python
Tags: python, programming, tutorial, coding
Published: 2023-09-05 19:47:59

{% embed https://www.youtube.com/watch?v=1Dmq4MJIY5E %}

## code 

```python

import time

def test():
    for i in range(100):
        print(i)
        
    time.sleep(1)
    

# starting time
start = time.time()

test()

# end time
end = time.time()

# total time taken
print(f"[Execution time is : {end - start} s] ")
```

## result
```
[Execution time is : 1.0190958976745605 s] 
```
Canvas Playground: broadcasting & pens
Tags: react, socketio
Published: 2023-09-05 19:42:47

One thing I struggle with when learning something new is feeling like I don't have progress to show. Today I've spent time looking at DynamoDB and EC2 so I can start determining how I want to deploy the server and potentially store the drawing actions but that would leave me without a visible progression. 

## Pens

To do something on that front, I decided to tackle making it possible to change color schemes for the pens and fixed a bug where the pen color was getting stuck.

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

The first step was moving the pens in to their own component.

Pen.tsx

```react
interface PenProps {
  color: {
    value: string;
    name: string;
  }
  changeColor: MouseEventHandler;
}

export default function Pen({ color }: PenProps) {
  return (
    <button 
      className='paint-button' 
      value={color.value} 
      onClick={changeColor}
    >
      <span 
        className='material-symbols-outlined' 
        style={{color: `${color.value}`}}
      >
        brush
      </span>
    </button>
  )
}
```

This component is receiving the pen color object and the `changeColor` function from the parent.

I wanted to make it so once the pen was selected it would maintain a class on `:active`. To do that, I passed in the currently selected color and updated the class on the pen to include the class `selected` if the pen color value and the `activeColor` matched.

```react
interface PenProps {
  color: {
    value: string;
    name: string;
  },
  activeColor: string;
  changeColor: MouseEventHandler;
}

export default function Pen({ color, activeColor, changeColor }: PenProps) {
  return (
    <button 
      className={`paint-button ${activeColor === color.value ? 'selected' : ''}`} 
      value={color.value} 
      onClick={changeColor}
    >
      <span 
        className='material-symbols-outlined' 
        style={{color: `${color.value}`}}>
          brush
      </span>
    </button>
  )
}
```

## Broadcasting
When I was setting up the server, I was sending back out the drawing events from the server, I just did a generic emit on the server so it would send the event back to all connected sockets. That worked, but I don't need the original socket sending info to get it back. To do this, I updated the server to use the [broadcast flag](https://socket.io/docs/v4/server-api/#flag-broadcast) after it receives the `userIsDrawing` event to broadcast that back out to the other attached sockets.

original:
```
  socket.on('userIsDrawing', (e) => {
    io.emit('userDrawing', e)
  })
```

broadcasting:
```
  socket.on('userIsDrawing', (e) => {
    socket.broadcast.emit('userDrawing', e)
  })
```

Tiny changes felt like some nice progress today:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rtvioezv9350ioqpypzp.gif)
All about FLEX
Tags: webdev, css, programming, beginners
Published: 2023-09-05 19:35:20

Display : The display enables flex for all children(inner components of html).
By doing this the direct child elements of a flex container automatically becomes flexible (flex) items.
 
Flex-direction -->Establishes the main axis.
<ul>
<li>flex-direction : row ->this is default property of flex,all items will appear in one single row.</li>
<li>flex-direction : row-reverse -> this acts same as row but in opposite direction.</li>
<li>flex-direction : column -> all elements appear in single column.</li>
<li>flex-direction : column-reverse -> as name suggest acts like column  but in opposite direction i.e. form bottom to top.
</li>
</ul>

flex-wrap --> wrap items if they can't all be made to fit on one line.
<ul>
<li>flex-wrap : nowrap -> as name suggest no wrapping is done.</li>
<li>flex-wrap : wrap -> content that doesn't fit in single line will be moved to next line.
</li>
<li>flex-wrap : wrap-reverse -> the content fits in reverse order i.e. from last line to second last line.
</li>

</ul>


Justify-content --> Attempts to distribute extra space on the main axis i.e. horizontal axis of webpage.
<ul>
<li>justify-content : flex-start -> all the elements will be on left side with no spaces in between.</li>
<li>justify-content : flex-end -> all the elements will be on the right side with no spaces in between.</li>
<li>justify-content : centre -> all the elements will be placed at the centre.</li>
<li>justify-content : space-between -> as the name suggests space left in entire web page/ view port is equally divided between the elements i.e. any two elements will have same space between them.</li>
<li>justify-content : space-around -> it is same as space-between but space is also present at ends in same amount as in between.</li>
<li>justify-content : space-evenly -> same is divided and alloted between element and remaining space in present at the two left and right corners.</li>
</ul>

Align-items --> Determines how items are laid out on the cross axis i.e. vertically
<ul>
<li>align-items :flex-start -> all items are horizontally  at top.</li>
<li>align-items :flex-end ->all items are horizontally  at bottom.</li>
<li>align-items :flex-center -> all items are horizontal and placed at center.</li>
<li>align-items :baseline -> all are placed at same level from a same reference line.</li>
<li>align-items :stretch -> all items are stretch from top to bottom.
</li>
</ul>

Align-content --> Only has an effect with more than one line of content, can be used with flex-wrap.
It also has same properties as start, end, center, space-between, space-around, stretch.

children 
Order --> allows you to explicitly set the order you want each child to appear in.
order: integer

flex-grow --> allows you to determine how each child is allowed to grow as a part of a whole

flex-basis --> defines the size of an element before remaining space is distributed.
e.g. first item 20%,second item 40%.

flex-shrink --> allows an item to shrink if necessary. Only really useful with a set size or flex-basis.

align-self --> sets alignment for individual item.
python cheatcode#
Published: 2023-09-05 19:20:38

This  is the simplest way to solve a challenge **IF statement**.
 

- lets say we are having this quiz 
- Given an integer, , perform the following conditional actions:
- If  is odd, print Weird
- If  is even and in the inclusive range of  to , 
print Not Weird
- If  is even and in the inclusive range of  to , print Weird
- If  is even and greater than , print Not Weird


Here is the solution:

```
  if __name__ == '__main__':
    n = int(input().strip())
    if n % 2 == 1:  
        print("Weird")
    elif n % 2 == 0 and 2 <= n <= 5:  
        print("Not Weird")
    elif n % 2 == 0 and 6 <= n <= 20: 
        print("Weird")
    elif n % 2 == 0 and n > 20:  
        print("Not Weird")
```
The Ultimate Cheatsheet to Typography! 😎
Tags: webdev, ui, beginners, tutorial
Published: 2023-09-05 19:04:44

**What is the most difficult things when it comes to building User interface?**

Every single developer has it's own take on this question, some might tell you that **Colors** are the most toughest thing to decide on. Others might say **Box Shadow**, but deep-down we all know, nothing can be more tiresome when it comes to choosing fonts.

## A great font-combination can do magic to UI
_was once said by me, Kaustubh Shinde._

With that being said, do people actually know the exact trick to choose the right fonts for UI?

Well the answer is, **NO!**

As of now, there is no **One-single way** to choose the font typography combination and even if you view 100's of different YouTube Videos or read 1000's of different articless it will break your brain because every single UI Designer has their own take on typography.

What these UI Designer suggest comes from their own experience and philosophy that worth a gold. 

However majority of developers who just want to get rid of the hassle of choosing typography do a much simple process.

They have a set of specific chosen font for their project and use those sets in rotation!

So keeping this in mind I came up with my own so-called **Ultimate cheatsheet** of choosing the right Typography.

I made a list of **43 fonts** and made **100 Combinations** out of these chosen fonts.

I've included the cheatsheet in my **Open UI Library Project** - Stack UI.


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

Project Link - [https://stackui.co/components/font_combine](https://stackui.co/components/font_combine)

Go ahead and use those to build your awesome User Interface. 😁
Vleer: The Music Player That Lets You Hear More for Less
Tags: vleer, music, opensource, warrradu
Published: 2023-09-05 18:51:47

## Introducing Vleer: A Redefined Way of How We Interact with Music
Have you ever wished for a music app that is free, open source, and customizable? A music app that lets you enjoy your favorite songs without any ads, subscriptions, or limitations? A music app that works seamlessly on your PC and your phone?

If you answered yes to any of these questions, then you might want to check out Vleer, a new music app that aims to replace Spotify, Apple Music, and other popular streaming services. Vleer is an app crafted entirely around you, with a simple and elegant user interface, a powerful music player, and a community-driven development.

## What is Vleer?
Vleer is a free and open source music app that lets you listen to your local music files or stream from various online sources. You can create playlists, browse by genres, artists, albums, or songs, and control the playback with keyboard shortcuts or touch gestures. You can also customize the app’s appearance, behavior, and functionality to suit your preferences.

Vleer is built with Tauri and Nuxt.js, which means it is fast, lightweight, and cross-platform. You can run Vleer on Windows, Linux, or macOS, as well as on Android or iOS devices. Vleer also supports offline mode, so you can enjoy your music even without an internet connection.

## Why should you use Vleer?
Vleer is not just another music app. It is a music app that respects your freedom, privacy, and creativity. Unlike other streaming services that charge you money, show you ads, or limit your choices, Vleer gives you full control over your music experience. You can listen to any song you want, from any source you want, without any restrictions.

Vleer is also a community-driven project, which means it is constantly evolving and improving based on user feedback and suggestions. You can contribute to Vleer’s development by reporting bugs, requesting features, or submitting code. You can also join the Vleer community on GitHub, Discord, or Twitter to share your thoughts, ideas, or opinions.

## How can you get Vleer?
Vleer is still in the early development stage, but you can download the latest version from the official website: [Vleer](https://vleer.app). You can also follow the installation instructions on the GitHub repository to build the app from source. Please note that Vleer may have some bugs or errors at this stage, so use it at your own risk.

If you want to support Vleer’s development, you can also donate via GitHub sponsor. Your donations will help cover the costs of hosting, domain name, and other expenses.

Join the [discord](https://discord.gg/vmpM79tkd7) to submit your own ideas.
The Power of Pure Functions: Why Every JavaScript Dev Should Care!
Tags: javascript, discuss, learning, web
Published: 2023-09-05 18:28:53

If you're on a quest to write cleaner, more maintainable, and bug-resistant code, pure functions should definitely be in your toolbox. Let's deep dive into this topic and understand why it's such a game-changer for JavaScript developers.

## What are Pure Functions? 🧐
In a nutshell:

They always return the same output for the same input.
They have no side-effects; they don't change anything in the outer world.

## A Real-world Example 🛍️: Online Shopping Cart
Let's understand this with a juicy example - calculating the total of an online shopping cart, including discounts and taxes.

### Without Pure Functions:
Imagine using a function relying on global variables:

```js
let discount = 10; // default 10% discount
let tax = 0.05;    // 5% tax

function calculateTotal(cart) {
    let total = 0;
    for (let product of cart) {
        total += product.price;
    }
    total = total - total * (discount / 100);
    total = total + total * tax;
    return total;
}
```
Here, **calculateTotal** isn't pure since it leans on global variables **discount** and **tax**. If **discount** or **tax** accidentally changes somewhere in your code, it can lead to incorrect calculations.

## With Pure Functions:
The better approach? Make **calculateTotal** pure by taking all its needed values as arguments:

```js
function calculateTotal(cart, discount, tax) {
    let total = 0;
    for (let product of cart) {
        total += product.price;
    }
    total = total - total * (discount / 100);
    total = total + total * tax;
    return total;
}
```

## Why You Should Care! 🌟

1. **Predictability**: With pure functions, you know that given the same arguments, they'll always return the same result. No more unexpected surprises!
2. 
3. **Testability**: Pure functions are a breeze to test. You can easily mock inputs and verify outputs without setting up and tearing down external states.
4. 
5. **Reusability**: They tend to be more reusable since they're not tied to any specific state or context.
6. 
7. **Optimization and Parallelism**: Certain platforms/libraries can make specific optimizations when they know a function is pure. Think about memoization or parallel processing. Neat, right?

## Wrap Up 🎁
Pure functions are not just a "nice-to-have"; they can significantly improve the quality of your codebase. So, the next time you're about to write a function, ask yourself: "Can I make this pure?"

And hey, if you found this useful, don't forget to smash that ❤️ button and share with your friends! Let's keep the conversation going. How have pure functions made a difference in your coding journey? Drop your thoughts below! 👇
Top 5 free developer utility tools
Tags: developers, tools, development
Published: 2023-09-05 18:25:22

**1. [CSV to JSON](https://www.dronahq.com/csv-to-json/#csvtojson)**
The CSV to JSON Converter tool allows you to quickly and easily convert CSV files to JSON format. This tool is commonly used in data analysis and web development applications.

**2. [REST API Generator](https://www.dronahq.com/api-generator/#apigenerator)**
REST API generator for building custom datasets that match your use case. Read and write APIs on top of it for prototyping and testing and build apps for your API.

**3. [URL Encoder and Decoder](https://www.dronahq.com/url-encoder-and-decoder/#urlencoderdecoder)**
URL encoder/decoder can convert URLs and text to and from a format that can be safely transmitted over the internet.

**4. [Base64 Encoder and Decoder](https://www.dronahq.com/base64-encoder-decoder/#base64encoderdecoder)**
Base64 encoder and decoder is a tool that converts data to and from Base64 format, commonly used for transmitting binary data over text-based mediums.

**5. [UUID Generator](https://www.dronahq.com/uuid-generator/#uuidgenerator)**
The UUID Generator tool generates unique identifiers using the universally unique identifier (UUID) standard, ensuring a high degree of randomness and uniqueness.
Type Error for Codux
Published: 2023-09-05 18:18:55


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

I am getting this error for codux visual IDE

**TypeError: fetch failed
**at Object.fetch (node:internal/deps/undici/undici:11413:11)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
Hi! I’m Tuan
Published: 2023-09-05 15:06:34

I'm teacher, writer, speaker, empower, learn and listen every thing in life. My core technology interests are Data Science, focus business domain.
With over 10 years of vast development experience in Microsoft .NET technology and many databases, joined full-time with CTO position and Software Developer position with many projects such as ERP, CRM, Transportation logistics , Education system, Elearning system
My rich skill set includes developing and managing IT/Web based applications in different technologies, such as C#.NET, .NET Core ADO.NET, LINQ to SQL, WCF, WPF, WEB API, ASP.NET 2.0/3.x/4.0/5.0/Core, MicroServices, MongoDB, SQL Server, Angular JS, React JS, TypeScript, Javascript, jQuery and Python.
I have possesses a Master’s degree in Computer Science and has been actively contributing to the development community for its betterment. I have written many articles/blogs, 3 research papers scopus, 2 eBooks on different technologies to help improve the knowledge of young technology professionals. I have trained/coaching more than one lakh students and professionals, as a speaker in workshops conducted in more than 5 universities of South Vietnam.
Currently, I am working on data science related problems to integrate into an existing software project and many similar projects and I am the CEO of the company, managing company products, managing many startup projects called learnX.
join 2023.09.05
Set id for users automatically in FastAPI and pydantic , uuid4 in Python.
Tags: python, fastapi, api, programming
Published: 2023-09-05 17:38:22

## Hi 🙂🖐

Welcome In a new post, today I will share with you how to set ids for users automatically in FastAPI and Pydantic, and uuid4 in Python.



## step 1
Import modules

```python
from fastapi import FastAPI
from pydantic import BaseModel
from uuid import uuid4

import json
```

## step 2
Create a Json file to store user into it

```json
{
    "users": [
        
    ]
}
```

## step 3
Load the json file

```python
users_db = json.load(open('users.json', 'r'))
```

## step 4
Create the user Model

```python
class User(BaseModel):
    username : str
    password : str
```

## step 5
Create the api and `add_user` Route

```python
app = FastAPI()

@app.post('/add_user')
def add_user(user : User):
    
    users_db['users'].append({
        "id": str(uuid4()),
        "username": user.username,
        "password": user.password
    })
    
    json.dump(users_db, open('users.json', 'w'), indent = 4)
    return {'user': user.username}
```

## full code
```python

from fastapi import FastAPI
from pydantic import BaseModel
from uuid import uuid4

import json

users_db = json.load(open('users.json', 'r'))

class User(BaseModel):
    username : str
    password : str

app = FastAPI()

@app.post('/add_user')
def add_user(user : User):
    
    users_db['users'].append({
        "id": str(uuid4()),
        "username": user.username,
        "password": user.password
    })
    
    json.dump(users_db, open('users.json', 'w'), indent = 4)
    return {'user': user.username}
```

Now we are redy to add new user

```python
import requests

data = {
    'username': 'test123',
    'password': '123'
}

res = requests.post('http://127.0.0.1:8000/add_user', json=data)
print(res.json())
```

## result
```
{'user': 'test123'}
```


**Now we're done 🤗**

**Don't forget to like and follow 🙂**

**Support me on PayPal 🤗**
https://www.paypal.com/paypalme/amr396
Injeção de dependência, interfaces e Laravel
Tags: php, laravel, braziliandevs
Published: 2023-09-05 17:14:43

Em 2020 eu fiz um repositorio com o Laravel, o objetivo era testar o framework, busquei usar inferfaces para desacoplar o código. Nisso injetei nos controllers a dependencia para uma interface, que é programar voltado para abstrações, pois isso desacopla o código, o que significa poder trocar de implementações.

```php
<?php

namespace App;

use \stdClass as User;

/**
 *
 * @author Raphael da Silva
 *
 */
interface UserFinder
{
   	public function getById(int $id): User;
}
```

```php
<?php

namespace App\Http\Controllers;

use Illuminate\Contracts\Support\Renderable;
use App\UserFinder;

/**
 *
 * @author Raphael da Silva
 *
 */
class UserDetailsController extends Controller
{
	private $userFinder;

	public function __construct(
		UserFinder $userFinder
	){
		$this->userFinder = $userFinder;
	}
    
	public function index(int $id): Renderable
	{
		return view('user-details', [
			'user' => $this->userFinder->getById($id)
		]);
	}

}
```

Ou seja, a interface `UserFinder` permite criar qualquer classe para buscar um usuário. A implementação padrão foi usando os componentes (as classes) de acesso a banco de dados o Laravel, pois essa implementação em questão busca usuários no banco de dados. Mas poderia ser em qualquer outra fonte de dados (um arquivo XML, um arquivo JSON).

E o acesso ao banco de dados do Laravel é um monte de método estático (agrupado num namespace chamado DB, que significa DataBase) do qual nao gosto muito, mas a beleza da coisa é que isso nao importa porque todo esse código está abstraido com a interface, apenas a implementação (`LaravelDBUserFinder`) usa esses métodos estáticos que são pertinentes a como o Laravel faz as coisas no seu ecossistema.

```php
<?php

namespace App;

use App\UserFinder;
use Illuminate\Support\Facades\DB;
use \stdClass as User;
use Illuminate\Database\Eloquent\ModelNotFoundException;

/**
 *
 * @author Raphael da Silva
 *
 */
class LaravelDBUserFinder implements UserFinder 
{
   	public function getById(int $id): User
   	{
   		$user = DB::table('users')->find($id);

   		if(is_null($user)){
   			throw new ModelNotFoundException('User not found.');
   		}

   		return $user;
   	}
}
```

Eu nao sou fluente em Laravel, nem domino esse framework, o máximo que fiz com ele foi testes para vagas de emprego (porque ele é muito usado pelo mercado, virou uma espécie de convenção), mas tento observar a arquitetura das coisas e busco desacoplar o código no paradigma da orientacao a objetos. Então gosto de ver as interfaces aplicadas e como isso traz legibilidade e desacoplamento para o código.

Link para o repositório: https://github.com/raphael-da-silva/testando-o-laravel

Originalmente publicado em: https://raphael-da-silva.github.io/injecao-de-dependencia-laravel/
How to upload file in FastAPI and Python.
Tags: python, fastapi, api, programming
Published: 2023-09-05 16:54:57

## Hi 🙂🖐

In this post, I will share with you how to upload file in FastAPI and Python in easy way.

## step 1
You need to install fastapi `pip install fastapi` 
and `pip install python-multipart`

## step 2
Create folder called `files`

## step 3

Create the api and upload_file Route

```python
from fastapi import FastAPI, UploadFile, File
import shutil

app = FastAPI()

@app.post('/upload_file')
def upload_and_create_file(file : UploadFile = File(...)):
    with open(f'files/{file.filename}', 'wb') as buffer:
        shutil.copyfileobj(file.file, buffer)
        
    return {'msg': 'done', 'file': file.filename}
```

Run the api
```
uvicorn main:app --reload
```

Now we are ready to Upload any file I will use requests to upload file

```python
import requests

files = {'file': open('test.mp4', 'rb')}
res = requests.post('http://127.0.0.1:8000/upload_file', files=files)
print(res.json())
```

## result

```
{'msg': 'done', 'file': 'test.mp4'}
```


**Now we're done 🤗**

**Don't forget to like and follow 🙂**

**Support me on PayPal 🤗**
https://www.paypal.com/paypalme/amr396