teleren/devto huggingface dataset:
I really don't get why people love Flutter
Tags: flutter, rant, dart
Published: 2023-02-02 11:28:38

I don't like Flutter, so much so I'm going to create a post to shit on it. Take my opinion with a grain of salt, but I've worked with Flutter professionally and personally.

1. The Flutter core library make breaking changes all the time, when the update are supposed to be minor
2. Basically no backward compatibility, don't even think about update your Flutter toolchain, because your app will break with old code, but you need to update because you encountered some bugs in the Flutter core library
3. The devtools are slow and bad, especially with the Widget Inspector
4. Sometimes vscode just doesn't show the devtools whatsoever and you need to `flutter clean` and reload the window again to get it working
5. Dart doesn't support reflection
6. No context API, and `riverpod` still doesn't support offline mode
7. Flutter web
8. YOU CANNOT CHANGE THE LINES LENGTH WITH DARTFMT, YOU MUST ADHERE TO 80 CHARACTERS PER LINE
9. Half ass implementation of i18n, you need external library to make it decent
10. Also half ass implementation of input fields, you need external library to make it even workable, otherwise your code will be a big mess (Consider using `flutter_form_builder` or `reactive_forms`)
11. When code quality is low, Flutter is exceptionally prone to performance hiccups (abusing initState, does not use `const` or `StatelessWidget` etc...)
12. Navigation 2.0 is hard and `go_router` is new, when you need to maintain old Flutter code, the router/navigation just doesn't make much sense

Choose React Native or Expo or Capacitor if you want a better experience
Using Geospatial Queries in MySQL
Tags: database, mysql, beginners, tutorial
Published: 2023-02-02 11:24:34

**Introduction**

Geospatial data, or data that represents a location on the Earth's surface, is becoming increasingly prevalent in today's data-driven world. To effectively work with geospatial data, databases need to have the ability to perform geospatial queries, which allow users to search, filter and analyze this data based on location. In this blog post, we will focus on implementing geospatial queries in MySQL, one of the most popular open-source relational databases.

**1.Enabling Geospatial Support in MySQL**

MySQL does not have built-in geospatial support, but it can be enabled through the installation of a plugin called "MySQL Spatial Extensions." This plugin adds a set of geospatial data types and functions that allow for the creation and querying of geospatial data. To install the plugin, you can run the following command:

```sql
INSTALL PLUGIN mysql_no_login SONAME 'libgeometry.so';
```

**2.Creating a Geospatial Table in MySQL**

To create a geospatial table in MySQL, you will need to specify the geospatial data type for each column that will contain geospatial data. Some common geospatial data types in MySQL include POINT, LINESTRING, and POLYGON.

Here is an example of how you can create a table to store restaurant locations:

```sql
CREATE TABLE restaurants (
  id INT PRIMARY KEY AUTO_INCREMENT,
  name VARCHAR(255),
  location POINT
);
```

**3.Indexing Geospatial Data in MySQL**

To improve query performance, it is recommended to create a spatial index on the geospatial column. This can be done by using the following syntax:

```sql
ALTER TABLE restaurants ADD SPATIAL INDEX (location);
```

**4.Performing Geospatial Queries in MySQL**

Once the geospatial data has been indexed, it can be queried using geospatial functions. Some common geospatial functions in MySQL include ST_Distance, ST_Within, and ST_Contains.

Here is an example of how you can find all restaurants within a certain radius of a location:

```sql
SELECT * FROM restaurants WHERE ST_DWithin(location, POINT(longitude, latitude), radius);
```

**5.Other Databases Supporting Geospatial Queries**

MySQL is not the only database that supports geospatial queries. Other popular databases that support geospatial queries include:

- PostgreSQL with PostGIS extension
- Microsoft SQL Server with spatial data types and functions
- Oracle with Spatial and Graph option
- MongoDB with native support for geospatial data and indexing

**Conclusion**

