teleren/devto huggingface dataset:
The Power of Command Line: Why Developers Should Embrace It
Tags: programming, webdev
Published: 2023-05-01 10:27:08


## Introduction:

The graphical user interface (GUI) has made computing easier for many people, but the command line interface still holds immense power, especially for developers. In this article, we will explore why developers should embrace the command line and some basic commands to get started.

The Versatility and Speed of Command Line:
The command line is one of the most versatile ways of interacting with the operating system. With direct communication with the computer, there is no friction, making it a fast way to communicate with the computer and get it to do something. Additionally, it is consistent, with low overhead, making it an efficient way to execute repetitive tasks.


## Basic Commands:
To get started with the command line, there are some basic commands that every developer should know. 
- The cp command is used to copy content from one file to another
- The cd command is used to change directories
- The cat command reads each File parameter in sequence and writes it to standard output.
- The ls command lists the contents of the current directory.
- The mkdir command is used to create a new directory.
- The rm command is used to delete files and directories.
- The mv command is used to move or rename files and directories.
- The echo command prints text to the terminal.

These commands are simple yet powerful, and they form the building blocks of more complex tasks.


## VIM: A Powerful Text Editor:

VIM is a powerful text editor that allows developers to edit files without going through lots of hurdles. It has three modes: insert, normal, and command modes. To open VIM, use the vi <name of file> command. Once in VIM, you can edit and insert text inside the file. To save and quit VIM, use the :wq command, and to quit without saving, use q!. VIM is a tool every developer should master to be efficient in their work.


## Understanding Shell:
The shell is the application running inside the terminal, and there are two popular shells that we know: bash and zsh. Zsh is a newer version of Bash mostly found on the latest macOS operating system, and it is a more extensible version of Bash. To check which shell your system is using, use the echo $0 or echo $shell command.


## Conclusion:
In conclusion, while the graphical user interface has made computing more accessible to many people, developers should embrace the power of the command line. The command line is fast, consistent, and efficient, making it a valuable tool for executing repetitive tasks. Additionally, VIM and shell knowledge can help developers increase their productivity and be more efficient in their work.
Micro Libraries
Tags: microlibraries, npm, typescript, webdev
Published: 2023-05-01 10:00:00