Geospatial queries allow databases to effectively work with geospatial data, enabling users to perform location-based analysis and search operations. Implementing geospatial queries in MySQL requires enabling geospatial support through the installation of a plugin and creating a geospatial table with the proper data types and indexes. Whether you are working with real estate data, tracking delivery trucks, or mapping out locations, geospatial queries provide a powerful tool for analyzing and understanding location-based data.
HTTP headers - Basics
Published: 2023-02-02 11:10:13

## HTTP headers

**HTTP headers** are key-value pairs sent in an HTTP request or response that provide additional information about the resource being requested or the data being sent. Some common HTTP headers and their uses include:

**Accept:** Specifies the preferred format of the response, such as "application/json" for a JSON response. This header helps the server determine the best format to return the data in.

**Content-Type:** Specifies the format of the data being sent in the request body, such as "application/json" for JSON data. This header helps the server understand the format of the data being sent in the request.

**Authorization:** Used to provide authentication information, such as a token or credentials. This header allows the server to validate the request and ensure that the client has permission to access the requested resource.

**User-Agent:** Provides information about the client making the request, such as the type of browser or operating system. This header helps the server understand the client and respond appropriately.

**Referer:** Indicates the URL of the resource from which the request originated. This header helps the server track where the request is coming from and understand the context of the request.

**If-Modified-Since:** Makes the request conditional, only returning the response if the resource has been modified since the specified date. This header helps the client avoid unnecessary data transfers by only requesting updated data.

**Cache-Control:** Specifies the cache-related headers that control the caching of the response. This header helps the client determine how long the response should be cached and whether to retrieve it from cache or from the server.

**Location:** Specifies the URL of a newly created resource, used in response to a POST request. This header helps the client find the newly created resource and perform additional operations on it if necessary.

These headers provide important information about the request or response, helping the client and server communicate effectively. RESTful APIs often use headers to provide additional context for each request, allowing the server to better understand and respond to the request.
Representational State Transfer (REST) - Basics
Tags: restapi
Published: 2023-02-02 11:08:05

**Representational State Transfer (REST)** is a software architectural style that defines a set of constraints and guidelines for building web services. REST is based on the HTTP protocol and is designed to be lightweight, fast, and scalable.

**RESTful web services follow certain principles**, including:

**Client-server architecture**: REST separates the user interface from the backend, allowing the client and server to evolve independently.

**Statelessness**: Each request from a client to a server must contain all the information necessary to understand the request, and the server should not store any client context between requests.

**Cacheability**: Clients can cache responses, allowing for better performance and scalability.

**Layered system**: REST allows for an intermediary, such as a load balancer, between the client and server, which can improve security and scalability.

**Code on demand (optional)**: REST allows for the client to download code, such as JavaScript, to extend its functionality.

To create a RESTful web service, you can use the HTTP methods (GET, POST, PUT, DELETE, etc.) to perform operations on resources. For example, you can use a GET request to retrieve a resource, a POST request to create a new resource, a PUT request to update an existing resource, and a DELETE request to delete a resource.

For example, consider a web service that allows users to manage a list of books. You could create the following RESTful endpoints:

- GET /books: Retrieve a list of all books.
- GET /books/{id}: Retrieve a specific book by its id.
- POST /books: Create a new book.
- PUT /books/{id}: Update an existing book.
- DELETE /books/{id}: Delete a specific book by its id.

RESTful web services can use various formats for data transfer, including JSON, XML, and HTML. The client and server negotiate the format using the Content-Type and Accept headers.

REST has become a popular choice for building web services due to its simplicity, flexibility, and scalability. RESTful web services are often used for building APIs for web and mobile applications, and for integrating different systems and services.
Fix slow ZSH startup due to NVM
Tags: zsh, shell, nvm
Published: 2023-02-02 11:04:23

NVM can really be helpful when dealing with older projects. But there’s a problem, still. The nvm installation adds a portion of code to your .zshrc to enable autocompletion. This, in turn, slows the startup of your shell quite a lot.

But we can easily fix this slow zsh startup! Instead of always loading your nvm autocompletion, we can command oh-my-zsh to just load nvm ressources on-demand, also known as lazy-loading.

## How do I check if just NVM slows my ZSH startup?

That’s easy. In your `~/.zshrc` you can simply add `zmodload zsh/zprof` as first line and `zprof` as last line. This will prove you a nice output on which plugin caused what delay.

So go ahead, add these both lines to your shell startup script and time your shell startup with `time zsh -i -c exit`. This will start your ZSH and execute the `exit` command.
Scroll a bit up and your zsh output should blame nvm:

![Slow startup on ZSH after installing NVM](https://lakur.tech/2021/12/grafik-1024x504.png)

Bad, right? That’s almost 90% startup time caused by a single tool I
don’t use _that much_. So let’s fix this!

## How do I fix the slow zsh startup?

As the average ZSH user, you probably already have different plugins provided by <a href="https://github.com/ohmyzsh/ohmyzsh" target="_blank" rel="noreferrer noopener">oh-my-zsh</a>. If not, really, go ahead and get yourself some nice plugins! It’s a community driven aggregator of many many great plugins.

The plugin we need now is the `nvm` plugin. It’s already included in `oh-my-zsh` and should be activated in your plugins array somewhere in your `.zshrc`. 

But you also want to add the line `zstyle ':omz:plugins:nvm' lazy yes`, which enables the
lazy-loading mode. This mode defers the load of the nvm plugin and activates the script when using it.
To further optimize your startup you can replace that line with `zstyle ':omz:plugins:nvm' autoload yes`.
This will only source the plugin in directories that contain a .nvmrc file. So, in conclusion,
add/modify the following in your zsh startup script:

```bash
zstyle ':omz:plugins:nvm' lazy yes
# Alternative:
# zstyle ':omz:plugins:nvm' autoload yes
plugins=(
  nvm
  // [...]
)
// [...]
```

Also, be sure to remove the lines added by nvm, they should be somewhere at the bottom of your script, mine looked like:

```bash
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion
```

## Checking fixed startup times

Now, go to any directory that shouldn’t autostart nvm and check your timings again. Mine looked like this:

![Improved startup times after nvm lazy-loading](https://lakur.tech/2021/12/grafik-1-1024x374.png)

As you can see above, nvm support takes now much less time to start, while still being available “on-call”.

## Done!

Now you can safely remove the debugging lines we introduced to our `.zshrc` earlier.

Hopefully I could help you a bit with this short post, see you around for the
next one 🙂
Hardware and software fundamentals.
Tags: hardware, softwar, programming, beginners
Published: 2023-02-02 11:00:05


**Hardware is anything physically connected to a computer.**

**Central Processing Unit (CPU)**
A physical object that takes data from the main memory, processes it, and returns the updated data to the main memory.

**Control unit (CU)**
A subunit of the CPU that controls data flow from and into the main memory.

**Arithmetic and logic unit (ALU)**
Subunit of the CPU that is responsible for processing arithmetic and logic operations.

**Input units**
Take data from the world or an input device and convert it into streams of bytes.

**Output units**
Take processed data from the CPU and render it in a 
human-understandable way.

**Storage units**
Where data is stored after being retrieved and processed. The physical memory space.

**Memory**
The main memory and RAM (physical spaces in the computer) and 
secondary storage (e.g. hard drives)


**Software is a collection of programs and procedures that perform 
tasks on a computer**

**Machine language**
The only language the computer can process: a stream of ones and zeros (binary). A low-level language.-

**Assembly language**
A human-readable language that translates binary into assembly 
instruction, which must be translated into machine language for the 
computer. A low-level language.

**High-level programming languages**
Allow the writing of human-readable programs without large amounts of 
low-level instructions (i.e. assembly language instructions).

**Assembler**
A utility program that translates an assembly language program into 
machine language.

**Compiler**
A program that translates human-readable source code into 
machine-readable target code in a low-level language. Once the 
translation is complete, the target code is passed to the target machine for execution.

**Interpreter**
A program that translates human-readable source code into 
machine-readable target code in a low-level language command by 
command while the source code is being executed.
**
Operating system**
Software that supports a computer's basic functions, manages computer hardware and software resources, and provides common services for computer programs


**User applications** 
Software written for the end-user that's designed to carry out a task unrelated to the operation of the computer system.
How to get current location in Angular 14+
Tags: angular
Published: 2023-02-02 10:59:46

<p class="paragraph"> In this article, we will see how to get the user's current location in Angular 14+. </p><p class="paragraph"> Generate location service </p><pre><code class="code-block">ng g service services/location/location</code></pre><p class="paragraph"> It will create location service inside services folder </p><p class="paragraph"> Now add below code in it </p><pre><code class="code-block">import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class LocationService {
  constructor() {}

  getCurrentLocation() {
    return new Promise((resolve, reject) =&gt; {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
          (position) =&gt; {
            if (position) {
              console.log(
                'Latitude: ' +
                  position.coords.latitude +
                  'Longitude: ' +
                  position.coords.longitude
              );
              let lat = position.coords.latitude;
              let lng = position.coords.longitude;

              const location = {
                lat,
                lng,
              };
              resolve(location);
            }
          },
          (error) =&gt; console.log(error)
        );
      } else {
        reject('Geolocation is not supported by this browser.');
      }
    });
  }
}
</code></pre><p class="paragraph"> Now use this location service in app.component.ts file as below: </p><pre><code class="code-block"> const position: any = await this.locationService.getCurrentLocation();
 console.log(position);</code></pre><p class="paragraph"> You will get the current latitude and longitude on the console. </p>