Some weeks ago I stumble upon the concept of *micro apps*: apps that serve only one [functionality/purpose](https://en.wikipedia.org/wiki/Microapp), being minimal in most of the cases. And I question myself: if we have microservices and micro apps, it's only logical that we have micro libraries, right?

So, what do these libraries offer? You guessed it, one **feature/functionality**. The earliest moment I remember seeing one of these libraries, was the `isX` libraries drama, where people claimed that JavaScript projects were becoming bloated because of the over-dependence on predicate function libraries, such as "is-number", for something as simple as asserting if a value is a number ([is-number](https://www.npmjs.com/package/is-number)).

While I agree that these type of libraries contribute to bloatiness, building them can be quite satisfying, because:

- they are fast to build
- they are easy to maintain
- they integrate with ease
- you are challenged to build without external dependencies and for optimization

There's an additional rule for micro-libraries: what you build must be **shipped through a single function**. For JS/TS libraries, you can achieve this by exporting only that function in the main module file.

---

One big advantage of using micro-libraries, is that **you get what you pay for**. For example, if you only need feature `X` from library `Y`, why should you also depend on feature `Z`, `W`, `A`, `B` and `C` that are bundled with `Y`?
This was my motivation for building `github-upsert`: a micro library for uploading/updating files in a GitHub repo.

I can now use this library on my Cloudflare Workers ([that are limited to 1M bundle size](https://developers.cloudflare.com/workers/platform/limits/#worker-size)) without depending on all the [GitHub JS SDK](https://bundlephobia.com/package/octokit@2.0.14) features, just to update a file on my GitHub repo.

[![github-upsert repo on github](https://opengraph.githubassets.com/9ebd196be9d01128c68af9334765364e508eca3c872ac342df11f95a5b0bf713/web-pacotes/github-upsert)](https://github.com/web-pacotes/github-upsert)
Plot FiftyOne visualisations with Seaborn
Tags: computervision, python, datascience
Published: 2023-05-01 09:58:48

## Why

I wanted more customisation options to draw figures for my thesis paper. It took me a while to figure this out, so I thought I'd share.

## How

I'm assuming you already have a FiftyOne dataset with computed embeddings and visualization. If not, you'll need to [create a dataset](https://docs.voxel51.com/user_guide/dataset_creation/index.html) and [compute the embeddings and visualization](https://voxel51.com/blog/fiftyone-computer-vision-embeddings-tips-and-tricks-mar-31-2023/) before proceeding.

I already have everything saved, so I load my dataset and the `compute_visualization` results before plotting:

```py
import fiftyone as fo

# load dataset
dataset = fo.load_dataset("dataset_name")

# load computed visualisation
results = dataset.load_brain_results("vis_name")
```

I have a sample field called "vehicle_type" that I want to use as the `hue` in my seaborn plot. To obtain this information for each sample, I wrote a simple function:

```py
def get_vehicle_type(sample_id):
    return dataset[sample_id]["vehicle_type"]
```

Next, I convert `results.points` into a pandas DataFrame and fetch the "vehicle_type" information from the FiftyOne dataset.

```py
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# turn results.points into dataframe
df_viz = pd.DataFrame(results.points, columns=["x", "y"])
# get sample ids for each sample
df_viz["sample_id"] = results.sample_ids

# use sample id to get the sample field info I need
df_viz["vehicle_type"] = df_viz["sample_id"].apply(get_vehicle_type)
```

Finally, I plot the results using seaborn:

```py
sns.scatterplot(data=df_viz, x='x', y='y', 
hue='vehicle_type', palette='mako_r', 
alpha=.9, s=1, edgecolor='none')
plt.title('Image Uniqueness')
plt.axis('off')
plt.show()
```

Seaborn allows for greater control over the appearance of the plot. Since I don't need the plot to be interactive, this is the perfect solution for creating uniform plots for my paper.

## Final result

![A scatter plot showing different clusters of similar images](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/znk8324oof02heilca7r.png)

## Extra: compute embeddings and visualisation

```py
import fiftyone.zoo as foz

# compute embeddings
model = foz.load_zoo_model("mobilenet-v2-imagenet-torch")
embeddings = dataset.compute_embeddings(model)

# pickle embeddings for later use, this the computation takes a while
with open('embeddings.pkl', 'wb') as file:
    pickle.dump(embeddings, file)

# Compute visualization
results = fob.compute_visualization(
    dataset, embeddings=embeddings, seed=42, brain_key="vis_name"
)
```
Securing Your PHP Application: Best Practices
Tags: php
Published: 2023-05-01 09:36:20

## Introduction

PHP is one of the most popular programming languages for web development. As with any web application, security is a critical aspect of PHP development. In this blog post, we will discuss the best practices for securing PHP applications.

## Input Validation

Input validation is the process of checking user input for errors or malicious content before using it in the application. It is important to validate all user input in PHP applications to prevent attacks such as cross-site scripting (XSS) and SQL injection.

To validate user input, you can use functions such as `filter_var()` and `preg_match()`. These functions can check for specific types of input, such as email addresses or phone numbers. Additionally, you can use Private HP frameworks such as Laravel and Symfony, which have built-in validation functions.

It is essential to validate user input because attackers can use it to execute malicious code that can harm your application. SQL injection is one of the most common types of attacks that can be prevented with input validation. The attacker can insert malicious SQL code into an application's input fields, which can then be executed by the application's database, potentially giving the attacker access to sensitive data.

## SQL Injection Prevention

SQL injection is a common attack that can be prevented by using prepared statements. Prepared statements use placeholders for user input, which are then replaced with safe values before being executed by the database. This prevents attackers from inserting malicious SQL code into the application.

To prevent SQL injection in PHP applications, you should use prepared statements. By doing so, you can significantly reduce the risk of security vulnerabilities in your application.

## Session Management

Sessions are used in PHP applications to maintain user state across multiple pages. It is important to manage sessions securely to prevent attacks such as session hijacking and session fixation.

To secure sessions in PHP applications, you should use secure cookies and set the session cookie parameters. You should also regenerate the session ID after successful login and logout to prevent session fixation. Additionally, you should use SSL/TLS to encrypt session data during transmission.

Session hijacking is a type of attack where an attacker takes control of a user's session. Session fixation is another type of attack where an attacker sets the session ID of the user before they log in. By managing sessions securely, you can prevent these types of attacks.

## Conclusion

Securing PHP applications is crucial to protect sensitive data and prevent attacks. By following these best practices for input validation, SQL injection prevention, and session management, you can significantly reduce the risk of security vulnerabilities in your PHP applications. Remember to always keep your PHP version up-to-date and regularly audit your code for potential vulnerabilities. By doing so, you can ensure that your application is secure and safe from potential attacks.
Writing about Arrays in JavaScript
Published: 2023-05-01 09:32:29


Arrays are an essential data structure in JavaScript, allowing you to store and manipulate multiple values in a single variable. In this blog post, we'll cover some of the basics of arrays in JavaScript.
There are different functions we can execute with arrays and I will be taking the commonly used functions and explain with examples. for the purpose of this lesson we will be using TypeScript.

**The sort function:**
it is used to sort elements of an array in ascending or descending manner
look at the pics below...
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0l9jnibb5fk1g3o07h6g.png)

**The filter function**
Iterative methods include the filter() method. For each element in an array, it makes a single call to the given callbackFn function, which creates a new array containing all the values for which callbackFn returns a truthy result. None of the array members that fail the callbackFn test are added to the new array.

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

**The map Function**
For each element of an array, map() calls a function to generate a new array. For empty elements, the function is not run by map(). The initial array is unaffected by map().

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


**The find Function**
The first element in the given array that fulfills the testing function is returned by the find() method. Undefined is returned if no values satisfy the testing function. Use findIndex() if you require the array's found element's index. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yf5wxj53i4hhczcf9c3y.png)
OpenCommit: killing lame commits with generative AI 🤯🔫 (open-source)
Tags: opensource, git, productivity, ai
Published: 2023-05-01 09:25:38

_first — let's grow [my twitter](https://twitter.com/_sukharev_), so i can tell about my inventions quicker and make the world even better place (or not, idk)_

---

![opencommit — comparison](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fdik9aq5iwk3e4bqsqbk.png)

A month ago I opensourced [OpenCommit](https://github.com/di-sukharev/opencommit).

Now you can switch to GPT-4 and see how it answers WHY and WHAT change was done 🤯🔫

## How to install OpenCommit

Simply install it globally with npm, to use in any repo:
```sh
npm i -g opencommit
```

After installing type `oc` and hit "Enter" in a terminal:
```sh
oc
```

If you want to edit a commit and make OpenCommit to be used by your IDE do:
```sh
oc hook set
```

That's it — have fun ;)
Tartigraid - Best api dev tool
Tags: opensource, api, node, typescript
Published: 2023-05-01 09:18:52

Hello fellow developers.
I started working on a new open source api dev tool called [tartigraid](https://github.com/idodav/tartigraid).

TL;DR:
It is a proxy that between you api server and the clients.
The tool provides a dashboard that provides insight and tools to help you develop the best API.

I have many ideas for features that could improve the quality of the API. And the quality of life for the developers.

Some features that I thought about:

- Automatic generation of open api schema
- Automatic generation of test suites. And execution tools.
- Automatic generation of json schema and typescript types/zod validators/types in any language.
- Postman integration
- Easily launch multiple proxies. For a microservice environment and provide insight on traffic between services.
- Re Execute requests made to the server
- Easily generate test data and execute a request

Would love to hear your thoughts especially if you have feature proposals.
And I would like it even more if you would like to contribute!!
[tartigraid](https://github.com/idodav/tartigraid)
Digital Marketing Course In Guwahati
Published: 2023-05-01 09:16:23

If you are planning to choose digital marketing as a profession, the best option to begin your digital marketing journey is enrolling at Digiperform. We Offer top-notch step by step courses for beginners, in Digital Marketing through our [Digital marketing Institutes Located in Guwahati.](https://digiperform.com/digital-marketing-course-in-guwahati/)
Bring your Next.JS API Experience
Tags: nextjs, express, discuss, api
Published: 2023-05-01 09:10:48

Hello fellow developers,

I've been noticing a lot of discussion around Next.js APIs lately. It seems that serverless functions can become expensive as user traffic grows, especially when compared to other providers besides Vercel. I'm curious to hear your thoughts on when and why you prefer to use Next.js APIs. Let's have a discussion about it in the comments below.

By the way, if you're interested in learning about some of the challenges that Josh faced while using Next.js APIs, you may find this video helpful: https://www.youtube.com/watch?v=6xvLUWpCSFM.
Temporal Scoping in JavaScript
Published: 2023-05-02 09:00:00

---
title: Temporal Scoping in JavaScript
published: true
date: 2023-05-01 09:08:26 UTC
tags: 
canonical_url: https://devwise.in/temporal-scoping
---

If you can explain why the following outputs between the variables declared with `var` and `let`/`const`, then you can skip this article. Thank you for giving it a look.

```
console.log(a); //Output: undefined
var a = 1;
console.log(a); //Output: 1

console.log(b); //Output: Reference Error: b is not defined
const b = 2;
console.log(b); //Output: 2

```

### Temporal Scoping

The reason is temporal-scoping. It was introduced in ES6 with the introduction of `let`/`const`.

A variable declared with `let`/`const` is unavailable before the declaration. Whereas, if declared with `var`, a variable is available in the entire scoping context. However, a value is assigned to it only when the variable is initialized. That is why, in the above example, `a` is available to use before its declaration, but it's still `undefined`.

### Conclusion

ES6 (ECMAScript 6 now) has been around for many years now. The concepts introduced with it are well-supported in all major browsers. However, this aspect of scoping is not talked about much. I hope that you learned something interesting from this post. Until the next one. Cheers!
Creating new route file in Laravel
Tags: laravel, php, routing
Published: 2023-05-01 09:04:44

Best approach:
web.php
```php
Route::prefix('company')->as('company:')->group(
    base_path('routes/company.php'),
);
```
Access URL: http://localhost:8000/company/random
The below isn't a very good approach:
RouteServiceProveider.php
```php
public function boot()
    {
        $this->configureRateLimiting();

        $this->routes(function () {
            Route::middleware('api')
                ->prefix('api')
                ->group(base_path('routes/api.php'));

            Route::middleware('web')
                ->group(base_path('routes/web.php'));

            Route::middleware('company')
                ->group(base_path('routes/company.php'));
        });
    }
```

Middleware/Kernel.php
```php
protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'company' => [
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ]
    ];
```

routes/company.php
```php
<?php

use Illuminate\Support\Facades\Route;

Route::get('/company', function(){
    return 'In Company';
});

Route::get('/random1', function(){
    return 'In Company';
});
```

Now localhost:8000/company will hit routes in this file


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4kagtsfqtsmn640wbudd.png)
How to download songs from SoundCloud? - A 2023 Guide
Published: 2023-05-01 08:55:27

[SoundCloud](https://soundcloud.com/) is a popular music streaming platform that allows users to listen to millions of tracks from around the world. However, the platform does not provide an option to download tracks directly from their website. This can be frustrating for users who want to listen to their favorite tracks offline. Fortunately, there are several [SoundCloud to MP3 downloader](https://soundcloudtomp3app.com/soundcloud-downloader/) tools available online, and one such tool is SoundCloudToMP3App.com.

SoundCloudToMP3App.com is a fast, free, and safe online tool that allows users to convert SoundCloud tracks to MP3 format and download them for free. The website has a simple and user-friendly interface, making it easy for users to download their favorite SoundCloud tracks in just a few clicks. Here's a detailed guide on how to use SoundCloudToMP3App.com to download tracks from SoundCloud.

**Step 1**: Copy the SoundCloud track URL
First, open the SoundCloud website and find the track that you want to download. Once you find the track, copy its URL from the address bar of your browser.

**Step 2**: Open SoundCloudToMP3App.com
Next, open [SoundCloud To MP3](https://soundcloudtomp3app.com/) in a new tab of your browser. Once the website loads, you will see a search bar where you can paste the SoundCloud track URL.

**Step 3**: Paste the SoundCloud track URL
Now, paste the SoundCloud track URL that you copied in step 1 into the search bar on SoundCloudToMP3App.com. Then click on the "Convert" button.

**Step 4**: Download the MP3 file
The website will now convert the SoundCloud track to MP3 format, and you will see a download link. Click on the "Download" button to save the MP3 file to your device.

It's that simple! SoundCloudToMP3App.com is a fast, free, and safe SoundCloud to MP3 downloader tool that allows users to download their favorite tracks from SoundCloud in just a few clicks. The website also has a feature that allows users to preview the track before downloading it, ensuring that they are downloading the correct track.

In conclusion, if you're looking for a fast, free, and safe SoundCloud to MP3 downloader tool, give SoundCloudToMP3App.com a try. The website has a simple and user-friendly interface, making it accessible to everyone, regardless of their technical expertise. With SoundCloudToMP3App.com, you can download your favorite SoundCloud tracks in MP3 format quickly and easily, and enjoy them offline on your device.
10 ReactJS quizzes
Tags: react, programming, quizz, javascript
Published: 2023-05-01 08:02:42

## If you want to import just the Component from the React library, what syntax do you use?

 ☑️ `import React.Component from 'react'`
 ☑️ `import [ Component ] from 'react'`
 ☑️ `import Component from 'react'`
 ✅ `import { Component } from 'react'`

## If a function component should always render the 
same way given the same props, what is a simple performance optimization available for it?

 ✅ Wrap it in the React.memo higher-order component.
 ☑️ Implement the useReducer Hook.
 ☑️ Implement the useMemo Hook.
 ☑️ Implement the shouldComponentUpdate lifecycle method.

## How do you fix the syntax error that results from running this code?
`const person =(firstName, lastName) =>
  {
     first: firstName,
     last: lastName
  }
console.log(person("Jill", "Wilson"))`

 ✅ Wrap the object in parentheses.
 ☑️ Call the function from another file.
 ☑️ Add a return statement before the first curly brace.
 ☑️ Replace the object with an array.

## If you see the following import in a file, what is being used for state management in the component?
`import React, {useState} from 'react';`

 ✅ React Hooks
 ☑️ stateful components
 ☑️ math
 ☑️ class components

## Using object literal enhancement, you can put values back into an object. When you log person to the console, what is the output?
`const name = 'Rachel';
const age = 31;
const person = { name, age };
console.log(person);`

 ☑️ `{{name: "Rachel", age: 31}}`
 ✅ `{name: "Rachel", age: 31}`
 ☑️ `{person: "Rachel", person: 31}}`
 ☑️ `{person: {name: "Rachel", age: 31}}`

## What is the testing library most often associated with React?
 
 ☑️ Mocha
 ☑️ Chai
 ☑️ Sinon
 ✅ Jest

## To get the first item from the array ("cooking") using array destructuring, how do you adjust this line?
`const topics = ['cooking', 'art', 'history'];`

 ☑️ `const first = ["cooking", "art", "history"]`
 ☑️ `const [] = ["cooking", "art", "history"]`
 ☑️ `const [, first]["cooking", "art", "history"]`
 ✅ `const [first] = ["cooking", "art", "history"]`

## How do you handle passing through the component tree without having to pass props down manually at every level?

 ☑️ React Send
 ☑️ React Pinpoint
 ☑️ React Router
 ✅ React Context


## What should the console read when the following code is run?
 `const [, , animal] = ['Horse', 'Mouse', 'Cat'];
 console.log(animal);`

 ☑️ Horse
 ✅ Cat
 ☑️ Mouse
 ☑️ undefined


## What is the name of the tool used to take JSX and turn it into 
createElement calls?

 ☑️ JSX Editor
 ☑️ ReactDOM
 ☑️ Browser Buddy
 ✅ Babel

https://dovudhon.com
https://github.com/dovudhonhusanov