How to get address location from latitude and longitude in Angular15+
Tags: angular, location, howto, webdev
Published: 2023-02-02 10:57:18

<p class="paragraph"> In this article, we will see how we can get address location from latitude and longitude in Angular15+ by using the Reverse Geocoding technique. </p><h2>What is&nbsp;Reverse Geocoding?</h2><p class="paragraph"> <b>Reverse geocoding </b>is the process to convert the latitude and longitude coordinates to a readable address. </p><h3>How to Get address location from latitude and longitude in Angular15+</h3><p class="paragraph"> Generate map componenent&nbsp; </p><pre><code class="code-block">ng g c map</code></pre><pre><code class="code-block"> getAddress(lat: number, lng: number): Promise&lt;any&gt; {
    return new Promise((resolve, reject) =&gt; {
      this.http
        .get&lt;any&gt;(
          `https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}&amp;key=${environment.googleMapsApiKey}`
        )
        .pipe(
          map((geoData) =&gt; {
            if (!geoData || !geoData.results || geoData.results.length === 0)
              throw null;
            return geoData.results[0];
          })
        )
        .subscribe(
          (data) =&gt; {
            resolve(data);
          },
          (e) =&gt; {
            reject(e);
          }
        );
    });
  }</code></pre><p class="paragraph"> and now use this function as below: </p><pre><code class="code-block">this.getAddress(23.01997577399075, 73.07245691797758);</code></pre>
How to redirect 301 in Angular Universal
Tags: angular, howto
Published: 2023-02-02 10:56:27

<p class="paragraph"> In this article, we will learn what is 301 redirect and how it can be implemented in Angular universal. </p><h2>What is 301 Redirect?</h2><p class="paragraph"> 301 is an HTTP status code sent by a web server to a browser.  </p><p class="paragraph"> When a URL is marked with a 301, it means that any users that request the old URL will be instantly redirected to the new URL.  </p><p class="paragraph"> A 301 redirect is most frequently used when a page has been relocated or deleted permanently from a website since it transfers all ranking power from the old URL to the new URL. </p><h3>How to redirect 301 in Angular Universal</h3><p class="paragraph"> Using 301 redirects in Angular Universal, you can redirect your old page to a new page using the technique described below.  </p><p class="paragraph"> This is by default code in&nbsp;<code>server.ts</code>&nbsp;file </p><pre><code class="code-block">// All regular routes use the Universal engine
  server.get('*', (req, res) =&gt; {
      res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
  });</code></pre><p class="paragraph"> &nbsp;&nbsp;The express server(SSR) renders the front-end angular HTML files after all routes arrive here. Therefore, we can transmit the 301 status code before sending the browser any answer. </p><p class="paragraph"> You can add some conditions like below: </p><h2>Use Case -1: Redirect HTTP to HTTPS</h2><pre><code class="code-block">// All regular routes use the Universal engine
  server.get('*', (req, res) =&gt; {
    if (index == req.originalUrl)
      res.redirect(301, 'https://www.tutscoder.com');
    else
      res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
  });</code></pre><h2>Use Case -2: Convert Underscore to Hyphen</h2><pre><code class="code-block">server.get("*", (req, res) =&gt; {
    if (req.originalUrl.indexOf("_") &gt; -1) {
      console.log('Before',req.originalUrl);
      req.originalUrl = req.originalUrl.replace(/_/g, "-");
      console.log('After',req.originalUrl);
       res.redirect(
        301,
        req.originalUrl
      );
    }else{
      res.render(indexHtml, {
        req,
        providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }],
      });
    }

  });</code></pre>
Serve your React build locally with nginx through docker
Tags: react, javascript, docker
Published: 2023-02-02 10:55:03

Sometimes, there are build differences between your development server and your build outcome. To debug this, you have to somehow host your build outcome locally. This can be done really easy, just mount your build into a nginx container!

## Creating the build

As a first step, you have to build and bundle your JavaScript / TypeScript by running the build command. You can find that command in your package.json. For a React App, created with create-react-app this would be `react-scripts build`, accessible in the most projects over the script build. This script can be executed through e.g. `npm run build`, depending on your node package manager.

This provides us our static files in `/build`. We will have to start a container and mount that directory next.

## Creating the container

The second step starts a container and mounts the built files as the default served directory. For the [default nginx image][1], this is the path `/usr/share/nginx/html`, which provides the famous `Welcome to nginx!` default page.  
Mounting our build output into this folder makes nginx serve the build instead of its default pages.

Start the container with the following command from your project root:  
`docker run -p 8082:80 -v $(pwd)/build:/usr/share/nginx/html nginx`

Your built files will be available under port 8082.

## Done!

Really easy, wasn’t it? If there’s any feedback, problems, or just a quick “Thanks, works” – be sure to comment below.

 [1]: https://hub.docker.com/_/nginx/
How to Load External Scripts Dynamically In Angular 14+
Tags: angular, frontend
Published: 2023-02-02 10:53:45

<p class="paragraph"> In this tutorial, we will see how to load external scripts Dynamically In Angular 14. </p><p class="paragraph"> The technique listed below can be used to dynamically load JS scripts and libraries into your Angular project as needed. </p><pre><code class="code-block">loadScript(): Promise&lt;any&gt; {
    return new Promise((resolve, reject) =&gt; {
      const script = document.createElement('script');
      script.src =
        'https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js'
      script.async = true;
      script.defer = true;
      document.body.appendChild(script);
    });</code></pre>
How to implement rate limiting in nodejs
Tags: node, security, backend, webdev
Published: 2023-02-02 10:52:21

<p class="paragraph"> In this tutorial, we will implement rate limiting in order to prevent the same IP from making too many requests to our API and that will then help us prevent attacks, like denial of services or brute force attacks. </p><p class="paragraph"> So, here we will implememnt rate limiter as global middlware, so basically the rate limiter will count the number of  </p><p class="paragraph"> requests comming from one IP and then,when thre are too many requets, block these requetsts. </p><pre><code class="code-block">npm install express-rate-limit</code></pre><pre><code class="code-block">const rateLimit = require('express-rate-limit')</code></pre><pre><code class="code-block">// Middleware

const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100, // Limit each IP to 100 requests per `window` (here, per 15 minutes)
  standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
  legacyHeaders: false, // Disable the `X-RateLimit-*` headers
  message: "Too many requests from this IP, please try again after in an hour",
});

// Apply the rate limiting middleware to all requests
app.use("/api", limiter);</code></pre><pre><code class="code-block">Too many requests from this IP, please try again after in an hour</code></pre>